Completed
Pull Request — develop (#512)
by Juliette
02:19
created

TGMPA_Utils   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 112
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0
Metric Value
wmc 17
lcom 1
cbo 0
dl 0
loc 112
rs 10

4 Methods

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

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

Loading history...
1019
1020
			foreach ( $this->plugins as $slug => $plugin ) {
1021
				if ( $this->is_plugin_active( $slug ) && false === $this->does_plugin_have_update( $slug ) ) {
1022
					continue;
1023
				}
1024
1025
				if ( ! $this->is_plugin_installed( $slug ) ) {
1026
					if ( current_user_can( 'install_plugins' ) ) {
1027
						$install_link_count++;
1028
1029
						if ( true === $plugin['required'] ) {
1030
							$message['notice_can_install_required'][] = $slug;
1031
						} else {
1032
							$message['notice_can_install_recommended'][] = $slug;
1033
						}
1034
					}
1035
					if ( true === $plugin['required'] ) {
1036
						$total_required_action_count++;
1037
					}
1038
				} else {
1039
					if ( ! $this->is_plugin_active( $slug ) && $this->can_plugin_activate( $slug ) ) {
1040
						if ( current_user_can( 'activate_plugins' ) ) {
1041
							$activate_link_count++;
1042
1043
							if ( true === $plugin['required'] ) {
1044
								$message['notice_can_activate_required'][] = $slug;
1045
							} else {
1046
								$message['notice_can_activate_recommended'][] = $slug;
1047
							}
1048
						}
1049
						if ( true === $plugin['required'] ) {
1050
							$total_required_action_count++;
1051
						}
1052
					}
1053
1054
					if ( $this->does_plugin_require_update( $slug ) || false !== $this->does_plugin_have_update( $slug ) ) {
1055
1056
						if ( current_user_can( 'update_plugins' ) ) {
1057
							$update_link_count++;
1058
1059
							if ( $this->does_plugin_require_update( $slug ) ) {
1060
								$message['notice_ask_to_update'][] = $slug;
1061
							} elseif ( false !== $this->does_plugin_have_update( $slug ) ) {
1062
								$message['notice_ask_to_update_maybe'][] = $slug;
1063
							}
1064
						}
1065
						if ( true === $plugin['required'] ) {
1066
							$total_required_action_count++;
1067
						}
1068
					}
1069
				}
1070
			}
1071
			unset( $slug, $plugin );
1072
1073
			// If we have notices to display, we move forward.
1074
			if ( ! empty( $message ) || $total_required_action_count > 0 ) {
1075
				krsort( $message ); // Sort messages.
1076
				$rendered = '';
1077
1078
				// As add_settings_error() wraps the final message in a <p> and as the final message can't be
1079
				// filtered, using <p>'s in our html would render invalid html output.
1080
				$line_template = '<span style="display: block; margin: 0.5em 0.5em 0 0; clear: both;">%s</span>' . "\n";
1081
1082
				if ( ! current_user_can( 'activate_plugins' ) && ! current_user_can( 'install_plugins' ) && ! current_user_can( 'update_plugins' ) ) {
1083
					$rendered = esc_html__( $this->strings['notice_cannot_install_activate'] . ' ' . $this->strings['contact_admin'] );
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 2 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
1084
					$rendered .= $this->create_user_action_links_for_notice( 0, 0, 0, $line_template );
1085
				} else {
1086
1087
					// If dismissable is false and a message is set, output it now.
1088
					if ( ! $this->dismissable && ! empty( $this->dismiss_msg ) ) {
1089
						$rendered .= sprintf( $line_template, wp_kses_post( $this->dismiss_msg ) );
1090
					}
1091
1092
					// Render the individual message lines for the notice.
1093
					foreach ( $message as $type => $plugin_group ) {
1094
						$linked_plugins = array();
1095
1096
						// Get the external info link for a plugin if one is available.
1097
						foreach ( $plugin_group as $plugin_slug ) {
1098
							$linked_plugins[] = $this->get_info_link( $plugin_slug );
1099
						}
1100
						unset( $plugin_slug );
1101
1102
						$count          = count( $plugin_group );
1103
						$linked_plugins = array_map( array( 'TGMPA_Utils', 'wrap_in_em' ), $linked_plugins );
1104
						$last_plugin    = array_pop( $linked_plugins ); // Pop off last name to prep for readability.
1105
						$imploded       = empty( $linked_plugins ) ? $last_plugin : ( implode( ', ', $linked_plugins ) . ' ' . esc_html_x( 'and', 'plugin A *and* plugin B', 'tgmpa' ) . ' ' . $last_plugin );
1106
1107
						$rendered .= sprintf(
1108
							$line_template,
1109
							sprintf(
1110
								translate_nooped_plural( $this->strings[ $type ], $count, 'tgmpa' ),
1111
								$imploded,
1112
								$count
1113
							)
1114
						);
1115
1116
					}
1117
					unset( $type, $plugin_group, $linked_plugins, $count, $last_plugin, $imploded );
1118
1119
					$rendered .= $this->create_user_action_links_for_notice( $install_link_count, $update_link_count, $activate_link_count, $line_template );
1120
				}
1121
1122
				// Register the nag messages and prepare them to be processed.
1123
				add_settings_error( 'tgmpa', 'tgmpa', $rendered, $this->get_admin_notice_class() );
1124
			}
1125
1126
			// Admin options pages already output settings_errors, so this is to avoid duplication.
1127
			if ( 'options-general' !== $GLOBALS['current_screen']->parent_base ) {
1128
				$this->display_settings_errors();
1129
			}
1130
		}
1131
1132
		/**
1133
		 * Generate the user action links for the admin notice.
1134
		 *
1135
		 * @since 2.x.x
1136
		 *
1137
		 * @param int $install_link_count  Number of plugins to install.
1138
		 * @param int $update_link_count   Number of plugins to update.
1139
		 * @param int $activate_link_count Number of plugins to activate.
1140
		 * @param int $line_template       Template for the HTML tag to output a line.
1141
		 * @return string Action links.
1142
		 */
1143
		protected function create_user_action_links_for_notice( $install_link_count, $update_link_count, $activate_link_count, $line_template ) {
1144
			// Setup action links.
1145
			$action_links = array(
1146
				'install'  => '',
1147
				'update'   => '',
1148
				'activate' => '',
1149
				'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>' : '',
1150
			);
1151
1152
			$link_template = '<a href="%2$s">%1$s</a>';
1153
1154
			if ( current_user_can( 'install_plugins' ) ) {
1155 View Code Duplication
				if ( $install_link_count > 0 ) {
1156
					$action_links['install'] = sprintf(
1157
						$link_template,
1158
						translate_nooped_plural( $this->strings['install_link'], $install_link_count, 'tgmpa' ),
1159
						esc_url( $this->get_tgmpa_status_url( 'install' ) )
1160
					);
1161
				}
1162 View Code Duplication
				if ( $update_link_count > 0 ) {
1163
					$action_links['update'] = sprintf(
1164
						$link_template,
1165
						translate_nooped_plural( $this->strings['update_link'], $update_link_count, 'tgmpa' ),
1166
						esc_url( $this->get_tgmpa_status_url( 'update' ) )
1167
					);
1168
				}
1169
			}
1170
1171 View Code Duplication
			if ( current_user_can( 'activate_plugins' ) && $activate_link_count > 0 ) {
1172
				$action_links['activate'] = sprintf(
1173
					$link_template,
1174
					translate_nooped_plural( $this->strings['activate_link'], $activate_link_count, 'tgmpa' ),
1175
					esc_url( $this->get_tgmpa_status_url( 'activate' ) )
1176
				);
1177
			}
1178
1179
			$action_links = apply_filters( 'tgmpa_notice_action_links', $action_links );
1180
1181
			$action_links = array_filter( (array) $action_links ); // Remove any empty array items.
1182
1183
			if ( ! empty( $action_links ) && is_array( $action_links ) ) {
1184
				$action_links = sprintf( $line_template, implode( ' | ', $action_links ) );
1185
				return apply_filters( 'tgmpa_notice_rendered_action_links', $action_links );
1186
			} else {
1187
				return '';
1188
			}
1189
		}
1190
1191
		/**
1192
		 * Get admin notice class.
1193
		 *
1194
		 * Work around all the changes to the various admin notice classes between WP 4.4 and 3.7
1195
		 * (lowest supported version by TGMPA).
1196
		 *
1197
		 * @since 2.x.x
1198
		 *
1199
		 * @return string
1200
		 */
1201
		protected function get_admin_notice_class() {
1202
			if ( ! empty( $this->strings['nag_type'] ) ) {
1203
				return sanitize_html_class( strtolower( $this->strings['nag_type'] ) );
1204
			} else {
1205
				if ( version_compare( $this->wp_version, '4.2', '>=' ) ) {
1206
					return 'notice-warning';
1207
				} elseif ( version_compare( $this->wp_version, '4.1', '>=' ) ) {
1208
					return 'notice';
1209
				} else {
1210
					return 'updated';
1211
				}
1212
			}
1213
		}
1214
1215
		/**
1216
		 * Display settings errors and remove those which have been displayed to avoid duplicate messages showing
1217
		 *
1218
		 * @since 2.5.0
1219
		 */
1220
		protected function display_settings_errors() {
1221
			global $wp_settings_errors;
1222
1223
			settings_errors( 'tgmpa' );
1224
1225
			foreach ( (array) $wp_settings_errors as $key => $details ) {
1226
				if ( 'tgmpa' === $details['setting'] ) {
1227
					unset( $wp_settings_errors[ $key ] );
1228
					break;
1229
				}
1230
			}
1231
		}
1232
1233
		/**
1234
		 * Add dismissable admin notices.
1235
		 *
1236
		 * Appends a link to the admin nag messages. If clicked, the admin notice disappears and no longer is visible to users.
1237
		 *
1238
		 * @since 2.1.0
1239
		 */
1240
		public function dismiss() {
1241
			if ( isset( $_GET['tgmpa-dismiss'] ) && check_admin_referer( 'tgmpa-dismis-' . get_current_user_id() ) ) {
1242
				update_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, 1 );
1243
			}
1244
		}
1245
1246
		/**
1247
		 * Add individual plugin to our collection of plugins.
1248
		 *
1249
		 * If the required keys are not set or the plugin has already
1250
		 * been registered, the plugin is not added.
1251
		 *
1252
		 * @since 2.0.0
1253
		 *
1254
		 * @param array|null $plugin Array of plugin arguments or null if invalid argument.
1255
		 * @return null Return early if incorrect argument.
1256
		 */
1257
		public function register( $plugin ) {
1258
			if ( empty( $plugin['slug'] ) || empty( $plugin['name'] ) ) {
1259
				return;
1260
			}
1261
1262
			if ( empty( $plugin['slug'] ) || ! is_string( $plugin['slug'] ) || isset( $this->plugins[ $plugin['slug'] ] ) ) {
1263
				return;
1264
			}
1265
1266
			$defaults = array(
1267
				'name'               => '',      // String
1268
				'slug'               => '',      // String
1269
				'source'             => 'repo',  // String
1270
				'required'           => false,   // Boolean
1271
				'version'            => '',      // String
1272
				'force_activation'   => false,   // Boolean
1273
				'force_deactivation' => false,   // Boolean
1274
				'external_url'       => '',      // String
1275
				'is_callable'        => '',      // String|Array.
1276
			);
1277
1278
			// Prepare the received data.
1279
			$plugin = wp_parse_args( $plugin, $defaults );
1280
1281
			// Standardize the received slug.
1282
			$plugin['slug'] = $this->sanitize_key( $plugin['slug'] );
1283
1284
			// Forgive users for using string versions of booleans or floats for version number.
1285
			$plugin['version']            = (string) $plugin['version'];
1286
			$plugin['source']             = empty( $plugin['source'] ) ? 'repo' : $plugin['source'];
1287
			$plugin['required']           = TGMPA_Utils::validate_bool( $plugin['required'] );
1288
			$plugin['force_activation']   = TGMPA_Utils::validate_bool( $plugin['force_activation'] );
1289
			$plugin['force_deactivation'] = TGMPA_Utils::validate_bool( $plugin['force_deactivation'] );
1290
1291
			// Enrich the received data.
1292
			$plugin['file_path']   = $this->_get_plugin_basename_from_slug( $plugin['slug'] );
1293
			$plugin['source_type'] = $this->get_plugin_source_type( $plugin['source'] );
1294
1295
			// Set the class properties.
1296
			$this->plugins[ $plugin['slug'] ]    = $plugin;
1297
			$this->sort_order[ $plugin['slug'] ] = $plugin['name'];
1298
1299
			// Should we add the force activation hook ?
1300
			if ( true === $plugin['force_activation'] ) {
1301
				$this->has_forced_activation = true;
1302
			}
1303
1304
			// Should we add the force deactivation hook ?
1305
			if ( true === $plugin['force_deactivation'] ) {
1306
				$this->has_forced_deactivation = true;
1307
			}
1308
		}
1309
1310
		/**
1311
		 * Determine what type of source the plugin comes from.
1312
		 *
1313
		 * @since 2.5.0
1314
		 *
1315
		 * @param string $source The source of the plugin as provided, either empty (= WP repo), a file path
1316
		 *                       (= bundled) or an external URL.
1317
		 * @return string 'repo', 'external', or 'bundled'
1318
		 */
1319
		protected function get_plugin_source_type( $source ) {
1320
			if ( 'repo' === $source || preg_match( self::WP_REPO_REGEX, $source ) ) {
1321
				return 'repo';
1322
			} elseif ( preg_match( self::IS_URL_REGEX, $source ) ) {
1323
				return 'external';
1324
			} else {
1325
				return 'bundled';
1326
			}
1327
		}
1328
1329
		/**
1330
		 * Sanitizes a string key.
1331
		 *
1332
		 * Near duplicate of WP Core `sanitize_key()`. The difference is that uppercase characters *are*
1333
		 * allowed, so as not to break upgrade paths from non-standard bundled plugins using uppercase
1334
		 * characters in the plugin directory path/slug. Silly them.
1335
		 *
1336
		 * @see https://developer.wordpress.org/reference/hooks/sanitize_key/
1337
		 *
1338
		 * @since 2.5.0
1339
		 *
1340
		 * @param string $key String key.
1341
		 * @return string Sanitized key
1342
		 */
1343
		public function sanitize_key( $key ) {
1344
			$raw_key = $key;
1345
			$key     = preg_replace( '`[^A-Za-z0-9_-]`', '', $key );
1346
1347
			/**
1348
			* Filter a sanitized key string.
1349
			*
1350
			* @since 3.0.0
1351
			*
1352
			* @param string $key     Sanitized key.
1353
			* @param string $raw_key The key prior to sanitization.
1354
			*/
1355
			return apply_filters( 'tgmpa_sanitize_key', $key, $raw_key );
1356
		}
1357
1358
		/**
1359
		 * Amend default configuration settings.
1360
		 *
1361
		 * @since 2.0.0
1362
		 *
1363
		 * @param array $config Array of config options to pass as class properties.
1364
		 */
1365
		public function config( $config ) {
1366
			$keys = array(
1367
				'id',
1368
				'default_path',
1369
				'has_notices',
1370
				'dismissable',
1371
				'dismiss_msg',
1372
				'menu',
1373
				'parent_slug',
1374
				'capability',
1375
				'is_automatic',
1376
				'message',
1377
				'strings',
1378
			);
1379
1380
			foreach ( $keys as $key ) {
1381
				if ( isset( $config[ $key ] ) ) {
1382
					if ( is_array( $config[ $key ] ) ) {
1383
						$this->$key = array_merge( $this->$key, $config[ $key ] );
1384
					} else {
1385
						$this->$key = $config[ $key ];
1386
					}
1387
				}
1388
			}
1389
		}
1390
1391
		/**
1392
		 * Amend action link after plugin installation.
1393
		 *
1394
		 * @since 2.0.0
1395
		 *
1396
		 * @param array $install_actions Existing array of actions.
1397
		 * @return array Amended array of actions.
1398
		 */
1399
		public function actions( $install_actions ) {
1400
			// Remove action links on the TGMPA install page.
1401
			if ( $this->is_tgmpa_page() ) {
1402
				return false;
1403
			}
1404
1405
			return $install_actions;
1406
		}
1407
1408
		/**
1409
		 * Flushes the plugins cache on theme switch to prevent stale entries
1410
		 * from remaining in the plugin table.
1411
		 *
1412
		 * @since 2.4.0
1413
		 *
1414
		 * @param bool $clear_update_cache Optional. Whether to clear the Plugin updates cache.
1415
		 *                                 Parameter added in v2.5.0.
1416
		 */
1417
		public function flush_plugins_cache( $clear_update_cache = true ) {
1418
			wp_clean_plugins_cache( $clear_update_cache );
1419
		}
1420
1421
		/**
1422
		 * Set file_path key for each installed plugin.
1423
		 *
1424
		 * @since 2.1.0
1425
		 *
1426
		 * @param string $plugin_slug Optional. If set, only (re-)populates the file path for that specific plugin.
1427
		 *                            Parameter added in v2.5.0.
1428
		 */
1429
		public function populate_file_path( $plugin_slug = '' ) {
1430
			if ( ! empty( $plugin_slug ) && is_string( $plugin_slug ) && isset( $this->plugins[ $plugin_slug ] ) ) {
1431
				$this->plugins[ $plugin_slug ]['file_path'] = $this->_get_plugin_basename_from_slug( $plugin_slug );
1432
			} else {
1433
				// Add file_path key for all plugins.
1434
				foreach ( $this->plugins as $slug => $values ) {
1435
					$this->plugins[ $slug ]['file_path'] = $this->_get_plugin_basename_from_slug( $slug );
1436
				}
1437
			}
1438
		}
1439
1440
		/**
1441
		 * Helper function to extract the file path of the plugin file from the
1442
		 * plugin slug, if the plugin is installed.
1443
		 *
1444
		 * @since 2.0.0
1445
		 *
1446
		 * @param string $slug Plugin slug (typically folder name) as provided by the developer.
1447
		 * @return string Either file path for plugin if installed, or just the plugin slug.
1448
		 */
1449
		protected function _get_plugin_basename_from_slug( $slug ) {
1450
			$keys = array_keys( $this->get_plugins() );
1451
1452
			foreach ( $keys as $key ) {
1453
				if ( preg_match( '|^' . $slug . '/|', $key ) ) {
1454
					return $key;
1455
				}
1456
			}
1457
1458
			return $slug;
1459
		}
1460
1461
		/**
1462
		 * Retrieve plugin data, given the plugin name.
1463
		 *
1464
		 * Loops through the registered plugins looking for $name. If it finds it,
1465
		 * it returns the $data from that plugin. Otherwise, returns false.
1466
		 *
1467
		 * @since 2.1.0
1468
		 *
1469
		 * @param string $name Name of the plugin, as it was registered.
1470
		 * @param string $data Optional. Array key of plugin data to return. Default is slug.
1471
		 * @return string|boolean Plugin slug if found, false otherwise.
1472
		 */
1473
		public function _get_plugin_data_from_name( $name, $data = 'slug' ) {
1474
			foreach ( $this->plugins as $values ) {
1475
				if ( $name === $values['name'] && isset( $values[ $data ] ) ) {
1476
					return $values[ $data ];
1477
				}
1478
			}
1479
1480
			return false;
1481
		}
1482
1483
		/**
1484
		 * Retrieve the download URL for a package.
1485
		 *
1486
		 * @since 2.5.0
1487
		 *
1488
		 * @param string $slug Plugin slug.
1489
		 * @return string Plugin download URL or path to local file or empty string if undetermined.
1490
		 */
1491
		public function get_download_url( $slug ) {
1492
			$dl_source = '';
1493
1494
			switch ( $this->plugins[ $slug ]['source_type'] ) {
1495
				case 'repo':
1496
					return $this->get_wp_repo_download_url( $slug );
1497
				case 'external':
1498
					return $this->plugins[ $slug ]['source'];
1499
				case 'bundled':
1500
					return $this->default_path . $this->plugins[ $slug ]['source'];
1501
			}
1502
1503
			return $dl_source; // Should never happen.
1504
		}
1505
1506
		/**
1507
		 * Retrieve the download URL for a WP repo package.
1508
		 *
1509
		 * @since 2.5.0
1510
		 *
1511
		 * @param string $slug Plugin slug.
1512
		 * @return string Plugin download URL.
1513
		 */
1514
		protected function get_wp_repo_download_url( $slug ) {
1515
			$source = '';
1516
			$api    = $this->get_plugins_api( $slug );
1517
1518
			if ( false !== $api && isset( $api->download_link ) ) {
1519
				$source = $api->download_link;
1520
			}
1521
1522
			return $source;
1523
		}
1524
1525
		/**
1526
		 * Try to grab information from WordPress API.
1527
		 *
1528
		 * @since 2.5.0
1529
		 *
1530
		 * @param string $slug Plugin slug.
1531
		 * @return object Plugins_api response object on success, WP_Error on failure.
1532
		 */
1533
		protected function get_plugins_api( $slug ) {
1534
			static $api = array(); // Cache received responses.
1535
1536
			if ( ! isset( $api[ $slug ] ) ) {
1537
				if ( ! function_exists( 'plugins_api' ) ) {
1538
					require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
1539
				}
1540
1541
				$response = plugins_api( 'plugin_information', array( 'slug' => $slug, 'fields' => array( 'sections' => false ) ) );
1542
1543
				$api[ $slug ] = false;
1544
1545
				if ( is_wp_error( $response ) ) {
1546
					wp_die( esc_html( $this->strings['oops'] ) );
1547
				} else {
1548
					$api[ $slug ] = $response;
1549
				}
1550
			}
1551
1552
			return $api[ $slug ];
1553
		}
1554
1555
		/**
1556
		 * Retrieve a link to a plugin information page.
1557
		 *
1558
		 * @since 2.5.0
1559
		 *
1560
		 * @param string $slug Plugin slug.
1561
		 * @return string Fully formed html link to a plugin information page if available
1562
		 *                or the plugin name if not.
1563
		 */
1564
		public function get_info_link( $slug ) {
1565
			if ( ! empty( $this->plugins[ $slug ]['external_url'] ) && preg_match( self::IS_URL_REGEX, $this->plugins[ $slug ]['external_url'] ) ) {
1566
				$link = sprintf(
1567
					'<a href="%1$s" target="_blank">%2$s</a>',
1568
					esc_url( $this->plugins[ $slug ]['external_url'] ),
1569
					esc_html( $this->plugins[ $slug ]['name'] )
1570
				);
1571
			} elseif ( 'repo' === $this->plugins[ $slug ]['source_type'] ) {
1572
				$url = add_query_arg(
1573
					array(
1574
						'tab'       => 'plugin-information',
1575
						'plugin'    => urlencode( $slug ),
1576
						'TB_iframe' => 'true',
1577
						'width'     => '640',
1578
						'height'    => '500',
1579
					),
1580
					self_admin_url( 'plugin-install.php' )
1581
				);
1582
1583
				$link = sprintf(
1584
					'<a href="%1$s" class="thickbox">%2$s</a>',
1585
					esc_url( $url ),
1586
					esc_html( $this->plugins[ $slug ]['name'] )
1587
				);
1588
			} else {
1589
				$link = esc_html( $this->plugins[ $slug ]['name'] ); // No hyperlink.
1590
			}
1591
1592
			return $link;
1593
		}
1594
1595
		/**
1596
		 * Determine if we're on the TGMPA Install page.
1597
		 *
1598
		 * @since 2.1.0
1599
		 *
1600
		 * @return boolean True when on the TGMPA page, false otherwise.
1601
		 */
1602
		protected function is_tgmpa_page() {
1603
			return isset( $_GET['page'] ) && $this->menu === $_GET['page'];
1604
		}
1605
1606
		/**
1607
		 * Determine if we're on a WP Core installation/upgrade page.
1608
		 *
1609
		 * @since 2.x.x
1610
		 *
1611
		 * @return boolean True when on a WP Core installation/upgrade page, false otherwise.
1612
		 */
1613
		protected function is_core_update_page() {
1614
			// Current screen is not always available, most notably on the customizer screen.
1615
			if ( ! function_exists( 'get_current_screen' ) ) {
1616
				return false;
1617
			}
1618
1619
			$screen = get_current_screen();
1620
1621
			if ( 'update-core' === $screen->base ) {
1622
				// Core update screen.
1623
				return true;
1624
			} elseif ( 'plugins' === $screen->base && isset( $_POST['action'] ) ) {
1625
				// Plugins bulk update screen.
1626
				return true;
1627
			} elseif ( 'update' === $screen->base && isset( $_POST['action'] ) ) {
1628
				// Individual updates (ajax call).
1629
				return true;
1630
			}
1631
1632
			return false;
1633
		}
1634
1635
		/**
1636
		 * Retrieve the URL to the TGMPA Install page.
1637
		 *
1638
		 * I.e. depending on the config settings passed something along the lines of:
1639
		 * http://example.com/wp-admin/themes.php?page=tgmpa-install-plugins
1640
		 *
1641
		 * @since 2.5.0
1642
		 *
1643
		 * @return string Properly encoded URL (not escaped).
1644
		 */
1645
		public function get_tgmpa_url() {
1646
			static $url;
1647
1648
			if ( ! isset( $url ) ) {
1649
				$parent = $this->parent_slug;
1650
				if ( false === strpos( $parent, '.php' ) ) {
1651
					$parent = 'admin.php';
1652
				}
1653
				$url = add_query_arg(
1654
					array(
1655
						'page' => urlencode( $this->menu ),
1656
					),
1657
					self_admin_url( $parent )
1658
				);
1659
			}
1660
1661
			return $url;
1662
		}
1663
1664
		/**
1665
		 * Retrieve the URL to the TGMPA Install page for a specific plugin status (view).
1666
		 *
1667
		 * I.e. depending on the config settings passed something along the lines of:
1668
		 * http://example.com/wp-admin/themes.php?page=tgmpa-install-plugins&plugin_status=install
1669
		 *
1670
		 * @since 2.5.0
1671
		 *
1672
		 * @param string $status Plugin status - either 'install', 'update' or 'activate'.
1673
		 * @return string Properly encoded URL (not escaped).
1674
		 */
1675
		public function get_tgmpa_status_url( $status ) {
1676
			return add_query_arg(
1677
				array(
1678
					'plugin_status' => urlencode( $status ),
1679
				),
1680
				$this->get_tgmpa_url()
1681
			);
1682
		}
1683
1684
		/**
1685
		 * Determine whether there are open actions for plugins registered with TGMPA.
1686
		 *
1687
		 * @since 2.5.0
1688
		 *
1689
		 * @return bool True if complete, i.e. no outstanding actions. False otherwise.
1690
		 */
1691
		public function is_tgmpa_complete() {
1692
			$complete = true;
1693
			foreach ( $this->plugins as $slug => $plugin ) {
1694
				if ( ! $this->is_plugin_active( $slug ) || false !== $this->does_plugin_have_update( $slug ) ) {
1695
					$complete = false;
1696
					break;
1697
				}
1698
			}
1699
1700
			return $complete;
1701
		}
1702
1703
		/**
1704
		 * Check if a plugin is installed. Does not take must-use plugins into account.
1705
		 *
1706
		 * @since 2.5.0
1707
		 *
1708
		 * @param string $slug Plugin slug.
1709
		 * @return bool True if installed, false otherwise.
1710
		 */
1711
		public function is_plugin_installed( $slug ) {
1712
			$installed_plugins = $this->get_plugins(); // Retrieve a list of all installed plugins (WP cached).
1713
1714
			return ( ! empty( $installed_plugins[ $this->plugins[ $slug ]['file_path'] ] ) );
1715
		}
1716
1717
		/**
1718
		 * Check if a plugin is active.
1719
		 *
1720
		 * @since 2.5.0
1721
		 *
1722
		 * @param string $slug Plugin slug.
1723
		 * @return bool True if active, false otherwise.
1724
		 */
1725
		public function is_plugin_active( $slug ) {
1726
			return ( ( ! empty( $this->plugins[ $slug ]['is_callable'] ) && is_callable( $this->plugins[ $slug ]['is_callable'] ) ) || is_plugin_active( $this->plugins[ $slug ]['file_path'] ) );
1727
		}
1728
1729
		/**
1730
		 * Check if a plugin can be updated, i.e. if we have information on the minimum WP version required
1731
		 * available, check whether the current install meets them.
1732
		 *
1733
		 * @since 2.5.0
1734
		 *
1735
		 * @param string $slug Plugin slug.
1736
		 * @return bool True if OK to update, false otherwise.
1737
		 */
1738
		public function can_plugin_update( $slug ) {
1739
			// We currently can't get reliable info on non-WP-repo plugins - issue #380.
1740
			if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) {
1741
				return true;
1742
			}
1743
1744
			$api = $this->get_plugins_api( $slug );
1745
1746
			if ( false !== $api && isset( $api->requires ) ) {
1747
				return version_compare( $GLOBALS['wp_version'], $api->requires, '>=' );
1748
			}
1749
1750
			// No usable info received from the plugins API, presume we can update.
1751
			return true;
1752
		}
1753
1754
		/**
1755
		 * Check to see if the plugin is 'updatetable', i.e. installed, with an update available
1756
		 * and no WP version requirements blocking it.
1757
		 *
1758
		 * @since 2.x.x
1759
		 *
1760
		 * @param string $slug Plugin slug.
1761
		 * @return bool True if OK to proceed with update, false otherwise.
1762
		 */
1763
		public function is_plugin_updatetable( $slug ) {
1764
			if ( ! $this->is_plugin_installed( $slug ) ) {
1765
				return false;
1766
			} else {
1767
				return ( $this->does_plugin_have_update( $slug ) && $this->can_plugin_update( $slug ) );
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->does_plugin_have_update($slug) of type false|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1768
			}
1769
		}
1770
1771
		/**
1772
		 * Check if a plugin can be activated, i.e. is not currently active and meets the minimum
1773
		 * plugin version requirements set in TGMPA (if any).
1774
		 *
1775
		 * @since 2.5.0
1776
		 *
1777
		 * @param string $slug Plugin slug.
1778
		 * @return bool True if OK to activate, false otherwise.
1779
		 */
1780
		public function can_plugin_activate( $slug ) {
1781
			return ( ! $this->is_plugin_active( $slug ) && ! $this->does_plugin_require_update( $slug ) );
1782
		}
1783
1784
		/**
1785
		 * Retrieve the version number of an installed plugin.
1786
		 *
1787
		 * @since 2.5.0
1788
		 *
1789
		 * @param string $slug Plugin slug.
1790
		 * @return string Version number as string or an empty string if the plugin is not installed
1791
		 *                or version unknown (plugins which don't comply with the plugin header standard).
1792
		 */
1793
		public function get_installed_version( $slug ) {
1794
			$installed_plugins = $this->get_plugins(); // Retrieve a list of all installed plugins (WP cached).
1795
1796
			if ( ! empty( $installed_plugins[ $this->plugins[ $slug ]['file_path'] ]['Version'] ) ) {
1797
				return $installed_plugins[ $this->plugins[ $slug ]['file_path'] ]['Version'];
1798
			}
1799
1800
			return '';
1801
		}
1802
1803
		/**
1804
		 * Check whether a plugin complies with the minimum version requirements.
1805
		 *
1806
		 * @since 2.5.0
1807
		 *
1808
		 * @param string $slug Plugin slug.
1809
		 * @return bool True when a plugin needs to be updated, otherwise false.
1810
		 */
1811
		public function does_plugin_require_update( $slug ) {
1812
			$installed_version = $this->get_installed_version( $slug );
1813
			$minimum_version   = $this->plugins[ $slug ]['version'];
1814
1815
			return version_compare( $minimum_version, $installed_version, '>' );
1816
		}
1817
1818
		/**
1819
		 * Check whether there is an update available for a plugin.
1820
		 *
1821
		 * @since 2.5.0
1822
		 *
1823
		 * @param string $slug Plugin slug.
1824
		 * @return false|string Version number string of the available update or false if no update available.
1825
		 */
1826
		public function does_plugin_have_update( $slug ) {
1827
			// Presume bundled and external plugins will point to a package which meets the minimum required version.
1828
			if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) {
1829
				if ( $this->does_plugin_require_update( $slug ) ) {
1830
					return $this->plugins[ $slug ]['version'];
1831
				}
1832
1833
				return false;
1834
			}
1835
1836
			$repo_updates = get_site_transient( 'update_plugins' );
1837
1838 View Code Duplication
			if ( isset( $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->new_version ) ) {
1839
				return $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->new_version;
1840
			}
1841
1842
			return false;
1843
		}
1844
1845
		/**
1846
		 * Retrieve potential upgrade notice for a plugin.
1847
		 *
1848
		 * @since 2.5.0
1849
		 *
1850
		 * @param string $slug Plugin slug.
1851
		 * @return string The upgrade notice or an empty string if no message was available or provided.
1852
		 */
1853
		public function get_upgrade_notice( $slug ) {
1854
			// We currently can't get reliable info on non-WP-repo plugins - issue #380.
1855
			if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) {
1856
				return '';
1857
			}
1858
1859
			$repo_updates = get_site_transient( 'update_plugins' );
1860
1861 View Code Duplication
			if ( ! empty( $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->upgrade_notice ) ) {
1862
				return $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->upgrade_notice;
1863
			}
1864
1865
			return '';
1866
		}
1867
1868
		/**
1869
		 * Wrapper around the core WP get_plugins function, making sure it's actually available.
1870
		 *
1871
		 * @since 2.5.0
1872
		 *
1873
		 * @param string $plugin_folder Optional. Relative path to single plugin folder.
1874
		 * @return array Array of installed plugins with plugin information.
1875
		 */
1876
		public function get_plugins( $plugin_folder = '' ) {
1877
			if ( ! function_exists( 'get_plugins' ) ) {
1878
				require_once ABSPATH . 'wp-admin/includes/plugin.php';
1879
			}
1880
1881
			return get_plugins( $plugin_folder );
1882
		}
1883
1884
		/**
1885
		 * Delete dismissable nag option when theme is switched.
1886
		 *
1887
		 * This ensures that the user(s) is/are again reminded via nag of required
1888
		 * and/or recommended plugins if they re-activate the theme.
1889
		 *
1890
		 * @since 2.1.1
1891
		 */
1892
		public function update_dismiss() {
1893
			delete_metadata( 'user', null, 'tgmpa_dismissed_notice_' . $this->id, null, true );
1894
		}
1895
1896
		/**
1897
		 * Forces plugin activation if the parameter 'force_activation' is
1898
		 * set to true.
1899
		 *
1900
		 * This allows theme authors to specify certain plugins that must be
1901
		 * active at all times while using the current theme.
1902
		 *
1903
		 * Please take special care when using this parameter as it has the
1904
		 * potential to be harmful if not used correctly. Setting this parameter
1905
		 * to true will not allow the specified plugin to be deactivated unless
1906
		 * the user switches themes.
1907
		 *
1908
		 * @since 2.2.0
1909
		 */
1910
		public function force_activation() {
1911
			foreach ( $this->plugins as $slug => $plugin ) {
1912
				if ( true === $plugin['force_activation'] ) {
1913
					if ( ! $this->is_plugin_installed( $slug ) ) {
1914
						// Oops, plugin isn't there so iterate to next condition.
1915
						continue;
1916
					} elseif ( $this->can_plugin_activate( $slug ) ) {
1917
						// There we go, activate the plugin.
1918
						activate_plugin( $plugin['file_path'] );
1919
					}
1920
				}
1921
			}
1922
		}
1923
1924
		/**
1925
		 * Forces plugin deactivation if the parameter 'force_deactivation'
1926
		 * is set to true.
1927
		 *
1928
		 * This allows theme authors to specify certain plugins that must be
1929
		 * deactivated upon switching from the current theme to another.
1930
		 *
1931
		 * Please take special care when using this parameter as it has the
1932
		 * potential to be harmful if not used correctly.
1933
		 *
1934
		 * @since 2.2.0
1935
		 */
1936
		public function force_deactivation() {
1937
			foreach ( $this->plugins as $slug => $plugin ) {
1938
				// Only proceed forward if the parameter is set to true and plugin is active.
1939
				if ( true === $plugin['force_deactivation'] && $this->is_plugin_active( $slug ) ) {
1940
					deactivate_plugins( $plugin['file_path'] );
1941
				}
1942
			}
1943
		}
1944
1945
		/**
1946
		 * Echo the current TGMPA version number to the page.
1947
		 */
1948
		public function show_tgmpa_version() {
1949
			echo '<p style="float: right; padding: 0em 1.5em 0.5em 0;"><strong><small>',
1950
				esc_html( sprintf( _x( 'TGMPA v%s', '%s = version number', 'tgmpa' ), self::TGMPA_VERSION ) ),
1951
				'</small></strong></p>';
1952
		}
1953
1954
		/**
1955
		 * Returns the singleton instance of the class.
1956
		 *
1957
		 * @since 2.4.0
1958
		 *
1959
		 * @return object The TGM_Plugin_Activation object.
1960
		 */
1961
		public static function get_instance() {
1962
			if ( ! isset( self::$instance ) && ! ( self::$instance instanceof self ) ) {
1963
				self::$instance = new self();
1964
			}
1965
1966
			return self::$instance;
1967
		}
1968
	}
1969
1970
	if ( ! function_exists( 'load_tgm_plugin_activation' ) ) {
1971
		/**
1972
		 * Ensure only one instance of the class is ever invoked.
1973
		 */
1974
		function load_tgm_plugin_activation() {
1975
			$GLOBALS['tgmpa'] = TGM_Plugin_Activation::get_instance();
1976
		}
1977
	}
1978
1979
	if ( did_action( 'plugins_loaded' ) ) {
1980
		load_tgm_plugin_activation();
1981
	} else {
1982
		add_action( 'plugins_loaded', 'load_tgm_plugin_activation' );
1983
	}
1984
}
1985
1986
if ( ! function_exists( 'tgmpa' ) ) {
1987
	/**
1988
	 * Helper function to register a collection of required plugins.
1989
	 *
1990
	 * @since 2.0.0
1991
	 * @api
1992
	 *
1993
	 * @param array $plugins An array of plugin arrays.
1994
	 * @param array $config  Optional. An array of configuration values.
1995
	 */
1996
	function tgmpa( $plugins, $config = array() ) {
1997
		$instance = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
1998
1999
		foreach ( $plugins as $plugin ) {
2000
			call_user_func( array( $instance, 'register' ), $plugin );
2001
		}
2002
2003
		if ( ! empty( $config ) && is_array( $config ) ) {
2004
			// Send out notices for deprecated arguments passed.
2005
			if ( isset( $config['notices'] ) ) {
2006
				_deprecated_argument( __FUNCTION__, '2.2.0', 'The `notices` config parameter was renamed to `has_notices` in TGMPA 2.2.0. Please adjust your configuration.' );
2007
				if ( ! isset( $config['has_notices'] ) ) {
2008
					$config['has_notices'] = $config['notices'];
2009
				}
2010
			}
2011
2012
			if ( isset( $config['parent_menu_slug'] ) ) {
2013
				_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.' );
2014
			}
2015
			if ( isset( $config['parent_url_slug'] ) ) {
2016
				_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.' );
2017
			}
2018
2019
			call_user_func( array( $instance, 'config' ), $config );
2020
		}
2021
	}
2022
}
2023
2024
/**
2025
 * WP_List_Table isn't always available. If it isn't available,
2026
 * we load it here.
2027
 *
2028
 * @since 2.2.0
2029
 */
2030
if ( ! class_exists( 'WP_List_Table' ) ) {
2031
	require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
2032
}
2033
2034
if ( ! class_exists( 'TGMPA_List_Table' ) ) {
2035
2036
	/**
2037
	 * List table class for handling plugins.
2038
	 *
2039
	 * Extends the WP_List_Table class to provide a future-compatible
2040
	 * way of listing out all required/recommended plugins.
2041
	 *
2042
	 * Gives users an interface similar to the Plugin Administration
2043
	 * area with similar (albeit stripped down) capabilities.
2044
	 *
2045
	 * This class also allows for the bulk install of plugins.
2046
	 *
2047
	 * @since 2.2.0
2048
	 *
2049
	 * @package TGM-Plugin-Activation
2050
	 * @author  Thomas Griffin
2051
	 * @author  Gary Jones
2052
	 */
2053
	class TGMPA_List_Table extends WP_List_Table {
2054
		/**
2055
		 * TGMPA instance.
2056
		 *
2057
		 * @since 2.5.0
2058
		 *
2059
		 * @var object
2060
		 */
2061
		protected $tgmpa;
2062
2063
		/**
2064
		 * The currently chosen view.
2065
		 *
2066
		 * @since 2.5.0
2067
		 *
2068
		 * @var string One of: 'all', 'install', 'update', 'activate'
2069
		 */
2070
		public $view_context = 'all';
2071
2072
		/**
2073
		 * The plugin counts for the various views.
2074
		 *
2075
		 * @since 2.5.0
2076
		 *
2077
		 * @var array
2078
		 */
2079
		protected $view_totals = array(
2080
			'all'      => 0,
2081
			'install'  => 0,
2082
			'update'   => 0,
2083
			'activate' => 0,
2084
		);
2085
2086
		/**
2087
		 * References parent constructor and sets defaults for class.
2088
		 *
2089
		 * @since 2.2.0
2090
		 */
2091
		public function __construct() {
2092
			$this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
2093
2094
			parent::__construct(
2095
				array(
2096
					'singular' => 'plugin',
2097
					'plural'   => 'plugins',
2098
					'ajax'     => false,
2099
				)
2100
			);
2101
2102
			if ( isset( $_REQUEST['plugin_status'] ) && in_array( $_REQUEST['plugin_status'], array( 'install', 'update', 'activate' ), true ) ) {
2103
				$this->view_context = sanitize_key( $_REQUEST['plugin_status'] );
2104
			}
2105
2106
			add_filter( 'tgmpa_table_data_items', array( $this, 'sort_table_items' ) );
2107
		}
2108
2109
		/**
2110
		 * Get a list of CSS classes for the <table> tag.
2111
		 *
2112
		 * Overruled to prevent the 'plural' argument from being added.
2113
		 *
2114
		 * @since 2.5.0
2115
		 *
2116
		 * @return array CSS classnames.
2117
		 */
2118
		public function get_table_classes() {
2119
			return array( 'widefat', 'fixed' );
2120
		}
2121
2122
		/**
2123
		 * Gathers and renames all of our plugin information to be used by WP_List_Table to create our table.
2124
		 *
2125
		 * @since 2.2.0
2126
		 *
2127
		 * @return array $table_data Information for use in table.
2128
		 */
2129
		protected function _gather_plugin_data() {
2130
			// Load thickbox for plugin links.
2131
			$this->tgmpa->admin_init();
2132
			$this->tgmpa->thickbox();
2133
2134
			// Categorize the plugins which have open actions.
2135
			$plugins = $this->categorize_plugins_to_views();
2136
2137
			// Set the counts for the view links.
2138
			$this->set_view_totals( $plugins );
2139
2140
			// Prep variables for use and grab list of all installed plugins.
2141
			$table_data = array();
2142
			$i          = 0;
2143
2144
			// Redirect to the 'all' view if no plugins were found for the selected view context.
2145
			if ( empty( $plugins[ $this->view_context ] ) ) {
2146
				$this->view_context = 'all';
2147
			}
2148
2149
			foreach ( $plugins[ $this->view_context ] as $slug => $plugin ) {
2150
				$table_data[ $i ]['sanitized_plugin']  = $plugin['name'];
2151
				$table_data[ $i ]['slug']              = $slug;
2152
				$table_data[ $i ]['plugin']            = '<strong>' . $this->tgmpa->get_info_link( $slug ) . '</strong>';
2153
				$table_data[ $i ]['source']            = $this->get_plugin_source_type_text( $plugin['source_type'] );
2154
				$table_data[ $i ]['type']              = $this->get_plugin_advise_type_text( $plugin['required'] );
2155
				$table_data[ $i ]['status']            = $this->get_plugin_status_text( $slug );
2156
				$table_data[ $i ]['installed_version'] = $this->tgmpa->get_installed_version( $slug );
2157
				$table_data[ $i ]['minimum_version']   = $plugin['version'];
2158
				$table_data[ $i ]['available_version'] = $this->tgmpa->does_plugin_have_update( $slug );
2159
2160
				// Prep the upgrade notice info.
2161
				$upgrade_notice = $this->tgmpa->get_upgrade_notice( $slug );
2162
				if ( ! empty( $upgrade_notice ) ) {
2163
					$table_data[ $i ]['upgrade_notice'] = $upgrade_notice;
2164
2165
					add_action( "tgmpa_after_plugin_row_$slug", array( $this, 'wp_plugin_update_row' ), 10, 2 );
2166
				}
2167
2168
				$table_data[ $i ] = apply_filters( 'tgmpa_table_data_item', $table_data[ $i ], $plugin );
2169
2170
				$i++;
2171
			}
2172
2173
			return $table_data;
2174
		}
2175
2176
		/**
2177
		 * Categorize the plugins which have open actions into views for the TGMPA page.
2178
		 *
2179
		 * @since 2.5.0
2180
		 */
2181
		protected function categorize_plugins_to_views() {
2182
			$plugins = array(
2183
				'all'      => array(), // Meaning: all plugins which still have open actions.
2184
				'install'  => array(),
2185
				'update'   => array(),
2186
				'activate' => array(),
2187
			);
2188
2189
			foreach ( $this->tgmpa->plugins as $slug => $plugin ) {
2190
				if ( $this->tgmpa->is_plugin_active( $slug ) && false === $this->tgmpa->does_plugin_have_update( $slug ) ) {
2191
					// No need to display plugins if they are installed, up-to-date and active.
2192
					continue;
2193
				} else {
2194
					$plugins['all'][ $slug ] = $plugin;
2195
2196
					if ( ! $this->tgmpa->is_plugin_installed( $slug ) ) {
2197
						$plugins['install'][ $slug ] = $plugin;
2198
					} else {
2199
						if ( false !== $this->tgmpa->does_plugin_have_update( $slug ) ) {
2200
							$plugins['update'][ $slug ] = $plugin;
2201
						}
2202
2203
						if ( $this->tgmpa->can_plugin_activate( $slug ) ) {
2204
							$plugins['activate'][ $slug ] = $plugin;
2205
						}
2206
					}
2207
				}
2208
			}
2209
2210
			return $plugins;
2211
		}
2212
2213
		/**
2214
		 * Set the counts for the view links.
2215
		 *
2216
		 * @since 2.5.0
2217
		 *
2218
		 * @param array $plugins Plugins order by view.
2219
		 */
2220
		protected function set_view_totals( $plugins ) {
2221
			foreach ( $plugins as $type => $list ) {
2222
				$this->view_totals[ $type ] = count( $list );
2223
			}
2224
		}
2225
2226
		/**
2227
		 * Get the plugin required/recommended text string.
2228
		 *
2229
		 * @since 2.5.0
2230
		 *
2231
		 * @param string $required Plugin required setting.
2232
		 * @return string
2233
		 */
2234
		protected function get_plugin_advise_type_text( $required ) {
2235
			if ( true === $required ) {
2236
				return __( 'Required', 'tgmpa' );
2237
			}
2238
2239
			return __( 'Recommended', 'tgmpa' );
2240
		}
2241
2242
		/**
2243
		 * Get the plugin source type text string.
2244
		 *
2245
		 * @since 2.5.0
2246
		 *
2247
		 * @param string $type Plugin type.
2248
		 * @return string
2249
		 */
2250
		protected function get_plugin_source_type_text( $type ) {
2251
			$string = '';
2252
2253
			switch ( $type ) {
2254
				case 'repo':
2255
					$string = __( 'WordPress Repository', 'tgmpa' );
2256
					break;
2257
				case 'external':
2258
					$string = __( 'External Source', 'tgmpa' );
2259
					break;
2260
				case 'bundled':
2261
					$string = __( 'Pre-Packaged', 'tgmpa' );
2262
					break;
2263
			}
2264
2265
			return $string;
2266
		}
2267
2268
		/**
2269
		 * Determine the plugin status message.
2270
		 *
2271
		 * @since 2.5.0
2272
		 *
2273
		 * @param string $slug Plugin slug.
2274
		 * @return string
2275
		 */
2276
		protected function get_plugin_status_text( $slug ) {
2277
			if ( ! $this->tgmpa->is_plugin_installed( $slug ) ) {
2278
				return __( 'Not Installed', 'tgmpa' );
2279
			}
2280
2281
			if ( ! $this->tgmpa->is_plugin_active( $slug ) ) {
2282
				$install_status = __( 'Installed But Not Activated', 'tgmpa' );
2283
			} else {
2284
				$install_status = __( 'Active', 'tgmpa' );
2285
			}
2286
2287
			$update_status = '';
2288
2289
			if ( $this->tgmpa->does_plugin_require_update( $slug ) && false === $this->tgmpa->does_plugin_have_update( $slug ) ) {
2290
				$update_status = __( 'Required Update not Available', 'tgmpa' );
2291
2292
			} elseif ( $this->tgmpa->does_plugin_require_update( $slug ) ) {
2293
				$update_status = __( 'Requires Update', 'tgmpa' );
2294
2295
			} elseif ( false !== $this->tgmpa->does_plugin_have_update( $slug ) ) {
2296
				$update_status = __( 'Update recommended', 'tgmpa' );
2297
			}
2298
2299
			if ( '' === $update_status ) {
2300
				return $install_status;
2301
			}
2302
2303
			return sprintf(
2304
				_x( '%1$s, %2$s', '%1$s = install status, %2$s = update status', 'tgmpa' ),
2305
				$install_status,
2306
				$update_status
2307
			);
2308
		}
2309
2310
		/**
2311
		 * Sort plugins by Required/Recommended type and by alphabetical plugin name within each type.
2312
		 *
2313
		 * @since 2.5.0
2314
		 *
2315
		 * @param array $items Prepared table items.
2316
		 * @return array Sorted table items.
2317
		 */
2318
		public function sort_table_items( $items ) {
2319
			$type = array();
2320
			$name = array();
2321
2322
			foreach ( $items as $i => $plugin ) {
2323
				$type[ $i ] = $plugin['type']; // Required / recommended.
2324
				$name[ $i ] = $plugin['sanitized_plugin'];
2325
			}
2326
2327
			array_multisort( $type, SORT_DESC, $name, SORT_ASC, $items );
2328
2329
			return $items;
2330
		}
2331
2332
		/**
2333
		 * Get an associative array ( id => link ) of the views available on this table.
2334
		 *
2335
		 * @since 2.5.0
2336
		 *
2337
		 * @return array
2338
		 */
2339
		public function get_views() {
2340
			$status_links = array();
2341
2342
			foreach ( $this->view_totals as $type => $count ) {
2343
				if ( $count < 1 ) {
2344
					continue;
2345
				}
2346
2347
				switch ( $type ) {
2348
					case 'all':
2349
						$text = _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $count, 'plugins', 'tgmpa' );
2350
						break;
2351
					case 'install':
2352
						$text = _n( 'To Install <span class="count">(%s)</span>', 'To Install <span class="count">(%s)</span>', $count, 'tgmpa' );
2353
						break;
2354
					case 'update':
2355
						$text = _n( 'Update Available <span class="count">(%s)</span>', 'Update Available <span class="count">(%s)</span>', $count, 'tgmpa' );
2356
						break;
2357
					case 'activate':
2358
						$text = _n( 'To Activate <span class="count">(%s)</span>', 'To Activate <span class="count">(%s)</span>', $count, 'tgmpa' );
2359
						break;
2360
					default:
2361
						$text = '';
2362
						break;
2363
				}
2364
2365
				if ( ! empty( $text ) ) {
2366
2367
					$status_links[ $type ] = sprintf(
2368
						'<a href="%s"%s>%s</a>',
2369
						esc_url( $this->tgmpa->get_tgmpa_status_url( $type ) ),
2370
						( $type === $this->view_context ) ? ' class="current"' : '',
2371
						sprintf( $text, number_format_i18n( $count ) )
2372
					);
2373
				}
2374
			}
2375
2376
			return $status_links;
2377
		}
2378
2379
		/**
2380
		 * Create default columns to display important plugin information
2381
		 * like type, action and status.
2382
		 *
2383
		 * @since 2.2.0
2384
		 *
2385
		 * @param array  $item        Array of item data.
2386
		 * @param string $column_name The name of the column.
2387
		 * @return string
2388
		 */
2389
		public function column_default( $item, $column_name ) {
2390
			return $item[ $column_name ];
2391
		}
2392
2393
		/**
2394
		 * Required for bulk installing.
2395
		 *
2396
		 * Adds a checkbox for each plugin.
2397
		 *
2398
		 * @since 2.2.0
2399
		 *
2400
		 * @param array $item Array of item data.
2401
		 * @return string The input checkbox with all necessary info.
2402
		 */
2403
		public function column_cb( $item ) {
2404
			return sprintf(
2405
				'<input type="checkbox" name="%1$s[]" value="%2$s" id="%3$s" />',
2406
				esc_attr( $this->_args['singular'] ),
2407
				esc_attr( $item['slug'] ),
2408
				esc_attr( $item['sanitized_plugin'] )
2409
			);
2410
		}
2411
2412
		/**
2413
		 * Create default title column along with the action links.
2414
		 *
2415
		 * @since 2.2.0
2416
		 *
2417
		 * @param array $item Array of item data.
2418
		 * @return string The plugin name and action links.
2419
		 */
2420
		public function column_plugin( $item ) {
2421
			return sprintf(
2422
				'%1$s %2$s',
2423
				$item['plugin'],
2424
				$this->row_actions( $this->get_row_actions( $item ), true )
2425
			);
2426
		}
2427
2428
		/**
2429
		 * Create version information column.
2430
		 *
2431
		 * @since 2.5.0
2432
		 *
2433
		 * @param array $item Array of item data.
2434
		 * @return string HTML-formatted version information.
2435
		 */
2436
		public function column_version( $item ) {
2437
			$output = array();
2438
2439
			if ( $this->tgmpa->is_plugin_installed( $item['slug'] ) ) {
2440
				$installed = ! empty( $item['installed_version'] ) ? $item['installed_version'] : _x( 'unknown', 'as in: "version nr unknown"', 'tgmpa' );
2441
2442
				$color = '';
2443
				if ( ! empty( $item['minimum_version'] ) && $this->tgmpa->does_plugin_require_update( $item['slug'] ) ) {
2444
					$color = ' color: #ff0000; font-weight: bold;';
2445
				}
2446
2447
				$output[] = sprintf(
2448
					'<p><span style="min-width: 32px; text-align: right; float: right;%1$s">%2$s</span>' . __( 'Installed version:', 'tgmpa' ) . '</p>',
2449
					$color,
2450
					$installed
2451
				);
2452
			}
2453
2454
			if ( ! empty( $item['minimum_version'] ) ) {
2455
				$output[] = sprintf(
2456
					'<p><span style="min-width: 32px; text-align: right; float: right;">%1$s</span>' . __( 'Minimum required version:', 'tgmpa' ) . '</p>',
2457
					$item['minimum_version']
2458
				);
2459
			}
2460
2461
			if ( ! empty( $item['available_version'] ) ) {
2462
				$color = '';
2463
				if ( ! empty( $item['minimum_version'] ) && version_compare( $item['available_version'], $item['minimum_version'], '>=' ) ) {
2464
					$color = ' color: #71C671; font-weight: bold;';
2465
				}
2466
2467
				$output[] = sprintf(
2468
					'<p><span style="min-width: 32px; text-align: right; float: right;%1$s">%2$s</span>' . __( 'Available version:', 'tgmpa' ) . '</p>',
2469
					$color,
2470
					$item['available_version']
2471
				);
2472
			}
2473
2474
			if ( empty( $output ) ) {
2475
				return '&nbsp;'; // Let's not break the table layout.
2476
			} else {
2477
				return implode( "\n", $output );
2478
			}
2479
		}
2480
2481
		/**
2482
		 * Sets default message within the plugins table if no plugins
2483
		 * are left for interaction.
2484
		 *
2485
		 * Hides the menu item to prevent the user from clicking and
2486
		 * getting a permissions error.
2487
		 *
2488
		 * @since 2.2.0
2489
		 */
2490
		public function no_items() {
2491
			printf( wp_kses_post( __( 'No plugins to install, update or activate. <a href="%1$s">Return to the Dashboard</a>', 'tgmpa' ) ), esc_url( self_admin_url() ) );
2492
			echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>';
2493
		}
2494
2495
		/**
2496
		 * Output all the column information within the table.
2497
		 *
2498
		 * @since 2.2.0
2499
		 *
2500
		 * @return array $columns The column names.
2501
		 */
2502
		public function get_columns() {
2503
			$columns = array(
2504
				'cb'     => '<input type="checkbox" />',
2505
				'plugin' => __( 'Plugin', 'tgmpa' ),
2506
				'source' => __( 'Source', 'tgmpa' ),
2507
				'type'   => __( 'Type', 'tgmpa' ),
2508
			);
2509
2510
			if ( 'all' === $this->view_context || 'update' === $this->view_context ) {
2511
				$columns['version'] = __( 'Version', 'tgmpa' );
2512
				$columns['status']  = __( 'Status', 'tgmpa' );
2513
			}
2514
2515
			return apply_filters( 'tgmpa_table_columns', $columns );
2516
		}
2517
2518
		/**
2519
		 * Get name of default primary column
2520
		 *
2521
		 * @since 2.5.0 / WP 4.3+ compatibility
2522
		 * @access protected
2523
		 *
2524
		 * @return string
2525
		 */
2526
		protected function get_default_primary_column_name() {
2527
			return 'plugin';
2528
		}
2529
2530
		/**
2531
		 * Get the name of the primary column.
2532
		 *
2533
		 * @since 2.5.0 / WP 4.3+ compatibility
2534
		 * @access protected
2535
		 *
2536
		 * @return string The name of the primary column.
2537
		 */
2538
		protected function get_primary_column_name() {
2539
			if ( method_exists( 'WP_List_Table', 'get_primary_column_name' ) ) {
2540
				return parent::get_primary_column_name();
2541
			} else {
2542
				return $this->get_default_primary_column_name();
2543
			}
2544
		}
2545
2546
		/**
2547
		 * Get the actions which are relevant for a specific plugin row.
2548
		 *
2549
		 * @since 2.5.0
2550
		 *
2551
		 * @param array $item Array of item data.
2552
		 * @return array Array with relevant action links.
2553
		 */
2554
		protected function get_row_actions( $item ) {
2555
			$actions      = array();
2556
			$action_links = array();
2557
2558
			// Display the 'Install' action link if the plugin is not yet available.
2559
			if ( ! $this->tgmpa->is_plugin_installed( $item['slug'] ) ) {
2560
				$actions['install'] = _x( 'Install %2$s', '%2$s = plugin name in screen reader markup', 'tgmpa' );
2561
			} else {
2562
				// Display the 'Update' action link if an update is available and WP complies with plugin minimum.
2563
				if ( false !== $this->tgmpa->does_plugin_have_update( $item['slug'] ) && $this->tgmpa->can_plugin_update( $item['slug'] ) ) {
2564
					$actions['update'] = _x( 'Update %2$s', '%2$s = plugin name in screen reader markup', 'tgmpa' );
2565
				}
2566
2567
				// Display the 'Activate' action link, but only if the plugin meets the minimum version.
2568
				if ( $this->tgmpa->can_plugin_activate( $item['slug'] ) ) {
2569
					$actions['activate'] = _x( 'Activate %2$s', '%2$s = plugin name in screen reader markup', 'tgmpa' );
2570
				}
2571
			}
2572
2573
			// Create the actual links.
2574
			foreach ( $actions as $action => $text ) {
2575
				$nonce_url = wp_nonce_url(
2576
					add_query_arg(
2577
						array(
2578
							'plugin'           => urlencode( $item['slug'] ),
2579
							'tgmpa-' . $action => $action . '-plugin',
2580
						),
2581
						$this->tgmpa->get_tgmpa_url()
2582
					),
2583
					'tgmpa-' . $action,
2584
					'tgmpa-nonce'
2585
				);
2586
2587
				$action_links[ $action ] = sprintf(
2588
					'<a href="%1$s">' . esc_html( $text ) . '</a>',
2589
					esc_url( $nonce_url ),
2590
					'<span class="screen-reader-text">' . esc_html( $item['sanitized_plugin'] ) . '</span>'
2591
				);
2592
			}
2593
2594
			$prefix = ( defined( 'WP_NETWORK_ADMIN' ) && WP_NETWORK_ADMIN ) ? 'network_admin_' : '';
2595
			return apply_filters( "tgmpa_{$prefix}plugin_action_links", array_filter( $action_links ), $item['slug'], $item, $this->view_context );
2596
		}
2597
2598
		/**
2599
		 * Generates content for a single row of the table.
2600
		 *
2601
		 * @since 2.5.0
2602
		 *
2603
		 * @param object $item The current item.
2604
		 */
2605
		public function single_row( $item ) {
2606
			parent::single_row( $item );
2607
2608
			/**
2609
			 * Fires after each specific row in the TGMPA Plugins list table.
2610
			 *
2611
			 * The dynamic portion of the hook name, `$item['slug']`, refers to the slug
2612
			 * for the plugin.
2613
			 *
2614
			 * @since 2.5.0
2615
			 */
2616
			do_action( "tgmpa_after_plugin_row_{$item['slug']}", $item['slug'], $item, $this->view_context );
2617
		}
2618
2619
		/**
2620
		 * Show the upgrade notice below a plugin row if there is one.
2621
		 *
2622
		 * @since 2.5.0
2623
		 *
2624
		 * @see /wp-admin/includes/update.php
2625
		 *
2626
		 * @param string $slug Plugin slug.
2627
		 * @param array  $item The information available in this table row.
2628
		 * @return null Return early if upgrade notice is empty.
2629
		 */
2630
		public function wp_plugin_update_row( $slug, $item ) {
2631
			if ( empty( $item['upgrade_notice'] ) ) {
2632
				return;
2633
			}
2634
2635
			echo '
2636
				<tr class="plugin-update-tr">
2637
					<td colspan="', absint( $this->get_column_count() ), '" class="plugin-update colspanchange">
2638
						<div class="update-message">',
2639
							esc_html__( 'Upgrade message from the plugin author:', 'tgmpa' ),
2640
							' <strong>', wp_kses_data( $item['upgrade_notice'] ), '</strong>
2641
						</div>
2642
					</td>
2643
				</tr>';
2644
		}
2645
2646
		/**
2647
		 * Extra controls to be displayed between bulk actions and pagination.
2648
		 *
2649
		 * @since 2.5.0
2650
		 *
2651
		 * @param string $which 'top' or 'bottom' table navigation.
2652
		 */
2653
		public function extra_tablenav( $which ) {
2654
			if ( 'bottom' === $which ) {
2655
				$this->tgmpa->show_tgmpa_version();
2656
			}
2657
		}
2658
2659
		/**
2660
		 * Defines the bulk actions for handling registered plugins.
2661
		 *
2662
		 * @since 2.2.0
2663
		 *
2664
		 * @return array $actions The bulk actions for the plugin install table.
2665
		 */
2666
		public function get_bulk_actions() {
2667
2668
			$actions = array();
2669
2670
			if ( 'update' !== $this->view_context && 'activate' !== $this->view_context ) {
2671
				if ( current_user_can( 'install_plugins' ) ) {
2672
					$actions['tgmpa-bulk-install'] = __( 'Install', 'tgmpa' );
2673
				}
2674
			}
2675
2676
			if ( 'install' !== $this->view_context ) {
2677
				if ( current_user_can( 'update_plugins' ) ) {
2678
					$actions['tgmpa-bulk-update'] = __( 'Update', 'tgmpa' );
2679
				}
2680
				if ( current_user_can( 'activate_plugins' ) ) {
2681
					$actions['tgmpa-bulk-activate'] = __( 'Activate', 'tgmpa' );
2682
				}
2683
			}
2684
2685
			return $actions;
2686
		}
2687
2688
		/**
2689
		 * Processes bulk installation and activation actions.
2690
		 *
2691
		 * The bulk installation process looks for the $_POST information and passes that
2692
		 * through if a user has to use WP_Filesystem to enter their credentials.
2693
		 *
2694
		 * @since 2.2.0
2695
		 */
2696
		public function process_bulk_actions() {
2697
			// Bulk installation process.
2698
			if ( 'tgmpa-bulk-install' === $this->current_action() || 'tgmpa-bulk-update' === $this->current_action() ) {
2699
2700
				check_admin_referer( 'bulk-' . $this->_args['plural'] );
2701
2702
				$install_type = 'install';
2703
				if ( 'tgmpa-bulk-update' === $this->current_action() ) {
2704
					$install_type = 'update';
2705
				}
2706
2707
				$plugins_to_install = array();
2708
2709
				// Did user actually select any plugins to install/update ?
2710 View Code Duplication
				if ( empty( $_POST['plugin'] ) ) {
2711
					if ( 'install' === $install_type ) {
2712
						$message = __( 'No plugins were selected to be installed. No action taken.', 'tgmpa' );
2713
					} else {
2714
						$message = __( 'No plugins were selected to be updated. No action taken.', 'tgmpa' );
2715
					}
2716
2717
					echo '<div id="message" class="error"><p>', esc_html( $message ), '</p></div>';
2718
2719
					return false;
2720
				}
2721
2722
				if ( is_array( $_POST['plugin'] ) ) {
2723
					$plugins_to_install = (array) $_POST['plugin'];
2724
				} elseif ( is_string( $_POST['plugin'] ) ) {
2725
					// Received via Filesystem page - un-flatten array (WP bug #19643).
2726
					$plugins_to_install = explode( ',', $_POST['plugin'] );
2727
				}
2728
2729
				// Sanitize the received input.
2730
				$plugins_to_install = array_map( 'urldecode', $plugins_to_install );
2731
				$plugins_to_install = array_map( array( $this->tgmpa, 'sanitize_key' ), $plugins_to_install );
2732
2733
				// Validate the received input.
2734
				foreach ( $plugins_to_install as $key => $slug ) {
2735
					// Check if the plugin was registered with TGMPA and remove if not.
2736
					if ( ! isset( $this->tgmpa->plugins[ $slug ] ) ) {
2737
						unset( $plugins_to_install[ $key ] );
2738
						continue;
2739
					}
2740
2741
					// For install: make sure this is a plugin we *can* install and not one already installed.
2742
					if ( 'install' === $install_type && true === $this->tgmpa->is_plugin_installed( $slug ) ) {
2743
						unset( $plugins_to_install[ $key ] );
2744
					}
2745
2746
					// For updates: make sure this is a plugin we *can* update (update available and WP version ok).
2747
					if ( 'update' === $install_type && false === $this->tgmpa->is_plugin_updatetable( $slug ) ) {
2748
						unset( $plugins_to_install[ $key ] );
2749
					}
2750
				}
2751
2752
				// No need to proceed further if we have no plugins to handle.
2753 View Code Duplication
				if ( empty( $plugins_to_install ) ) {
2754
					if ( 'install' === $install_type ) {
2755
						$message = __( 'No plugins are available to be installed at this time.', 'tgmpa' );
2756
					} else {
2757
						$message = __( 'No plugins are available to be updated at this time.', 'tgmpa' );
2758
					}
2759
2760
					echo '<div id="message" class="error"><p>', esc_html( $message ), '</p></div>';
2761
2762
					return false;
2763
				}
2764
2765
				// Pass all necessary information if WP_Filesystem is needed.
2766
				$url = wp_nonce_url(
2767
					$this->tgmpa->get_tgmpa_url(),
2768
					'bulk-' . $this->_args['plural']
2769
				);
2770
2771
				// Give validated data back to $_POST which is the only place the filesystem looks for extra fields.
2772
				$_POST['plugin'] = implode( ',', $plugins_to_install ); // Work around for WP bug #19643.
2773
2774
				$method = ''; // Leave blank so WP_Filesystem can populate it as necessary.
2775
				$fields = array_keys( $_POST ); // Extra fields to pass to WP_Filesystem.
2776
2777 View Code Duplication
				if ( false === ( $creds = request_filesystem_credentials( esc_url_raw( $url ), $method, false, false, $fields ) ) ) {
2778
					return true; // Stop the normal page form from displaying, credential request form will be shown.
2779
				}
2780
2781
				// Now we have some credentials, setup WP_Filesystem.
2782 View Code Duplication
				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...
2783
					// Our credentials were no good, ask the user for them again.
2784
					request_filesystem_credentials( esc_url_raw( $url ), $method, true, false, $fields );
2785
2786
					return true;
2787
				}
2788
2789
				/* If we arrive here, we have the filesystem */
2790
2791
				// Store all information in arrays since we are processing a bulk installation.
2792
				$names      = array();
2793
				$sources    = array(); // Needed for installs.
2794
				$file_paths = array(); // Needed for upgrades.
2795
				$to_inject  = array(); // Information to inject into the update_plugins transient.
2796
2797
				// Prepare the data for validated plugins for the install/upgrade.
2798
				foreach ( $plugins_to_install as $slug ) {
2799
					$name   = $this->tgmpa->plugins[ $slug ]['name'];
2800
					$source = $this->tgmpa->get_download_url( $slug );
2801
2802
					if ( ! empty( $name ) && ! empty( $source ) ) {
2803
						$names[] = $name;
2804
2805
						switch ( $install_type ) {
2806
2807
							case 'install':
2808
								$sources[] = $source;
2809
								break;
2810
2811
							case 'update':
2812
								$file_paths[]                 = $this->tgmpa->plugins[ $slug ]['file_path'];
2813
								$to_inject[ $slug ]           = $this->tgmpa->plugins[ $slug ];
2814
								$to_inject[ $slug ]['source'] = $source;
2815
								break;
2816
						}
2817
					}
2818
				}
2819
				unset( $slug, $name, $source );
2820
2821
				// Create a new instance of TGMPA_Bulk_Installer.
2822
				$installer = new TGMPA_Bulk_Installer(
2823
					new TGMPA_Bulk_Installer_Skin(
2824
						array(
2825
							'url'          => esc_url_raw( $this->tgmpa->get_tgmpa_url() ),
2826
							'nonce'        => 'bulk-' . $this->_args['plural'],
2827
							'names'        => $names,
2828
							'install_type' => $install_type,
2829
						)
2830
					)
2831
				);
2832
2833
				// Wrap the install process with the appropriate HTML.
2834
				echo '<div class="tgmpa">',
2835
					'<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>
2836
					<div class="update-php" style="width: 100%; height: 98%; min-height: 850px; padding-top: 1px;">';
2837
2838
				// Process the bulk installation submissions.
2839
				add_filter( 'upgrader_source_selection', array( $this->tgmpa, 'maybe_adjust_source_dir' ), 1, 3 );
2840
2841
				if ( 'tgmpa-bulk-update' === $this->current_action() ) {
2842
					// Inject our info into the update transient.
2843
					$this->tgmpa->inject_update_info( $to_inject );
2844
2845
					$installer->bulk_upgrade( $file_paths );
2846
				} else {
2847
					$installer->bulk_install( $sources );
2848
				}
2849
2850
				remove_filter( 'upgrader_source_selection', array( $this->tgmpa, 'maybe_adjust_source_dir' ), 1, 3 );
2851
2852
				echo '</div></div>';
2853
2854
				return true;
2855
			}
2856
2857
			// Bulk activation process.
2858
			if ( 'tgmpa-bulk-activate' === $this->current_action() ) {
2859
				check_admin_referer( 'bulk-' . $this->_args['plural'] );
2860
2861
				// Did user actually select any plugins to activate ?
2862
				if ( empty( $_POST['plugin'] ) ) {
2863
					echo '<div id="message" class="error"><p>', esc_html__( 'No plugins were selected to be activated. No action taken.', 'tgmpa' ), '</p></div>';
2864
2865
					return false;
2866
				}
2867
2868
				// Grab plugin data from $_POST.
2869
				$plugins = array();
2870
				if ( isset( $_POST['plugin'] ) ) {
2871
					$plugins = array_map( 'urldecode', (array) $_POST['plugin'] );
2872
					$plugins = array_map( array( $this->tgmpa, 'sanitize_key' ), $plugins );
2873
				}
2874
2875
				$plugins_to_activate = array();
2876
				$plugin_names        = array();
2877
2878
				// Grab the file paths for the selected & inactive plugins from the registration array.
2879
				foreach ( $plugins as $slug ) {
2880
					if ( $this->tgmpa->can_plugin_activate( $slug ) ) {
2881
						$plugins_to_activate[] = $this->tgmpa->plugins[ $slug ]['file_path'];
2882
						$plugin_names[]        = $this->tgmpa->plugins[ $slug ]['name'];
2883
					}
2884
				}
2885
				unset( $slug );
2886
2887
				// Return early if there are no plugins to activate.
2888
				if ( empty( $plugins_to_activate ) ) {
2889
					echo '<div id="message" class="error"><p>', esc_html__( 'No plugins are available to be activated at this time.', 'tgmpa' ), '</p></div>';
2890
2891
					return false;
2892
				}
2893
2894
				// Now we are good to go - let's start activating plugins.
2895
				$activate = activate_plugins( $plugins_to_activate );
2896
2897
				if ( is_wp_error( $activate ) ) {
2898
					echo '<div id="message" class="error"><p>', wp_kses_post( $activate->get_error_message() ), '</p></div>';
2899
				} else {
2900
					$count        = count( $plugin_names ); // Count so we can use _n function.
2901
					$plugin_names = array_map( array( 'TGMPA_Utils', 'wrap_in_strong' ), $plugin_names );
2902
					$last_plugin  = array_pop( $plugin_names ); // Pop off last name to prep for readability.
2903
					$imploded     = empty( $plugin_names ) ? $last_plugin : ( implode( ', ', $plugin_names ) . ' ' . esc_html_x( 'and', 'plugin A *and* plugin B', 'tgmpa' ) . ' ' . $last_plugin );
2904
2905
					printf( // WPCS: xss ok.
2906
						'<div id="message" class="updated"><p>%1$s %2$s.</p></div>',
2907
						esc_html( _n( 'The following plugin was activated successfully:', 'The following plugins were activated successfully:', $count, 'tgmpa' ) ),
2908
						$imploded
2909
					);
2910
2911
					// Update recently activated plugins option.
2912
					$recent = (array) get_option( 'recently_activated' );
2913
					foreach ( $plugins_to_activate as $plugin => $time ) {
2914
						if ( isset( $recent[ $plugin ] ) ) {
2915
							unset( $recent[ $plugin ] );
2916
						}
2917
					}
2918
					update_option( 'recently_activated', $recent );
2919
				}
2920
2921
				unset( $_POST ); // Reset the $_POST variable in case user wants to perform one action after another.
2922
2923
				return true;
2924
			}
2925
2926
			return false;
2927
		}
2928
2929
		/**
2930
		 * Prepares all of our information to be outputted into a usable table.
2931
		 *
2932
		 * @since 2.2.0
2933
		 */
2934
		public function prepare_items() {
2935
			$columns               = $this->get_columns(); // Get all necessary column information.
2936
			$hidden                = array(); // No columns to hide, but we must set as an array.
2937
			$sortable              = array(); // No reason to make sortable columns.
2938
			$primary               = $this->get_primary_column_name(); // Column which has the row actions.
2939
			$this->_column_headers = array( $columns, $hidden, $sortable, $primary ); // Get all necessary column headers.
2940
2941
			// Process our bulk activations here.
2942
			if ( 'tgmpa-bulk-activate' === $this->current_action() ) {
2943
				$this->process_bulk_actions();
2944
			}
2945
2946
			// Store all of our plugin data into $items array so WP_List_Table can use it.
2947
			$this->items = apply_filters( 'tgmpa_table_data_items', $this->_gather_plugin_data() );
2948
		}
2949
2950
		/* *********** DEPRECATED METHODS *********** */
2951
2952
		/**
2953
		 * Retrieve plugin data, given the plugin name.
2954
		 *
2955
		 * @since      2.2.0
2956
		 * @deprecated 2.5.0 use {@see TGM_Plugin_Activation::_get_plugin_data_from_name()} instead.
2957
		 * @see        TGM_Plugin_Activation::_get_plugin_data_from_name()
2958
		 *
2959
		 * @param string $name Name of the plugin, as it was registered.
2960
		 * @param string $data Optional. Array key of plugin data to return. Default is slug.
2961
		 * @return string|boolean Plugin slug if found, false otherwise.
2962
		 */
2963
		protected function _get_plugin_data_from_name( $name, $data = 'slug' ) {
2964
			_deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'TGM_Plugin_Activation::_get_plugin_data_from_name()' );
2965
2966
			return $this->tgmpa->_get_plugin_data_from_name( $name, $data );
2967
		}
2968
	}
2969
}
2970
2971
2972
if ( ! class_exists( 'TGM_Bulk_Installer' ) ) {
2973
2974
	/**
2975
	 * Hack: Prevent TGMPA v2.4.1- bulk installer class from being loaded if 2.4.1- is loaded after 2.5+.
2976
	 */
2977
	class TGM_Bulk_Installer {
2978
	}
2979
}
2980
if ( ! class_exists( 'TGM_Bulk_Installer_Skin' ) ) {
2981
2982
	/**
2983
	 * Hack: Prevent TGMPA v2.4.1- bulk installer skin class from being loaded if 2.4.1- is loaded after 2.5+.
2984
	 */
2985
	class TGM_Bulk_Installer_Skin {
2986
	}
2987
}
2988
2989
/**
2990
 * The WP_Upgrader file isn't always available. If it isn't available,
2991
 * we load it here.
2992
 *
2993
 * We check to make sure no action or activation keys are set so that WordPress
2994
 * does not try to re-include the class when processing upgrades or installs outside
2995
 * of the class.
2996
 *
2997
 * @since 2.2.0
2998
 */
2999
add_action( 'admin_init', 'tgmpa_load_bulk_installer' );
3000
if ( ! function_exists( 'tgmpa_load_bulk_installer' ) ) {
3001
	/**
3002
	 * Load bulk installer
3003
	 */
3004
	function tgmpa_load_bulk_installer() {
3005
		// Silently fail if 2.5+ is loaded *after* an older version.
3006
		if ( ! isset( $GLOBALS['tgmpa'] ) ) {
3007
			return;
3008
		}
3009
3010
		// Get TGMPA class instance.
3011
		$tgmpa_instance = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
3012
3013
		if ( isset( $_GET['page'] ) && $tgmpa_instance->menu === $_GET['page'] ) {
3014
			if ( ! class_exists( 'Plugin_Upgrader', false ) ) {
3015
				require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
3016
			}
3017
3018
			if ( ! class_exists( 'TGMPA_Bulk_Installer' ) ) {
3019
3020
				/**
3021
				 * Installer class to handle bulk plugin installations.
3022
				 *
3023
				 * Extends WP_Upgrader and customizes to suit the installation of multiple
3024
				 * plugins.
3025
				 *
3026
				 * @since 2.2.0
3027
				 *
3028
				 * @internal Since 2.5.0 the class is an extension of Plugin_Upgrader rather than WP_Upgrader
3029
				 * @internal Since 2.5.2 the class has been renamed from TGM_Bulk_Installer to TGMPA_Bulk_Installer.
3030
				 *           This was done to prevent backward compatibility issues with v2.3.6.
3031
				 *
3032
				 * @package TGM-Plugin-Activation
3033
				 * @author  Thomas Griffin
3034
				 * @author  Gary Jones
3035
				 */
3036
				class TGMPA_Bulk_Installer extends Plugin_Upgrader {
3037
					/**
3038
					 * Holds result of bulk plugin installation.
3039
					 *
3040
					 * @since 2.2.0
3041
					 *
3042
					 * @var string
3043
					 */
3044
					public $result;
3045
3046
					/**
3047
					 * Flag to check if bulk installation is occurring or not.
3048
					 *
3049
					 * @since 2.2.0
3050
					 *
3051
					 * @var boolean
3052
					 */
3053
					public $bulk = false;
3054
3055
					/**
3056
					 * TGMPA instance
3057
					 *
3058
					 * @since 2.5.0
3059
					 *
3060
					 * @var object
3061
					 */
3062
					protected $tgmpa;
3063
3064
					/**
3065
					 * Whether or not the destination directory needs to be cleared ( = on update).
3066
					 *
3067
					 * @since 2.5.0
3068
					 *
3069
					 * @var bool
3070
					 */
3071
					protected $clear_destination = false;
3072
3073
					/**
3074
					 * References parent constructor and sets defaults for class.
3075
					 *
3076
					 * @since 2.2.0
3077
					 *
3078
					 * @param \Bulk_Upgrader_Skin|null $skin Installer skin.
3079
					 */
3080
					public function __construct( $skin = null ) {
3081
						// Get TGMPA class instance.
3082
						$this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
3083
3084
						parent::__construct( $skin );
3085
3086
						if ( isset( $this->skin->options['install_type'] ) && 'update' === $this->skin->options['install_type'] ) {
3087
							$this->clear_destination = true;
3088
						}
3089
3090
						if ( $this->tgmpa->is_automatic ) {
3091
							$this->activate_strings();
3092
						}
3093
3094
						add_action( 'upgrader_process_complete', array( $this->tgmpa, 'populate_file_path' ) );
3095
					}
3096
3097
					/**
3098
					 * Sets the correct activation strings for the installer skin to use.
3099
					 *
3100
					 * @since 2.2.0
3101
					 */
3102
					public function activate_strings() {
3103
						$this->strings['activation_failed']  = __( 'Plugin activation failed.', 'tgmpa' );
3104
						$this->strings['activation_success'] = __( 'Plugin activated successfully.', 'tgmpa' );
3105
					}
3106
3107
					/**
3108
					 * Performs the actual installation of each plugin.
3109
					 *
3110
					 * @since 2.2.0
3111
					 *
3112
					 * @see WP_Upgrader::run()
3113
					 *
3114
					 * @param array $options The installation config options.
3115
					 * @return null|array Return early if error, array of installation data on success.
3116
					 */
3117
					public function run( $options ) {
3118
						$result = parent::run( $options );
3119
3120
						// Reset the strings in case we changed one during automatic activation.
3121
						if ( $this->tgmpa->is_automatic ) {
3122
							if ( 'update' === $this->skin->options['install_type'] ) {
3123
								$this->upgrade_strings();
3124
							} else {
3125
								$this->install_strings();
3126
							}
3127
						}
3128
3129
						return $result;
3130
					}
3131
3132
					/**
3133
					 * Processes the bulk installation of plugins.
3134
					 *
3135
					 * @since 2.2.0
3136
					 *
3137
					 * @internal This is basically a near identical copy of the WP Core Plugin_Upgrader::bulk_upgrade()
3138
					 * method, with minor adjustments to deal with new installs instead of upgrades.
3139
					 * For ease of future synchronizations, the adjustments are clearly commented, but no other
3140
					 * comments are added. Code style has been made to comply.
3141
					 *
3142
					 * @see Plugin_Upgrader::bulk_upgrade()
3143
					 * @see https://core.trac.wordpress.org/browser/tags/4.2.1/src/wp-admin/includes/class-wp-upgrader.php#L838
3144
					 *
3145
					 * @param array $plugins The plugin sources needed for installation.
3146
					 * @param array $args    Arbitrary passed extra arguments.
3147
					 * @return string|bool Install confirmation messages on success, false on failure.
3148
					 */
3149
					public function bulk_install( $plugins, $args = array() ) {
3150
						// [TGMPA + ] Hook auto-activation in.
3151
						add_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3152
3153
						$defaults    = array(
3154
							'clear_update_cache' => true,
3155
						);
3156
						$parsed_args = wp_parse_args( $args, $defaults );
3157
3158
						$this->init();
3159
						$this->bulk = true;
3160
3161
						$this->install_strings(); // [TGMPA + ] adjusted.
3162
3163
						/* [TGMPA - ] $current = get_site_transient( 'update_plugins' ); */
3164
3165
						/* [TGMPA - ] add_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'), 10, 4); */
3166
3167
						$this->skin->header();
3168
3169
						// Connect to the Filesystem first.
3170
						$res = $this->fs_connect( array( WP_CONTENT_DIR, WP_PLUGIN_DIR ) );
3171
						if ( ! $res ) {
3172
							$this->skin->footer();
3173
3174
							return false;
3175
						}
3176
3177
						$this->skin->bulk_header();
3178
3179
						// Only start maintenance mode if:
3180
						// - running Multisite and there are one or more plugins specified, OR
3181
						// - a plugin with an update available is currently active.
3182
						// @TODO: For multisite, maintenance mode should only kick in for individual sites if at all possible.
3183
						$maintenance = ( is_multisite() && ! empty( $plugins ) );
3184
3185
						/*
1 ignored issue
show
Unused Code Comprehensibility introduced by
49% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
3186
						[TGMPA - ]
3187
						foreach ( $plugins as $plugin )
3188
							$maintenance = $maintenance || ( is_plugin_active( $plugin ) && isset( $current->response[ $plugin] ) );
3189
						*/
3190
						if ( $maintenance ) {
3191
							$this->maintenance_mode( true );
3192
						}
3193
3194
						$results = array();
3195
3196
						$this->update_count   = count( $plugins );
3197
						$this->update_current = 0;
3198
						foreach ( $plugins as $plugin ) {
3199
							$this->update_current++;
3200
3201
							/*
1 ignored issue
show
Unused Code Comprehensibility introduced by
49% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
3202
							[TGMPA - ]
3203
							$this->skin->plugin_info = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin, false, true);
3204
3205
							if ( !isset( $current->response[ $plugin ] ) ) {
3206
								$this->skin->set_result('up_to_date');
3207
								$this->skin->before();
3208
								$this->skin->feedback('up_to_date');
3209
								$this->skin->after();
3210
								$results[$plugin] = true;
3211
								continue;
3212
							}
3213
3214
							// Get the URL to the zip file
3215
							$r = $current->response[ $plugin ];
3216
3217
							$this->skin->plugin_active = is_plugin_active($plugin);
3218
							*/
3219
3220
							$result = $this->run(
3221
								array(
3222
									'package'           => $plugin, // [TGMPA + ] adjusted.
3223
									'destination'       => WP_PLUGIN_DIR,
3224
									'clear_destination' => false, // [TGMPA + ] adjusted.
3225
									'clear_working'     => true,
3226
									'is_multi'          => true,
3227
									'hook_extra'        => array(
3228
										'plugin' => $plugin,
3229
									),
3230
								)
3231
							);
3232
3233
							$results[ $plugin ] = $this->result;
3234
3235
							// Prevent credentials auth screen from displaying multiple times.
3236
							if ( false === $result ) {
3237
								break;
3238
							}
3239
						} //end foreach $plugins
3240
3241
						$this->maintenance_mode( false );
3242
3243
						/**
3244
						 * Fires when the bulk upgrader process is complete.
3245
						 *
3246
						 * @since WP 3.6.0 / TGMPA 2.5.0
3247
						 *
3248
						 * @param Plugin_Upgrader $this Plugin_Upgrader instance. In other contexts, $this, might
3249
						 *                              be a Theme_Upgrader or Core_Upgrade instance.
3250
						 * @param array           $data {
3251
						 *     Array of bulk item update data.
3252
						 *
3253
						 *     @type string $action   Type of action. Default 'update'.
3254
						 *     @type string $type     Type of update process. Accepts 'plugin', 'theme', or 'core'.
3255
						 *     @type bool   $bulk     Whether the update process is a bulk update. Default true.
3256
						 *     @type array  $packages Array of plugin, theme, or core packages to update.
3257
						 * }
3258
						 */
3259
						do_action( 'upgrader_process_complete', $this, array(
3260
							'action'  => 'install', // [TGMPA + ] adjusted.
3261
							'type'    => 'plugin',
3262
							'bulk'    => true,
3263
							'plugins' => $plugins,
3264
						) );
3265
3266
						$this->skin->bulk_footer();
3267
3268
						$this->skin->footer();
3269
3270
						// Cleanup our hooks, in case something else does a upgrade on this connection.
3271
						/* [TGMPA - ] remove_filter('upgrader_clear_destination', array($this, 'delete_old_plugin')); */
3272
3273
						// [TGMPA + ] Remove our auto-activation hook.
3274
						remove_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3275
3276
						// Force refresh of plugin update information.
3277
						wp_clean_plugins_cache( $parsed_args['clear_update_cache'] );
3278
3279
						return $results;
3280
					}
3281
3282
					/**
3283
					 * Handle a bulk upgrade request.
3284
					 *
3285
					 * @since 2.5.0
3286
					 *
3287
					 * @see Plugin_Upgrader::bulk_upgrade()
3288
					 *
3289
					 * @param array $plugins The local WP file_path's of the plugins which should be upgraded.
3290
					 * @param array $args    Arbitrary passed extra arguments.
3291
					 * @return string|bool Install confirmation messages on success, false on failure.
3292
					 */
3293
					public function bulk_upgrade( $plugins, $args = array() ) {
3294
3295
						add_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3296
3297
						$result = parent::bulk_upgrade( $plugins, $args );
3298
3299
						remove_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3300
3301
						return $result;
3302
					}
3303
3304
					/**
3305
					 * Abuse a filter to auto-activate plugins after installation.
3306
					 *
3307
					 * Hooked into the 'upgrader_post_install' filter hook.
3308
					 *
3309
					 * @since 2.5.0
3310
					 *
3311
					 * @param bool $bool The value we need to give back (true).
3312
					 * @return bool
3313
					 */
3314
					public function auto_activate( $bool ) {
3315
						// Only process the activation of installed plugins if the automatic flag is set to true.
3316
						if ( $this->tgmpa->is_automatic ) {
3317
							// Flush plugins cache so the headers of the newly installed plugins will be read correctly.
3318
							wp_clean_plugins_cache();
3319
3320
							// Get the installed plugin file.
3321
							$plugin_info = $this->plugin_info();
3322
3323
							// Don't try to activate on upgrade of active plugin as WP will do this already.
3324
							if ( ! is_plugin_active( $plugin_info ) ) {
3325
								$activate = activate_plugin( $plugin_info );
3326
3327
								// Adjust the success string based on the activation result.
3328
								$this->strings['process_success'] = $this->strings['process_success'] . "<br />\n";
3329
3330
								if ( is_wp_error( $activate ) ) {
3331
									$this->skin->error( $activate );
3332
									$this->strings['process_success'] .= $this->strings['activation_failed'];
3333
								} else {
3334
									$this->strings['process_success'] .= $this->strings['activation_success'];
3335
								}
3336
							}
3337
						}
3338
3339
						return $bool;
3340
					}
3341
				}
3342
			}
3343
3344
			if ( ! class_exists( 'TGMPA_Bulk_Installer_Skin' ) ) {
3345
3346
				/**
3347
				 * Installer skin to set strings for the bulk plugin installations..
3348
				 *
3349
				 * Extends Bulk_Upgrader_Skin and customizes to suit the installation of multiple
3350
				 * plugins.
3351
				 *
3352
				 * @since 2.2.0
3353
				 *
3354
				 * @internal Since 2.5.2 the class has been renamed from TGM_Bulk_Installer_Skin to
3355
				 *           TGMPA_Bulk_Installer_Skin.
3356
				 *           This was done to prevent backward compatibility issues with v2.3.6.
3357
				 *
3358
				 * @see https://core.trac.wordpress.org/browser/trunk/src/wp-admin/includes/class-wp-upgrader-skins.php
3359
				 *
3360
				 * @package TGM-Plugin-Activation
3361
				 * @author  Thomas Griffin
3362
				 * @author  Gary Jones
3363
				 */
3364
				class TGMPA_Bulk_Installer_Skin extends Bulk_Upgrader_Skin {
3365
					/**
3366
					 * Holds plugin info for each individual plugin installation.
3367
					 *
3368
					 * @since 2.2.0
3369
					 *
3370
					 * @var array
3371
					 */
3372
					public $plugin_info = array();
3373
3374
					/**
3375
					 * Holds names of plugins that are undergoing bulk installations.
3376
					 *
3377
					 * @since 2.2.0
3378
					 *
3379
					 * @var array
3380
					 */
3381
					public $plugin_names = array();
3382
3383
					/**
3384
					 * Integer to use for iteration through each plugin installation.
3385
					 *
3386
					 * @since 2.2.0
3387
					 *
3388
					 * @var integer
3389
					 */
3390
					public $i = 0;
3391
3392
					/**
3393
					 * TGMPA instance
3394
					 *
3395
					 * @since 2.5.0
3396
					 *
3397
					 * @var object
3398
					 */
3399
					protected $tgmpa;
3400
3401
					/**
3402
					 * Constructor. Parses default args with new ones and extracts them for use.
3403
					 *
3404
					 * @since 2.2.0
3405
					 *
3406
					 * @param array $args Arguments to pass for use within the class.
3407
					 */
3408
					public function __construct( $args = array() ) {
3409
						// Get TGMPA class instance.
3410
						$this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
3411
3412
						// Parse default and new args.
3413
						$defaults = array(
3414
							'url'          => '',
3415
							'nonce'        => '',
3416
							'names'        => array(),
3417
							'install_type' => 'install',
3418
						);
3419
						$args     = wp_parse_args( $args, $defaults );
3420
3421
						// Set plugin names to $this->plugin_names property.
3422
						$this->plugin_names = $args['names'];
3423
3424
						// Extract the new args.
3425
						parent::__construct( $args );
3426
					}
3427
3428
					/**
3429
					 * Sets install skin strings for each individual plugin.
3430
					 *
3431
					 * Checks to see if the automatic activation flag is set and uses the
3432
					 * the proper strings accordingly.
3433
					 *
3434
					 * @since 2.2.0
3435
					 */
3436
					public function add_strings() {
3437
						if ( 'update' === $this->options['install_type'] ) {
3438
							parent::add_strings();
3439
							$this->upgrader->strings['skin_before_update_header'] = __( 'Updating Plugin %1$s (%2$d/%3$d)', 'tgmpa' );
3440
						} else {
3441
							$this->upgrader->strings['skin_update_failed_error'] = __( 'An error occurred while installing %1$s: <strong>%2$s</strong>.', 'tgmpa' );
3442
							$this->upgrader->strings['skin_update_failed']       = __( 'The installation of %1$s failed.', 'tgmpa' );
3443
3444
							if ( $this->tgmpa->is_automatic ) {
3445
								// Automatic activation strings.
3446
								$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' );
3447
								$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>';
3448
								$this->upgrader->strings['skin_upgrade_end']          = __( 'All installations and activations have been completed.', 'tgmpa' );
3449
								$this->upgrader->strings['skin_before_update_header'] = __( 'Installing and Activating Plugin %1$s (%2$d/%3$d)', 'tgmpa' );
3450
							} else {
3451
								// Default installation strings.
3452
								$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' );
3453
								$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>';
3454
								$this->upgrader->strings['skin_upgrade_end']          = __( 'All installations have been completed.', 'tgmpa' );
3455
								$this->upgrader->strings['skin_before_update_header'] = __( 'Installing Plugin %1$s (%2$d/%3$d)', 'tgmpa' );
3456
							}
3457
						}
3458
					}
3459
3460
					/**
3461
					 * Outputs the header strings and necessary JS before each plugin installation.
3462
					 *
3463
					 * @since 2.2.0
3464
					 *
3465
					 * @param string $title Unused in this implementation.
3466
					 */
3467
					public function before( $title = '' ) {
3468
						if ( empty( $title ) ) {
3469
							$title = esc_html( $this->plugin_names[ $this->i ] );
3470
						}
3471
						parent::before( $title );
3472
					}
3473
3474
					/**
3475
					 * Outputs the footer strings and necessary JS after each plugin installation.
3476
					 *
3477
					 * Checks for any errors and outputs them if they exist, else output
3478
					 * success strings.
3479
					 *
3480
					 * @since 2.2.0
3481
					 *
3482
					 * @param string $title Unused in this implementation.
3483
					 */
3484
					public function after( $title = '' ) {
3485
						if ( empty( $title ) ) {
3486
							$title = esc_html( $this->plugin_names[ $this->i ] );
3487
						}
3488
						parent::after( $title );
3489
3490
						$this->i++;
3491
					}
3492
3493
					/**
3494
					 * Outputs links after bulk plugin installation is complete.
3495
					 *
3496
					 * @since 2.2.0
3497
					 */
3498
					public function bulk_footer() {
3499
						// Serve up the string to say installations (and possibly activations) are complete.
3500
						parent::bulk_footer();
3501
3502
						// Flush plugins cache so we can make sure that the installed plugins list is always up to date.
3503
						wp_clean_plugins_cache();
3504
3505
						$this->tgmpa->show_tgmpa_version();
3506
3507
						// Display message based on if all plugins are now active or not.
3508
						$update_actions = array();
3509
3510
						if ( $this->tgmpa->is_tgmpa_complete() ) {
3511
							// All plugins are active, so we display the complete string and hide the menu to protect users.
3512
							echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>';
3513
							$update_actions['dashboard'] = sprintf(
3514
								esc_html( $this->tgmpa->strings['complete'] ),
3515
								'<a href="' . esc_url( self_admin_url() ) . '">' . esc_html__( 'Return to the Dashboard', 'tgmpa' ) . '</a>'
3516
							);
3517
						} else {
3518
							$update_actions['tgmpa_page'] = '<a href="' . esc_url( $this->tgmpa->get_tgmpa_url() ) . '" target="_parent">' . esc_html( $this->tgmpa->strings['return'] ) . '</a>';
3519
						}
3520
3521
						/**
3522
						 * Filter the list of action links available following bulk plugin installs/updates.
3523
						 *
3524
						 * @since 2.5.0
3525
						 *
3526
						 * @param array $update_actions Array of plugin action links.
3527
						 * @param array $plugin_info    Array of information for the last-handled plugin.
3528
						 */
3529
						$update_actions = apply_filters( 'tgmpa_update_bulk_plugins_complete_actions', $update_actions, $this->plugin_info );
3530
3531
						if ( ! empty( $update_actions ) ) {
3532
							$this->feedback( implode( ' | ', (array) $update_actions ) );
3533
						}
3534
					}
3535
3536
					/* *********** DEPRECATED METHODS *********** */
3537
3538
					/**
3539
					 * Flush header output buffer.
3540
					 *
3541
					 * @since      2.2.0
3542
					 * @deprecated 2.5.0 use {@see Bulk_Upgrader_Skin::flush_output()} instead
3543
					 * @see        Bulk_Upgrader_Skin::flush_output()
3544
					 */
3545
					public function before_flush_output() {
3546
						_deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'Bulk_Upgrader_Skin::flush_output()' );
3547
						$this->flush_output();
3548
					}
3549
3550
					/**
3551
					 * Flush footer output buffer and iterate $this->i to make sure the
3552
					 * installation strings reference the correct plugin.
3553
					 *
3554
					 * @since      2.2.0
3555
					 * @deprecated 2.5.0 use {@see Bulk_Upgrader_Skin::flush_output()} instead
3556
					 * @see        Bulk_Upgrader_Skin::flush_output()
3557
					 */
3558
					public function after_flush_output() {
3559
						_deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'Bulk_Upgrader_Skin::flush_output()' );
3560
						$this->flush_output();
3561
						$this->i++;
3562
					}
3563
				}
3564
			}
3565
		}
3566
	}
3567
}
3568
3569
if ( ! class_exists( 'TGMPA_Utils' ) ) {
3570
3571
	/**
3572
	 * Generic utilities for TGMPA.
3573
	 *
3574
	 * All methods are static, poor-dev name-spacing class wrapper.
3575
	 *
3576
	 * Class was called TGM_Utils in 2.5.0 but renamed TGMPA_Utils in 2.5.1 as this was conflicting with Soliloquy.
3577
	 *
3578
	 * @since 2.5.0
3579
	 *
3580
	 * @package TGM-Plugin-Activation
3581
	 * @author  Juliette Reinders Folmer
3582
	 */
3583
	class TGMPA_Utils {
3584
		/**
3585
		 * Whether the PHP filter extension is enabled.
3586
		 *
3587
		 * @see http://php.net/book.filter
3588
		 *
3589
		 * @since 2.5.0
3590
		 *
3591
		 * @static
3592
		 *
3593
		 * @var bool $has_filters True is the extension is enabled.
3594
		 */
3595
		public static $has_filters;
3596
3597
		/**
3598
		 * Wrap an arbitrary string in <em> tags. Meant to be used in combination with array_map().
3599
		 *
3600
		 * @since 2.5.0
3601
		 *
3602
		 * @static
3603
		 *
3604
		 * @param string $string Text to be wrapped.
3605
		 * @return string
3606
		 */
3607
		public static function wrap_in_em( $string ) {
3608
			return '<em>' . wp_kses_post( $string ) . '</em>';
3609
		}
3610
3611
		/**
3612
		 * Wrap an arbitrary string in <strong> tags. Meant to be used in combination with array_map().
3613
		 *
3614
		 * @since 2.5.0
3615
		 *
3616
		 * @static
3617
		 *
3618
		 * @param string $string Text to be wrapped.
3619
		 * @return string
3620
		 */
3621
		public static function wrap_in_strong( $string ) {
3622
			return '<strong>' . wp_kses_post( $string ) . '</strong>';
3623
		}
3624
3625
		/**
3626
		 * Helper function: Validate a value as boolean
3627
		 *
3628
		 * @since 2.5.0
3629
		 *
3630
		 * @static
3631
		 *
3632
		 * @param mixed $value Arbitrary value.
3633
		 * @return bool
3634
		 */
3635
		public static function validate_bool( $value ) {
3636
			if ( ! isset( self::$has_filters ) ) {
3637
				self::$has_filters = extension_loaded( 'filter' );
3638
			}
3639
3640
			if ( self::$has_filters ) {
3641
				return filter_var( $value, FILTER_VALIDATE_BOOLEAN );
3642
			} else {
3643
				return self::emulate_filter_bool( $value );
3644
			}
3645
		}
3646
3647
		/**
3648
		 * Helper function: Cast a value to bool
3649
		 *
3650
		 * @since 2.5.0
3651
		 *
3652
		 * @static
3653
		 *
3654
		 * @param mixed $value Value to cast.
3655
		 * @return bool
3656
		 */
3657
		protected static function emulate_filter_bool( $value ) {
3658
			// @codingStandardsIgnoreStart
3659
			static $true  = array(
3660
				'1',
3661
				'true', 'True', 'TRUE',
3662
				'y', 'Y',
3663
				'yes', 'Yes', 'YES',
3664
				'on', 'On', 'ON',
3665
			);
3666
			static $false = array(
3667
				'0',
3668
				'false', 'False', 'FALSE',
3669
				'n', 'N',
3670
				'no', 'No', 'NO',
3671
				'off', 'Off', 'OFF',
3672
			);
3673
			// @codingStandardsIgnoreEnd
3674
3675
			if ( is_bool( $value ) ) {
3676
				return $value;
3677
			} else if ( is_int( $value ) && ( 0 === $value || 1 === $value ) ) {
3678
				return (bool) $value;
3679
			} else if ( ( is_float( $value ) && ! is_nan( $value ) ) && ( (float) 0 === $value || (float) 1 === $value ) ) {
3680
				return (bool) $value;
3681
			} else if ( is_string( $value ) ) {
3682
				$value = trim( $value );
3683
				if ( in_array( $value, $true, true ) ) {
3684
					return true;
3685
				} else if ( in_array( $value, $false, true ) ) {
3686
					return false;
3687
				} else {
3688
					return false;
3689
				}
3690
			}
3691
3692
			return false;
3693
		}
3694
	} // End of class TGMPA_Utils
3695
} // End of class_exists wrapper
3696