TGMPA_List_Table   F
last analyzed

Complexity

Total Complexity 119

Size/Duplication

Total Lines 928
Duplicated Lines 3.02 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 28
loc 928
rs 1.672
c 0
b 0
f 0
wmc 119
lcom 1
cbo 2

26 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 17 3
A get_table_classes() 0 3 1
A _gather_plugin_data() 0 46 4
B categorize_plugins_to_views() 0 31 7
A set_view_totals() 0 5 2
A get_plugin_advise_type_text() 0 7 2
A get_plugin_source_type_text() 0 17 4
B get_plugin_status_text() 0 34 8
A sort_table_items() 0 13 2
B get_views() 0 43 9
A column_default() 0 3 1
A column_cb() 0 8 1
A column_plugin() 0 7 1
B column_version() 0 44 10
A no_items() 0 4 1
A get_columns() 0 15 3
A get_default_primary_column_name() 0 3 1
A get_primary_column_name() 0 7 2
B get_row_actions() 0 46 8
A single_row() 0 15 1
A wp_plugin_update_row() 0 15 2
A extra_tablenav() 0 5 2
B get_bulk_actions() 0 21 7
F process_bulk_actions() 28 234 34
A prepare_items() 0 15 2
A _get_plugin_data_from_name() 0 5 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like TGMPA_List_Table often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use TGMPA_List_Table, and based on these observations, apply Extract Interface, too.

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
			// phpcs:ignore Squiz.PHP.NonExecutableCode.ReturnNotRequired -- See explanation above.
298
			return;
299
		}
300
301
		/**
302
		 * Magic method to get the value of a protected property outside of this class context.
303
		 *
304
		 * @since 2.5.2
305
		 *
306
		 * @param string $name Name of an inaccessible property.
307
		 * @return mixed The property value.
308
		 */
309
		public function __get( $name ) {
310
			return $this->{$name};
311
		}
312
313
		/**
314
		 * Initialise the interactions between this class and WordPress.
315
		 *
316
		 * Hooks in three new methods for the class: admin_menu, notices and styles.
317
		 *
318
		 * @since 2.0.0
319
		 *
320
		 * @see TGM_Plugin_Activation::admin_menu()
321
		 * @see TGM_Plugin_Activation::notices()
322
		 * @see TGM_Plugin_Activation::styles()
323
		 */
324
		public function init() {
325
			/**
326
			 * By default TGMPA only loads on the WP back-end and not in an Ajax call. Using this filter
327
			 * you can overrule that behaviour.
328
			 *
329
			 * @since 2.5.0
330
			 *
331
			 * @param bool $load Whether or not TGMPA should load.
332
			 *                   Defaults to the return of `is_admin() && ! defined( 'DOING_AJAX' )`.
333
			 */
334
			if ( true !== apply_filters( 'tgmpa_load', ( is_admin() && ! defined( 'DOING_AJAX' ) ) ) ) {
335
				return;
336
			}
337
338
			// Load class strings.
339
			$this->strings = array(
340
				'page_title'                      => __( 'Install Required Plugins', 'tgmpa' ),
341
				'menu_title'                      => __( 'Install Plugins', 'tgmpa' ),
342
				/* translators: %s: plugin name. */
343
				'installing'                      => __( 'Installing Plugin: %s', 'tgmpa' ),
344
				/* translators: %s: plugin name. */
345
				'updating'                        => __( 'Updating Plugin: %s', 'tgmpa' ),
346
				'oops'                            => __( 'Something went wrong with the plugin API.', 'tgmpa' ),
347
				/* translators: 1: plugin name(s). */
348
				'notice_can_install_required'     => _n_noop(
349
					'This theme requires the following plugin: %1$s.',
350
					'This theme requires the following plugins: %1$s.',
351
					'tgmpa'
352
				),
353
				/* translators: 1: plugin name(s). */
354
				'notice_can_install_recommended'  => _n_noop(
355
					'This theme recommends the following plugin: %1$s.',
356
					'This theme recommends the following plugins: %1$s.',
357
					'tgmpa'
358
				),
359
				/* translators: 1: plugin name(s). */
360
				'notice_ask_to_update'            => _n_noop(
361
					'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.',
362
					'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.',
363
					'tgmpa'
364
				),
365
				/* translators: 1: plugin name(s). */
366
				'notice_ask_to_update_maybe'      => _n_noop(
367
					'There is an update available for: %1$s.',
368
					'There are updates available for the following plugins: %1$s.',
369
					'tgmpa'
370
				),
371
				/* translators: 1: plugin name(s). */
372
				'notice_can_activate_required'    => _n_noop(
373
					'The following required plugin is currently inactive: %1$s.',
374
					'The following required plugins are currently inactive: %1$s.',
375
					'tgmpa'
376
				),
377
				/* translators: 1: plugin name(s). */
378
				'notice_can_activate_recommended' => _n_noop(
379
					'The following recommended plugin is currently inactive: %1$s.',
380
					'The following recommended plugins are currently inactive: %1$s.',
381
					'tgmpa'
382
				),
383
				'install_link'                    => _n_noop(
384
					'Begin installing plugin',
385
					'Begin installing plugins',
386
					'tgmpa'
387
				),
388
				'update_link'                     => _n_noop(
389
					'Begin updating plugin',
390
					'Begin updating plugins',
391
					'tgmpa'
392
				),
393
				'activate_link'                   => _n_noop(
394
					'Begin activating plugin',
395
					'Begin activating plugins',
396
					'tgmpa'
397
				),
398
				'return'                          => __( 'Return to Required Plugins Installer', 'tgmpa' ),
399
				'dashboard'                       => __( 'Return to the Dashboard', 'tgmpa' ),
400
				'plugin_activated'                => __( 'Plugin activated successfully.', 'tgmpa' ),
401
				'activated_successfully'          => __( 'The following plugin was activated successfully:', 'tgmpa' ),
402
				/* translators: 1: plugin name. */
403
				'plugin_already_active'           => __( 'No action taken. Plugin %1$s was already active.', 'tgmpa' ),
404
				/* translators: 1: plugin name. */
405
				'plugin_needs_higher_version'     => __( 'Plugin not activated. A higher version of %s is needed for this theme. Please update the plugin.', 'tgmpa' ),
406
				/* translators: 1: dashboard link. */
407
				'complete'                        => __( 'All plugins installed and activated successfully. %1$s', 'tgmpa' ),
408
				'dismiss'                         => __( 'Dismiss this notice', 'tgmpa' ),
409
				'notice_cannot_install_activate'  => __( 'There are one or more required or recommended plugins to install, update or activate.', 'tgmpa' ),
410
				'contact_admin'                   => __( 'Please contact the administrator of this site for help.', 'tgmpa' ),
411
			);
412
413
			do_action( 'tgmpa_register' );
414
415
			/* After this point, the plugins should be registered and the configuration set. */
416
417
			// Proceed only if we have plugins to handle.
418
			if ( empty( $this->plugins ) || ! is_array( $this->plugins ) ) {
419
				return;
420
			}
421
422
			// Set up the menu and notices if we still have outstanding actions.
423
			if ( true !== $this->is_tgmpa_complete() ) {
424
				// Sort the plugins.
425
				array_multisort( $this->sort_order, SORT_ASC, $this->plugins );
426
427
				add_action( 'admin_menu', array( $this, 'admin_menu' ) );
428
				add_action( 'admin_head', array( $this, 'dismiss' ) );
429
430
				// Prevent the normal links from showing underneath a single install/update page.
431
				add_filter( 'install_plugin_complete_actions', array( $this, 'actions' ) );
432
				add_filter( 'update_plugin_complete_actions', array( $this, 'actions' ) );
433
434
				if ( $this->has_notices ) {
435
					add_action( 'admin_notices', array( $this, 'notices' ) );
436
					add_action( 'admin_init', array( $this, 'admin_init' ), 1 );
437
					add_action( 'admin_enqueue_scripts', array( $this, 'thickbox' ) );
438
				}
439
			}
440
441
			// If needed, filter plugin action links.
442
			add_action( 'load-plugins.php', array( $this, 'add_plugin_action_link_filters' ), 1 );
443
444
			// Make sure things get reset on switch theme.
445
			add_action( 'switch_theme', array( $this, 'flush_plugins_cache' ) );
446
447
			if ( $this->has_notices ) {
448
				add_action( 'switch_theme', array( $this, 'update_dismiss' ) );
449
			}
450
451
			// Setup the force activation hook.
452
			if ( true === $this->has_forced_activation ) {
453
				add_action( 'admin_init', array( $this, 'force_activation' ) );
454
			}
455
456
			// Setup the force deactivation hook.
457
			if ( true === $this->has_forced_deactivation ) {
458
				add_action( 'switch_theme', array( $this, 'force_deactivation' ) );
459
			}
460
461
			// Add CSS for the TGMPA admin page.
462
			add_action( 'admin_head', array( $this, 'admin_css' ) );
463
		}
464
465
		/**
466
		 * Load translations.
467
		 *
468
		 * @since 2.6.0
469
		 *
470
		 * (@internal Uses `load_theme_textdomain()` rather than `load_plugin_textdomain()` to
471
		 * get round the different ways of handling the path and deprecated notices being thrown
472
		 * and such. For plugins, the actual file name will be corrected by a filter.}}
473
		 *
474
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
475
		 * generator on the website.}}
476
		 */
477
		public function load_textdomain() {
478
			if ( is_textdomain_loaded( 'tgmpa' ) ) {
479
				return;
480
			}
481
482
			if ( false !== strpos( __FILE__, WP_PLUGIN_DIR ) || false !== strpos( __FILE__, WPMU_PLUGIN_DIR ) ) {
483
				// Plugin, we'll need to adjust the file name.
484
				add_action( 'load_textdomain_mofile', array( $this, 'correct_plugin_mofile' ), 10, 2 );
485
				load_theme_textdomain( 'tgmpa', dirname( __FILE__ ) . '/languages' );
486
				remove_action( 'load_textdomain_mofile', array( $this, 'correct_plugin_mofile' ), 10 );
487
			} else {
488
				load_theme_textdomain( 'tgmpa', dirname( __FILE__ ) . '/languages' );
489
			}
490
		}
491
492
		/**
493
		 * Correct the .mo file name for (must-use) plugins.
494
		 *
495
		 * Themese use `/path/{locale}.mo` while plugins use `/path/{text-domain}-{locale}.mo`.
496
		 *
497
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
498
		 * generator on the website.}}
499
		 *
500
		 * @since 2.6.0
501
		 *
502
		 * @param string $mofile Full path to the target mofile.
503
		 * @param string $domain The domain for which a language file is being loaded.
504
		 * @return string $mofile
505
		 */
506
		public function correct_plugin_mofile( $mofile, $domain ) {
507
			// Exit early if not our domain (just in case).
508
			if ( 'tgmpa' !== $domain ) {
509
				return $mofile;
510
			}
511
			return preg_replace( '`/([a-z]{2}_[A-Z]{2}.mo)$`', '/tgmpa-$1', $mofile );
512
		}
513
514
		/**
515
		 * Potentially overload the fall-back translation file for the current language.
516
		 *
517
		 * WP, by default since WP 3.7, will load a local translation first and if none
518
		 * can be found, will try and find a translation in the /wp-content/languages/ directory.
519
		 * As this library is theme/plugin agnostic, translation files for TGMPA can exist both
520
		 * in the WP_LANG_DIR /plugins/ subdirectory as well as in the /themes/ subdirectory.
521
		 *
522
		 * This method makes sure both directories are checked.
523
		 *
524
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
525
		 * generator on the website.}}
526
		 *
527
		 * @since 2.6.0
528
		 *
529
		 * @param string $mofile Full path to the target mofile.
530
		 * @param string $domain The domain for which a language file is being loaded.
531
		 * @return string $mofile
532
		 */
533
		public function overload_textdomain_mofile( $mofile, $domain ) {
534
			// Exit early if not our domain, not a WP_LANG_DIR load or if the file exists and is readable.
535
			if ( 'tgmpa' !== $domain || false === strpos( $mofile, WP_LANG_DIR ) || @is_readable( $mofile ) ) {
536
				return $mofile;
537
			}
538
539
			// Current fallback file is not valid, let's try the alternative option.
540
			if ( false !== strpos( $mofile, '/themes/' ) ) {
541
				return str_replace( '/themes/', '/plugins/', $mofile );
542
			} elseif ( false !== strpos( $mofile, '/plugins/' ) ) {
543
				return str_replace( '/plugins/', '/themes/', $mofile );
544
			} else {
545
				return $mofile;
546
			}
547
		}
548
549
		/**
550
		 * Hook in plugin action link filters for the WP native plugins page.
551
		 *
552
		 * - Prevent activation of plugins which don't meet the minimum version requirements.
553
		 * - Prevent deactivation of force-activated plugins.
554
		 * - Add update notice if update available.
555
		 *
556
		 * @since 2.5.0
557
		 */
558
		public function add_plugin_action_link_filters() {
559
			foreach ( $this->plugins as $slug => $plugin ) {
560
				if ( false === $this->can_plugin_activate( $slug ) ) {
561
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_activate' ), 20 );
562
				}
563
564
				if ( true === $plugin['force_activation'] ) {
565
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_deactivate' ), 20 );
566
				}
567
568
				if ( false !== $this->does_plugin_require_update( $slug ) ) {
569
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_update' ), 20 );
570
				}
571
			}
572
		}
573
574
		/**
575
		 * Remove the 'Activate' link on the WP native plugins page if the plugin does not meet the
576
		 * minimum version requirements.
577
		 *
578
		 * @since 2.5.0
579
		 *
580
		 * @param array $actions Action links.
581
		 * @return array
582
		 */
583
		public function filter_plugin_action_links_activate( $actions ) {
584
			unset( $actions['activate'] );
585
586
			return $actions;
587
		}
588
589
		/**
590
		 * Remove the 'Deactivate' link on the WP native plugins page if the plugin has been set to force activate.
591
		 *
592
		 * @since 2.5.0
593
		 *
594
		 * @param array $actions Action links.
595
		 * @return array
596
		 */
597
		public function filter_plugin_action_links_deactivate( $actions ) {
598
			unset( $actions['deactivate'] );
599
600
			return $actions;
601
		}
602
603
		/**
604
		 * Add a 'Requires update' link on the WP native plugins page if the plugin does not meet the
605
		 * minimum version requirements.
606
		 *
607
		 * @since 2.5.0
608
		 *
609
		 * @param array $actions Action links.
610
		 * @return array
611
		 */
612
		public function filter_plugin_action_links_update( $actions ) {
613
			$actions['update'] = sprintf(
614
				'<a href="%1$s" title="%2$s" class="edit">%3$s</a>',
615
				esc_url( $this->get_tgmpa_status_url( 'update' ) ),
616
				esc_attr__( 'This plugin needs to be updated to be compatible with your theme.', 'tgmpa' ),
617
				esc_html__( 'Update Required', 'tgmpa' )
618
			);
619
620
			return $actions;
621
		}
622
623
		/**
624
		 * Handles calls to show plugin information via links in the notices.
625
		 *
626
		 * We get the links in the admin notices to point to the TGMPA page, rather
627
		 * than the typical plugin-install.php file, so we can prepare everything
628
		 * beforehand.
629
		 *
630
		 * WP does not make it easy to show the plugin information in the thickbox -
631
		 * here we have to require a file that includes a function that does the
632
		 * main work of displaying it, enqueue some styles, set up some globals and
633
		 * finally call that function before exiting.
634
		 *
635
		 * Down right easy once you know how...
636
		 *
637
		 * Returns early if not the TGMPA page.
638
		 *
639
		 * @since 2.1.0
640
		 *
641
		 * @global string $tab Used as iframe div class names, helps with styling
642
		 * @global string $body_id Used as the iframe body ID, helps with styling
643
		 *
644
		 * @return null Returns early if not the TGMPA page.
645
		 */
646
		public function admin_init() {
647
			if ( ! $this->is_tgmpa_page() ) {
648
				return;
649
			}
650
651
			if ( isset( $_REQUEST['tab'] ) && 'plugin-information' === $_REQUEST['tab'] ) {
652
				// Needed for install_plugin_information().
653
				require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
654
655
				wp_enqueue_style( 'plugin-install' );
656
657
				global $tab, $body_id;
658
				// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- WP requirement.
659
				$body_id = 'plugin-information';
660
661
				// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Overriding the WP global is the point.
662
				$tab = 'plugin-information';
663
664
				install_plugin_information();
665
666
				exit;
667
			}
668
		}
669
670
		/**
671
		 * Enqueue thickbox scripts/styles for plugin info.
672
		 *
673
		 * Thickbox is not automatically included on all admin pages, so we must
674
		 * manually enqueue it for those pages.
675
		 *
676
		 * Thickbox is only loaded if the user has not dismissed the admin
677
		 * notice or if there are any plugins left to install and activate.
678
		 *
679
		 * @since 2.1.0
680
		 */
681
		public function thickbox() {
682
			if ( ! get_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, true ) ) {
683
				add_thickbox();
684
			}
685
		}
686
687
		/**
688
		 * Adds submenu page if there are plugin actions to take.
689
		 *
690
		 * This method adds the submenu page letting users know that a required
691
		 * plugin needs to be installed.
692
		 *
693
		 * This page disappears once the plugin has been installed and activated.
694
		 *
695
		 * @since 1.0.0
696
		 *
697
		 * @see TGM_Plugin_Activation::init()
698
		 * @see TGM_Plugin_Activation::install_plugins_page()
699
		 *
700
		 * @return null Return early if user lacks capability to install a plugin.
701
		 */
702
		public function admin_menu() {
703
			// Make sure privileges are correct to see the page.
704
			if ( ! current_user_can( 'install_plugins' ) ) {
705
				return;
706
			}
707
708
			$args = apply_filters(
709
				'tgmpa_admin_menu_args',
710
				array(
711
					'parent_slug' => $this->parent_slug,                     // Parent Menu slug.
712
					'page_title'  => $this->strings['page_title'],           // Page title.
713
					'menu_title'  => $this->strings['menu_title'],           // Menu title.
714
					'capability'  => $this->capability,                      // Capability.
715
					'menu_slug'   => $this->menu,                            // Menu slug.
716
					'function'    => array( $this, 'install_plugins_page' ), // Callback.
717
				)
718
			);
719
720
			$this->add_admin_menu( $args );
721
		}
722
723
		/**
724
		 * Add the menu item.
725
		 *
726
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
727
		 * generator on the website.}}
728
		 *
729
		 * @since 2.5.0
730
		 *
731
		 * @param array $args Menu item configuration.
732
		 */
733
		protected function add_admin_menu( array $args ) {
734
			if ( has_filter( 'tgmpa_admin_menu_use_add_theme_page' ) ) {
735
				_deprecated_function( 'The "tgmpa_admin_menu_use_add_theme_page" filter', '2.5.0', esc_html__( 'Set the parent_slug config variable instead.', 'tgmpa' ) );
736
			}
737
738
			if ( 'themes.php' === $this->parent_slug ) {
739
				$this->page_hook = call_user_func( 'add_theme_page', $args['page_title'], $args['menu_title'], $args['capability'], $args['menu_slug'], $args['function'] );
740
			} else {
741
				$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'] );
742
			}
743
		}
744
745
		/**
746
		 * Echoes plugin installation form.
747
		 *
748
		 * This method is the callback for the admin_menu method function.
749
		 * This displays the admin page and form area where the user can select to install and activate the plugin.
750
		 * Aborts early if we're processing a plugin installation action.
751
		 *
752
		 * @since 1.0.0
753
		 *
754
		 * @return null Aborts early if we're processing a plugin installation action.
755
		 */
756
		public function install_plugins_page() {
757
			// Store new instance of plugin table in object.
758
			$plugin_table = new TGMPA_List_Table();
759
760
			// Return early if processing a plugin installation action.
761
			if ( ( ( 'tgmpa-bulk-install' === $plugin_table->current_action() || 'tgmpa-bulk-update' === $plugin_table->current_action() ) && $plugin_table->process_bulk_actions() ) || $this->do_plugin_install() ) {
762
				return;
763
			}
764
765
			// Force refresh of available plugin information so we'll know about manual updates/deletes.
766
			wp_clean_plugins_cache( false );
767
768
			?>
769
			<div class="tgmpa wrap">
770
				<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
771
				<?php $plugin_table->prepare_items(); ?>
772
773
				<?php
774
				if ( ! empty( $this->message ) && is_string( $this->message ) ) {
775
					echo wp_kses_post( $this->message );
776
				}
777
				?>
778
				<?php $plugin_table->views(); ?>
779
780
				<form id="tgmpa-plugins" action="" method="post">
781
					<input type="hidden" name="tgmpa-page" value="<?php echo esc_attr( $this->menu ); ?>" />
782
					<input type="hidden" name="plugin_status" value="<?php echo esc_attr( $plugin_table->view_context ); ?>" />
783
					<?php $plugin_table->display(); ?>
784
				</form>
785
			</div>
786
			<?php
787
		}
788
789
		/**
790
		 * Installs, updates or activates a plugin depending on the action link clicked by the user.
791
		 *
792
		 * Checks the $_GET variable to see which actions have been
793
		 * passed and responds with the appropriate method.
794
		 *
795
		 * Uses WP_Filesystem to process and handle the plugin installation
796
		 * method.
797
		 *
798
		 * @since 1.0.0
799
		 *
800
		 * @uses WP_Filesystem
801
		 * @uses WP_Error
802
		 * @uses WP_Upgrader
803
		 * @uses Plugin_Upgrader
804
		 * @uses Plugin_Installer_Skin
805
		 * @uses Plugin_Upgrader_Skin
806
		 *
807
		 * @return boolean True on success, false on failure.
808
		 */
809
		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...
810
			if ( empty( $_GET['plugin'] ) ) {
811
				return false;
812
			}
813
814
			// All plugin information will be stored in an array for processing.
815
			$slug = $this->sanitize_key( urldecode( $_GET['plugin'] ) );
816
817
			if ( ! isset( $this->plugins[ $slug ] ) ) {
818
				return false;
819
			}
820
821
			// Was an install or upgrade action link clicked?
822
			if ( ( isset( $_GET['tgmpa-install'] ) && 'install-plugin' === $_GET['tgmpa-install'] ) || ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) ) {
823
824
				$install_type = 'install';
825
				if ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) {
826
					$install_type = 'update';
827
				}
828
829
				check_admin_referer( 'tgmpa-' . $install_type, 'tgmpa-nonce' );
830
831
				// Pass necessary information via URL if WP_Filesystem is needed.
832
				$url = wp_nonce_url(
833
					add_query_arg(
834
						array(
835
							'plugin'                 => urlencode( $slug ),
836
							'tgmpa-' . $install_type => $install_type . '-plugin',
837
						),
838
						$this->get_tgmpa_url()
839
					),
840
					'tgmpa-' . $install_type,
841
					'tgmpa-nonce'
842
				);
843
844
				$method = ''; // Leave blank so WP_Filesystem can populate it as necessary.
845
846
				$creds = request_filesystem_credentials( esc_url_raw( $url ), $method, false, false, array() );
847
				if ( false === $creds ) {
848
					return true;
849
				}
850
851 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...
852
					request_filesystem_credentials( esc_url_raw( $url ), $method, true, false, array() ); // Setup WP_Filesystem.
853
					return true;
854
				}
855
856
				/* If we arrive here, we have the filesystem. */
857
858
				// Prep variables for Plugin_Installer_Skin class.
859
				$extra         = array();
860
				$extra['slug'] = $slug; // Needed for potentially renaming of directory name.
861
				$source        = $this->get_download_url( $slug );
862
				$api           = ( 'repo' === $this->plugins[ $slug ]['source_type'] ) ? $this->get_plugins_api( $slug ) : null;
863
				$api           = ( false !== $api ) ? $api : null;
864
865
				$url = add_query_arg(
866
					array(
867
						'action' => $install_type . '-plugin',
868
						'plugin' => urlencode( $slug ),
869
					),
870
					'update.php'
871
				);
872
873
				if ( ! class_exists( 'Plugin_Upgrader', false ) ) {
874
					require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
875
				}
876
877
				$title     = ( 'update' === $install_type ) ? $this->strings['updating'] : $this->strings['installing'];
878
				$skin_args = array(
879
					'type'   => ( 'bundled' !== $this->plugins[ $slug ]['source_type'] ) ? 'web' : 'upload',
880
					'title'  => sprintf( $title, $this->plugins[ $slug ]['name'] ),
881
					'url'    => esc_url_raw( $url ),
882
					'nonce'  => $install_type . '-plugin_' . $slug,
883
					'plugin' => '',
884
					'api'    => $api,
885
					'extra'  => $extra,
886
				);
887
				unset( $title );
888
889
				if ( 'update' === $install_type ) {
890
					$skin_args['plugin'] = $this->plugins[ $slug ]['file_path'];
891
					$skin                = new Plugin_Upgrader_Skin( $skin_args );
892
				} else {
893
					$skin = new Plugin_Installer_Skin( $skin_args );
894
				}
895
896
				// Create a new instance of Plugin_Upgrader.
897
				$upgrader = new Plugin_Upgrader( $skin );
898
899
				// Perform the action and install the plugin from the $source urldecode().
900
				add_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1, 3 );
901
902
				if ( 'update' === $install_type ) {
903
					// Inject our info into the update transient.
904
					$to_inject                    = array(
905
						$slug => $this->plugins[ $slug ],
906
					);
907
					$to_inject[ $slug ]['source'] = $source;
908
					$this->inject_update_info( $to_inject );
909
910
					$upgrader->upgrade( $this->plugins[ $slug ]['file_path'] );
911
				} else {
912
					$upgrader->install( $source );
913
				}
914
915
				remove_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1 );
916
917
				// Make sure we have the correct file path now the plugin is installed/updated.
918
				$this->populate_file_path( $slug );
919
920
				// Only activate plugins if the config option is set to true and the plugin isn't
921
				// already active (upgrade).
922
				if ( $this->is_automatic && ! $this->is_plugin_active( $slug ) ) {
923
					$plugin_activate = $upgrader->plugin_info(); // Grab the plugin info from the Plugin_Upgrader method.
924
					if ( false === $this->activate_single_plugin( $plugin_activate, $slug, true ) ) {
925
						return true; // Finish execution of the function early as we encountered an error.
926
					}
927
				}
928
929
				$this->show_tgmpa_version();
930
931
				// Display message based on if all plugins are now active or not.
932
				if ( $this->is_tgmpa_complete() ) {
933
					echo '<p>', sprintf( esc_html( $this->strings['complete'] ), '<a href="' . esc_url( self_admin_url() ) . '">' . esc_html( $this->strings['dashboard'] ) . '</a>' ), '</p>';
934
					echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>';
935
				} else {
936
					echo '<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>';
937
				}
938
939
				return true;
940
			} elseif ( isset( $this->plugins[ $slug ]['file_path'], $_GET['tgmpa-activate'] ) && 'activate-plugin' === $_GET['tgmpa-activate'] ) {
941
				// Activate action link was clicked.
942
				check_admin_referer( 'tgmpa-activate', 'tgmpa-nonce' );
943
944
				if ( false === $this->activate_single_plugin( $this->plugins[ $slug ]['file_path'], $slug ) ) {
945
					return true; // Finish execution of the function early as we encountered an error.
946
				}
947
			}
948
949
			return false;
950
		}
951
952
		/**
953
		 * Inject information into the 'update_plugins' site transient as WP checks that before running an update.
954
		 *
955
		 * @since 2.5.0
956
		 *
957
		 * @param array $plugins The plugin information for the plugins which are to be updated.
958
		 */
959
		public function inject_update_info( $plugins ) {
960
			$repo_updates = get_site_transient( 'update_plugins' );
961
962
			if ( ! is_object( $repo_updates ) ) {
963
				$repo_updates = new stdClass();
964
			}
965
966
			foreach ( $plugins as $slug => $plugin ) {
967
				$file_path = $plugin['file_path'];
968
969
				if ( empty( $repo_updates->response[ $file_path ] ) ) {
970
					$repo_updates->response[ $file_path ] = new stdClass();
971
				}
972
973
				// We only really need to set package, but let's do all we can in case WP changes something.
974
				$repo_updates->response[ $file_path ]->slug        = $slug;
975
				$repo_updates->response[ $file_path ]->plugin      = $file_path;
976
				$repo_updates->response[ $file_path ]->new_version = $plugin['version'];
977
				$repo_updates->response[ $file_path ]->package     = $plugin['source'];
978
				if ( empty( $repo_updates->response[ $file_path ]->url ) && ! empty( $plugin['external_url'] ) ) {
979
					$repo_updates->response[ $file_path ]->url = $plugin['external_url'];
980
				}
981
			}
982
983
			set_site_transient( 'update_plugins', $repo_updates );
984
		}
985
986
		/**
987
		 * Adjust the plugin directory name if necessary.
988
		 *
989
		 * The final destination directory of a plugin is based on the subdirectory name found in the
990
		 * (un)zipped source. In some cases - most notably GitHub repository plugin downloads -, this
991
		 * subdirectory name is not the same as the expected slug and the plugin will not be recognized
992
		 * as installed. This is fixed by adjusting the temporary unzipped source subdirectory name to
993
		 * the expected plugin slug.
994
		 *
995
		 * @since 2.5.0
996
		 *
997
		 * @param string       $source        Path to upgrade/zip-file-name.tmp/subdirectory/.
998
		 * @param string       $remote_source Path to upgrade/zip-file-name.tmp.
999
		 * @param \WP_Upgrader $upgrader      Instance of the upgrader which installs the plugin.
1000
		 * @return string $source
1001
		 */
1002
		public function maybe_adjust_source_dir( $source, $remote_source, $upgrader ) {
1003
			if ( ! $this->is_tgmpa_page() || ! is_object( $GLOBALS['wp_filesystem'] ) ) {
1004
				return $source;
1005
			}
1006
1007
			// Check for single file plugins.
1008
			$source_files = array_keys( $GLOBALS['wp_filesystem']->dirlist( $remote_source ) );
1009
			if ( 1 === count( $source_files ) && false === $GLOBALS['wp_filesystem']->is_dir( $source ) ) {
1010
				return $source;
1011
			}
1012
1013
			// Multi-file plugin, let's see if the directory is correctly named.
1014
			$desired_slug = '';
1015
1016
			// Figure out what the slug is supposed to be.
1017
			if ( false === $upgrader->bulk && ! empty( $upgrader->skin->options['extra']['slug'] ) ) {
1018
				$desired_slug = $upgrader->skin->options['extra']['slug'];
1019
			} else {
1020
				// Bulk installer contains less info, so fall back on the info registered here.
1021
				foreach ( $this->plugins as $slug => $plugin ) {
1022
					if ( ! empty( $upgrader->skin->plugin_names[ $upgrader->skin->i ] ) && $plugin['name'] === $upgrader->skin->plugin_names[ $upgrader->skin->i ] ) {
1023
						$desired_slug = $slug;
1024
						break;
1025
					}
1026
				}
1027
				unset( $slug, $plugin );
1028
			}
1029
1030
			if ( ! empty( $desired_slug ) ) {
1031
				$subdir_name = untrailingslashit( str_replace( trailingslashit( $remote_source ), '', $source ) );
1032
1033
				if ( ! empty( $subdir_name ) && $subdir_name !== $desired_slug ) {
1034
					$from_path = untrailingslashit( $source );
1035
					$to_path   = trailingslashit( $remote_source ) . $desired_slug;
1036
1037
					if ( true === $GLOBALS['wp_filesystem']->move( $from_path, $to_path ) ) {
1038
						return trailingslashit( $to_path );
1039 View Code Duplication
					} else {
1040
						return new WP_Error(
1041
							'rename_failed',
1042
							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' ),
1043
							array(
1044
								'found'    => $subdir_name,
1045
								'expected' => $desired_slug,
1046
							)
1047
						);
1048
					}
1049 View Code Duplication
				} elseif ( empty( $subdir_name ) ) {
1050
					return new WP_Error(
1051
						'packaged_wrong',
1052
						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' ),
1053
						array(
1054
							'found'    => $subdir_name,
1055
							'expected' => $desired_slug,
1056
						)
1057
					);
1058
				}
1059
			}
1060
1061
			return $source;
1062
		}
1063
1064
		/**
1065
		 * Activate a single plugin and send feedback about the result to the screen.
1066
		 *
1067
		 * @since 2.5.0
1068
		 *
1069
		 * @param string $file_path Path within wp-plugins/ to main plugin file.
1070
		 * @param string $slug      Plugin slug.
1071
		 * @param bool   $automatic Whether this is an automatic activation after an install. Defaults to false.
1072
		 *                          This determines the styling of the output messages.
1073
		 * @return bool False if an error was encountered, true otherwise.
1074
		 */
1075
		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...
1076
			if ( $this->can_plugin_activate( $slug ) ) {
1077
				$activate = activate_plugin( $file_path );
1078
1079
				if ( is_wp_error( $activate ) ) {
1080
					echo '<div id="message" class="error"><p>', wp_kses_post( $activate->get_error_message() ), '</p></div>',
1081
						'<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>';
1082
1083
					return false; // End it here if there is an error with activation.
1084
				} else {
1085
					if ( ! $automatic ) {
1086
						// Make sure message doesn't display again if bulk activation is performed
1087
						// immediately after a single activation.
1088
						// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Not using the superglobal.
1089
						if ( ! isset( $_POST['action'] ) ) {
1090
							echo '<div id="message" class="updated"><p>', esc_html( $this->strings['activated_successfully'] ), ' <strong>', esc_html( $this->plugins[ $slug ]['name'] ), '.</strong></p></div>';
1091
						}
1092
					} else {
1093
						// Simpler message layout for use on the plugin install page.
1094
						echo '<p>', esc_html( $this->strings['plugin_activated'] ), '</p>';
1095
					}
1096
				}
1097 View Code Duplication
			} elseif ( $this->is_plugin_active( $slug ) ) {
1098
				// No simpler message format provided as this message should never be encountered
1099
				// on the plugin install page.
1100
				echo '<div id="message" class="error"><p>',
1101
					sprintf(
1102
						esc_html( $this->strings['plugin_already_active'] ),
1103
						'<strong>' . esc_html( $this->plugins[ $slug ]['name'] ) . '</strong>'
1104
					),
1105
					'</p></div>';
1106
			} elseif ( $this->does_plugin_require_update( $slug ) ) {
1107
				if ( ! $automatic ) {
1108
					// Make sure message doesn't display again if bulk activation is performed
1109
					// immediately after a single activation.
1110
					// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Not using the superglobal.
1111 View Code Duplication
					if ( ! isset( $_POST['action'] ) ) {