Completed
Push — master ( 48e484...cedfdf )
by
unknown
03:10
created

class-tgm-plugin-activation.php ➔ tgmpa()   C

Complexity

Conditions 8
Paths 26

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 8
eloc 14
c 2
b 1
f 0
nc 26
nop 2
dl 0
loc 26
rs 5.3846
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 61 and the first side effect is on line 1911.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * Plugin installation and activation for WordPress themes.
4
 *
5
 * Please note that this is a drop-in library for a theme or plugin.
6
 * The authors of this library (Thomas, Gary and Juliette) are NOT responsible
7
 * for the support of your plugin or theme. Please contact the plugin
8
 * or theme author for support.
9
 *
10
 * @package   TGM-Plugin-Activation
11
 * @version   2.5.2
12
 * @link      http://tgmpluginactivation.com/
13
 * @author    Thomas Griffin, Gary Jones, Juliette Reinders Folmer
14
 * @copyright Copyright (c) 2011, Thomas Griffin
15
 * @license   GPL-2.0+
16
 *
17
 * @wordpress-plugin
18
 * Plugin Name: TGM Plugin Activation
19
 * Plugin URI:
20
 * Description: Plugin installation and activation for WordPress themes.
21
 * Version:     2.5.2
22
 * Author:      Thomas Griffin, Gary Jones, Juliette Reinders Folmer
23
 * Author URI:  http://tgmpluginactivation.com/
24
 * Text Domain: tgmpa
25
 * Domain Path: /languages/
26
 * Copyright:   2011, Thomas Griffin
27
 */
28
29
/*
30
	Copyright 2011 Thomas Griffin (thomasgriffinmedia.com)
31
32
	This program is free software; you can redistribute it and/or modify
33
	it under the terms of the GNU General Public License, version 2, as
34
	published by the Free Software Foundation.
35
36
	This program is distributed in the hope that it will be useful,
37
	but WITHOUT ANY WARRANTY; without even the implied warranty of
38
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
39
	GNU General Public License for more details.
40
41
	You should have received a copy of the GNU General Public License
42
	along with this program; if not, write to the Free Software
43
	Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
44
*/
45
46
if ( ! class_exists( 'TGM_Plugin_Activation' ) ) {
47
48
	/**
49
	 * Automatic plugin installation and activation library.
50
	 *
51
	 * Creates a way to automatically install and activate plugins from within themes.
52
	 * The plugins can be either bundled, downloaded from the WordPress
53
	 * Plugin Repository or downloaded from another external source.
54
	 *
55
	 * @since 1.0.0
56
	 *
57
	 * @package TGM-Plugin-Activation
58
	 * @author  Thomas Griffin
59
	 * @author  Gary Jones
60
	 */
61
	class TGM_Plugin_Activation {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
62
		/**
63
		 * TGMPA version number.
64
		 *
65
		 * @since 2.5.0
66
		 *
67
		 * @const string Version number.
68
		 */
69
		const TGMPA_VERSION = '2.5.2';
70
71
		/**
72
		 * Regular expression to test if a URL is a WP plugin repo URL.
73
		 *
74
		 * @const string Regex.
75
		 *
76
		 * @since 2.5.0
77
		 */
78
		const WP_REPO_REGEX = '|^http[s]?://wordpress\.org/(?:extend/)?plugins/|';
79
80
		/**
81
		 * Arbitrary regular expression to test if a string starts with a URL.
82
		 *
83
		 * @const string Regex.
84
		 *
85
		 * @since 2.5.0
86
		 */
87
		const IS_URL_REGEX = '|^http[s]?://|';
88
89
		/**
90
		 * Holds a copy of itself, so it can be referenced by the class name.
91
		 *
92
		 * @since 1.0.0
93
		 *
94
		 * @var TGM_Plugin_Activation
95
		 */
96
		public static $instance;
97
98
		/**
99
		 * Holds arrays of plugin details.
100
		 *
101
		 * @since 1.0.0
102
		 *
103
		 * @since 2.5.0 the array has the plugin slug as an associative key.
104
		 *
105
		 * @var array
106
		 */
107
		public $plugins = array();
108
109
		/**
110
		 * Holds arrays of plugin names to use to sort the plugins array.
111
		 *
112
		 * @since 2.5.0
113
		 *
114
		 * @var array
115
		 */
116
		protected $sort_order = array();
117
118
		/**
119
		 * Whether any plugins have the 'force_activation' setting set to true.
120
		 *
121
		 * @since 2.5.0
122
		 *
123
		 * @var bool
124
		 */
125
		protected $has_forced_activation = false;
126
127
		/**
128
		 * Whether any plugins have the 'force_deactivation' setting set to true.
129
		 *
130
		 * @since 2.5.0
131
		 *
132
		 * @var bool
133
		 */
134
		protected $has_forced_deactivation = false;
135
136
		/**
137
		 * Name of the unique ID to hash notices.
138
		 *
139
		 * @since 2.4.0
140
		 *
141
		 * @var string
142
		 */
143
		public $id = 'tgmpa';
144
145
		/**
146
		 * Name of the query-string argument for the admin page.
147
		 *
148
		 * @since 1.0.0
149
		 *
150
		 * @var string
151
		 */
152
		protected $menu = 'tgmpa-install-plugins';
153
154
		/**
155
		 * Parent menu file slug.
156
		 *
157
		 * @since 2.5.0
158
		 *
159
		 * @var string
160
		 */
161
		public $parent_slug = 'themes.php';
162
163
		/**
164
		 * Capability needed to view the plugin installation menu item.
165
		 *
166
		 * @since 2.5.0
167
		 *
168
		 * @var string
169
		 */
170
		public $capability = 'edit_theme_options';
171
172
		/**
173
		 * Default absolute path to folder containing bundled plugin zip files.
174
		 *
175
		 * @since 2.0.0
176
		 *
177
		 * @var string Absolute path prefix to zip file location for bundled plugins. Default is empty string.
178
		 */
179
		public $default_path = '';
180
181
		/**
182
		 * Flag to show admin notices or not.
183
		 *
184
		 * @since 2.1.0
185
		 *
186
		 * @var boolean
187
		 */
188
		public $has_notices = true;
189
190
		/**
191
		 * Flag to determine if the user can dismiss the notice nag.
192
		 *
193
		 * @since 2.4.0
194
		 *
195
		 * @var boolean
196
		 */
197
		public $dismissable = true;
198
199
		/**
200
		 * Message to be output above nag notice if dismissable is false.
201
		 *
202
		 * @since 2.4.0
203
		 *
204
		 * @var string
205
		 */
206
		public $dismiss_msg = '';
207
208
		/**
209
		 * Flag to set automatic activation of plugins. Off by default.
210
		 *
211
		 * @since 2.2.0
212
		 *
213
		 * @var boolean
214
		 */
215
		public $is_automatic = false;
216
217
		/**
218
		 * Optional message to display before the plugins table.
219
		 *
220
		 * @since 2.2.0
221
		 *
222
		 * @var string Message filtered by wp_kses_post(). Default is empty string.
223
		 */
224
		public $message = '';
225
226
		/**
227
		 * Holds configurable array of strings.
228
		 *
229
		 * Default values are added in the constructor.
230
		 *
231
		 * @since 2.0.0
232
		 *
233
		 * @var array
234
		 */
235
		public $strings = array();
236
237
		/**
238
		 * Holds the version of WordPress.
239
		 *
240
		 * @since 2.4.0
241
		 *
242
		 * @var int
243
		 */
244
		public $wp_version;
245
246
		/**
247
		 * Holds the hook name for the admin page.
248
		 *
249
		 * @since 2.5.0
250
		 *
251
		 * @var string
252
		 */
253
		public $page_hook;
254
255
		/**
256
		 * Adds a reference of this object to $instance, populates default strings,
257
		 * does the tgmpa_init action hook, and hooks in the interactions to init.
258
		 *
259
		 * @internal This method should be `protected`, but as too many TGMPA implementations
260
		 * haven't upgraded beyond v2.3.6 yet, this gives backward compatibility issues.
261
		 * Reverted back to public for the time being.
262
		 *
263
		 * @since 1.0.0
264
		 *
265
		 * @see TGM_Plugin_Activation::init()
266
		 */
267
		public function __construct() {
0 ignored issues
show
Coding Style introduced by
__construct uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
268
			// Set the current WordPress version.
269
			$this->wp_version = $GLOBALS['wp_version'];
270
271
			// Announce that the class is ready, and pass the object (for advanced use).
272
			do_action_ref_array( 'tgmpa_init', array( $this ) );
273
274
			// When the rest of WP has loaded, kick-start the rest of the class.
275
			add_action( 'init', array( $this, 'init' ) );
276
		}
277
278
		/**
279
		 * Magic method to (not) set protected properties from outside of this class.
280
		 *
281
		 * @internal hackedihack... There is a serious bug in v2.3.2 - 2.3.6  where the `menu` property
282
		 * is being assigned rather than tested in a conditional, effectively rendering it useless.
283
		 * This 'hack' prevents this from happening.
284
		 *
285
		 * @see https://github.com/TGMPA/TGM-Plugin-Activation/blob/2.3.6/tgm-plugin-activation/class-tgm-plugin-activation.php#L1593
286
		 *
287
		 * @param string $name  Name of an inaccessible property.
288
		 * @param mixed  $value Value to assign to the property.
289
		 * @return void  Silently fail to set the property when this is tried from outside of this class context.
290
		 *               (Inside this class context, the __set() method if not used as there is direct access.)
291
		 */
292
		public function __set( $name, $value ) {
0 ignored issues
show
Unused Code introduced by
The parameter $name is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $value is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
293
			return;
294
		}
295
296
		/**
297
		 * Magic method to get the value of a protected property outside of this class context.
298
		 *
299
		 * @param string $name Name of an inaccessible property.
300
		 * @return mixed The property value.
301
		 */
302
		public function __get( $name ) {
303
			return $this->{$name};
304
		}
305
306
		/**
307
		 * Initialise the interactions between this class and WordPress.
308
		 *
309
		 * Hooks in three new methods for the class: admin_menu, notices and styles.
310
		 *
311
		 * @since 2.0.0
312
		 *
313
		 * @see TGM_Plugin_Activation::admin_menu()
314
		 * @see TGM_Plugin_Activation::notices()
315
		 * @see TGM_Plugin_Activation::styles()
316
		 */
317
		public function init() {
318
			/**
319
			 * By default TGMPA only loads on the WP back-end and not in an Ajax call. Using this filter
320
			 * you can overrule that behaviour.
321
			 *
322
			 * @since 2.5.0
323
			 *
324
			 * @param bool $load Whether or not TGMPA should load.
325
			 *                   Defaults to the return of `is_admin() && ! defined( 'DOING_AJAX' )`.
326
			 */
327
			if ( true !== apply_filters( 'tgmpa_load', ( is_admin() && ! defined( 'DOING_AJAX' ) ) ) ) {
328
				return;
329
			}
330
331
			// Load class strings.
332
			$this->strings = array(
333
				'page_title'                      => __( 'Install Required Plugins', 'tgmpa' ),
334
				'menu_title'                      => __( 'Install Plugins', 'tgmpa' ),
335
				'installing'                      => __( 'Installing Plugin: %s', 'tgmpa' ),
336
				'oops'                            => __( 'Something went wrong with the plugin API.', 'tgmpa' ),
337
				'notice_can_install_required'     => _n_noop(
338
					'This theme requires the following plugin: %1$s.',
339
					'This theme requires the following plugins: %1$s.',
340
					'tgmpa'
341
				),
342
				'notice_can_install_recommended'  => _n_noop(
343
					'This theme recommends the following plugin: %1$s.',
344
					'This theme recommends the following plugins: %1$s.',
345
					'tgmpa'
346
				),
347
				'notice_cannot_install'           => _n_noop(
348
					'Sorry, but you do not have the correct permissions to install the %1$s plugin.',
349
					'Sorry, but you do not have the correct permissions to install the %1$s plugins.',
350
					'tgmpa'
351
				),
352
				'notice_ask_to_update'            => _n_noop(
353
					'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.',
354
					'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.',
355
					'tgmpa'
356
				),
357
				'notice_ask_to_update_maybe'      => _n_noop(
358
					'There is an update available for: %1$s.',
359
					'There are updates available for the following plugins: %1$s.',
360
					'tgmpa'
361
				),
362
				'notice_cannot_update'            => _n_noop(
363
					'Sorry, but you do not have the correct permissions to update the %1$s plugin.',
364
					'Sorry, but you do not have the correct permissions to update the %1$s plugins.',
365
					'tgmpa'
366
				),
367
				'notice_can_activate_required'    => _n_noop(
368
					'The following required plugin is currently inactive: %1$s.',
369
					'The following required plugins are currently inactive: %1$s.',
370
					'tgmpa'
371
				),
372
				'notice_can_activate_recommended' => _n_noop(
373
					'The following recommended plugin is currently inactive: %1$s.',
374
					'The following recommended plugins are currently inactive: %1$s.',
375
					'tgmpa'
376
				),
377
				'notice_cannot_activate'          => _n_noop(
378
					'Sorry, but you do not have the correct permissions to activate the %1$s plugin.',
379
					'Sorry, but you do not have the correct permissions to activate the %1$s plugins.',
380
					'tgmpa'
381
				),
382
				'install_link'                    => _n_noop(
383
					'Begin installing plugin',
384
					'Begin installing plugins',
385
					'tgmpa'
386
				),
387
				'update_link'                     => _n_noop(
388
					'Begin updating plugin',
389
					'Begin updating plugins',
390
					'tgmpa'
391
				),
392
				'activate_link'                   => _n_noop(
393
					'Begin activating plugin',
394
					'Begin activating plugins',
395
					'tgmpa'
396
				),
397
				'return'                          => __( 'Return to Required Plugins Installer', 'tgmpa' ),
398
				'dashboard'                       => __( 'Return to the dashboard', 'tgmpa' ),
399
				'plugin_activated'                => __( 'Plugin activated successfully.', 'tgmpa' ),
400
				'activated_successfully'          => __( 'The following plugin was activated successfully:', 'tgmpa' ),
401
				'plugin_already_active'           => __( 'No action taken. Plugin %1$s was already active.', 'tgmpa' ),
402
				'plugin_needs_higher_version'     => __( 'Plugin not activated. A higher version of %s is needed for this theme. Please update the plugin.', 'tgmpa' ),
403
				'complete'                        => __( 'All plugins installed and activated successfully. %1$s', 'tgmpa' ),
404
				'dismiss'                         => __( 'Dismiss this notice', 'tgmpa' ),
405
				'contact_admin'                   => __( 'Please contact the administrator of this site for help.', 'tgmpa' ),
406
			);
407
408
			do_action( 'tgmpa_register' );
409
410
			/* After this point, the plugins should be registered and the configuration set. */
411
412
			// Proceed only if we have plugins to handle.
413
			if ( empty( $this->plugins ) || ! is_array( $this->plugins ) ) {
414
				return;
415
			}
416
417
			// Set up the menu and notices if we still have outstanding actions.
418
			if ( true !== $this->is_tgmpa_complete() ) {
419
				// Sort the plugins.
420
				array_multisort( $this->sort_order, SORT_ASC, $this->plugins );
421
422
				add_action( 'admin_menu', array( $this, 'admin_menu' ) );
423
				add_action( 'admin_head', array( $this, 'dismiss' ) );
424
425
				// Prevent the normal links from showing underneath a single install/update page.
426
				add_filter( 'install_plugin_complete_actions', array( $this, 'actions' ) );
427
				add_filter( 'update_plugin_complete_actions', array( $this, 'actions' ) );
428
429
				if ( $this->has_notices ) {
430
					add_action( 'admin_notices', array( $this, 'notices' ) );
431
					add_action( 'admin_init', array( $this, 'admin_init' ), 1 );
432
					add_action( 'admin_enqueue_scripts', array( $this, 'thickbox' ) );
433
				}
434
435
				add_action( 'load-plugins.php', array( $this, 'add_plugin_action_link_filters' ), 1 );
436
			}
437
438
			// Make sure things get reset on switch theme.
439
			add_action( 'switch_theme', array( $this, 'flush_plugins_cache' ) );
440
441
			if ( $this->has_notices ) {
442
				add_action( 'switch_theme', array( $this, 'update_dismiss' ) );
443
			}
444
445
			// Setup the force activation hook.
446
			if ( true === $this->has_forced_activation ) {
447
				add_action( 'admin_init', array( $this, 'force_activation' ) );
448
			}
449
450
			// Setup the force deactivation hook.
451
			if ( true === $this->has_forced_deactivation ) {
452
				add_action( 'switch_theme', array( $this, 'force_deactivation' ) );
453
			}
454
		}
455
456
		/**
457
		 * Prevent activation of plugins which don't meet the minimum version requirement from the
458
		 * WP native plugins page.
459
		 *
460
		 * @since 2.5.0
461
		 */
462
		public function add_plugin_action_link_filters() {
463
			foreach ( $this->plugins as $slug => $plugin ) {
464
				if ( false === $this->can_plugin_activate( $slug ) ) {
465
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_activate' ), 20 );
466
				}
467
468
				if ( true === $plugin['force_activation'] ) {
469
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_deactivate' ), 20 );
470
				}
471
472
				if ( false !== $this->does_plugin_require_update( $slug ) ) {
473
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_update' ), 20 );
474
				}
475
			}
476
		}
477
478
		/**
479
		 * Remove the 'Activate' link on the WP native plugins page if the plugin does not meet the
480
		 * minimum version requirements.
481
		 *
482
		 * @since 2.5.0
483
		 *
484
		 * @param array $actions Action links.
485
		 * @return array
486
		 */
487
		public function filter_plugin_action_links_activate( $actions ) {
488
			unset( $actions['activate'] );
489
490
			return $actions;
491
		}
492
493
		/**
494
		 * Remove the 'Deactivate' link on the WP native plugins page if the plugin has been set to force activate.
495
		 *
496
		 * @since 2.5.0
497
		 *
498
		 * @param array $actions Action links.
499
		 * @return array
500
		 */
501
		public function filter_plugin_action_links_deactivate( $actions ) {
502
			unset( $actions['deactivate'] );
503
504
			return $actions;
505
		}
506
507
		/**
508
		 * Add a 'Requires update' link on the WP native plugins page if the plugin does not meet the
509
		 * minimum version requirements.
510
		 *
511
		 * @since 2.5.0
512
		 *
513
		 * @param array $actions Action links.
514
		 * @return array
515
		 */
516
		public function filter_plugin_action_links_update( $actions ) {
517
			$actions['update'] = sprintf(
518
				'<a href="%1$s" title="%2$s" class="edit">%3$s</a>',
519
				esc_url( $this->get_tgmpa_status_url( 'update' ) ),
520
				esc_attr__( 'This plugin needs to be updated to be compatible with your theme.', 'tgmpa' ),
521
				esc_html__( 'Update Required', 'tgmpa' )
522
			);
523
524
			return $actions;
525
		}
526
527
		/**
528
		 * Handles calls to show plugin information via links in the notices.
529
		 *
530
		 * We get the links in the admin notices to point to the TGMPA page, rather
531
		 * than the typical plugin-install.php file, so we can prepare everything
532
		 * beforehand.
533
		 *
534
		 * WP does not make it easy to show the plugin information in the thickbox -
535
		 * here we have to require a file that includes a function that does the
536
		 * main work of displaying it, enqueue some styles, set up some globals and
537
		 * finally call that function before exiting.
538
		 *
539
		 * Down right easy once you know how...
540
		 *
541
		 * Returns early if not the TGMPA page.
542
		 *
543
		 * @since 2.1.0
544
		 *
545
		 * @global string $tab Used as iframe div class names, helps with styling
546
		 * @global string $body_id Used as the iframe body ID, helps with styling
547
		 *
548
		 * @return null Returns early if not the TGMPA page.
549
		 */
550
		public function admin_init() {
0 ignored issues
show
Coding Style introduced by
admin_init uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
551
			if ( ! $this->is_tgmpa_page() ) {
552
				return;
553
			}
554
555
			if ( isset( $_REQUEST['tab'] ) && 'plugin-information' === $_REQUEST['tab'] ) {
556
				// Needed for install_plugin_information().
557
				require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
558
559
				wp_enqueue_style( 'plugin-install' );
560
561
				global $tab, $body_id;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
562
				$body_id = 'plugin-information';
563
				// @codingStandardsIgnoreStart
564
				$tab     = 'plugin-information';
565
				// @codingStandardsIgnoreEnd
566
567
				install_plugin_information();
568
569
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_init() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
570
			}
571
		}
572
573
		/**
574
		 * Enqueue thickbox scripts/styles for plugin info.
575
		 *
576
		 * Thickbox is not automatically included on all admin pages, so we must
577
		 * manually enqueue it for those pages.
578
		 *
579
		 * Thickbox is only loaded if the user has not dismissed the admin
580
		 * notice or if there are any plugins left to install and activate.
581
		 *
582
		 * @since 2.1.0
583
		 */
584
		public function thickbox() {
585
			if ( ! get_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, true ) ) {
586
				add_thickbox();
587
			}
588
		}
589
590
		/**
591
		 * Adds submenu page if there are plugin actions to take.
592
		 *
593
		 * This method adds the submenu page letting users know that a required
594
		 * plugin needs to be installed.
595
		 *
596
		 * This page disappears once the plugin has been installed and activated.
597
		 *
598
		 * @since 1.0.0
599
		 *
600
		 * @see TGM_Plugin_Activation::init()
601
		 * @see TGM_Plugin_Activation::install_plugins_page()
602
		 *
603
		 * @return null Return early if user lacks capability to install a plugin.
604
		 */
605
		public function admin_menu() {
606
			// Make sure privileges are correct to see the page.
607
			if ( ! current_user_can( 'install_plugins' ) ) {
608
				return;
609
			}
610
611
			$args = apply_filters(
612
				'tgmpa_admin_menu_args',
613
				array(
614
					'parent_slug' => $this->parent_slug,                     // Parent Menu slug.
615
					'page_title'  => $this->strings['page_title'],           // Page title.
616
					'menu_title'  => $this->strings['menu_title'],           // Menu title.
617
					'capability'  => $this->capability,                      // Capability.
618
					'menu_slug'   => $this->menu,                            // Menu slug.
619
					'function'    => array( $this, 'install_plugins_page' ), // Callback.
620
				)
621
			);
622
623
			$this->add_admin_menu( $args );
624
		}
625
626
		/**
627
		 * Add the menu item.
628
		 *
629
		 * @since 2.5.0
630
		 *
631
		 * @param array $args Menu item configuration.
632
		 */
633
		protected function add_admin_menu( array $args ) {
634
			if ( has_filter( 'tgmpa_admin_menu_use_add_theme_page' ) ) {
635
				_deprecated_function( 'The "tgmpa_admin_menu_use_add_theme_page" filter', '2.5.0', esc_html__( 'Set the parent_slug config variable instead.', 'tgmpa' ) );
636
			}
637
638
			if ( 'themes.php' === $this->parent_slug ) {
639
				$this->page_hook = call_user_func( 'add_theme_page', $args['page_title'], $args['menu_title'], $args['capability'], $args['menu_slug'], $args['function'] );
640
			} else {
641
				$this->page_hook = call_user_func( 'add_submenu_page', $args['parent_slug'], $args['page_title'], $args['menu_title'], $args['capability'], $args['menu_slug'], $args['function'] );
642
			}
643
		}
644
645
		/**
646
		 * Echoes plugin installation form.
647
		 *
648
		 * This method is the callback for the admin_menu method function.
649
		 * This displays the admin page and form area where the user can select to install and activate the plugin.
650
		 * Aborts early if we're processing a plugin installation action.
651
		 *
652
		 * @since 1.0.0
653
		 *
654
		 * @return null Aborts early if we're processing a plugin installation action.
655
		 */
656
		public function install_plugins_page() {
657
			// Store new instance of plugin table in object.
658
			$plugin_table = new TGMPA_List_Table;
659
660
			// Return early if processing a plugin installation action.
661
			if ( ( ( 'tgmpa-bulk-install' === $plugin_table->current_action() || 'tgmpa-bulk-update' === $plugin_table->current_action() ) && $plugin_table->process_bulk_actions() ) || $this->do_plugin_install() ) {
662
				return;
663
			}
664
665
			// Force refresh of available plugin information so we'll know about manual updates/deletes.
666
			wp_clean_plugins_cache( false );
667
668
			?>
669
			<div class="tgmpa wrap">
670
				<h2><?php echo esc_html( get_admin_page_title() ); ?></h2>
671
				<?php $plugin_table->prepare_items(); ?>
672
673
				<?php
674
				if ( ! empty( $this->message ) && is_string( $this->message ) ) {
675
					echo wp_kses_post( $this->message );
676
				}
677
				?>
678
				<?php $plugin_table->views(); ?>
679
680
				<form id="tgmpa-plugins" action="" method="post">
681
					<input type="hidden" name="tgmpa-page" value="<?php echo esc_attr( $this->menu ); ?>" />
682
					<input type="hidden" name="plugin_status" value="<?php echo esc_attr( $plugin_table->view_context ); ?>" />
683
					<?php $plugin_table->display(); ?>
684
				</form>
685
			</div>
686
			<?php
687
		}
688
689
		/**
690
		 * Installs, updates or activates a plugin depending on the action link clicked by the user.
691
		 *
692
		 * Checks the $_GET variable to see which actions have been
693
		 * passed and responds with the appropriate method.
694
		 *
695
		 * Uses WP_Filesystem to process and handle the plugin installation
696
		 * method.
697
		 *
698
		 * @since 1.0.0
699
		 *
700
		 * @uses WP_Filesystem
701
		 * @uses WP_Error
702
		 * @uses WP_Upgrader
703
		 * @uses Plugin_Upgrader
704
		 * @uses Plugin_Installer_Skin
705
		 * @uses Plugin_Upgrader_Skin
706
		 *
707
		 * @return boolean True on success, false on failure.
708
		 */
709
		protected function do_plugin_install() {
0 ignored issues
show
Coding Style introduced by
do_plugin_install uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
710
			if ( empty( $_GET['plugin'] ) ) {
711
				return false;
712
			}
713
714
			// All plugin information will be stored in an array for processing.
715
			$slug = $this->sanitize_key( urldecode( $_GET['plugin'] ) );
716
717
			if ( ! isset( $this->plugins[ $slug ] ) ) {
718
				return false;
719
			}
720
721
			// Was an install or upgrade action link clicked?
722
			if ( ( isset( $_GET['tgmpa-install'] ) && 'install-plugin' === $_GET['tgmpa-install'] ) || ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) ) {
723
724
				$install_type = 'install';
725
				if ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) {
726
					$install_type = 'update';
727
				}
728
729
				check_admin_referer( 'tgmpa-' . $install_type, 'tgmpa-nonce' );
730
731
				// Pass necessary information via URL if WP_Filesystem is needed.
732
				$url = wp_nonce_url(
733
					add_query_arg(
734
						array(
735
							'plugin'                 => urlencode( $slug ),
736
							'tgmpa-' . $install_type => $install_type . '-plugin',
737
						),
738
						$this->get_tgmpa_url()
739
					),
740
					'tgmpa-' . $install_type,
741
					'tgmpa-nonce'
742
				);
743
744
				$method = ''; // Leave blank so WP_Filesystem can populate it as necessary.
745
746
				if ( false === ( $creds = request_filesystem_credentials( esc_url_raw( $url ), $method, false, false, array() ) ) ) {
747
					return true;
748
				}
749
750 View Code Duplication
				if ( ! WP_Filesystem( $creds ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
751
					request_filesystem_credentials( esc_url_raw( $url ), $method, true, false, array() ); // Setup WP_Filesystem.
752
					return true;
753
				}
754
755
				/* If we arrive here, we have the filesystem. */
756
757
				// Prep variables for Plugin_Installer_Skin class.
758
				$extra         = array();
759
				$extra['slug'] = $slug; // Needed for potentially renaming of directory name.
760
				$source        = $this->get_download_url( $slug );
761
				$api           = ( 'repo' === $this->plugins[ $slug ]['source_type'] ) ? $this->get_plugins_api( $slug ) : null;
762
				$api           = ( false !== $api ) ? $api : null;
763
764
				$url = add_query_arg(
765
					array(
766
						'action' => $install_type . '-plugin',
767
						'plugin' => urlencode( $slug ),
768
					),
769
					'update.php'
770
				);
771
772
				if ( ! class_exists( 'Plugin_Upgrader', false ) ) {
773
					require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
774
				}
775
776
				$skin_args = array(
777
					'type'   => ( 'bundled' !== $this->plugins[ $slug ]['source_type'] ) ? 'web' : 'upload',
778
					'title'  => sprintf( $this->strings['installing'], $this->plugins[ $slug ]['name'] ),
779
					'url'    => esc_url_raw( $url ),
780
					'nonce'  => $install_type . '-plugin_' . $slug,
781
					'plugin' => '',
782
					'api'    => $api,
783
					'extra'  => $extra,
784
				);
785
786
				if ( 'update' === $install_type ) {
787
					$skin_args['plugin'] = $this->plugins[ $slug ]['file_path'];
788
					$skin                = new Plugin_Upgrader_Skin( $skin_args );
789
				} else {
790
					$skin = new Plugin_Installer_Skin( $skin_args );
791
				}
792
793
				// Create a new instance of Plugin_Upgrader.
794
				$upgrader = new Plugin_Upgrader( $skin );
795
796
				// Perform the action and install the plugin from the $source urldecode().
797
				add_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1, 3 );
798
799
				if ( 'update' === $install_type ) {
800
					// Inject our info into the update transient.
801
					$to_inject                    = array( $slug => $this->plugins[ $slug ] );
802
					$to_inject[ $slug ]['source'] = $source;
803
					$this->inject_update_info( $to_inject );
804
805
					$upgrader->upgrade( $this->plugins[ $slug ]['file_path'] );
806
				} else {
807
					$upgrader->install( $source );
808
				}
809
810
				remove_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1, 3 );
811
812
				// Make sure we have the correct file path now the plugin is installed/updated.
813
				$this->populate_file_path( $slug );
814
815
				// Only activate plugins if the config option is set to true and the plugin isn't
816
				// already active (upgrade).
817
				if ( $this->is_automatic && ! $this->is_plugin_active( $slug ) ) {
818
					$plugin_activate = $upgrader->plugin_info(); // Grab the plugin info from the Plugin_Upgrader method.
819
					if ( false === $this->activate_single_plugin( $plugin_activate, $slug, true ) ) {
820
						return true; // Finish execution of the function early as we encountered an error.
821
					}
822
				}
823
824
				$this->show_tgmpa_version();
825
826
				// Display message based on if all plugins are now active or not.
827
				if ( $this->is_tgmpa_complete() ) {
828
					echo '<p>', sprintf( esc_html( $this->strings['complete'] ), '<a href="' . esc_url( self_admin_url() ) . '">' . esc_html__( 'Return to the Dashboard', 'tgmpa' ) . '</a>' ), '</p>';
829
					echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>';
830
				} else {
831
					echo '<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>';
832
				}
833
834
				return true;
835
			} elseif ( isset( $this->plugins[ $slug ]['file_path'], $_GET['tgmpa-activate'] ) && 'activate-plugin' === $_GET['tgmpa-activate'] ) {
836
				// Activate action link was clicked.
837
				check_admin_referer( 'tgmpa-activate', 'tgmpa-nonce' );
838
839
				if ( false === $this->activate_single_plugin( $this->plugins[ $slug ]['file_path'], $slug ) ) {
840
					return true; // Finish execution of the function early as we encountered an error.
841
				}
842
			}
843
844
			return false;
845
		}
846
847
		/**
848
		 * Inject information into the 'update_plugins' site transient as WP checks that before running an update.
849
		 *
850
		 * @since 2.5.0
851
		 *
852
		 * @param array $plugins The plugin information for the plugins which are to be updated.
853
		 */
854
		public function inject_update_info( $plugins ) {
855
			$repo_updates = get_site_transient( 'update_plugins' );
856
857
			if ( ! is_object( $repo_updates ) ) {
858
				$repo_updates = new stdClass;
859
			}
860
861
			foreach ( $plugins as $slug => $plugin ) {
862
				$file_path = $plugin['file_path'];
863
864
				if ( empty( $repo_updates->response[ $file_path ] ) ) {
865
					$repo_updates->response[ $file_path ] = new stdClass;
866
				}
867
868
				// We only really need to set package, but let's do all we can in case WP changes something.
869
				$repo_updates->response[ $file_path ]->slug        = $slug;
870
				$repo_updates->response[ $file_path ]->plugin      = $file_path;
871
				$repo_updates->response[ $file_path ]->new_version = $plugin['version'];
872
				$repo_updates->response[ $file_path ]->package     = $plugin['source'];
873
				if ( empty( $repo_updates->response[ $file_path ]->url ) && ! empty( $plugin['external_url'] ) ) {
874
					$repo_updates->response[ $file_path ]->url = $plugin['external_url'];
875
				}
876
			}
877
878
			set_site_transient( 'update_plugins', $repo_updates );
879
		}
880
881
		/**
882
		 * Adjust the plugin directory name if necessary.
883
		 *
884
		 * The final destination directory of a plugin is based on the subdirectory name found in the
885
		 * (un)zipped source. In some cases - most notably GitHub repository plugin downloads -, this
886
		 * subdirectory name is not the same as the expected slug and the plugin will not be recognized
887
		 * as installed. This is fixed by adjusting the temporary unzipped source subdirectory name to
888
		 * the expected plugin slug.
889
		 *
890
		 * @since 2.5.0
891
		 *
892
		 * @param string       $source        Path to upgrade/zip-file-name.tmp/subdirectory/.
893
		 * @param string       $remote_source Path to upgrade/zip-file-name.tmp.
894
		 * @param \WP_Upgrader $upgrader      Instance of the upgrader which installs the plugin.
895
		 * @return string $source
896
		 */
897
		public function maybe_adjust_source_dir( $source, $remote_source, $upgrader ) {
0 ignored issues
show
Coding Style introduced by
maybe_adjust_source_dir uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
898
			if ( ! $this->is_tgmpa_page() || ! is_object( $GLOBALS['wp_filesystem'] ) ) {
899
				return $source;
900
			}
901
902
			// Check for single file plugins.
903
			$source_files = array_keys( $GLOBALS['wp_filesystem']->dirlist( $remote_source ) );
904
			if ( 1 === count( $source_files ) && false === $GLOBALS['wp_filesystem']->is_dir( $source ) ) {
905
				return $source;
906
			}
907
908
			// Multi-file plugin, let's see if the directory is correctly named.
909
			$desired_slug = '';
910
911
			// Figure out what the slug is supposed to be.
912
			if ( false === $upgrader->bulk && ! empty( $upgrader->skin->options['extra']['slug'] ) ) {
913
				$desired_slug = $upgrader->skin->options['extra']['slug'];
914
			} else {
915
				// Bulk installer contains less info, so fall back on the info registered here.
916
				foreach ( $this->plugins as $slug => $plugin ) {
917
					if ( ! empty( $upgrader->skin->plugin_names[ $upgrader->skin->i ] ) && $plugin['name'] === $upgrader->skin->plugin_names[ $upgrader->skin->i ] ) {
918
						$desired_slug = $slug;
919
						break;
920
					}
921
				}
922
				unset( $slug, $plugin );
923
			}
924
925
			if ( ! empty( $desired_slug ) ) {
926
				$subdir_name = untrailingslashit( str_replace( trailingslashit( $remote_source ), '', $source ) );
927
928
				if ( ! empty( $subdir_name ) && $subdir_name !== $desired_slug ) {
929
					$from = untrailingslashit( $source );
930
					$to   = trailingslashit( $remote_source ) . $desired_slug;
931
932
					if ( true === $GLOBALS['wp_filesystem']->move( $from, $to ) ) {
933
						return trailingslashit( $to );
934 View Code Duplication
					} else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
935
						return new WP_Error( 'rename_failed', esc_html__( 'The remote plugin package does not contain a folder with the desired slug and renaming did not work.', 'tgmpa' ) . ' ' . esc_html__( 'Please contact the plugin provider and ask them to package their plugin according to the WordPress guidelines.', 'tgmpa' ), array( 'found' => $subdir_name, 'expected' => $desired_slug ) );
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \WP_Error('re...ed' => $desired_slug)); (WP_Error) is incompatible with the return type documented by TGM_Plugin_Activation::maybe_adjust_source_dir of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
936
					}
937 View Code Duplication
				} elseif ( empty( $subdir_name ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
938
					return new WP_Error( 'packaged_wrong', esc_html__( 'The remote plugin package consists of more than one file, but the files are not packaged in a folder.', 'tgmpa' ) . ' ' . esc_html__( 'Please contact the plugin provider and ask them to package their plugin according to the WordPress guidelines.', 'tgmpa' ), array( 'found' => $subdir_name, 'expected' => $desired_slug ) );
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \WP_Error('pa...ed' => $desired_slug)); (WP_Error) is incompatible with the return type documented by TGM_Plugin_Activation::maybe_adjust_source_dir of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
939
				}
940
			}
941
942
			return $source;
943
		}
944
945
		/**
946
		 * Activate a single plugin and send feedback about the result to the screen.
947
		 *
948
		 * @since 2.5.0
949
		 *
950
		 * @param string $file_path Path within wp-plugins/ to main plugin file.
951
		 * @param string $slug      Plugin slug.
952
		 * @param bool   $automatic Whether this is an automatic activation after an install. Defaults to false.
953
		 *                          This determines the styling of the output messages.
954
		 * @return bool False if an error was encountered, true otherwise.
955
		 */
956
		protected function activate_single_plugin( $file_path, $slug, $automatic = false ) {
0 ignored issues
show
Coding Style introduced by
activate_single_plugin uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
957
			if ( $this->can_plugin_activate( $slug ) ) {
958
				$activate = activate_plugin( $file_path );
959
960
				if ( is_wp_error( $activate ) ) {
961
					echo '<div id="message" class="error"><p>', wp_kses_post( $activate->get_error_message() ), '</p></div>',
962
						'<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>';
963
964
					return false; // End it here if there is an error with activation.
965
				} else {
966
					if ( ! $automatic ) {
967
						// Make sure message doesn't display again if bulk activation is performed
968
						// immediately after a single activation.
969
						if ( ! isset( $_POST['action'] ) ) { // WPCS: CSRF OK.
970
							echo '<div id="message" class="updated"><p>', esc_html( $this->strings['activated_successfully'] ), ' <strong>', esc_html( $this->plugins[ $slug ]['name'] ), '.</strong></p></div>';
971
						}
972
					} else {
973
						// Simpler message layout for use on the plugin install page.
974
						echo '<p>', esc_html( $this->strings['plugin_activated'] ), '</p>';
975
					}
976
				}
977 View Code Duplication
			} elseif ( $this->is_plugin_active( $slug ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
978
				// No simpler message format provided as this message should never be encountered
979
				// on the plugin install page.
980
				echo '<div id="message" class="error"><p>',
981
					sprintf(
982
						esc_html( $this->strings['plugin_already_active'] ),
983
						'<strong>' . esc_html( $this->plugins[ $slug ]['name'] ) . '</strong>'
984
					),
985
					'</p></div>';
986
			} elseif ( $this->does_plugin_require_update( $slug ) ) {
987
				if ( ! $automatic ) {
988
					// Make sure message doesn't display again if bulk activation is performed
989
					// immediately after a single activation.
990 View Code Duplication
					if ( ! isset( $_POST['action'] ) ) { // WPCS: CSRF OK.
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
991
						echo '<div id="message" class="error"><p>',
992
							sprintf(
993
								esc_html( $this->strings['plugin_needs_higher_version'] ),
994
								'<strong>' . esc_html( $this->plugins[ $slug ]['name'] ) . '</strong>'
995
							),
996
							'</p></div>';
997
					}
998
				} else {
999
					// Simpler message layout for use on the plugin install page.
1000
					echo '<p>', sprintf( esc_html( $this->strings['plugin_needs_higher_version'] ), esc_html( $this->plugins[ $slug ]['name'] ) ), '</p>';
1001
				}
1002
			}
1003
1004
			return true;
1005
		}
1006
1007
		/**
1008
		 * Echoes required plugin notice.
1009
		 *
1010
		 * Outputs a message telling users that a specific plugin is required for
1011
		 * their theme. If appropriate, it includes a link to the form page where
1012
		 * users can install and activate the plugin.
1013
		 *
1014
		 * Returns early if we're on the Install page.
1015
		 *
1016
		 * @since 1.0.0
1017
		 *
1018
		 * @global object $current_screen
1019
		 *
1020
		 * @return null Returns early if we're on the Install page.
1021
		 */
1022
		public function notices() {
0 ignored issues
show
Coding Style introduced by
notices uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1023
			// Remove nag on the install page / Return early if the nag message has been dismissed.
1024
			if ( $this->is_tgmpa_page() || get_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, true ) ) {
1025
				return;
1026
			}
1027
1028
			// Store for the plugin slugs by message type.
1029
			$message = array();
1030
1031
			// Initialize counters used to determine plurality of action link texts.
1032
			$install_link_count  = 0;
1033
			$update_link_count   = 0;
1034
			$activate_link_count = 0;
1035
1036
			foreach ( $this->plugins as $slug => $plugin ) {
1037
				if ( $this->is_plugin_active( $slug ) && false === $this->does_plugin_have_update( $slug ) ) {
1038
					continue;
1039
				}
1040
1041
				if ( ! $this->is_plugin_installed( $slug ) ) {
1042
					if ( current_user_can( 'install_plugins' ) ) {
1043
						$install_link_count++;
1044
1045
						if ( true === $plugin['required'] ) {
1046
							$message['notice_can_install_required'][] = $slug;
1047
						} else {
1048
							$message['notice_can_install_recommended'][] = $slug;
1049
						}
1050
					} else {
1051
						// Need higher privileges to install the plugin.
1052
						$message['notice_cannot_install'][] = $slug;
1053
					}
1054
				} else {
1055
					if ( ! $this->is_plugin_active( $slug ) && $this->can_plugin_activate( $slug ) ) {
1056
						if ( current_user_can( 'activate_plugins' ) ) {
1057
							$activate_link_count++;
1058
1059
							if ( true === $plugin['required'] ) {
1060
								$message['notice_can_activate_required'][] = $slug;
1061
							} else {
1062
								$message['notice_can_activate_recommended'][] = $slug;
1063
							}
1064
						} else {
1065
							// Need higher privileges to activate the plugin.
1066
							$message['notice_cannot_activate'][] = $slug;
1067
						}
1068
					}
1069
1070
					if ( $this->does_plugin_require_update( $slug ) || false !== $this->does_plugin_have_update( $slug ) ) {
1071
1072
						if ( current_user_can( 'install_plugins' ) ) {
1073
							$update_link_count++;
1074
1075
							if ( $this->does_plugin_require_update( $slug ) ) {
1076
								$message['notice_ask_to_update'][] = $slug;
1077
							} elseif ( false !== $this->does_plugin_have_update( $slug ) ) {
1078
								$message['notice_ask_to_update_maybe'][] = $slug;
1079
							}
1080
						} else {
1081
							// Need higher privileges to update the plugin.
1082
							$message['notice_cannot_update'][] = $slug;
1083
						}
1084
					}
1085
				}
1086
			}
1087
			unset( $slug, $plugin );
1088
1089
			// If we have notices to display, we move forward.
1090
			if ( ! empty( $message ) ) {
1091
				krsort( $message ); // Sort messages.
1092
				$rendered = '';
1093
1094
				// As add_settings_error() wraps the final message in a <p> and as the final message can't be
1095
				// filtered, using <p>'s in our html would render invalid html output.
1096
				$line_template = '<span style="display: block; margin: 0.5em 0.5em 0 0; clear: both;">%s</span>' . "\n";
1097
1098
				// If dismissable is false and a message is set, output it now.
1099
				if ( ! $this->dismissable && ! empty( $this->dismiss_msg ) ) {
1100
					$rendered .= sprintf( $line_template, wp_kses_post( $this->dismiss_msg ) );
1101
				}
1102
1103
				// Render the individual message lines for the notice.
1104
				foreach ( $message as $type => $plugin_group ) {
1105
					$linked_plugins = array();
1106
1107
					// Get the external info link for a plugin if one is available.
1108
					foreach ( $plugin_group as $plugin_slug ) {
1109
						$linked_plugins[] = $this->get_info_link( $plugin_slug );
1110
					}
1111
					unset( $plugin_slug );
1112
1113
					$count          = count( $plugin_group );
1114
					$linked_plugins = array_map( array( 'TGMPA_Utils', 'wrap_in_em' ), $linked_plugins );
1115
					$last_plugin    = array_pop( $linked_plugins ); // Pop off last name to prep for readability.
1116
					$imploded       = empty( $linked_plugins ) ? $last_plugin : ( implode( ', ', $linked_plugins ) . ' ' . esc_html_x( 'and', 'plugin A *and* plugin B', 'tgmpa' ) . ' ' . $last_plugin );
1117
1118
					$rendered .= sprintf(
1119
						$line_template,
1120
						sprintf(
1121
							translate_nooped_plural( $this->strings[ $type ], $count, 'tgmpa' ),
1122
							$imploded,
1123
							$count
1124
						)
1125
					);
1126
1127
					if ( 0 === strpos( $type, 'notice_cannot' ) ) {
1128
						$rendered .= $this->strings['contact_admin'];
1129
					}
1130
				}
1131
				unset( $type, $plugin_group, $linked_plugins, $count, $last_plugin, $imploded );
1132
1133
				// Setup action links.
1134
				$action_links = array(
1135
					'install'  => '',
1136
					'update'   => '',
1137
					'activate' => '',
1138
					'dismiss'  => $this->dismissable ? '<a href="' . esc_url( add_query_arg( 'tgmpa-dismiss', 'dismiss_admin_notices' ) ) . '" class="dismiss-notice" target="_parent">' . esc_html( $this->strings['dismiss'] ) . '</a>' : '',
1139
				);
1140
1141
				$link_template = '<a href="%2$s">%1$s</a>';
1142
1143
				if ( current_user_can( 'install_plugins' ) ) {
1144 View Code Duplication
					if ( $install_link_count > 0 ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
1145
						$action_links['install'] = sprintf(
1146
							$link_template,
1147
							translate_nooped_plural( $this->strings['install_link'], $install_link_count, 'tgmpa' ),
1148
							esc_url( $this->get_tgmpa_status_url( 'install' ) )
1149
						);
1150
					}
1151 View Code Duplication
					if ( $update_link_count > 0 ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
1152
						$action_links['update'] = sprintf(
1153
							$link_template,
1154
							translate_nooped_plural( $this->strings['update_link'], $update_link_count, 'tgmpa' ),
1155
							esc_url( $this->get_tgmpa_status_url( 'update' ) )
1156
						);
1157
					}
1158
				}
1159
1160 View Code Duplication
				if ( current_user_can( 'activate_plugins' ) && $activate_link_count > 0 ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
1161
					$action_links['activate'] = sprintf(
1162
						$link_template,
1163
						translate_nooped_plural( $this->strings['activate_link'], $activate_link_count, 'tgmpa' ),
1164
						esc_url( $this->get_tgmpa_status_url( 'activate' ) )
1165
					);
1166
				}
1167
1168
				$action_links = apply_filters( 'tgmpa_notice_action_links', $action_links );
1169
1170
				$action_links = array_filter( (array) $action_links ); // Remove any empty array items.
1171
1172
				if ( ! empty( $action_links ) && is_array( $action_links ) ) {
1173
					$action_links = sprintf( $line_template, implode( ' | ', $action_links ) );
1174
					$rendered    .= apply_filters( 'tgmpa_notice_rendered_action_links', $action_links );
1175
				}
1176
1177
				// Register the nag messages and prepare them to be processed.
1178
				if ( ! empty( $this->strings['nag_type'] ) ) {
1179
					add_settings_error( 'tgmpa', 'tgmpa', $rendered, sanitize_html_class( strtolower( $this->strings['nag_type'] ) ) );
1180
				} else {
1181
					$nag_class = version_compare( $this->wp_version, '3.8', '<' ) ? 'updated' : 'update-nag';
1182
					add_settings_error( 'tgmpa', 'tgmpa', $rendered, $nag_class );
1183
				}
1184
			}
1185
1186
			// Admin options pages already output settings_errors, so this is to avoid duplication.
1187
			if ( 'options-general' !== $GLOBALS['current_screen']->parent_base ) {
1188
				$this->display_settings_errors();
1189
			}
1190
		}
1191
1192
		/**
1193
		 * Display settings errors and remove those which have been displayed to avoid duplicate messages showing
1194
		 *
1195
		 * @since 2.5.0
1196
		 */
1197
		protected function display_settings_errors() {
1198
			global $wp_settings_errors;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
1199
1200
			settings_errors( 'tgmpa' );
1201
1202
			foreach ( (array) $wp_settings_errors as $key => $details ) {
1203
				if ( 'tgmpa' === $details['setting'] ) {
1204
					unset( $wp_settings_errors[ $key ] );
1205
					break;
1206
				}
1207
			}
1208
		}
1209
1210
		/**
1211
		 * Add dismissable admin notices.
1212
		 *
1213
		 * Appends a link to the admin nag messages. If clicked, the admin notice disappears and no longer is visible to users.
1214
		 *
1215
		 * @since 2.1.0
1216
		 */
1217
		public function dismiss() {
0 ignored issues
show
Coding Style introduced by
dismiss uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1218
			if ( isset( $_GET['tgmpa-dismiss'] ) ) {
1219
				update_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, 1 );
1220
			}
1221
		}
1222
1223
		/**
1224
		 * Add individual plugin to our collection of plugins.
1225
		 *
1226
		 * If the required keys are not set or the plugin has already
1227
		 * been registered, the plugin is not added.
1228
		 *
1229
		 * @since 2.0.0
1230
		 *
1231
		 * @param array|null $plugin Array of plugin arguments or null if invalid argument.
1232
		 * @return null Return early if incorrect argument.
1233
		 */
1234
		public function register( $plugin ) {
1235
			if ( empty( $plugin['slug'] ) || empty( $plugin['name'] ) ) {
1236
				return;
1237
			}
1238
1239
			if ( empty( $plugin['slug'] ) || ! is_string( $plugin['slug'] ) || isset( $this->plugins[ $plugin['slug'] ] ) ) {
1240
				return;
1241
			}
1242
1243
			$defaults = array(
1244
				'name'               => '',      // String
1245
				'slug'               => '',      // String
1246
				'source'             => 'repo',  // String
1247
				'required'           => false,   // Boolean
1248
				'version'            => '',      // String
1249
				'force_activation'   => false,   // Boolean
1250
				'force_deactivation' => false,   // Boolean
1251
				'external_url'       => '',      // String
1252
				'is_callable'        => '',      // String|Array.
1253
			);
1254
1255
			// Prepare the received data.
1256
			$plugin = wp_parse_args( $plugin, $defaults );
1257
1258
			// Standardize the received slug.
1259
			$plugin['slug'] = $this->sanitize_key( $plugin['slug'] );
1260
1261
			// Forgive users for using string versions of booleans or floats for version number.
1262
			$plugin['version']            = (string) $plugin['version'];
1263
			$plugin['source']             = empty( $plugin['source'] ) ? 'repo' : $plugin['source'];
1264
			$plugin['required']           = TGMPA_Utils::validate_bool( $plugin['required'] );
1265
			$plugin['force_activation']   = TGMPA_Utils::validate_bool( $plugin['force_activation'] );
1266
			$plugin['force_deactivation'] = TGMPA_Utils::validate_bool( $plugin['force_deactivation'] );
1267
1268
			// Enrich the received data.
1269
			$plugin['file_path']   = $this->_get_plugin_basename_from_slug( $plugin['slug'] );
1270
			$plugin['source_type'] = $this->get_plugin_source_type( $plugin['source'] );
1271
1272
			// Set the class properties.
1273
			$this->plugins[ $plugin['slug'] ]    = $plugin;
1274
			$this->sort_order[ $plugin['slug'] ] = $plugin['name'];
1275
1276
			// Should we add the force activation hook ?
1277
			if ( true === $plugin['force_activation'] ) {
1278
				$this->has_forced_activation = true;
1279
			}
1280
1281
			// Should we add the force deactivation hook ?
1282
			if ( true === $plugin['force_deactivation'] ) {
1283
				$this->has_forced_deactivation = true;
1284
			}
1285
		}
1286
1287
		/**
1288
		 * Determine what type of source the plugin comes from.
1289
		 *
1290
		 * @since 2.5.0
1291
		 *
1292
		 * @param string $source The source of the plugin as provided, either empty (= WP repo), a file path
1293
		 *                       (= bundled) or an external URL.
1294
		 * @return string 'repo', 'external', or 'bundled'
1295
		 */
1296
		protected function get_plugin_source_type( $source ) {
1297
			if ( 'repo' === $source || preg_match( self::WP_REPO_REGEX, $source ) ) {
1298
				return 'repo';
1299
			} elseif ( preg_match( self::IS_URL_REGEX, $source ) ) {
1300
				return 'external';
1301
			} else {
1302
				return 'bundled';
1303
			}
1304
		}
1305
1306
		/**
1307
		 * Sanitizes a string key.
1308
		 *
1309
		 * Near duplicate of WP Core `sanitize_key()`. The difference is that uppercase characters *are*
1310
		 * allowed, so as not to break upgrade paths from non-standard bundled plugins using uppercase
1311
		 * characters in the plugin directory path/slug. Silly them.
1312
		 *
1313
		 * @see https://developer.wordpress.org/reference/hooks/sanitize_key/
1314
		 *
1315
		 * @since 2.5.0
1316
		 *
1317
		 * @param string $key String key.
1318
		 * @return string Sanitized key
1319
		 */
1320
		public function sanitize_key( $key ) {
1321
			$raw_key = $key;
1322
			$key     = preg_replace( '`[^A-Za-z0-9_-]`', '', $key );
1323
1324
			/**
1325
			* Filter a sanitized key string.
1326
			*
1327
			* @since 3.0.0
1328
			*
1329
			* @param string $key     Sanitized key.
1330
			* @param string $raw_key The key prior to sanitization.
1331
			*/
1332
			return apply_filters( 'tgmpa_sanitize_key', $key, $raw_key );
1333
		}
1334
1335
		/**
1336
		 * Amend default configuration settings.
1337
		 *
1338
		 * @since 2.0.0
1339
		 *
1340
		 * @param array $config Array of config options to pass as class properties.
1341
		 */
1342
		public function config( $config ) {
1343
			$keys = array(
1344
				'id',
1345
				'default_path',
1346
				'has_notices',
1347
				'dismissable',
1348
				'dismiss_msg',
1349
				'menu',
1350
				'parent_slug',
1351
				'capability',
1352
				'is_automatic',
1353
				'message',
1354
				'strings',
1355
			);
1356
1357
			foreach ( $keys as $key ) {
1358
				if ( isset( $config[ $key ] ) ) {
1359
					if ( is_array( $config[ $key ] ) ) {
1360
						$this->$key = array_merge( $this->$key, $config[ $key ] );
1361
					} else {
1362
						$this->$key = $config[ $key ];
1363
					}
1364
				}
1365
			}
1366
		}
1367
1368
		/**
1369
		 * Amend action link after plugin installation.
1370
		 *
1371
		 * @since 2.0.0
1372
		 *
1373
		 * @param array $install_actions Existing array of actions.
1374
		 * @return array Amended array of actions.
1375
		 */
1376
		public function actions( $install_actions ) {
1377
			// Remove action links on the TGMPA install page.
1378
			if ( $this->is_tgmpa_page() ) {
1379
				return false;
1380
			}
1381
1382
			return $install_actions;
1383
		}
1384
1385
		/**
1386
		 * Flushes the plugins cache on theme switch to prevent stale entries
1387
		 * from remaining in the plugin table.
1388
		 *
1389
		 * @since 2.4.0
1390
		 *
1391
		 * @param bool $clear_update_cache Optional. Whether to clear the Plugin updates cache.
1392
		 *                                 Parameter added in v2.5.0.
1393
		 */
1394
		public function flush_plugins_cache( $clear_update_cache = true ) {
1395
			wp_clean_plugins_cache( $clear_update_cache );
1396
		}
1397
1398
		/**
1399
		 * Set file_path key for each installed plugin.
1400
		 *
1401
		 * @since 2.1.0
1402
		 *
1403
		 * @param string $plugin_slug Optional. If set, only (re-)populates the file path for that specific plugin.
1404
		 *                            Parameter added in v2.5.0.
1405
		 */
1406
		public function populate_file_path( $plugin_slug = '' ) {
1407
			if ( ! empty( $plugin_slug ) && is_string( $plugin_slug ) && isset( $this->plugins[ $plugin_slug ] ) ) {
1408
				$this->plugins[ $plugin_slug ]['file_path'] = $this->_get_plugin_basename_from_slug( $plugin_slug );
1409
			} else {
1410
				// Add file_path key for all plugins.
1411
				foreach ( $this->plugins as $slug => $values ) {
1412
					$this->plugins[ $slug ]['file_path'] = $this->_get_plugin_basename_from_slug( $slug );
1413
				}
1414
			}
1415
		}
1416
1417
		/**
1418
		 * Helper function to extract the file path of the plugin file from the
1419
		 * plugin slug, if the plugin is installed.
1420
		 *
1421
		 * @since 2.0.0
1422
		 *
1423
		 * @param string $slug Plugin slug (typically folder name) as provided by the developer.
1424
		 * @return string Either file path for plugin if installed, or just the plugin slug.
1425
		 */
1426
		protected function _get_plugin_basename_from_slug( $slug ) {
1427
			$keys = array_keys( $this->get_plugins() );
1428
1429
			foreach ( $keys as $key ) {
1430
				if ( preg_match( '|^' . $slug . '/|', $key ) ) {
1431
					return $key;
1432
				}
1433
			}
1434
1435
			return $slug;
1436
		}
1437
1438
		/**
1439
		 * Retrieve plugin data, given the plugin name.
1440
		 *
1441
		 * Loops through the registered plugins looking for $name. If it finds it,
1442
		 * it returns the $data from that plugin. Otherwise, returns false.
1443
		 *
1444
		 * @since 2.1.0
1445
		 *
1446
		 * @param string $name Name of the plugin, as it was registered.
1447
		 * @param string $data Optional. Array key of plugin data to return. Default is slug.
1448
		 * @return string|boolean Plugin slug if found, false otherwise.
1449
		 */
1450
		public function _get_plugin_data_from_name( $name, $data = 'slug' ) {
1451
			foreach ( $this->plugins as $values ) {
1452
				if ( $name === $values['name'] && isset( $values[ $data ] ) ) {
1453
					return $values[ $data ];
1454
				}
1455
			}
1456
1457
			return false;
1458
		}
1459
1460
		/**
1461
		 * Retrieve the download URL for a package.
1462
		 *
1463
		 * @since 2.5.0
1464
		 *
1465
		 * @param string $slug Plugin slug.
1466
		 * @return string Plugin download URL or path to local file or empty string if undetermined.
1467
		 */
1468
		public function get_download_url( $slug ) {
1469
			$dl_source = '';
1470
1471
			switch ( $this->plugins[ $slug ]['source_type'] ) {
1472
				case 'repo':
1473
					return $this->get_wp_repo_download_url( $slug );
1474
				case 'external':
1475
					return $this->plugins[ $slug ]['source'];
1476
				case 'bundled':
1477
					return $this->default_path . $this->plugins[ $slug ]['source'];
1478
			}
1479
1480
			return $dl_source; // Should never happen.
1481
		}
1482
1483
		/**
1484
		 * Retrieve the download URL for a WP repo package.
1485
		 *
1486
		 * @since 2.5.0
1487
		 *
1488
		 * @param string $slug Plugin slug.
1489
		 * @return string Plugin download URL.
1490
		 */
1491
		protected function get_wp_repo_download_url( $slug ) {
1492
			$source = '';
1493
			$api    = $this->get_plugins_api( $slug );
1494
1495
			if ( false !== $api && isset( $api->download_link ) ) {
1496
				$source = $api->download_link;
1497
			}
1498
1499
			return $source;
1500
		}
1501
1502
		/**
1503
		 * Try to grab information from WordPress API.
1504
		 *
1505
		 * @since 2.5.0
1506
		 *
1507
		 * @param string $slug Plugin slug.
1508
		 * @return object Plugins_api response object on success, WP_Error on failure.
1509
		 */
1510
		protected function get_plugins_api( $slug ) {
1511
			static $api = array(); // Cache received responses.
1512
1513
			if ( ! isset( $api[ $slug ] ) ) {
1514
				if ( ! function_exists( 'plugins_api' ) ) {
1515
					require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
1516
				}
1517
1518
				$response = plugins_api( 'plugin_information', array( 'slug' => $slug, 'fields' => array( 'sections' => false ) ) );
1519
1520
				$api[ $slug ] = false;
1521
1522
				if ( is_wp_error( $response ) ) {
1523
					wp_die( esc_html( $this->strings['oops'] ) );
1524
				} else {
1525
					$api[ $slug ] = $response;
1526
				}
1527
			}
1528
1529
			return $api[ $slug ];
1530
		}
1531
1532
		/**
1533
		 * Retrieve a link to a plugin information page.
1534
		 *
1535
		 * @since 2.5.0
1536
		 *
1537
		 * @param string $slug Plugin slug.
1538
		 * @return string Fully formed html link to a plugin information page if available
1539
		 *                or the plugin name if not.
1540
		 */
1541
		public function get_info_link( $slug ) {
1542
			if ( ! empty( $this->plugins[ $slug ]['external_url'] ) && preg_match( self::IS_URL_REGEX, $this->plugins[ $slug ]['external_url'] ) ) {
1543
				$link = sprintf(
1544
					'<a href="%1$s" target="_blank">%2$s</a>',
1545
					esc_url( $this->plugins[ $slug ]['external_url'] ),
1546
					esc_html( $this->plugins[ $slug ]['name'] )
1547
				);
1548
			} elseif ( 'repo' === $this->plugins[ $slug ]['source_type'] ) {
1549
				$url = add_query_arg(
1550
					array(
1551
						'tab'       => 'plugin-information',
1552
						'plugin'    => urlencode( $slug ),
1553
						'TB_iframe' => 'true',
1554
						'width'     => '640',
1555
						'height'    => '500',
1556
					),
1557
					self_admin_url( 'plugin-install.php' )
1558
				);
1559
1560
				$link = sprintf(
1561
					'<a href="%1$s" class="thickbox">%2$s</a>',
1562
					esc_url( $url ),
1563
					esc_html( $this->plugins[ $slug ]['name'] )
1564
				);
1565
			} else {
1566
				$link = esc_html( $this->plugins[ $slug ]['name'] ); // No hyperlink.
1567
			}
1568
1569
			return $link;
1570
		}
1571
1572
		/**
1573
		 * Determine if we're on the TGMPA Install page.
1574
		 *
1575
		 * @since 2.1.0
1576
		 *
1577
		 * @return boolean True when on the TGMPA page, false otherwise.
1578
		 */
1579
		protected function is_tgmpa_page() {
0 ignored issues
show
Coding Style introduced by
is_tgmpa_page uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1580
			return isset( $_GET['page'] ) && $this->menu === $_GET['page'];
1581
		}
1582
1583
		/**
1584
		 * Retrieve the URL to the TGMPA Install page.
1585
		 *
1586
		 * I.e. depending on the config settings passed something along the lines of:
1587
		 * http://example.com/wp-admin/themes.php?page=tgmpa-install-plugins
1588
		 *
1589
		 * @since 2.5.0
1590
		 *
1591
		 * @return string Properly encoded URL (not escaped).
1592
		 */
1593
		public function get_tgmpa_url() {
1594
			static $url;
1595
1596
			if ( ! isset( $url ) ) {
1597
				$parent = $this->parent_slug;
1598
				if ( false === strpos( $parent, '.php' ) ) {
1599
					$parent = 'admin.php';
1600
				}
1601
				$url = add_query_arg(
1602
					array(
1603
						'page' => urlencode( $this->menu ),
1604
					),
1605
					self_admin_url( $parent )
1606
				);
1607
			}
1608
1609
			return $url;
1610
		}
1611
1612
		/**
1613
		 * Retrieve the URL to the TGMPA Install page for a specific plugin status (view).
1614
		 *
1615
		 * I.e. depending on the config settings passed something along the lines of:
1616
		 * http://example.com/wp-admin/themes.php?page=tgmpa-install-plugins&plugin_status=install
1617
		 *
1618
		 * @since 2.5.0
1619
		 *
1620
		 * @param string $status Plugin status - either 'install', 'update' or 'activate'.
1621
		 * @return string Properly encoded URL (not escaped).
1622
		 */
1623
		public function get_tgmpa_status_url( $status ) {
1624
			return add_query_arg(
1625
				array(
1626
					'plugin_status' => urlencode( $status ),
1627
				),
1628
				$this->get_tgmpa_url()
1629
			);
1630
		}
1631
1632
		/**
1633
		 * Determine whether there are open actions for plugins registered with TGMPA.
1634
		 *
1635
		 * @since 2.5.0
1636
		 *
1637
		 * @return bool True if complete, i.e. no outstanding actions. False otherwise.
1638
		 */
1639
		public function is_tgmpa_complete() {
1640
			$complete = true;
1641
			foreach ( $this->plugins as $slug => $plugin ) {
1642
				if ( ! $this->is_plugin_active( $slug ) || false !== $this->does_plugin_have_update( $slug ) ) {
1643
					$complete = false;
1644
					break;
1645
				}
1646
			}
1647
1648
			return $complete;
1649
		}
1650
1651
		/**
1652
		 * Check if a plugin is installed. Does not take must-use plugins into account.
1653
		 *
1654
		 * @since 2.5.0
1655
		 *
1656
		 * @param string $slug Plugin slug.
1657
		 * @return bool True if installed, false otherwise.
1658
		 */
1659
		public function is_plugin_installed( $slug ) {
1660
			$installed_plugins = $this->get_plugins(); // Retrieve a list of all installed plugins (WP cached).
1661
1662
			return ( ! empty( $installed_plugins[ $this->plugins[ $slug ]['file_path'] ] ) );
1663
		}
1664
1665
		/**
1666
		 * Check if a plugin is active.
1667
		 *
1668
		 * @since 2.5.0
1669
		 *
1670
		 * @param string $slug Plugin slug.
1671
		 * @return bool True if active, false otherwise.
1672
		 */
1673
		public function is_plugin_active( $slug ) {
1674
			return ( ( ! empty( $this->plugins[ $slug ]['is_callable'] ) && is_callable( $this->plugins[ $slug ]['is_callable'] ) ) || is_plugin_active( $this->plugins[ $slug ]['file_path'] ) );
1675
		}
1676
1677
		/**
1678
		 * Check if a plugin can be updated, i.e. if we have information on the minimum WP version required
1679
		 * available, check whether the current install meets them.
1680
		 *
1681
		 * @since 2.5.0
1682
		 *
1683
		 * @param string $slug Plugin slug.
1684
		 * @return bool True if OK to update, false otherwise.
1685
		 */
1686
		public function can_plugin_update( $slug ) {
0 ignored issues
show
Coding Style introduced by
can_plugin_update uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1687
			// We currently can't get reliable info on non-WP-repo plugins - issue #380.
1688
			if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) {
1689
				return true;
1690
			}
1691
1692
			$api = $this->get_plugins_api( $slug );
1693
1694
			if ( false !== $api && isset( $api->requires ) ) {
1695
				return version_compare( $GLOBALS['wp_version'], $api->requires, '>=' );
1696
			}
1697
1698
			// No usable info received from the plugins API, presume we can update.
1699
			return true;
1700
		}
1701
1702
		/**
1703
		 * Check if a plugin can be activated, i.e. is not currently active and meets the minimum
1704
		 * plugin version requirements set in TGMPA (if any).
1705
		 *
1706
		 * @since 2.5.0
1707
		 *
1708
		 * @param string $slug Plugin slug.
1709
		 * @return bool True if OK to activate, false otherwise.
1710
		 */
1711
		public function can_plugin_activate( $slug ) {
1712
			return ( ! $this->is_plugin_active( $slug ) && ! $this->does_plugin_require_update( $slug ) );
1713
		}
1714
1715
		/**
1716
		 * Retrieve the version number of an installed plugin.
1717
		 *
1718
		 * @since 2.5.0
1719
		 *
1720
		 * @param string $slug Plugin slug.
1721
		 * @return string Version number as string or an empty string if the plugin is not installed
1722
		 *                or version unknown (plugins which don't comply with the plugin header standard).
1723
		 */
1724
		public function get_installed_version( $slug ) {
1725
			$installed_plugins = $this->get_plugins(); // Retrieve a list of all installed plugins (WP cached).
1726
1727
			if ( ! empty( $installed_plugins[ $this->plugins[ $slug ]['file_path'] ]['Version'] ) ) {
1728
				return $installed_plugins[ $this->plugins[ $slug ]['file_path'] ]['Version'];
1729
			}
1730
1731
			return '';
1732
		}
1733
1734
		/**
1735
		 * Check whether a plugin complies with the minimum version requirements.
1736
		 *
1737
		 * @since 2.5.0
1738
		 *
1739
		 * @param string $slug Plugin slug.
1740
		 * @return bool True when a plugin needs to be updated, otherwise false.
1741
		 */
1742
		public function does_plugin_require_update( $slug ) {
1743
			$installed_version = $this->get_installed_version( $slug );
1744
			$minimum_version   = $this->plugins[ $slug ]['version'];
1745
1746
			return version_compare( $minimum_version, $installed_version, '>' );
1747
		}
1748
1749
		/**
1750
		 * Check whether there is an update available for a plugin.
1751
		 *
1752
		 * @since 2.5.0
1753
		 *
1754
		 * @param string $slug Plugin slug.
1755
		 * @return false|string Version number string of the available update or false if no update available.
1756
		 */
1757
		public function does_plugin_have_update( $slug ) {
1758
			// Presume bundled and external plugins will point to a package which meets the minimum required version.
1759
			if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) {
1760
				if ( $this->does_plugin_require_update( $slug ) ) {
1761
					return $this->plugins[ $slug ]['version'];
1762
				}
1763
1764
				return false;
1765
			}
1766
1767
			$repo_updates = get_site_transient( 'update_plugins' );
1768
1769 View Code Duplication
			if ( isset( $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->new_version ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
1770
				return $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->new_version;
1771
			}
1772
1773
			return false;
1774
		}
1775
1776
		/**
1777
		 * Retrieve potential upgrade notice for a plugin.
1778
		 *
1779
		 * @since 2.5.0
1780
		 *
1781
		 * @param string $slug Plugin slug.
1782
		 * @return string The upgrade notice or an empty string if no message was available or provided.
1783
		 */
1784
		public function get_upgrade_notice( $slug ) {
1785
			// We currently can't get reliable info on non-WP-repo plugins - issue #380.
1786
			if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) {
1787
				return '';
1788
			}
1789
1790
			$repo_updates = get_site_transient( 'update_plugins' );
1791
1792 View Code Duplication
			if ( ! empty( $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->upgrade_notice ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
1793
				return $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->upgrade_notice;
1794
			}
1795
1796
			return '';
1797
		}
1798
1799
		/**
1800
		 * Wrapper around the core WP get_plugins function, making sure it's actually available.
1801
		 *
1802
		 * @since 2.5.0
1803
		 *
1804
		 * @param string $plugin_folder Optional. Relative path to single plugin folder.
1805
		 * @return array Array of installed plugins with plugin information.
1806
		 */
1807
		public function get_plugins( $plugin_folder = '' ) {
1808
			if ( ! function_exists( 'get_plugins' ) ) {
1809
				require_once ABSPATH . 'wp-admin/includes/plugin.php';
1810
			}
1811
1812
			return get_plugins( $plugin_folder );
1813
		}
1814
1815
		/**
1816
		 * Delete dismissable nag option when theme is switched.
1817
		 *
1818
		 * This ensures that the user(s) is/are again reminded via nag of required
1819
		 * and/or recommended plugins if they re-activate the theme.
1820
		 *
1821
		 * @since 2.1.1
1822
		 */
1823
		public function update_dismiss() {
1824
			delete_metadata( 'user', null, 'tgmpa_dismissed_notice_' . $this->id, null, true );
1825
		}
1826
1827
		/**
1828
		 * Forces plugin activation if the parameter 'force_activation' is
1829
		 * set to true.
1830
		 *
1831
		 * This allows theme authors to specify certain plugins that must be
1832
		 * active at all times while using the current theme.
1833
		 *
1834
		 * Please take special care when using this parameter as it has the
1835
		 * potential to be harmful if not used correctly. Setting this parameter
1836
		 * to true will not allow the specified plugin to be deactivated unless
1837
		 * the user switches themes.
1838
		 *
1839
		 * @since 2.2.0
1840
		 */
1841
		public function force_activation() {
1842
			foreach ( $this->plugins as $slug => $plugin ) {
1843
				if ( true === $plugin['force_activation'] ) {
1844
					if ( ! $this->is_plugin_installed( $slug ) ) {
1845
						// Oops, plugin isn't there so iterate to next condition.
1846
						continue;
1847
					} elseif ( $this->can_plugin_activate( $slug ) ) {
1848
						// There we go, activate the plugin.
1849
						activate_plugin( $plugin['file_path'] );
1850
					}
1851
				}
1852
			}
1853
		}
1854
1855
		/**
1856
		 * Forces plugin deactivation if the parameter 'force_deactivation'
1857
		 * is set to true.
1858
		 *
1859
		 * This allows theme authors to specify certain plugins that must be
1860
		 * deactivated upon switching from the current theme to another.
1861
		 *
1862
		 * Please take special care when using this parameter as it has the
1863
		 * potential to be harmful if not used correctly.
1864
		 *
1865
		 * @since 2.2.0
1866
		 */
1867
		public function force_deactivation() {
1868
			foreach ( $this->plugins as $slug => $plugin ) {
1869
				// Only proceed forward if the parameter is set to true and plugin is active.
1870
				if ( true === $plugin['force_deactivation'] && $this->is_plugin_active( $slug ) ) {
1871
					deactivate_plugins( $plugin['file_path'] );
1872
				}
1873
			}
1874
		}
1875
1876
		/**
1877
		 * Echo the current TGMPA version number to the page.
1878
		 */
1879
		public function show_tgmpa_version() {
1880
			echo '<p style="float: right; padding: 0em 1.5em 0.5em 0;"><strong><small>',
1881
				esc_html( sprintf( _x( 'TGMPA v%s', '%s = version number', 'tgmpa' ), self::TGMPA_VERSION ) ),
1882
				'</small></strong></p>';
1883
		}
1884
1885
		/**
1886
		 * Returns the singleton instance of the class.
1887
		 *
1888
		 * @since 2.4.0
1889
		 *
1890
		 * @return object The TGM_Plugin_Activation object.
1891
		 */
1892
		public static function get_instance() {
1893
			if ( ! isset( self::$instance ) && ! ( self::$instance instanceof self ) ) {
1894
				self::$instance = new self();
1895
			}
1896
1897
			return self::$instance;
1898
		}
1899
	}
1900
1901
	if ( ! function_exists( 'load_tgm_plugin_activation' ) ) {
1902
		/**
1903
		 * Ensure only one instance of the class is ever invoked.
1904
		 */
1905
		function load_tgm_plugin_activation() {
0 ignored issues
show
Coding Style introduced by
load_tgm_plugin_activation uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1906
			$GLOBALS['tgmpa'] = TGM_Plugin_Activation::get_instance();
1907
		}
1908
	}
1909
1910
	if ( did_action( 'plugins_loaded' ) ) {
1911
		load_tgm_plugin_activation();
1912
	} else {
1913
		add_action( 'plugins_loaded', 'load_tgm_plugin_activation' );
1914
	}
1915
}
1916
1917
if ( ! function_exists( 'tgmpa' ) ) {
1918
	/**
1919
	 * Helper function to register a collection of required plugins.
1920
	 *
1921
	 * @since 2.0.0
1922
	 * @api
1923
	 *
1924
	 * @param array $plugins An array of plugin arrays.
1925
	 * @param array $config  Optional. An array of configuration values.
1926
	 */
1927
	function tgmpa( $plugins, $config = array() ) {
0 ignored issues
show
Coding Style introduced by
tgmpa uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1928
		$instance = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
1929
1930
		foreach ( $plugins as $plugin ) {
1931
			call_user_func( array( $instance, 'register' ), $plugin );
1932
		}
1933
1934
		if ( ! empty( $config ) && is_array( $config ) ) {
1935
			// Send out notices for deprecated arguments passed.
1936
			if ( isset( $config['notices'] ) ) {
1937
				_deprecated_argument( __FUNCTION__, '2.2.0', 'The `notices` config parameter was renamed to `has_notices` in TGMPA 2.2.0. Please adjust your configuration.' );
1938
				if ( ! isset( $config['has_notices'] ) ) {
1939
					$config['has_notices'] = $config['notices'];
1940
				}
1941
			}
1942
1943
			if ( isset( $config['parent_menu_slug'] ) ) {
1944
				_deprecated_argument( __FUNCTION__, '2.4.0', 'The `parent_menu_slug` config parameter was removed in TGMPA 2.4.0. In TGMPA 2.5.0 an alternative was (re-)introduced. Please adjust your configuration. For more information visit the website: http://tgmpluginactivation.com/configuration/#h-configuration-options.' );
1945
			}
1946
			if ( isset( $config['parent_url_slug'] ) ) {
1947
				_deprecated_argument( __FUNCTION__, '2.4.0', 'The `parent_url_slug` config parameter was removed in TGMPA 2.4.0. In TGMPA 2.5.0 an alternative was (re-)introduced. Please adjust your configuration. For more information visit the website: http://tgmpluginactivation.com/configuration/#h-configuration-options.' );
1948
			}
1949
1950
			call_user_func( array( $instance, 'config' ), $config );
1951
		}
1952
	}
1953
}
1954
1955
/**
1956
 * WP_List_Table isn't always available. If it isn't available,
1957
 * we load it here.
1958
 *
1959
 * @since 2.2.0
1960
 */
1961
if ( ! class_exists( 'WP_List_Table' ) ) {
1962
	require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
1963
}
1964
1965
if ( ! class_exists( 'TGMPA_List_Table' ) ) {
1966
1967
	/**
1968
	 * List table class for handling plugins.
1969
	 *
1970
	 * Extends the WP_List_Table class to provide a future-compatible
1971
	 * way of listing out all required/recommended plugins.
1972
	 *
1973
	 * Gives users an interface similar to the Plugin Administration
1974
	 * area with similar (albeit stripped down) capabilities.
1975
	 *
1976
	 * This class also allows for the bulk install of plugins.
1977
	 *
1978
	 * @since 2.2.0
1979
	 *
1980
	 * @package TGM-Plugin-Activation
1981
	 * @author  Thomas Griffin
1982
	 * @author  Gary Jones
1983
	 */
1984
	class TGMPA_List_Table extends WP_List_Table {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
1985
		/**
1986
		 * TGMPA instance.
1987
		 *
1988
		 * @since 2.5.0
1989
		 *
1990
		 * @var object
1991
		 */
1992
		protected $tgmpa;
1993
1994
		/**
1995
		 * The currently chosen view.
1996
		 *
1997
		 * @since 2.5.0
1998
		 *
1999
		 * @var string One of: 'all', 'install', 'update', 'activate'
2000
		 */
2001
		public $view_context = 'all';
2002
2003
		/**
2004
		 * The plugin counts for the various views.
2005
		 *
2006
		 * @since 2.5.0
2007
		 *
2008
		 * @var array
2009
		 */
2010
		protected $view_totals = array(
2011
			'all'      => 0,
2012
			'install'  => 0,
2013
			'update'   => 0,
2014
			'activate' => 0,
2015
		);
2016
2017
		/**
2018
		 * References parent constructor and sets defaults for class.
2019
		 *
2020
		 * @since 2.2.0
2021
		 */
2022
		public function __construct() {
0 ignored issues
show
Coding Style introduced by
__construct uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
__construct uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
2023
			$this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
2024
2025
			parent::__construct(
2026
				array(
2027
					'singular' => 'plugin',
2028
					'plural'   => 'plugins',
2029
					'ajax'     => false,
2030
				)
2031
			);
2032
2033
			if ( isset( $_REQUEST['plugin_status'] ) && in_array( $_REQUEST['plugin_status'], array( 'install', 'update', 'activate' ), true ) ) {
2034
				$this->view_context = sanitize_key( $_REQUEST['plugin_status'] );
2035
			}
2036
2037
			add_filter( 'tgmpa_table_data_items', array( $this, 'sort_table_items' ) );
2038
		}
2039
2040
		/**
2041
		 * Get a list of CSS classes for the <table> tag.
2042
		 *
2043
		 * Overruled to prevent the 'plural' argument from being added.
2044
		 *
2045
		 * @since 2.5.0
2046
		 *
2047
		 * @return array CSS classnames.
2048
		 */
2049
		public function get_table_classes() {
2050
			return array( 'widefat', 'fixed' );
2051
		}
2052
2053
		/**
2054
		 * Gathers and renames all of our plugin information to be used by WP_List_Table to create our table.
2055
		 *
2056
		 * @since 2.2.0
2057
		 *
2058
		 * @return array $table_data Information for use in table.
2059
		 */
2060
		protected function _gather_plugin_data() {
2061
			// Load thickbox for plugin links.
2062
			$this->tgmpa->admin_init();
2063
			$this->tgmpa->thickbox();
2064
2065
			// Categorize the plugins which have open actions.
2066
			$plugins = $this->categorize_plugins_to_views();
2067
2068
			// Set the counts for the view links.
2069
			$this->set_view_totals( $plugins );
2070
2071
			// Prep variables for use and grab list of all installed plugins.
2072
			$table_data = array();
2073
			$i          = 0;
2074
2075
			// Redirect to the 'all' view if no plugins were found for the selected view context.
2076
			if ( empty( $plugins[ $this->view_context ] ) ) {
2077
				$this->view_context = 'all';
2078
			}
2079
2080
			foreach ( $plugins[ $this->view_context ] as $slug => $plugin ) {
2081
				$table_data[ $i ]['sanitized_plugin']  = $plugin['name'];
2082
				$table_data[ $i ]['slug']              = $slug;
2083
				$table_data[ $i ]['plugin']            = '<strong>' . $this->tgmpa->get_info_link( $slug ) . '</strong>';
2084
				$table_data[ $i ]['source']            = $this->get_plugin_source_type_text( $plugin['source_type'] );
2085
				$table_data[ $i ]['type']              = $this->get_plugin_advise_type_text( $plugin['required'] );
2086
				$table_data[ $i ]['status']            = $this->get_plugin_status_text( $slug );
2087
				$table_data[ $i ]['installed_version'] = $this->tgmpa->get_installed_version( $slug );
2088
				$table_data[ $i ]['minimum_version']   = $plugin['version'];
2089
				$table_data[ $i ]['available_version'] = $this->tgmpa->does_plugin_have_update( $slug );
2090
2091
				// Prep the upgrade notice info.
2092
				$upgrade_notice = $this->tgmpa->get_upgrade_notice( $slug );
2093
				if ( ! empty( $upgrade_notice ) ) {
2094
					$table_data[ $i ]['upgrade_notice'] = $upgrade_notice;
2095
2096
					add_action( "tgmpa_after_plugin_row_$slug", array( $this, 'wp_plugin_update_row' ), 10, 2 );
2097
				}
2098
2099
				$table_data[ $i ] = apply_filters( 'tgmpa_table_data_item', $table_data[ $i ], $plugin );
2100
2101
				$i++;
2102
			}
2103
2104
			return $table_data;
2105
		}
2106
2107
		/**
2108
		 * Categorize the plugins which have open actions into views for the TGMPA page.
2109
		 *
2110
		 * @since 2.5.0
2111
		 */
2112
		protected function categorize_plugins_to_views() {
2113
			$plugins = array(
2114
				'all'      => array(), // Meaning: all plugins which still have open actions.
2115
				'install'  => array(),
2116
				'update'   => array(),
2117
				'activate' => array(),
2118
			);
2119
2120
			foreach ( $this->tgmpa->plugins as $slug => $plugin ) {
2121
				if ( $this->tgmpa->is_plugin_active( $slug ) && false === $this->tgmpa->does_plugin_have_update( $slug ) ) {
2122
					// No need to display plugins if they are installed, up-to-date and active.
2123
					continue;
2124
				} else {
2125
					$plugins['all'][ $slug ] = $plugin;
2126
2127
					if ( ! $this->tgmpa->is_plugin_installed( $slug ) ) {
2128
						$plugins['install'][ $slug ] = $plugin;
2129
					} else {
2130
						if ( false !== $this->tgmpa->does_plugin_have_update( $slug ) ) {
2131
							$plugins['update'][ $slug ] = $plugin;
2132
						}
2133
2134
						if ( $this->tgmpa->can_plugin_activate( $slug ) ) {
2135
							$plugins['activate'][ $slug ] = $plugin;
2136
						}
2137
					}
2138
				}
2139
			}
2140
2141
			return $plugins;
2142
		}
2143
2144
		/**
2145
		 * Set the counts for the view links.
2146
		 *
2147
		 * @since 2.5.0
2148
		 *
2149
		 * @param array $plugins Plugins order by view.
2150
		 */
2151
		protected function set_view_totals( $plugins ) {
2152
			foreach ( $plugins as $type => $list ) {
2153
				$this->view_totals[ $type ] = count( $list );
2154
			}
2155
		}
2156
2157
		/**
2158
		 * Get the plugin required/recommended text string.
2159
		 *
2160
		 * @since 2.5.0
2161
		 *
2162
		 * @param string $required Plugin required setting.
2163
		 * @return string
2164
		 */
2165
		protected function get_plugin_advise_type_text( $required ) {
2166
			if ( true === $required ) {
2167
				return __( 'Required', 'tgmpa' );
2168
			}
2169
2170
			return __( 'Recommended', 'tgmpa' );
2171
		}
2172
2173
		/**
2174
		 * Get the plugin source type text string.
2175
		 *
2176
		 * @since 2.5.0
2177
		 *
2178
		 * @param string $type Plugin type.
2179
		 * @return string
2180
		 */
2181
		protected function get_plugin_source_type_text( $type ) {
2182
			$string = '';
2183
2184
			switch ( $type ) {
2185
				case 'repo':
2186
					$string = __( 'WordPress Repository', 'tgmpa' );
2187
					break;
2188
				case 'external':
2189
					$string = __( 'External Source', 'tgmpa' );
2190
					break;
2191
				case 'bundled':
2192
					$string = __( 'Pre-Packaged', 'tgmpa' );
2193
					break;
2194
			}
2195
2196
			return $string;
2197
		}
2198
2199
		/**
2200
		 * Determine the plugin status message.
2201
		 *
2202
		 * @since 2.5.0
2203
		 *
2204
		 * @param string $slug Plugin slug.
2205
		 * @return string
2206
		 */
2207
		protected function get_plugin_status_text( $slug ) {
2208
			if ( ! $this->tgmpa->is_plugin_installed( $slug ) ) {
2209
				return __( 'Not Installed', 'tgmpa' );
2210
			}
2211
2212
			if ( ! $this->tgmpa->is_plugin_active( $slug ) ) {
2213
				$install_status = __( 'Installed But Not Activated', 'tgmpa' );
2214
			} else {
2215
				$install_status = __( 'Active', 'tgmpa' );
2216
			}
2217
2218
			$update_status = '';
2219
2220
			if ( $this->tgmpa->does_plugin_require_update( $slug ) && false === $this->tgmpa->does_plugin_have_update( $slug ) ) {
2221
				$update_status = __( 'Required Update not Available', 'tgmpa' );
2222
2223
			} elseif ( $this->tgmpa->does_plugin_require_update( $slug ) ) {
2224
				$update_status = __( 'Requires Update', 'tgmpa' );
2225
2226
			} elseif ( false !== $this->tgmpa->does_plugin_have_update( $slug ) ) {
2227
				$update_status = __( 'Update recommended', 'tgmpa' );
2228
			}
2229
2230
			if ( '' === $update_status ) {
2231
				return $install_status;
2232
			}
2233
2234
			return sprintf(
2235
				_x( '%1$s, %2$s', '%1$s = install status, %2$s = update status', 'tgmpa' ),
2236
				$install_status,
2237
				$update_status
2238
			);
2239
		}
2240
2241
		/**
2242
		 * Sort plugins by Required/Recommended type and by alphabetical plugin name within each type.
2243
		 *
2244
		 * @since 2.5.0
2245
		 *
2246
		 * @param array $items Prepared table items.
2247
		 * @return array Sorted table items.
2248
		 */
2249
		public function sort_table_items( $items ) {
2250
			$type = array();
2251
			$name = array();
2252
2253
			foreach ( $items as $i => $plugin ) {
2254
				$type[ $i ] = $plugin['type']; // Required / recommended.
2255
				$name[ $i ] = $plugin['sanitized_plugin'];
2256
			}
2257
2258
			array_multisort( $type, SORT_DESC, $name, SORT_ASC, $items );
2259
2260
			return $items;
2261
		}
2262
2263
		/**
2264
		 * Get an associative array ( id => link ) of the views available on this table.
2265
		 *
2266
		 * @since 2.5.0
2267
		 *
2268
		 * @return array
2269
		 */
2270
		public function get_views() {
2271
			$status_links = array();
2272
2273
			foreach ( $this->view_totals as $type => $count ) {
2274
				if ( $count < 1 ) {
2275
					continue;
2276
				}
2277
2278
				switch ( $type ) {
2279
					case 'all':
2280
						$text = _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $count, 'plugins', 'tgmpa' );
2281
						break;
2282
					case 'install':
2283
						$text = _n( 'To Install <span class="count">(%s)</span>', 'To Install <span class="count">(%s)</span>', $count, 'tgmpa' );
2284
						break;
2285
					case 'update':
2286
						$text = _n( 'Update Available <span class="count">(%s)</span>', 'Update Available <span class="count">(%s)</span>', $count, 'tgmpa' );
2287
						break;
2288
					case 'activate':
2289
						$text = _n( 'To Activate <span class="count">(%s)</span>', 'To Activate <span class="count">(%s)</span>', $count, 'tgmpa' );
2290
						break;
2291
					default:
2292
						$text = '';
2293
						break;
2294
				}
2295
2296
				if ( ! empty( $text ) ) {
2297
2298
					$status_links[ $type ] = sprintf(
2299
						'<a href="%s"%s>%s</a>',
2300
						esc_url( $this->tgmpa->get_tgmpa_status_url( $type ) ),
2301
						( $type === $this->view_context ) ? ' class="current"' : '',
2302
						sprintf( $text, number_format_i18n( $count ) )
2303
					);
2304
				}
2305
			}
2306
2307
			return $status_links;
2308
		}
2309
2310
		/**
2311
		 * Create default columns to display important plugin information
2312
		 * like type, action and status.
2313
		 *
2314
		 * @since 2.2.0
2315
		 *
2316
		 * @param array  $item        Array of item data.
2317
		 * @param string $column_name The name of the column.
2318
		 * @return string
2319
		 */
2320
		public function column_default( $item, $column_name ) {
2321
			return $item[ $column_name ];
2322
		}
2323
2324
		/**
2325
		 * Required for bulk installing.
2326
		 *
2327
		 * Adds a checkbox for each plugin.
2328
		 *
2329
		 * @since 2.2.0
2330
		 *
2331
		 * @param array $item Array of item data.
2332
		 * @return string The input checkbox with all necessary info.
2333
		 */
2334
		public function column_cb( $item ) {
2335
			return sprintf(
2336
				'<input type="checkbox" name="%1$s[]" value="%2$s" id="%3$s" />',
2337
				esc_attr( $this->_args['singular'] ),
2338
				esc_attr( $item['slug'] ),
2339
				esc_attr( $item['sanitized_plugin'] )
2340
			);
2341
		}
2342
2343
		/**
2344
		 * Create default title column along with the action links.
2345
		 *
2346
		 * @since 2.2.0
2347
		 *
2348
		 * @param array $item Array of item data.
2349
		 * @return string The plugin name and action links.
2350
		 */
2351
		public function column_plugin( $item ) {
2352
			return sprintf(
2353
				'%1$s %2$s',
2354
				$item['plugin'],
2355
				$this->row_actions( $this->get_row_actions( $item ), true )
2356
			);
2357
		}
2358
2359
		/**
2360
		 * Create version information column.
2361
		 *
2362
		 * @since 2.5.0
2363
		 *
2364
		 * @param array $item Array of item data.
2365
		 * @return string HTML-formatted version information.
2366
		 */
2367
		public function column_version( $item ) {
2368
			$output = array();
2369
2370
			if ( $this->tgmpa->is_plugin_installed( $item['slug'] ) ) {
2371
				$installed = ! empty( $item['installed_version'] ) ? $item['installed_version'] : _x( 'unknown', 'as in: "version nr unknown"', 'tgmpa' );
2372
2373
				$color = '';
2374
				if ( ! empty( $item['minimum_version'] ) && $this->tgmpa->does_plugin_require_update( $item['slug'] ) ) {
2375
					$color = ' color: #ff0000; font-weight: bold;';
2376
				}
2377
2378
				$output[] = sprintf(
2379
					'<p><span style="min-width: 32px; text-align: right; float: right;%1$s">%2$s</span>' . __( 'Installed version:', 'tgmpa' ) . '</p>',
2380
					$color,
2381
					$installed
2382
				);
2383
			}
2384
2385
			if ( ! empty( $item['minimum_version'] ) ) {
2386
				$output[] = sprintf(
2387
					'<p><span style="min-width: 32px; text-align: right; float: right;">%1$s</span>' . __( 'Minimum required version:', 'tgmpa' ) . '</p>',
2388
					$item['minimum_version']
2389
				);
2390
			}
2391
2392
			if ( ! empty( $item['available_version'] ) ) {
2393
				$color = '';
2394
				if ( ! empty( $item['minimum_version'] ) && version_compare( $item['available_version'], $item['minimum_version'], '>=' ) ) {
2395
					$color = ' color: #71C671; font-weight: bold;';
2396
				}
2397
2398
				$output[] = sprintf(
2399
					'<p><span style="min-width: 32px; text-align: right; float: right;%1$s">%2$s</span>' . __( 'Available version:', 'tgmpa' ) . '</p>',
2400
					$color,
2401
					$item['available_version']
2402
				);
2403
			}
2404
2405
			if ( empty( $output ) ) {
2406
				return '&nbsp;'; // Let's not break the table layout.
2407
			} else {
2408
				return implode( "\n", $output );
2409
			}
2410
		}
2411
2412
		/**
2413
		 * Sets default message within the plugins table if no plugins
2414
		 * are left for interaction.
2415
		 *
2416
		 * Hides the menu item to prevent the user from clicking and
2417
		 * getting a permissions error.
2418
		 *
2419
		 * @since 2.2.0
2420
		 */
2421
		public function no_items() {
2422
			printf( wp_kses_post( __( 'No plugins to install, update or activate. <a href="%1$s">Return to the Dashboard</a>', 'tgmpa' ) ), esc_url( self_admin_url() ) );
2423
			echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>';
2424
		}
2425
2426
		/**
2427
		 * Output all the column information within the table.
2428
		 *
2429
		 * @since 2.2.0
2430
		 *
2431
		 * @return array $columns The column names.
2432
		 */
2433
		public function get_columns() {
2434
			$columns = array(
2435
				'cb'     => '<input type="checkbox" />',
2436
				'plugin' => __( 'Plugin', 'tgmpa' ),
2437
				'source' => __( 'Source', 'tgmpa' ),
2438
				'type'   => __( 'Type', 'tgmpa' ),
2439
			);
2440
2441
			if ( 'all' === $this->view_context || 'update' === $this->view_context ) {
2442
				$columns['version'] = __( 'Version', 'tgmpa' );
2443
				$columns['status']  = __( 'Status', 'tgmpa' );
2444
			}
2445
2446
			return apply_filters( 'tgmpa_table_columns', $columns );
2447
		}
2448
2449
		/**
2450
		 * Get name of default primary column
2451
		 *
2452
		 * @since 2.5.0 / WP 4.3+ compatibility
2453
		 * @access protected
2454
		 *
2455
		 * @return string
2456
		 */
2457
		protected function get_default_primary_column_name() {
2458
			return 'plugin';
2459
		}
2460
2461
		/**
2462
		 * Get the name of the primary column.
2463
		 *
2464
		 * @since 2.5.0 / WP 4.3+ compatibility
2465
		 * @access protected
2466
		 *
2467
		 * @return string The name of the primary column.
2468
		 */
2469
		protected function get_primary_column_name() {
2470
			if ( method_exists( 'WP_List_Table', 'get_primary_column_name' ) ) {
2471
				return parent::get_primary_column_name();
2472
			} else {
2473
				return $this->get_default_primary_column_name();
2474
			}
2475
		}
2476
2477
		/**
2478
		 * Get the actions which are relevant for a specific plugin row.
2479
		 *
2480
		 * @since 2.5.0
2481
		 *
2482
		 * @param array $item Array of item data.
2483
		 * @return array Array with relevant action links.
2484
		 */
2485
		protected function get_row_actions( $item ) {
2486
			$actions      = array();
2487
			$action_links = array();
2488
2489
			// Display the 'Install' action link if the plugin is not yet available.
2490
			if ( ! $this->tgmpa->is_plugin_installed( $item['slug'] ) ) {
2491
				$actions['install'] = _x( 'Install %2$s', '%2$s = plugin name in screen reader markup', 'tgmpa' );
2492
			} else {
2493
				// Display the 'Update' action link if an update is available and WP complies with plugin minimum.
2494
				if ( false !== $this->tgmpa->does_plugin_have_update( $item['slug'] ) && $this->tgmpa->can_plugin_update( $item['slug'] ) ) {
2495
					$actions['update'] = _x( 'Update %2$s', '%2$s = plugin name in screen reader markup', 'tgmpa' );
2496
				}
2497
2498
				// Display the 'Activate' action link, but only if the plugin meets the minimum version.
2499
				if ( $this->tgmpa->can_plugin_activate( $item['slug'] ) ) {
2500
					$actions['activate'] = _x( 'Activate %2$s', '%2$s = plugin name in screen reader markup', 'tgmpa' );
2501
				}
2502
			}
2503
2504
			// Create the actual links.
2505
			foreach ( $actions as $action => $text ) {
2506
				$nonce_url = wp_nonce_url(
2507
					add_query_arg(
2508
						array(
2509
							'plugin'           => urlencode( $item['slug'] ),
2510
							'tgmpa-' . $action => $action . '-plugin',
2511
						),
2512
						$this->tgmpa->get_tgmpa_url()
2513
					),
2514
					'tgmpa-' . $action,
2515
					'tgmpa-nonce'
2516
				);
2517
2518
				$action_links[ $action ] = sprintf(
2519
					'<a href="%1$s">' . esc_html( $text ) . '</a>',
2520
					esc_url( $nonce_url ),
2521
					'<span class="screen-reader-text">' . esc_html( $item['sanitized_plugin'] ) . '</span>'
2522
				);
2523
			}
2524
2525
			$prefix = ( defined( 'WP_NETWORK_ADMIN' ) && WP_NETWORK_ADMIN ) ? 'network_admin_' : '';
2526
			return apply_filters( "tgmpa_{$prefix}plugin_action_links", array_filter( $action_links ), $item['slug'], $item, $this->view_context );
2527
		}
2528
2529
		/**
2530
		 * Generates content for a single row of the table.
2531
		 *
2532
		 * @since 2.5.0
2533
		 *
2534
		 * @param object $item The current item.
2535
		 */
2536
		public function single_row( $item ) {
2537
			parent::single_row( $item );
2538
2539
			/**
2540
			 * Fires after each specific row in the TGMPA Plugins list table.
2541
			 *
2542
			 * The dynamic portion of the hook name, `$item['slug']`, refers to the slug
2543
			 * for the plugin.
2544
			 *
2545
			 * @since 2.5.0
2546
			 */
2547
			do_action( "tgmpa_after_plugin_row_{$item['slug']}", $item['slug'], $item, $this->view_context );
2548
		}
2549
2550
		/**
2551
		 * Show the upgrade notice below a plugin row if there is one.
2552
		 *
2553
		 * @since 2.5.0
2554
		 *
2555
		 * @see /wp-admin/includes/update.php
2556
		 *
2557
		 * @param string $slug Plugin slug.
2558
		 * @param array  $item The information available in this table row.
2559
		 * @return null Return early if upgrade notice is empty.
2560
		 */
2561
		public function wp_plugin_update_row( $slug, $item ) {
2562
			if ( empty( $item['upgrade_notice'] ) ) {
2563
				return;
2564
			}
2565
2566
			echo '
2567
				<tr class="plugin-update-tr">
2568
					<td colspan="', absint( $this->get_column_count() ), '" class="plugin-update colspanchange">
2569
						<div class="update-message">',
2570
							esc_html__( 'Upgrade message from the plugin author:', 'tgmpa' ),
2571
							' <strong>', wp_kses_data( $item['upgrade_notice'] ), '</strong>
2572
						</div>
2573
					</td>
2574
				</tr>';
2575
		}
2576
2577
		/**
2578
		 * Extra controls to be displayed between bulk actions and pagination.
2579
		 *
2580
		 * @since 2.5.0
2581
		 *
2582
		 * @param string $which 'top' or 'bottom' table navigation.
2583
		 */
2584
		public function extra_tablenav( $which ) {
2585
			if ( 'bottom' === $which ) {
2586
				$this->tgmpa->show_tgmpa_version();
2587
			}
2588
		}
2589
2590
		/**
2591
		 * Defines the bulk actions for handling registered plugins.
2592
		 *
2593
		 * @since 2.2.0
2594
		 *
2595
		 * @return array $actions The bulk actions for the plugin install table.
2596
		 */
2597
		public function get_bulk_actions() {
2598
2599
			$actions = array();
2600
2601
			if ( 'update' !== $this->view_context && 'activate' !== $this->view_context ) {
2602
				if ( current_user_can( 'install_plugins' ) ) {
2603
					$actions['tgmpa-bulk-install'] = __( 'Install', 'tgmpa' );
2604
				}
2605
			}
2606
2607
			if ( 'install' !== $this->view_context ) {
2608
				if ( current_user_can( 'update_plugins' ) ) {
2609
					$actions['tgmpa-bulk-update'] = __( 'Update', 'tgmpa' );
2610
				}
2611
				if ( current_user_can( 'activate_plugins' ) ) {
2612
					$actions['tgmpa-bulk-activate'] = __( 'Activate', 'tgmpa' );
2613
				}
2614
			}
2615
2616
			return $actions;
2617
		}
2618
2619
		/**
2620
		 * Processes bulk installation and activation actions.
2621
		 *
2622
		 * The bulk installation process looks for the $_POST information and passes that
2623
		 * through if a user has to use WP_Filesystem to enter their credentials.
2624
		 *
2625
		 * @since 2.2.0
2626
		 */
2627
		public function process_bulk_actions() {
0 ignored issues
show
Coding Style introduced by
process_bulk_actions uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
2628
			// Bulk installation process.
2629
			if ( 'tgmpa-bulk-install' === $this->current_action() || 'tgmpa-bulk-update' === $this->current_action() ) {
2630
2631
				check_admin_referer( 'bulk-' . $this->_args['plural'] );
2632
2633
				$install_type = 'install';
2634
				if ( 'tgmpa-bulk-update' === $this->current_action() ) {
2635
					$install_type = 'update';
2636
				}
2637
2638
				$plugins_to_install = array();
2639
2640
				// Did user actually select any plugins to install/update ?
2641 View Code Duplication
				if ( empty( $_POST['plugin'] ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
2642
					if ( 'install' === $install_type ) {
2643
						$message = __( 'No plugins were selected to be installed. No action taken.', 'tgmpa' );
2644
					} else {
2645
						$message = __( 'No plugins were selected to be updated. No action taken.', 'tgmpa' );
2646
					}
2647
2648
					echo '<div id="message" class="error"><p>', esc_html( $message ), '</p></div>';
2649
2650
					return false;
2651
				}
2652
2653
				if ( is_array( $_POST['plugin'] ) ) {
2654
					$plugins_to_install = (array) $_POST['plugin'];
2655
				} elseif ( is_string( $_POST['plugin'] ) ) {
2656
					// Received via Filesystem page - un-flatten array (WP bug #19643).
2657
					$plugins_to_install = explode( ',', $_POST['plugin'] );
2658
				}
2659
2660
				// Sanitize the received input.
2661
				$plugins_to_install = array_map( 'urldecode', $plugins_to_install );
2662
				$plugins_to_install = array_map( array( $this->tgmpa, 'sanitize_key' ), $plugins_to_install );
2663
2664
				// Validate the received input.
2665
				foreach ( $plugins_to_install as $key => $slug ) {
2666
					// Check if the plugin was registered with TGMPA and remove if not.
2667
					if ( ! isset( $this->tgmpa->plugins[ $slug ] ) ) {
2668
						unset( $plugins_to_install[ $key ] );
2669
						continue;
2670
					}
2671
2672
					// For updates: make sure this is a plugin we *can* update (update available and WP version ok).
2673
					if ( 'update' === $install_type && ( $this->tgmpa->is_plugin_installed( $slug ) && ( false === $this->tgmpa->does_plugin_have_update( $slug ) || ! $this->tgmpa->can_plugin_update( $slug ) ) ) ) {
2674
						unset( $plugins_to_install[ $key ] );
2675
					}
2676
				}
2677
2678
				// No need to proceed further if we have no plugins to handle.
2679 View Code Duplication
				if ( empty( $plugins_to_install ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
2680
					if ( 'install' === $install_type ) {
2681
						$message = __( 'No plugins are available to be installed at this time.', 'tgmpa' );
2682
					} else {
2683
						$message = __( 'No plugins are available to be updated at this time.', 'tgmpa' );
2684
					}
2685
2686
					echo '<div id="message" class="error"><p>', esc_html( $message ), '</p></div>';
2687
2688
					return false;
2689
				}
2690
2691
				// Pass all necessary information if WP_Filesystem is needed.
2692
				$url = wp_nonce_url(
2693
					$this->tgmpa->get_tgmpa_url(),
2694
					'bulk-' . $this->_args['plural']
2695
				);
2696
2697
				// Give validated data back to $_POST which is the only place the filesystem looks for extra fields.
2698
				$_POST['plugin'] = implode( ',', $plugins_to_install ); // Work around for WP bug #19643.
2699
2700
				$method = ''; // Leave blank so WP_Filesystem can populate it as necessary.
2701
				$fields = array_keys( $_POST ); // Extra fields to pass to WP_Filesystem.
2702
2703 View Code Duplication
				if ( false === ( $creds = request_filesystem_credentials( esc_url_raw( $url ), $method, false, false, $fields ) ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
2704
					return true; // Stop the normal page form from displaying, credential request form will be shown.
2705
				}
2706
2707
				// Now we have some credentials, setup WP_Filesystem.
2708 View Code Duplication
				if ( ! WP_Filesystem( $creds ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
2709
					// Our credentials were no good, ask the user for them again.
2710
					request_filesystem_credentials( esc_url_raw( $url ), $method, true, false, $fields );
2711
2712
					return true;
2713
				}
2714
2715
				/* If we arrive here, we have the filesystem */
2716
2717
				// Store all information in arrays since we are processing a bulk installation.
2718
				$names      = array();
2719
				$sources    = array(); // Needed for installs.
2720
				$file_paths = array(); // Needed for upgrades.
2721
				$to_inject  = array(); // Information to inject into the update_plugins transient.
2722
2723
				// Prepare the data for validated plugins for the install/upgrade.
2724
				foreach ( $plugins_to_install as $slug ) {
2725
					$name   = $this->tgmpa->plugins[ $slug ]['name'];
2726
					$source = $this->tgmpa->get_download_url( $slug );
2727
2728
					if ( ! empty( $name ) && ! empty( $source ) ) {
2729
						$names[] = $name;
2730
2731
						switch ( $install_type ) {
2732
2733
							case 'install':
2734
								$sources[] = $source;
2735
								break;
2736
2737
							case 'update':
2738
								$file_paths[]                 = $this->tgmpa->plugins[ $slug ]['file_path'];
2739
								$to_inject[ $slug ]           = $this->tgmpa->plugins[ $slug ];
2740
								$to_inject[ $slug ]['source'] = $source;
2741
								break;
2742
						}
2743
					}
2744
				}
2745
				unset( $slug, $name, $source );
2746
2747
				// Create a new instance of TGMPA_Bulk_Installer.
2748
				$installer = new TGMPA_Bulk_Installer(
2749
					new TGMPA_Bulk_Installer_Skin(
2750
						array(
2751
							'url'          => esc_url_raw( $this->tgmpa->get_tgmpa_url() ),
2752
							'nonce'        => 'bulk-' . $this->_args['plural'],
2753
							'names'        => $names,
2754
							'install_type' => $install_type,
2755
						)
2756
					)
2757
				);
2758
2759
				// Wrap the install process with the appropriate HTML.
2760
				echo '<div class="tgmpa wrap">',
2761
					'<h2>', esc_html( get_admin_page_title() ), '</h2>';
2762
2763
				// Process the bulk installation submissions.
2764
				add_filter( 'upgrader_source_selection', array( $this->tgmpa, 'maybe_adjust_source_dir' ), 1, 3 );
2765
2766
				if ( 'tgmpa-bulk-update' === $this->current_action() ) {
2767
					// Inject our info into the update transient.
2768
					$this->tgmpa->inject_update_info( $to_inject );
2769
2770
					$installer->bulk_upgrade( $file_paths );
2771
				} else {
2772
					$installer->bulk_install( $sources );
2773
				}
2774
2775
				remove_filter( 'upgrader_source_selection', array( $this->tgmpa, 'maybe_adjust_source_dir' ), 1, 3 );
2776
2777
				echo '</div>';
2778
2779
				return true;
2780
			}
2781
2782
			// Bulk activation process.
2783
			if ( 'tgmpa-bulk-activate' === $this->current_action() ) {
2784
				check_admin_referer( 'bulk-' . $this->_args['plural'] );
2785
2786
				// Did user actually select any plugins to activate ?
2787
				if ( empty( $_POST['plugin'] ) ) {
2788
					echo '<div id="message" class="error"><p>', esc_html__( 'No plugins were selected to be activated. No action taken.', 'tgmpa' ), '</p></div>';
2789
2790
					return false;
2791
				}
2792
2793
				// Grab plugin data from $_POST.
2794
				$plugins = array();
2795
				if ( isset( $_POST['plugin'] ) ) {
2796
					$plugins = array_map( 'urldecode', (array) $_POST['plugin'] );
2797
					$plugins = array_map( array( $this->tgmpa, 'sanitize_key' ), $plugins );
2798
				}
2799
2800
				$plugins_to_activate = array();
2801
				$plugin_names        = array();
2802
2803
				// Grab the file paths for the selected & inactive plugins from the registration array.
2804
				foreach ( $plugins as $slug ) {
2805
					if ( $this->tgmpa->can_plugin_activate( $slug ) ) {
2806
						$plugins_to_activate[] = $this->tgmpa->plugins[ $slug ]['file_path'];
2807
						$plugin_names[]        = $this->tgmpa->plugins[ $slug ]['name'];
2808
					}
2809
				}
2810
				unset( $slug );
2811
2812
				// Return early if there are no plugins to activate.
2813
				if ( empty( $plugins_to_activate ) ) {
2814
					echo '<div id="message" class="error"><p>', esc_html__( 'No plugins are available to be activated at this time.', 'tgmpa' ), '</p></div>';
2815
2816
					return false;
2817
				}
2818
2819
				// Now we are good to go - let's start activating plugins.
2820
				$activate = activate_plugins( $plugins_to_activate );
2821
2822
				if ( is_wp_error( $activate ) ) {
2823
					echo '<div id="message" class="error"><p>', wp_kses_post( $activate->get_error_message() ), '</p></div>';
2824
				} else {
2825
					$count        = count( $plugin_names ); // Count so we can use _n function.
2826
					$plugin_names = array_map( array( 'TGMPA_Utils', 'wrap_in_strong' ), $plugin_names );
2827
					$last_plugin  = array_pop( $plugin_names ); // Pop off last name to prep for readability.
2828
					$imploded     = empty( $plugin_names ) ? $last_plugin : ( implode( ', ', $plugin_names ) . ' ' . esc_html_x( 'and', 'plugin A *and* plugin B', 'tgmpa' ) . ' ' . $last_plugin );
2829
2830
					printf( // WPCS: xss ok.
2831
						'<div id="message" class="updated"><p>%1$s %2$s.</p></div>',
2832
						esc_html( _n( 'The following plugin was activated successfully:', 'The following plugins were activated successfully:', $count, 'tgmpa' ) ),
2833
						$imploded
2834
					);
2835
2836
					// Update recently activated plugins option.
2837
					$recent = (array) get_option( 'recently_activated' );
2838
					foreach ( $plugins_to_activate as $plugin => $time ) {
2839
						if ( isset( $recent[ $plugin ] ) ) {
2840
							unset( $recent[ $plugin ] );
2841
						}
2842
					}
2843
					update_option( 'recently_activated', $recent );
2844
				}
2845
2846
				unset( $_POST ); // Reset the $_POST variable in case user wants to perform one action after another.
2847
2848
				return true;
2849
			}
2850
2851
			return false;
2852
		}
2853
2854
		/**
2855
		 * Prepares all of our information to be outputted into a usable table.
2856
		 *
2857
		 * @since 2.2.0
2858
		 */
2859
		public function prepare_items() {
2860
			$columns               = $this->get_columns(); // Get all necessary column information.
2861
			$hidden                = array(); // No columns to hide, but we must set as an array.
2862
			$sortable              = array(); // No reason to make sortable columns.
2863
			$primary               = $this->get_primary_column_name(); // Column which has the row actions.
2864
			$this->_column_headers = array( $columns, $hidden, $sortable, $primary ); // Get all necessary column headers.
2865
2866
			// Process our bulk activations here.
2867
			if ( 'tgmpa-bulk-activate' === $this->current_action() ) {
2868
				$this->process_bulk_actions();
2869
			}
2870
2871
			// Store all of our plugin data into $items array so WP_List_Table can use it.
2872
			$this->items = apply_filters( 'tgmpa_table_data_items', $this->_gather_plugin_data() );
2873
		}
2874
2875
		/* *********** DEPRECATED METHODS *********** */
2876
2877
		/**
2878
		 * Retrieve plugin data, given the plugin name.
2879
		 *
2880
		 * @since      2.2.0
2881
		 * @deprecated 2.5.0 use {@see TGM_Plugin_Activation::_get_plugin_data_from_name()} instead.
2882
		 * @see        TGM_Plugin_Activation::_get_plugin_data_from_name()
2883
		 *
2884
		 * @param string $name Name of the plugin, as it was registered.
2885
		 * @param string $data Optional. Array key of plugin data to return. Default is slug.
2886
		 * @return string|boolean Plugin slug if found, false otherwise.
2887
		 */
2888
		protected function _get_plugin_data_from_name( $name, $data = 'slug' ) {
2889
			_deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'TGM_Plugin_Activation::_get_plugin_data_from_name()' );
2890
2891
			return $this->tgmpa->_get_plugin_data_from_name( $name, $data );
2892
		}
2893
	}
2894
}
2895
2896
2897
if ( ! class_exists( 'TGM_Bulk_Installer' ) ) {
2898
2899
	/**
2900
	 * Hack: Prevent TGMPA v2.4.1- bulk installer class from being loaded if 2.4.1- is loaded after 2.5+.
2901
	 */
2902
	class TGM_Bulk_Installer {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
2903
	}
2904
}
2905
if ( ! class_exists( 'TGM_Bulk_Installer_Skin' ) ) {
2906
2907
	/**
2908
	 * Hack: Prevent TGMPA v2.4.1- bulk installer skin class from being loaded if 2.4.1- is loaded after 2.5+.
2909
	 */
2910
	class TGM_Bulk_Installer_Skin {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
2911
	}
2912
}
2913
2914
/**
2915
 * The WP_Upgrader file isn't always available. If it isn't available,
2916
 * we load it here.
2917
 *
2918
 * We check to make sure no action or activation keys are set so that WordPress
2919
 * does not try to re-include the class when processing upgrades or installs outside
2920
 * of the class.
2921
 *
2922
 * @since 2.2.0
2923
 */
2924
add_action( 'admin_init', 'tgmpa_load_bulk_installer' );
2925
if ( ! function_exists( 'tgmpa_load_bulk_installer' ) ) {
2926
	/**
2927
	 * Load bulk installer
2928
	 */
2929
	function tgmpa_load_bulk_installer() {
0 ignored issues
show
Coding Style introduced by
tgmpa_load_bulk_installer uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
tgmpa_load_bulk_installer uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
2930
		// Silently fail if 2.5+ is loaded *after* an older version.
2931
		if ( ! isset( $GLOBALS['tgmpa'] ) ) {
2932
			return;
2933
		}
2934
2935
		// Get TGMPA class instance.
2936
		$tgmpa_instance = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
2937
2938
		if ( isset( $_GET['page'] ) && $tgmpa_instance->menu === $_GET['page'] ) {
2939
			if ( ! class_exists( 'Plugin_Upgrader', false ) ) {
2940
				require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
2941
			}
2942
2943
			if ( ! class_exists( 'TGMPA_Bulk_Installer' ) ) {
2944
2945
				/**
2946
				 * Installer class to handle bulk plugin installations.
2947
				 *
2948
				 * Extends WP_Upgrader and customizes to suit the installation of multiple
2949
				 * plugins.
2950
				 *
2951
				 * @since 2.2.0
2952
				 *
2953
				 * @internal Since 2.5.0 the class is an extension of Plugin_Upgrader rather than WP_Upgrader
2954
				 * @internal Since 2.5.2 the class has been renamed from TGM_Bulk_Installer to TGMPA_Bulk_Installer.
2955
				 *           This was done to prevent backward compatibility issues with v2.3.6.
2956
				 *
2957
				 * @package TGM-Plugin-Activation
2958
				 * @author  Thomas Griffin
2959
				 * @author  Gary Jones
2960
				 */
2961
				class TGMPA_Bulk_Installer extends Plugin_Upgrader {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
2962
					/**
2963
					 * Holds result of bulk plugin installation.
2964
					 *
2965
					 * @since 2.2.0
2966
					 *
2967
					 * @var string
2968
					 */
2969
					public $result;
2970
2971
					/**
2972
					 * Flag to check if bulk installation is occurring or not.
2973
					 *
2974
					 * @since 2.2.0
2975
					 *
2976
					 * @var boolean
2977
					 */
2978
					public $bulk = false;
2979
2980
					/**
2981
					 * TGMPA instance
2982
					 *
2983
					 * @since 2.5.0
2984
					 *
2985
					 * @var object
2986
					 */
2987
					protected $tgmpa;
2988
2989
					/**
2990
					 * Whether or not the destination directory needs to be cleared ( = on update).
2991
					 *
2992
					 * @since 2.5.0
2993
					 *
2994
					 * @var bool
2995
					 */
2996
					protected $clear_destination = false;
2997
2998
					/**
2999
					 * References parent constructor and sets defaults for class.
3000
					 *
3001
					 * @since 2.2.0
3002
					 *
3003
					 * @param \Bulk_Upgrader_Skin|null $skin Installer skin.
3004
					 */
3005
					public function __construct( $skin = null ) {
0 ignored issues
show
Coding Style introduced by
__construct uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
3006
						// Get TGMPA class instance.
3007
						$this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
3008
3009
						parent::__construct( $skin );
3010
3011
						if ( isset( $this->skin->options['install_type'] ) && 'update' === $this->skin->options['install_type'] ) {
3012
							$this->clear_destination = true;
3013
						}
3014
3015
						if ( $this->tgmpa->is_automatic ) {
3016
							$this->activate_strings();
3017
						}
3018
3019
						add_action( 'upgrader_process_complete', array( $this->tgmpa, 'populate_file_path' ) );
3020
					}
3021
3022
					/**
3023
					 * Sets the correct activation strings for the installer skin to use.
3024
					 *
3025
					 * @since 2.2.0
3026
					 */
3027
					public function activate_strings() {
3028
						$this->strings['activation_failed']  = __( 'Plugin activation failed.', 'tgmpa' );
3029
						$this->strings['activation_success'] = __( 'Plugin activated successfully.', 'tgmpa' );
3030
					}
3031
3032
					/**
3033
					 * Performs the actual installation of each plugin.
3034
					 *
3035
					 * @since 2.2.0
3036
					 *
3037
					 * @see WP_Upgrader::run()
3038
					 *
3039
					 * @param array $options The installation config options.
3040
					 * @return null|array Return early if error, array of installation data on success.
3041
					 */
3042
					public function run( $options ) {
3043
						$result = parent::run( $options );
3044
3045
						// Reset the strings in case we changed one during automatic activation.
3046
						if ( $this->tgmpa->is_automatic ) {
3047
							if ( 'update' === $this->skin->options['install_type'] ) {
3048
								$this->upgrade_strings();
3049
							} else {
3050
								$this->install_strings();
3051
							}
3052
						}
3053
3054
						return $result;
3055
					}
3056
3057
					/**
3058
					 * Processes the bulk installation of plugins.
3059
					 *
3060
					 * @since 2.2.0
3061
					 *
3062
					 * @internal This is basically a near identical copy of the WP Core Plugin_Upgrader::bulk_upgrade()
3063
					 * method, with minor adjustments to deal with new installs instead of upgrades.
3064
					 * For ease of future synchronizations, the adjustments are clearly commented, but no other
3065
					 * comments are added. Code style has been made to comply.
3066
					 *
3067
					 * @see Plugin_Upgrader::bulk_upgrade()
3068
					 * @see https://core.trac.wordpress.org/browser/tags/4.2.1/src/wp-admin/includes/class-wp-upgrader.php#L838
3069
					 *
3070
					 * @param array $plugins The plugin sources needed for installation.
3071
					 * @param array $args    Arbitrary passed extra arguments.
3072
					 * @return string|bool Install confirmation messages on success, false on failure.
3073
					 */
3074
					public function bulk_install( $plugins, $args = array() ) {
3075
						// [TGMPA + ] Hook auto-activation in.
3076
						add_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3077
3078
						$defaults    = array(
3079
							'clear_update_cache' => true,
3080
						);
3081
						$parsed_args = wp_parse_args( $args, $defaults );
3082
3083
						$this->init();
3084
						$this->bulk = true;
3085
3086
						$this->install_strings(); // [TGMPA + ] adjusted.
3087
3088
						/* [TGMPA - ] $current = get_site_transient( 'update_plugins' ); */
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
3089
3090
						/* [TGMPA - ] add_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'), 10, 4); */
0 ignored issues
show
Unused Code Comprehensibility introduced by
61% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
3091
3092
						$this->skin->header();
3093
3094
						// Connect to the Filesystem first.
3095
						$res = $this->fs_connect( array( WP_CONTENT_DIR, WP_PLUGIN_DIR ) );
3096
						if ( ! $res ) {
3097
							$this->skin->footer();
3098
3099
							return false;
3100
						}
3101
3102
						$this->skin->bulk_header();
3103
3104
						// Only start maintenance mode if:
3105
						// - running Multisite and there are one or more plugins specified, OR
3106
						// - a plugin with an update available is currently active.
3107
						// @TODO: For multisite, maintenance mode should only kick in for individual sites if at all possible.
3108
						$maintenance = ( is_multisite() && ! empty( $plugins ) );
3109
3110
						/*
0 ignored issues
show
Unused Code Comprehensibility introduced by
49% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
3111
						[TGMPA - ]
3112
						foreach ( $plugins as $plugin )
3113
							$maintenance = $maintenance || ( is_plugin_active( $plugin ) && isset( $current->response[ $plugin] ) );
3114
						*/
3115
						if ( $maintenance ) {
3116
							$this->maintenance_mode( true );
3117
						}
3118
3119
						$results = array();
3120
3121
						$this->update_count   = count( $plugins );
3122
						$this->update_current = 0;
3123
						foreach ( $plugins as $plugin ) {
3124
							$this->update_current++;
3125
3126
							/*
0 ignored issues
show
Unused Code Comprehensibility introduced by
49% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
3127
							[TGMPA - ]
3128
							$this->skin->plugin_info = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin, false, true);
3129
3130
							if ( !isset( $current->response[ $plugin ] ) ) {
3131
								$this->skin->set_result('up_to_date');
3132
								$this->skin->before();
3133
								$this->skin->feedback('up_to_date');
3134
								$this->skin->after();
3135
								$results[$plugin] = true;
3136
								continue;
3137
							}
3138
3139
							// Get the URL to the zip file
3140
							$r = $current->response[ $plugin ];
3141
3142
							$this->skin->plugin_active = is_plugin_active($plugin);
3143
							*/
3144
3145
							$result = $this->run( array(
3146
								'package'           => $plugin, // [TGMPA + ] adjusted.
3147
								'destination'       => WP_PLUGIN_DIR,
3148
								'clear_destination' => false, // [TGMPA + ] adjusted.
3149
								'clear_working'     => true,
3150
								'is_multi'          => true,
3151
								'hook_extra'        => array(
3152
									'plugin' => $plugin,
3153
								),
3154
							) );
3155
3156
							$results[ $plugin ] = $this->result;
3157
3158
							// Prevent credentials auth screen from displaying multiple times.
3159
							if ( false === $result ) {
3160
								break;
3161
							}
3162
						} //end foreach $plugins
3163
3164
						$this->maintenance_mode( false );
3165
3166
						/**
3167
						 * Fires when the bulk upgrader process is complete.
3168
						 *
3169
						 * @since WP 3.6.0 / TGMPA 2.5.0
3170
						 *
3171
						 * @param Plugin_Upgrader $this Plugin_Upgrader instance. In other contexts, $this, might
3172
						 *                              be a Theme_Upgrader or Core_Upgrade instance.
3173
						 * @param array           $data {
3174
						 *     Array of bulk item update data.
3175
						 *
3176
						 *     @type string $action   Type of action. Default 'update'.
3177
						 *     @type string $type     Type of update process. Accepts 'plugin', 'theme', or 'core'.
3178
						 *     @type bool   $bulk     Whether the update process is a bulk update. Default true.
3179
						 *     @type array  $packages Array of plugin, theme, or core packages to update.
3180
						 * }
3181
						 */
3182
						do_action( 'upgrader_process_complete', $this, array(
3183
							'action'  => 'install', // [TGMPA + ] adjusted.
3184
							'type'    => 'plugin',
3185
							'bulk'    => true,
3186
							'plugins' => $plugins,
3187
						) );
3188
3189
						$this->skin->bulk_footer();
3190
3191
						$this->skin->footer();
3192
3193
						// Cleanup our hooks, in case something else does a upgrade on this connection.
3194
						/* [TGMPA - ] remove_filter('upgrader_clear_destination', array($this, 'delete_old_plugin')); */
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
3195
3196
						// [TGMPA + ] Remove our auto-activation hook.
3197
						remove_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3198
3199
						// Force refresh of plugin update information.
3200
						wp_clean_plugins_cache( $parsed_args['clear_update_cache'] );
3201
3202
						return $results;
3203
					}
3204
3205
					/**
3206
					 * Handle a bulk upgrade request.
3207
					 *
3208
					 * @since 2.5.0
3209
					 *
3210
					 * @see Plugin_Upgrader::bulk_upgrade()
3211
					 *
3212
					 * @param array $plugins The local WP file_path's of the plugins which should be upgraded.
3213
					 * @param array $args    Arbitrary passed extra arguments.
3214
					 * @return string|bool Install confirmation messages on success, false on failure.
3215
					 */
3216
					public function bulk_upgrade( $plugins, $args = array() ) {
3217
3218
						add_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3219
3220
						$result = parent::bulk_upgrade( $plugins, $args );
3221
3222
						remove_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3223
3224
						return $result;
3225
					}
3226
3227
					/**
3228
					 * Abuse a filter to auto-activate plugins after installation.
3229
					 *
3230
					 * Hooked into the 'upgrader_post_install' filter hook.
3231
					 *
3232
					 * @since 2.5.0
3233
					 *
3234
					 * @param bool $bool The value we need to give back (true).
3235
					 * @return bool
3236
					 */
3237
					public function auto_activate( $bool ) {
3238
						// Only process the activation of installed plugins if the automatic flag is set to true.
3239
						if ( $this->tgmpa->is_automatic ) {
3240
							// Flush plugins cache so the headers of the newly installed plugins will be read correctly.
3241
							wp_clean_plugins_cache();
3242
3243
							// Get the installed plugin file.
3244
							$plugin_info = $this->plugin_info();
3245
3246
							// Don't try to activate on upgrade of active plugin as WP will do this already.
3247
							if ( ! is_plugin_active( $plugin_info ) ) {
3248
								$activate = activate_plugin( $plugin_info );
3249
3250
								// Adjust the success string based on the activation result.
3251
								$this->strings['process_success'] = $this->strings['process_success'] . "<br />\n";
3252
3253
								if ( is_wp_error( $activate ) ) {
3254
									$this->skin->error( $activate );
3255
									$this->strings['process_success'] .= $this->strings['activation_failed'];
3256
								} else {
3257
									$this->strings['process_success'] .= $this->strings['activation_success'];
3258
								}
3259
							}
3260
						}
3261
3262
						return $bool;
3263
					}
3264
				}
3265
			}
3266
3267
			if ( ! class_exists( 'TGMPA_Bulk_Installer_Skin' ) ) {
3268
3269
				/**
3270
				 * Installer skin to set strings for the bulk plugin installations..
3271
				 *
3272
				 * Extends Bulk_Upgrader_Skin and customizes to suit the installation of multiple
3273
				 * plugins.
3274
				 *
3275
				 * @since 2.2.0
3276
				 *
3277
				 * @internal Since 2.5.2 the class has been renamed from TGM_Bulk_Installer_Skin to
3278
				 *           TGMPA_Bulk_Installer_Skin.
3279
				 *           This was done to prevent backward compatibility issues with v2.3.6.
3280
				 *
3281
				 * @see https://core.trac.wordpress.org/browser/trunk/src/wp-admin/includes/class-wp-upgrader-skins.php
3282
				 *
3283
				 * @package TGM-Plugin-Activation
3284
				 * @author  Thomas Griffin
3285
				 * @author  Gary Jones
3286
				 */
3287
				class TGMPA_Bulk_Installer_Skin extends Bulk_Upgrader_Skin {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
3288
					/**
3289
					 * Holds plugin info for each individual plugin installation.
3290
					 *
3291
					 * @since 2.2.0
3292
					 *
3293
					 * @var array
3294
					 */
3295
					public $plugin_info = array();
3296
3297
					/**
3298
					 * Holds names of plugins that are undergoing bulk installations.
3299
					 *
3300
					 * @since 2.2.0
3301
					 *
3302
					 * @var array
3303
					 */
3304
					public $plugin_names = array();
3305
3306
					/**
3307
					 * Integer to use for iteration through each plugin installation.
3308
					 *
3309
					 * @since 2.2.0
3310
					 *
3311
					 * @var integer
3312
					 */
3313
					public $i = 0;
3314
3315
					/**
3316
					 * TGMPA instance
3317
					 *
3318
					 * @since 2.5.0
3319
					 *
3320
					 * @var object
3321
					 */
3322
					protected $tgmpa;
3323
3324
					/**
3325
					 * Constructor. Parses default args with new ones and extracts them for use.
3326
					 *
3327
					 * @since 2.2.0
3328
					 *
3329
					 * @param array $args Arguments to pass for use within the class.
3330
					 */
3331
					public function __construct( $args = array() ) {
0 ignored issues
show
Coding Style introduced by
__construct uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
3332
						// Get TGMPA class instance.
3333
						$this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
3334
3335
						// Parse default and new args.
3336
						$defaults = array(
3337
							'url'          => '',
3338
							'nonce'        => '',
3339
							'names'        => array(),
3340
							'install_type' => 'install',
3341
						);
3342
						$args     = wp_parse_args( $args, $defaults );
3343
3344
						// Set plugin names to $this->plugin_names property.
3345
						$this->plugin_names = $args['names'];
3346
3347
						// Extract the new args.
3348
						parent::__construct( $args );
3349
					}
3350
3351
					/**
3352
					 * Sets install skin strings for each individual plugin.
3353
					 *
3354
					 * Checks to see if the automatic activation flag is set and uses the
3355
					 * the proper strings accordingly.
3356
					 *
3357
					 * @since 2.2.0
3358
					 */
3359
					public function add_strings() {
3360
						if ( 'update' === $this->options['install_type'] ) {
3361
							parent::add_strings();
3362
							$this->upgrader->strings['skin_before_update_header'] = __( 'Updating Plugin %1$s (%2$d/%3$d)', 'tgmpa' );
3363
						} else {
3364
							$this->upgrader->strings['skin_update_failed_error'] = __( 'An error occurred while installing %1$s: <strong>%2$s</strong>.', 'tgmpa' );
3365
							$this->upgrader->strings['skin_update_failed']       = __( 'The installation of %1$s failed.', 'tgmpa' );
3366
3367
							if ( $this->tgmpa->is_automatic ) {
3368
								// Automatic activation strings.
3369
								$this->upgrader->strings['skin_upgrade_start']        = __( 'The installation and activation process is starting. This process may take a while on some hosts, so please be patient.', 'tgmpa' );
3370
								$this->upgrader->strings['skin_update_successful']    = __( '%1$s installed and activated successfully.', 'tgmpa' ) . ' <a href="#" class="hide-if-no-js" onclick="%2$s"><span>' . esc_html__( 'Show Details', 'tgmpa' ) . '</span><span class="hidden">' . esc_html__( 'Hide Details', 'tgmpa' ) . '</span>.</a>';
3371
								$this->upgrader->strings['skin_upgrade_end']          = __( 'All installations and activations have been completed.', 'tgmpa' );
3372
								$this->upgrader->strings['skin_before_update_header'] = __( 'Installing and Activating Plugin %1$s (%2$d/%3$d)', 'tgmpa' );
3373
							} else {
3374
								// Default installation strings.
3375
								$this->upgrader->strings['skin_upgrade_start']        = __( 'The installation process is starting. This process may take a while on some hosts, so please be patient.', 'tgmpa' );
3376
								$this->upgrader->strings['skin_update_successful']    = esc_html__( '%1$s installed successfully.', 'tgmpa' ) . ' <a href="#" class="hide-if-no-js" onclick="%2$s"><span>' . esc_html__( 'Show Details', 'tgmpa' ) . '</span><span class="hidden">' . esc_html__( 'Hide Details', 'tgmpa' ) . '</span>.</a>';
3377
								$this->upgrader->strings['skin_upgrade_end']          = __( 'All installations have been completed.', 'tgmpa' );
3378
								$this->upgrader->strings['skin_before_update_header'] = __( 'Installing Plugin %1$s (%2$d/%3$d)', 'tgmpa' );
3379
							}
3380
						}
3381
					}
3382
3383
					/**
3384
					 * Outputs the header strings and necessary JS before each plugin installation.
3385
					 *
3386
					 * @since 2.2.0
3387
					 *
3388
					 * @param string $title Unused in this implementation.
3389
					 */
3390
					public function before( $title = '' ) {
3391
						if ( empty( $title ) ) {
3392
							$title = esc_html( $this->plugin_names[ $this->i ] );
3393
						}
3394
						parent::before( $title );
3395
					}
3396
3397
					/**
3398
					 * Outputs the footer strings and necessary JS after each plugin installation.
3399
					 *
3400
					 * Checks for any errors and outputs them if they exist, else output
3401
					 * success strings.
3402
					 *
3403
					 * @since 2.2.0
3404
					 *
3405
					 * @param string $title Unused in this implementation.
3406
					 */
3407
					public function after( $title = '' ) {
3408
						if ( empty( $title ) ) {
3409
							$title = esc_html( $this->plugin_names[ $this->i ] );
3410
						}
3411
						parent::after( $title );
3412
3413
						$this->i++;
3414
					}
3415
3416
					/**
3417
					 * Outputs links after bulk plugin installation is complete.
3418
					 *
3419
					 * @since 2.2.0
3420
					 */
3421
					public function bulk_footer() {
3422
						// Serve up the string to say installations (and possibly activations) are complete.
3423
						parent::bulk_footer();
3424
3425
						// Flush plugins cache so we can make sure that the installed plugins list is always up to date.
3426
						wp_clean_plugins_cache();
3427
3428
						$this->tgmpa->show_tgmpa_version();
3429
3430
						// Display message based on if all plugins are now active or not.
3431
						$update_actions = array();
3432
3433
						if ( $this->tgmpa->is_tgmpa_complete() ) {
3434
							// All plugins are active, so we display the complete string and hide the menu to protect users.
3435
							echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>';
3436
							$update_actions['dashboard'] = sprintf(
3437
								esc_html( $this->tgmpa->strings['complete'] ),
3438
								'<a href="' . esc_url( self_admin_url() ) . '">' . esc_html__( 'Return to the Dashboard', 'tgmpa' ) . '</a>'
3439
							);
3440
						} else {
3441
							$update_actions['tgmpa_page'] = '<a href="' . esc_url( $this->tgmpa->get_tgmpa_url() ) . '" target="_parent">' . esc_html( $this->tgmpa->strings['return'] ) . '</a>';
3442
						}
3443
3444
						/**
3445
						 * Filter the list of action links available following bulk plugin installs/updates.
3446
						 *
3447
						 * @since 2.5.0
3448
						 *
3449
						 * @param array $update_actions Array of plugin action links.
3450
						 * @param array $plugin_info    Array of information for the last-handled plugin.
3451
						 */
3452
						$update_actions = apply_filters( 'tgmpa_update_bulk_plugins_complete_actions', $update_actions, $this->plugin_info );
3453
3454
						if ( ! empty( $update_actions ) ) {
3455
							$this->feedback( implode( ' | ', (array) $update_actions ) );
3456
						}
3457
					}
3458
3459
					/* *********** DEPRECATED METHODS *********** */
3460
3461
					/**
3462
					 * Flush header output buffer.
3463
					 *
3464
					 * @since      2.2.0
3465
					 * @deprecated 2.5.0 use {@see Bulk_Upgrader_Skin::flush_output()} instead
3466
					 * @see        Bulk_Upgrader_Skin::flush_output()
3467
					 */
3468
					public function before_flush_output() {
3469
						_deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'Bulk_Upgrader_Skin::flush_output()' );
3470
						$this->flush_output();
3471
					}
3472
3473
					/**
3474
					 * Flush footer output buffer and iterate $this->i to make sure the
3475
					 * installation strings reference the correct plugin.
3476
					 *
3477
					 * @since      2.2.0
3478
					 * @deprecated 2.5.0 use {@see Bulk_Upgrader_Skin::flush_output()} instead
3479
					 * @see        Bulk_Upgrader_Skin::flush_output()
3480
					 */
3481
					public function after_flush_output() {
3482
						_deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'Bulk_Upgrader_Skin::flush_output()' );
3483
						$this->flush_output();
3484
						$this->i++;
3485
					}
3486
				}
3487
			}
3488
		}
3489
	}
3490
}
3491
3492
if ( ! class_exists( 'TGMPA_Utils' ) ) {
3493
3494
	/**
3495
	 * Generic utilities for TGMPA.
3496
	 *
3497
	 * All methods are static, poor-dev name-spacing class wrapper.
3498
	 *
3499
	 * Class was called TGM_Utils in 2.5.0 but renamed TGMPA_Utils in 2.5.1 as this was conflicting with Soliloquy.
3500
	 *
3501
	 * @since 2.5.0
3502
	 *
3503
	 * @package TGM-Plugin-Activation
3504
	 * @author  Juliette Reinders Folmer
3505
	 */
3506
	class TGMPA_Utils {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
3507
		/**
3508
		 * Whether the PHP filter extension is enabled.
3509
		 *
3510
		 * @see http://php.net/book.filter
3511
		 *
3512
		 * @since 2.5.0
3513
		 *
3514
		 * @static
3515
		 *
3516
		 * @var bool $has_filters True is the extension is enabled.
3517
		 */
3518
		public static $has_filters;
3519
3520
		/**
3521
		 * Wrap an arbitrary string in <em> tags. Meant to be used in combination with array_map().
3522
		 *
3523
		 * @since 2.5.0
3524
		 *
3525
		 * @static
3526
		 *
3527
		 * @param string $string Text to be wrapped.
3528
		 * @return string
3529
		 */
3530
		public static function wrap_in_em( $string ) {
3531
			return '<em>' . wp_kses_post( $string ) . '</em>';
3532
		}
3533
3534
		/**
3535
		 * Wrap an arbitrary string in <strong> tags. Meant to be used in combination with array_map().
3536
		 *
3537
		 * @since 2.5.0
3538
		 *
3539
		 * @static
3540
		 *
3541
		 * @param string $string Text to be wrapped.
3542
		 * @return string
3543
		 */
3544
		public static function wrap_in_strong( $string ) {
3545
			return '<strong>' . wp_kses_post( $string ) . '</strong>';
3546
		}
3547
3548
		/**
3549
		 * Helper function: Validate a value as boolean
3550
		 *
3551
		 * @since 2.5.0
3552
		 *
3553
		 * @static
3554
		 *
3555
		 * @param mixed $value Arbitrary value.
3556
		 * @return bool
3557
		 */
3558
		public static function validate_bool( $value ) {
3559
			if ( ! isset( self::$has_filters ) ) {
3560
				self::$has_filters = extension_loaded( 'filter' );
3561
			}
3562
3563
			if ( self::$has_filters ) {
3564
				return filter_var( $value, FILTER_VALIDATE_BOOLEAN );
3565
			} else {
3566
				return self::emulate_filter_bool( $value );
3567
			}
3568
		}
3569
3570
		/**
3571
		 * Helper function: Cast a value to bool
3572
		 *
3573
		 * @since 2.5.0
3574
		 *
3575
		 * @static
3576
		 *
3577
		 * @param mixed $value Value to cast.
3578
		 * @return bool
3579
		 */
3580
		protected static function emulate_filter_bool( $value ) {
3581
			// @codingStandardsIgnoreStart
3582
			static $true  = array(
3583
				'1',
3584
				'true', 'True', 'TRUE',
3585
				'y', 'Y',
3586
				'yes', 'Yes', 'YES',
3587
				'on', 'On', 'ON',
3588
			);
3589
			static $false = array(
3590
				'0',
3591
				'false', 'False', 'FALSE',
3592
				'n', 'N',
3593
				'no', 'No', 'NO',
3594
				'off', 'Off', 'OFF',
3595
			);
3596
			// @codingStandardsIgnoreEnd
3597
3598
			if ( is_bool( $value ) ) {
3599
				return $value;
3600
			} else if ( is_int( $value ) && ( 0 === $value || 1 === $value ) ) {
3601
				return (bool) $value;
3602
			} else if ( ( is_float( $value ) && ! is_nan( $value ) ) && ( (float) 0 === $value || (float) 1 === $value ) ) {
3603
				return (bool) $value;
3604
			} else if ( is_string( $value ) ) {
3605
				$value = trim( $value );
3606
				if ( in_array( $value, $true, true ) ) {
3607
					return true;
3608
				} else if ( in_array( $value, $false, true ) ) {
3609
					return false;
3610
				} else {
3611
					return false;
3612
				}
3613
			}
3614
3615
			return false;
3616
		}
3617
	} // End of class TGMPA_Utils
3618
} // End of class_exists wrapper
3619