Completed
Push — develop ( c2585a...6963a5 )
by Gary
7s
created

TGMPA_Utils   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 112
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 112
rs 10
wmc 17
lcom 1
cbo 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A wrap_in_em() 0 3 1
A wrap_in_strong() 0 3 1
A validate_bool() 0 11 3
C emulate_filter_bool() 0 37 12
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.0
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.0';
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
456
		/**
457
		 * Load translations.
458
		 *
459
		 * @since 2.6.0
460
		 *
461
		 * (@internal Uses `load_theme_textdomain()` rather than `load_plugin_textdomain()` to
462
		 * get round the different ways of handling the path and deprecated notices being thrown
463
		 * and such. For plugins, the actual file name will be corrected by a filter.}}
464
		 *
465
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
466
		 * generator on the website.}}
467
		 */
468
		public function load_textdomain() {
469
			if ( is_textdomain_loaded( 'tgmpa' ) ) {
470
				return;
471
			}
472
473
			if ( false !== strpos( __FILE__, WP_PLUGIN_DIR ) || false !== strpos( __FILE__, WPMU_PLUGIN_DIR ) ) {
474
				// Plugin, we'll need to adjust the file name.
475
				add_action( 'load_textdomain_mofile', array( $this, 'correct_plugin_mofile' ), 10, 2 );
476
				load_theme_textdomain( 'tgmpa', dirname( __FILE__ ) . '/languages' );
477
				remove_action( 'load_textdomain_mofile', array( $this, 'correct_plugin_mofile' ), 10 );
478
			} else {
479
				load_theme_textdomain( 'tgmpa', dirname( __FILE__ ) . '/languages' );
480
			}
481
		}
482
483
		/**
484
		 * Correct the .mo file name for (must-use) plugins.
485
		 *
486
		 * Themese use `/path/{locale}.mo` while plugins use `/path/{text-domain}-{locale}.mo`.
487
		 *
488
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
489
		 * generator on the website.}}
490
		 *
491
		 * @since 2.6.0
492
		 *
493
		 * @param string $mofile Full path to the target mofile.
494
		 * @param string $domain The domain for which a language file is being loaded.
495
		 * @return string $mofile
496
		 */
497
		public function correct_plugin_mofile( $mofile, $domain ) {
498
			// Exit early if not our domain (just in case).
499
			if ( 'tgmpa' !== $domain ) {
500
				return $mofile;
501
			}
502
			return preg_replace( '`/([a-z]{2}_[A-Z]{2}.mo)$`', '/tgmpa-$1', $mofile );
503
		}
504
505
		/**
506
		 * Potentially overload the fall-back translation file for the current language.
507
		 *
508
		 * WP, by default since WP 3.7, will load a local translation first and if none
509
		 * can be found, will try and find a translation in the /wp-content/languages/ directory.
510
		 * As this library is theme/plugin agnostic, translation files for TGMPA can exist both
511
		 * in the WP_LANG_DIR /plugins/ subdirectory as well as in the /themes/ subdirectory.
512
		 *
513
		 * This method makes sure both directories are checked.
514
		 *
515
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
516
		 * generator on the website.}}
517
		 *
518
		 * @since 2.6.0
519
		 *
520
		 * @param string $mofile Full path to the target mofile.
521
		 * @param string $domain The domain for which a language file is being loaded.
522
		 * @return string $mofile
523
		 */
524
		public function overload_textdomain_mofile( $mofile, $domain ) {
525
			// Exit early if not our domain, not a WP_LANG_DIR load or if the file exists and is readable.
526
			if ( 'tgmpa' !== $domain || false === strpos( $mofile, WP_LANG_DIR ) || @is_readable( $mofile ) ) {
527
				return $mofile;
528
			}
529
530
			// Current fallback file is not valid, let's try the alternative option.
531
			if ( false !== strpos( $mofile, '/themes/' ) ) {
532
				return str_replace( '/themes/', '/plugins/', $mofile );
533
			} elseif ( false !== strpos( $mofile, '/plugins/' ) ) {
534
				return str_replace( '/plugins/', '/themes/', $mofile );
535
			} else {
536
				return $mofile;
537
			}
538
		}
539
540
		/**
541
		 * Hook in plugin action link filters for the WP native plugins page.
542
		 *
543
		 * - Prevent activation of plugins which don't meet the minimum version requirements.
544
		 * - Prevent deactivation of force-activated plugins.
545
		 * - Add update notice if update available.
546
		 *
547
		 * @since 2.5.0
548
		 */
549
		public function add_plugin_action_link_filters() {
550
			foreach ( $this->plugins as $slug => $plugin ) {
551
				if ( false === $this->can_plugin_activate( $slug ) ) {
552
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_activate' ), 20 );
553
				}
554
555
				if ( true === $plugin['force_activation'] ) {
556
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_deactivate' ), 20 );
557
				}
558
559
				if ( false !== $this->does_plugin_require_update( $slug ) ) {
560
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_update' ), 20 );
561
				}
562
			}
563
		}
564
565
		/**
566
		 * Remove the 'Activate' link on the WP native plugins page if the plugin does not meet the
567
		 * minimum version requirements.
568
		 *
569
		 * @since 2.5.0
570
		 *
571
		 * @param array $actions Action links.
572
		 * @return array
573
		 */
574
		public function filter_plugin_action_links_activate( $actions ) {
575
			unset( $actions['activate'] );
576
577
			return $actions;
578
		}
579
580
		/**
581
		 * Remove the 'Deactivate' link on the WP native plugins page if the plugin has been set to force activate.
582
		 *
583
		 * @since 2.5.0
584
		 *
585
		 * @param array $actions Action links.
586
		 * @return array
587
		 */
588
		public function filter_plugin_action_links_deactivate( $actions ) {
589
			unset( $actions['deactivate'] );
590
591
			return $actions;
592
		}
593
594
		/**
595
		 * Add a 'Requires update' link on the WP native plugins page if the plugin does not meet the
596
		 * minimum version requirements.
597
		 *
598
		 * @since 2.5.0
599
		 *
600
		 * @param array $actions Action links.
601
		 * @return array
602
		 */
603
		public function filter_plugin_action_links_update( $actions ) {
604
			$actions['update'] = sprintf(
605
				'<a href="%1$s" title="%2$s" class="edit">%3$s</a>',
606
				esc_url( $this->get_tgmpa_status_url( 'update' ) ),
607
				esc_attr__( 'This plugin needs to be updated to be compatible with your theme.', 'tgmpa' ),
608
				esc_html__( 'Update Required', 'tgmpa' )
609
			);
610
611
			return $actions;
612
		}
613
614
		/**
615
		 * Handles calls to show plugin information via links in the notices.
616
		 *
617
		 * We get the links in the admin notices to point to the TGMPA page, rather
618
		 * than the typical plugin-install.php file, so we can prepare everything
619
		 * beforehand.
620
		 *
621
		 * WP does not make it easy to show the plugin information in the thickbox -
622
		 * here we have to require a file that includes a function that does the
623
		 * main work of displaying it, enqueue some styles, set up some globals and
624
		 * finally call that function before exiting.
625
		 *
626
		 * Down right easy once you know how...
627
		 *
628
		 * Returns early if not the TGMPA page.
629
		 *
630
		 * @since 2.1.0
631
		 *
632
		 * @global string $tab Used as iframe div class names, helps with styling
633
		 * @global string $body_id Used as the iframe body ID, helps with styling
634
		 *
635
		 * @return null Returns early if not the TGMPA page.
636
		 */
637
		public function admin_init() {
638
			if ( ! $this->is_tgmpa_page() ) {
639
				return;
640
			}
641
642
			if ( isset( $_REQUEST['tab'] ) && 'plugin-information' === $_REQUEST['tab'] ) {
643
				// Needed for install_plugin_information().
644
				require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
645
646
				wp_enqueue_style( 'plugin-install' );
647
648
				global $tab, $body_id;
0 ignored issues
show
Compatibility Best Practice introduced by jrfnl
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

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

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

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

Loading history...
841
					request_filesystem_credentials( esc_url_raw( $url ), $method, true, false, array() ); // Setup WP_Filesystem.
842
					return true;
843
				}
844
845
				/* If we arrive here, we have the filesystem. */
846
847
				// Prep variables for Plugin_Installer_Skin class.
848
				$extra         = array();
849
				$extra['slug'] = $slug; // Needed for potentially renaming of directory name.
850
				$source        = $this->get_download_url( $slug );
851
				$api           = ( 'repo' === $this->plugins[ $slug ]['source_type'] ) ? $this->get_plugins_api( $slug ) : null;
852
				$api           = ( false !== $api ) ? $api : null;
853
854
				$url = add_query_arg(
855
					array(
856
						'action' => $install_type . '-plugin',
857
						'plugin' => urlencode( $slug ),
858
					),
859
					'update.php'
860
				);
861
862
				if ( ! class_exists( 'Plugin_Upgrader', false ) ) {
863
					require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
864
				}
865
866
				$title     = ( 'update' === $install_type ) ? $this->strings['updating'] : $this->strings['installing'];
867
				$skin_args = array(
868
					'type'   => ( 'bundled' !== $this->plugins[ $slug ]['source_type'] ) ? 'web' : 'upload',
869
					'title'  => sprintf( $title, $this->plugins[ $slug ]['name'] ),
870
					'url'    => esc_url_raw( $url ),
871
					'nonce'  => $install_type . '-plugin_' . $slug,
872
					'plugin' => '',
873
					'api'    => $api,
874
					'extra'  => $extra,
875
				);
876
				unset( $title );
877
878
				if ( 'update' === $install_type ) {
879
					$skin_args['plugin'] = $this->plugins[ $slug ]['file_path'];
880
					$skin                = new Plugin_Upgrader_Skin( $skin_args );
881
				} else {
882
					$skin = new Plugin_Installer_Skin( $skin_args );
883
				}
884
885
				// Create a new instance of Plugin_Upgrader.
886
				$upgrader = new Plugin_Upgrader( $skin );
887
888
				// Perform the action and install the plugin from the $source urldecode().
889
				add_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1, 3 );
890
891
				if ( 'update' === $install_type ) {
892
					// Inject our info into the update transient.
893
					$to_inject                    = array( $slug => $this->plugins[ $slug ] );
894
					$to_inject[ $slug ]['source'] = $source;
895
					$this->inject_update_info( $to_inject );
896
897
					$upgrader->upgrade( $this->plugins[ $slug ]['file_path'] );
898
				} else {
899
					$upgrader->install( $source );
900
				}
901
902
				remove_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1 );
903
904
				// Make sure we have the correct file path now the plugin is installed/updated.
905
				$this->populate_file_path( $slug );
906
907
				// Only activate plugins if the config option is set to true and the plugin isn't
908
				// already active (upgrade).
909
				if ( $this->is_automatic && ! $this->is_plugin_active( $slug ) ) {
910
					$plugin_activate = $upgrader->plugin_info(); // Grab the plugin info from the Plugin_Upgrader method.
911
					if ( false === $this->activate_single_plugin( $plugin_activate, $slug, true ) ) {
912
						return true; // Finish execution of the function early as we encountered an error.
913
					}
914
				}
915
916
				$this->show_tgmpa_version();
917
918
				// Display message based on if all plugins are now active or not.
919
				if ( $this->is_tgmpa_complete() ) {
920
					echo '<p>', sprintf( esc_html( $this->strings['complete'] ), '<a href="' . esc_url( self_admin_url() ) . '">' . esc_html__( 'Return to the Dashboard', 'tgmpa' ) . '</a>' ), '</p>';
921
					echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>';
922
				} else {
923
					echo '<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>';
924
				}
925
926
				return true;
927
			} elseif ( isset( $this->plugins[ $slug ]['file_path'], $_GET['tgmpa-activate'] ) && 'activate-plugin' === $_GET['tgmpa-activate'] ) {
928
				// Activate action link was clicked.
929
				check_admin_referer( 'tgmpa-activate', 'tgmpa-nonce' );
930
931
				if ( false === $this->activate_single_plugin( $this->plugins[ $slug ]['file_path'], $slug ) ) {
932
					return true; // Finish execution of the function early as we encountered an error.
933
				}
934
			}
935
936
			return false;
937
		}
938
939
		/**
940
		 * Inject information into the 'update_plugins' site transient as WP checks that before running an update.
941
		 *
942
		 * @since 2.5.0
943
		 *
944
		 * @param array $plugins The plugin information for the plugins which are to be updated.
945
		 */
946
		public function inject_update_info( $plugins ) {
947
			$repo_updates = get_site_transient( 'update_plugins' );
948
949
			if ( ! is_object( $repo_updates ) ) {
950
				$repo_updates = new stdClass;
951
			}
952
953
			foreach ( $plugins as $slug => $plugin ) {
954
				$file_path = $plugin['file_path'];
955
956
				if ( empty( $repo_updates->response[ $file_path ] ) ) {
957
					$repo_updates->response[ $file_path ] = new stdClass;
958
				}
959
960
				// We only really need to set package, but let's do all we can in case WP changes something.
961
				$repo_updates->response[ $file_path ]->slug        = $slug;
962
				$repo_updates->response[ $file_path ]->plugin      = $file_path;
963
				$repo_updates->response[ $file_path ]->new_version = $plugin['version'];
964
				$repo_updates->response[ $file_path ]->package     = $plugin['source'];
965
				if ( empty( $repo_updates->response[ $file_path ]->url ) && ! empty( $plugin['external_url'] ) ) {
966
					$repo_updates->response[ $file_path ]->url = $plugin['external_url'];
967
				}
968
			}
969
970
			set_site_transient( 'update_plugins', $repo_updates );
971
		}
972
973
		/**
974
		 * Adjust the plugin directory name if necessary.
975
		 *
976
		 * The final destination directory of a plugin is based on the subdirectory name found in the
977
		 * (un)zipped source. In some cases - most notably GitHub repository plugin downloads -, this
978
		 * subdirectory name is not the same as the expected slug and the plugin will not be recognized
979
		 * as installed. This is fixed by adjusting the temporary unzipped source subdirectory name to
980
		 * the expected plugin slug.
981
		 *
982
		 * @since 2.5.0
983
		 *
984
		 * @param string       $source        Path to upgrade/zip-file-name.tmp/subdirectory/.
985
		 * @param string       $remote_source Path to upgrade/zip-file-name.tmp.
986
		 * @param \WP_Upgrader $upgrader      Instance of the upgrader which installs the plugin.
987
		 * @return string $source
988
		 */
989
		public function maybe_adjust_source_dir( $source, $remote_source, $upgrader ) {
990
			if ( ! $this->is_tgmpa_page() || ! is_object( $GLOBALS['wp_filesystem'] ) ) {
991
				return $source;
992
			}
993
994
			// Check for single file plugins.
995
			$source_files = array_keys( $GLOBALS['wp_filesystem']->dirlist( $remote_source ) );
996
			if ( 1 === count( $source_files ) && false === $GLOBALS['wp_filesystem']->is_dir( $source ) ) {
997
				return $source;
998
			}
999
1000
			// Multi-file plugin, let's see if the directory is correctly named.
1001
			$desired_slug = '';
1002
1003
			// Figure out what the slug is supposed to be.
1004
			if ( false === $upgrader->bulk && ! empty( $upgrader->skin->options['extra']['slug'] ) ) {
1005
				$desired_slug = $upgrader->skin->options['extra']['slug'];
1006
			} else {
1007
				// Bulk installer contains less info, so fall back on the info registered here.
1008
				foreach ( $this->plugins as $slug => $plugin ) {
1009
					if ( ! empty( $upgrader->skin->plugin_names[ $upgrader->skin->i ] ) && $plugin['name'] === $upgrader->skin->plugin_names[ $upgrader->skin->i ] ) {
1010
						$desired_slug = $slug;
1011
						break;
1012
					}
1013
				}
1014
				unset( $slug, $plugin );
1015
			}
1016
1017
			if ( ! empty( $desired_slug ) ) {
1018
				$subdir_name = untrailingslashit( str_replace( trailingslashit( $remote_source ), '', $source ) );
1019
1020
				if ( ! empty( $subdir_name ) && $subdir_name !== $desired_slug ) {
1021
					$from_path = untrailingslashit( $source );
1022
					$to_path   = trailingslashit( $remote_source ) . $desired_slug;
1023
1024
					if ( true === $GLOBALS['wp_filesystem']->move( $from_path, $to_path ) ) {
1025
						return trailingslashit( $to_path );
1026 View Code Duplication
					} else {
1027
						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 ) );
1028
					}
1029 View Code Duplication
				} elseif ( empty( $subdir_name ) ) {
1030
					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 ) );
1031
				}
1032
			}
1033
1034
			return $source;
1035
		}
1036
1037
		/**
1038
		 * Activate a single plugin and send feedback about the result to the screen.
1039
		 *
1040
		 * @since 2.5.0
1041
		 *
1042
		 * @param string $file_path Path within wp-plugins/ to main plugin file.
1043
		 * @param string $slug      Plugin slug.
1044
		 * @param bool   $automatic Whether this is an automatic activation after an install. Defaults to false.
1045
		 *                          This determines the styling of the output messages.
1046
		 * @return bool False if an error was encountered, true otherwise.
1047
		 */
1048
		protected function activate_single_plugin( $file_path, $slug, $automatic = false ) {
1049
			if ( $this->can_plugin_activate( $slug ) ) {
1050
				$activate = activate_plugin( $file_path );
1051
1052
				if ( is_wp_error( $activate ) ) {
1053
					echo '<div id="message" class="error"><p>', wp_kses_post( $activate->get_error_message() ), '</p></div>',
1054
						'<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>';
1055
1056
					return false; // End it here if there is an error with activation.
1057
				} else {
1058
					if ( ! $automatic ) {
1059
						// Make sure message doesn't display again if bulk activation is performed
1060
						// immediately after a single activation.
1061
						if ( ! isset( $_POST['action'] ) ) { // WPCS: CSRF OK.
1062
							echo '<div id="message" class="updated"><p>', esc_html( $this->strings['activated_successfully'] ), ' <strong>', esc_html( $this->plugins[ $slug ]['name'] ), '.</strong></p></div>';
1063
						}
1064
					} else {
1065
						// Simpler message layout for use on the plugin install page.
1066
						echo '<p>', esc_html( $this->strings['plugin_activated'] ), '</p>';
1067
					}
1068
				}
1069 View Code Duplication
			} elseif ( $this->is_plugin_active( $slug ) ) {
1070
				// No simpler message format provided as this message should never be encountered
1071
				// on the plugin install page.
1072
				echo '<div id="message" class="error"><p>',
1073
					sprintf(
1074
						esc_html( $this->strings['plugin_already_active'] ),
1075
						'<strong>' . esc_html( $this->plugins[ $slug ]['name'] ) . '</strong>'
1076
					),
1077
					'</p></div>';
1078
			} elseif ( $this->does_plugin_require_update( $slug ) ) {
1079
				if ( ! $automatic ) {
1080
					// Make sure message doesn't display again if bulk activation is performed
1081
					// immediately after a single activation.
1082 View Code Duplication
					if ( ! isset( $_POST['action'] ) ) { // WPCS: CSRF OK.
1083
						echo '<div id="message" class="error"><p>',
1084
							sprintf(
1085
								esc_html( $this->strings['plugin_needs_higher_version'] ),
1086
								'<strong>' . esc_html( $this->plugins[ $slug ]['name'] ) . '</strong>'
1087
							),
1088
							'</p></div>';
1089
					}
1090
				} else {
1091
					// Simpler message layout for use on the plugin install page.
1092
					echo '<p>', sprintf( esc_html( $this->strings['plugin_needs_higher_version'] ), esc_html( $this->plugins[ $slug ]['name'] ) ), '</p>';
1093
				}
1094
			}
1095
1096
			return true;
1097
		}
1098
1099
		/**
1100
		 * Echoes required plugin notice.
1101
		 *
1102
		 * Outputs a message telling users that a specific plugin is required for
1103
		 * their theme. If appropriate, it includes a link to the form page where
1104
		 * users can install and activate the plugin.
1105
		 *
1106
		 * Returns early if we're on the Install page.
1107
		 *
1108
		 * @since 1.0.0
1109
		 *
1110
		 * @global object $current_screen
1111
		 *
1112
		 * @return null Returns early if we're on the Install page.
1113
		 */
1114
		public function notices() {
1115
			// Remove nag on the install page / Return early if the nag message has been dismissed or user < author.
1116
			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' ) ) ) {
1117
				return;
1118
			}
1119
1120
			// Store for the plugin slugs by message type.
1121
			$message = array();
1122
1123
			// Initialize counters used to determine plurality of action link texts.
1124
			$install_link_count          = 0;
1125
			$update_link_count           = 0;
1126
			$activate_link_count         = 0;
1127
			$total_required_action_count = 0;
1128
1129
			foreach ( $this->plugins as $slug => $plugin ) {
1130
				if ( $this->is_plugin_active( $slug ) && false === $this->does_plugin_have_update( $slug ) ) {
1131
					continue;
1132
				}
1133
1134
				if ( ! $this->is_plugin_installed( $slug ) ) {
1135
					if ( current_user_can( 'install_plugins' ) ) {
1136
						$install_link_count++;
1137
1138
						if ( true === $plugin['required'] ) {
1139
							$message['notice_can_install_required'][] = $slug;
1140
						} else {
1141
							$message['notice_can_install_recommended'][] = $slug;
1142
						}
1143
					}
1144
					if ( true === $plugin['required'] ) {
1145
						$total_required_action_count++;
1146
					}
1147
				} else {
1148
					if ( ! $this->is_plugin_active( $slug ) && $this->can_plugin_activate( $slug ) ) {
1149
						if ( current_user_can( 'activate_plugins' ) ) {
1150
							$activate_link_count++;
1151
1152
							if ( true === $plugin['required'] ) {
1153
								$message['notice_can_activate_required'][] = $slug;
1154
							} else {
1155
								$message['notice_can_activate_recommended'][] = $slug;
1156
							}
1157
						}
1158
						if ( true === $plugin['required'] ) {
1159
							$total_required_action_count++;
1160
						}