Completed
Push — develop ( 171df5...06a03a )
by Gary
02:38
created

class-tgm-plugin-activation.php (1 issue)

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