Completed
Pull Request — develop (#569)
by
unknown
03:13 queued 51s
created

TGM_Plugin_Activation::build_message()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 33
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

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

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

Loading history...
1381
1382
				if ( $force_activated_and_active_plugins ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $force_activated_and_active_plugins of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1383
					?>
1384
					<div class="notice <?php echo esc_attr( $this->get_admin_notice_class() ); ?> is-dismissible">
1385
						<p><strong><?php echo wp_kses_post( $this->build_message( array( 'notice_force_activation' => $force_activated_and_active_plugins ) ) ); ?></strong></p>
1386
					</div>
1387
					<?php
1388
				}
1389
1390
				delete_transient( 'tgmpa_force_activated_plugins' );
1391
			}
1392
		}
1393
1394
		/**
1395
		 * Remove inactive plugins from an array of plugin slugs.
1396
		 *
1397
		 * @since 2.x.x
1398
		 *
1399
		 * @param array $plugins Slugs of plugins.
1400
		 * @return array         Slugs with inactive plugins removed.
1401
		 */
1402
		protected function clean_inactive_plugins( $plugins ) {
1403
			$active_plugins = array();
1404
1405
			foreach ( $plugins as $slug ) {
1406
				if ( $this->is_plugin_active( $slug ) ) {
1407
					$active_plugins[] = $slug;
1408
				}
1409
			}
1410
1411
			return $active_plugins;
1412
		}
1413
1414
		/**
1415
		 * Register dismissal of admin notices.
1416
		 *
1417
		 * Acts on the dismiss link in the admin nag messages.
1418
		 * If clicked, the admin notice disappears and will no longer be visible to this user.
1419
		 *
1420
		 * @since 2.1.0
1421
		 */
1422
		public function dismiss() {
1423
			if ( isset( $_GET['tgmpa-dismiss'] ) && check_admin_referer( 'tgmpa-dismiss-' . get_current_user_id() ) ) {
1424
				update_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, 1 );
1425
			}
1426
		}
1427
1428
		/**
1429
		 * Add individual plugin to our collection of plugins.
1430
		 *
1431
		 * If the required keys are not set or the plugin has already
1432
		 * been registered, the plugin is not added.
1433
		 *
1434
		 * @since 2.0.0
1435
		 *
1436
		 * @param array|null $plugin Array of plugin arguments or null if invalid argument.
1437
		 * @return null Return early if incorrect argument.
1438
		 */
1439
		public function register( $plugin ) {
1440
			if ( empty( $plugin['slug'] ) || empty( $plugin['name'] ) ) {
1441
				return;
1442
			}
1443
1444
			if ( empty( $plugin['slug'] ) || ! is_string( $plugin['slug'] ) || isset( $this->plugins[ $plugin['slug'] ] ) ) {
1445
				return;
1446
			}
1447
1448
			$defaults = array(
1449
				'name'               => '',      // String
1450
				'slug'               => '',      // String
1451
				'source'             => 'repo',  // String
1452
				'required'           => false,   // Boolean
1453
				'version'            => '',      // String
1454
				'force_activation'   => false,   // Boolean
1455
				'force_deactivation' => false,   // Boolean
1456
				'external_url'       => '',      // String
1457
				'is_callable'        => '',      // String|Array.
1458
			);
1459
1460
			// Prepare the received data.
1461
			$plugin = wp_parse_args( $plugin, $defaults );
1462
1463
			// Standardize the received slug.
1464
			$plugin['slug'] = $this->sanitize_key( $plugin['slug'] );
1465
1466
			// Forgive users for using string versions of booleans or floats for version number.
1467
			$plugin['version']            = (string) $plugin['version'];
1468
			$plugin['source']             = empty( $plugin['source'] ) ? 'repo' : $plugin['source'];
1469
			$plugin['required']           = TGMPA_Utils::validate_bool( $plugin['required'] );
1470
			$plugin['force_activation']   = TGMPA_Utils::validate_bool( $plugin['force_activation'] );
1471
			$plugin['force_deactivation'] = TGMPA_Utils::validate_bool( $plugin['force_deactivation'] );
1472
1473
			// Enrich the received data.
1474
			$plugin['file_path']   = $this->_get_plugin_basename_from_slug( $plugin['slug'] );
1475
			$plugin['source_type'] = $this->get_plugin_source_type( $plugin['source'] );
1476
1477
			// Set the class properties.
1478
			$this->plugins[ $plugin['slug'] ]    = $plugin;
1479
			$this->sort_order[ $plugin['slug'] ] = $plugin['name'];
1480
1481
			// Should we add the force activation hook ?
1482
			if ( true === $plugin['force_activation'] ) {
1483
				$this->has_forced_activation = true;
1484
			}
1485
1486
			// Should we add the force deactivation hook ?
1487
			if ( true === $plugin['force_deactivation'] ) {
1488
				$this->has_forced_deactivation = true;
1489
			}
1490
		}
1491
1492
		/**
1493
		 * Determine what type of source the plugin comes from.
1494
		 *
1495
		 * @since 2.5.0
1496
		 *
1497
		 * @param string $source The source of the plugin as provided, either empty (= WP repo), a file path
1498
		 *                       (= bundled) or an external URL.
1499
		 * @return string 'repo', 'external', or 'bundled'
1500
		 */
1501
		protected function get_plugin_source_type( $source ) {
1502
			if ( 'repo' === $source || preg_match( self::WP_REPO_REGEX, $source ) ) {
1503
				return 'repo';
1504
			} elseif ( preg_match( self::IS_URL_REGEX, $source ) ) {
1505
				return 'external';
1506
			} else {
1507
				return 'bundled';
1508
			}
1509
		}
1510
1511
		/**
1512
		 * Sanitizes a string key.
1513
		 *
1514
		 * Near duplicate of WP Core `sanitize_key()`. The difference is that uppercase characters *are*
1515
		 * allowed, so as not to break upgrade paths from non-standard bundled plugins using uppercase
1516
		 * characters in the plugin directory path/slug. Silly them.
1517
		 *
1518
		 * @see https://developer.wordpress.org/reference/hooks/sanitize_key/
1519
		 *
1520
		 * @since 2.5.0
1521
		 *
1522
		 * @param string $key String key.
1523
		 * @return string Sanitized key
1524
		 */
1525
		public function sanitize_key( $key ) {
1526
			$raw_key = $key;
1527
			$key     = preg_replace( '`[^A-Za-z0-9_-]`', '', $key );
1528
1529
			/**
1530
			 * Filter a sanitized key string.
1531
			 *
1532
			 * @since 2.5.0
1533
			 *
1534
			 * @param string $key     Sanitized key.
1535
			 * @param string $raw_key The key prior to sanitization.
1536
			 */
1537
			return apply_filters( 'tgmpa_sanitize_key', $key, $raw_key );
1538
		}
1539
1540
		/**
1541
		 * Amend default configuration settings.
1542
		 *
1543
		 * @since 2.0.0
1544
		 *
1545
		 * @param array $config Array of config options to pass as class properties.
1546
		 */
1547
		public function config( $config ) {
1548
			$keys = array(
1549
				'id',
1550
				'default_path',
1551
				'has_notices',
1552
				'dismissable',
1553
				'dismiss_msg',
1554
				'menu',
1555
				'parent_slug',
1556
				'capability',
1557
				'is_automatic',
1558
				'message',
1559
				'strings',
1560
			);
1561
1562
			foreach ( $keys as $key ) {
1563
				if ( isset( $config[ $key ] ) ) {
1564
					if ( is_array( $config[ $key ] ) ) {
1565
						$this->$key = array_merge( $this->$key, $config[ $key ] );
1566
					} else {
1567
						$this->$key = $config[ $key ];
1568
					}
1569
				}
1570
			}
1571
		}
1572
1573
		/**
1574
		 * Amend action link after plugin installation.
1575
		 *
1576
		 * @since 2.0.0
1577
		 *
1578
		 * @param array $install_actions Existing array of actions.
1579
		 * @return false|array Amended array of actions.
1580
		 */
1581
		public function actions( $install_actions ) {
1582
			// Remove action links on the TGMPA install page.
1583
			if ( $this->is_tgmpa_page() ) {
1584
				return false;
1585
			}
1586
1587
			return $install_actions;
1588
		}
1589
1590
		/**
1591
		 * Flushes the plugins cache on theme switch to prevent stale entries
1592
		 * from remaining in the plugin table.
1593
		 *
1594
		 * @since 2.4.0
1595
		 *
1596
		 * @param bool $clear_update_cache Optional. Whether to clear the Plugin updates cache.
1597
		 *                                 Parameter added in v2.5.0.
1598
		 */
1599
		public function flush_plugins_cache( $clear_update_cache = true ) {
1600
			wp_clean_plugins_cache( $clear_update_cache );
1601
		}
1602
1603
		/**
1604
		 * Set file_path key for each installed plugin.
1605
		 *
1606
		 * @since 2.1.0
1607
		 *
1608
		 * @param string $plugin_slug Optional. If set, only (re-)populates the file path for that specific plugin.
1609
		 *                            Parameter added in v2.5.0.
1610
		 */
1611
		public function populate_file_path( $plugin_slug = '' ) {
1612
			if ( ! empty( $plugin_slug ) && is_string( $plugin_slug ) && isset( $this->plugins[ $plugin_slug ] ) ) {
1613
				$this->plugins[ $plugin_slug ]['file_path'] = $this->_get_plugin_basename_from_slug( $plugin_slug );
1614
			} else {
1615
				// Add file_path key for all plugins.
1616
				foreach ( $this->plugins as $slug => $values ) {
1617
					$this->plugins[ $slug ]['file_path'] = $this->_get_plugin_basename_from_slug( $slug );
1618
				}
1619
			}
1620
		}
1621
1622
		/**
1623
		 * Helper function to extract the file path of the plugin file from the
1624
		 * plugin slug, if the plugin is installed.
1625
		 *
1626
		 * @since 2.0.0
1627
		 *
1628
		 * @param string $slug Plugin slug (typically folder name) as provided by the developer.
1629
		 * @return string Either file path for plugin if installed, or just the plugin slug.
1630
		 */
1631
		protected function _get_plugin_basename_from_slug( $slug ) {
1632
			$keys = array_keys( $this->get_plugins() );
1633
1634
			foreach ( $keys as $key ) {
1635
				if ( preg_match( '|^' . $slug . '/|', $key ) ) {
1636
					return $key;
1637
				}
1638
			}
1639
1640
			return $slug;
1641
		}
1642
1643
		/**
1644
		 * Retrieve plugin data, given the plugin name.
1645
		 *
1646
		 * Loops through the registered plugins looking for $name. If it finds it,
1647
		 * it returns the $data from that plugin. Otherwise, returns false.
1648
		 *
1649
		 * @since 2.1.0
1650
		 *
1651
		 * @param string $name Name of the plugin, as it was registered.
1652
		 * @param string $data Optional. Array key of plugin data to return. Default is slug.
1653
		 * @return string|boolean Plugin slug if found, false otherwise.
1654
		 */
1655
		public function _get_plugin_data_from_name( $name, $data = 'slug' ) {
1656
			foreach ( $this->plugins as $values ) {
1657
				if ( $name === $values['name'] && isset( $values[ $data ] ) ) {
1658
					return $values[ $data ];
1659
				}
1660
			}
1661
1662
			return false;
1663
		}
1664
1665
		/**
1666
		 * Retrieve the download URL for a package.
1667
		 *
1668
		 * @since 2.5.0
1669
		 *
1670
		 * @param string $slug Plugin slug.
1671
		 * @return string Plugin download URL or path to local file or empty string if undetermined.
1672
		 */
1673
		public function get_download_url( $slug ) {
1674
			$dl_source = '';
1675
1676
			switch ( $this->plugins[ $slug ]['source_type'] ) {
1677
				case 'repo':
1678
					return $this->get_wp_repo_download_url( $slug );
1679
				case 'external':
1680
					return $this->plugins[ $slug ]['source'];
1681
				case 'bundled':
1682
					return $this->default_path . $this->plugins[ $slug ]['source'];
1683
			}
1684
1685
			return $dl_source; // Should never happen.
1686
		}
1687
1688
		/**
1689
		 * Retrieve the download URL for a WP repo package.
1690
		 *
1691
		 * @since 2.5.0
1692
		 *
1693
		 * @param string $slug Plugin slug.
1694
		 * @return string Plugin download URL.
1695
		 */
1696
		protected function get_wp_repo_download_url( $slug ) {
1697
			$source = '';
1698
			$api    = $this->get_plugins_api( $slug );
1699
1700
			if ( false !== $api && isset( $api->download_link ) ) {
1701
				$source = $api->download_link;
1702
			}
1703
1704
			return $source;
1705
		}
1706
1707
		/**
1708
		 * Try to grab information from WordPress API.
1709
		 *
1710
		 * @since 2.5.0
1711
		 *
1712
		 * @param string $slug Plugin slug.
1713
		 * @return object Plugins_api response object on success, WP_Error on failure.
1714
		 */
1715
		protected function get_plugins_api( $slug ) {
1716
			static $api = array(); // Cache received responses.
1717
1718
			if ( ! isset( $api[ $slug ] ) ) {
1719
				if ( ! function_exists( 'plugins_api' ) ) {
1720
					require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
1721
				}
1722
1723
				$response = plugins_api( 'plugin_information', array( 'slug' => $slug, 'fields' => array( 'sections' => false ) ) );
1724
1725
				$api[ $slug ] = false;
1726
1727
				if ( is_wp_error( $response ) ) {
1728
					wp_die( esc_html( $this->strings['oops'] ) );
1729
				} else {
1730
					$api[ $slug ] = $response;
1731
				}
1732
			}
1733
1734
			return $api[ $slug ];
1735
		}
1736
1737
		/**
1738
		 * Retrieve a link to a plugin information page.
1739
		 *
1740
		 * @since 2.5.0
1741
		 *
1742
		 * @param string $slug Plugin slug.
1743
		 * @return string Fully formed html link to a plugin information page if available
1744
		 *                or the plugin name if not.
1745
		 */
1746
		public function get_info_link( $slug ) {
1747
			if ( ! empty( $this->plugins[ $slug ]['external_url'] ) && preg_match( self::IS_URL_REGEX, $this->plugins[ $slug ]['external_url'] ) ) {
1748
				$link = sprintf(
1749
					'<a href="%1$s" target="_blank">%2$s</a>',
1750
					esc_url( $this->plugins[ $slug ]['external_url'] ),
1751
					esc_html( $this->plugins[ $slug ]['name'] )
1752
				);
1753
			} elseif ( 'repo' === $this->plugins[ $slug ]['source_type'] ) {
1754
				$url = add_query_arg(
1755
					array(
1756
						'tab'       => 'plugin-information',
1757
						'plugin'    => urlencode( $slug ),
1758
						'TB_iframe' => 'true',
1759
						'width'     => '640',
1760
						'height'    => '500',
1761
					),
1762
					self_admin_url( 'plugin-install.php' )
1763
				);
1764
1765
				$link = sprintf(
1766
					'<a href="%1$s" class="thickbox">%2$s</a>',
1767
					esc_url( $url ),
1768
					esc_html( $this->plugins[ $slug ]['name'] )
1769
				);
1770
			} else {
1771
				$link = esc_html( $this->plugins[ $slug ]['name'] ); // No hyperlink.
1772
			}
1773
1774
			return $link;
1775
		}
1776
1777
		/**
1778
		 * Determine if we're on the TGMPA Install page.
1779
		 *
1780
		 * @since 2.1.0
1781
		 *
1782
		 * @return boolean True when on the TGMPA page, false otherwise.
1783
		 */
1784
		protected function is_tgmpa_page() {
1785
			return isset( $_GET['page'] ) && $this->menu === $_GET['page'];
1786
		}
1787
1788
		/**
1789
		 * Determine if we're on a WP Core installation/upgrade page.
1790
		 *
1791
		 * @since 2.6.0
1792
		 *
1793
		 * @return boolean True when on a WP Core installation/upgrade page, false otherwise.
1794
		 */
1795
		protected function is_core_update_page() {
1796
			// Current screen is not always available, most notably on the customizer screen.
1797
			if ( ! function_exists( 'get_current_screen' ) ) {
1798
				return false;
1799
			}
1800
1801
			$screen = get_current_screen();
1802
1803
			if ( 'update-core' === $screen->base ) {
1804
				// Core update screen.
1805
				return true;
1806
			} elseif ( 'plugins' === $screen->base && ! empty( $_POST['action'] ) ) { // WPCS: CSRF ok.
1807
				// Plugins bulk update screen.
1808
				return true;
1809
			} elseif ( 'update' === $screen->base && ! empty( $_POST['action'] ) ) { // WPCS: CSRF ok.
1810
				// Individual updates (ajax call).
1811
				return true;
1812
			}
1813
1814
			return false;
1815
		}
1816
1817
		/**
1818
		 * Retrieve the URL to the TGMPA Install page.
1819
		 *
1820
		 * I.e. depending on the config settings passed something along the lines of:
1821
		 * http://example.com/wp-admin/themes.php?page=tgmpa-install-plugins
1822
		 *
1823
		 * @since 2.5.0
1824
		 *
1825
		 * @return string Properly encoded URL (not escaped).
1826
		 */
1827
		public function get_tgmpa_url() {
1828
			static $url;
1829
1830
			if ( ! isset( $url ) ) {
1831
				$parent = $this->parent_slug;
1832
				if ( false === strpos( $parent, '.php' ) ) {
1833
					$parent = 'admin.php';
1834
				}
1835
				$url = add_query_arg(
1836
					array(
1837
						'page' => urlencode( $this->menu ),
1838
					),
1839
					self_admin_url( $parent )
1840
				);
1841
			}
1842
1843
			return $url;
1844
		}
1845
1846
		/**
1847
		 * Retrieve the URL to the TGMPA Install page for a specific plugin status (view).
1848
		 *
1849
		 * I.e. depending on the config settings passed something along the lines of:
1850
		 * http://example.com/wp-admin/themes.php?page=tgmpa-install-plugins&plugin_status=install
1851
		 *
1852
		 * @since 2.5.0
1853
		 *
1854
		 * @param string $status Plugin status - either 'install', 'update' or 'activate'.
1855
		 * @return string Properly encoded URL (not escaped).
1856
		 */
1857
		public function get_tgmpa_status_url( $status ) {
1858
			return add_query_arg(
1859
				array(
1860
					'plugin_status' => urlencode( $status ),
1861
				),
1862
				$this->get_tgmpa_url()
1863
			);
1864
		}
1865
1866
		/**
1867
		 * Determine whether there are open actions for plugins registered with TGMPA.
1868
		 *
1869
		 * @since 2.5.0
1870
		 *
1871
		 * @return bool True if complete, i.e. no outstanding actions. False otherwise.
1872
		 */
1873
		public function is_tgmpa_complete() {
1874
			$complete = true;
1875
			foreach ( $this->plugins as $slug => $plugin ) {
1876
				if ( ! $this->is_plugin_active( $slug ) || false !== $this->does_plugin_have_update( $slug ) ) {
1877
					$complete = false;
1878
					break;
1879
				}
1880
			}
1881
1882
			return $complete;
1883
		}
1884
1885
		/**
1886
		 * Check if a plugin is installed. Does not take must-use plugins into account.
1887
		 *
1888
		 * @since 2.5.0
1889
		 *
1890
		 * @param string $slug Plugin slug.
1891
		 * @return bool True if installed, false otherwise.
1892
		 */
1893
		public function is_plugin_installed( $slug ) {
1894
			$installed_plugins = $this->get_plugins(); // Retrieve a list of all installed plugins (WP cached).
1895
1896
			return ( ! empty( $installed_plugins[ $this->plugins[ $slug ]['file_path'] ] ) );
1897
		}
1898
1899
		/**
1900
		 * Check if a plugin is active.
1901
		 *
1902
		 * @since 2.5.0
1903
		 *
1904
		 * @param string $slug Plugin slug.
1905
		 * @return bool True if active, false otherwise.
1906
		 */
1907
		public function is_plugin_active( $slug ) {
1908
			return ( ( ! empty( $this->plugins[ $slug ]['is_callable'] ) && is_callable( $this->plugins[ $slug ]['is_callable'] ) ) || is_plugin_active( $this->plugins[ $slug ]['file_path'] ) );
1909
		}
1910
1911
		/**
1912
		 * Check if a plugin can be updated, i.e. if we have information on the minimum WP version required
1913
		 * available, check whether the current install meets them.
1914
		 *
1915
		 * @since 2.5.0
1916
		 *
1917
		 * @param string $slug Plugin slug.
1918
		 * @return bool True if OK to update, false otherwise.
1919
		 */
1920
		public function can_plugin_update( $slug ) {
1921
			// We currently can't get reliable info on non-WP-repo plugins - issue #380.
1922
			if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) {
1923
				return true;
1924
			}
1925
1926
			$api = $this->get_plugins_api( $slug );
1927
1928
			if ( false !== $api && isset( $api->requires ) ) {
1929
				return version_compare( $this->wp_version, $api->requires, '>=' );
1930
			}
1931
1932
			// No usable info received from the plugins API, presume we can update.
1933
			return true;
1934
		}
1935
1936
		/**
1937
		 * Check to see if the plugin is 'updatetable', i.e. installed, with an update available
1938
		 * and no WP version requirements blocking it.
1939
		 *
1940
		 * @since 2.6.0
1941
		 *
1942
		 * @param string $slug Plugin slug.
1943
		 * @return bool True if OK to proceed with update, false otherwise.
1944
		 */
1945
		public function is_plugin_updatetable( $slug ) {
1946
			if ( ! $this->is_plugin_installed( $slug ) ) {
1947
				return false;
1948
			} else {
1949
				return ( false !== $this->does_plugin_have_update( $slug ) && $this->can_plugin_update( $slug ) );
1950
			}
1951
		}
1952
1953
		/**
1954
		 * Check if a plugin can be activated, i.e. is not currently active and meets the minimum
1955
		 * plugin version requirements set in TGMPA (if any).
1956
		 *
1957
		 * @since 2.5.0
1958
		 *
1959
		 * @param string $slug Plugin slug.
1960
		 * @return bool True if OK to activate, false otherwise.
1961
		 */
1962
		public function can_plugin_activate( $slug ) {
1963
			return ( ! $this->is_plugin_active( $slug ) && ! $this->does_plugin_require_update( $slug ) );
1964
		}
1965
1966
		/**
1967
		 * Retrieve the version number of an installed plugin.
1968
		 *
1969
		 * @since 2.5.0
1970
		 *
1971
		 * @param string $slug Plugin slug.
1972
		 * @return string Version number as string or an empty string if the plugin is not installed
1973
		 *                or version unknown (plugins which don't comply with the plugin header standard).
1974
		 */
1975
		public function get_installed_version( $slug ) {
1976
			$installed_plugins = $this->get_plugins(); // Retrieve a list of all installed plugins (WP cached).
1977
1978
			if ( ! empty( $installed_plugins[ $this->plugins[ $slug ]['file_path'] ]['Version'] ) ) {
1979
				return $installed_plugins[ $this->plugins[ $slug ]['file_path'] ]['Version'];
1980
			}
1981
1982
			return '';
1983
		}
1984
1985
		/**
1986
		 * Check whether a plugin complies with the minimum version requirements.
1987
		 *
1988
		 * @since 2.5.0
1989
		 *
1990
		 * @param string $slug Plugin slug.
1991
		 * @return bool True when a plugin needs to be updated, otherwise false.
1992
		 */
1993
		public function does_plugin_require_update( $slug ) {
1994
			$installed_version = $this->get_installed_version( $slug );
1995
			$minimum_version   = $this->plugins[ $slug ]['version'];
1996
1997
			return version_compare( $minimum_version, $installed_version, '>' );
1998
		}
1999
2000
		/**
2001
		 * Check whether there is an update available for a plugin.
2002
		 *
2003
		 * @since 2.5.0
2004
		 *
2005
		 * @param string $slug Plugin slug.
2006
		 * @return false|string Version number string of the available update or false if no update available.
2007
		 */
2008
		public function does_plugin_have_update( $slug ) {
2009
			// Presume bundled and external plugins will point to a package which meets the minimum required version.
2010
			if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) {
2011
				if ( $this->does_plugin_require_update( $slug ) ) {
2012
					return $this->plugins[ $slug ]['version'];
2013
				}
2014
2015
				return false;
2016
			}
2017
2018
			$repo_updates = get_site_transient( 'update_plugins' );
2019
2020 View Code Duplication
			if ( isset( $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->new_version ) ) {
2021
				return $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->new_version;
2022
			}
2023
2024
			return false;
2025
		}
2026
2027
		/**
2028
		 * Retrieve potential upgrade notice for a plugin.
2029
		 *
2030
		 * @since 2.5.0
2031
		 *
2032
		 * @param string $slug Plugin slug.
2033
		 * @return string The upgrade notice or an empty string if no message was available or provided.
2034
		 */
2035
		public function get_upgrade_notice( $slug ) {
2036
			// We currently can't get reliable info on non-WP-repo plugins - issue #380.
2037
			if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) {
2038
				return '';
2039
			}
2040
2041
			$repo_updates = get_site_transient( 'update_plugins' );
2042
2043 View Code Duplication
			if ( ! empty( $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->upgrade_notice ) ) {
2044
				return $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->upgrade_notice;
2045
			}
2046
2047
			return '';
2048
		}
2049
2050
		/**
2051
		 * Wrapper around the core WP get_plugins function, making sure it's actually available.
2052
		 *
2053
		 * @since 2.5.0
2054
		 *
2055
		 * @param string $plugin_folder Optional. Relative path to single plugin folder.
2056
		 * @return array Array of installed plugins with plugin information.
2057
		 */
2058
		public function get_plugins( $plugin_folder = '' ) {
2059
			if ( ! function_exists( 'get_plugins' ) ) {
2060
				require_once ABSPATH . 'wp-admin/includes/plugin.php';
2061
			}
2062
2063
			return get_plugins( $plugin_folder );
2064
		}
2065
2066
		/**
2067
		 * Delete dismissable nag option when theme is switched.
2068
		 *
2069
		 * This ensures that the user(s) is/are again reminded via nag of required
2070
		 * and/or recommended plugins if they re-activate the theme.
2071
		 *
2072
		 * @since 2.1.1
2073
		 */
2074
		public function update_dismiss() {
2075
			delete_metadata( 'user', null, 'tgmpa_dismissed_notice_' . $this->id, null, true );
2076
		}
2077
2078
		/**
2079
		 * Forces plugin activation if the parameter 'force_activation' is
2080
		 * set to true.
2081
		 *
2082
		 * This allows theme authors to specify certain plugins that must be
2083
		 * active at all times while using the current theme.
2084
		 *
2085
		 * Please take special care when using this parameter as it has the
2086
		 * potential to be harmful if not used correctly. Setting this parameter
2087
		 * to true will not allow the specified plugin to be deactivated unless
2088
		 * the user switches themes.
2089
		 *
2090
		 * @since 2.2.0
2091
		 */
2092
		public function force_activation() {
2093
			foreach ( $this->plugins as $slug => $plugin ) {
2094
				if ( true === $plugin['force_activation'] ) {
2095
					if ( ! $this->is_plugin_installed( $slug ) ) {
2096
						// Oops, plugin isn't there so iterate to next condition.
2097
						continue;
2098
					} elseif ( $this->can_plugin_activate( $slug ) ) {
2099
						// There we go, activate the plugin.
2100
						activate_plugin( $plugin['file_path'] );
2101
						$this->append_transient( 'tgmpa_force_activated_plugins', $slug );
2102
					}
2103
				}
2104
			}
2105
		}
2106
2107
		/**
2108
		 * Set/update a transient, appending the new value if the transient already exists.
2109
		 *
2110
		 * @since 2.x.x
2111
		 *
2112
		 * @param string       $transient_key Name of transient.
2113
		 * @param string|array $data          To set or add to transient.
2114
		 */
2115
		protected function append_transient( $transient_key, $data ) {
2116
			$transient_data = get_transient( $transient_key );
2117
2118
			if ( false === $transient_data ) {
2119
				$transient_data = array();
2120
			}
2121
2122
			if ( ! is_array( $transient_data ) ) {
2123
				$transient_data = (array) $transient_data;
2124
			}
2125
2126
			if ( $data ) {
2127
				if ( is_string( $data ) ) {
2128
					$transient_data[] = $data;
2129
				} elseif ( is_array( $data ) ) {
2130
					$transient_data = $transient_data + $data;
2131
				}
2132
2133
				set_transient( $transient_key, $transient_data );
2134
			}
2135
		}
2136
2137
		/**
2138
		 * Forces plugin deactivation if the parameter 'force_deactivation'
2139
		 * is set to true and adds the plugin to the 'recently active' plugins list.
2140
		 *
2141
		 * This allows theme authors to specify certain plugins that must be
2142
		 * deactivated upon switching from the current theme to another.
2143
		 *
2144
		 * Please take special care when using this parameter as it has the
2145
		 * potential to be harmful if not used correctly.
2146
		 *
2147
		 * @since 2.2.0
2148
		 */
2149
		public function force_deactivation() {
2150
			$deactivated = array();
2151
2152
			foreach ( $this->plugins as $slug => $plugin ) {
2153
				/*
2154
				 * Only proceed forward if the parameter is set to true and plugin is active
2155
				 * as a 'normal' (not must-use) plugin.
2156
				 */
2157
				if ( true === $plugin['force_deactivation'] && is_plugin_active( $plugin['file_path'] ) ) {
2158
					deactivate_plugins( $plugin['file_path'] );
2159
					$deactivated[ $plugin['file_path'] ] = time();
2160
				}
2161
			}
2162
2163
			if ( ! empty( $deactivated ) ) {
2164
				update_option( 'recently_activated', $deactivated + (array) get_option( 'recently_activated' ) );
2165
			}
2166
		}
2167
2168
		/**
2169
		 * Echo the current TGMPA version number to the page.
2170
		 *
2171
		 * @since 2.5.0
2172
		 */
2173
		public function show_tgmpa_version() {
2174
			echo '<p style="float: right; padding: 0em 1.5em 0.5em 0;"><strong><small>',
2175
				esc_html(
2176
					sprintf(
2177
						/* translators: %s: version number */
2178
						__( 'TGMPA v%s', 'tgmpa' ),
2179
						self::TGMPA_VERSION
2180
					)
2181
				),
2182
				'</small></strong></p>';
2183
		}
2184
2185
		/**
2186
		 * Returns the singleton instance of the class.
2187
		 *
2188
		 * @since 2.4.0
2189
		 *
2190
		 * @return \TGM_Plugin_Activation The TGM_Plugin_Activation object.
2191
		 */
2192
		public static function get_instance() {
2193
			if ( ! isset( self::$instance ) && ! ( self::$instance instanceof self ) ) {
2194
				self::$instance = new self();
2195
			}
2196
2197
			return self::$instance;
2198
		}
2199
	}
2200
2201
	if ( ! function_exists( 'load_tgm_plugin_activation' ) ) {
2202
		/**
2203
		 * Ensure only one instance of the class is ever invoked.
2204
		 *
2205
		 * @since 2.5.0
2206
		 */
2207
		function load_tgm_plugin_activation() {
2208
			$GLOBALS['tgmpa'] = TGM_Plugin_Activation::get_instance();
2209
		}
2210
	}
2211
2212
	if ( did_action( 'plugins_loaded' ) ) {
2213
		load_tgm_plugin_activation();
2214
	} else {
2215
		add_action( 'plugins_loaded', 'load_tgm_plugin_activation' );
2216
	}
2217
}
2218
2219
if ( ! function_exists( 'tgmpa' ) ) {
2220
	/**
2221
	 * Helper function to register a collection of required plugins.
2222
	 *
2223
	 * @since 2.0.0
2224
	 * @api
2225
	 *
2226
	 * @param array $plugins An array of plugin arrays.
2227
	 * @param array $config  Optional. An array of configuration values.
2228
	 */
2229
	function tgmpa( $plugins, $config = array() ) {
2230
		$instance = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
2231
2232
		foreach ( $plugins as $plugin ) {
2233
			call_user_func( array( $instance, 'register' ), $plugin );
2234
		}
2235
2236
		if ( ! empty( $config ) && is_array( $config ) ) {
2237
			// Send out notices for deprecated arguments passed.
2238
			if ( isset( $config['notices'] ) ) {
2239
				_deprecated_argument( __FUNCTION__, '2.2.0', 'The `notices` config parameter was renamed to `has_notices` in TGMPA 2.2.0. Please adjust your configuration.' );
2240
				if ( ! isset( $config['has_notices'] ) ) {
2241
					$config['has_notices'] = $config['notices'];
2242
				}
2243
			}
2244
2245
			if ( isset( $config['parent_menu_slug'] ) ) {
2246
				_deprecated_argument( __FUNCTION__, '2.4.0', 'The `parent_menu_slug` config parameter was removed in TGMPA 2.4.0. In TGMPA 2.5.0 an alternative was (re-)introduced. Please adjust your configuration. For more information visit the website: http://tgmpluginactivation.com/configuration/#h-configuration-options.' );
2247
			}
2248
			if ( isset( $config['parent_url_slug'] ) ) {
2249
				_deprecated_argument( __FUNCTION__, '2.4.0', 'The `parent_url_slug` config parameter was removed in TGMPA 2.4.0. In TGMPA 2.5.0 an alternative was (re-)introduced. Please adjust your configuration. For more information visit the website: http://tgmpluginactivation.com/configuration/#h-configuration-options.' );
2250
			}
2251
2252
			call_user_func( array( $instance, 'config' ), $config );
2253
		}
2254
	}
2255
}
2256
2257
/**
2258
 * WP_List_Table isn't always available. If it isn't available,
2259
 * we load it here.
2260
 *
2261
 * @since 2.2.0
2262
 */
2263
if ( ! class_exists( 'WP_List_Table' ) ) {
2264
	require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
2265
}
2266
2267
if ( ! class_exists( 'TGMPA_List_Table' ) ) {
2268
2269
	/**
2270
	 * List table class for handling plugins.
2271
	 *
2272
	 * Extends the WP_List_Table class to provide a future-compatible
2273
	 * way of listing out all required/recommended plugins.
2274
	 *
2275
	 * Gives users an interface similar to the Plugin Administration
2276
	 * area with similar (albeit stripped down) capabilities.
2277
	 *
2278
	 * This class also allows for the bulk install of plugins.
2279
	 *
2280
	 * @since 2.2.0
2281
	 *
2282
	 * @package TGM-Plugin-Activation
2283
	 * @author  Thomas Griffin
2284
	 * @author  Gary Jones
2285
	 */
2286
	class TGMPA_List_Table extends WP_List_Table {
2287
		/**
2288
		 * TGMPA instance.
2289
		 *
2290
		 * @since 2.5.0
2291
		 *
2292
		 * @var object
2293
		 */
2294
		protected $tgmpa;
2295
2296
		/**
2297
		 * The currently chosen view.
2298
		 *
2299
		 * @since 2.5.0
2300
		 *
2301
		 * @var string One of: 'all', 'install', 'update', 'activate'
2302
		 */
2303
		public $view_context = 'all';
2304
2305
		/**
2306
		 * The plugin counts for the various views.
2307
		 *
2308
		 * @since 2.5.0
2309
		 *
2310
		 * @var array
2311
		 */
2312
		protected $view_totals = array(
2313
			'all'      => 0,
2314
			'install'  => 0,
2315
			'update'   => 0,
2316
			'activate' => 0,
2317
		);
2318
2319
		/**
2320
		 * References parent constructor and sets defaults for class.
2321
		 *
2322
		 * @since 2.2.0
2323
		 */
2324
		public function __construct() {
2325
			$this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
2326
2327
			parent::__construct(
2328
				array(
2329
					'singular' => 'plugin',
2330
					'plural'   => 'plugins',
2331
					'ajax'     => false,
2332
				)
2333
			);
2334
2335
			if ( isset( $_REQUEST['plugin_status'] ) && in_array( $_REQUEST['plugin_status'], array( 'install', 'update', 'activate' ), true ) ) {
2336
				$this->view_context = sanitize_key( $_REQUEST['plugin_status'] );
2337
			}
2338
2339
			add_filter( 'tgmpa_table_data_items', array( $this, 'sort_table_items' ) );
2340
		}
2341
2342
		/**
2343
		 * Get a list of CSS classes for the <table> tag.
2344
		 *
2345
		 * Overruled to prevent the 'plural' argument from being added.
2346
		 *
2347
		 * @since 2.5.0
2348
		 *
2349
		 * @return array CSS classnames.
2350
		 */
2351
		public function get_table_classes() {
2352
			return array( 'widefat', 'fixed' );
2353
		}
2354
2355
		/**
2356
		 * Gathers and renames all of our plugin information to be used by WP_List_Table to create our table.
2357
		 *
2358
		 * @since 2.2.0
2359
		 *
2360
		 * @return array $table_data Information for use in table.
2361
		 */
2362
		protected function _gather_plugin_data() {
2363
			// Load thickbox for plugin links.
2364
			$this->tgmpa->admin_init();
2365
			$this->tgmpa->thickbox();
2366
2367
			// Categorize the plugins which have open actions.
2368
			$plugins = $this->categorize_plugins_to_views();
2369
2370
			// Set the counts for the view links.
2371
			$this->set_view_totals( $plugins );
2372
2373
			// Prep variables for use and grab list of all installed plugins.
2374
			$table_data = array();
2375
			$i          = 0;
2376
2377
			// Redirect to the 'all' view if no plugins were found for the selected view context.
2378
			if ( empty( $plugins[ $this->view_context ] ) ) {
2379
				$this->view_context = 'all';
2380
			}
2381
2382
			foreach ( $plugins[ $this->view_context ] as $slug => $plugin ) {
2383
				$table_data[ $i ]['sanitized_plugin']  = $plugin['name'];
2384
				$table_data[ $i ]['slug']              = $slug;
2385
				$table_data[ $i ]['plugin']            = '<strong>' . $this->tgmpa->get_info_link( $slug ) . '</strong>';
2386
				$table_data[ $i ]['source']            = $this->get_plugin_source_type_text( $plugin['source_type'] );
2387
				$table_data[ $i ]['type']              = $this->get_plugin_advise_type_text( $plugin['required'] );
2388
				$table_data[ $i ]['status']            = $this->get_plugin_status_text( $slug );
2389
				$table_data[ $i ]['installed_version'] = $this->tgmpa->get_installed_version( $slug );
2390
				$table_data[ $i ]['minimum_version']   = $plugin['version'];
2391
				$table_data[ $i ]['available_version'] = $this->tgmpa->does_plugin_have_update( $slug );
2392
2393
				// Prep the upgrade notice info.
2394
				$upgrade_notice = $this->tgmpa->get_upgrade_notice( $slug );
2395
				if ( ! empty( $upgrade_notice ) ) {
2396
					$table_data[ $i ]['upgrade_notice'] = $upgrade_notice;
2397
2398
					add_action( "tgmpa_after_plugin_row_{$slug}", array( $this, 'wp_plugin_update_row' ), 10, 2 );
2399
				}
2400
2401
				$table_data[ $i ] = apply_filters( 'tgmpa_table_data_item', $table_data[ $i ], $plugin );
2402
2403
				$i++;
2404
			}
2405
2406
			return $table_data;
2407
		}
2408
2409
		/**
2410
		 * Categorize the plugins which have open actions into views for the TGMPA page.
2411
		 *
2412
		 * @since 2.5.0
2413
		 */
2414
		protected function categorize_plugins_to_views() {
2415
			$plugins = array(
2416
				'all'      => array(), // Meaning: all plugins which still have open actions.
2417
				'install'  => array(),
2418
				'update'   => array(),
2419
				'activate' => array(),
2420
			);
2421
2422
			foreach ( $this->tgmpa->plugins as $slug => $plugin ) {
2423
				if ( $this->tgmpa->is_plugin_active( $slug ) && false === $this->tgmpa->does_plugin_have_update( $slug ) ) {
2424
					// No need to display plugins if they are installed, up-to-date and active.
2425
					continue;
2426
				} else {
2427
					$plugins['all'][ $slug ] = $plugin;
2428
2429
					if ( ! $this->tgmpa->is_plugin_installed( $slug ) ) {
2430
						$plugins['install'][ $slug ] = $plugin;
2431
					} else {
2432
						if ( false !== $this->tgmpa->does_plugin_have_update( $slug ) ) {
2433
							$plugins['update'][ $slug ] = $plugin;
2434
						}
2435
2436
						if ( $this->tgmpa->can_plugin_activate( $slug ) ) {
2437
							$plugins['activate'][ $slug ] = $plugin;
2438
						}
2439
					}
2440
				}
2441
			}
2442
2443
			return $plugins;
2444
		}
2445
2446
		/**
2447
		 * Set the counts for the view links.
2448
		 *
2449
		 * @since 2.5.0
2450
		 *
2451
		 * @param array $plugins Plugins order by view.
2452
		 */
2453
		protected function set_view_totals( $plugins ) {
2454
			foreach ( $plugins as $type => $list ) {
2455
				$this->view_totals[ $type ] = count( $list );
2456
			}
2457
		}
2458
2459
		/**
2460
		 * Get the plugin required/recommended text string.
2461
		 *
2462
		 * @since 2.5.0
2463
		 *
2464
		 * @param string $required Plugin required setting.
2465
		 * @return string
2466
		 */
2467
		protected function get_plugin_advise_type_text( $required ) {
2468
			if ( true === $required ) {
2469
				return __( 'Required', 'tgmpa' );
2470
			}
2471
2472
			return __( 'Recommended', 'tgmpa' );
2473
		}
2474
2475
		/**
2476
		 * Get the plugin source type text string.
2477
		 *
2478
		 * @since 2.5.0
2479
		 *
2480
		 * @param string $type Plugin type.
2481
		 * @return string
2482
		 */
2483
		protected function get_plugin_source_type_text( $type ) {
2484
			$string = '';
2485
2486
			switch ( $type ) {
2487
				case 'repo':
2488
					$string = __( 'WordPress Repository', 'tgmpa' );
2489
					break;
2490
				case 'external':
2491
					$string = __( 'External Source', 'tgmpa' );
2492
					break;
2493
				case 'bundled':
2494
					$string = __( 'Pre-Packaged', 'tgmpa' );
2495
					break;
2496
			}
2497
2498
			return $string;
2499
		}
2500
2501
		/**
2502
		 * Determine the plugin status message.
2503
		 *
2504
		 * @since 2.5.0
2505
		 *
2506
		 * @param string $slug Plugin slug.
2507
		 * @return string
2508
		 */
2509
		protected function get_plugin_status_text( $slug ) {
2510
			if ( ! $this->tgmpa->is_plugin_installed( $slug ) ) {
2511
				return __( 'Not Installed', 'tgmpa' );
2512
			}
2513
2514
			if ( ! $this->tgmpa->is_plugin_active( $slug ) ) {
2515
				$install_status = __( 'Installed But Not Activated', 'tgmpa' );
2516
			} else {
2517
				$install_status = __( 'Active', 'tgmpa' );
2518
			}
2519
2520
			$update_status = '';
2521
2522
			if ( $this->tgmpa->does_plugin_require_update( $slug ) && false === $this->tgmpa->does_plugin_have_update( $slug ) ) {
2523
				$update_status = __( 'Required Update not Available', 'tgmpa' );
2524
2525
			} elseif ( $this->tgmpa->does_plugin_require_update( $slug ) ) {
2526
				$update_status = __( 'Requires Update', 'tgmpa' );
2527
2528
			} elseif ( false !== $this->tgmpa->does_plugin_have_update( $slug ) ) {
2529
				$update_status = __( 'Update recommended', 'tgmpa' );
2530
			}
2531
2532
			if ( '' === $update_status ) {
2533
				return $install_status;
2534
			}
2535
2536
			return sprintf(
2537
				/* translators: 1: install status, 2: update status */
2538
				_x( '%1$s, %2$s', 'Install/Update Status', 'tgmpa' ),
2539
				$install_status,
2540
				$update_status
2541
			);
2542
		}
2543
2544
		/**
2545
		 * Sort plugins by Required/Recommended type and by alphabetical plugin name within each type.
2546
		 *
2547
		 * @since 2.5.0
2548
		 *
2549
		 * @param array $items Prepared table items.
2550
		 * @return array Sorted table items.
2551
		 */
2552
		public function sort_table_items( $items ) {
2553
			$type = array();
2554
			$name = array();
2555
2556
			foreach ( $items as $i => $plugin ) {
2557
				$type[ $i ] = $plugin['type']; // Required / recommended.
2558
				$name[ $i ] = $plugin['sanitized_plugin'];
2559
			}
2560
2561
			array_multisort( $type, SORT_DESC, $name, SORT_ASC, $items );
2562
2563
			return $items;
2564
		}
2565
2566
		/**
2567
		 * Get an associative array ( id => link ) of the views available on this table.
2568
		 *
2569
		 * @since 2.5.0
2570
		 *
2571
		 * @return array
2572
		 */
2573
		public function get_views() {
2574
			$status_links = array();
2575
2576
			foreach ( $this->view_totals as $type => $count ) {
2577
				if ( $count < 1 ) {
2578
					continue;
2579
				}
2580
2581
				switch ( $type ) {
2582
					case 'all':
2583
						/* translators: 1: number of plugins. */
2584
						$text = _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $count, 'plugins', 'tgmpa' );
2585
						break;
2586
					case 'install':
2587
						/* translators: 1: number of plugins. */
2588
						$text = _n( 'To Install <span class="count">(%s)</span>', 'To Install <span class="count">(%s)</span>', $count, 'tgmpa' );
2589
						break;
2590
					case 'update':
2591
						/* translators: 1: number of plugins. */
2592
						$text = _n( 'Update Available <span class="count">(%s)</span>', 'Update Available <span class="count">(%s)</span>', $count, 'tgmpa' );
2593
						break;
2594
					case 'activate':
2595
						/* translators: 1: number of plugins. */
2596
						$text = _n( 'To Activate <span class="count">(%s)</span>', 'To Activate <span class="count">(%s)</span>', $count, 'tgmpa' );
2597
						break;
2598
					default:
2599
						$text = '';
2600
						break;
2601
				}
2602
2603
				if ( ! empty( $text ) ) {
2604
2605
					$status_links[ $type ] = sprintf(
2606
						'<a href="%s"%s>%s</a>',
2607
						esc_url( $this->tgmpa->get_tgmpa_status_url( $type ) ),
2608
						( $type === $this->view_context ) ? ' class="current"' : '',
2609
						sprintf( $text, number_format_i18n( $count ) )
2610
					);
2611
				}
2612
			}
2613
2614
			return $status_links;
2615
		}
2616
2617
		/**
2618
		 * Create default columns to display important plugin information
2619
		 * like type, action and status.
2620
		 *
2621
		 * @since 2.2.0
2622
		 *
2623
		 * @param array  $item        Array of item data.
2624
		 * @param string $column_name The name of the column.
2625
		 * @return string
2626
		 */
2627
		public function column_default( $item, $column_name ) {
2628
			return $item[ $column_name ];
2629
		}
2630
2631
		/**
2632
		 * Required for bulk installing.
2633
		 *
2634
		 * Adds a checkbox for each plugin.
2635
		 *
2636
		 * @since 2.2.0
2637
		 *
2638
		 * @param array $item Array of item data.
2639
		 * @return string The input checkbox with all necessary info.
2640
		 */
2641
		public function column_cb( $item ) {
2642
			return sprintf(
2643
				'<input type="checkbox" name="%1$s[]" value="%2$s" id="%3$s" />',
2644
				esc_attr( $this->_args['singular'] ),
2645
				esc_attr( $item['slug'] ),
2646
				esc_attr( $item['sanitized_plugin'] )
2647
			);
2648
		}
2649
2650
		/**
2651
		 * Create default title column along with the action links.
2652
		 *
2653
		 * @since 2.2.0
2654
		 *
2655
		 * @param array $item Array of item data.
2656
		 * @return string The plugin name and action links.
2657
		 */
2658
		public function column_plugin( $item ) {
2659
			return sprintf(
2660
				'%1$s %2$s',
2661
				$item['plugin'],
2662
				$this->row_actions( $this->get_row_actions( $item ), true )
2663
			);
2664
		}
2665
2666
		/**
2667
		 * Create version information column.
2668
		 *
2669
		 * @since 2.5.0
2670
		 *
2671
		 * @param array $item Array of item data.
2672
		 * @return string HTML-formatted version information.
2673
		 */
2674
		public function column_version( $item ) {
2675
			$output = array();
2676
2677
			if ( $this->tgmpa->is_plugin_installed( $item['slug'] ) ) {
2678
				$installed = ! empty( $item['installed_version'] ) ? $item['installed_version'] : _x( 'unknown', 'as in: "version nr unknown"', 'tgmpa' );
2679
2680
				$color = '';
2681
				if ( ! empty( $item['minimum_version'] ) && $this->tgmpa->does_plugin_require_update( $item['slug'] ) ) {
2682
					$color = ' color: #ff0000; font-weight: bold;';
2683
				}
2684
2685
				$output[] = sprintf(
2686
					'<p><span style="min-width: 32px; text-align: right; float: right;%1$s">%2$s</span>' . __( 'Installed version:', 'tgmpa' ) . '</p>',
2687
					$color,
2688
					$installed
2689
				);
2690
			}
2691
2692
			if ( ! empty( $item['minimum_version'] ) ) {
2693
				$output[] = sprintf(
2694
					'<p><span style="min-width: 32px; text-align: right; float: right;">%1$s</span>' . __( 'Minimum required version:', 'tgmpa' ) . '</p>',
2695
					$item['minimum_version']
2696
				);
2697
			}
2698
2699
			if ( ! empty( $item['available_version'] ) ) {
2700
				$color = '';
2701
				if ( ! empty( $item['minimum_version'] ) && version_compare( $item['available_version'], $item['minimum_version'], '>=' ) ) {
2702
					$color = ' color: #71C671; font-weight: bold;';
2703
				}
2704
2705
				$output[] = sprintf(
2706
					'<p><span style="min-width: 32px; text-align: right; float: right;%1$s">%2$s</span>' . __( 'Available version:', 'tgmpa' ) . '</p>',
2707
					$color,
2708
					$item['available_version']
2709
				);
2710
			}
2711
2712
			if ( empty( $output ) ) {
2713
				return '&nbsp;'; // Let's not break the table layout.
2714
			} else {
2715
				return implode( "\n", $output );
2716
			}
2717
		}
2718
2719
		/**
2720
		 * Sets default message within the plugins table if no plugins
2721
		 * are left for interaction.
2722
		 *
2723
		 * Hides the menu item to prevent the user from clicking and
2724
		 * getting a permissions error.
2725
		 *
2726
		 * @since 2.2.0
2727
		 */
2728
		public function no_items() {
2729
			echo esc_html__( 'No plugins to install, update or activate.', 'tgmpa' ) . ' <a href="' . esc_url( self_admin_url() ) . '"> ' . esc_html__( 'Return to the Dashboard', 'tgmpa' ) . '</a>';
2730
			echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>';
2731
		}
2732
2733
		/**
2734
		 * Output all the column information within the table.
2735
		 *
2736
		 * @since 2.2.0
2737
		 *
2738
		 * @return array $columns The column names.
2739
		 */
2740
		public function get_columns() {
2741
			$columns = array(
2742
				'cb'     => '<input type="checkbox" />',
2743
				'plugin' => __( 'Plugin', 'tgmpa' ),
2744
				'source' => __( 'Source', 'tgmpa' ),
2745
				'type'   => __( 'Type', 'tgmpa' ),
2746
			);
2747
2748
			if ( 'all' === $this->view_context || 'update' === $this->view_context ) {
2749
				$columns['version'] = __( 'Version', 'tgmpa' );
2750
				$columns['status']  = __( 'Status', 'tgmpa' );
2751
			}
2752
2753
			return apply_filters( 'tgmpa_table_columns', $columns );
2754
		}
2755
2756
		/**
2757
		 * Get name of default primary column
2758
		 *
2759
		 * @since 2.5.0 / WP 4.3+ compatibility
2760
		 * @access protected
2761
		 *
2762
		 * @return string
2763
		 */
2764
		protected function get_default_primary_column_name() {
2765
			return 'plugin';
2766
		}
2767
2768
		/**
2769
		 * Get the name of the primary column.
2770
		 *
2771
		 * @since 2.5.0 / WP 4.3+ compatibility
2772
		 * @access protected
2773
		 *
2774
		 * @return string The name of the primary column.
2775
		 */
2776
		protected function get_primary_column_name() {
2777
			if ( method_exists( 'WP_List_Table', 'get_primary_column_name' ) ) {
2778
				return parent::get_primary_column_name();
2779
			} else {
2780
				return $this->get_default_primary_column_name();
2781
			}
2782
		}
2783
2784
		/**
2785
		 * Get the actions which are relevant for a specific plugin row.
2786
		 *
2787
		 * @since 2.5.0
2788
		 *
2789
		 * @param array $item Array of item data.
2790
		 * @return array Array with relevant action links.
2791
		 */
2792
		protected function get_row_actions( $item ) {
2793
			$actions      = array();
2794
			$action_links = array();
2795
2796
			// Display the 'Install' action link if the plugin is not yet available.
2797
			if ( ! $this->tgmpa->is_plugin_installed( $item['slug'] ) ) {
2798
				/* translators: %s: plugin name in screen reader markup */
2799
				$actions['install'] = __( 'Install %s', 'tgmpa' );
2800
			} else {
2801
				// Display the 'Update' action link if an update is available and WP complies with plugin minimum.
2802
				if ( false !== $this->tgmpa->does_plugin_have_update( $item['slug'] ) && $this->tgmpa->can_plugin_update( $item['slug'] ) ) {
2803
					/* translators: %s: plugin name in screen reader markup */
2804
					$actions['update'] = __( 'Update %s', 'tgmpa' );
2805
				}
2806
2807
				// Display the 'Activate' action link, but only if the plugin meets the minimum version.
2808
				if ( $this->tgmpa->can_plugin_activate( $item['slug'] ) ) {
2809
					/* translators: %s: plugin name in screen reader markup */
2810
					$actions['activate'] = __( 'Activate %s', 'tgmpa' );
2811
				}
2812
			}
2813
2814
			// Create the actual links.
2815
			foreach ( $actions as $action => $text ) {
2816
				$nonce_url = wp_nonce_url(
2817
					add_query_arg(
2818
						array(
2819
							'plugin'           => urlencode( $item['slug'] ),
2820
							'tgmpa-' . $action => $action . '-plugin',
2821
						),
2822
						$this->tgmpa->get_tgmpa_url()
2823
					),
2824
					'tgmpa-' . $action,
2825
					'tgmpa-nonce'
2826
				);
2827
2828
				$action_links[ $action ] = sprintf(
2829
					'<a href="%1$s">' . esc_html( $text ) . '</a>',
2830
					esc_url( $nonce_url ),
2831
					'<span class="screen-reader-text">' . esc_html( $item['sanitized_plugin'] ) . '</span>'
2832
				);
2833
			}
2834
2835
			$prefix = ( defined( 'WP_NETWORK_ADMIN' ) && WP_NETWORK_ADMIN ) ? 'network_admin_' : '';
2836
			return apply_filters( "tgmpa_{$prefix}plugin_action_links", array_filter( $action_links ), $item['slug'], $item, $this->view_context );
2837
		}
2838
2839
		/**
2840
		 * Generates content for a single row of the table.
2841
		 *
2842
		 * @since 2.5.0
2843
		 *
2844
		 * @param object $item The current item.
2845
		 */
2846
		public function single_row( $item ) {
2847
			parent::single_row( $item );
2848
2849
			/**
2850
			 * Fires after each specific row in the TGMPA Plugins list table.
2851
			 *
2852
			 * The dynamic portion of the hook name, `$item['slug']`, refers to the slug
2853
			 * for the plugin.
2854
			 *
2855
			 * @since 2.5.0
2856
			 */
2857
			do_action( "tgmpa_after_plugin_row_{$item['slug']}", $item['slug'], $item, $this->view_context );
2858
		}
2859
2860
		/**
2861
		 * Show the upgrade notice below a plugin row if there is one.
2862
		 *
2863
		 * @since 2.5.0
2864
		 *
2865
		 * @see /wp-admin/includes/update.php
2866
		 *
2867
		 * @param string $slug Plugin slug.
2868
		 * @param array  $item The information available in this table row.
2869
		 * @return null Return early if upgrade notice is empty.
2870
		 */
2871
		public function wp_plugin_update_row( $slug, $item ) {
2872
			if ( empty( $item['upgrade_notice'] ) ) {
2873
				return;
2874
			}
2875
2876
			echo '
2877
				<tr class="plugin-update-tr">
2878
					<td colspan="', absint( $this->get_column_count() ), '" class="plugin-update colspanchange">
2879
						<div class="update-message">',
2880
							esc_html__( 'Upgrade message from the plugin author:', 'tgmpa' ),
2881
							' <strong>', wp_kses_data( $item['upgrade_notice'] ), '</strong>
2882
						</div>
2883
					</td>
2884
				</tr>';
2885
		}
2886
2887
		/**
2888
		 * Extra controls to be displayed between bulk actions and pagination.
2889
		 *
2890
		 * @since 2.5.0
2891
		 *
2892
		 * @param string $which 'top' or 'bottom' table navigation.
2893
		 */
2894
		public function extra_tablenav( $which ) {
2895
			if ( 'bottom' === $which ) {
2896
				$this->tgmpa->show_tgmpa_version();
2897
			}
2898
		}
2899
2900
		/**
2901
		 * Defines the bulk actions for handling registered plugins.
2902
		 *
2903
		 * @since 2.2.0
2904
		 *
2905
		 * @return array $actions The bulk actions for the plugin install table.
2906
		 */
2907
		public function get_bulk_actions() {
2908
2909
			$actions = array();
2910
2911
			if ( 'update' !== $this->view_context && 'activate' !== $this->view_context ) {
2912
				if ( current_user_can( 'install_plugins' ) ) {
2913
					$actions['tgmpa-bulk-install'] = __( 'Install', 'tgmpa' );
2914
				}
2915
			}
2916
2917
			if ( 'install' !== $this->view_context ) {
2918
				if ( current_user_can( 'update_plugins' ) ) {
2919
					$actions['tgmpa-bulk-update'] = __( 'Update', 'tgmpa' );
2920
				}
2921
				if ( current_user_can( 'activate_plugins' ) ) {
2922
					$actions['tgmpa-bulk-activate'] = __( 'Activate', 'tgmpa' );
2923
				}
2924
			}
2925
2926
			return $actions;
2927
		}
2928
2929
		/**
2930
		 * Processes bulk installation and activation actions.
2931
		 *
2932
		 * The bulk installation process looks for the $_POST information and passes that
2933
		 * through if a user has to use WP_Filesystem to enter their credentials.
2934
		 *
2935
		 * @since 2.2.0
2936
		 */
2937
		public function process_bulk_actions() {
2938
			// Bulk installation process.
2939
			if ( 'tgmpa-bulk-install' === $this->current_action() || 'tgmpa-bulk-update' === $this->current_action() ) {
2940
2941
				check_admin_referer( 'bulk-' . $this->_args['plural'] );
2942
2943
				$install_type = 'install';
2944
				if ( 'tgmpa-bulk-update' === $this->current_action() ) {
2945
					$install_type = 'update';
2946
				}
2947
2948
				$plugins_to_install = array();
2949
2950
				// Did user actually select any plugins to install/update ?
2951 View Code Duplication
				if ( empty( $_POST['plugin'] ) ) {
2952
					if ( 'install' === $install_type ) {
2953
						$message = __( 'No plugins were selected to be installed. No action taken.', 'tgmpa' );
2954
					} else {
2955
						$message = __( 'No plugins were selected to be updated. No action taken.', 'tgmpa' );
2956
					}
2957
2958
					echo '<div id="message" class="error"><p>', esc_html( $message ), '</p></div>';
2959
2960
					return false;
2961
				}
2962
2963
				if ( is_array( $_POST['plugin'] ) ) {
2964
					$plugins_to_install = (array) $_POST['plugin'];
2965
				} elseif ( is_string( $_POST['plugin'] ) ) {
2966
					// Received via Filesystem page - un-flatten array (WP bug #19643).
2967
					$plugins_to_install = explode( ',', $_POST['plugin'] );
2968
				}
2969
2970
				// Sanitize the received input.
2971
				$plugins_to_install = array_map( 'urldecode', $plugins_to_install );
2972
				$plugins_to_install = array_map( array( $this->tgmpa, 'sanitize_key' ), $plugins_to_install );
2973
2974
				// Validate the received input.
2975
				foreach ( $plugins_to_install as $key => $slug ) {
2976
					// Check if the plugin was registered with TGMPA and remove if not.
2977
					if ( ! isset( $this->tgmpa->plugins[ $slug ] ) ) {
2978
						unset( $plugins_to_install[ $key ] );
2979
						continue;
2980
					}
2981
2982
					// For install: make sure this is a plugin we *can* install and not one already installed.
2983
					if ( 'install' === $install_type && true === $this->tgmpa->is_plugin_installed( $slug ) ) {
2984
						unset( $plugins_to_install[ $key ] );
2985
					}
2986
2987
					// For updates: make sure this is a plugin we *can* update (update available and WP version ok).
2988
					if ( 'update' === $install_type && false === $this->tgmpa->is_plugin_updatetable( $slug ) ) {
2989
						unset( $plugins_to_install[ $key ] );
2990
					}
2991
				}
2992
2993
				// No need to proceed further if we have no plugins to handle.
2994 View Code Duplication
				if ( empty( $plugins_to_install ) ) {
2995
					if ( 'install' === $install_type ) {
2996
						$message = __( 'No plugins are available to be installed at this time.', 'tgmpa' );
2997
					} else {
2998
						$message = __( 'No plugins are available to be updated at this time.', 'tgmpa' );
2999
					}
3000
3001
					echo '<div id="message" class="error"><p>', esc_html( $message ), '</p></div>';
3002
3003
					return false;
3004
				}
3005
3006
				// Pass all necessary information if WP_Filesystem is needed.
3007
				$url = wp_nonce_url(
3008
					$this->tgmpa->get_tgmpa_url(),
3009
					'bulk-' . $this->_args['plural']
3010
				);
3011
3012
				// Give validated data back to $_POST which is the only place the filesystem looks for extra fields.
3013
				$_POST['plugin'] = implode( ',', $plugins_to_install ); // Work around for WP bug #19643.
3014
3015
				$method = ''; // Leave blank so WP_Filesystem can populate it as necessary.
3016
				$fields = array_keys( $_POST ); // Extra fields to pass to WP_Filesystem.
3017
3018
				if ( false === ( $creds = request_filesystem_credentials( esc_url_raw( $url ), $method, false, false, $fields ) ) ) {
3019
					return true; // Stop the normal page form from displaying, credential request form will be shown.
3020
				}
3021
3022
				// Now we have some credentials, setup WP_Filesystem.
3023
				if ( ! WP_Filesystem( $creds ) ) {
0 ignored issues
show
Duplication introduced by
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...
3024
					// Our credentials were no good, ask the user for them again.
3025
					request_filesystem_credentials( esc_url_raw( $url ), $method, true, false, $fields );
3026
3027
					return true;
3028
				}
3029
3030
				/* If we arrive here, we have the filesystem */
3031
3032
				// Store all information in arrays since we are processing a bulk installation.
3033
				$names      = array();
3034
				$sources    = array(); // Needed for installs.
3035
				$file_paths = array(); // Needed for upgrades.
3036
				$to_inject  = array(); // Information to inject into the update_plugins transient.
3037
3038
				// Prepare the data for validated plugins for the install/upgrade.
3039
				foreach ( $plugins_to_install as $slug ) {
3040
					$name   = $this->tgmpa->plugins[ $slug ]['name'];
3041
					$source = $this->tgmpa->get_download_url( $slug );
3042
3043
					if ( ! empty( $name ) && ! empty( $source ) ) {
3044
						$names[] = $name;
3045
3046
						switch ( $install_type ) {
3047
3048
							case 'install':
3049
								$sources[] = $source;
3050
								break;
3051
3052
							case 'update':
3053
								$file_paths[]                 = $this->tgmpa->plugins[ $slug ]['file_path'];
3054
								$to_inject[ $slug ]           = $this->tgmpa->plugins[ $slug ];
3055
								$to_inject[ $slug ]['source'] = $source;
3056
								break;
3057
						}
3058
					}
3059
				}
3060
				unset( $slug, $name, $source );
3061
3062
				// Create a new instance of TGMPA_Bulk_Installer.
3063
				$installer = new TGMPA_Bulk_Installer(
3064
					new TGMPA_Bulk_Installer_Skin(
3065
						array(
3066
							'url'          => esc_url_raw( $this->tgmpa->get_tgmpa_url() ),
3067
							'nonce'        => 'bulk-' . $this->_args['plural'],
3068
							'names'        => $names,
3069
							'install_type' => $install_type,
3070
						)
3071
					)
3072
				);
3073
3074
				// Wrap the install process with the appropriate HTML.
3075
				echo '<div class="tgmpa">',
3076
					'<h2 style="font-size: 23px; font-weight: 400; line-height: 29px; margin: 0; padding: 9px 15px 4px 0;">', esc_html( get_admin_page_title() ), '</h2>
3077
					<div class="update-php" style="width: 100%; height: 98%; min-height: 850px; padding-top: 1px;">';
3078
3079
				// Process the bulk installation submissions.
3080
				add_filter( 'upgrader_source_selection', array( $this->tgmpa, 'maybe_adjust_source_dir' ), 1, 3 );
3081
3082
				if ( 'tgmpa-bulk-update' === $this->current_action() ) {
3083
					// Inject our info into the update transient.
3084
					$this->tgmpa->inject_update_info( $to_inject );
3085
3086
					$installer->bulk_upgrade( $file_paths );
3087
				} else {
3088
					$installer->bulk_install( $sources );
3089
				}
3090
3091
				remove_filter( 'upgrader_source_selection', array( $this->tgmpa, 'maybe_adjust_source_dir' ), 1 );
3092
3093
				echo '</div></div>';
3094
3095
				return true;
3096
			}
3097
3098
			// Bulk activation process.
3099
			if ( 'tgmpa-bulk-activate' === $this->current_action() ) {
3100
				check_admin_referer( 'bulk-' . $this->_args['plural'] );
3101
3102
				// Did user actually select any plugins to activate ?
3103
				if ( empty( $_POST['plugin'] ) ) {
3104
					echo '<div id="message" class="error"><p>', esc_html__( 'No plugins were selected to be activated. No action taken.', 'tgmpa' ), '</p></div>';
3105
3106
					return false;
3107
				}
3108
3109
				// Grab plugin data from $_POST.
3110
				$plugins = array();
3111
				if ( isset( $_POST['plugin'] ) ) {
3112
					$plugins = array_map( 'urldecode', (array) $_POST['plugin'] );
3113
					$plugins = array_map( array( $this->tgmpa, 'sanitize_key' ), $plugins );
3114
				}
3115
3116
				$plugins_to_activate = array();
3117
				$plugin_names        = array();
3118
3119
				// Grab the file paths for the selected & inactive plugins from the registration array.
3120
				foreach ( $plugins as $slug ) {
3121
					if ( $this->tgmpa->can_plugin_activate( $slug ) ) {
3122
						$plugins_to_activate[] = $this->tgmpa->plugins[ $slug ]['file_path'];
3123
						$plugin_names[]        = $this->tgmpa->plugins[ $slug ]['name'];
3124
					}
3125
				}
3126
				unset( $slug );
3127
3128
				// Return early if there are no plugins to activate.
3129
				if ( empty( $plugins_to_activate ) ) {
3130
					echo '<div id="message" class="error"><p>', esc_html__( 'No plugins are available to be activated at this time.', 'tgmpa' ), '</p></div>';
3131
3132
					return false;
3133
				}
3134
3135
				// Now we are good to go - let's start activating plugins.
3136
				$activate = activate_plugins( $plugins_to_activate );
3137
3138
				if ( is_wp_error( $activate ) ) {
3139
					echo '<div id="message" class="error"><p>', wp_kses_post( $activate->get_error_message() ), '</p></div>';
3140
				} else {
3141
					$count        = count( $plugin_names ); // Count so we can use _n function.
3142
					$plugin_names = array_map( array( 'TGMPA_Utils', 'wrap_in_strong' ), $plugin_names );
3143
					$last_plugin  = array_pop( $plugin_names ); // Pop off last name to prep for readability.
3144
					$imploded     = empty( $plugin_names ) ? $last_plugin : ( implode( ', ', $plugin_names ) . ' ' . esc_html_x( 'and', 'plugin A *and* plugin B', 'tgmpa' ) . ' ' . $last_plugin );
3145
3146
					printf( // WPCS: xss ok.
3147
						'<div id="message" class="updated"><p>%1$s %2$s.</p></div>',
3148
						esc_html( _n( 'The following plugin was activated successfully:', 'The following plugins were activated successfully:', $count, 'tgmpa' ) ),
3149
						$imploded
3150
					);
3151
3152
					// Update recently activated plugins option.
3153
					$recent = (array) get_option( 'recently_activated' );
3154
					foreach ( $plugins_to_activate as $plugin => $time ) {
3155
						if ( isset( $recent[ $plugin ] ) ) {
3156
							unset( $recent[ $plugin ] );
3157
						}
3158
					}
3159
					update_option( 'recently_activated', $recent );
3160
				}
3161
3162
				unset( $_POST ); // Reset the $_POST variable in case user wants to perform one action after another.
3163
3164
				return true;
3165
			}
3166
3167
			return false;
3168
		}
3169
3170
		/**
3171
		 * Prepares all of our information to be outputted into a usable table.
3172
		 *
3173
		 * @since 2.2.0
3174
		 */
3175
		public function prepare_items() {
3176
			$columns               = $this->get_columns(); // Get all necessary column information.
3177
			$hidden                = array(); // No columns to hide, but we must set as an array.
3178
			$sortable              = array(); // No reason to make sortable columns.
3179
			$primary               = $this->get_primary_column_name(); // Column which has the row actions.
3180
			$this->_column_headers = array( $columns, $hidden, $sortable, $primary ); // Get all necessary column headers.
3181
3182
			// Process our bulk activations here.
3183
			if ( 'tgmpa-bulk-activate' === $this->current_action() ) {
3184
				$this->process_bulk_actions();
3185
			}
3186
3187
			// Store all of our plugin data into $items array so WP_List_Table can use it.
3188
			$this->items = apply_filters( 'tgmpa_table_data_items', $this->_gather_plugin_data() );
3189
		}
3190
3191
		/* *********** DEPRECATED METHODS *********** */
3192
3193
		/**
3194
		 * Retrieve plugin data, given the plugin name.
3195
		 *
3196
		 * @since      2.2.0
3197
		 * @deprecated 2.5.0 use {@see TGM_Plugin_Activation::_get_plugin_data_from_name()} instead.
3198
		 * @see        TGM_Plugin_Activation::_get_plugin_data_from_name()
3199
		 *
3200
		 * @param string $name Name of the plugin, as it was registered.
3201
		 * @param string $data Optional. Array key of plugin data to return. Default is slug.
3202
		 * @return string|boolean Plugin slug if found, false otherwise.
3203
		 */
3204
		protected function _get_plugin_data_from_name( $name, $data = 'slug' ) {
3205
			_deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'TGM_Plugin_Activation::_get_plugin_data_from_name()' );
3206
3207
			return $this->tgmpa->_get_plugin_data_from_name( $name, $data );
3208
		}
3209
	}
3210
}
3211
3212
3213
if ( ! class_exists( 'TGM_Bulk_Installer' ) ) {
3214
3215
	/**
3216
	 * Hack: Prevent TGMPA v2.4.1- bulk installer class from being loaded if 2.4.1- is loaded after 2.5+.
3217
	 *
3218
	 * @since 2.5.2
3219
	 *
3220
	 * {@internal The TGMPA_Bulk_Installer class was originally called TGM_Bulk_Installer.
3221
	 *            For more information, see that class.}}
3222
	 */
3223
	class TGM_Bulk_Installer {
3224
	}
3225
}
3226
if ( ! class_exists( 'TGM_Bulk_Installer_Skin' ) ) {
3227
3228
	/**
3229
	 * Hack: Prevent TGMPA v2.4.1- bulk installer skin class from being loaded if 2.4.1- is loaded after 2.5+.
3230
	 *
3231
	 * @since 2.5.2
3232
	 *
3233
	 * {@internal The TGMPA_Bulk_Installer_Skin class was originally called TGM_Bulk_Installer_Skin.
3234
	 *            For more information, see that class.}}
3235
	 */
3236
	class TGM_Bulk_Installer_Skin {
3237
	}
3238
}
3239
3240
/**
3241
 * The WP_Upgrader file isn't always available. If it isn't available,
3242
 * we load it here.
3243
 *
3244
 * We check to make sure no action or activation keys are set so that WordPress
3245
 * does not try to re-include the class when processing upgrades or installs outside
3246
 * of the class.
3247
 *
3248
 * @since 2.2.0
3249
 */
3250
add_action( 'admin_init', 'tgmpa_load_bulk_installer' );
3251
if ( ! function_exists( 'tgmpa_load_bulk_installer' ) ) {
3252
	/**
3253
	 * Load bulk installer
3254
	 */
3255
	function tgmpa_load_bulk_installer() {
3256
		// Silently fail if 2.5+ is loaded *after* an older version.
3257
		if ( ! isset( $GLOBALS['tgmpa'] ) ) {
3258
			return;
3259
		}
3260
3261
		// Get TGMPA class instance.
3262
		$tgmpa_instance = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
3263
3264
		if ( isset( $_GET['page'] ) && $tgmpa_instance->menu === $_GET['page'] ) {
3265
			if ( ! class_exists( 'Plugin_Upgrader', false ) ) {
3266
				require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
3267
			}
3268
3269
			if ( ! class_exists( 'TGMPA_Bulk_Installer' ) ) {
3270
3271
				/**
3272
				 * Installer class to handle bulk plugin installations.
3273
				 *
3274
				 * Extends WP_Upgrader and customizes to suit the installation of multiple
3275
				 * plugins.
3276
				 *
3277
				 * @since 2.2.0
3278
				 *
3279
				 * {@internal Since 2.5.0 the class is an extension of Plugin_Upgrader rather than WP_Upgrader.}}
3280
				 * {@internal Since 2.5.2 the class has been renamed from TGM_Bulk_Installer to TGMPA_Bulk_Installer.
3281
				 *            This was done to prevent backward compatibility issues with v2.3.6.}}
3282
				 *
3283
				 * @package TGM-Plugin-Activation
3284
				 * @author  Thomas Griffin
3285
				 * @author  Gary Jones
3286
				 */
3287
				class TGMPA_Bulk_Installer extends Plugin_Upgrader {
3288
					/**
3289
					 * Holds result of bulk plugin installation.
3290
					 *
3291
					 * @since 2.2.0
3292
					 *
3293
					 * @var string
3294
					 */
3295
					public $result;
3296
3297
					/**
3298
					 * Flag to check if bulk installation is occurring or not.
3299
					 *
3300
					 * @since 2.2.0
3301
					 *
3302
					 * @var boolean
3303
					 */
3304
					public $bulk = false;
3305
3306
					/**
3307
					 * TGMPA instance
3308
					 *
3309
					 * @since 2.5.0
3310
					 *
3311
					 * @var object
3312
					 */
3313
					protected $tgmpa;
3314
3315
					/**
3316
					 * Whether or not the destination directory needs to be cleared ( = on update).
3317
					 *
3318
					 * @since 2.5.0
3319
					 *
3320
					 * @var bool
3321
					 */
3322
					protected $clear_destination = false;
3323
3324
					/**
3325
					 * References parent constructor and sets defaults for class.
3326
					 *
3327
					 * @since 2.2.0
3328
					 *
3329
					 * @param \Bulk_Upgrader_Skin|null $skin Installer skin.
3330
					 */
3331
					public function __construct( $skin = null ) {
3332
						// Get TGMPA class instance.
3333
						$this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
3334
3335
						parent::__construct( $skin );
3336
3337
						if ( isset( $this->skin->options['install_type'] ) && 'update' === $this->skin->options['install_type'] ) {
3338
							$this->clear_destination = true;
3339
						}
3340
3341
						if ( $this->tgmpa->is_automatic ) {
3342
							$this->activate_strings();
3343
						}
3344
3345
						add_action( 'upgrader_process_complete', array( $this->tgmpa, 'populate_file_path' ) );
3346
					}
3347
3348
					/**
3349
					 * Sets the correct activation strings for the installer skin to use.
3350
					 *
3351
					 * @since 2.2.0
3352
					 */
3353
					public function activate_strings() {
3354
						$this->strings['activation_failed']  = __( 'Plugin activation failed.', 'tgmpa' );
3355
						$this->strings['activation_success'] = __( 'Plugin activated successfully.', 'tgmpa' );
3356
					}
3357
3358
					/**
3359
					 * Performs the actual installation of each plugin.
3360
					 *
3361
					 * @since 2.2.0
3362
					 *
3363
					 * @see WP_Upgrader::run()
3364
					 *
3365
					 * @param array $options The installation config options.
3366
					 * @return null|array Return early if error, array of installation data on success.
3367
					 */
3368
					public function run( $options ) {
3369
						$result = parent::run( $options );
3370
3371
						// Reset the strings in case we changed one during automatic activation.
3372
						if ( $this->tgmpa->is_automatic ) {
3373
							if ( 'update' === $this->skin->options['install_type'] ) {
3374
								$this->upgrade_strings();
3375
							} else {
3376
								$this->install_strings();
3377
							}
3378
						}
3379
3380
						return $result;
3381
					}
3382
3383
					/**
3384
					 * Processes the bulk installation of plugins.
3385
					 *
3386
					 * @since 2.2.0
3387
					 *
3388
					 * {@internal This is basically a near identical copy of the WP Core
3389
					 * Plugin_Upgrader::bulk_upgrade() method, with minor adjustments to deal with
3390
					 * new installs instead of upgrades.
3391
					 * For ease of future synchronizations, the adjustments are clearly commented, but no other
3392
					 * comments are added. Code style has been made to comply.}}
3393
					 *
3394
					 * @see Plugin_Upgrader::bulk_upgrade()
3395
					 * @see https://core.trac.wordpress.org/browser/tags/4.2.1/src/wp-admin/includes/class-wp-upgrader.php#L838
3396
					 * (@internal Last synced: Dec 31st 2015 against https://core.trac.wordpress.org/browser/trunk?rev=36134}}
3397
					 *
3398
					 * @param array $plugins The plugin sources needed for installation.
3399
					 * @param array $args    Arbitrary passed extra arguments.
3400
					 * @return array|false   Install confirmation messages on success, false on failure.
3401
					 */
3402
					public function bulk_install( $plugins, $args = array() ) {
3403
						// [TGMPA + ] Hook auto-activation in.
3404
						add_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3405
3406
						$defaults    = array(
3407
							'clear_update_cache' => true,
3408
						);
3409
						$parsed_args = wp_parse_args( $args, $defaults );
3410
3411
						$this->init();
3412
						$this->bulk = true;
3413
3414
						$this->install_strings(); // [TGMPA + ] adjusted.
3415
3416
						/* [TGMPA - ] $current = get_site_transient( 'update_plugins' ); */
3417
3418
						/* [TGMPA - ] add_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'), 10, 4); */
3419
3420
						$this->skin->header();
3421
3422
						// Connect to the Filesystem first.
3423
						$res = $this->fs_connect( array( WP_CONTENT_DIR, WP_PLUGIN_DIR ) );
3424
						if ( ! $res ) {
3425
							$this->skin->footer();
3426
							return false;
3427
						}
3428
3429
						$this->skin->bulk_header();
3430
3431
						/*
3432
						 * Only start maintenance mode if:
3433
						 * - running Multisite and there are one or more plugins specified, OR
3434
						 * - a plugin with an update available is currently active.
3435
						 * @TODO: For multisite, maintenance mode should only kick in for individual sites if at all possible.
3436
						 */
3437
						$maintenance = ( is_multisite() && ! empty( $plugins ) );
3438
3439
						/*
3440
						[TGMPA - ]
3441
						foreach ( $plugins as $plugin )
3442
							$maintenance = $maintenance || ( is_plugin_active( $plugin ) && isset( $current->response[ $plugin] ) );
3443
						*/
3444
						if ( $maintenance ) {
3445
							$this->maintenance_mode( true );
3446
						}
3447
3448
						$results = array();
3449
3450
						$this->update_count   = count( $plugins );
3451
						$this->update_current = 0;
3452
						foreach ( $plugins as $plugin ) {
3453
							$this->update_current++;
3454
3455
							/*
3456
							[TGMPA - ]
3457
							$this->skin->plugin_info = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin, false, true);
3458
3459
							if ( !isset( $current->response[ $plugin ] ) ) {
3460
								$this->skin->set_result('up_to_date');
3461
								$this->skin->before();
3462
								$this->skin->feedback('up_to_date');
3463
								$this->skin->after();
3464
								$results[$plugin] = true;
3465
								continue;
3466
							}
3467
3468
							// Get the URL to the zip file.
3469
							$r = $current->response[ $plugin ];
3470
3471
							$this->skin->plugin_active = is_plugin_active($plugin);
3472
							*/
3473
3474
							$result = $this->run(
3475
								array(
3476
									'package'           => $plugin, // [TGMPA + ] adjusted.
3477
									'destination'       => WP_PLUGIN_DIR,
3478
									'clear_destination' => false, // [TGMPA + ] adjusted.
3479
									'clear_working'     => true,
3480
									'is_multi'          => true,
3481
									'hook_extra'        => array(
3482
										'plugin' => $plugin,
3483
									),
3484
								)
3485
							);
3486
3487
							$results[ $plugin ] = $this->result;
3488
3489
							// Prevent credentials auth screen from displaying multiple times.
3490
							if ( false === $result ) {
3491
								break;
3492
							}
3493
						} //end foreach $plugins
3494
3495
						$this->maintenance_mode( false );
3496
3497
						/**
3498
						 * Fires when the bulk upgrader process is complete.
3499
						 *
3500
						 * @since WP 3.6.0 / TGMPA 2.5.0
3501
						 *
3502
						 * @param Plugin_Upgrader $this Plugin_Upgrader instance. In other contexts, $this, might
3503
						 *                              be a Theme_Upgrader or Core_Upgrade instance.
3504
						 * @param array           $data {
3505
						 *     Array of bulk item update data.
3506
						 *
3507
						 *     @type string $action   Type of action. Default 'update'.
3508
						 *     @type string $type     Type of update process. Accepts 'plugin', 'theme', or 'core'.
3509
						 *     @type bool   $bulk     Whether the update process is a bulk update. Default true.
3510
						 *     @type array  $packages Array of plugin, theme, or core packages to update.
3511
						 * }
3512
						 */
3513
						do_action( 'upgrader_process_complete', $this, array(
3514
							'action'  => 'install', // [TGMPA + ] adjusted.
3515
							'type'    => 'plugin',
3516
							'bulk'    => true,
3517
							'plugins' => $plugins,
3518
						) );
3519
3520
						$this->skin->bulk_footer();
3521
3522
						$this->skin->footer();
3523
3524
						// Cleanup our hooks, in case something else does a upgrade on this connection.
3525
						/* [TGMPA - ] remove_filter('upgrader_clear_destination', array($this, 'delete_old_plugin')); */
3526
3527
						// [TGMPA + ] Remove our auto-activation hook.
3528
						remove_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3529
3530
						// Force refresh of plugin update information.
3531
						wp_clean_plugins_cache( $parsed_args['clear_update_cache'] );
3532
3533
						return $results;
3534
					}
3535
3536
					/**
3537
					 * Handle a bulk upgrade request.
3538
					 *
3539
					 * @since 2.5.0
3540
					 *
3541
					 * @see Plugin_Upgrader::bulk_upgrade()
3542
					 *
3543
					 * @param array $plugins The local WP file_path's of the plugins which should be upgraded.
3544
					 * @param array $args    Arbitrary passed extra arguments.
3545
					 * @return string|bool Install confirmation messages on success, false on failure.
3546
					 */
3547
					public function bulk_upgrade( $plugins, $args = array() ) {
3548
3549
						add_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3550
3551
						$result = parent::bulk_upgrade( $plugins, $args );
3552
3553
						remove_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3554
3555
						return $result;
3556
					}
3557
3558
					/**
3559
					 * Abuse a filter to auto-activate plugins after installation.
3560
					 *
3561
					 * Hooked into the 'upgrader_post_install' filter hook.
3562
					 *
3563
					 * @since 2.5.0
3564
					 *
3565
					 * @param bool $bool The value we need to give back (true).
3566
					 * @return bool
3567
					 */
3568
					public function auto_activate( $bool ) {
3569
						// Only process the activation of installed plugins if the automatic flag is set to true.
3570
						if ( $this->tgmpa->is_automatic ) {
3571
							// Flush plugins cache so the headers of the newly installed plugins will be read correctly.
3572
							wp_clean_plugins_cache();
3573
3574
							// Get the installed plugin file.
3575
							$plugin_info = $this->plugin_info();
3576
3577
							// Don't try to activate on upgrade of active plugin as WP will do this already.
3578
							if ( ! is_plugin_active( $plugin_info ) ) {
3579
								$activate = activate_plugin( $plugin_info );
3580
3581
								// Adjust the success string based on the activation result.
3582
								$this->strings['process_success'] = $this->strings['process_success'] . "<br />\n";
3583
3584
								if ( is_wp_error( $activate ) ) {
3585
									$this->skin->error( $activate );
3586
									$this->strings['process_success'] .= $this->strings['activation_failed'];
3587
								} else {
3588
									$this->strings['process_success'] .= $this->strings['activation_success'];
3589
								}
3590
							}
3591
						}
3592
3593
						return $bool;
3594
					}
3595
				}
3596
			}
3597
3598
			if ( ! class_exists( 'TGMPA_Bulk_Installer_Skin' ) ) {
3599
3600
				/**
3601
				 * Installer skin to set strings for the bulk plugin installations..
3602
				 *
3603
				 * Extends Bulk_Upgrader_Skin and customizes to suit the installation of multiple
3604
				 * plugins.
3605
				 *
3606
				 * @since 2.2.0
3607
				 *
3608
				 * {@internal Since 2.5.2 the class has been renamed from TGM_Bulk_Installer_Skin to
3609
				 *            TGMPA_Bulk_Installer_Skin.
3610
				 *            This was done to prevent backward compatibility issues with v2.3.6.}}
3611
				 *
3612
				 * @see https://core.trac.wordpress.org/browser/trunk/src/wp-admin/includes/class-wp-upgrader-skins.php
3613
				 *
3614
				 * @package TGM-Plugin-Activation
3615
				 * @author  Thomas Griffin
3616
				 * @author  Gary Jones
3617
				 */
3618
				class TGMPA_Bulk_Installer_Skin extends Bulk_Upgrader_Skin {
3619
					/**
3620
					 * Holds plugin info for each individual plugin installation.
3621
					 *
3622
					 * @since 2.2.0
3623
					 *
3624
					 * @var array
3625
					 */
3626
					public $plugin_info = array();
3627
3628
					/**
3629
					 * Holds names of plugins that are undergoing bulk installations.
3630
					 *
3631
					 * @since 2.2.0
3632
					 *
3633
					 * @var array
3634
					 */
3635
					public $plugin_names = array();
3636
3637
					/**
3638
					 * Integer to use for iteration through each plugin installation.
3639
					 *
3640
					 * @since 2.2.0
3641
					 *
3642
					 * @var integer
3643
					 */
3644
					public $i = 0;
3645
3646
					/**
3647
					 * TGMPA instance
3648
					 *
3649
					 * @since 2.5.0
3650
					 *
3651
					 * @var object
3652
					 */
3653
					protected $tgmpa;
3654
3655
					/**
3656
					 * Constructor. Parses default args with new ones and extracts them for use.
3657
					 *
3658
					 * @since 2.2.0
3659
					 *
3660
					 * @param array $args Arguments to pass for use within the class.
3661
					 */
3662
					public function __construct( $args = array() ) {
3663
						// Get TGMPA class instance.
3664
						$this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
3665
3666
						// Parse default and new args.
3667
						$defaults = array(
3668
							'url'          => '',
3669
							'nonce'        => '',
3670
							'names'        => array(),
3671
							'install_type' => 'install',
3672
						);
3673
						$args     = wp_parse_args( $args, $defaults );
3674
3675
						// Set plugin names to $this->plugin_names property.
3676
						$this->plugin_names = $args['names'];
3677
3678
						// Extract the new args.
3679
						parent::__construct( $args );
3680
					}
3681
3682
					/**
3683
					 * Sets install skin strings for each individual plugin.
3684
					 *
3685
					 * Checks to see if the automatic activation flag is set and uses the
3686
					 * the proper strings accordingly.
3687
					 *
3688
					 * @since 2.2.0
3689
					 */
3690
					public function add_strings() {
3691
						if ( 'update' === $this->options['install_type'] ) {
3692
							parent::add_strings();
3693
							/* translators: 1: plugin name, 2: action number 3: total number of actions. */
3694
							$this->upgrader->strings['skin_before_update_header'] = __( 'Updating Plugin %1$s (%2$d/%3$d)', 'tgmpa' );
3695
						} else {
3696
							/* translators: 1: plugin name, 2: error message. */
3697
							$this->upgrader->strings['skin_update_failed_error'] = __( 'An error occurred while installing %1$s: <strong>%2$s</strong>.', 'tgmpa' );
3698
							/* translators: 1: plugin name. */
3699
							$this->upgrader->strings['skin_update_failed'] = __( 'The installation of %1$s failed.', 'tgmpa' );
3700
3701
							if ( $this->tgmpa->is_automatic ) {
3702
								// Automatic activation strings.
3703
								$this->upgrader->strings['skin_upgrade_start'] = __( 'The installation and activation process is starting. This process may take a while on some hosts, so please be patient.', 'tgmpa' );
3704
								/* translators: 1: plugin name. */
3705
								$this->upgrader->strings['skin_update_successful'] = __( '%1$s installed and activated successfully.', 'tgmpa' ) . ' <a href="#" class="hide-if-no-js" onclick="%2$s"><span>' . esc_html__( 'Show Details', 'tgmpa' ) . '</span><span class="hidden">' . esc_html__( 'Hide Details', 'tgmpa' ) . '</span>.</a>';
3706
								$this->upgrader->strings['skin_upgrade_end']       = __( 'All installations and activations have been completed.', 'tgmpa' );
3707
								/* translators: 1: plugin name, 2: action number 3: total number of actions. */
3708
								$this->upgrader->strings['skin_before_update_header'] = __( 'Installing and Activating Plugin %1$s (%2$d/%3$d)', 'tgmpa' );
3709
							} else {
3710
								// Default installation strings.
3711
								$this->upgrader->strings['skin_upgrade_start'] = __( 'The installation process is starting. This process may take a while on some hosts, so please be patient.', 'tgmpa' );
3712
								/* translators: 1: plugin name. */
3713
								$this->upgrader->strings['skin_update_successful'] = esc_html__( '%1$s installed successfully.', 'tgmpa' ) . ' <a href="#" class="hide-if-no-js" onclick="%2$s"><span>' . esc_html__( 'Show Details', 'tgmpa' ) . '</span><span class="hidden">' . esc_html__( 'Hide Details', 'tgmpa' ) . '</span>.</a>';
3714
								$this->upgrader->strings['skin_upgrade_end']       = __( 'All installations have been completed.', 'tgmpa' );
3715
								/* translators: 1: plugin name, 2: action number 3: total number of actions. */
3716
								$this->upgrader->strings['skin_before_update_header'] = __( 'Installing Plugin %1$s (%2$d/%3$d)', 'tgmpa' );
3717
							}
3718
						}
3719
					}
3720
3721
					/**
3722
					 * Outputs the header strings and necessary JS before each plugin installation.
3723
					 *
3724
					 * @since 2.2.0
3725
					 *
3726
					 * @param string $title Unused in this implementation.
3727
					 */
3728
					public function before( $title = '' ) {
3729
						if ( empty( $title ) ) {
3730
							$title = esc_html( $this->plugin_names[ $this->i ] );
3731
						}
3732
						parent::before( $title );
3733
					}
3734
3735
					/**
3736
					 * Outputs the footer strings and necessary JS after each plugin installation.
3737
					 *
3738
					 * Checks for any errors and outputs them if they exist, else output
3739
					 * success strings.
3740
					 *
3741
					 * @since 2.2.0
3742
					 *
3743
					 * @param string $title Unused in this implementation.
3744
					 */
3745
					public function after( $title = '' ) {
3746
						if ( empty( $title ) ) {
3747
							$title = esc_html( $this->plugin_names[ $this->i ] );
3748
						}
3749
						parent::after( $title );
3750
3751
						$this->i++;
3752
					}
3753
3754
					/**
3755
					 * Outputs links after bulk plugin installation is complete.
3756
					 *
3757
					 * @since 2.2.0
3758
					 */
3759
					public function bulk_footer() {
3760
						// Serve up the string to say installations (and possibly activations) are complete.
3761
						parent::bulk_footer();
3762
3763
						// Flush plugins cache so we can make sure that the installed plugins list is always up to date.
3764
						wp_clean_plugins_cache();
3765
3766
						$this->tgmpa->show_tgmpa_version();
3767
3768
						// Display message based on if all plugins are now active or not.
3769
						$update_actions = array();
3770
3771
						if ( $this->tgmpa->is_tgmpa_complete() ) {
3772
							// All plugins are active, so we display the complete string and hide the menu to protect users.
3773
							echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>';
3774
							$update_actions['dashboard'] = sprintf(
3775
								esc_html( $this->tgmpa->strings['complete'] ),
3776
								'<a href="' . esc_url( self_admin_url() ) . '">' . esc_html__( 'Return to the Dashboard', 'tgmpa' ) . '</a>'
3777
							);
3778
						} else {
3779
							$update_actions['tgmpa_page'] = '<a href="' . esc_url( $this->tgmpa->get_tgmpa_url() ) . '" target="_parent">' . esc_html( $this->tgmpa->strings['return'] ) . '</a>';
3780
						}
3781
3782
						/**
3783
						 * Filter the list of action links available following bulk plugin installs/updates.
3784
						 *
3785
						 * @since 2.5.0
3786
						 *
3787
						 * @param array $update_actions Array of plugin action links.
3788
						 * @param array $plugin_info    Array of information for the last-handled plugin.
3789
						 */
3790
						$update_actions = apply_filters( 'tgmpa_update_bulk_plugins_complete_actions', $update_actions, $this->plugin_info );
3791
3792
						if ( ! empty( $update_actions ) ) {
3793
							$this->feedback( implode( ' | ', (array) $update_actions ) );
3794
						}
3795
					}
3796
3797
					/* *********** DEPRECATED METHODS *********** */
3798
3799
					/**
3800
					 * Flush header output buffer.
3801
					 *
3802
					 * @since      2.2.0
3803
					 * @deprecated 2.5.0 use {@see Bulk_Upgrader_Skin::flush_output()} instead
3804
					 * @see        Bulk_Upgrader_Skin::flush_output()
3805
					 */
3806
					public function before_flush_output() {
3807
						_deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'Bulk_Upgrader_Skin::flush_output()' );
3808
						$this->flush_output();
3809
					}
3810
3811
					/**
3812
					 * Flush footer output buffer and iterate $this->i to make sure the
3813
					 * installation strings reference the correct plugin.
3814
					 *
3815
					 * @since      2.2.0
3816
					 * @deprecated 2.5.0 use {@see Bulk_Upgrader_Skin::flush_output()} instead
3817
					 * @see        Bulk_Upgrader_Skin::flush_output()
3818
					 */
3819
					public function after_flush_output() {
3820
						_deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'Bulk_Upgrader_Skin::flush_output()' );
3821
						$this->flush_output();
3822
						$this->i++;
3823
					}
3824
				}
3825
			}
3826
		}
3827
	}
3828
}
3829
3830
if ( ! class_exists( 'TGMPA_Utils' ) ) {
3831
3832
	/**
3833
	 * Generic utilities for TGMPA.
3834
	 *
3835
	 * All methods are static, poor-dev name-spacing class wrapper.
3836
	 *
3837
	 * Class was called TGM_Utils in 2.5.0 but renamed TGMPA_Utils in 2.5.1 as this was conflicting with Soliloquy.
3838
	 *
3839
	 * @since 2.5.0
3840
	 *
3841
	 * @package TGM-Plugin-Activation
3842
	 * @author  Juliette Reinders Folmer
3843
	 */
3844
	class TGMPA_Utils {
3845
		/**
3846
		 * Whether the PHP filter extension is enabled.
3847
		 *
3848
		 * @see http://php.net/book.filter
3849
		 *
3850
		 * @since 2.5.0
3851
		 *
3852
		 * @static
3853
		 *
3854
		 * @var bool $has_filters True is the extension is enabled.
3855
		 */
3856
		public static $has_filters;
3857
3858
		/**
3859
		 * Wrap an arbitrary string in <em> tags. Meant to be used in combination with array_map().
3860
		 *
3861
		 * @since 2.5.0
3862
		 *
3863
		 * @static
3864
		 *
3865
		 * @param string $string Text to be wrapped.
3866
		 * @return string
3867
		 */
3868
		public static function wrap_in_em( $string ) {
3869
			return '<em>' . wp_kses_post( $string ) . '</em>';
3870
		}
3871
3872
		/**
3873
		 * Wrap an arbitrary string in <strong> tags. Meant to be used in combination with array_map().
3874
		 *
3875
		 * @since 2.5.0
3876
		 *
3877
		 * @static
3878
		 *
3879
		 * @param string $string Text to be wrapped.
3880
		 * @return string
3881
		 */
3882
		public static function wrap_in_strong( $string ) {
3883
			return '<strong>' . wp_kses_post( $string ) . '</strong>';
3884
		}
3885
3886
		/**
3887
		 * Helper function: Validate a value as boolean
3888
		 *
3889
		 * @since 2.5.0
3890
		 *
3891
		 * @static
3892
		 *
3893
		 * @param mixed $value Arbitrary value.
3894
		 * @return bool
3895
		 */
3896
		public static function validate_bool( $value ) {
3897
			if ( ! isset( self::$has_filters ) ) {
3898
				self::$has_filters = extension_loaded( 'filter' );
3899
			}
3900
3901
			if ( self::$has_filters ) {
3902
				return filter_var( $value, FILTER_VALIDATE_BOOLEAN );
3903
			} else {
3904
				return self::emulate_filter_bool( $value );
3905
			}
3906
		}
3907
3908
		/**
3909
		 * Helper function: Cast a value to bool
3910
		 *
3911
		 * @since 2.5.0
3912
		 *
3913
		 * @static
3914
		 *
3915
		 * @param mixed $value Value to cast.
3916
		 * @return bool
3917
		 */
3918
		protected static function emulate_filter_bool( $value ) {
3919
			// @codingStandardsIgnoreStart
3920
			static $true  = array(
3921
				'1',
3922
				'true', 'True', 'TRUE',
3923
				'y', 'Y',
3924
				'yes', 'Yes', 'YES',
3925
				'on', 'On', 'ON',
3926
			);
3927
			static $false = array(
3928
				'0',
3929
				'false', 'False', 'FALSE',
3930
				'n', 'N',
3931
				'no', 'No', 'NO',
3932
				'off', 'Off', 'OFF',
3933
			);
3934
			// @codingStandardsIgnoreEnd
3935
3936
			if ( is_bool( $value ) ) {
3937
				return $value;
3938
			} elseif ( is_int( $value ) && ( 0 === $value || 1 === $value ) ) {
3939
				return (bool) $value;
3940
			} elseif ( ( is_float( $value ) && ! is_nan( $value ) ) && ( (float) 0 === $value || (float) 1 === $value ) ) {
3941
				return (bool) $value;
3942
			} elseif ( is_string( $value ) ) {
3943
				$value = trim( $value );
3944
				if ( in_array( $value, $true, true ) ) {
3945
					return true;
3946
				} elseif ( in_array( $value, $false, true ) ) {
3947
					return false;
3948
				} else {
3949
					return false;
3950
				}
3951
			}
3952
3953
			return false;
3954
		}
3955
	} // End of class TGMPA_Utils
3956
} // End of class_exists wrapper
3957