Completed
Push — develop ( d9f9af...ac26ad )
by Juliette
02:40
created

class-tgm-plugin-activation.php (3 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
if ( ! class_exists( 'TGM_Plugin_Activation' ) ) {
36
37
	/**
38
	 * Automatic plugin installation and activation library.
39
	 *
40
	 * Creates a way to automatically install and activate plugins from within themes.
41
	 * The plugins can be either bundled, downloaded from the WordPress
42
	 * Plugin Repository or downloaded from another external source.
43
	 *
44
	 * @since 1.0.0
45
	 *
46
	 * @package TGM-Plugin-Activation
47
	 * @author  Thomas Griffin
48
	 * @author  Gary Jones
49
	 */
50
	class TGM_Plugin_Activation {
51
		/**
52
		 * TGMPA version number.
53
		 *
54
		 * @since 2.5.0
55
		 *
56
		 * @const string Version number.
57
		 */
58
		const TGMPA_VERSION = '2.6.1';
59
60
		/**
61
		 * Regular expression to test if a URL is a WP plugin repo URL.
62
		 *
63
		 * @const string Regex.
64
		 *
65
		 * @since 2.5.0
66
		 */
67
		const WP_REPO_REGEX = '|^http[s]?://wordpress\.org/(?:extend/)?plugins/|';
68
69
		/**
70
		 * Arbitrary regular expression to test if a string starts with a URL.
71
		 *
72
		 * @const string Regex.
73
		 *
74
		 * @since 2.5.0
75
		 */
76
		const IS_URL_REGEX = '|^http[s]?://|';
77
78
		/**
79
		 * Holds a copy of itself, so it can be referenced by the class name.
80
		 *
81
		 * @since 1.0.0
82
		 *
83
		 * @var TGM_Plugin_Activation
84
		 */
85
		public static $instance;
86
87
		/**
88
		 * Holds arrays of plugin details.
89
		 *
90
		 * @since 1.0.0
91
		 * @since 2.5.0 the array has the plugin slug as an associative key.
92
		 *
93
		 * @var array
94
		 */
95
		public $plugins = array();
96
97
		/**
98
		 * Holds arrays of plugin names to use to sort the plugins array.
99
		 *
100
		 * @since 2.5.0
101
		 *
102
		 * @var array
103
		 */
104
		protected $sort_order = array();
105
106
		/**
107
		 * Whether any plugins have the 'force_activation' setting set to true.
108
		 *
109
		 * @since 2.5.0
110
		 *
111
		 * @var bool
112
		 */
113
		protected $has_forced_activation = false;
114
115
		/**
116
		 * Whether any plugins have the 'force_deactivation' setting set to true.
117
		 *
118
		 * @since 2.5.0
119
		 *
120
		 * @var bool
121
		 */
122
		protected $has_forced_deactivation = false;
123
124
		/**
125
		 * Name of the unique ID to hash notices.
126
		 *
127
		 * @since 2.4.0
128
		 *
129
		 * @var string
130
		 */
131
		public $id = 'tgmpa';
132
133
		/**
134
		 * Name of the query-string argument for the admin page.
135
		 *
136
		 * @since 1.0.0
137
		 *
138
		 * @var string
139
		 */
140
		protected $menu = 'tgmpa-install-plugins';
141
142
		/**
143
		 * Parent menu file slug.
144
		 *
145
		 * @since 2.5.0
146
		 *
147
		 * @var string
148
		 */
149
		public $parent_slug = 'themes.php';
150
151
		/**
152
		 * Capability needed to view the plugin installation menu item.
153
		 *
154
		 * @since 2.5.0
155
		 *
156
		 * @var string
157
		 */
158
		public $capability = 'edit_theme_options';
159
160
		/**
161
		 * Default absolute path to folder containing bundled plugin zip files.
162
		 *
163
		 * @since 2.0.0
164
		 *
165
		 * @var string Absolute path prefix to zip file location for bundled plugins. Default is empty string.
166
		 */
167
		public $default_path = '';
168
169
		/**
170
		 * Flag to show admin notices or not.
171
		 *
172
		 * @since 2.1.0
173
		 *
174
		 * @var boolean
175
		 */
176
		public $has_notices = true;
177
178
		/**
179
		 * Flag to determine if the user can dismiss the notice nag.
180
		 *
181
		 * @since 2.4.0
182
		 *
183
		 * @var boolean
184
		 */
185
		public $dismissable = true;
186
187
		/**
188
		 * Message to be output above nag notice if dismissable is false.
189
		 *
190
		 * @since 2.4.0
191
		 *
192
		 * @var string
193
		 */
194
		public $dismiss_msg = '';
195
196
		/**
197
		 * Flag to set automatic activation of plugins. Off by default.
198
		 *
199
		 * @since 2.2.0
200
		 *
201
		 * @var boolean
202
		 */
203
		public $is_automatic = false;
204
205
		/**
206
		 * Optional message to display before the plugins table.
207
		 *
208
		 * @since 2.2.0
209
		 *
210
		 * @var string Message filtered by wp_kses_post(). Default is empty string.
211
		 */
212
		public $message = '';
213
214
		/**
215
		 * Holds configurable array of strings.
216
		 *
217
		 * Default values are added in the constructor.
218
		 *
219
		 * @since 2.0.0
220
		 *
221
		 * @var array
222
		 */
223
		public $strings = array();
224
225
		/**
226
		 * Holds the version of WordPress.
227
		 *
228
		 * @since 2.4.0
229
		 *
230
		 * @var int
231
		 */
232
		public $wp_version;
233
234
		/**
235
		 * Holds the hook name for the admin page.
236
		 *
237
		 * @since 2.5.0
238
		 *
239
		 * @var string
240
		 */
241
		public $page_hook;
242
243
		/**
244
		 * Adds a reference of this object to $instance, populates default strings,
245
		 * does the tgmpa_init action hook, and hooks in the interactions to init.
246
		 *
247
		 * {@internal This method should be `protected`, but as too many TGMPA implementations
248
		 * haven't upgraded beyond v2.3.6 yet, this gives backward compatibility issues.
249
		 * Reverted back to public for the time being.}}
250
		 *
251
		 * @since 1.0.0
252
		 *
253
		 * @see TGM_Plugin_Activation::init()
254
		 */
255
		public function __construct() {
256
			// Set the current WordPress version.
257
			$this->wp_version = $GLOBALS['wp_version'];
258
259
			// Announce that the class is ready, and pass the object (for advanced use).
260
			do_action_ref_array( 'tgmpa_init', array( $this ) );
261
262
			/*
263
			 * Load our text domain and allow for overloading the fall-back file.
264
			 *
265
			 * {@internal IMPORTANT! If this code changes, review the regex in the custom TGMPA
266
			 * generator on the website.}}
267
			 */
268
			add_action( 'init', array( $this, 'load_textdomain' ), 5 );
269
			add_filter( 'load_textdomain_mofile', array( $this, 'overload_textdomain_mofile' ), 10, 2 );
270
271
			// When the rest of WP has loaded, kick-start the rest of the class.
272
			add_action( 'init', array( $this, 'init' ) );
273
		}
274
275
		/**
276
		 * Magic method to (not) set protected properties from outside of this class.
277
		 *
278
		 * {@internal hackedihack... There is a serious bug in v2.3.2 - 2.3.6  where the `menu` property
279
		 * is being assigned rather than tested in a conditional, effectively rendering it useless.
280
		 * This 'hack' prevents this from happening.}}
281
		 *
282
		 * @see https://github.com/TGMPA/TGM-Plugin-Activation/blob/2.3.6/tgm-plugin-activation/class-tgm-plugin-activation.php#L1593
283
		 *
284
		 * @since 2.5.2
285
		 *
286
		 * @param string $name  Name of an inaccessible property.
287
		 * @param mixed  $value Value to assign to the property.
288
		 * @return void  Silently fail to set the property when this is tried from outside of this class context.
289
		 *               (Inside this class context, the __set() method if not used as there is direct access.)
290
		 */
291
		public function __set( $name, $value ) {
292
			return;
293
		}
294
295
		/**
296
		 * Magic method to get the value of a protected property outside of this class context.
297
		 *
298
		 * @since 2.5.2
299
		 *
300
		 * @param string $name Name of an inaccessible property.
301
		 * @return mixed The property value.
302
		 */
303
		public function __get( $name ) {
304
			return $this->{$name};
305
		}
306
307
		/**
308
		 * Initialise the interactions between this class and WordPress.
309
		 *
310
		 * Hooks in three new methods for the class: admin_menu, notices and styles.
311
		 *
312
		 * @since 2.0.0
313
		 *
314
		 * @see TGM_Plugin_Activation::admin_menu()
315
		 * @see TGM_Plugin_Activation::notices()
316
		 * @see TGM_Plugin_Activation::styles()
317
		 */
318
		public function init() {
319
			/**
320
			 * By default TGMPA only loads on the WP back-end and not in an Ajax call. Using this filter
321
			 * you can overrule that behaviour.
322
			 *
323
			 * @since 2.5.0
324
			 *
325
			 * @param bool $load Whether or not TGMPA should load.
326
			 *                   Defaults to the return of `is_admin() && ! defined( 'DOING_AJAX' )`.
327
			 */
328
			if ( true !== apply_filters( 'tgmpa_load', ( is_admin() && ! defined( 'DOING_AJAX' ) ) ) ) {
329
				return;
330
			}
331
332
			// Load class strings.
333
			$this->strings = array(
334
				'page_title'                      => __( 'Install Required Plugins', 'tgmpa' ),
335
				'menu_title'                      => __( 'Install Plugins', 'tgmpa' ),
336
				/* translators: %s: plugin name. */
337
				'installing'                      => __( 'Installing Plugin: %s', 'tgmpa' ),
338
				/* translators: %s: plugin name. */
339
				'updating'                        => __( 'Updating Plugin: %s', 'tgmpa' ),
340
				'oops'                            => __( 'Something went wrong with the plugin API.', 'tgmpa' ),
341
				'notice_can_install_required'     => _n_noop(
342
					/* translators: 1: plugin name(s). */
343
					'This theme requires the following plugin: %1$s.',
344
					'This theme requires the following plugins: %1$s.',
345
					'tgmpa'
346
				),
347
				'notice_can_install_recommended'  => _n_noop(
348
					/* translators: 1: plugin name(s). */
349
					'This theme recommends the following plugin: %1$s.',
350
					'This theme recommends the following plugins: %1$s.',
351
					'tgmpa'
352
				),
353
				'notice_ask_to_update'            => _n_noop(
354
					/* translators: 1: plugin name(s). */
355
					'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.',
356
					'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.',
357
					'tgmpa'
358
				),
359
				'notice_ask_to_update_maybe'      => _n_noop(
360
					/* translators: 1: plugin name(s). */
361
					'There is an update available for: %1$s.',
362
					'There are updates available for the following plugins: %1$s.',
363
					'tgmpa'
364
				),
365
				'notice_can_activate_required'    => _n_noop(
366
					/* translators: 1: plugin name(s). */
367
					'The following required plugin is currently inactive: %1$s.',
368
					'The following required plugins are currently inactive: %1$s.',
369
					'tgmpa'
370
				),
371
				'notice_can_activate_recommended' => _n_noop(
372
					/* translators: 1: plugin name(s). */
373
					'The following recommended plugin is currently inactive: %1$s.',
374
					'The following recommended plugins are currently inactive: %1$s.',
375
					'tgmpa'
376
				),
377
				'install_link'                    => _n_noop(
378
					'Begin installing plugin',
379
					'Begin installing plugins',
380
					'tgmpa'
381
				),
382
				'update_link'                     => _n_noop(
383
					'Begin updating plugin',
384
					'Begin updating plugins',
385
					'tgmpa'
386
				),
387
				'activate_link'                   => _n_noop(
388
					'Begin activating plugin',
389
					'Begin activating plugins',
390
					'tgmpa'
391
				),
392
				'return'                          => __( 'Return to Required Plugins Installer', 'tgmpa' ),
393
				'dashboard'                       => __( 'Return to the Dashboard', 'tgmpa' ),
394
				'plugin_activated'                => __( 'Plugin activated successfully.', 'tgmpa' ),
395
				'activated_successfully'          => __( 'The following plugin was activated successfully:', 'tgmpa' ),
396
				/* translators: 1: plugin name. */
397
				'plugin_already_active'           => __( 'No action taken. Plugin %1$s was already active.', 'tgmpa' ),
398
				/* translators: 1: plugin name. */
399
				'plugin_needs_higher_version'     => __( 'Plugin not activated. A higher version of %s is needed for this theme. Please update the plugin.', 'tgmpa' ),
400
				/* translators: 1: dashboard link. */
401
				'complete'                        => __( 'All plugins installed and activated successfully. %1$s', 'tgmpa' ),
402
				'dismiss'                         => __( 'Dismiss this notice', 'tgmpa' ),
403
				'notice_cannot_install_activate'  => __( 'There are one or more required or recommended plugins to install, update or activate.', 'tgmpa' ),
404
				'contact_admin'                   => __( 'Please contact the administrator of this site for help.', 'tgmpa' ),
405
			);
406
407
			do_action( 'tgmpa_register' );
408
409
			/* After this point, the plugins should be registered and the configuration set. */
410
411
			// Proceed only if we have plugins to handle.
412
			if ( empty( $this->plugins ) || ! is_array( $this->plugins ) ) {
413
				return;
414
			}
415
416
			// Set up the menu and notices if we still have outstanding actions.
417
			if ( true !== $this->is_tgmpa_complete() ) {
418
				// Sort the plugins.
419
				array_multisort( $this->sort_order, SORT_ASC, $this->plugins );
420
421
				add_action( 'admin_menu', array( $this, 'admin_menu' ) );
422
				add_action( 'admin_head', array( $this, 'dismiss' ) );
423
424
				// Prevent the normal links from showing underneath a single install/update page.
425
				add_filter( 'install_plugin_complete_actions', array( $this, 'actions' ) );
426
				add_filter( 'update_plugin_complete_actions', array( $this, 'actions' ) );
427
428
				if ( $this->has_notices ) {
429
					add_action( 'admin_notices', array( $this, 'notices' ) );
430
					add_action( 'admin_init', array( $this, 'admin_init' ), 1 );
431
					add_action( 'admin_enqueue_scripts', array( $this, 'thickbox' ) );
432
				}
433
			}
434
435
			// If needed, filter plugin action links.
436
			add_action( 'load-plugins.php', array( $this, 'add_plugin_action_link_filters' ), 1 );
437
438
			// Make sure things get reset on switch theme.
439
			add_action( 'switch_theme', array( $this, 'flush_plugins_cache' ) );
440
441
			if ( $this->has_notices ) {
442
				add_action( 'switch_theme', array( $this, 'update_dismiss' ) );
443
			}
444
445
			// Setup the force activation hook.
446
			if ( true === $this->has_forced_activation ) {
447
				add_action( 'admin_init', array( $this, 'force_activation' ) );
448
			}
449
450
			// Setup the force deactivation hook.
451
			if ( true === $this->has_forced_deactivation ) {
452
				add_action( 'switch_theme', array( $this, 'force_deactivation' ) );
453
			}
454
455
			// Add CSS for the TGMPA admin page.
456
			add_action( 'admin_head',  array( $this, 'admin_css' ) );
457
		}
458
459
		/**
460
		 * Load translations.
461
		 *
462
		 * @since 2.6.0
463
		 *
464
		 * (@internal Uses `load_theme_textdomain()` rather than `load_plugin_textdomain()` to
465
		 * get round the different ways of handling the path and deprecated notices being thrown
466
		 * and such. For plugins, the actual file name will be corrected by a filter.}}
467
		 *
468
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
469
		 * generator on the website.}}
470
		 */
471
		public function load_textdomain() {
472
			if ( is_textdomain_loaded( 'tgmpa' ) ) {
473
				return;
474
			}
475
476
			if ( false !== strpos( __FILE__, WP_PLUGIN_DIR ) || false !== strpos( __FILE__, WPMU_PLUGIN_DIR ) ) {
477
				// Plugin, we'll need to adjust the file name.
478
				add_action( 'load_textdomain_mofile', array( $this, 'correct_plugin_mofile' ), 10, 2 );
479
				load_theme_textdomain( 'tgmpa', dirname( __FILE__ ) . '/languages' );
480
				remove_action( 'load_textdomain_mofile', array( $this, 'correct_plugin_mofile' ), 10 );
481
			} else {
482
				load_theme_textdomain( 'tgmpa', dirname( __FILE__ ) . '/languages' );
483
			}
484
		}
485
486
		/**
487
		 * Correct the .mo file name for (must-use) plugins.
488
		 *
489
		 * Themese use `/path/{locale}.mo` while plugins use `/path/{text-domain}-{locale}.mo`.
490
		 *
491
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
492
		 * generator on the website.}}
493
		 *
494
		 * @since 2.6.0
495
		 *
496
		 * @param string $mofile Full path to the target mofile.
497
		 * @param string $domain The domain for which a language file is being loaded.
498
		 * @return string $mofile
499
		 */
500
		public function correct_plugin_mofile( $mofile, $domain ) {
501
			// Exit early if not our domain (just in case).
502
			if ( 'tgmpa' !== $domain ) {
503
				return $mofile;
504
			}
505
			return preg_replace( '`/([a-z]{2}_[A-Z]{2}.mo)$`', '/tgmpa-$1', $mofile );
506
		}
507
508
		/**
509
		 * Potentially overload the fall-back translation file for the current language.
510
		 *
511
		 * WP, by default since WP 3.7, will load a local translation first and if none
512
		 * can be found, will try and find a translation in the /wp-content/languages/ directory.
513
		 * As this library is theme/plugin agnostic, translation files for TGMPA can exist both
514
		 * in the WP_LANG_DIR /plugins/ subdirectory as well as in the /themes/ subdirectory.
515
		 *
516
		 * This method makes sure both directories are checked.
517
		 *
518
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
519
		 * generator on the website.}}
520
		 *
521
		 * @since 2.6.0
522
		 *
523
		 * @param string $mofile Full path to the target mofile.
524
		 * @param string $domain The domain for which a language file is being loaded.
525
		 * @return string $mofile
526
		 */
527
		public function overload_textdomain_mofile( $mofile, $domain ) {
528
			// Exit early if not our domain, not a WP_LANG_DIR load or if the file exists and is readable.
529
			if ( 'tgmpa' !== $domain || false === strpos( $mofile, WP_LANG_DIR ) || @is_readable( $mofile ) ) {
530
				return $mofile;
531
			}
532
533
			// Current fallback file is not valid, let's try the alternative option.
534
			if ( false !== strpos( $mofile, '/themes/' ) ) {
535
				return str_replace( '/themes/', '/plugins/', $mofile );
536
			} elseif ( false !== strpos( $mofile, '/plugins/' ) ) {
537
				return str_replace( '/plugins/', '/themes/', $mofile );
538
			} else {
539
				return $mofile;
540
			}
541
		}
542
543
		/**
544
		 * Hook in plugin action link filters for the WP native plugins page.
545
		 *
546
		 * - Prevent activation of plugins which don't meet the minimum version requirements.
547
		 * - Prevent deactivation of force-activated plugins.
548
		 * - Add update notice if update available.
549
		 *
550
		 * @since 2.5.0
551
		 */
552
		public function add_plugin_action_link_filters() {
553
			foreach ( $this->plugins as $slug => $plugin ) {
554
				if ( false === $this->can_plugin_activate( $slug ) ) {
555
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_activate' ), 20 );
556
				}
557
558
				if ( true === $plugin['force_activation'] ) {
559
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_deactivate' ), 20 );
560
				}
561
562
				if ( false !== $this->does_plugin_require_update( $slug ) ) {
563
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_update' ), 20 );
564
				}
565
			}
566
		}
567
568
		/**
569
		 * Remove the 'Activate' link on the WP native plugins page if the plugin does not meet the
570
		 * minimum version requirements.
571
		 *
572
		 * @since 2.5.0
573
		 *
574
		 * @param array $actions Action links.
575
		 * @return array
576
		 */
577
		public function filter_plugin_action_links_activate( $actions ) {
578
			unset( $actions['activate'] );
579
580
			return $actions;
581
		}
582
583
		/**
584
		 * Remove the 'Deactivate' link on the WP native plugins page if the plugin has been set to force activate.
585
		 *
586
		 * @since 2.5.0
587
		 *
588
		 * @param array $actions Action links.
589
		 * @return array
590
		 */
591
		public function filter_plugin_action_links_deactivate( $actions ) {
592
			unset( $actions['deactivate'] );
593
594
			return $actions;
595
		}
596
597
		/**
598
		 * Add a 'Requires update' link on the WP native plugins page if the plugin does not meet the
599
		 * minimum version requirements.
600
		 *
601
		 * @since 2.5.0
602
		 *
603
		 * @param array $actions Action links.
604
		 * @return array
605
		 */
606
		public function filter_plugin_action_links_update( $actions ) {
607
			$actions['update'] = sprintf(
608
				'<a href="%1$s" title="%2$s" class="edit">%3$s</a>',
609
				esc_url( $this->get_tgmpa_status_url( 'update' ) ),
610
				esc_attr__( 'This plugin needs to be updated to be compatible with your theme.', 'tgmpa' ),
611
				esc_html__( 'Update Required', 'tgmpa' )
612
			);
613
614
			return $actions;
615
		}
616
617
		/**
618
		 * Handles calls to show plugin information via links in the notices.
619
		 *
620
		 * We get the links in the admin notices to point to the TGMPA page, rather
621
		 * than the typical plugin-install.php file, so we can prepare everything
622
		 * beforehand.
623
		 *
624
		 * WP does not make it easy to show the plugin information in the thickbox -
625
		 * here we have to require a file that includes a function that does the
626
		 * main work of displaying it, enqueue some styles, set up some globals and
627
		 * finally call that function before exiting.
628
		 *
629
		 * Down right easy once you know how...
630
		 *
631
		 * Returns early if not the TGMPA page.
632
		 *
633
		 * @since 2.1.0
634
		 *
635
		 * @global string $tab Used as iframe div class names, helps with styling
636
		 * @global string $body_id Used as the iframe body ID, helps with styling
637
		 *
638
		 * @return null Returns early if not the TGMPA page.
639
		 */
640
		public function admin_init() {
641
			if ( ! $this->is_tgmpa_page() ) {
642
				return;
643
			}
644
645
			if ( isset( $_REQUEST['tab'] ) && 'plugin-information' === $_REQUEST['tab'] ) {
646
				// Needed for install_plugin_information().
647
				require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
648
649
				wp_enqueue_style( 'plugin-install' );
650
651
				global $tab, $body_id;
652
				$body_id = 'plugin-information';
653
				// @codingStandardsIgnoreStart
654
				$tab     = 'plugin-information';
655
				// @codingStandardsIgnoreEnd
656
657
				install_plugin_information();
658
659
				exit;
660
			}
661
		}
662
663
		/**
664
		 * Enqueue thickbox scripts/styles for plugin info.
665
		 *
666
		 * Thickbox is not automatically included on all admin pages, so we must
667
		 * manually enqueue it for those pages.
668
		 *
669
		 * Thickbox is only loaded if the user has not dismissed the admin
670
		 * notice or if there are any plugins left to install and activate.
671
		 *
672
		 * @since 2.1.0
673
		 */
674
		public function thickbox() {
675
			if ( ! get_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, true ) ) {
676
				add_thickbox();
677
			}
678
		}
679
680
		/**
681
		 * Adds submenu page if there are plugin actions to take.
682
		 *
683
		 * This method adds the submenu page letting users know that a required
684
		 * plugin needs to be installed.
685
		 *
686
		 * This page disappears once the plugin has been installed and activated.
687
		 *
688
		 * @since 1.0.0
689
		 *
690
		 * @see TGM_Plugin_Activation::init()
691
		 * @see TGM_Plugin_Activation::install_plugins_page()
692
		 *
693
		 * @return null Return early if user lacks capability to install a plugin.
694
		 */
695
		public function admin_menu() {
696
			// Make sure privileges are correct to see the page.
697
			if ( ! current_user_can( 'install_plugins' ) ) {
698
				return;
699
			}
700
701
			$args = apply_filters(
702
				'tgmpa_admin_menu_args',
703
				array(
704
					'parent_slug' => $this->parent_slug,                     // Parent Menu slug.
705
					'page_title'  => $this->strings['page_title'],           // Page title.
706
					'menu_title'  => $this->strings['menu_title'],           // Menu title.
707
					'capability'  => $this->capability,                      // Capability.
708
					'menu_slug'   => $this->menu,                            // Menu slug.
709
					'function'    => array( $this, 'install_plugins_page' ), // Callback.
710
				)
711
			);
712
713
			$this->add_admin_menu( $args );
714
		}
715
716
		/**
717
		 * Add the menu item.
718
		 *
719
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
720
		 * generator on the website.}}
721
		 *
722
		 * @since 2.5.0
723
		 *
724
		 * @param array $args Menu item configuration.
725
		 */
726
		protected function add_admin_menu( array $args ) {
727
			if ( has_filter( 'tgmpa_admin_menu_use_add_theme_page' ) ) {
728
				_deprecated_function( 'The "tgmpa_admin_menu_use_add_theme_page" filter', '2.5.0', esc_html__( 'Set the parent_slug config variable instead.', 'tgmpa' ) );
729
			}
730
731
			if ( 'themes.php' === $this->parent_slug ) {
732
				$this->page_hook = call_user_func( 'add_theme_page', $args['page_title'], $args['menu_title'], $args['capability'], $args['menu_slug'], $args['function'] );
733
			} else {
734
				$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'] );
735
			}
736
		}
737
738
		/**
739
		 * Echoes plugin installation form.
740
		 *
741
		 * This method is the callback for the admin_menu method function.
742
		 * This displays the admin page and form area where the user can select to install and activate the plugin.
743
		 * Aborts early if we're processing a plugin installation action.
744
		 *
745
		 * @since 1.0.0
746
		 *
747
		 * @return null Aborts early if we're processing a plugin installation action.
748
		 */
749
		public function install_plugins_page() {
750
			// Store new instance of plugin table in object.
751
			$plugin_table = new TGMPA_List_Table;
752
753
			// Return early if processing a plugin installation action.
754
			if ( ( ( 'tgmpa-bulk-install' === $plugin_table->current_action() || 'tgmpa-bulk-update' === $plugin_table->current_action() ) && $plugin_table->process_bulk_actions() ) || $this->do_plugin_install() ) {
755
				return;
756
			}
757
758
			// Force refresh of available plugin information so we'll know about manual updates/deletes.
759
			wp_clean_plugins_cache( false );
760
761
			?>
762
			<div class="tgmpa wrap">
763
				<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
764
				<?php $plugin_table->prepare_items(); ?>
765
766
				<?php
767
				if ( ! empty( $this->message ) && is_string( $this->message ) ) {
768
					echo wp_kses_post( $this->message );
769
				}
770
				?>
771
				<?php $plugin_table->views(); ?>
772
773
				<form id="tgmpa-plugins" action="" method="post">
774
					<input type="hidden" name="tgmpa-page" value="<?php echo esc_attr( $this->menu ); ?>" />
775
					<input type="hidden" name="plugin_status" value="<?php echo esc_attr( $plugin_table->view_context ); ?>" />
776
					<?php $plugin_table->display(); ?>
777
				</form>
778
			</div>
779
			<?php
780
		}
781
782
		/**
783
		 * Installs, updates or activates a plugin depending on the action link clicked by the user.
784
		 *
785
		 * Checks the $_GET variable to see which actions have been
786
		 * passed and responds with the appropriate method.
787
		 *
788
		 * Uses WP_Filesystem to process and handle the plugin installation
789
		 * method.
790
		 *
791
		 * @since 1.0.0
792
		 *
793
		 * @uses WP_Filesystem
794
		 * @uses WP_Error
795
		 * @uses WP_Upgrader
796
		 * @uses Plugin_Upgrader
797
		 * @uses Plugin_Installer_Skin
798
		 * @uses Plugin_Upgrader_Skin
799
		 *
800
		 * @return boolean True on success, false on failure.
801
		 */
802
		protected function do_plugin_install() {
803
			if ( empty( $_GET['plugin'] ) ) {
804
				return false;
805
			}
806
807
			// All plugin information will be stored in an array for processing.
808
			$slug = $this->sanitize_key( urldecode( $_GET['plugin'] ) );
809
810
			if ( ! isset( $this->plugins[ $slug ] ) ) {
811
				return false;
812
			}
813
814
			// Was an install or upgrade action link clicked?
815
			if ( ( isset( $_GET['tgmpa-install'] ) && 'install-plugin' === $_GET['tgmpa-install'] ) || ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) ) {
816
817
				$install_type = 'install';
818
				if ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) {
819
					$install_type = 'update';
820
				}
821
822
				check_admin_referer( 'tgmpa-' . $install_type, 'tgmpa-nonce' );
823
824
				// Pass necessary information via URL if WP_Filesystem is needed.
825
				$url = wp_nonce_url(
826
					add_query_arg(
827
						array(
828
							'plugin'                 => urlencode( $slug ),
829
							'tgmpa-' . $install_type => $install_type . '-plugin',
830
						),
831
						$this->get_tgmpa_url()
832
					),
833
					'tgmpa-' . $install_type,
834
					'tgmpa-nonce'
835
				);
836
837
				$method = ''; // Leave blank so WP_Filesystem can populate it as necessary.
838
839
				if ( false === ( $creds = request_filesystem_credentials( esc_url_raw( $url ), $method, false, false, array() ) ) ) {
840
					return true;
841
				}
842
843
				if ( ! WP_Filesystem( $creds ) ) {
0 ignored issues
show
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...
844
					request_filesystem_credentials( esc_url_raw( $url ), $method, true, false, array() ); // Setup WP_Filesystem.
845
					return true;
846
				}
847
848
				/* If we arrive here, we have the filesystem. */
849
850
				// Prep variables for Plugin_Installer_Skin class.
851
				$extra         = array();
852
				$extra['slug'] = $slug; // Needed for potentially renaming of directory name.
853
				$source        = $this->get_download_url( $slug );
854
				$api           = ( 'repo' === $this->plugins[ $slug ]['source_type'] ) ? $this->get_plugins_api( $slug ) : null;
855
				$api           = ( false !== $api ) ? $api : null;
856
857
				$url = add_query_arg(
858
					array(
859
						'action' => $install_type . '-plugin',
860
						'plugin' => urlencode( $slug ),
861
					),
862
					'update.php'
863
				);
864
865
				if ( ! class_exists( 'Plugin_Upgrader', false ) ) {
866
					require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
867
				}
868
869
				$title     = ( 'update' === $install_type ) ? $this->strings['updating'] : $this->strings['installing'];
870
				$skin_args = array(
871
					'type'   => ( 'bundled' !== $this->plugins[ $slug ]['source_type'] ) ? 'web' : 'upload',
872
					'title'  => sprintf( $title, $this->plugins[ $slug ]['name'] ),
873
					'url'    => esc_url_raw( $url ),
874
					'nonce'  => $install_type . '-plugin_' . $slug,
875
					'plugin' => '',
876
					'api'    => $api,
877
					'extra'  => $extra,
878
				);
879
				unset( $title );
880
881
				if ( 'update' === $install_type ) {
882
					$skin_args['plugin'] = $this->plugins[ $slug ]['file_path'];
883
					$skin                = new Plugin_Upgrader_Skin( $skin_args );
884
				} else {
885
					$skin = new Plugin_Installer_Skin( $skin_args );
886
				}
887
888
				// Create a new instance of Plugin_Upgrader.
889
				$upgrader = new Plugin_Upgrader( $skin );
890
891
				// Perform the action and install the plugin from the $source urldecode().
892
				add_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1, 3 );
893
894
				if ( 'update' === $install_type ) {
895
					// Inject our info into the update transient.
896
					$to_inject                    = array( $slug => $this->plugins[ $slug ] );
897
					$to_inject[ $slug ]['source'] = $source;
898
					$this->inject_update_info( $to_inject );
899
900
					$upgrader->upgrade( $this->plugins[ $slug ]['file_path'] );
901
				} else {
902
					$upgrader->install( $source );
903
				}
904
905
				remove_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1 );
906
907
				// Make sure we have the correct file path now the plugin is installed/updated.
908
				$this->populate_file_path( $slug );
909
910
				// Only activate plugins if the config option is set to true and the plugin isn't
911
				// already active (upgrade).
912
				if ( $this->is_automatic && ! $this->is_plugin_active( $slug ) ) {
913
					$plugin_activate = $upgrader->plugin_info(); // Grab the plugin info from the Plugin_Upgrader method.
914
					if ( false === $this->activate_single_plugin( $plugin_activate, $slug, true ) ) {
915
						return true; // Finish execution of the function early as we encountered an error.
916
					}
917
				}
918
919
				$this->show_tgmpa_version();
920
921
				// Display message based on if all plugins are now active or not.
922
				if ( $this->is_tgmpa_complete() ) {
923
					echo '<p>', sprintf( esc_html( $this->strings['complete'] ), '<a href="' . esc_url( self_admin_url() ) . '">' . esc_html__( 'Return to the Dashboard', 'tgmpa' ) . '</a>' ), '</p>';
924
					echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>';
925
				} else {
926
					echo '<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>';
927
				}
928
929
				return true;
930
			} elseif ( isset( $this->plugins[ $slug ]['file_path'], $_GET['tgmpa-activate'] ) && 'activate-plugin' === $_GET['tgmpa-activate'] ) {
931
				// Activate action link was clicked.
932
				check_admin_referer( 'tgmpa-activate', 'tgmpa-nonce' );
933
934
				if ( false === $this->activate_single_plugin( $this->plugins[ $slug ]['file_path'], $slug ) ) {
935
					return true; // Finish execution of the function early as we encountered an error.
936
				}
937
			}
938
939
			return false;
940
		}
941
942
		/**
943
		 * Inject information into the 'update_plugins' site transient as WP checks that before running an update.
944
		 *
945
		 * @since 2.5.0
946
		 *
947
		 * @param array $plugins The plugin information for the plugins which are to be updated.
948
		 */
949
		public function inject_update_info( $plugins ) {
950
			$repo_updates = get_site_transient( 'update_plugins' );
951
952
			if ( ! is_object( $repo_updates ) ) {
953
				$repo_updates = new stdClass;
954
			}
955
956
			foreach ( $plugins as $slug => $plugin ) {
957
				$file_path = $plugin['file_path'];
958
959
				if ( empty( $repo_updates->response[ $file_path ] ) ) {
960
					$repo_updates->response[ $file_path ] = new stdClass;
961
				}
962
963
				// We only really need to set package, but let's do all we can in case WP changes something.
964
				$repo_updates->response[ $file_path ]->slug        = $slug;
965
				$repo_updates->response[ $file_path ]->plugin      = $file_path;
966
				$repo_updates->response[ $file_path ]->new_version = $plugin['version'];
967
				$repo_updates->response[ $file_path ]->package     = $plugin['source'];
968
				if ( empty( $repo_updates->response[ $file_path ]->url ) && ! empty( $plugin['external_url'] ) ) {
969
					$repo_updates->response[ $file_path ]->url = $plugin['external_url'];
970
				}
971
			}
972
973
			set_site_transient( 'update_plugins', $repo_updates );
974
		}
975
976
		/**
977
		 * Adjust the plugin directory name if necessary.
978
		 *
979
		 * The final destination directory of a plugin is based on the subdirectory name found in the
980
		 * (un)zipped source. In some cases - most notably GitHub repository plugin downloads -, this
981
		 * subdirectory name is not the same as the expected slug and the plugin will not be recognized
982
		 * as installed. This is fixed by adjusting the temporary unzipped source subdirectory name to
983
		 * the expected plugin slug.
984
		 *
985
		 * @since 2.5.0
986
		 *
987
		 * @param string       $source        Path to upgrade/zip-file-name.tmp/subdirectory/.
988
		 * @param string       $remote_source Path to upgrade/zip-file-name.tmp.
989
		 * @param \WP_Upgrader $upgrader      Instance of the upgrader which installs the plugin.
990
		 * @return string $source
991
		 */
992
		public function maybe_adjust_source_dir( $source, $remote_source, $upgrader ) {
993
			if ( ! $this->is_tgmpa_page() || ! is_object( $GLOBALS['wp_filesystem'] ) ) {
994
				return $source;
995
			}
996
997
			// Check for single file plugins.
998
			$source_files = array_keys( $GLOBALS['wp_filesystem']->dirlist( $remote_source ) );
999
			if ( 1 === count( $source_files ) && false === $GLOBALS['wp_filesystem']->is_dir( $source ) ) {
1000
				return $source;
1001
			}
1002
1003
			// Multi-file plugin, let's see if the directory is correctly named.
1004
			$desired_slug = '';
1005
1006
			// Figure out what the slug is supposed to be.
1007
			if ( false === $upgrader->bulk && ! empty( $upgrader->skin->options['extra']['slug'] ) ) {
1008
				$desired_slug = $upgrader->skin->options['extra']['slug'];
1009
			} else {
1010
				// Bulk installer contains less info, so fall back on the info registered here.
1011
				foreach ( $this->plugins as $slug => $plugin ) {
1012
					if ( ! empty( $upgrader->skin->plugin_names[ $upgrader->skin->i ] ) && $plugin['name'] === $upgrader->skin->plugin_names[ $upgrader->skin->i ] ) {
1013
						$desired_slug = $slug;
1014
						break;
1015
					}
1016
				}
1017
				unset( $slug, $plugin );
1018
			}
1019
1020
			if ( ! empty( $desired_slug ) ) {
1021
				$subdir_name = untrailingslashit( str_replace( trailingslashit( $remote_source ), '', $source ) );
1022
1023
				if ( ! empty( $subdir_name ) && $subdir_name !== $desired_slug ) {
1024
					$from_path = untrailingslashit( $source );
1025
					$to_path   = trailingslashit( $remote_source ) . $desired_slug;
1026
1027
					if ( true === $GLOBALS['wp_filesystem']->move( $from_path, $to_path ) ) {
1028
						return trailingslashit( $to_path );
1029 View Code Duplication
					} else {
1030
						return new WP_Error( 'rename_failed', esc_html__( 'The remote plugin package does not contain a folder with the desired slug and renaming did not work.', 'tgmpa' ) . ' ' . esc_html__( 'Please contact the plugin provider and ask them to package their plugin according to the WordPress guidelines.', 'tgmpa' ), array( 'found' => $subdir_name, 'expected' => $desired_slug ) );
1031
					}
1032 View Code Duplication
				} elseif ( empty( $subdir_name ) ) {
1033
					return new WP_Error( 'packaged_wrong', esc_html__( 'The remote plugin package consists of more than one file, but the files are not packaged in a folder.', 'tgmpa' ) . ' ' . esc_html__( 'Please contact the plugin provider and ask them to package their plugin according to the WordPress guidelines.', 'tgmpa' ), array( 'found' => $subdir_name, 'expected' => $desired_slug ) );
1034
				}
1035
			}
1036
1037
			return $source;
1038
		}
1039
1040
		/**
1041
		 * Activate a single plugin and send feedback about the result to the screen.
1042
		 *
1043
		 * @since 2.5.0
1044
		 *
1045
		 * @param string $file_path Path within wp-plugins/ to main plugin file.
1046
		 * @param string $slug      Plugin slug.
1047
		 * @param bool   $automatic Whether this is an automatic activation after an install. Defaults to false.
1048
		 *                          This determines the styling of the output messages.
1049
		 * @return bool False if an error was encountered, true otherwise.
1050
		 */
1051
		protected function activate_single_plugin( $file_path, $slug, $automatic = false ) {
1052
			if ( $this->can_plugin_activate( $slug ) ) {
1053
				$activate = activate_plugin( $file_path );
1054
1055
				if ( is_wp_error( $activate ) ) {
1056
					echo '<div id="message" class="error"><p>', wp_kses_post( $activate->get_error_message() ), '</p></div>',
1057
						'<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>';
1058
1059
					return false; // End it here if there is an error with activation.
1060
				} else {
1061
					if ( ! $automatic ) {
1062
						// Make sure message doesn't display again if bulk activation is performed
1063
						// immediately after a single activation.
1064
						if ( ! isset( $_POST['action'] ) ) { // WPCS: CSRF OK.
1065
							echo '<div id="message" class="updated"><p>', esc_html( $this->strings['activated_successfully'] ), ' <strong>', esc_html( $this->plugins[ $slug ]['name'] ), '.</strong></p></div>';
1066
						}
1067
					} else {
1068
						// Simpler message layout for use on the plugin install page.
1069
						echo '<p>', esc_html( $this->strings['plugin_activated'] ), '</p>';
1070
					}
1071
				}
1072 View Code Duplication
			} elseif ( $this->is_plugin_active( $slug ) ) {
1073
				// No simpler message format provided as this message should never be encountered
1074
				// on the plugin install page.
1075
				echo '<div id="message" class="error"><p>',
1076
					sprintf(
1077
						esc_html( $this->strings['plugin_already_active'] ),
1078
						'<strong>' . esc_html( $this->plugins[ $slug ]['name'] ) . '</strong>'
1079
					),
1080
					'</p></div>';
1081
			} elseif ( $this->does_plugin_require_update( $slug ) ) {
1082
				if ( ! $automatic ) {
1083
					// Make sure message doesn't display again if bulk activation is performed
1084
					// immediately after a single activation.
1085 View Code Duplication
					if ( ! isset( $_POST['action'] ) ) { // WPCS: CSRF OK.
1086
						echo '<div id="message" class="error"><p>',
1087
							sprintf(
1088
								esc_html( $this->strings['plugin_needs_higher_version'] ),
1089
								'<strong>' . esc_html( $this->plugins[ $slug ]['name'] ) . '</strong>'
1090
							),
1091
							'</p></div>';
1092
					}
1093
				} else {
1094
					// Simpler message layout for use on the plugin install page.
1095
					echo '<p>', sprintf( esc_html( $this->strings['plugin_needs_higher_version'] ), esc_html( $this->plugins[ $slug ]['name'] ) ), '</p>';
1096
				}
1097
			}
1098
1099
			return true;
1100
		}
1101
1102
		/**
1103
		 * Echoes required plugin notice.
1104
		 *
1105
		 * Outputs a message telling users that a specific plugin is required for
1106
		 * their theme. If appropriate, it includes a link to the form page where
1107
		 * users can install and activate the plugin.
1108
		 *
1109
		 * Returns early if we're on the Install page.
1110
		 *
1111
		 * @since 1.0.0
1112
		 *
1113
		 * @global object $current_screen
1114
		 *
1115
		 * @return null Returns early if we're on the Install page.
1116
		 */
1117
		public function notices() {
1118
			// Remove nag on the install page / Return early if the nag message has been dismissed or user < author.
1119
			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' ) ) ) {
1120
				return;
1121
			}
1122
1123
			// Store for the plugin slugs by message type.
1124
			$message = array();
1125
1126
			// Initialize counters used to determine plurality of action link texts.
1127
			$install_link_count          = 0;
1128
			$update_link_count           = 0;
1129
			$activate_link_count         = 0;
1130
			$total_required_action_count = 0;
1131
1132
			foreach ( $this->plugins as $slug => $plugin ) {
1133
				if ( $this->is_plugin_active( $slug ) && false === $this->does_plugin_have_update( $slug ) ) {
1134
					continue;
1135
				}
1136
1137
				if ( ! $this->is_plugin_installed( $slug ) ) {
1138
					if ( current_user_can( 'install_plugins' ) ) {
1139
						$install_link_count++;
1140
1141
						if ( true === $plugin['required'] ) {
1142
							$message['notice_can_install_required'][] = $slug;
1143
						} else {
1144
							$message['notice_can_install_recommended'][] = $slug;
1145
						}
1146
					}
1147
					if ( true === $plugin['required'] ) {
1148
						$total_required_action_count++;
1149
					}
1150
				} else {
1151
					if ( ! $this->is_plugin_active( $slug ) && $this->can_plugin_activate( $slug ) ) {
1152
						if ( current_user_can( 'activate_plugins' ) ) {
1153
							$activate_link_count++;
1154
1155
							if ( true === $plugin['required'] ) {
1156
								$message['notice_can_activate_required'][] = $slug;
1157
							} else {
1158
								$message['notice_can_activate_recommended'][] = $slug;
1159
							}
1160
						}
1161
						if ( true === $plugin['required'] ) {
1162
							$total_required_action_count++;
1163
						}
1164
					}
1165
1166
					if ( $this->does_plugin_require_update( $slug ) || false !== $this->does_plugin_have_update( $slug ) ) {
1167
1168
						if ( current_user_can( 'update_plugins' ) ) {
1169
							$update_link_count++;
1170
1171
							if ( $this->does_plugin_require_update( $slug ) ) {
1172
								$message['notice_ask_to_update'][] = $slug;
1173
							} elseif ( false !== $this->does_plugin_have_update( $slug ) ) {