Completed
Push — develop ( 13b3c8...9c97e4 )
by Gary
03:06
created

TGMPA_Bulk_Installer_Skin::add_strings()   B

Complexity

Conditions 3

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

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

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
1125
1126
			foreach ( $this->plugins as $slug => $plugin ) {
1127
				if ( $this->is_plugin_active( $slug ) && false === $this->does_plugin_have_update( $slug ) ) {
1128
					continue;
1129
				}
1130
1131
				if ( ! $this->is_plugin_installed( $slug ) ) {
1132
					if ( current_user_can( 'install_plugins' ) ) {
1133
						$install_link_count++;
1134
1135
						if ( true === $plugin['required'] ) {
1136
							$message['notice_can_install_required'][] = $slug;
1137
						} else {
1138
							$message['notice_can_install_recommended'][] = $slug;
1139
						}
1140
					}
1141
					if ( true === $plugin['required'] ) {
1142
						$total_required_action_count++;
1143
					}
1144
				} else {
1145
					if ( ! $this->is_plugin_active( $slug ) && $this->can_plugin_activate( $slug ) ) {
1146
						if ( current_user_can( 'activate_plugins' ) ) {
1147
							$activate_link_count++;
1148
1149
							if ( true === $plugin['required'] ) {
1150
								$message['notice_can_activate_required'][] = $slug;
1151
							} else {
1152
								$message['notice_can_activate_recommended'][] = $slug;
1153
							}
1154
						}
1155
						if ( true === $plugin['required'] ) {
1156
							$total_required_action_count++;
1157
						}
1158
					}
1159
1160
					if ( $this->does_plugin_require_update( $slug ) || false !== $this->does_plugin_have_update( $slug ) ) {
1161
1162
						if ( current_user_can( 'update_plugins' ) ) {
1163
							$update_link_count++;
1164
1165
							if ( $this->does_plugin_require_update( $slug ) ) {
1166
								$message['notice_ask_to_update'][] = $slug;
1167
							} elseif ( false !== $this->does_plugin_have_update( $slug ) ) {
1168
								$message['notice_ask_to_update_maybe'][] = $slug;
1169
							}
1170
						}
1171
						if ( true === $plugin['required'] ) {
1172
							$total_required_action_count++;
1173
						}
1174