TGMPA_List_Table::process_bulk_actions()   F
last analyzed

Complexity

Conditions 34
Paths 534

Size

Total Lines 233

Duplication

Lines 28
Ratio 12.02 %

Importance

Changes 0
Metric Value
cc 34
nc 534
nop 0
dl 28
loc 233
rs 0.5177
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/**
3
 * 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.6.1
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
18
/*
19
	Copyright 2011 Thomas Griffin (thomasgriffinmedia.com)
20
21
	This program is free software; you can redistribute it and/or modify
22
	it under the terms of the GNU General Public License, version 2, as
23
	published by the Free Software Foundation.
24
25
	This program is distributed in the hope that it will be useful,
26
	but WITHOUT ANY WARRANTY; without even the implied warranty of
27
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
28
	GNU General Public License for more details.
29
30
	You should have received a copy of the GNU General Public License
31
	along with this program; if not, write to the Free Software
32
	Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
33
*/
34
35
// Exit if accessed directly.
36
if ( ! defined( 'ABSPATH' ) ) {
37
	return;
38
}
39
40
if ( ! class_exists( 'TGM_Plugin_Activation' ) ) {
41
42
	/**
43
	 * Automatic plugin installation and activation library.
44
	 *
45
	 * Creates a way to automatically install and activate plugins from within themes.
46
	 * The plugins can be either bundled, downloaded from the WordPress
47
	 * Plugin Repository or downloaded from another external source.
48
	 *
49
	 * @since 1.0.0
50
	 *
51
	 * @package TGM-Plugin-Activation
52
	 * @author  Thomas Griffin
53
	 * @author  Gary Jones
54
	 */
55
	class TGM_Plugin_Activation {
56
		/**
57
		 * TGMPA version number.
58
		 *
59
		 * @since 2.5.0
60
		 *
61
		 * @const string Version number.
62
		 */
63
		const TGMPA_VERSION = '2.6.1';
64
65
		/**
66
		 * Regular expression to test if a URL is a WP plugin repo URL.
67
		 *
68
		 * @const string Regex.
69
		 *
70
		 * @since 2.5.0
71
		 */
72
		const WP_REPO_REGEX = '|^http[s]?://wordpress\.org/(?:extend/)?plugins/|';
73
74
		/**
75
		 * Arbitrary regular expression to test if a string starts with a URL.
76
		 *
77
		 * @const string Regex.
78
		 *
79
		 * @since 2.5.0
80
		 */
81
		const IS_URL_REGEX = '|^http[s]?://|';
82
83
		/**
84
		 * Holds a copy of itself, so it can be referenced by the class name.
85
		 *
86
		 * @since 1.0.0
87
		 *
88
		 * @var TGM_Plugin_Activation
89
		 */
90
		public static $instance;
91
92
		/**
93
		 * Holds arrays of plugin details.
94
		 *
95
		 * @since 1.0.0
96
		 * @since 2.5.0 the array has the plugin slug as an associative key.
97
		 *
98
		 * @var array
99
		 */
100
		public $plugins = array();
101
102
		/**
103
		 * Holds arrays of plugin names to use to sort the plugins array.
104
		 *
105
		 * @since 2.5.0
106
		 *
107
		 * @var array
108
		 */
109
		protected $sort_order = array();
110
111
		/**
112
		 * Whether any plugins have the 'force_activation' setting set to true.
113
		 *
114
		 * @since 2.5.0
115
		 *
116
		 * @var bool
117
		 */
118
		protected $has_forced_activation = false;
119
120
		/**
121
		 * Whether any plugins have the 'force_deactivation' setting set to true.
122
		 *
123
		 * @since 2.5.0
124
		 *
125
		 * @var bool
126
		 */
127
		protected $has_forced_deactivation = false;
128
129
		/**
130
		 * Name of the unique ID to hash notices.
131
		 *
132
		 * @since 2.4.0
133
		 *
134
		 * @var string
135
		 */
136
		public $id = 'tgmpa';
137
138
		/**
139
		 * Name of the query-string argument for the admin page.
140
		 *
141
		 * @since 1.0.0
142
		 *
143
		 * @var string
144
		 */
145
		protected $menu = 'tgmpa-install-plugins';
146
147
		/**
148
		 * Parent menu file slug.
149
		 *
150
		 * @since 2.5.0
151
		 *
152
		 * @var string
153
		 */
154
		public $parent_slug = 'themes.php';
155
156
		/**
157
		 * Capability needed to view the plugin installation menu item.
158
		 *
159
		 * @since 2.5.0
160
		 *
161
		 * @var string
162
		 */
163
		public $capability = 'edit_theme_options';
164
165
		/**
166
		 * Default absolute path to folder containing bundled plugin zip files.
167
		 *
168
		 * @since 2.0.0
169
		 *
170
		 * @var string Absolute path prefix to zip file location for bundled plugins. Default is empty string.
171
		 */
172
		public $default_path = '';
173
174
		/**
175
		 * Flag to show admin notices or not.
176
		 *
177
		 * @since 2.1.0
178
		 *
179
		 * @var boolean
180
		 */
181
		public $has_notices = true;
182
183
		/**
184
		 * Flag to determine if the user can dismiss the notice nag.
185
		 *
186
		 * @since 2.4.0
187
		 *
188
		 * @var boolean
189
		 */
190
		public $dismissable = true;
191
192
		/**
193
		 * Message to be output above nag notice if dismissable is false.
194
		 *
195
		 * @since 2.4.0
196
		 *
197
		 * @var string
198
		 */
199
		public $dismiss_msg = '';
200
201
		/**
202
		 * Flag to set automatic activation of plugins. Off by default.
203
		 *
204
		 * @since 2.2.0
205
		 *
206
		 * @var boolean
207
		 */
208
		public $is_automatic = false;
209
210
		/**
211
		 * Optional message to display before the plugins table.
212
		 *
213
		 * @since 2.2.0
214
		 *
215
		 * @var string Message filtered by wp_kses_post(). Default is empty string.
216
		 */
217
		public $message = '';
218
219
		/**
220
		 * Holds configurable array of strings.
221
		 *
222
		 * Default values are added in the constructor.
223
		 *
224
		 * @since 2.0.0
225
		 *
226
		 * @var array
227
		 */
228
		public $strings = array();
229
230
		/**
231
		 * Holds the version of WordPress.
232
		 *
233
		 * @since 2.4.0
234
		 *
235
		 * @var int
236
		 */
237
		public $wp_version;
238
239
		/**
240
		 * Holds the hook name for the admin page.
241
		 *
242
		 * @since 2.5.0
243
		 *
244
		 * @var string
245
		 */
246
		public $page_hook;
247
248
		/**
249
		 * Adds a reference of this object to $instance, populates default strings,
250
		 * does the tgmpa_init action hook, and hooks in the interactions to init.
251
		 *
252
		 * {@internal This method should be `protected`, but as too many TGMPA implementations
253
		 * haven't upgraded beyond v2.3.6 yet, this gives backward compatibility issues.
254
		 * Reverted back to public for the time being.}}
255
		 *
256
		 * @since 1.0.0
257
		 *
258
		 * @see TGM_Plugin_Activation::init()
259
		 */
260
		public function __construct() {
261
			// Set the current WordPress version.
262
			$this->wp_version = $GLOBALS['wp_version'];
263
264
			// Announce that the class is ready, and pass the object (for advanced use).
265
			do_action_ref_array( 'tgmpa_init', array( $this ) );
266
267
			/*
268
			 * Load our text domain and allow for overloading the fall-back file.
269
			 *
270
			 * {@internal IMPORTANT! If this code changes, review the regex in the custom TGMPA
271
			 * generator on the website.}}
272
			 */
273
			add_action( 'init', array( $this, 'load_textdomain' ), 5 );
274
			add_filter( 'load_textdomain_mofile', array( $this, 'overload_textdomain_mofile' ), 10, 2 );
275
276
			// When the rest of WP has loaded, kick-start the rest of the class.
277
			add_action( 'init', array( $this, 'init' ) );
278
		}
279
280
		/**
281
		 * Magic method to (not) set protected properties from outside of this class.
282
		 *
283
		 * {@internal hackedihack... There is a serious bug in v2.3.2 - 2.3.6  where the `menu` property
284
		 * is being assigned rather than tested in a conditional, effectively rendering it useless.
285
		 * This 'hack' prevents this from happening.}}
286
		 *
287
		 * @see https://github.com/TGMPA/TGM-Plugin-Activation/blob/2.3.6/tgm-plugin-activation/class-tgm-plugin-activation.php#L1593
288
		 *
289
		 * @since 2.5.2
290
		 *
291
		 * @param string $name  Name of an inaccessible property.
292
		 * @param mixed  $value Value to assign to the property.
293
		 * @return void  Silently fail to set the property when this is tried from outside of this class context.
294
		 *               (Inside this class context, the __set() method if not used as there is direct access.)
295
		 */
296
		public function __set( $name, $value ) {
297
			return;
298
		}
299
300
		/**
301
		 * Magic method to get the value of a protected property outside of this class context.
302
		 *
303
		 * @since 2.5.2
304
		 *
305
		 * @param string $name Name of an inaccessible property.
306
		 * @return mixed The property value.
307
		 */
308
		public function __get( $name ) {
309
			return $this->{$name};
310
		}
311
312
		/**
313
		 * Initialise the interactions between this class and WordPress.
314
		 *
315
		 * Hooks in three new methods for the class: admin_menu, notices and styles.
316
		 *
317
		 * @since 2.0.0
318
		 *
319
		 * @see TGM_Plugin_Activation::admin_menu()
320
		 * @see TGM_Plugin_Activation::notices()
321
		 * @see TGM_Plugin_Activation::styles()
322
		 */
323
		public function init() {
324
			/**
325
			 * By default TGMPA only loads on the WP back-end and not in an Ajax call. Using this filter
326
			 * you can overrule that behaviour.
327
			 *
328
			 * @since 2.5.0
329
			 *
330
			 * @param bool $load Whether or not TGMPA should load.
331
			 *                   Defaults to the return of `is_admin() && ! defined( 'DOING_AJAX' )`.
332
			 */
333
			if ( true !== apply_filters( 'tgmpa_load', ( is_admin() && ! defined( 'DOING_AJAX' ) ) ) ) {
334
				return;
335
			}
336
337
			// Load class strings.
338
			$this->strings = array(
339
				'page_title'                      => __( 'Install Required Plugins', 'tgmpa' ),
340
				'menu_title'                      => __( 'Install Plugins', 'tgmpa' ),
341
				/* translators: %s: plugin name. */
342
				'installing'                      => __( 'Installing Plugin: %s', 'tgmpa' ),
343
				/* translators: %s: plugin name. */
344
				'updating'                        => __( 'Updating Plugin: %s', 'tgmpa' ),
345
				'oops'                            => __( 'Something went wrong with the plugin API.', 'tgmpa' ),
346
				/* translators: 1: plugin name(s). */
347
				'notice_can_install_required'     => _n_noop(
348
					'This theme requires the following plugin: %1$s.',
349
					'This theme requires the following plugins: %1$s.',
350
					'tgmpa'
351
				),
352
				/* translators: 1: plugin name(s). */
353
				'notice_can_install_recommended'  => _n_noop(
354
					'This theme recommends the following plugin: %1$s.',
355
					'This theme recommends the following plugins: %1$s.',
356
					'tgmpa'
357
				),
358
				/* translators: 1: plugin name(s). */
359
				'notice_ask_to_update'            => _n_noop(
360
					'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.',
361
					'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.',
362
					'tgmpa'
363
				),
364
				/* translators: 1: plugin name(s). */
365
				'notice_ask_to_update_maybe'      => _n_noop(
366
					'There is an update available for: %1$s.',
367
					'There are updates available for the following plugins: %1$s.',
368
					'tgmpa'
369
				),
370
				/* translators: 1: plugin name(s). */
371
				'notice_can_activate_required'    => _n_noop(
372
					'The following required plugin is currently inactive: %1$s.',
373
					'The following required plugins are currently inactive: %1$s.',
374
					'tgmpa'
375
				),
376
				/* translators: 1: plugin name(s). */
377
				'notice_can_activate_recommended' => _n_noop(
378
					'The following recommended plugin is currently inactive: %1$s.',
379
					'The following recommended plugins are currently inactive: %1$s.',
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
				/* translators: 1: plugin name. */
402
				'plugin_already_active'           => __( 'No action taken. Plugin %1$s was already active.', 'tgmpa' ),
403
				/* translators: 1: plugin name. */
404
				'plugin_needs_higher_version'     => __( 'Plugin not activated. A higher version of %s is needed for this theme. Please update the plugin.', 'tgmpa' ),
405
				/* translators: 1: dashboard link. */
406
				'complete'                        => __( 'All plugins installed and activated successfully. %1$s', 'tgmpa' ),
407
				'dismiss'                         => __( 'Dismiss this notice', 'tgmpa' ),
408
				'notice_cannot_install_activate'  => __( 'There are one or more required or recommended plugins to install, update or activate.', 'tgmpa' ),
409
				'contact_admin'                   => __( 'Please contact the administrator of this site for help.', 'tgmpa' ),
410
			);
411
412
			do_action( 'tgmpa_register' );
413
414
			/* After this point, the plugins should be registered and the configuration set. */
415
416
			// Proceed only if we have plugins to handle.
417
			if ( empty( $this->plugins ) || ! is_array( $this->plugins ) ) {
418
				return;
419
			}
420
421
			// Set up the menu and notices if we still have outstanding actions.
422
			if ( true !== $this->is_tgmpa_complete() ) {
423
				// Sort the plugins.
424
				array_multisort( $this->sort_order, SORT_ASC, $this->plugins );
425
426
				add_action( 'admin_menu', array( $this, 'admin_menu' ) );
427
				add_action( 'admin_head', array( $this, 'dismiss' ) );
428
429
				// Prevent the normal links from showing underneath a single install/update page.
430
				add_filter( 'install_plugin_complete_actions', array( $this, 'actions' ) );
431
				add_filter( 'update_plugin_complete_actions', array( $this, 'actions' ) );
432
433
				if ( $this->has_notices ) {
434
					add_action( 'admin_notices', array( $this, 'notices' ) );
435
					add_action( 'admin_init', array( $this, 'admin_init' ), 1 );
436
					add_action( 'admin_enqueue_scripts', array( $this, 'thickbox' ) );
437
				}
438
			}
439
440
			// If needed, filter plugin action links.
441
			add_action( 'load-plugins.php', array( $this, 'add_plugin_action_link_filters' ), 1 );
442
443
			// Make sure things get reset on switch theme.
444
			add_action( 'switch_theme', array( $this, 'flush_plugins_cache' ) );
445
446
			if ( $this->has_notices ) {
447
				add_action( 'switch_theme', array( $this, 'update_dismiss' ) );
448
			}
449
450
			// Setup the force activation hook.
451
			if ( true === $this->has_forced_activation ) {
452
				add_action( 'admin_init', array( $this, 'force_activation' ) );
453
			}
454
455
			// Setup the force deactivation hook.
456
			if ( true === $this->has_forced_deactivation ) {
457
				add_action( 'switch_theme', array( $this, 'force_deactivation' ) );
458
			}
459
460
			// Add CSS for the TGMPA admin page.
461
			add_action( 'admin_head', array( $this, 'admin_css' ) );
462
		}
463
464
		/**
465
		 * Load translations.
466
		 *
467
		 * @since 2.6.0
468
		 *
469
		 * (@internal Uses `load_theme_textdomain()` rather than `load_plugin_textdomain()` to
470
		 * get round the different ways of handling the path and deprecated notices being thrown
471
		 * and such. For plugins, the actual file name will be corrected by a filter.}}
472
		 *
473
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
474
		 * generator on the website.}}
475
		 */
476
		public function load_textdomain() {
477
			if ( is_textdomain_loaded( 'tgmpa' ) ) {
478
				return;
479
			}
480
481
			if ( false !== strpos( __FILE__, WP_PLUGIN_DIR ) || false !== strpos( __FILE__, WPMU_PLUGIN_DIR ) ) {
482
				// Plugin, we'll need to adjust the file name.
483
				add_action( 'load_textdomain_mofile', array( $this, 'correct_plugin_mofile' ), 10, 2 );
484
				load_theme_textdomain( 'tgmpa', dirname( __FILE__ ) . '/languages' );
485
				remove_action( 'load_textdomain_mofile', array( $this, 'correct_plugin_mofile' ), 10 );
486
			} else {
487
				load_theme_textdomain( 'tgmpa', dirname( __FILE__ ) . '/languages' );
488
			}
489
		}
490
491
		/**
492
		 * Correct the .mo file name for (must-use) plugins.
493
		 *
494
		 * Themese use `/path/{locale}.mo` while plugins use `/path/{text-domain}-{locale}.mo`.
495
		 *
496
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
497
		 * generator on the website.}}
498
		 *
499
		 * @since 2.6.0
500
		 *
501
		 * @param string $mofile Full path to the target mofile.
502
		 * @param string $domain The domain for which a language file is being loaded.
503
		 * @return string $mofile
504
		 */
505
		public function correct_plugin_mofile( $mofile, $domain ) {
506
			// Exit early if not our domain (just in case).
507
			if ( 'tgmpa' !== $domain ) {
508
				return $mofile;
509
			}
510
			return preg_replace( '`/([a-z]{2}_[A-Z]{2}.mo)$`', '/tgmpa-$1', $mofile );
511
		}
512
513
		/**
514
		 * Potentially overload the fall-back translation file for the current language.
515
		 *
516
		 * WP, by default since WP 3.7, will load a local translation first and if none
517
		 * can be found, will try and find a translation in the /wp-content/languages/ directory.
518
		 * As this library is theme/plugin agnostic, translation files for TGMPA can exist both
519
		 * in the WP_LANG_DIR /plugins/ subdirectory as well as in the /themes/ subdirectory.
520
		 *
521
		 * This method makes sure both directories are checked.
522
		 *
523
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
524
		 * generator on the website.}}
525
		 *
526
		 * @since 2.6.0
527
		 *
528
		 * @param string $mofile Full path to the target mofile.
529
		 * @param string $domain The domain for which a language file is being loaded.
530
		 * @return string $mofile
531
		 */
532
		public function overload_textdomain_mofile( $mofile, $domain ) {
533
			// Exit early if not our domain, not a WP_LANG_DIR load or if the file exists and is readable.
534
			if ( 'tgmpa' !== $domain || false === strpos( $mofile, WP_LANG_DIR ) || @is_readable( $mofile ) ) {
535
				return $mofile;
536
			}
537
538
			// Current fallback file is not valid, let's try the alternative option.
539
			if ( false !== strpos( $mofile, '/themes/' ) ) {
540
				return str_replace( '/themes/', '/plugins/', $mofile );
541
			} elseif ( false !== strpos( $mofile, '/plugins/' ) ) {
542
				return str_replace( '/plugins/', '/themes/', $mofile );
543
			} else {
544
				return $mofile;
545
			}
546
		}
547
548
		/**
549
		 * Hook in plugin action link filters for the WP native plugins page.
550
		 *
551
		 * - Prevent activation of plugins which don't meet the minimum version requirements.
552
		 * - Prevent deactivation of force-activated plugins.
553
		 * - Add update notice if update available.
554
		 *
555
		 * @since 2.5.0
556
		 */
557
		public function add_plugin_action_link_filters() {
558
			foreach ( $this->plugins as $slug => $plugin ) {
559
				if ( false === $this->can_plugin_activate( $slug ) ) {
560
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_activate' ), 20 );
561
				}
562
563
				if ( true === $plugin['force_activation'] ) {
564
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_deactivate' ), 20 );
565
				}
566
567
				if ( false !== $this->does_plugin_require_update( $slug ) ) {
568
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_update' ), 20 );
569
				}
570
			}
571
		}
572
573
		/**
574
		 * Remove the 'Activate' link on the WP native plugins page if the plugin does not meet the
575
		 * minimum version requirements.
576
		 *
577
		 * @since 2.5.0
578
		 *
579
		 * @param array $actions Action links.
580
		 * @return array
581
		 */
582
		public function filter_plugin_action_links_activate( $actions ) {
583
			unset( $actions['activate'] );
584
585
			return $actions;
586
		}
587
588
		/**
589
		 * Remove the 'Deactivate' link on the WP native plugins page if the plugin has been set to force activate.
590
		 *
591
		 * @since 2.5.0
592
		 *
593
		 * @param array $actions Action links.
594
		 * @return array
595
		 */
596
		public function filter_plugin_action_links_deactivate( $actions ) {
597
			unset( $actions['deactivate'] );
598
599
			return $actions;
600
		}
601
602
		/**
603
		 * Add a 'Requires update' link on the WP native plugins page if the plugin does not meet the
604
		 * minimum version requirements.
605
		 *
606
		 * @since 2.5.0
607
		 *
608
		 * @param array $actions Action links.
609
		 * @return array
610
		 */
611
		public function filter_plugin_action_links_update( $actions ) {
612
			$actions['update'] = sprintf(
613
				'<a href="%1$s" title="%2$s" class="edit">%3$s</a>',
614
				esc_url( $this->get_tgmpa_status_url( 'update' ) ),
615
				esc_attr__( 'This plugin needs to be updated to be compatible with your theme.', 'tgmpa' ),
616
				esc_html__( 'Update Required', 'tgmpa' )
617
			);
618
619
			return $actions;
620
		}
621
622
		/**
623
		 * Handles calls to show plugin information via links in the notices.
624
		 *
625
		 * We get the links in the admin notices to point to the TGMPA page, rather
626
		 * than the typical plugin-install.php file, so we can prepare everything
627
		 * beforehand.
628
		 *
629
		 * WP does not make it easy to show the plugin information in the thickbox -
630
		 * here we have to require a file that includes a function that does the
631
		 * main work of displaying it, enqueue some styles, set up some globals and
632
		 * finally call that function before exiting.
633
		 *
634
		 * Down right easy once you know how...
635
		 *
636
		 * Returns early if not the TGMPA page.
637
		 *
638
		 * @since 2.1.0
639
		 *
640
		 * @global string $tab Used as iframe div class names, helps with styling
641
		 * @global string $body_id Used as the iframe body ID, helps with styling
642
		 *
643
		 * @return null Returns early if not the TGMPA page.
644
		 */
645
		public function admin_init() {
646
			if ( ! $this->is_tgmpa_page() ) {
647
				return;
648
			}
649
650
			if ( isset( $_REQUEST['tab'] ) && 'plugin-information' === $_REQUEST['tab'] ) {
651
				// Needed for install_plugin_information().
652
				require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
653
654
				wp_enqueue_style( 'plugin-install' );
655
656
				global $tab, $body_id;
0 ignored issues
show
Compatibility Best Practice introduced by jrfnl
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...
657
				$body_id = 'plugin-information'; // WPCS: override ok, prefix ok.
658
				$tab     = 'plugin-information'; // WPCS: override ok.
659
660
				install_plugin_information();
661
662
				exit;
663
			}
664
		}
665
666
		/**
667
		 * Enqueue thickbox scripts/styles for plugin info.
668
		 *
669
		 * Thickbox is not automatically included on all admin pages, so we must
670
		 * manually enqueue it for those pages.
671
		 *
672
		 * Thickbox is only loaded if the user has not dismissed the admin
673
		 * notice or if there are any plugins left to install and activate.
674
		 *
675
		 * @since 2.1.0
676
		 */
677
		public function thickbox() {
678
			if ( ! get_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, true ) ) {
679
				add_thickbox();
680
			}
681
		}
682
683
		/**
684
		 * Adds submenu page if there are plugin actions to take.
685
		 *
686
		 * This method adds the submenu page letting users know that a required
687
		 * plugin needs to be installed.
688
		 *
689
		 * This page disappears once the plugin has been installed and activated.
690
		 *
691
		 * @since 1.0.0
692
		 *
693
		 * @see TGM_Plugin_Activation::init()
694
		 * @see TGM_Plugin_Activation::install_plugins_page()
695
		 *
696
		 * @return null Return early if user lacks capability to install a plugin.
697
		 */
698
		public function admin_menu() {
699
			// Make sure privileges are correct to see the page.
700
			if ( ! current_user_can( 'install_plugins' ) ) {
701
				return;
702
			}
703
704
			$args = apply_filters(
705
				'tgmpa_admin_menu_args',
706
				array(
707
					'parent_slug' => $this->parent_slug,                     // Parent Menu slug.
708
					'page_title'  => $this->strings['page_title'],           // Page title.
709
					'menu_title'  => $this->strings['menu_title'],           // Menu title.
710
					'capability'  => $this->capability,                      // Capability.
711
					'menu_slug'   => $this->menu,                            // Menu slug.
712
					'function'    => array( $this, 'install_plugins_page' ), // Callback.
713
				)
714
			);
715
716
			$this->add_admin_menu( $args );
717
		}
718
719
		/**
720
		 * Add the menu item.
721
		 *
722
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
723
		 * generator on the website.}}
724
		 *
725
		 * @since 2.5.0
726
		 *
727
		 * @param array $args Menu item configuration.
728
		 */
729
		protected function add_admin_menu( array $args ) {
730
			if ( has_filter( 'tgmpa_admin_menu_use_add_theme_page' ) ) {
731
				_deprecated_function( 'The "tgmpa_admin_menu_use_add_theme_page" filter', '2.5.0', esc_html__( 'Set the parent_slug config variable instead.', 'tgmpa' ) );
732
			}
733
734
			if ( 'themes.php' === $this->parent_slug ) {
735
				$this->page_hook = call_user_func( 'add_theme_page', $args['page_title'], $args['menu_title'], $args['capability'], $args['menu_slug'], $args['function'] );
736
			} else {
737
				$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'] );
738
			}
739
		}
740
741
		/**
742
		 * Echoes plugin installation form.
743
		 *
744
		 * This method is the callback for the admin_menu method function.
745
		 * This displays the admin page and form area where the user can select to install and activate the plugin.
746
		 * Aborts early if we're processing a plugin installation action.
747
		 *
748
		 * @since 1.0.0
749
		 *
750
		 * @return null Aborts early if we're processing a plugin installation action.
751
		 */
752
		public function install_plugins_page() {
753
			// Store new instance of plugin table in object.
754
			$plugin_table = new TGMPA_List_Table();
755
756
			// Return early if processing a plugin installation action.
757
			if ( ( ( 'tgmpa-bulk-install' === $plugin_table->current_action() || 'tgmpa-bulk-update' === $plugin_table->current_action() ) && $plugin_table->process_bulk_actions() ) || $this->do_plugin_install() ) {
758
				return;
759
			}
760
761
			// Force refresh of available plugin information so we'll know about manual updates/deletes.
762
			wp_clean_plugins_cache( false );
763
764
			?>
765
			<div class="tgmpa wrap">
766
				<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
767
				<?php $plugin_table->prepare_items(); ?>
768
769
				<?php
770
				if ( ! empty( $this->message ) && is_string( $this->message ) ) {
771
					echo wp_kses_post( $this->message );
772
				}
773
				?>
774
				<?php $plugin_table->views(); ?>
775
776
				<form id="tgmpa-plugins" action="" method="post">
777
					<input type="hidden" name="tgmpa-page" value="<?php echo esc_attr( $this->menu ); ?>" />
778
					<input type="hidden" name="plugin_status" value="<?php echo esc_attr( $plugin_table->view_context ); ?>" />
779
					<?php $plugin_table->display(); ?>
780
				</form>
781
			</div>
782
			<?php
783
		}
784
785
		/**
786
		 * Installs, updates or activates a plugin depending on the action link clicked by the user.
787
		 *
788
		 * Checks the $_GET variable to see which actions have been
789
		 * passed and responds with the appropriate method.
790
		 *
791
		 * Uses WP_Filesystem to process and handle the plugin installation
792
		 * method.
793
		 *
794
		 * @since 1.0.0
795
		 *
796
		 * @uses WP_Filesystem
797
		 * @uses WP_Error
798
		 * @uses WP_Upgrader
799
		 * @uses Plugin_Upgrader
800
		 * @uses Plugin_Installer_Skin
801
		 * @uses Plugin_Upgrader_Skin
802
		 *
803
		 * @return boolean True on success, false on failure.
804
		 */
805
		protected function do_plugin_install() {
0 ignored issues
show
Coding Style introduced by jrfnl
function do_plugin_install() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
806
			if ( empty( $_GET['plugin'] ) ) {
807
				return false;
808
			}
809
810
			// All plugin information will be stored in an array for processing.
811
			$slug = $this->sanitize_key( urldecode( $_GET['plugin'] ) );
812
813
			if ( ! isset( $this->plugins[ $slug ] ) ) {
814
				return false;
815
			}
816
817
			// Was an install or upgrade action link clicked?
818
			if ( ( isset( $_GET['tgmpa-install'] ) && 'install-plugin' === $_GET['tgmpa-install'] ) || ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) ) {
819
820
				$install_type = 'install';
821
				if ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) {
822
					$install_type = 'update';
823
				}
824
825
				check_admin_referer( 'tgmpa-' . $install_type, 'tgmpa-nonce' );
826
827
				// Pass necessary information via URL if WP_Filesystem is needed.
828
				$url = wp_nonce_url(
829
					add_query_arg(
830
						array(
831
							'plugin'                 => urlencode( $slug ),
832
							'tgmpa-' . $install_type => $install_type . '-plugin',
833
						),
834
						$this->get_tgmpa_url()
835
					),
836
					'tgmpa-' . $install_type,
837
					'tgmpa-nonce'
838
				);
839
840
				$method = ''; // Leave blank so WP_Filesystem can populate it as necessary.
841
842
				$creds = request_filesystem_credentials( esc_url_raw( $url ), $method, false, false, array() );
843
				if ( false === $creds ) {
844
					return true;
845
				}
846
847 View Code Duplication
				if ( ! WP_Filesystem( $creds ) ) {
0 ignored issues
show
Duplication introduced by jrfnl
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...
848
					request_filesystem_credentials( esc_url_raw( $url ), $method, true, false, array() ); // Setup WP_Filesystem.
849
					return true;
850
				}
851
852
				/* If we arrive here, we have the filesystem. */
853
854
				// Prep variables for Plugin_Installer_Skin class.
855
				$extra         = array();
856
				$extra['slug'] = $slug; // Needed for potentially renaming of directory name.
857
				$source        = $this->get_download_url( $slug );
858
				$api           = ( 'repo' === $this->plugins[ $slug ]['source_type'] ) ? $this->get_plugins_api( $slug ) : null;
859
				$api           = ( false !== $api ) ? $api : null;
860
861
				$url = add_query_arg(
862
					array(
863
						'action' => $install_type . '-plugin',
864
						'plugin' => urlencode( $slug ),
865
					),
866
					'update.php'
867
				);
868
869
				if ( ! class_exists( 'Plugin_Upgrader', false ) ) {
870
					require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
871
				}
872
873
				$title     = ( 'update' === $install_type ) ? $this->strings['updating'] : $this->strings['installing'];
874
				$skin_args = array(
875
					'type'   => ( 'bundled' !== $this->plugins[ $slug ]['source_type'] ) ? 'web' : 'upload',
876
					'title'  => sprintf( $title, $this->plugins[ $slug ]['name'] ),
877
					'url'    => esc_url_raw( $url ),
878
					'nonce'  => $install_type . '-plugin_' . $slug,
879
					'plugin' => '',
880
					'api'    => $api,
881
					'extra'  => $extra,
882
				);
883
				unset( $title );
884
885
				if ( 'update' === $install_type ) {
886
					$skin_args['plugin'] = $this->plugins[ $slug ]['file_path'];
887
					$skin                = new Plugin_Upgrader_Skin( $skin_args );
888
				} else {
889
					$skin = new Plugin_Installer_Skin( $skin_args );
890
				}
891
892
				// Create a new instance of Plugin_Upgrader.
893
				$upgrader = new Plugin_Upgrader( $skin );
894
895
				// Perform the action and install the plugin from the $source urldecode().
896
				add_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1, 3 );
897
898
				if ( 'update' === $install_type ) {
899
					// Inject our info into the update transient.
900
					$to_inject                    = array(
901
						$slug => $this->plugins[ $slug ],
902
					);
903
					$to_inject[ $slug ]['source'] = $source;
904
					$this->inject_update_info( $to_inject );
905
906
					$upgrader->upgrade( $this->plugins[ $slug ]['file_path'] );
907
				} else {
908
					$upgrader->install( $source );
909
				}
910
911
				remove_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1 );
912
913
				// Make sure we have the correct file path now the plugin is installed/updated.
914
				$this->populate_file_path( $slug );
915
916
				// Only activate plugins if the config option is set to true and the plugin isn't
917
				// already active (upgrade).
918
				if ( $this->is_automatic && ! $this->is_plugin_active( $slug ) ) {
919
					$plugin_activate = $upgrader->plugin_info(); // Grab the plugin info from the Plugin_Upgrader method.
920
					if ( false === $this->activate_single_plugin( $plugin_activate, $slug, true ) ) {
921
						return true; // Finish execution of the function early as we encountered an error.
922
					}
923
				}
924
925
				$this->show_tgmpa_version();
926
927
				// Display message based on if all plugins are now active or not.
928
				if ( $this->is_tgmpa_complete() ) {
929
					echo '<p>', sprintf( esc_html( $this->strings['complete'] ), '<a href="' . esc_url( self_admin_url() ) . '">' . esc_html( $this->strings['dashboard'] ) . '</a>' ), '</p>';
930
					echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>';
931
				} else {
932
					echo '<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>';
933
				}
934
935
				return true;
936
			} elseif ( isset( $this->plugins[ $slug ]['file_path'], $_GET['tgmpa-activate'] ) && 'activate-plugin' === $_GET['tgmpa-activate'] ) {
937
				// Activate action link was clicked.
938
				check_admin_referer( 'tgmpa-activate', 'tgmpa-nonce' );
939
940
				if ( false === $this->activate_single_plugin( $this->plugins[ $slug ]['file_path'], $slug ) ) {
941
					return true; // Finish execution of the function early as we encountered an error.
942
				}
943
			}
944
945
			return false;
946
		}
947
948
		/**
949
		 * Inject information into the 'update_plugins' site transient as WP checks that before running an update.
950
		 *
951
		 * @since 2.5.0
952
		 *
953
		 * @param array $plugins The plugin information for the plugins which are to be updated.
954
		 */
955
		public function inject_update_info( $plugins ) {
956
			$repo_updates = get_site_transient( 'update_plugins' );
957
958
			if ( ! is_object( $repo_updates ) ) {
959
				$repo_updates = new stdClass();
960
			}
961
962
			foreach ( $plugins as $slug => $plugin ) {
963
				$file_path = $plugin['file_path'];
964
965
				if ( empty( $repo_updates->response[ $file_path ] ) ) {
966
					$repo_updates->response[ $file_path ] = new stdClass();
967
				}
968
969
				// We only really need to set package, but let's do all we can in case WP changes something.
970
				$repo_updates->response[ $file_path ]->slug        = $slug;
971
				$repo_updates->response[ $file_path ]->plugin      = $file_path;
972
				$repo_updates->response[ $file_path ]->new_version = $plugin['version'];
973
				$repo_updates->response[ $file_path ]->package     = $plugin['source'];
974
				if ( empty( $repo_updates->response[ $file_path ]->url ) && ! empty( $plugin['external_url'] ) ) {
975
					$repo_updates->response[ $file_path ]->url = $plugin['external_url'];
976
				}
977
			}
978
979
			set_site_transient( 'update_plugins', $repo_updates );
980
		}
981
982
		/**
983
		 * Adjust the plugin directory name if necessary.
984
		 *
985
		 * The final destination directory of a plugin is based on the subdirectory name found in the
986
		 * (un)zipped source. In some cases - most notably GitHub repository plugin downloads -, this
987
		 * subdirectory name is not the same as the expected slug and the plugin will not be recognized
988
		 * as installed. This is fixed by adjusting the temporary unzipped source subdirectory name to
989
		 * the expected plugin slug.
990
		 *
991
		 * @since 2.5.0
992
		 *
993
		 * @param string       $source        Path to upgrade/zip-file-name.tmp/subdirectory/.
994
		 * @param string       $remote_source Path to upgrade/zip-file-name.tmp.
995
		 * @param \WP_Upgrader $upgrader      Instance of the upgrader which installs the plugin.
996
		 * @return string $source
997
		 */
998
		public function maybe_adjust_source_dir( $source, $remote_source, $upgrader ) {
999
			if ( ! $this->is_tgmpa_page() || ! is_object( $GLOBALS['wp_filesystem'] ) ) {
1000
				return $source;
1001
			}
1002
1003
			// Check for single file plugins.
1004
			$source_files = array_keys( $GLOBALS['wp_filesystem']->dirlist( $remote_source ) );
1005
			if ( 1 === count( $source_files ) && false === $GLOBALS['wp_filesystem']->is_dir( $source ) ) {
1006
				return $source;
1007
			}
1008
1009
			// Multi-file plugin, let's see if the directory is correctly named.
1010
			$desired_slug = '';
1011
1012
			// Figure out what the slug is supposed to be.
1013
			if ( false === $upgrader->bulk && ! empty( $upgrader->skin->options['extra']['slug'] ) ) {
1014
				$desired_slug = $upgrader->skin->options['extra']['slug'];
1015
			} else {
1016
				// Bulk installer contains less info, so fall back on the info registered here.
1017
				foreach ( $this->plugins as $slug => $plugin ) {
1018
					if ( ! empty( $upgrader->skin->plugin_names[ $upgrader->skin->i ] ) && $plugin['name'] === $upgrader->skin->plugin_names[ $upgrader->skin->i ] ) {
1019
						$desired_slug = $slug;
1020
						break;
1021
					}
1022
				}
1023
				unset( $slug, $plugin );
1024
			}
1025
1026
			if ( ! empty( $desired_slug ) ) {
1027
				$subdir_name = untrailingslashit( str_replace( trailingslashit( $remote_source ), '', $source ) );
1028
1029
				if ( ! empty( $subdir_name ) && $subdir_name !== $desired_slug ) {
1030
					$from_path = untrailingslashit( $source );
1031
					$to_path   = trailingslashit( $remote_source ) . $desired_slug;
1032
1033
					if ( true === $GLOBALS['wp_filesystem']->move( $from_path, $to_path ) ) {
1034
						return trailingslashit( $to_path );
1035 View Code Duplication
					} else {
1036
						return new WP_Error(
1037
							'rename_failed',
1038
							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' ),
1039
							array(
1040
								'found'    => $subdir_name,
1041
								'expected' => $desired_slug,
1042
							)
1043
						);
1044
					}
1045 View Code Duplication
				} elseif ( empty( $subdir_name ) ) {
1046
					return new WP_Error(
1047
						'packaged_wrong',
1048
						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' ),
1049
						array(
1050
							'found'    => $subdir_name,
1051
							'expected' => $desired_slug,
1052
						)
1053
					);
1054
				}
1055
			}
1056
1057
			return $source;
1058
		}
1059
1060
		/**
1061
		 * Activate a single plugin and send feedback about the result to the screen.
1062
		 *
1063
		 * @since 2.5.0
1064
		 *
1065
		 * @param string $file_path Path within wp-plugins/ to main plugin file.
1066
		 * @param string $slug      Plugin slug.
1067
		 * @param bool   $automatic Whether this is an automatic activation after an install. Defaults to false.
1068
		 *                          This determines the styling of the output messages.
1069
		 * @return bool False if an error was encountered, true otherwise.
1070
		 */
1071
		protected function activate_single_plugin( $file_path, $slug, $automatic = false ) {
0 ignored issues
show
Coding Style introduced by jrfnl
function activate_single_plugin() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
1072
			if ( $this->can_plugin_activate( $slug ) ) {
1073
				$activate = activate_plugin( $file_path );
1074
1075
				if ( is_wp_error( $activate ) ) {
1076
					echo '<div id="message" class="error"><p>', wp_kses_post( $activate->get_error_message() ), '</p></div>',
1077
						'<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>';
1078
1079
					return false; // End it here if there is an error with activation.
1080
				} else {
1081
					if ( ! $automatic ) {
1082
						// Make sure message doesn't display again if bulk activation is performed
1083
						// immediately after a single activation.
1084
						if ( ! isset( $_POST['action'] ) ) { // WPCS: CSRF OK.
1085
							echo '<div id="message" class="updated"><p>', esc_html( $this->strings['activated_successfully'] ), ' <strong>', esc_html( $this->plugins[ $slug ]['name'] ), '.</strong></p></div>';
1086
						}
1087
					} else {
1088
						// Simpler message layout for use on the plugin install page.
1089
						echo '<p>', esc_html( $this->strings['plugin_activated'] ), '</p>';
1090
					}
1091
				}
1092 View Code Duplication
			} elseif ( $this->is_plugin_active( $slug ) ) {
1093
				// No simpler message format provided as this message should never be encountered
1094
				// on the plugin install page.
1095
				echo '<div id="message" class="error"><p>',
1096
					sprintf(
1097
						esc_html( $this->strings['plugin_already_active'] ),
1098
						'<strong>' . esc_html( $this->plugins[ $slug ]['name'] ) . '</strong>'
1099
					),
1100
					'</p></div>';
1101
			} elseif ( $this->does_plugin_require_update( $slug ) ) {
1102
				if ( ! $automatic ) {
1103
					// Make sure message doesn't display again if bulk activation is performed
1104
					// immediately after a single activation.
1105 View Code Duplication
					if ( ! isset( $_POST['action'] ) ) { // WPCS: CSRF OK.
1106
						echo '<div id="message" class="error"><p>',
1107
							sprintf(
1108
								esc_html( $this->strings['plugin_needs_higher_version'] ),
1109
								'<strong>' . esc_html( $this->plugins[ $slug ]['name'] ) . '</strong>'
1110
							),
1111
							'</p></div>';
1112
					}
1113
				} else {
1114
					// Simpler message layout for use on the plugin install page.
1115
					echo '<p>', sprintf( esc_html( $this->strings['plugin_needs_higher_version'] ), esc_html( $this->plugins[ $slug ]['name'] ) ), '</p>';
1116
				}
1117
			}
1118
1119
			return true;
1120
		}
1121
1122
		/**
1123
		 * Echoes required plugin notice.
1124
		 *
1125
		 * Outputs a message telling users that a specific plugin is required for
1126
		 * their theme. If appropriate, it includes a link to the form page where
1127
		 * users can install and activate the plugin.
1128
		 *
1129
		 * Returns early if we're on the Install page.
1130
		 *
1131
		 * @since 1.0.0
1132
		 *
1133
		 * @global object $current_screen
1134
		 *
1135
		 * @return null Returns early if we're on the Install page.
1136
		 */
1137
		public function notices() {
1138
			// Remove nag on the install page / Return early if the nag message has been dismissed or user < author.
1139
			if ( ( $this->is_tgmpa_page() || $this->is_core_update_page() ) || get_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, true ) || ! current_user_can( apply_filters( 'tgmpa_show_admin_notice_capability', 'publish_posts' ) ) ) {
1140
				return;
1141
			}
1142
1143
			// Store for the plugin slugs by message type.
1144
			$message = array();
1145
1146
			// Initialize counters used to determine plurality of action link texts.
1147
			$install_link_count          = 0;
1148
			$update_link_count           = 0;
1149
			$activate_link_count         = 0;
1150
			$total_required_action_count = 0;
1151
1152
			foreach ( $this->plugins as $slug => $plugin ) {
1153
				if ( $this->is_plugin_active( $slug ) && false === $this->does_plugin_have_update( $slug ) ) {
1154
					continue;
1155
				}
1156
1157
				if ( ! $this->is_plugin_installed( $slug ) ) {
1158
					if ( current_user_can( 'install_plugins' ) ) {