Completed
Pull Request — develop (#689)
by
unknown
01:46
created

TGM_Plugin_Activation::do_plugin_install()   F

Complexity

Conditions 25
Paths 1289

Size

Total Lines 142
Code Lines 81

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 25
eloc 81
nc 1289
nop 0
dl 0
loc 142
rs 2
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
	namespace TGM;
4
	
5
	/**
6
	 * Automatic plugin installation and activation library.
7
	 *
8
	 * Creates a way to automatically install and activate plugins from within themes.
9
	 * The plugins can be either bundled, downloaded from the WordPress
10
	 * Plugin Repository or downloaded from another external source.
11
	 *
12
	 * @since 1.0.0
13
	 *
14
	 * @package TGM-Plugin-Activation
15
	 * @author  Thomas Griffin
16
	 * @author  Gary Jones
17
	 */
18
	class TGM_Plugin_Activation {
19
		/**
20
		 * TGMPA version number.
21
		 *
22
		 * @since 2.5.0
23
		 *
24
		 * @const string Version number.
25
		 */
26
		const TGMPA_VERSION = '2.6.2';
27
28
		/**
29
		 * Regular expression to test if a URL is a WP plugin repo URL.
30
		 *
31
		 * @const string Regex.
32
		 *
33
		 * @since 2.5.0
34
		 */
35
		const WP_REPO_REGEX = '|^http[s]?://wordpress\.org/(?:extend/)?plugins/|';
36
37
		/**
38
		 * Arbitrary regular expression to test if a string starts with a URL.
39
		 *
40
		 * @const string Regex.
41
		 *
42
		 * @since 2.5.0
43
		 */
44
		const IS_URL_REGEX = '|^http[s]?://|';
45
46
		/**
47
		 * Holds a copy of itself, so it can be referenced by the class name.
48
		 *
49
		 * @since 1.0.0
50
		 *
51
		 * @var TGM_Plugin_Activation
52
		 */
53
		public static $instance;
54
55
		/**
56
		 * Holds arrays of plugin details.
57
		 *
58
		 * @since 1.0.0
59
		 * @since 2.5.0 the array has the plugin slug as an associative key.
60
		 *
61
		 * @var array
62
		 */
63
		public $plugins = array();
64
65
		/**
66
		 * Holds arrays of plugin names to use to sort the plugins array.
67
		 *
68
		 * @since 2.5.0
69
		 *
70
		 * @var array
71
		 */
72
		protected $sort_order = array();
73
74
		/**
75
		 * Whether any plugins have the 'force_activation' setting set to true.
76
		 *
77
		 * @since 2.5.0
78
		 *
79
		 * @var bool
80
		 */
81
		protected $has_forced_activation = false;
82
83
		/**
84
		 * Whether any plugins have the 'force_deactivation' setting set to true.
85
		 *
86
		 * @since 2.5.0
87
		 *
88
		 * @var bool
89
		 */
90
		protected $has_forced_deactivation = false;
91
92
		/**
93
		 * Name of the unique ID to hash notices.
94
		 *
95
		 * @since 2.4.0
96
		 *
97
		 * @var string
98
		 */
99
		public $id = 'tgmpa';
100
101
		/**
102
		 * Name of the query-string argument for the admin page.
103
		 *
104
		 * @since 1.0.0
105
		 *
106
		 * @var string
107
		 */
108
		protected $menu = 'tgmpa-install-plugins';
109
110
		/**
111
		 * Parent menu file slug.
112
		 *
113
		 * @since 2.5.0
114
		 *
115
		 * @var string
116
		 */
117
		public $parent_slug = 'themes.php';
118
119
		/**
120
		 * Capability needed to view the plugin installation menu item.
121
		 *
122
		 * @since 2.5.0
123
		 *
124
		 * @var string
125
		 */
126
		public $capability = 'edit_theme_options';
127
128
		/**
129
		 * Default absolute path to folder containing bundled plugin zip files.
130
		 *
131
		 * @since 2.0.0
132
		 *
133
		 * @var string Absolute path prefix to zip file location for bundled plugins. Default is empty string.
134
		 */
135
		public $default_path = '';
136
137
		/**
138
		 * Flag to show admin notices or not.
139
		 *
140
		 * @since 2.1.0
141
		 *
142
		 * @var boolean
143
		 */
144
		public $has_notices = true;
145
146
		/**
147
		 * Flag to determine if the user can dismiss the notice nag.
148
		 *
149
		 * @since 2.4.0
150
		 *
151
		 * @var boolean
152
		 */
153
		public $dismissable = true;
154
155
		/**
156
		 * Message to be output above nag notice if dismissable is false.
157
		 *
158
		 * @since 2.4.0
159
		 *
160
		 * @var string
161
		 */
162
		public $dismiss_msg = '';
163
164
		/**
165
		 * Flag to set automatic activation of plugins. Off by default.
166
		 *
167
		 * @since 2.2.0
168
		 *
169
		 * @var boolean
170
		 */
171
		public $is_automatic = false;
172
173
		/**
174
		 * Optional message to display before the plugins table.
175
		 *
176
		 * @since 2.2.0
177
		 *
178
		 * @var string Message filtered by wp_kses_post(). Default is empty string.
179
		 */
180
		public $message = '';
181
182
		/**
183
		 * Holds configurable array of strings.
184
		 *
185
		 * Default values are added in the constructor.
186
		 *
187
		 * @since 2.0.0
188
		 *
189
		 * @var array
190
		 */
191
		public $strings = array();
192
193
		/**
194
		 * Holds the version of WordPress.
195
		 *
196
		 * @since 2.4.0
197
		 *
198
		 * @var int
199
		 */
200
		public $wp_version;
201
202
		/**
203
		 * Holds the hook name for the admin page.
204
		 *
205
		 * @since 2.5.0
206
		 *
207
		 * @var string
208
		 */
209
		public $page_hook;
210
211
		/**
212
		 * Adds a reference of this object to $instance, populates default strings,
213
		 * does the tgmpa_init action hook, and hooks in the interactions to init.
214
		 *
215
		 * {@internal This method should be `protected`, but as too many TGMPA implementations
216
		 * haven't upgraded beyond v2.3.6 yet, this gives backward compatibility issues.
217
		 * Reverted back to public for the time being.}}
218
		 *
219
		 * @since 1.0.0
220
		 *
221
		 * @see TGM_Plugin_Activation::init()
222
		 */
223
		public function __construct() {
224
			// Set the current WordPress version.
225
			$this->wp_version = $GLOBALS['wp_version'];
226
227
			// Announce that the class is ready, and pass the object (for advanced use).
228
			do_action_ref_array( 'tgmpa_init', array( $this ) );
229
230
			/*
231
			 * Load our text domain and allow for overloading the fall-back file.
232
			 *
233
			 * {@internal IMPORTANT! If this code changes, review the regex in the custom TGMPA
234
			 * generator on the website.}}
235
			 */
236
			add_action( 'init', array( $this, 'load_textdomain' ), 5 );
237
			add_filter( 'load_textdomain_mofile', array( $this, 'overload_textdomain_mofile' ), 10, 2 );
238
239
			// When the rest of WP has loaded, kick-start the rest of the class.
240
			add_action( 'init', array( $this, 'init' ) );
241
		}
242
243
		/**
244
		 * Magic method to (not) set protected properties from outside of this class.
245
		 *
246
		 * {@internal hackedihack... There is a serious bug in v2.3.2 - 2.3.6  where the `menu` property
247
		 * is being assigned rather than tested in a conditional, effectively rendering it useless.
248
		 * This 'hack' prevents this from happening.}}
249
		 *
250
		 * @see https://github.com/TGMPA/TGM-Plugin-Activation/blob/2.3.6/tgm-plugin-activation/class-tgm-plugin-activation.php#L1593
251
		 *
252
		 * @since 2.5.2
253
		 *
254
		 * @param string $name  Name of an inaccessible property.
255
		 * @param mixed  $value Value to assign to the property.
256
		 * @return void  Silently fail to set the property when this is tried from outside of this class context.
257
		 *               (Inside this class context, the __set() method if not used as there is direct access.)
258
		 */
259
		public function __set( $name, $value ) {
260
			return;
261
		}
262
263
		/**
264
		 * Magic method to get the value of a protected property outside of this class context.
265
		 *
266
		 * @since 2.5.2
267
		 *
268
		 * @param string $name Name of an inaccessible property.
269
		 * @return mixed The property value.
270
		 */
271
		public function __get( $name ) {
272
			return $this->{$name};
273
		}
274
275
		/**
276
		 * Initialise the interactions between this class and WordPress.
277
		 *
278
		 * Hooks in three new methods for the class: admin_menu, notices and styles.
279
		 *
280
		 * @since 2.0.0
281
		 *
282
		 * @see TGM_Plugin_Activation::admin_menu()
283
		 * @see TGM_Plugin_Activation::notices()
284
		 * @see TGM_Plugin_Activation::styles()
285
		 */
286
		public function init() {
287
			/**
288
			 * By default TGMPA only loads on the WP back-end and not in an Ajax call. Using this filter
289
			 * you can overrule that behaviour.
290
			 *
291
			 * @since 2.5.0
292
			 *
293
			 * @param bool $load Whether or not TGMPA should load.
294
			 *                   Defaults to the return of `is_admin() && ! defined( 'DOING_AJAX' )`.
295
			 */
296
			if ( true !== apply_filters( 'tgmpa_load', ( is_admin() && ! defined( 'DOING_AJAX' ) ) ) ) {
297
				return;
298
			}
299
300
			// Load class strings.
301
			$this->strings = array(
302
				'page_title'                      => __( 'Install Required Plugins', 'tgmpa' ),
303
				'menu_title'                      => __( 'Install Plugins', 'tgmpa' ),
304
				/* translators: %s: plugin name. */
305
				'installing'                      => __( 'Installing Plugin: %s', 'tgmpa' ),
306
				/* translators: %s: plugin name. */
307
				'updating'                        => __( 'Updating Plugin: %s', 'tgmpa' ),
308
				'oops'                            => __( 'Something went wrong with the plugin API.', 'tgmpa' ),
309
				/* translators: 1: plugin name(s). */
310
				'notice_can_install_required'     => _n_noop(
311
					'This theme requires the following plugin: %1$s.',
312
					'This theme requires the following plugins: %1$s.',
313
					'tgmpa'
314
				),
315
				/* translators: 1: plugin name(s). */
316
				'notice_can_install_recommended'  => _n_noop(
317
					'This theme recommends the following plugin: %1$s.',
318
					'This theme recommends the following plugins: %1$s.',
319
					'tgmpa'
320
				),
321
				/* translators: 1: plugin name(s). */
322
				'notice_ask_to_update'            => _n_noop(
323
					'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.',
324
					'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.',
325
					'tgmpa'
326
				),
327
				/* translators: 1: plugin name(s). */
328
				'notice_ask_to_update_maybe'      => _n_noop(
329
					'There is an update available for: %1$s.',
330
					'There are updates available for the following plugins: %1$s.',
331
					'tgmpa'
332
				),
333
				/* translators: 1: plugin name(s). */
334
				'notice_can_activate_required'    => _n_noop(
335
					'The following required plugin is currently inactive: %1$s.',
336
					'The following required plugins are currently inactive: %1$s.',
337
					'tgmpa'
338
				),
339
				/* translators: 1: plugin name(s). */
340
				'notice_can_activate_recommended' => _n_noop(
341
					'The following recommended plugin is currently inactive: %1$s.',
342
					'The following recommended plugins are currently inactive: %1$s.',
343
					'tgmpa'
344
				),
345
				'install_link'                    => _n_noop(
346
					'Begin installing plugin',
347
					'Begin installing plugins',
348
					'tgmpa'
349
				),
350
				'update_link'                     => _n_noop(
351
					'Begin updating plugin',
352
					'Begin updating plugins',
353
					'tgmpa'
354
				),
355
				'activate_link'                   => _n_noop(
356
					'Begin activating plugin',
357
					'Begin activating plugins',
358
					'tgmpa'
359
				),
360
				'return'                          => __( 'Return to Required Plugins Installer', 'tgmpa' ),
361
				'dashboard'                       => __( 'Return to the Dashboard', 'tgmpa' ),
362
				'plugin_activated'                => __( 'Plugin activated successfully.', 'tgmpa' ),
363
				'activated_successfully'          => __( 'The following plugin was activated successfully:', 'tgmpa' ),
364
				/* translators: 1: plugin name. */
365
				'plugin_already_active'           => __( 'No action taken. Plugin %1$s was already active.', 'tgmpa' ),
366
				/* translators: 1: plugin name. */
367
				'plugin_needs_higher_version'     => __( 'Plugin not activated. A higher version of %s is needed for this theme. Please update the plugin.', 'tgmpa' ),
368
				/* translators: 1: dashboard link. */
369
				'complete'                        => __( 'All plugins installed and activated successfully. %1$s', 'tgmpa' ),
370
				'dismiss'                         => __( 'Dismiss this notice', 'tgmpa' ),
371
				'notice_cannot_install_activate'  => __( 'There are one or more required or recommended plugins to install, update or activate.', 'tgmpa' ),
372
				'contact_admin'                   => __( 'Please contact the administrator of this site for help.', 'tgmpa' ),
373
			);
374
375
			do_action( 'tgmpa_register' );
376
377
			/* After this point, the plugins should be registered and the configuration set. */
378
379
			// Proceed only if we have plugins to handle.
380
			if ( empty( $this->plugins ) || ! is_array( $this->plugins ) ) {
381
				return;
382
			}
383
384
			// Set up the menu and notices if we still have outstanding actions.
385
			if ( true !== $this->is_tgmpa_complete() ) {
386
				// Sort the plugins.
387
				array_multisort( $this->sort_order, SORT_ASC, $this->plugins );
388
389
				add_action( 'admin_menu', array( $this, 'admin_menu' ) );
390
				add_action( 'admin_head', array( $this, 'dismiss' ) );
391
392
				// Prevent the normal links from showing underneath a single install/update page.
393
				add_filter( 'install_plugin_complete_actions', array( $this, 'actions' ) );
394
				add_filter( 'update_plugin_complete_actions', array( $this, 'actions' ) );
395
396
				if ( $this->has_notices ) {
397
					add_action( 'admin_notices', array( $this, 'notices' ) );
398
					add_action( 'admin_init', array( $this, 'admin_init' ), 1 );
399
					add_action( 'admin_enqueue_scripts', array( $this, 'thickbox' ) );
400
				}
401
			}
402
403
			// If needed, filter plugin action links.
404
			add_action( 'load-plugins.php', array( $this, 'add_plugin_action_link_filters' ), 1 );
405
406
			// Make sure things get reset on switch theme.
407
			add_action( 'switch_theme', array( $this, 'flush_plugins_cache' ) );
408
409
			if ( $this->has_notices ) {
410
				add_action( 'switch_theme', array( $this, 'update_dismiss' ) );
411
			}
412
413
			// Setup the force activation hook.
414
			if ( true === $this->has_forced_activation ) {
415
				add_action( 'admin_init', array( $this, 'force_activation' ) );
416
			}
417
418
			// Setup the force deactivation hook.
419
			if ( true === $this->has_forced_deactivation ) {
420
				add_action( 'switch_theme', array( $this, 'force_deactivation' ) );
421
			}
422
423
			// Add CSS for the TGMPA admin page.
424
			add_action( 'admin_head', array( $this, 'admin_css' ) );
425
		}
426
427
		/**
428
		 * Load translations.
429
		 *
430
		 * @since 2.6.0
431
		 *
432
		 * (@internal Uses `load_theme_textdomain()` rather than `load_plugin_textdomain()` to
433
		 * get round the different ways of handling the path and deprecated notices being thrown
434
		 * and such. For plugins, the actual file name will be corrected by a filter.}}
435
		 *
436
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
437
		 * generator on the website.}}
438
		 */
439
		public function load_textdomain() {
440
			if ( is_textdomain_loaded( 'tgmpa' ) ) {
441
				return;
442
			}
443
444
			if ( false !== strpos( __FILE__, WP_PLUGIN_DIR ) || false !== strpos( __FILE__, WPMU_PLUGIN_DIR ) ) {
445
				// Plugin, we'll need to adjust the file name.
446
				add_action( 'load_textdomain_mofile', array( $this, 'correct_plugin_mofile' ), 10, 2 );
447
				load_theme_textdomain( 'tgmpa', dirname( __FILE__ ) . '/languages' );
448
				remove_action( 'load_textdomain_mofile', array( $this, 'correct_plugin_mofile' ), 10 );
449
			} else {
450
				load_theme_textdomain( 'tgmpa', dirname( __FILE__ ) . '/languages' );
451
			}
452
		}
453
454
		/**
455
		 * Correct the .mo file name for (must-use) plugins.
456
		 *
457
		 * Themese use `/path/{locale}.mo` while plugins use `/path/{text-domain}-{locale}.mo`.
458
		 *
459
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
460
		 * generator on the website.}}
461
		 *
462
		 * @since 2.6.0
463
		 *
464
		 * @param string $mofile Full path to the target mofile.
465
		 * @param string $domain The domain for which a language file is being loaded.
466
		 * @return string $mofile
467
		 */
468
		public function correct_plugin_mofile( $mofile, $domain ) {
469
			// Exit early if not our domain (just in case).
470
			if ( 'tgmpa' !== $domain ) {
471
				return $mofile;
472
			}
473
			return preg_replace( '`/([a-z]{2}_[A-Z]{2}.mo)$`', '/tgmpa-$1', $mofile );
474
		}
475
476
		/**
477
		 * Potentially overload the fall-back translation file for the current language.
478
		 *
479
		 * WP, by default since WP 3.7, will load a local translation first and if none
480
		 * can be found, will try and find a translation in the /wp-content/languages/ directory.
481
		 * As this library is theme/plugin agnostic, translation files for TGMPA can exist both
482
		 * in the WP_LANG_DIR /plugins/ subdirectory as well as in the /themes/ subdirectory.
483
		 *
484
		 * This method makes sure both directories are checked.
485
		 *
486
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
487
		 * generator on the website.}}
488
		 *
489
		 * @since 2.6.0
490
		 *
491
		 * @param string $mofile Full path to the target mofile.
492
		 * @param string $domain The domain for which a language file is being loaded.
493
		 * @return string $mofile
494
		 */
495
		public function overload_textdomain_mofile( $mofile, $domain ) {
496
			// Exit early if not our domain, not a WP_LANG_DIR load or if the file exists and is readable.
497
			if ( 'tgmpa' !== $domain || false === strpos( $mofile, WP_LANG_DIR ) || @is_readable( $mofile ) ) {
498
				return $mofile;
499
			}
500
501
			// Current fallback file is not valid, let's try the alternative option.
502
			if ( false !== strpos( $mofile, '/themes/' ) ) {
503
				return str_replace( '/themes/', '/plugins/', $mofile );
504
			} elseif ( false !== strpos( $mofile, '/plugins/' ) ) {
505
				return str_replace( '/plugins/', '/themes/', $mofile );
506
			} else {
507
				return $mofile;
508
			}
509
		}
510
511
		/**
512
		 * Hook in plugin action link filters for the WP native plugins page.
513
		 *
514
		 * - Prevent activation of plugins which don't meet the minimum version requirements.
515
		 * - Prevent deactivation of force-activated plugins.
516
		 * - Add update notice if update available.
517
		 *
518
		 * @since 2.5.0
519
		 */
520
		public function add_plugin_action_link_filters() {
521
			foreach ( $this->plugins as $slug => $plugin ) {
522
				if ( false === $this->can_plugin_activate( $slug ) ) {
523
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_activate' ), 20 );
524
				}
525
526
				if ( true === $plugin['force_activation'] ) {
527
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_deactivate' ), 20 );
528
				}
529
530
				if ( false !== $this->does_plugin_require_update( $slug ) ) {
531
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_update' ), 20 );
532
				}
533
			}
534
		}
535
536
		/**
537
		 * Remove the 'Activate' link on the WP native plugins page if the plugin does not meet the
538
		 * minimum version requirements.
539
		 *
540
		 * @since 2.5.0
541
		 *
542
		 * @param array $actions Action links.
543
		 * @return array
544
		 */
545
		public function filter_plugin_action_links_activate( $actions ) {
546
			unset( $actions['activate'] );
547
548
			return $actions;
549
		}
550
551
		/**
552
		 * Remove the 'Deactivate' link on the WP native plugins page if the plugin has been set to force activate.
553
		 *
554
		 * @since 2.5.0
555
		 *
556
		 * @param array $actions Action links.
557
		 * @return array
558
		 */
559
		public function filter_plugin_action_links_deactivate( $actions ) {
560
			unset( $actions['deactivate'] );
561
562
			return $actions;
563
		}
564
565
		/**
566
		 * Add a 'Requires update' link on the WP native plugins page if the plugin does not meet the
567
		 * minimum version requirements.
568
		 *
569
		 * @since 2.5.0
570
		 *
571
		 * @param array $actions Action links.
572
		 * @return array
573
		 */
574
		public function filter_plugin_action_links_update( $actions ) {
575
			$actions['update'] = sprintf(
576
				'<a href="%1$s" title="%2$s" class="edit">%3$s</a>',
577
				esc_url( $this->get_tgmpa_status_url( 'update' ) ),
578
				esc_attr__( 'This plugin needs to be updated to be compatible with your theme.', 'tgmpa' ),
579
				esc_html__( 'Update Required', 'tgmpa' )
580
			);
581
582
			return $actions;
583
		}
584
585
		/**
586
		 * Handles calls to show plugin information via links in the notices.
587
		 *
588
		 * We get the links in the admin notices to point to the TGMPA page, rather
589
		 * than the typical plugin-install.php file, so we can prepare everything
590
		 * beforehand.
591
		 *
592
		 * WP does not make it easy to show the plugin information in the thickbox -
593
		 * here we have to require a file that includes a function that does the
594
		 * main work of displaying it, enqueue some styles, set up some globals and
595
		 * finally call that function before exiting.
596
		 *
597
		 * Down right easy once you know how...
598
		 *
599
		 * Returns early if not the TGMPA page.
600
		 *
601
		 * @since 2.1.0
602
		 *
603
		 * @global string $tab Used as iframe div class names, helps with styling
604
		 * @global string $body_id Used as the iframe body ID, helps with styling
605
		 *
606
		 * @return null Returns early if not the TGMPA page.
607
		 */
608
		public function admin_init() {
609
			if ( ! $this->is_tgmpa_page() ) {
610
				return;
611
			}
612
613
			if ( isset( $_REQUEST['tab'] ) && 'plugin-information' === $_REQUEST['tab'] ) {
614
				// Needed for install_plugin_information().
615
				require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
616
617
				wp_enqueue_style( 'plugin-install' );
618
619
				global $tab, $body_id;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
620
				$body_id = 'plugin-information'; // WPCS: override ok, prefix ok.
621
				$tab     = 'plugin-information'; // WPCS: override ok.
622
623
				install_plugin_information();
624
625
				exit;
626
			}
627
		}
628
629
		/**
630
		 * Enqueue thickbox scripts/styles for plugin info.
631
		 *
632
		 * Thickbox is not automatically included on all admin pages, so we must
633
		 * manually enqueue it for those pages.
634
		 *
635
		 * Thickbox is only loaded if the user has not dismissed the admin
636
		 * notice or if there are any plugins left to install and activate.
637
		 *
638
		 * @since 2.1.0
639
		 */
640
		public function thickbox() {
641
			if ( ! get_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, true ) ) {
642
				add_thickbox();
643
			}
644
		}
645
646
		/**
647
		 * Adds submenu page if there are plugin actions to take.
648
		 *
649
		 * This method adds the submenu page letting users know that a required
650
		 * plugin needs to be installed.
651
		 *
652
		 * This page disappears once the plugin has been installed and activated.
653
		 *
654
		 * @since 1.0.0
655
		 *
656
		 * @see TGM_Plugin_Activation::init()
657
		 * @see TGM_Plugin_Activation::install_plugins_page()
658
		 *
659
		 * @return null Return early if user lacks capability to install a plugin.
660
		 */
661
		public function admin_menu() {
662
			// Make sure privileges are correct to see the page.
663
			if ( ! current_user_can( 'install_plugins' ) ) {
664
				return;
665
			}
666
667
			$args = apply_filters(
668
				'tgmpa_admin_menu_args',
669
				array(
670
					'parent_slug' => $this->parent_slug,                     // Parent Menu slug.
671
					'page_title'  => $this->strings['page_title'],           // Page title.
672
					'menu_title'  => $this->strings['menu_title'],           // Menu title.
673
					'capability'  => $this->capability,                      // Capability.
674
					'menu_slug'   => $this->menu,                            // Menu slug.
675
					'function'    => array( $this, 'install_plugins_page' ), // Callback.
676
				)
677
			);
678
679
			$this->add_admin_menu( $args );
680
		}
681
682
		/**
683
		 * Add the menu item.
684
		 *
685
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
686
		 * generator on the website.}}
687
		 *
688
		 * @since 2.5.0
689
		 *
690
		 * @param array $args Menu item configuration.
691
		 */
692
		protected function add_admin_menu( array $args ) {
693
			if ( has_filter( 'tgmpa_admin_menu_use_add_theme_page' ) ) {
694
				_deprecated_function( 'The "tgmpa_admin_menu_use_add_theme_page" filter', '2.5.0', esc_html__( 'Set the parent_slug config variable instead.', 'tgmpa' ) );
695
			}
696
697
			if ( 'themes.php' === $this->parent_slug ) {
698
				$this->page_hook = call_user_func( 'add_theme_page', $args['page_title'], $args['menu_title'], $args['capability'], $args['menu_slug'], $args['function'] );
699
			} else {
700
				$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'] );
701
			}
702
		}
703
704
		/**
705
		 * Echoes plugin installation form.
706
		 *
707
		 * This method is the callback for the admin_menu method function.
708
		 * This displays the admin page and form area where the user can select to install and activate the plugin.
709
		 * Aborts early if we're processing a plugin installation action.
710
		 *
711
		 * @since 1.0.0
712
		 *
713
		 * @return null Aborts early if we're processing a plugin installation action.
714
		 */
715
		public function install_plugins_page() {
716
			
717
			/**
718
			 * WP_List_Table isn't always available. If it isn't available,
719
			 * we load it here.
720
			 *
721
			 * @since 2.2.0
722
			 */
723
			if ( ! class_exists( 'WP_List_Table' ) ) {
724
				require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
725
			}
726
727
			// Store new instance of plugin table in object.
728
			$plugin_table = new TGMPA_List_Table();
729
730
			// Return early if processing a plugin installation action.
731
			if ( ( ( 'tgmpa-bulk-install' === $plugin_table->current_action() || 'tgmpa-bulk-update' === $plugin_table->current_action() ) && $plugin_table->process_bulk_actions() ) || $this->do_plugin_install() ) {
732
				return;
733
			}
734
735
			// Force refresh of available plugin information so we'll know about manual updates/deletes.
736
			wp_clean_plugins_cache( false );
737
738
			?>
739
			<div class="tgmpa wrap">
740
				<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
741
				<?php $plugin_table->prepare_items(); ?>
742
743
				<?php
744
				if ( ! empty( $this->message ) && is_string( $this->message ) ) {
745
					echo wp_kses_post( $this->message );
746
				}
747
				?>
748
				<?php $plugin_table->views(); ?>
749
750
				<form id="tgmpa-plugins" action="" method="post">
751
					<input type="hidden" name="tgmpa-page" value="<?php echo esc_attr( $this->menu ); ?>" />
752
					<input type="hidden" name="plugin_status" value="<?php echo esc_attr( $plugin_table->view_context ); ?>" />
753
					<?php $plugin_table->display(); ?>
754
				</form>
755
			</div>
756
			<?php
757
		}
758
759
		/**
760
		 * Installs, updates or activates a plugin depending on the action link clicked by the user.
761
		 *
762
		 * Checks the $_GET variable to see which actions have been
763
		 * passed and responds with the appropriate method.
764
		 *
765
		 * Uses WP_Filesystem to process and handle the plugin installation
766
		 * method.
767
		 *
768
		 * @since 1.0.0
769
		 *
770
		 * @uses WP_Filesystem
771
		 * @uses WP_Error
772
		 * @uses WP_Upgrader
773
		 * @uses Plugin_Upgrader
774
		 * @uses Plugin_Installer_Skin
775
		 * @uses Plugin_Upgrader_Skin
776
		 *
777
		 * @return boolean True on success, false on failure.
778
		 */
779
		protected function do_plugin_install() {
0 ignored issues
show
Coding Style introduced by
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...
780
			if ( empty( $_GET['plugin'] ) ) {
781
				return false;
782
			}
783
784
			// All plugin information will be stored in an array for processing.
785
			$slug = $this->sanitize_key( urldecode( $_GET['plugin'] ) );
786
787
			if ( ! isset( $this->plugins[ $slug ] ) ) {
788
				return false;
789
			}
790
791
			// Was an install or upgrade action link clicked?
792
			if ( ( isset( $_GET['tgmpa-install'] ) && 'install-plugin' === $_GET['tgmpa-install'] ) || ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) ) {
793
794
				$install_type = 'install';
795
				if ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) {
796
					$install_type = 'update';
797
				}
798
799
				check_admin_referer( 'tgmpa-' . $install_type, 'tgmpa-nonce' );
800
801
				// Pass necessary information via URL if WP_Filesystem is needed.
802
				$url = wp_nonce_url(
803
					add_query_arg(
804
						array(
805
							'plugin'                 => urlencode( $slug ),
806
							'tgmpa-' . $install_type => $install_type . '-plugin',
807
						),
808
						$this->get_tgmpa_url()
809
					),
810
					'tgmpa-' . $install_type,
811
					'tgmpa-nonce'
812
				);
813
814
				$method = ''; // Leave blank so WP_Filesystem can populate it as necessary.
815
816
				$creds = request_filesystem_credentials( esc_url_raw( $url ), $method, false, false, array() );
817
				if ( false === $creds ) {
818
					return true;
819
				}
820
821
				if ( ! WP_Filesystem( $creds ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
822
					request_filesystem_credentials( esc_url_raw( $url ), $method, true, false, array() ); // Setup WP_Filesystem.
823
					return true;
824
				}
825
826
				/* If we arrive here, we have the filesystem. */
827
828
				// Prep variables for Plugin_Installer_Skin class.
829
				$extra         = array();
830
				$extra['slug'] = $slug; // Needed for potentially renaming of directory name.
831
				$source        = $this->get_download_url( $slug );
832
				$api           = ( 'repo' === $this->plugins[ $slug ]['source_type'] ) ? $this->get_plugins_api( $slug ) : null;
833
				$api           = ( false !== $api ) ? $api : null;
834
835
				$url = add_query_arg(
836
					array(
837
						'action' => $install_type . '-plugin',
838
						'plugin' => urlencode( $slug ),
839
					),
840
					'update.php'
841
				);
842
843
				if ( ! class_exists( 'Plugin_Upgrader', false ) ) {
844
					require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
845
				}
846
847
				$title     = ( 'update' === $install_type ) ? $this->strings['updating'] : $this->strings['installing'];
848
				$skin_args = array(
849
					'type'   => ( 'bundled' !== $this->plugins[ $slug ]['source_type'] ) ? 'web' : 'upload',
850
					'title'  => sprintf( $title, $this->plugins[ $slug ]['name'] ),
851
					'url'    => esc_url_raw( $url ),
852
					'nonce'  => $install_type . '-plugin_' . $slug,
853
					'plugin' => '',
854
					'api'    => $api,
855
					'extra'  => $extra,
856
				);
857
				unset( $title );
858
859
				if ( 'update' === $install_type ) {
860
					$skin_args['plugin'] = $this->plugins[ $slug ]['file_path'];
861
					$skin                = new Plugin_Upgrader_Skin( $skin_args );
862
				} else {
863
					$skin = new Plugin_Installer_Skin( $skin_args );
864
				}
865
866
				// Create a new instance of Plugin_Upgrader.
867
				$upgrader = new Plugin_Upgrader( $skin );
868
869
				// Perform the action and install the plugin from the $source urldecode().
870
				add_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1, 3 );
871
872
				if ( 'update' === $install_type ) {
873
					// Inject our info into the update transient.
874
					$to_inject                    = array(
875
						$slug => $this->plugins[ $slug ],
876
					);
877
					$to_inject[ $slug ]['source'] = $source;
878
					$this->inject_update_info( $to_inject );
879
880
					$upgrader->upgrade( $this->plugins[ $slug ]['file_path'] );
881
				} else {
882
					$upgrader->install( $source );
883
				}
884
885
				remove_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1 );
886
887
				// Make sure we have the correct file path now the plugin is installed/updated.
888
				$this->populate_file_path( $slug );
889
890
				// Only activate plugins if the config option is set to true and the plugin isn't
891
				// already active (upgrade).
892
				if ( $this->is_automatic && ! $this->is_plugin_active( $slug ) ) {
893
					$plugin_activate = $upgrader->plugin_info(); // Grab the plugin info from the Plugin_Upgrader method.
894
					if ( false === $this->activate_single_plugin( $plugin_activate, $slug, true ) ) {
895
						return true; // Finish execution of the function early as we encountered an error.
896
					}
897
				}
898
899
				$this->show_tgmpa_version();
900
901
				// Display message based on if all plugins are now active or not.
902
				if ( $this->is_tgmpa_complete() ) {
903
					echo '<p>', sprintf( esc_html( $this->strings['complete'] ), '<a href="' . esc_url( self_admin_url() ) . '">' . esc_html( $this->strings['dashboard'] ) . '</a>' ), '</p>';
904
					echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>';
905
				} else {
906
					echo '<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>';
907
				}
908
909
				return true;
910
			} elseif ( isset( $this->plugins[ $slug ]['file_path'], $_GET['tgmpa-activate'] ) && 'activate-plugin' === $_GET['tgmpa-activate'] ) {
911
				// Activate action link was clicked.
912
				check_admin_referer( 'tgmpa-activate', 'tgmpa-nonce' );
913
914
				if ( false === $this->activate_single_plugin( $this->plugins[ $slug ]['file_path'], $slug ) ) {
915
					return true; // Finish execution of the function early as we encountered an error.
916
				}
917
			}
918
919
			return false;
920
		}
921
922
		/**
923
		 * Inject information into the 'update_plugins' site transient as WP checks that before running an update.
924
		 *
925
		 * @since 2.5.0
926
		 *
927
		 * @param array $plugins The plugin information for the plugins which are to be updated.
928
		 */
929
		public function inject_update_info( $plugins ) {
930
			$repo_updates = get_site_transient( 'update_plugins' );
931
932
			if ( ! is_object( $repo_updates ) ) {
933
				$repo_updates = new stdClass();
934
			}
935
936
			foreach ( $plugins as $slug => $plugin ) {
937
				$file_path = $plugin['file_path'];
938
939
				if ( empty( $repo_updates->response[ $file_path ] ) ) {
940
					$repo_updates->response[ $file_path ] = new stdClass();
941
				}
942
943
				// We only really need to set package, but let's do all we can in case WP changes something.
944
				$repo_updates->response[ $file_path ]->slug        = $slug;
945
				$repo_updates->response[ $file_path ]->plugin      = $file_path;
946
				$repo_updates->response[ $file_path ]->new_version = $plugin['version'];
947
				$repo_updates->response[ $file_path ]->package     = $plugin['source'];
948
				if ( empty( $repo_updates->response[ $file_path ]->url ) && ! empty( $plugin['external_url'] ) ) {
949
					$repo_updates->response[ $file_path ]->url = $plugin['external_url'];
950
				}
951
			}
952
953
			set_site_transient( 'update_plugins', $repo_updates );
954
		}
955
956
		/**
957
		 * Adjust the plugin directory name if necessary.
958
		 *
959
		 * The final destination directory of a plugin is based on the subdirectory name found in the
960
		 * (un)zipped source. In some cases - most notably GitHub repository plugin downloads -, this
961
		 * subdirectory name is not the same as the expected slug and the plugin will not be recognized
962
		 * as installed. This is fixed by adjusting the temporary unzipped source subdirectory name to
963
		 * the expected plugin slug.
964
		 *
965
		 * @since 2.5.0
966
		 *
967
		 * @param string       $source        Path to upgrade/zip-file-name.tmp/subdirectory/.
968
		 * @param string       $remote_source Path to upgrade/zip-file-name.tmp.
969
		 * @param \WP_Upgrader $upgrader      Instance of the upgrader which installs the plugin.
970
		 * @return string $source
971
		 */
972
		public function maybe_adjust_source_dir( $source, $remote_source, $upgrader ) {
973
			if ( ! $this->is_tgmpa_page() || ! is_object( $GLOBALS['wp_filesystem'] ) ) {
974
				return $source;
975
			}
976
977
			// Check for single file plugins.
978
			$source_files = array_keys( $GLOBALS['wp_filesystem']->dirlist( $remote_source ) );
979
			if ( 1 === count( $source_files ) && false === $GLOBALS['wp_filesystem']->is_dir( $source ) ) {
980
				return $source;
981
			}
982
983
			// Multi-file plugin, let's see if the directory is correctly named.
984
			$desired_slug = '';
985
986
			// Figure out what the slug is supposed to be.
987
			if ( false === $upgrader->bulk && ! empty( $upgrader->skin->options['extra']['slug'] ) ) {
988
				$desired_slug = $upgrader->skin->options['extra']['slug'];
989
			} else {
990
				// Bulk installer contains less info, so fall back on the info registered here.
991
				foreach ( $this->plugins as $slug => $plugin ) {
992
					if ( ! empty( $upgrader->skin->plugin_names[ $upgrader->skin->i ] ) && $plugin['name'] === $upgrader->skin->plugin_names[ $upgrader->skin->i ] ) {
993
						$desired_slug = $slug;
994
						break;
995
					}
996
				}
997
				unset( $slug, $plugin );
998
			}
999
1000
			if ( ! empty( $desired_slug ) ) {
1001
				$subdir_name = untrailingslashit( str_replace( trailingslashit( $remote_source ), '', $source ) );
1002
1003
				if ( ! empty( $subdir_name ) && $subdir_name !== $desired_slug ) {
1004
					$from_path = untrailingslashit( $source );
1005
					$to_path   = trailingslashit( $remote_source ) . $desired_slug;
1006
1007
					if ( true === $GLOBALS['wp_filesystem']->move( $from_path, $to_path ) ) {
1008
						return trailingslashit( $to_path );
1009 View Code Duplication
					} else {
1010
						return new WP_Error(
1011
							'rename_failed',
1012
							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' ),
1013
							array(
1014
								'found'    => $subdir_name,
1015
								'expected' => $desired_slug,
1016
							)
1017
						);
1018
					}
1019 View Code Duplication
				} elseif ( empty( $subdir_name ) ) {
1020
					return new WP_Error(
1021
						'packaged_wrong',
1022
						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' ),
1023
						array(
1024
							'found'    => $subdir_name,
1025
							'expected' => $desired_slug,
1026
						)
1027
					);
1028
				}
1029
			}
1030
1031
			return $source;
1032
		}
1033
1034
		/**
1035
		 * Activate a single plugin and send feedback about the result to the screen.
1036
		 *
1037
		 * @since 2.5.0
1038
		 *
1039
		 * @param string $file_path Path within wp-plugins/ to main plugin file.
1040
		 * @param string $slug      Plugin slug.
1041
		 * @param bool   $automatic Whether this is an automatic activation after an install. Defaults to false.
1042
		 *                          This determines the styling of the output messages.
1043
		 * @return bool False if an error was encountered, true otherwise.
1044
		 */
1045
		protected function activate_single_plugin( $file_path, $slug, $automatic = false ) {
0 ignored issues
show
Coding Style introduced by
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...
1046
			if ( $this->can_plugin_activate( $slug ) ) {
1047
				$activate = activate_plugin( $file_path );
1048
1049
				if ( is_wp_error( $activate ) ) {
1050
					echo '<div id="message" class="error"><p>', wp_kses_post( $activate->get_error_message() ), '</p></div>',
1051
						'<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>';
1052
1053
					return false; // End it here if there is an error with activation.
1054
				} else {
1055
					if ( ! $automatic ) {
1056
						// Make sure message doesn't display again if bulk activation is performed
1057
						// immediately after a single activation.
1058
						if ( ! isset( $_POST['action'] ) ) { // WPCS: CSRF OK.
1059
							echo '<div id="message" class="updated"><p>', esc_html( $this->strings['activated_successfully'] ), ' <strong>', esc_html( $this->plugins[ $slug ]['name'] ), '.</strong></p></div>';
1060
						}
1061
					} else {
1062
						// Simpler message layout for use on the plugin install page.
1063
						echo '<p>', esc_html( $this->strings['plugin_activated'] ), '</p>';
1064
					}
1065
				}
1066 View Code Duplication
			} elseif ( $this->is_plugin_active( $slug ) ) {
1067
				// No simpler message format provided as this message should never be encountered
1068
				// on the plugin install page.
1069
				echo '<div id="message" class="error"><p>',
1070
					sprintf(
1071
						esc_html( $this->strings['plugin_already_active'] ),
1072
						'<strong>' . esc_html( $this->plugins[ $slug ]['name'] ) . '</strong>'
1073
					),
1074
					'</p></div>';
1075
			} elseif ( $this->does_plugin_require_update( $slug ) ) {
1076
				if ( ! $automatic ) {
1077
					// Make sure message doesn't display again if bulk activation is performed
1078
					// immediately after a single activation.
1079 View Code Duplication
					if ( ! isset( $_POST['action'] ) ) { // WPCS: CSRF OK.
1080
						echo '<div id="message" class="error"><p>',
1081
							sprintf(
1082
								esc_html( $this->strings['plugin_needs_higher_version'] ),
1083
								'<strong>' . esc_html( $this->plugins[ $slug ]['name'] ) . '</strong>'
1084
							),
1085
							'</p></div>';
1086
					}
1087
				} else {
1088
					// Simpler message layout for use on the plugin install page.
1089
					echo '<p>', sprintf( esc_html( $this->strings['plugin_needs_higher_version'] ), esc_html( $this->plugins[ $slug ]['name'] ) ), '</p>';
1090
				}
1091
			}
1092
1093
			return true;
1094
		}
1095
1096
		/**
1097
		 * Echoes required plugin notice.
1098
		 *
1099
		 * Outputs a message telling users that a specific plugin is required for
1100
		 * their theme. If appropriate, it includes a link to the form page where
1101
		 * users can install and activate the plugin.
1102
		 *
1103
		 * Returns early if we're on the Install page.
1104
		 *
1105
		 * @since 1.0.0
1106
		 *
1107
		 * @global object $current_screen
1108
		 *
1109
		 * @return null Returns early if we're on the Install page.
1110
		 */
1111
		public function notices() {
1112
			// Remove nag on the install page / Return early if the nag message has been dismissed or user < author.
1113
			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' ) ) ) {
1114
				return;
1115
			}
1116
1117
			// Store for the plugin slugs by message type.
1118
			$message = array();
1119
1120
			// Initialize counters used to determine plurality of action link texts.
1121
			$install_link_count          = 0;
1122
			$update_link_count           = 0;
1123
			$activate_link_count         = 0;
1124
			$total_required_action_count = 0;
1125
1126
			foreach ( $this->plugins as $slug => $plugin ) {
1127
				if ( $this->is_plugin_active( $slug ) && false === $this->does_plugin_have_update( $slug ) ) {
1128
					continue;
1129
				}
1130
1131
				if ( ! $this->is_plugin_installed( $slug ) ) {
1132
					if ( current_user_can( 'install_plugins' ) ) {
1133
						$install_link_count++;
1134
1135
						if ( true === $plugin['required'] ) {
1136
							$message['notice_can_install_required'][] = $slug;
1137
						} else {
1138
							$message['notice_can_install_recommended'][] = $slug;
1139
						}
1140
					}
1141
					if ( true === $plugin['required'] ) {
1142
						$total_required_action_count++;
1143
					}
1144
				} else {
1145
					if ( ! $this->is_plugin_active( $slug ) && $this->can_plugin_activate( $slug ) ) {
1146
						if ( current_user_can( 'activate_plugins' ) ) {
1147
							$activate_link_count++;
1148
1149
							if ( true === $plugin['required'] ) {
1150
								$message['notice_can_activate_required'][] = $slug;
1151
							} else {
1152
								$message['notice_can_activate_recommended'][] = $slug;
1153
							}
1154
						}
1155
						if ( true === $plugin['required'] ) {
1156
							$total_required_action_count++;
1157
						}
1158
					}
1159
1160
					if ( $this->does_plugin_require_update( $slug ) || false !== $this->does_plugin_have_update( $slug ) ) {
1161
1162
						if ( current_user_can( 'update_plugins' ) ) {
1163
							$update_link_count++;
1164
1165
							if ( $this->does_plugin_require_update( $slug ) ) {
1166
								$message['notice_ask_to_update'][] = $slug;
1167
							} elseif ( false !== $this->does_plugin_have_update( $slug ) ) {
1168
								$message['notice_ask_to_update_maybe'][] = $slug;
1169
							}
1170
						}
1171
						if ( true === $plugin['required'] ) {
1172
							$total_required_action_count++;
1173
						}
1174
					}
1175
				}
1176
			}
1177
			unset( $slug, $plugin );
1178
1179
			// If we have notices to display, we move forward.
1180
			if ( ! empty( $message ) || $total_required_action_count > 0 ) {
1181
				krsort( $message ); // Sort messages.
1182
				$rendered = '';
1183
1184
				// As add_settings_error() wraps the final message in a <p> and as the final message can't be
1185
				// filtered, using <p>'s in our html would render invalid html output.
1186
				$line_template = '<span style="display: block; margin: 0.5em 0.5em 0 0; clear: both;">%s</span>' . "\n";
1187
1188
				if ( ! current_user_can( 'activate_plugins' ) && ! current_user_can( 'install_plugins' ) && ! current_user_can( 'update_plugins' ) ) {
1189
					$rendered  = esc_html( $this->strings['notice_cannot_install_activate'] ) . ' ' . esc_html( $this->strings['contact_admin'] );
1190
					$rendered .= $this->create_user_action_links_for_notice( 0, 0, 0, $line_template );
1191
				} else {
1192
1193
					// If dismissable is false and a message is set, output it now.
1194
					if ( ! $this->dismissable && ! empty( $this->dismiss_msg ) ) {
1195
						$rendered .= sprintf( $line_template, wp_kses_post( $this->dismiss_msg ) );
1196
					}
1197
1198
					// Render the individual message lines for the notice.
1199
					foreach ( $message as $type => $plugin_group ) {
1200
						$linked_plugins = array();
1201
1202
						// Get the external info link for a plugin if one is available.
1203
						foreach ( $plugin_group as $plugin_slug ) {
1204
							$linked_plugins[] = $this->get_info_link( $plugin_slug );
1205
						}
1206
						unset( $plugin_slug );
1207
1208
						$count          = count( $plugin_group );
1209
						$linked_plugins = array_map( array( TGMPA_Utils::class, 'wrap_in_em' ), $linked_plugins );
1210
						$last_plugin    = array_pop( $linked_plugins ); // Pop off last name to prep for readability.
1211
						$imploded       = empty( $linked_plugins ) ? $last_plugin : ( implode( ', ', $linked_plugins ) . ' ' . esc_html_x( 'and', 'plugin A *and* plugin B', 'tgmpa' ) . ' ' . $last_plugin );
1212
1213
						$rendered .= sprintf(
1214
							$line_template,
1215
							sprintf(
1216
								translate_nooped_plural( $this->strings[ $type ], $count, 'tgmpa' ),
1217
								$imploded,
1218
								$count
1219
							)
1220
						);
1221
1222
					}
1223
					unset( $type, $plugin_group, $linked_plugins, $count, $last_plugin, $imploded );
1224
1225
					$rendered .= $this->create_user_action_links_for_notice( $install_link_count, $update_link_count, $activate_link_count, $line_template );
1226
				}
1227
1228
				// Register the nag messages and prepare them to be processed.
1229
				add_settings_error( 'tgmpa', 'tgmpa', $rendered, $this->get_admin_notice_class() );
1230
			}
1231
1232
			// Admin options pages already output settings_errors, so this is to avoid duplication.
1233
			if ( 'options-general' !== $GLOBALS['current_screen']->parent_base ) {
1234
				$this->display_settings_errors();
1235
			}
1236
		}
1237
1238
		/**
1239
		 * Generate the user action links for the admin notice.
1240
		 *
1241
		 * @since 2.6.0
1242
		 *
1243
		 * @param int $install_count  Number of plugins to install.
1244
		 * @param int $update_count   Number of plugins to update.
1245
		 * @param int $activate_count Number of plugins to activate.
1246
		 * @param int $line_template  Template for the HTML tag to output a line.
1247
		 * @return string Action links.
1248
		 */
1249
		protected function create_user_action_links_for_notice( $install_count, $update_count, $activate_count, $line_template ) {
1250
			// Setup action links.
1251
			$action_links = array(
1252
				'install'  => '',
1253
				'update'   => '',
1254
				'activate' => '',
1255
				'dismiss'  => $this->dismissable ? '<a href="' . esc_url( wp_nonce_url( add_query_arg( 'tgmpa-dismiss', 'dismiss_admin_notices' ), 'tgmpa-dismiss-' . get_current_user_id() ) ) . '" class="dismiss-notice" target="_parent">' . esc_html( $this->strings['dismiss'] ) . '</a>' : '',
1256
			);
1257
1258
			$link_template = '<a href="%2$s">%1$s</a>';
1259
1260
			if ( current_user_can( 'install_plugins' ) ) {
1261
				if ( $install_count > 0 ) {
1262
					$action_links['install'] = sprintf(
1263
						$link_template,
1264
						translate_nooped_plural( $this->strings['install_link'], $install_count, 'tgmpa' ),
1265
						esc_url( $this->get_tgmpa_status_url( 'install' ) )
1266
					);
1267
				}
1268
				if ( $update_count > 0 ) {
1269
					$action_links['update'] = sprintf(
1270
						$link_template,
1271
						translate_nooped_plural( $this->strings['update_link'], $update_count, 'tgmpa' ),
1272
						esc_url( $this->get_tgmpa_status_url( 'update' ) )
1273
					);
1274
				}
1275
			}
1276
1277
			if ( current_user_can( 'activate_plugins' ) && $activate_count > 0 ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
1278
				$action_links['activate'] = sprintf(
1279
					$link_template,
1280
					translate_nooped_plural( $this->strings['activate_link'], $activate_count, 'tgmpa' ),
1281
					esc_url( $this->get_tgmpa_status_url( 'activate' ) )
1282
				);
1283
			}
1284
1285
			$action_links = apply_filters( 'tgmpa_notice_action_links', $action_links );
1286
1287
			$action_links = array_filter( (array) $action_links ); // Remove any empty array items.
1288
1289
			if ( ! empty( $action_links ) ) {
1290
				$action_links = sprintf( $line_template, implode( ' | ', $action_links ) );
1291
				return apply_filters( 'tgmpa_notice_rendered_action_links', $action_links );
1292
			} else {
1293
				return '';
1294
			}
1295
		}
1296
1297
		/**
1298
		 * Get admin notice class.
1299
		 *
1300
		 * Work around all the changes to the various admin notice classes between WP 4.4 and 3.7
1301
		 * (lowest supported version by TGMPA).
1302
		 *
1303
		 * @since 2.6.0
1304
		 *
1305
		 * @return string
1306
		 */
1307
		protected function get_admin_notice_class() {
1308
			if ( ! empty( $this->strings['nag_type'] ) ) {
1309
				return sanitize_html_class( strtolower( $this->strings['nag_type'] ) );
1310
			} else {
1311
				if ( version_compare( $this->wp_version, '4.2', '>=' ) ) {
1312
					return 'notice-warning';
1313
				} elseif ( version_compare( $this->wp_version, '4.1', '>=' ) ) {
1314
					return 'notice';
1315
				} else {
1316
					return 'updated';
1317
				}
1318
			}
1319
		}
1320
1321
		/**
1322
		 * Display settings errors and remove those which have been displayed to avoid duplicate messages showing
1323
		 *
1324
		 * @since 2.5.0
1325
		 */
1326
		protected function display_settings_errors() {
1327
			global $wp_settings_errors;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
1328
1329
			settings_errors( 'tgmpa' );
1330
1331
			foreach ( (array) $wp_settings_errors as $key => $details ) {
1332
				if ( 'tgmpa' === $details['setting'] ) {
1333
					unset( $wp_settings_errors[ $key ] );
1334
					break;
1335
				}
1336
			}
1337
		}
1338
1339
		/**
1340
		 * Register dismissal of admin notices.
1341
		 *
1342
		 * Acts on the dismiss link in the admin nag messages.
1343
		 * If clicked, the admin notice disappears and will no longer be visible to this user.
1344
		 *
1345
		 * @since 2.1.0
1346
		 */
1347
		public function dismiss() {
1348
			if ( isset( $_GET['tgmpa-dismiss'] ) && check_admin_referer( 'tgmpa-dismiss-' . get_current_user_id() ) ) {
1349
				update_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, 1 );
1350
			}
1351
		}
1352
1353
		/**
1354
		 * Add individual plugin to our collection of plugins.
1355
		 *
1356
		 * If the required keys are not set or the plugin has already
1357
		 * been registered, the plugin is not added.
1358
		 *
1359
		 * @since 2.0.0
1360
		 *
1361
		 * @param array|null $plugin Array of plugin arguments or null if invalid argument.
1362
		 * @return null Return early if incorrect argument.
1363
		 */
1364
		public function register( $plugin ) {
1365
			if ( empty( $plugin['slug'] ) || empty( $plugin['name'] ) ) {
1366
				return;
1367
			}
1368
1369
			if ( empty( $plugin['slug'] ) || ! is_string( $plugin['slug'] ) || isset( $this->plugins[ $plugin['slug'] ] ) ) {
1370
				return;
1371
			}
1372
1373
			$defaults = array(
1374
				'name'               => '',      // String
1375
				'slug'               => '',      // String
1376
				'source'             => 'repo',  // String
1377
				'required'           => false,   // Boolean
1378
				'version'            => '',      // String
1379
				'force_activation'   => false,   // Boolean
1380
				'force_deactivation' => false,   // Boolean
1381
				'external_url'       => '',      // String
1382
				'is_callable'        => '',      // String|Array.
1383
			);
1384
1385
			// Prepare the received data.
1386
			$plugin = wp_parse_args( $plugin, $defaults );
1387
1388
			// Standardize the received slug.
1389
			$plugin['slug'] = $this->sanitize_key( $plugin['slug'] );
1390
1391
			// Forgive users for using string versions of booleans or floats for version number.
1392
			$plugin['version']            = (string) $plugin['version'];
1393
			$plugin['source']             = empty( $plugin['source'] ) ? 'repo' : $plugin['source'];
1394
			$plugin['required']           = TGMPA_Utils::validate_bool( $plugin['required'] );
1395
			$plugin['force_activation']   = TGMPA_Utils::validate_bool( $plugin['force_activation'] );
1396
			$plugin['force_deactivation'] = TGMPA_Utils::validate_bool( $plugin['force_deactivation'] );
1397
1398
			// Enrich the received data.
1399
			$plugin['file_path']   = $this->_get_plugin_basename_from_slug( $plugin['slug'] );
1400
			$plugin['source_type'] = $this->get_plugin_source_type( $plugin['source'] );
1401
1402
			// Set the class properties.
1403
			$this->plugins[ $plugin['slug'] ]    = $plugin;
1404
			$this->sort_order[ $plugin['slug'] ] = $plugin['name'];
1405
1406
			// Should we add the force activation hook ?
1407
			if ( true === $plugin['force_activation'] ) {
1408
				$this->has_forced_activation = true;
1409
			}
1410
1411
			// Should we add the force deactivation hook ?
1412
			if ( true === $plugin['force_deactivation'] ) {
1413
				$this->has_forced_deactivation = true;
1414
			}
1415
		}
1416
1417
		/**
1418
		 * Determine what type of source the plugin comes from.
1419
		 *
1420
		 * @since 2.5.0
1421
		 *
1422
		 * @param string $source The source of the plugin as provided, either empty (= WP repo), a file path
1423
		 *                       (= bundled) or an external URL.
1424
		 * @return string 'repo', 'external', or 'bundled'
1425
		 */
1426
		protected function get_plugin_source_type( $source ) {
1427
			if ( 'repo' === $source || preg_match( self::WP_REPO_REGEX, $source ) ) {
1428
				return 'repo';
1429
			} elseif ( preg_match( self::IS_URL_REGEX, $source ) ) {
1430
				return 'external';
1431
			} else {
1432
				return 'bundled';
1433
			}
1434
		}
1435
1436
		/**
1437
		 * Sanitizes a string key.
1438
		 *
1439
		 * Near duplicate of WP Core `sanitize_key()`. The difference is that uppercase characters *are*
1440
		 * allowed, so as not to break upgrade paths from non-standard bundled plugins using uppercase
1441
		 * characters in the plugin directory path/slug. Silly them.
1442
		 *
1443
		 * @see https://developer.wordpress.org/reference/hooks/sanitize_key/
1444
		 *
1445
		 * @since 2.5.0
1446
		 *
1447
		 * @param string $key String key.
1448
		 * @return string Sanitized key
1449
		 */
1450
		public function sanitize_key( $key ) {
1451
			$raw_key = $key;
1452
			$key     = preg_replace( '`[^A-Za-z0-9_-]`', '', $key );
1453
1454
			/**
1455
			 * Filter a sanitized key string.
1456
			 *
1457
			 * @since 2.5.0
1458
			 *
1459
			 * @param string $key     Sanitized key.
1460
			 * @param string $raw_key The key prior to sanitization.
1461
			 */
1462
			return apply_filters( 'tgmpa_sanitize_key', $key, $raw_key );
1463
		}
1464
1465
		/**
1466
		 * Amend default configuration settings.
1467
		 *
1468
		 * @since 2.0.0
1469
		 *
1470
		 * @param array $config Array of config options to pass as class properties.
1471
		 */
1472
		public function config( $config ) {
1473
			$keys = array(
1474
				'id',
1475
				'default_path',
1476
				'has_notices',
1477
				'dismissable',
1478
				'dismiss_msg',
1479
				'menu',
1480
				'parent_slug',
1481
				'capability',
1482
				'is_automatic',
1483
				'message',
1484
				'strings',
1485
			);
1486
1487
			foreach ( $keys as $key ) {
1488
				if ( isset( $config[ $key ] ) ) {
1489
					if ( is_array( $config[ $key ] ) ) {
1490
						$this->$key = array_merge( $this->$key, $config[ $key ] );
1491
					} else {
1492
						$this->$key = $config[ $key ];
1493
					}
1494
				}
1495
			}
1496
		}
1497
1498
		/**
1499
		 * Amend action link after plugin installation.
1500
		 *
1501
		 * @since 2.0.0
1502
		 *
1503
		 * @param array $install_actions Existing array of actions.
1504
		 * @return false|array Amended array of actions.
1505
		 */
1506
		public function actions( $install_actions ) {
1507
			// Remove action links on the TGMPA install page.
1508
			if ( $this->is_tgmpa_page() ) {
1509
				return false;
1510
			}
1511
1512
			return $install_actions;
1513
		}
1514
1515
		/**
1516
		 * Flushes the plugins cache on theme switch to prevent stale entries
1517
		 * from remaining in the plugin table.
1518
		 *
1519
		 * @since 2.4.0
1520
		 *
1521
		 * @param bool $clear_update_cache Optional. Whether to clear the Plugin updates cache.
1522
		 *                                 Parameter added in v2.5.0.
1523
		 */
1524
		public function flush_plugins_cache( $clear_update_cache = true ) {
1525
			wp_clean_plugins_cache( $clear_update_cache );
1526
		}
1527
1528
		/**
1529
		 * Set file_path key for each installed plugin.
1530
		 *
1531
		 * @since 2.1.0
1532
		 *
1533
		 * @param string $plugin_slug Optional. If set, only (re-)populates the file path for that specific plugin.
1534
		 *                            Parameter added in v2.5.0.
1535
		 */
1536
		public function populate_file_path( $plugin_slug = '' ) {
1537
			if ( ! empty( $plugin_slug ) && is_string( $plugin_slug ) && isset( $this->plugins[ $plugin_slug ] ) ) {
1538
				$this->plugins[ $plugin_slug ]['file_path'] = $this->_get_plugin_basename_from_slug( $plugin_slug );
1539
			} else {
1540
				// Add file_path key for all plugins.
1541
				foreach ( $this->plugins as $slug => $values ) {
1542
					$this->plugins[ $slug ]['file_path'] = $this->_get_plugin_basename_from_slug( $slug );
1543
				}
1544
			}
1545
		}
1546
1547
		/**
1548
		 * Helper function to extract the file path of the plugin file from the
1549
		 * plugin slug, if the plugin is installed.
1550
		 *
1551
		 * @since 2.0.0
1552
		 *
1553
		 * @param string $slug Plugin slug (typically folder name) as provided by the developer.
1554
		 * @return string Either file path for plugin if installed, or just the plugin slug.
1555
		 */
1556
		protected function _get_plugin_basename_from_slug( $slug ) {
0 ignored issues
show
Coding Style introduced by
function _get_plugin_basename_from_slug() does not seem to conform to the naming convention (^(?:[a-z]|__)[a-z_0-9]*$).

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...
1557
			$keys = array_keys( $this->get_plugins() );
1558
1559
			foreach ( $keys as $key ) {
1560
				if ( preg_match( '|^' . $slug . '/|', $key ) ) {
1561
					return $key;
1562
				}
1563
			}
1564
1565
			return $slug;
1566
		}
1567
1568
		/**
1569
		 * Retrieve plugin data, given the plugin name.
1570
		 *
1571
		 * Loops through the registered plugins looking for $name. If it finds it,
1572
		 * it returns the $data from that plugin. Otherwise, returns false.
1573
		 *
1574
		 * @since 2.1.0
1575
		 *
1576
		 * @param string $name Name of the plugin, as it was registered.
1577
		 * @param string $data Optional. Array key of plugin data to return. Default is slug.
1578
		 * @return string|boolean Plugin slug if found, false otherwise.
1579
		 */
1580
		public function _get_plugin_data_from_name( $name, $data = 'slug' ) {
0 ignored issues
show
Coding Style introduced by
function _get_plugin_data_from_name() does not seem to conform to the naming convention (^(?:[a-z]|__)[a-z_0-9]*$).

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...
1581
			foreach ( $this->plugins as $values ) {
1582
				if ( $name === $values['name'] && isset( $values[ $data ] ) ) {
1583
					return $values[ $data ];
1584
				}
1585
			}
1586
1587
			return false;
1588
		}
1589
1590
		/**
1591
		 * Retrieve the download URL for a package.
1592
		 *
1593
		 * @since 2.5.0
1594
		 *
1595
		 * @param string $slug Plugin slug.
1596
		 * @return string Plugin download URL or path to local file or empty string if undetermined.
1597
		 */
1598
		public function get_download_url( $slug ) {
1599
			$dl_source = '';
1600
1601
			switch ( $this->plugins[ $slug ]['source_type'] ) {
1602
				case 'repo':
1603
					return $this->get_wp_repo_download_url( $slug );
1604
				case 'external':
1605
					return $this->plugins[ $slug ]['source'];
1606
				case 'bundled':
1607
					return $this->default_path . $this->plugins[ $slug ]['source'];
1608
			}
1609
1610
			return $dl_source; // Should never happen.
1611
		}
1612
1613
		/**
1614
		 * Retrieve the download URL for a WP repo package.
1615
		 *
1616
		 * @since 2.5.0
1617
		 *
1618
		 * @param string $slug Plugin slug.
1619
		 * @return string Plugin download URL.
1620
		 */
1621
		protected function get_wp_repo_download_url( $slug ) {
1622
			$source = '';
1623
			$api    = $this->get_plugins_api( $slug );
1624
1625
			if ( false !== $api && isset( $api->download_link ) ) {
1626
				$source = $api->download_link;
1627
			}
1628
1629
			return $source;
1630
		}
1631
1632
		/**
1633
		 * Try to grab information from WordPress API.
1634
		 *
1635
		 * @since 2.5.0
1636
		 *
1637
		 * @param string $slug Plugin slug.
1638
		 * @return object Plugins_api response object on success, WP_Error on failure.
1639
		 */
1640
		protected function get_plugins_api( $slug ) {
1641
			static $api = array(); // Cache received responses.
1642
1643
			if ( ! isset( $api[ $slug ] ) ) {
1644
				if ( ! function_exists( 'plugins_api' ) ) {
1645
					require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
1646
				}
1647
1648
				$response = plugins_api(
1649
					'plugin_information',
1650
					array(
1651
						'slug'   => $slug,
1652
						'fields' => array(
1653
							'sections' => false,
1654
						),
1655
					)
1656
				);
1657
1658
				$api[ $slug ] = false;
1659
1660
				if ( is_wp_error( $response ) ) {
1661
					wp_die( esc_html( $this->strings['oops'] ) );
1662
				} else {
1663
					$api[ $slug ] = $response;
1664
				}
1665
			}
1666
1667
			return $api[ $slug ];
1668
		}
1669
1670
		/**
1671
		 * Retrieve a link to a plugin information page.
1672
		 *
1673
		 * @since 2.5.0
1674
		 *
1675
		 * @param string $slug Plugin slug.
1676
		 * @return string Fully formed html link to a plugin information page if available
1677
		 *                or the plugin name if not.
1678
		 */
1679
		public function get_info_link( $slug ) {
1680
			if ( ! empty( $this->plugins[ $slug ]['external_url'] ) && preg_match( self::IS_URL_REGEX, $this->plugins[ $slug ]['external_url'] ) ) {
1681
				$link = sprintf(
1682
					'<a href="%1$s" target="_blank">%2$s</a>',
1683
					esc_url( $this->plugins[ $slug ]['external_url'] ),
1684
					esc_html( $this->plugins[ $slug ]['name'] )
1685
				);
1686
			} elseif ( 'repo' === $this->plugins[ $slug ]['source_type'] ) {
1687
				$url = add_query_arg(
1688
					array(
1689
						'tab'       => 'plugin-information',
1690
						'plugin'    => urlencode( $slug ),
1691
						'TB_iframe' => 'true',
1692
						'width'     => '640',
1693
						'height'    => '500',
1694
					),
1695
					self_admin_url( 'plugin-install.php' )
1696
				);
1697
1698
				$link = sprintf(
1699
					'<a href="%1$s" class="thickbox">%2$s</a>',
1700
					esc_url( $url ),
1701
					esc_html( $this->plugins[ $slug ]['name'] )
1702
				);
1703
			} else {
1704
				$link = esc_html( $this->plugins[ $slug ]['name'] ); // No hyperlink.
1705
			}
1706
1707
			return $link;
1708
		}
1709
1710
		/**
1711
		 * Determine if we're on the TGMPA Install page.
1712
		 *
1713
		 * @since 2.1.0
1714
		 *
1715
		 * @return boolean True when on the TGMPA page, false otherwise.
1716
		 */
1717
		protected function is_tgmpa_page() {
1718
			return isset( $_GET['page'] ) && $this->menu === $_GET['page'];
1719
		}
1720
1721
		/**
1722
		 * Determine if we're on a WP Core installation/upgrade page.
1723
		 *
1724
		 * @since 2.6.0
1725
		 *
1726
		 * @return boolean True when on a WP Core installation/upgrade page, false otherwise.
1727
		 */
1728
		protected function is_core_update_page() {
1729
			// Current screen is not always available, most notably on the customizer screen.
1730
			if ( ! function_exists( 'get_current_screen' ) ) {
1731
				return false;
1732
			}
1733
1734
			$screen = get_current_screen();
1735
1736
			if ( 'update-core' === $screen->base ) {
1737
				// Core update screen.
1738
				return true;
1739
			} elseif ( 'plugins' === $screen->base && ! empty( $_POST['action'] ) ) { // WPCS: CSRF ok.
1740
				// Plugins bulk update screen.
1741
				return true;
1742
			} elseif ( 'update' === $screen->base && ! empty( $_POST['action'] ) ) { // WPCS: CSRF ok.
1743
				// Individual updates (ajax call).
1744
				return true;
1745
			}
1746
1747
			return false;
1748
		}
1749
1750
		/**
1751
		 * Retrieve the URL to the TGMPA Install page.
1752
		 *
1753
		 * I.e. depending on the config settings passed something along the lines of:
1754
		 * http://example.com/wp-admin/themes.php?page=tgmpa-install-plugins
1755
		 *
1756
		 * @since 2.5.0
1757
		 *
1758
		 * @return string Properly encoded URL (not escaped).
1759
		 */
1760
		public function get_tgmpa_url() {
1761
			static $url;
1762
1763
			if ( ! isset( $url ) ) {
1764
				$parent = $this->parent_slug;
1765
				if ( false === strpos( $parent, '.php' ) ) {
1766
					$parent = 'admin.php';
1767
				}
1768
				$url = add_query_arg(
1769
					array(
1770
						'page' => urlencode( $this->menu ),
1771
					),
1772
					self_admin_url( $parent )
1773
				);
1774
			}
1775
1776
			return $url;
1777
		}
1778
1779
		/**
1780
		 * Retrieve the URL to the TGMPA Install page for a specific plugin status (view).
1781
		 *
1782
		 * I.e. depending on the config settings passed something along the lines of:
1783
		 * http://example.com/wp-admin/themes.php?page=tgmpa-install-plugins&plugin_status=install
1784
		 *
1785
		 * @since 2.5.0
1786
		 *
1787
		 * @param string $status Plugin status - either 'install', 'update' or 'activate'.
1788
		 * @return string Properly encoded URL (not escaped).
1789
		 */
1790
		public function get_tgmpa_status_url( $status ) {
1791
			return add_query_arg(
1792
				array(
1793
					'plugin_status' => urlencode( $status ),
1794
				),
1795
				$this->get_tgmpa_url()
1796
			);
1797
		}
1798
1799
		/**
1800
		 * Determine whether there are open actions for plugins registered with TGMPA.
1801
		 *
1802
		 * @since 2.5.0
1803
		 *
1804
		 * @return bool True if complete, i.e. no outstanding actions. False otherwise.
1805
		 */
1806
		public function is_tgmpa_complete() {
1807
			$complete = true;
1808
			foreach ( $this->plugins as $slug => $plugin ) {
1809
				if ( ! $this->is_plugin_active( $slug ) || false !== $this->does_plugin_have_update( $slug ) ) {
1810
					$complete = false;
1811
					break;
1812
				}
1813
			}
1814
1815
			return $complete;
1816
		}
1817
1818
		/**
1819
		 * Check if a plugin is installed. Does not take must-use plugins into account.
1820
		 *
1821
		 * @since 2.5.0
1822
		 *
1823
		 * @param string $slug Plugin slug.
1824
		 * @return bool True if installed, false otherwise.
1825
		 */
1826
		public function is_plugin_installed( $slug ) {
1827
			$installed_plugins = $this->get_plugins(); // Retrieve a list of all installed plugins (WP cached).
1828
1829
			return ( ! empty( $installed_plugins[ $this->plugins[ $slug ]['file_path'] ] ) );
1830
		}
1831
1832
		/**
1833
		 * Check if a plugin is active.
1834
		 *
1835
		 * @since 2.5.0
1836
		 *
1837
		 * @param string $slug Plugin slug.
1838
		 * @return bool True if active, false otherwise.
1839
		 */
1840
		public function is_plugin_active( $slug ) {
1841
			return ( ( ! empty( $this->plugins[ $slug ]['is_callable'] ) && is_callable( $this->plugins[ $slug ]['is_callable'] ) ) || is_plugin_active( $this->plugins[ $slug ]['file_path'] ) );
1842
		}
1843
1844
		/**
1845
		 * Check if a plugin can be updated, i.e. if we have information on the minimum WP version required
1846
		 * available, check whether the current install meets them.
1847
		 *
1848
		 * @since 2.5.0
1849
		 *
1850
		 * @param string $slug Plugin slug.
1851
		 * @return bool True if OK to update, false otherwise.
1852
		 */
1853
		public function can_plugin_update( $slug ) {
0 ignored issues
show
Coding Style introduced by
function can_plugin_update() 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...
1854
			// We currently can't get reliable info on non-WP-repo plugins - issue #380.
1855
			if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) {
1856
				return true;
1857
			}
1858
1859
			$api = $this->get_plugins_api( $slug );
1860
1861
			if ( false !== $api && isset( $api->requires ) ) {
1862
				return version_compare( $this->wp_version, $api->requires, '>=' );
1863
			}
1864
1865
			// No usable info received from the plugins API, presume we can update.
1866
			return true;
1867
		}
1868
1869
		/**
1870
		 * Check to see if the plugin is 'updatetable', i.e. installed, with an update available
1871
		 * and no WP version requirements blocking it.
1872
		 *
1873
		 * @since 2.6.0
1874
		 *
1875
		 * @param string $slug Plugin slug.
1876
		 * @return bool True if OK to proceed with update, false otherwise.
1877
		 */
1878
		public function is_plugin_updatetable( $slug ) {
1879
			if ( ! $this->is_plugin_installed( $slug ) ) {
1880
				return false;
1881
			} else {
1882
				return ( false !== $this->does_plugin_have_update( $slug ) && $this->can_plugin_update( $slug ) );
1883
			}
1884
		}
1885
1886
		/**
1887
		 * Check if a plugin can be activated, i.e. is not currently active and meets the minimum
1888
		 * plugin version requirements set in TGMPA (if any).
1889
		 *
1890
		 * @since 2.5.0
1891
		 *
1892
		 * @param string $slug Plugin slug.
1893
		 * @return bool True if OK to activate, false otherwise.
1894
		 */
1895
		public function can_plugin_activate( $slug ) {
0 ignored issues
show
Coding Style introduced by
function can_plugin_activate() 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...
1896
			return ( ! $this->is_plugin_active( $slug ) && ! $this->does_plugin_require_update( $slug ) );
1897
		}
1898
1899
		/**
1900
		 * Retrieve the version number of an installed plugin.
1901
		 *
1902
		 * @since 2.5.0
1903
		 *
1904
		 * @param string $slug Plugin slug.
1905
		 * @return string Version number as string or an empty string if the plugin is not installed
1906
		 *                or version unknown (plugins which don't comply with the plugin header standard).
1907
		 */
1908
		public function get_installed_version( $slug ) {
1909
			$installed_plugins = $this->get_plugins(); // Retrieve a list of all installed plugins (WP cached).
1910
1911
			if ( ! empty( $installed_plugins[ $this->plugins[ $slug ]['file_path'] ]['Version'] ) ) {
1912
				return $installed_plugins[ $this->plugins[ $slug ]['file_path'] ]['Version'];
1913
			}
1914
1915
			return '';
1916
		}
1917
1918
		/**
1919
		 * Check whether a plugin complies with the minimum version requirements.
1920
		 *
1921
		 * @since 2.5.0
1922
		 *
1923
		 * @param string $slug Plugin slug.
1924
		 * @return bool True when a plugin needs to be updated, otherwise false.
1925
		 */
1926
		public function does_plugin_require_update( $slug ) {
0 ignored issues
show
Coding Style introduced by
function does_plugin_require_update() 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...
1927
			$installed_version = $this->get_installed_version( $slug );
1928
			$minimum_version   = $this->plugins[ $slug ]['version'];
1929
1930
			return version_compare( $minimum_version, $installed_version, '>' );
1931
		}
1932
1933
		/**
1934
		 * Check whether there is an update available for a plugin.
1935
		 *
1936
		 * @since 2.5.0
1937
		 *
1938
		 * @param string $slug Plugin slug.
1939
		 * @return false|string Version number string of the available update or false if no update available.
1940
		 */
1941
		public function does_plugin_have_update( $slug ) {
1942
			// Presume bundled and external plugins will point to a package which meets the minimum required version.
1943
			if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) {
1944
				if ( $this->does_plugin_require_update( $slug ) ) {
1945
					return $this->plugins[ $slug ]['version'];
1946
				}
1947
1948
				return false;
1949
			}
1950
1951
			$repo_updates = get_site_transient( 'update_plugins' );
1952
1953 View Code Duplication
			if ( isset( $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->new_version ) ) {
1954
				return $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->new_version;
1955
			}
1956
1957
			return false;
1958
		}
1959
1960
		/**
1961
		 * Retrieve potential upgrade notice for a plugin.
1962
		 *
1963
		 * @since 2.5.0
1964
		 *
1965
		 * @param string $slug Plugin slug.
1966
		 * @return string The upgrade notice or an empty string if no message was available or provided.
1967
		 */
1968
		public function get_upgrade_notice( $slug ) {
1969
			// We currently can't get reliable info on non-WP-repo plugins - issue #380.
1970
			if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) {
1971
				return '';
1972
			}
1973
1974
			$repo_updates = get_site_transient( 'update_plugins' );
1975
1976 View Code Duplication
			if ( ! empty( $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->upgrade_notice ) ) {
1977
				return $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->upgrade_notice;
1978
			}
1979
1980
			return '';
1981
		}
1982
1983
		/**
1984
		 * Wrapper around the core WP get_plugins function, making sure it's actually available.
1985
		 *
1986
		 * @since 2.5.0
1987
		 *
1988
		 * @param string $plugin_folder Optional. Relative path to single plugin folder.
1989
		 * @return array Array of installed plugins with plugin information.
1990
		 */
1991
		public function get_plugins( $plugin_folder = '' ) {
1992
			if ( ! function_exists( 'get_plugins' ) ) {
1993
				require_once ABSPATH . 'wp-admin/includes/plugin.php';
1994
			}
1995
1996
			return get_plugins( $plugin_folder );
1997
		}
1998
1999
		/**
2000
		 * Delete dismissable nag option when theme is switched.
2001
		 *
2002
		 * This ensures that the user(s) is/are again reminded via nag of required
2003
		 * and/or recommended plugins if they re-activate the theme.
2004
		 *
2005
		 * @since 2.1.1
2006
		 */
2007
		public function update_dismiss() {
2008
			delete_metadata( 'user', null, 'tgmpa_dismissed_notice_' . $this->id, null, true );
2009
		}
2010
2011
		/**
2012
		 * Forces plugin activation if the parameter 'force_activation' is
2013
		 * set to true.
2014
		 *
2015
		 * This allows theme authors to specify certain plugins that must be
2016
		 * active at all times while using the current theme.
2017
		 *
2018
		 * Please take special care when using this parameter as it has the
2019
		 * potential to be harmful if not used correctly. Setting this parameter
2020
		 * to true will not allow the specified plugin to be deactivated unless
2021
		 * the user switches themes.
2022
		 *
2023
		 * @since 2.2.0
2024
		 */
2025
		public function force_activation() {
2026
			foreach ( $this->plugins as $slug => $plugin ) {
2027
				if ( true === $plugin['force_activation'] ) {
2028
					if ( ! $this->is_plugin_installed( $slug ) ) {
2029
						// Oops, plugin isn't there so iterate to next condition.
2030
						continue;
2031
					} elseif ( $this->can_plugin_activate( $slug ) ) {
2032
						// There we go, activate the plugin.
2033
						activate_plugin( $plugin['file_path'] );
2034
					}
2035
				}
2036
			}
2037
		}
2038
2039
		/**
2040
		 * Forces plugin deactivation if the parameter 'force_deactivation'
2041
		 * is set to true and adds the plugin to the 'recently active' plugins list.
2042
		 *
2043
		 * This allows theme authors to specify certain plugins that must be
2044
		 * deactivated upon switching from the current theme to another.
2045
		 *
2046
		 * Please take special care when using this parameter as it has the
2047
		 * potential to be harmful if not used correctly.
2048
		 *
2049
		 * @since 2.2.0
2050
		 */
2051
		public function force_deactivation() {
2052
			$deactivated = array();
2053
2054
			foreach ( $this->plugins as $slug => $plugin ) {
2055
				/*
2056
				 * Only proceed forward if the parameter is set to true and plugin is active
2057
				 * as a 'normal' (not must-use) plugin.
2058
				 */
2059
				if ( true === $plugin['force_deactivation'] && is_plugin_active( $plugin['file_path'] ) ) {
2060
					deactivate_plugins( $plugin['file_path'] );
2061
					$deactivated[ $plugin['file_path'] ] = time();
2062
				}
2063
			}
2064
2065
			if ( ! empty( $deactivated ) ) {
2066
				update_option( 'recently_activated', $deactivated + (array) get_option( 'recently_activated' ) );
2067
			}
2068
		}
2069
2070
		/**
2071
		 * Echo the current TGMPA version number to the page.
2072
		 *
2073
		 * @since 2.5.0
2074
		 */
2075
		public function show_tgmpa_version() {
2076
			echo '<p style="float: right; padding: 0em 1.5em 0.5em 0;"><strong><small>',
2077
				esc_html(
2078
					sprintf(
2079
						/* translators: %s: version number */
2080
						__( 'TGMPA v%s', 'tgmpa' ),
2081
						self::TGMPA_VERSION
2082
					)
2083
				),
2084
				'</small></strong></p>';
2085
		}
2086
2087
		/**
2088
		 * Adds CSS to admin head.
2089
		 *
2090
		 * @since 2.6.2
2091
		 */
2092
		public function admin_css() {
2093
			if ( ! $this->is_tgmpa_page() ) {
2094
				return;
2095
			}
2096
2097
			echo '
2098
			<style>
2099
			#tgmpa-plugins .tgmpa-type-required > th {
2100
				border-left: 3px solid #dc3232;
2101
			}
2102
			</style>';
2103
		}
2104
2105
		/**
2106
		 * Returns the singleton instance of the class.
2107
		 *
2108
		 * @since 2.4.0
2109
		 *
2110
		 * @return \TGM_Plugin_Activation The TGM_Plugin_Activation object.
0 ignored issues
show
Documentation introduced by
Should the return type not be TGM_Plugin_Activation?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
2111
		 */
2112
		public static function get_instance() {
2113
			if ( ! isset( self::$instance ) && ! ( self::$instance instanceof self ) ) {
2114
				self::$instance = new self();
2115
			}
2116
2117
			return self::$instance;
2118
		}
2119
	}
2120