Completed
Push — develop ( 0f64a5...940a42 )
by Gary
9s
created

TGM_Plugin_Activation::admin_init()   A

Complexity

Conditions 4
Paths 3

Duplication

Lines 0
Ratio 0 %

Size

Total Lines 20
Code Lines 11

Importance

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