Completed
Pull Request — develop (#513)
by Juliette
05:50 queued 03:11
created

class-tgm-plugin-activation.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
				'oops'                            => __( 'Something went wrong with the plugin API.', 'tgmpa' ),
326
				'notice_can_install_required'     => _n_noop(
327
					'This theme requires the following plugin: %1$s.',
328
					'This theme requires the following plugins: %1$s.',
329
					'tgmpa'
330
				),
331
				'notice_can_install_recommended'  => _n_noop(
332
					'This theme recommends the following plugin: %1$s.',
333
					'This theme recommends the following plugins: %1$s.',
334
					'tgmpa'
335
				),
336
				'notice_ask_to_update'            => _n_noop(
337
					'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.',
338
					'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.',
339
					'tgmpa'
340
				),
341
				'notice_ask_to_update_maybe'      => _n_noop(
342
					'There is an update available for: %1$s.',
343
					'There are updates available for the following plugins: %1$s.',
344
					'tgmpa'
345
				),
346
				'notice_can_activate_required'    => _n_noop(
347
					'The following required plugin is currently inactive: %1$s.',
348
					'The following required plugins are currently inactive: %1$s.',
349
					'tgmpa'
350
				),
351
				'notice_can_activate_recommended' => _n_noop(
352
					'The following recommended plugin is currently inactive: %1$s.',
353
					'The following recommended plugins are currently inactive: %1$s.',
354
					'tgmpa'
355
				),
356
				'install_link'                    => _n_noop(
357
					'Begin installing plugin',
358
					'Begin installing plugins',
359
					'tgmpa'
360
				),
361
				'update_link'                     => _n_noop(
362
					'Begin updating plugin',
363
					'Begin updating plugins',
364
					'tgmpa'
365
				),
366
				'activate_link'                   => _n_noop(
367
					'Begin activating plugin',
368
					'Begin activating plugins',
369
					'tgmpa'
370
				),
371
				'return'                          => __( 'Return to Required Plugins Installer', 'tgmpa' ),
372
				'dashboard'                       => __( 'Return to the dashboard', 'tgmpa' ),
373
				'plugin_activated'                => __( 'Plugin activated successfully.', 'tgmpa' ),
374
				'activated_successfully'          => __( 'The following plugin was activated successfully:', 'tgmpa' ),
375
				'plugin_already_active'           => __( 'No action taken. Plugin %1$s was already active.', 'tgmpa' ),
376
				'plugin_needs_higher_version'     => __( 'Plugin not activated. A higher version of %s is needed for this theme. Please update the plugin.', 'tgmpa' ),
377
				'complete'                        => __( 'All plugins installed and activated successfully. %1$s', 'tgmpa' ),
378
				'dismiss'                         => __( 'Dismiss this notice', 'tgmpa' ),
379
				'notice_cannot_install_activate'  => __( 'There are one or more required or recommended plugins to install, update or activate.', 'tgmpa' ),
380
				'contact_admin'                   => __( 'Please contact the administrator of this site for help.', 'tgmpa' ),
381
			);
382
383
			do_action( 'tgmpa_register' );
384
385
			/* After this point, the plugins should be registered and the configuration set. */
386
387
			// Proceed only if we have plugins to handle.
388
			if ( empty( $this->plugins ) || ! is_array( $this->plugins ) ) {
389
				return;
390
			}
391
392
			// Set up the menu and notices if we still have outstanding actions.
393
			if ( true !== $this->is_tgmpa_complete() ) {
394
				// Sort the plugins.
395
				array_multisort( $this->sort_order, SORT_ASC, $this->plugins );
396
397
				add_action( 'admin_menu', array( $this, 'admin_menu' ) );
398
				add_action( 'admin_head', array( $this, 'dismiss' ) );
399
400
				// Prevent the normal links from showing underneath a single install/update page.
401
				add_filter( 'install_plugin_complete_actions', array( $this, 'actions' ) );
402
				add_filter( 'update_plugin_complete_actions', array( $this, 'actions' ) );
403
404
				if ( $this->has_notices ) {
405
					add_action( 'admin_notices', array( $this, 'notices' ) );
406
					add_action( 'admin_init', array( $this, 'admin_init' ), 1 );
407
					add_action( 'admin_enqueue_scripts', array( $this, 'thickbox' ) );
408
				}
409
			}
410
411
			// If needed, filter plugin action links.
412
			add_action( 'load-plugins.php', array( $this, 'add_plugin_action_link_filters' ), 1 );
413
414
			// Make sure things get reset on switch theme.
415
			add_action( 'switch_theme', array( $this, 'flush_plugins_cache' ) );
416
417
			if ( $this->has_notices ) {
418
				add_action( 'switch_theme', array( $this, 'update_dismiss' ) );
419
			}
420
421
			// Setup the force activation hook.
422
			if ( true === $this->has_forced_activation ) {
423
				add_action( 'admin_init', array( $this, 'force_activation' ) );
424
			}
425
426
			// Setup the force deactivation hook.
427
			if ( true === $this->has_forced_deactivation ) {
428
				add_action( 'switch_theme', array( $this, 'force_deactivation' ) );
429
			}
430
		}
431
432
		/**
433
		 * Hook in plugin action link filters for the WP native plugins page.
434
		 *
435
		 * - Prevent activation of plugins which don't meet the minimum version requirements.
436
		 * - Prevent deactivation of force-activated plugins.
437
		 * - Add update notice if update available.
438
		 *
439
		 * @since 2.5.0
440
		 */
441
		public function add_plugin_action_link_filters() {
442
			foreach ( $this->plugins as $slug => $plugin ) {
443
				if ( false === $this->can_plugin_activate( $slug ) ) {
444
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_activate' ), 20 );
445
				}
446
447
				if ( true === $plugin['force_activation'] ) {
448
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_deactivate' ), 20 );
449
				}
450
451
				if ( false !== $this->does_plugin_require_update( $slug ) ) {
452
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_update' ), 20 );
453
				}
454
			}
455
		}
456
457
		/**
458
		 * Remove the 'Activate' link on the WP native plugins page if the plugin does not meet the
459
		 * minimum version requirements.
460
		 *
461
		 * @since 2.5.0
462
		 *
463
		 * @param array $actions Action links.
464
		 * @return array
465
		 */
466
		public function filter_plugin_action_links_activate( $actions ) {
467
			unset( $actions['activate'] );
468
469
			return $actions;
470
		}
471
472
		/**
473
		 * Remove the 'Deactivate' link on the WP native plugins page if the plugin has been set to force activate.
474
		 *
475
		 * @since 2.5.0
476
		 *
477
		 * @param array $actions Action links.
478
		 * @return array
479
		 */
480
		public function filter_plugin_action_links_deactivate( $actions ) {
481
			unset( $actions['deactivate'] );
482
483
			return $actions;
484
		}
485
486
		/**
487
		 * Add a 'Requires update' link on the WP native plugins page if the plugin does not meet the
488
		 * minimum version requirements.
489
		 *
490
		 * @since 2.5.0
491
		 *
492
		 * @param array $actions Action links.
493
		 * @return array
494
		 */
495
		public function filter_plugin_action_links_update( $actions ) {
496
			$actions['update'] = sprintf(
497
				'<a href="%1$s" title="%2$s" class="edit">%3$s</a>',
498
				esc_url( $this->get_tgmpa_status_url( 'update' ) ),
499
				esc_attr__( 'This plugin needs to be updated to be compatible with your theme.', 'tgmpa' ),
500
				esc_html__( 'Update Required', 'tgmpa' )
501
			);
502
503
			return $actions;
504
		}
505
506
		/**
507
		 * Handles calls to show plugin information via links in the notices.
508
		 *
509
		 * We get the links in the admin notices to point to the TGMPA page, rather
510
		 * than the typical plugin-install.php file, so we can prepare everything
511
		 * beforehand.
512
		 *
513
		 * WP does not make it easy to show the plugin information in the thickbox -
514
		 * here we have to require a file that includes a function that does the
515
		 * main work of displaying it, enqueue some styles, set up some globals and
516
		 * finally call that function before exiting.
517
		 *
518
		 * Down right easy once you know how...
519
		 *
520
		 * Returns early if not the TGMPA page.
521
		 *
522
		 * @since 2.1.0
523
		 *
524
		 * @global string $tab Used as iframe div class names, helps with styling
525
		 * @global string $body_id Used as the iframe body ID, helps with styling
526
		 *
527
		 * @return null Returns early if not the TGMPA page.
528
		 */
529
		public function admin_init() {
530
			if ( ! $this->is_tgmpa_page() ) {
531
				return;
532
			}
533
534
			if ( isset( $_REQUEST['tab'] ) && 'plugin-information' === $_REQUEST['tab'] ) {
535
				// Needed for install_plugin_information().
536
				require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
537
538
				wp_enqueue_style( 'plugin-install' );
539
540
				global $tab, $body_id;
541
				$body_id = 'plugin-information';
542
				// @codingStandardsIgnoreStart
543
				$tab     = 'plugin-information';
544
				// @codingStandardsIgnoreEnd
545
546
				install_plugin_information();
547
548
				exit;
549
			}
550
		}
551
552
		/**
553
		 * Enqueue thickbox scripts/styles for plugin info.
554
		 *
555
		 * Thickbox is not automatically included on all admin pages, so we must
556
		 * manually enqueue it for those pages.
557
		 *
558
		 * Thickbox is only loaded if the user has not dismissed the admin
559
		 * notice or if there are any plugins left to install and activate.
560
		 *
561
		 * @since 2.1.0
562
		 */
563
		public function thickbox() {
564
			if ( ! get_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, true ) ) {
565
				add_thickbox();
566
			}
567
		}
568
569
		/**
570
		 * Adds submenu page if there are plugin actions to take.
571
		 *
572
		 * This method adds the submenu page letting users know that a required
573
		 * plugin needs to be installed.
574
		 *
575
		 * This page disappears once the plugin has been installed and activated.
576
		 *
577
		 * @since 1.0.0
578
		 *
579
		 * @see TGM_Plugin_Activation::init()
580
		 * @see TGM_Plugin_Activation::install_plugins_page()
581
		 *
582
		 * @return null Return early if user lacks capability to install a plugin.
583
		 */
584
		public function admin_menu() {
585
			// Make sure privileges are correct to see the page.
586
			if ( ! current_user_can( 'install_plugins' ) ) {
587
				return;
588
			}
589
590
			$args = apply_filters(
591
				'tgmpa_admin_menu_args',
592
				array(
593
					'parent_slug' => $this->parent_slug,                     // Parent Menu slug.
594
					'page_title'  => $this->strings['page_title'],           // Page title.
595
					'menu_title'  => $this->strings['menu_title'],           // Menu title.
596
					'capability'  => $this->capability,                      // Capability.
597
					'menu_slug'   => $this->menu,                            // Menu slug.
598
					'function'    => array( $this, 'install_plugins_page' ), // Callback.
599
				)
600
			);
601
602
			$this->add_admin_menu( $args );
603
		}
604
605
		/**
606
		 * Add the menu item.
607
		 *
608
		 * @since 2.5.0
609
		 *
610
		 * @param array $args Menu item configuration.
611
		 */
612
		protected function add_admin_menu( array $args ) {
613
			if ( has_filter( 'tgmpa_admin_menu_use_add_theme_page' ) ) {
614
				_deprecated_function( 'The "tgmpa_admin_menu_use_add_theme_page" filter', '2.5.0', esc_html__( 'Set the parent_slug config variable instead.', 'tgmpa' ) );
615
			}
616
617
			if ( 'themes.php' === $this->parent_slug ) {
618
				$this->page_hook = call_user_func( 'add_theme_page', $args['page_title'], $args['menu_title'], $args['capability'], $args['menu_slug'], $args['function'] );
619
			} else {
620
				$type = 'submenu';
621
				$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'] );
622
			}
623
		}
624
625
		/**
626
		 * Echoes plugin installation form.
627
		 *
628
		 * This method is the callback for the admin_menu method function.
629
		 * This displays the admin page and form area where the user can select to install and activate the plugin.
630
		 * Aborts early if we're processing a plugin installation action.
631
		 *
632
		 * @since 1.0.0
633
		 *
634
		 * @return null Aborts early if we're processing a plugin installation action.
635
		 */
636
		public function install_plugins_page() {
637
			// Store new instance of plugin table in object.
638
			$plugin_table = new TGMPA_List_Table;
639
640
			// Return early if processing a plugin installation action.
641
			if ( ( ( 'tgmpa-bulk-install' === $plugin_table->current_action() || 'tgmpa-bulk-update' === $plugin_table->current_action() ) && $plugin_table->process_bulk_actions() ) || $this->do_plugin_install() ) {
642
				return;
643
			}
644
645
			// Force refresh of available plugin information so we'll know about manual updates/deletes.
646
			wp_clean_plugins_cache( false );
647
648
			?>
649
			<div class="tgmpa wrap">
650
				<h2><?php echo esc_html( get_admin_page_title() ); ?></h2>
651
				<?php $plugin_table->prepare_items(); ?>
652
653
				<?php
654
				if ( ! empty( $this->message ) && is_string( $this->message ) ) {
655
					echo wp_kses_post( $this->message );
656
				}
657
				?>
658
				<?php $plugin_table->views(); ?>
659
660
				<form id="tgmpa-plugins" action="" method="post">
661
					<input type="hidden" name="tgmpa-page" value="<?php echo esc_attr( $this->menu ); ?>" />
662
					<input type="hidden" name="plugin_status" value="<?php echo esc_attr( $plugin_table->view_context ); ?>" />
663
					<?php $plugin_table->display(); ?>
664
				</form>
665
			</div>
666
			<?php
667
		}
668
669
		/**
670
		 * Installs, updates or activates a plugin depending on the action link clicked by the user.
671
		 *
672
		 * Checks the $_GET variable to see which actions have been
673
		 * passed and responds with the appropriate method.
674
		 *
675
		 * Uses WP_Filesystem to process and handle the plugin installation
676
		 * method.
677
		 *
678
		 * @since 1.0.0
679
		 *
680
		 * @uses WP_Filesystem
681
		 * @uses WP_Error
682
		 * @uses WP_Upgrader
683
		 * @uses Plugin_Upgrader
684
		 * @uses Plugin_Installer_Skin
685
		 * @uses Plugin_Upgrader_Skin
686
		 *
687
		 * @return boolean True on success, false on failure.
688
		 */
689
		protected function do_plugin_install() {
690
			if ( empty( $_GET['plugin'] ) ) {
691
				return false;
692
			}
693
694
			// All plugin information will be stored in an array for processing.
695
			$slug = $this->sanitize_key( urldecode( $_GET['plugin'] ) );
696
697
			if ( ! isset( $this->plugins[ $slug ] ) ) {
698
				return false;
699
			}
700
701
			// Was an install or upgrade action link clicked?
702
			if ( ( isset( $_GET['tgmpa-install'] ) && 'install-plugin' === $_GET['tgmpa-install'] ) || ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) ) {
703
704
				$install_type = 'install';
705
				if ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) {
706
					$install_type = 'update';
707
				}
708
709
				check_admin_referer( 'tgmpa-' . $install_type, 'tgmpa-nonce' );
710
711
				// Pass necessary information via URL if WP_Filesystem is needed.
712
				$url = wp_nonce_url(
713
					add_query_arg(
714
						array(
715
							'plugin'                 => urlencode( $slug ),
716
							'tgmpa-' . $install_type => $install_type . '-plugin',
717
						),
718
						$this->get_tgmpa_url()
719
					),
720
					'tgmpa-' . $install_type,
721
					'tgmpa-nonce'
722
				);
723
724
				$method = ''; // Leave blank so WP_Filesystem can populate it as necessary.
725
726
				if ( false === ( $creds = request_filesystem_credentials( esc_url_raw( $url ), $method, false, false, array() ) ) ) {
727
					return true;
728
				}
729
730 View Code Duplication
				if ( ! WP_Filesystem( $creds ) ) {
0 ignored issues
show
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...
731
					request_filesystem_credentials( esc_url_raw( $url ), $method, true, false, array() ); // Setup WP_Filesystem.
732
					return true;
733
				}
734
735
				/* If we arrive here, we have the filesystem. */
736
737
				// Prep variables for Plugin_Installer_Skin class.
738
				$extra         = array();
739
				$extra['slug'] = $slug; // Needed for potentially renaming of directory name.
740
				$source        = $this->get_download_url( $slug );
741
				$api           = ( 'repo' === $this->plugins[ $slug ]['source_type'] ) ? $this->get_plugins_api( $slug ) : null;
742
				$api           = ( false !== $api ) ? $api : null;
743
744
				$url = add_query_arg(
745
					array(
746
						'action' => $install_type . '-plugin',
747
						'plugin' => urlencode( $slug ),
748
					),
749
					'update.php'
750
				);
751
752
				if ( ! class_exists( 'Plugin_Upgrader', false ) ) {
753
					require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
754
				}
755
756
				$skin_args = array(
757
					'type'   => ( 'bundled' !== $this->plugins[ $slug ]['source_type'] ) ? 'web' : 'upload',
758
					'title'  => sprintf( $this->strings['installing'], $this->plugins[ $slug ]['name'] ),
759
					'url'    => esc_url_raw( $url ),
760
					'nonce'  => $install_type . '-plugin_' . $slug,
761
					'plugin' => '',
762
					'api'    => $api,
763
					'extra'  => $extra,
764
				);
765
766
				if ( 'update' === $install_type ) {
767
					$skin_args['plugin'] = $this->plugins[ $slug ]['file_path'];
768
					$skin                = new Plugin_Upgrader_Skin( $skin_args );
769
				} else {
770
					$skin = new Plugin_Installer_Skin( $skin_args );
771
				}
772
773
				// Create a new instance of Plugin_Upgrader.
774
				$upgrader = new Plugin_Upgrader( $skin );
775
776
				// Perform the action and install the plugin from the $source urldecode().
777
				add_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1, 3 );
778
779
				if ( 'update' === $install_type ) {
780
					// Inject our info into the update transient.
781
					$to_inject                    = array( $slug => $this->plugins[ $slug ] );
782
					$to_inject[ $slug ]['source'] = $source;
783
					$this->inject_update_info( $to_inject );
784
785
					$upgrader->upgrade( $this->plugins[ $slug ]['file_path'] );
786
				} else {
787
					$upgrader->install( $source );
788
				}
789
790
				remove_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1, 3 );
791
792
				// Make sure we have the correct file path now the plugin is installed/updated.
793
				$this->populate_file_path( $slug );
794
795
				// Only activate plugins if the config option is set to true and the plugin isn't
796
				// already active (upgrade).
797
				if ( $this->is_automatic && ! $this->is_plugin_active( $slug ) ) {
798
					$plugin_activate = $upgrader->plugin_info(); // Grab the plugin info from the Plugin_Upgrader method.
799
					if ( false === $this->activate_single_plugin( $plugin_activate, $slug, true ) ) {
800
						return true; // Finish execution of the function early as we encountered an error.
801
					}
802
				}
803
804
				$this->show_tgmpa_version();
805
806
				// Display message based on if all plugins are now active or not.
807
				if ( $this->is_tgmpa_complete() ) {
808
					echo '<p>', sprintf( esc_html( $this->strings['complete'] ), '<a href="' . esc_url( self_admin_url() ) . '">' . esc_html__( 'Return to the Dashboard', 'tgmpa' ) . '</a>' ), '</p>';
809
					echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>';
810
				} else {
811
					echo '<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>';
812
				}
813
814
				return true;
815
			} elseif ( isset( $this->plugins[ $slug ]['file_path'], $_GET['tgmpa-activate'] ) && 'activate-plugin' === $_GET['tgmpa-activate'] ) {
816
				// Activate action link was clicked.
817
				check_admin_referer( 'tgmpa-activate', 'tgmpa-nonce' );
818
819
				if ( false === $this->activate_single_plugin( $this->plugins[ $slug ]['file_path'], $slug ) ) {
820
					return true; // Finish execution of the function early as we encountered an error.
821
				}
822
			}
823
824
			return false;
825
		}
826
827
		/**
828
		 * Inject information into the 'update_plugins' site transient as WP checks that before running an update.
829
		 *
830
		 * @since 2.5.0
831
		 *
832
		 * @param array $plugins The plugin information for the plugins which are to be updated.
833
		 */
834
		public function inject_update_info( $plugins ) {
835
			$repo_updates = get_site_transient( 'update_plugins' );
836
837
			if ( ! is_object( $repo_updates ) ) {
838
				$repo_updates = new stdClass;
839
			}
840
841
			foreach ( $plugins as $slug => $plugin ) {
842
				$file_path = $plugin['file_path'];
843
844
				if ( empty( $repo_updates->response[ $file_path ] ) ) {
845
					$repo_updates->response[ $file_path ] = new stdClass;
846
				}
847
848
				// We only really need to set package, but let's do all we can in case WP changes something.
849
				$repo_updates->response[ $file_path ]->slug        = $slug;
850
				$repo_updates->response[ $file_path ]->plugin      = $file_path;
851
				$repo_updates->response[ $file_path ]->new_version = $plugin['version'];
852
				$repo_updates->response[ $file_path ]->package     = $plugin['source'];
853
				if ( empty( $repo_updates->response[ $file_path ]->url ) && ! empty( $plugin['external_url'] ) ) {
854
					$repo_updates->response[ $file_path ]->url = $plugin['external_url'];
855
				}
856
			}
857
858
			set_site_transient( 'update_plugins', $repo_updates );
859
		}
860
861
		/**
862
		 * Adjust the plugin directory name if necessary.
863
		 *
864
		 * The final destination directory of a plugin is based on the subdirectory name found in the
865
		 * (un)zipped source. In some cases - most notably GitHub repository plugin downloads -, this
866
		 * subdirectory name is not the same as the expected slug and the plugin will not be recognized
867
		 * as installed. This is fixed by adjusting the temporary unzipped source subdirectory name to
868
		 * the expected plugin slug.
869
		 *
870
		 * @since 2.5.0
871
		 *
872
		 * @param string       $source        Path to upgrade/zip-file-name.tmp/subdirectory/.
873
		 * @param string       $remote_source Path to upgrade/zip-file-name.tmp.
874
		 * @param \WP_Upgrader $upgrader      Instance of the upgrader which installs the plugin.
875
		 * @return string $source
876
		 */
877
		public function maybe_adjust_source_dir( $source, $remote_source, $upgrader ) {
878
			if ( ! $this->is_tgmpa_page() || ! is_object( $GLOBALS['wp_filesystem'] ) ) {
879
				return $source;
880
			}
881
882
			// Check for single file plugins.
883
			$source_files = array_keys( $GLOBALS['wp_filesystem']->dirlist( $remote_source ) );
884
			if ( 1 === count( $source_files ) && false === $GLOBALS['wp_filesystem']->is_dir( $source ) ) {
885
				return $source;
886
			}
887
888
			// Multi-file plugin, let's see if the directory is correctly named.
889
			$desired_slug = '';
890
891
			// Figure out what the slug is supposed to be.
892
			if ( false === $upgrader->bulk && ! empty( $upgrader->skin->options['extra']['slug'] ) ) {
893
				$desired_slug = $upgrader->skin->options['extra']['slug'];
894
			} else {
895
				// Bulk installer contains less info, so fall back on the info registered here.
896
				foreach ( $this->plugins as $slug => $plugin ) {
897
					if ( ! empty( $upgrader->skin->plugin_names[ $upgrader->skin->i ] ) && $plugin['name'] === $upgrader->skin->plugin_names[ $upgrader->skin->i ] ) {
898
						$desired_slug = $slug;
899
						break;
900
					}
901
				}
902
				unset( $slug, $plugin );
903
			}
904
905
			if ( ! empty( $desired_slug ) ) {
906
				$subdir_name = untrailingslashit( str_replace( trailingslashit( $remote_source ), '', $source ) );
907
908
				if ( ! empty( $subdir_name ) && $subdir_name !== $desired_slug ) {
909
					$from = untrailingslashit( $source );
910
					$to   = trailingslashit( $remote_source ) . $desired_slug;
911
912
					if ( true === $GLOBALS['wp_filesystem']->move( $from, $to ) ) {
913
						return trailingslashit( $to );
914 View Code Duplication
					} else {
915
						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 ) );
916
					}
917 View Code Duplication
				} elseif ( empty( $subdir_name ) ) {
918
					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 ) );
919
				}
920
			}
921
922
			return $source;
923
		}
924
925
		/**
926
		 * Activate a single plugin and send feedback about the result to the screen.
927
		 *
928
		 * @since 2.5.0
929
		 *
930
		 * @param string $file_path Path within wp-plugins/ to main plugin file.
931
		 * @param string $slug      Plugin slug.
932
		 * @param bool   $automatic Whether this is an automatic activation after an install. Defaults to false.
933
		 *                          This determines the styling of the output messages.
934
		 * @return bool False if an error was encountered, true otherwise.
935
		 */
936
		protected function activate_single_plugin( $file_path, $slug, $automatic = false ) {
937
			if ( $this->can_plugin_activate( $slug ) ) {
938
				$activate = activate_plugin( $file_path );
939
940
				if ( is_wp_error( $activate ) ) {
941
					echo '<div id="message" class="error"><p>', wp_kses_post( $activate->get_error_message() ), '</p></div>',
942
						'<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>';
943
944
					return false; // End it here if there is an error with activation.
945
				} else {
946
					if ( ! $automatic ) {
947
						// Make sure message doesn't display again if bulk activation is performed
948
						// immediately after a single activation.
949
						if ( ! isset( $_POST['action'] ) ) { // WPCS: CSRF OK.
950
							echo '<div id="message" class="updated"><p>', esc_html( $this->strings['activated_successfully'] ), ' <strong>', esc_html( $this->plugins[ $slug ]['name'] ), '.</strong></p></div>';
951
						}
952
					} else {
953
						// Simpler message layout for use on the plugin install page.
954
						echo '<p>', esc_html( $this->strings['plugin_activated'] ), '</p>';
955
					}
956
				}
957 View Code Duplication
			} elseif ( $this->is_plugin_active( $slug ) ) {
958
				// No simpler message format provided as this message should never be encountered
959
				// on the plugin install page.
960
				echo '<div id="message" class="error"><p>',
961
					sprintf(
962
						esc_html( $this->strings['plugin_already_active'] ),
963
						'<strong>' . esc_html( $this->plugins[ $slug ]['name'] ) . '</strong>'
964
					),
965
					'</p></div>';
966
			} elseif ( $this->does_plugin_require_update( $slug ) ) {
967
				if ( ! $automatic ) {
968
					// Make sure message doesn't display again if bulk activation is performed
969
					// immediately after a single activation.
970 View Code Duplication
					if ( ! isset( $_POST['action'] ) ) { // WPCS: CSRF OK.
971
						echo '<div id="message" class="error"><p>',
972
							sprintf(
973
								esc_html( $this->strings['plugin_needs_higher_version'] ),
974
								'<strong>' . esc_html( $this->plugins[ $slug ]['name'] ) . '</strong>'
975
							),
976
							'</p></div>';
977
					}
978
				} else {
979
					// Simpler message layout for use on the plugin install page.
980
					echo '<p>', sprintf( esc_html( $this->strings['plugin_needs_higher_version'] ), esc_html( $this->plugins[ $slug ]['name'] ) ), '</p>';
981
				}
982
			}
983
984
			return true;
985
		}
986
987
		/**
988
		 * Echoes required plugin notice.
989
		 *
990
		 * Outputs a message telling users that a specific plugin is required for
991
		 * their theme. If appropriate, it includes a link to the form page where
992
		 * users can install and activate the plugin.
993
		 *
994
		 * Returns early if we're on the Install page.
995
		 *
996
		 * @since 1.0.0
997
		 *
998
		 * @global object $current_screen
999
		 *
1000
		 * @return null Returns early if we're on the Install page.
1001
		 */
1002
		public function notices() {
1003
			// Remove nag on the install page / Return early if the nag message has been dismissed or user < author.
1004
			if ( $this->is_tgmpa_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' ) ) ) {
1005
				return;
1006
			}
1007
1008
			// Store for the plugin slugs by message type.
1009
			$message = array();
1010
1011
			// Initialize counters used to determine plurality of action link texts.
1012
			$install_link_count          = 0;
1013
			$update_link_count           = 0;
1014
			$activate_link_count         = 0;
1015
			$total_required_action_count = 0;
1016
1017
			foreach ( $this->plugins as $slug => $plugin ) {
1018
				if ( $this->is_plugin_active( $slug ) && false === $this->does_plugin_have_update( $slug ) ) {
1019
					continue;
1020
				}
1021
1022
				if ( ! $this->is_plugin_installed( $slug ) ) {
1023
					if ( current_user_can( 'install_plugins' ) ) {
1024
						$install_link_count++;
1025
1026
						if ( true === $plugin['required'] ) {
1027
							$message['notice_can_install_required'][] = $slug;
1028
						} else {
1029
							$message['notice_can_install_recommended'][] = $slug;
1030
						}
1031
					}
1032
					if ( true === $plugin['required'] ) {
1033
						$total_required_action_count++;
1034
					}
1035
				} else {
1036
					if ( ! $this->is_plugin_active( $slug ) && $this->can_plugin_activate( $slug ) ) {
1037
						if ( current_user_can( 'activate_plugins' ) ) {
1038
							$activate_link_count++;
1039
1040
							if ( true === $plugin['required'] ) {
1041
								$message['notice_can_activate_required'][] = $slug;
1042
							} else {
1043
								$message['notice_can_activate_recommended'][] = $slug;
1044
							}
1045
						}
1046
						if ( true === $plugin['required'] ) {
1047
							$total_required_action_count++;
1048
						}
1049
					}
1050
1051
					if ( $this->does_plugin_require_update( $slug ) || false !== $this->does_plugin_have_update( $slug ) ) {
1052
1053
						if ( current_user_can( 'update_plugins' ) ) {
1054
							$update_link_count++;
1055
1056
							if ( $this->does_plugin_require_update( $slug ) ) {
1057
								$message['notice_ask_to_update'][] = $slug;
1058
							} elseif ( false !== $this->does_plugin_have_update( $slug ) ) {
1059
								$message['notice_ask_to_update_maybe'][] = $slug;
1060
							}
1061
						}
1062
						if ( true === $plugin['required'] ) {
1063
							$total_required_action_count++;
1064
						}
1065
					}
1066
				}
1067
			}
1068
			unset( $slug, $plugin );
1069
1070
			// If we have notices to display, we move forward.
1071
			if ( ! empty( $message ) || $total_required_action_count > 0 ) {
1072
				krsort( $message ); // Sort messages.
1073
				$rendered = '';
1074
1075
				// As add_settings_error() wraps the final message in a <p> and as the final message can't be
1076
				// filtered, using <p>'s in our html would render invalid html output.
1077
				$line_template = '<span style="display: block; margin: 0.5em 0.5em 0 0; clear: both;">%s</span>' . "\n";
1078
1079
				if ( ! current_user_can( 'activate_plugins' ) && ! current_user_can( 'install_plugins' ) && ! current_user_can( 'update_plugins' ) ) {
1080
					$rendered = esc_html__( $this->strings['notice_cannot_install_activate'] . ' ' . $this->strings['contact_admin'] );
1081
					$rendered .= $this->create_user_action_links_for_notice( 0, 0, 0, $line_template );
1082
				} else {
1083
1084
					// If dismissable is false and a message is set, output it now.
1085
					if ( ! $this->dismissable && ! empty( $this->dismiss_msg ) ) {
1086
						$rendered .= sprintf( $line_template, wp_kses_post( $this->dismiss_msg ) );
1087
					}
1088
1089
					// Render the individual message lines for the notice.
1090
					foreach ( $message as $type => $plugin_group ) {
1091
						$linked_plugins = array();
1092
1093
						// Get the external info link for a plugin if one is available.
1094
						foreach ( $plugin_group as $plugin_slug ) {
1095
							$linked_plugins[] = $this->get_info_link( $plugin_slug );
1096
						}
1097
						unset( $plugin_slug );
1098
1099
						$count          = count( $plugin_group );
1100
						$linked_plugins = array_map( array( 'TGMPA_Utils', 'wrap_in_em' ), $linked_plugins );
1101
						$last_plugin    = array_pop( $linked_plugins ); // Pop off last name to prep for readability.
1102
						$imploded       = empty( $linked_plugins ) ? $last_plugin : ( implode( ', ', $linked_plugins ) . ' ' . esc_html_x( 'and', 'plugin A *and* plugin B', 'tgmpa' ) . ' ' . $last_plugin );
1103
1104
						$rendered .= sprintf(
1105
							$line_template,
1106
							sprintf(
1107
								translate_nooped_plural( $this->strings[ $type ], $count, 'tgmpa' ),
1108
								$imploded,
1109
								$count
1110
							)
1111
						);
1112
1113
					}
1114
					unset( $type, $plugin_group, $linked_plugins, $count, $last_plugin, $imploded );
1115
1116
					$rendered .= $this->create_user_action_links_for_notice( $install_link_count, $update_link_count, $activate_link_count, $line_template );
1117
				}
1118
1119
				// Register the nag messages and prepare them to be processed.
1120
				add_settings_error( 'tgmpa', 'tgmpa', $rendered, $this->get_admin_notice_class() );
1121
			}
1122
1123
			// Admin options pages already output settings_errors, so this is to avoid duplication.
1124
			if ( 'options-general' !== $GLOBALS['current_screen']->parent_base ) {
1125
				$this->display_settings_errors();
1126
			}
1127
		}
1128
1129
		/**
1130
		 * Generate the user action links for the admin notice.
1131
		 *
1132
		 * @since 2.x.x
1133
		 *
1134
		 * @param int $install_link_count  Number of plugins to install.
1135
		 * @param int $update_link_count   Number of plugins to update.
1136
		 * @param int $activate_link_count Number of plugins to activate.
1137
		 * @param int $line_template       Template for the HTML tag to output a line.
1138
		 * @return string Action links.
1139
		 */
1140
		protected function create_user_action_links_for_notice( $install_link_count, $update_link_count, $activate_link_count, $line_template ) {
1141
			// Setup action links.
1142
			$action_links = array(
1143
				'install'  => '',
1144
				'update'   => '',
1145
				'activate' => '',
1146
				'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>' : '',
1147
			);
1148
1149
			$link_template = '<a href="%2$s">%1$s</a>';
1150
1151
			if ( current_user_can( 'install_plugins' ) ) {
1152 View Code Duplication
				if ( $install_link_count > 0 ) {
1153
					$action_links['install'] = sprintf(
1154
						$link_template,
1155
						translate_nooped_plural( $this->strings['install_link'], $install_link_count, 'tgmpa' ),
1156
						esc_url( $this->get_tgmpa_status_url( 'install' ) )
1157
					);
1158
				}
1159 View Code Duplication
				if ( $update_link_count > 0 ) {
1160
					$action_links['update'] = sprintf(
1161
						$link_template,
1162
						translate_nooped_plural( $this->strings['update_link'], $update_link_count, 'tgmpa' ),
1163
						esc_url( $this->get_tgmpa_status_url( 'update' ) )
1164
					);
1165
				}
1166
			}
1167
1168 View Code Duplication
			if ( current_user_can( 'activate_plugins' ) && $activate_link_count > 0 ) {
1169
				$action_links['activate'] = sprintf(
1170
					$link_template,
1171
					translate_nooped_plural( $this->strings['activate_link'], $activate_link_count, 'tgmpa' ),
1172
					esc_url( $this->get_tgmpa_status_url( 'activate' ) )
1173
				);
1174
			}
1175
1176
			$action_links = apply_filters( 'tgmpa_notice_action_links', $action_links );
1177
1178
			$action_links = array_filter( (array) $action_links ); // Remove any empty array items.
1179
1180
			if ( ! empty( $action_links ) && is_array( $action_links ) ) {
1181
				$action_links = sprintf( $line_template, implode( ' | ', $action_links ) );
1182
				return apply_filters( 'tgmpa_notice_rendered_action_links', $action_links );
1183
			} else {
1184
				return '';
1185
			}
1186
		}
1187
1188
		/**
1189
		 * Get admin notice class.
1190
		 *
1191
		 * Work around all the changes to the various admin notice classes between WP 4.4 and 3.7
1192
		 * (lowest supported version by TGMPA).
1193
		 *
1194
		 * @since 2.x.x
1195
		 *
1196
		 * @return string
1197
		 */
1198
		protected function get_admin_notice_class() {
1199
			if ( ! empty( $this->strings['nag_type'] ) ) {
1200
				return sanitize_html_class( strtolower( $this->strings['nag_type'] ) );
1201
			} else {
1202
				if ( version_compare( $this->wp_version, '4.2', '>=' ) ) {
1203
					return 'notice-warning';
1204
				} elseif ( version_compare( $this->wp_version, '4.1', '>=' ) ) {
1205
					return 'notice';
1206
				} else {
1207
					return 'updated';
1208
				}
1209
			}
1210
		}
1211
1212
		/**
1213
		 * Display settings errors and remove those which have been displayed to avoid duplicate messages showing
1214
		 *
1215
		 * @since 2.5.0
1216
		 */
1217
		protected function display_settings_errors() {
1218
			global $wp_settings_errors;
1219
1220
			settings_errors( 'tgmpa' );
1221
1222
			foreach ( (array) $wp_settings_errors as $key => $details ) {
1223
				if ( 'tgmpa' === $details['setting'] ) {
1224
					unset( $wp_settings_errors[ $key ] );
1225
					break;
1226
				}
1227
			}
1228
		}
1229
1230
		/**
1231
		 * Add dismissable admin notices.
1232
		 *
1233
		 * Appends a link to the admin nag messages. If clicked, the admin notice disappears and no longer is visible to users.
1234
		 *
1235
		 * @since 2.1.0
1236
		 */
1237
		public function dismiss() {
1238
			if ( isset( $_GET['tgmpa-dismiss'] ) && check_admin_referer( 'tgmpa-dismis-' . get_current_user_id() ) ) {
1239
				update_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, 1 );
1240
			}
1241
		}
1242
1243
		/**
1244
		 * Add individual plugin to our collection of plugins.
1245
		 *
1246
		 * If the required keys are not set or the plugin has already
1247
		 * been registered, the plugin is not added.
1248
		 *
1249
		 * @since 2.0.0
1250
		 *
1251
		 * @param array|null $plugin Array of plugin arguments or null if invalid argument.
1252
		 * @return null Return early if incorrect argument.
1253
		 */
1254
		public function register( $plugin ) {
1255
			if ( empty( $plugin['slug'] ) || empty( $plugin['name'] ) ) {
1256
				return;
1257
			}
1258
1259
			if ( empty( $plugin['slug'] ) || ! is_string( $plugin['slug'] ) || isset( $this->plugins[ $plugin['slug'] ] ) ) {
1260
				return;
1261
			}
1262
1263
			$defaults = array(
1264
				'name'               => '',      // String
1265
				'slug'               => '',      // String
1266
				'source'             => 'repo',  // String
1267
				'required'           => false,   // Boolean
1268
				'version'            => '',      // String
1269
				'force_activation'   => false,   // Boolean
1270
				'force_deactivation' => false,   // Boolean
1271
				'external_url'       => '',      // String
1272
				'is_callable'        => '',      // String|Array.
1273
			);
1274
1275
			// Prepare the received data.
1276
			$plugin = wp_parse_args( $plugin, $defaults );
1277
1278
			// Standardize the received slug.
1279
			$plugin['slug'] = $this->sanitize_key( $plugin['slug'] );
1280
1281
			// Forgive users for using string versions of booleans or floats for version number.
1282
			$plugin['version']            = (string) $plugin['version'];
1283
			$plugin['source']             = empty( $plugin['source'] ) ? 'repo' : $plugin['source'];
1284
			$plugin['required']           = TGMPA_Utils::validate_bool( $plugin['required'] );
1285
			$plugin['force_activation']   = TGMPA_Utils::validate_bool( $plugin['force_activation'] );
1286
			$plugin['force_deactivation'] = TGMPA_Utils::validate_bool( $plugin['force_deactivation'] );
1287
1288
			// Enrich the received data.
1289
			$plugin['file_path']   = $this->_get_plugin_basename_from_slug( $plugin['slug'] );
1290
			$plugin['source_type'] = $this->get_plugin_source_type( $plugin['source'] );
1291
1292
			// Set the class properties.
1293
			$this->plugins[ $plugin['slug'] ]    = $plugin;
1294
			$this->sort_order[ $plugin['slug'] ] = $plugin['name'];
1295
1296
			// Should we add the force activation hook ?
1297
			if ( true === $plugin['force_activation'] ) {
1298
				$this->has_forced_activation = true;
1299
			}
1300
1301
			// Should we add the force deactivation hook ?
1302
			if ( true === $plugin['force_deactivation'] ) {
1303
				$this->has_forced_deactivation = true;
1304
			}
1305
		}
1306
1307
		/**
1308
		 * Determine what type of source the plugin comes from.
1309
		 *
1310
		 * @since 2.5.0
1311
		 *
1312
		 * @param string $source The source of the plugin as provided, either empty (= WP repo), a file path
1313
		 *                       (= bundled) or an external URL.
1314
		 * @return string 'repo', 'external', or 'bundled'
1315
		 */
1316
		protected function get_plugin_source_type( $source ) {
1317
			if ( 'repo' === $source || preg_match( self::WP_REPO_REGEX, $source ) ) {
1318
				return 'repo';
1319
			} elseif ( preg_match( self::IS_URL_REGEX, $source ) ) {
1320
				return 'external';
1321
			} else {
1322
				return 'bundled';
1323
			}
1324
		}
1325
1326
		/**
1327
		 * Sanitizes a string key.
1328
		 *
1329
		 * Near duplicate of WP Core `sanitize_key()`. The difference is that uppercase characters *are*
1330
		 * allowed, so as not to break upgrade paths from non-standard bundled plugins using uppercase
1331
		 * characters in the plugin directory path/slug. Silly them.
1332
		 *
1333
		 * @see https://developer.wordpress.org/reference/hooks/sanitize_key/
1334
		 *
1335
		 * @since 2.5.0
1336
		 *
1337
		 * @param string $key String key.
1338
		 * @return string Sanitized key
1339
		 */
1340
		public function sanitize_key( $key ) {
1341
			$raw_key = $key;
1342
			$key     = preg_replace( '`[^A-Za-z0-9_-]`', '', $key );
1343
1344
			/**
1345
			* Filter a sanitized key string.
1346
			*
1347
			* @since 3.0.0
1348
			*
1349
			* @param string $key     Sanitized key.
1350
			* @param string $raw_key The key prior to sanitization.
1351
			*/
1352
			return apply_filters( 'tgmpa_sanitize_key', $key, $raw_key );
1353
		}
1354
1355
		/**
1356
		 * Amend default configuration settings.
1357
		 *
1358
		 * @since 2.0.0
1359
		 *
1360
		 * @param array $config Array of config options to pass as class properties.
1361
		 */
1362
		public function config( $config ) {
1363
			$keys = array(
1364
				'id',
1365
				'default_path',
1366
				'has_notices',
1367
				'dismissable',
1368
				'dismiss_msg',
1369
				'menu',
1370
				'parent_slug',
1371
				'capability',
1372
				'is_automatic',
1373
				'message',
1374
				'strings',
1375
			);
1376
1377
			foreach ( $keys as $key ) {
1378
				if ( isset( $config[ $key ] ) ) {
1379
					if ( is_array( $config[ $key ] ) ) {
1380
						$this->$key = array_merge( $this->$key, $config[ $key ] );
1381
					} else {
1382
						$this->$key = $config[ $key ];
1383
					}
1384
				}
1385
			}
1386
		}
1387
1388
		/**
1389
		 * Amend action link after plugin installation.
1390
		 *
1391
		 * @since 2.0.0
1392
		 *
1393
		 * @param array $install_actions Existing array of actions.
1394
		 * @return array Amended array of actions.
1395
		 */
1396
		public function actions( $install_actions ) {
1397
			// Remove action links on the TGMPA install page.
1398
			if ( $this->is_tgmpa_page() ) {
1399
				return false;
1400
			}
1401
1402
			return $install_actions;
1403
		}
1404
1405
		/**
1406
		 * Flushes the plugins cache on theme switch to prevent stale entries
1407
		 * from remaining in the plugin table.
1408
		 *
1409
		 * @since 2.4.0
1410
		 *
1411
		 * @param bool $clear_update_cache Optional. Whether to clear the Plugin updates cache.
1412
		 *                                 Parameter added in v2.5.0.
1413
		 */
1414
		public function flush_plugins_cache( $clear_update_cache = true ) {
1415
			wp_clean_plugins_cache( $clear_update_cache );
1416
		}
1417
1418
		/**
1419
		 * Set file_path key for each installed plugin.
1420
		 *
1421
		 * @since 2.1.0
1422
		 *
1423
		 * @param string $plugin_slug Optional. If set, only (re-)populates the file path for that specific plugin.
1424
		 *                            Parameter added in v2.5.0.
1425
		 */
1426
		public function populate_file_path( $plugin_slug = '' ) {
1427
			if ( ! empty( $plugin_slug ) && is_string( $plugin_slug ) && isset( $this->plugins[ $plugin_slug ] ) ) {
1428
				$this->plugins[ $plugin_slug ]['file_path'] = $this->_get_plugin_basename_from_slug( $plugin_slug );
1429
			} else {
1430
				// Add file_path key for all plugins.
1431
				foreach ( $this->plugins as $slug => $values ) {
1432
					$this->plugins[ $slug ]['file_path'] = $this->_get_plugin_basename_from_slug( $slug );
1433
				}
1434
			}
1435
		}
1436
1437
		/**
1438
		 * Helper function to extract the file path of the plugin file from the
1439
		 * plugin slug, if the plugin is installed.
1440
		 *
1441
		 * @since 2.0.0
1442
		 *
1443
		 * @param string $slug Plugin slug (typically folder name) as provided by the developer.
1444
		 * @return string Either file path for plugin if installed, or just the plugin slug.
1445
		 */
1446
		protected function _get_plugin_basename_from_slug( $slug ) {
1447
			$keys = array_keys( $this->get_plugins() );
1448
1449
			foreach ( $keys as $key ) {
1450
				if ( preg_match( '|^' . $slug . '/|', $key ) ) {
1451
					return $key;
1452
				}
1453
			}
1454
1455
			return $slug;
1456
		}
1457
1458
		/**
1459
		 * Retrieve plugin data, given the plugin name.
1460
		 *
1461
		 * Loops through the registered plugins looking for $name. If it finds it,
1462
		 * it returns the $data from that plugin. Otherwise, returns false.
1463
		 *
1464
		 * @since 2.1.0
1465
		 *
1466
		 * @param string $name Name of the plugin, as it was registered.
1467
		 * @param string $data Optional. Array key of plugin data to return. Default is slug.
1468
		 * @return string|boolean Plugin slug if found, false otherwise.
1469
		 */
1470
		public function _get_plugin_data_from_name( $name, $data = 'slug' ) {
1471
			foreach ( $this->plugins as $values ) {
1472
				if ( $name === $values['name'] && isset( $values[ $data ] ) ) {
1473
					return $values[ $data ];
1474
				}
1475
			}
1476
1477
			return false;
1478
		}
1479
1480
		/**
1481
		 * Retrieve the download URL for a package.
1482
		 *
1483
		 * @since 2.5.0
1484
		 *
1485
		 * @param string $slug Plugin slug.
1486
		 * @return string Plugin download URL or path to local file or empty string if undetermined.
1487
		 */
1488
		public function get_download_url( $slug ) {
1489
			$dl_source = '';
1490
1491
			switch ( $this->plugins[ $slug ]['source_type'] ) {
1492
				case 'repo':
1493
					return $this->get_wp_repo_download_url( $slug );
1494
				case 'external':
1495
					return $this->plugins[ $slug ]['source'];
1496
				case 'bundled':
1497
					return $this->default_path . $this->plugins[ $slug ]['source'];
1498
			}
1499
1500
			return $dl_source; // Should never happen.
1501
		}
1502
1503
		/**
1504
		 * Retrieve the download URL for a WP repo package.
1505
		 *
1506
		 * @since 2.5.0
1507
		 *
1508
		 * @param string $slug Plugin slug.
1509
		 * @return string Plugin download URL.
1510
		 */
1511
		protected function get_wp_repo_download_url( $slug ) {
1512
			$source = '';
1513
			$api    = $this->get_plugins_api( $slug );
1514
1515
			if ( false !== $api && isset( $api->download_link ) ) {
1516
				$source = $api->download_link;
1517
			}
1518
1519
			return $source;
1520
		}
1521
1522
		/**
1523
		 * Try to grab information from WordPress API.
1524
		 *
1525
		 * @since 2.5.0
1526
		 *
1527
		 * @param string $slug Plugin slug.
1528
		 * @return object Plugins_api response object on success, WP_Error on failure.
1529
		 */
1530
		protected function get_plugins_api( $slug ) {
1531
			static $api = array(); // Cache received responses.
1532
1533
			if ( ! isset( $api[ $slug ] ) ) {
1534
				if ( ! function_exists( 'plugins_api' ) ) {
1535
					require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
1536
				}
1537
1538
				$response = plugins_api( 'plugin_information', array( 'slug' => $slug, 'fields' => array( 'sections' => false ) ) );
1539
1540
				$api[ $slug ] = false;
1541
1542
				if ( is_wp_error( $response ) ) {
1543
					wp_die( esc_html( $this->strings['oops'] ) );
1544
				} else {
1545
					$api[ $slug ] = $response;
1546
				}
1547
			}
1548
1549
			return $api[ $slug ];
1550
		}
1551
1552
		/**
1553
		 * Retrieve a link to a plugin information page.
1554
		 *
1555
		 * @since 2.5.0
1556
		 *
1557
		 * @param string $slug Plugin slug.
1558
		 * @return string Fully formed html link to a plugin information page if available
1559
		 *                or the plugin name if not.
1560
		 */
1561
		public function get_info_link( $slug ) {
1562
			if ( ! empty( $this->plugins[ $slug ]['external_url'] ) && preg_match( self::IS_URL_REGEX, $this->plugins[ $slug ]['external_url'] ) ) {
1563
				$link = sprintf(
1564
					'<a href="%1$s" target="_blank">%2$s</a>',
1565
					esc_url( $this->plugins[ $slug ]['external_url'] ),
1566
					esc_html( $this->plugins[ $slug ]['name'] )
1567
				);
1568
			} elseif ( 'repo' === $this->plugins[ $slug ]['source_type'] ) {
1569
				$url = add_query_arg(
1570
					array(
1571
						'tab'       => 'plugin-information',
1572
						'plugin'    => urlencode( $slug ),
1573
						'TB_iframe' => 'true',
1574
						'width'     => '640',
1575
						'height'    => '500',
1576
					),
1577
					self_admin_url( 'plugin-install.php' )
1578
				);
1579
1580
				$link = sprintf(
1581
					'<a href="%1$s" class="thickbox">%2$s</a>',
1582
					esc_url( $url ),
1583
					esc_html( $this->plugins[ $slug ]['name'] )
1584
				);
1585
			} else {
1586
				$link = esc_html( $this->plugins[ $slug ]['name'] ); // No hyperlink.
1587
			}
1588
1589
			return $link;
1590
		}
1591
1592
		/**
1593
		 * Determine if we're on the TGMPA Install page.
1594
		 *
1595
		 * @since 2.1.0
1596
		 *
1597
		 * @return boolean True when on the TGMPA page, false otherwise.
1598
		 */
1599
		protected function is_tgmpa_page() {
1600
			return isset( $_GET['page'] ) && $this->menu === $_GET['page'];
1601
		}
1602
1603
		/**
1604
		 * Retrieve the URL to the TGMPA Install page.
1605
		 *
1606
		 * I.e. depending on the config settings passed something along the lines of:
1607
		 * http://example.com/wp-admin/themes.php?page=tgmpa-install-plugins
1608
		 *
1609
		 * @since 2.5.0
1610
		 *
1611
		 * @return string Properly encoded URL (not escaped).
1612
		 */
1613
		public function get_tgmpa_url() {
1614
			static $url;
1615
1616
			if ( ! isset( $url ) ) {
1617
				$parent = $this->parent_slug;
1618
				if ( false === strpos( $parent, '.php' ) ) {
1619
					$parent = 'admin.php';
1620
				}
1621
				$url = add_query_arg(
1622
					array(
1623
						'page' => urlencode( $this->menu ),
1624
					),
1625
					self_admin_url( $parent )
1626
				);
1627
			}
1628
1629
			return $url;
1630
		}
1631
1632
		/**
1633
		 * Retrieve the URL to the TGMPA Install page for a specific plugin status (view).
1634
		 *
1635
		 * I.e. depending on the config settings passed something along the lines of:
1636
		 * http://example.com/wp-admin/themes.php?page=tgmpa-install-plugins&plugin_status=install
1637
		 *
1638
		 * @since 2.5.0
1639
		 *
1640
		 * @param string $status Plugin status - either 'install', 'update' or 'activate'.
1641
		 * @return string Properly encoded URL (not escaped).
1642
		 */
1643
		public function get_tgmpa_status_url( $status ) {
1644
			return add_query_arg(
1645
				array(
1646
					'plugin_status' => urlencode( $status ),
1647
				),
1648
				$this->get_tgmpa_url()
1649
			);
1650
		}
1651
1652
		/**
1653
		 * Determine whether there are open actions for plugins registered with TGMPA.
1654
		 *
1655
		 * @since 2.5.0
1656
		 *
1657
		 * @return bool True if complete, i.e. no outstanding actions. False otherwise.
1658
		 */
1659
		public function is_tgmpa_complete() {
1660
			$complete = true;
1661
			foreach ( $this->plugins as $slug => $plugin ) {
1662
				if ( ! $this->is_plugin_active( $slug ) || false !== $this->does_plugin_have_update( $slug ) ) {
1663
					$complete = false;
1664
					break;
1665
				}
1666
			}
1667
1668
			return $complete;
1669
		}
1670
1671
		/**
1672
		 * Check if a plugin is installed. Does not take must-use plugins into account.
1673
		 *
1674
		 * @since 2.5.0
1675
		 *
1676
		 * @param string $slug Plugin slug.
1677
		 * @return bool True if installed, false otherwise.
1678
		 */
1679
		public function is_plugin_installed( $slug ) {
1680
			$installed_plugins = $this->get_plugins(); // Retrieve a list of all installed plugins (WP cached).
1681
1682
			return ( ! empty( $installed_plugins[ $this->plugins[ $slug ]['file_path'] ] ) );
1683
		}
1684
1685
		/**
1686
		 * Check if a plugin is active.
1687
		 *
1688
		 * @since 2.5.0
1689
		 *
1690
		 * @param string $slug Plugin slug.
1691
		 * @return bool True if active, false otherwise.
1692
		 */
1693
		public function is_plugin_active( $slug ) {
1694
			return ( ( ! empty( $this->plugins[ $slug ]['is_callable'] ) && is_callable( $this->plugins[ $slug ]['is_callable'] ) ) || is_plugin_active( $this->plugins[ $slug ]['file_path'] ) );
1695
		}
1696
1697
		/**
1698
		 * Check if a plugin can be updated, i.e. if we have information on the minimum WP version required
1699
		 * available, check whether the current install meets them.
1700
		 *
1701
		 * @since 2.5.0
1702
		 *
1703
		 * @param string $slug Plugin slug.
1704
		 * @return bool True if OK to update, false otherwise.
1705
		 */
1706
		public function can_plugin_update( $slug ) {
1707
			// We currently can't get reliable info on non-WP-repo plugins - issue #380.
1708
			if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) {
1709
				return true;
1710
			}
1711
1712
			$api = $this->get_plugins_api( $slug );
1713
1714
			if ( false !== $api && isset( $api->requires ) ) {
1715
				return version_compare( $GLOBALS['wp_version'], $api->requires, '>=' );
1716
			}
1717
1718
			// No usable info received from the plugins API, presume we can update.
1719
			return true;
1720
		}
1721
1722
		/**
1723
		 * Check to see if the plugin is 'updatetable', i.e. installed, with an update available
1724
		 * and no WP version requirements blocking it.
1725
		 *
1726
		 * @since 2.x.x
1727
		 *
1728
		 * @param string $slug Plugin slug.
1729
		 * @return bool True if OK to proceed with update, false otherwise.
1730
		 */
1731
		public function is_plugin_updatetable( $slug ) {
1732
			if ( ! $this->is_plugin_installed( $slug ) ) {
1733
				return false;
1734
			} else {
1735
				return ( $this->does_plugin_have_update( $slug ) && $this->can_plugin_update( $slug ) );
1736
			}
1737
		}
1738
1739
		/**
1740
		 * Check if a plugin can be activated, i.e. is not currently active and meets the minimum
1741
		 * plugin version requirements set in TGMPA (if any).
1742
		 *
1743
		 * @since 2.5.0
1744
		 *
1745
		 * @param string $slug Plugin slug.
1746
		 * @return bool True if OK to activate, false otherwise.
1747
		 */
1748
		public function can_plugin_activate( $slug ) {
1749
			return ( ! $this->is_plugin_active( $slug ) && ! $this->does_plugin_require_update( $slug ) );
1750
		}
1751
1752
		/**
1753
		 * Retrieve the version number of an installed plugin.
1754
		 *
1755
		 * @since 2.5.0
1756
		 *
1757
		 * @param string $slug Plugin slug.
1758
		 * @return string Version number as string or an empty string if the plugin is not installed
1759
		 *                or version unknown (plugins which don't comply with the plugin header standard).
1760
		 */
1761
		public function get_installed_version( $slug ) {
1762
			$installed_plugins = $this->get_plugins(); // Retrieve a list of all installed plugins (WP cached).
1763
1764
			if ( ! empty( $installed_plugins[ $this->plugins[ $slug ]['file_path'] ]['Version'] ) ) {
1765
				return $installed_plugins[ $this->plugins[ $slug ]['file_path'] ]['Version'];
1766
			}
1767
1768
			return '';
1769
		}
1770
1771
		/**
1772
		 * Check whether a plugin complies with the minimum version requirements.
1773
		 *
1774
		 * @since 2.5.0
1775
		 *
1776
		 * @param string $slug Plugin slug.
1777
		 * @return bool True when a plugin needs to be updated, otherwise false.
1778
		 */
1779
		public function does_plugin_require_update( $slug ) {
1780
			$installed_version = $this->get_installed_version( $slug );
1781
			$minimum_version   = $this->plugins[ $slug ]['version'];
1782
1783
			return version_compare( $minimum_version, $installed_version, '>' );
1784
		}
1785
1786
		/**
1787
		 * Check whether there is an update available for a plugin.
1788
		 *
1789
		 * @since 2.5.0
1790
		 *
1791
		 * @param string $slug Plugin slug.
1792
		 * @return false|string Version number string of the available update or false if no update available.
1793
		 */
1794
		public function does_plugin_have_update( $slug ) {
1795
			// Presume bundled and external plugins will point to a package which meets the minimum required version.
1796
			if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) {
1797
				if ( $this->does_plugin_require_update( $slug ) ) {
1798
					return $this->plugins[ $slug ]['version'];
1799
				}
1800
1801
				return false;
1802
			}
1803
1804
			$repo_updates = get_site_transient( 'update_plugins' );
1805
1806 View Code Duplication
			if ( isset( $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->new_version ) ) {
1807
				return $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->new_version;
1808
			}
1809
1810
			return false;
1811
		}
1812
1813
		/**
1814
		 * Retrieve potential upgrade notice for a plugin.
1815
		 *
1816
		 * @since 2.5.0
1817
		 *
1818
		 * @param string $slug Plugin slug.
1819
		 * @return string The upgrade notice or an empty string if no message was available or provided.
1820
		 */
1821
		public function get_upgrade_notice( $slug ) {
1822
			// We currently can't get reliable info on non-WP-repo plugins - issue #380.
1823
			if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) {
1824
				return '';
1825
			}
1826
1827
			$repo_updates = get_site_transient( 'update_plugins' );
1828
1829 View Code Duplication
			if ( ! empty( $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->upgrade_notice ) ) {
1830
				return $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->upgrade_notice;
1831
			}
1832
1833
			return '';
1834
		}
1835
1836
		/**
1837
		 * Wrapper around the core WP get_plugins function, making sure it's actually available.
1838
		 *
1839
		 * @since 2.5.0
1840
		 *
1841
		 * @param string $plugin_folder Optional. Relative path to single plugin folder.
1842
		 * @return array Array of installed plugins with plugin information.
1843
		 */
1844
		public function get_plugins( $plugin_folder = '' ) {
1845
			if ( ! function_exists( 'get_plugins' ) ) {
1846
				require_once ABSPATH . 'wp-admin/includes/plugin.php';
1847
			}
1848
1849
			return get_plugins( $plugin_folder );
1850
		}
1851
1852
		/**
1853
		 * Delete dismissable nag option when theme is switched.
1854
		 *
1855
		 * This ensures that the user(s) is/are again reminded via nag of required
1856
		 * and/or recommended plugins if they re-activate the theme.
1857
		 *
1858
		 * @since 2.1.1
1859
		 */
1860
		public function update_dismiss() {
1861
			delete_metadata( 'user', null, 'tgmpa_dismissed_notice_' . $this->id, null, true );
1862
		}
1863
1864
		/**
1865
		 * Forces plugin activation if the parameter 'force_activation' is
1866
		 * set to true.
1867
		 *
1868
		 * This allows theme authors to specify certain plugins that must be
1869
		 * active at all times while using the current theme.
1870
		 *
1871
		 * Please take special care when using this parameter as it has the
1872
		 * potential to be harmful if not used correctly. Setting this parameter
1873
		 * to true will not allow the specified plugin to be deactivated unless
1874
		 * the user switches themes.
1875
		 *
1876
		 * @since 2.2.0
1877
		 */
1878
		public function force_activation() {
1879
			foreach ( $this->plugins as $slug => $plugin ) {
1880
				if ( true === $plugin['force_activation'] ) {
1881
					if ( ! $this->is_plugin_installed( $slug ) ) {
1882
						// Oops, plugin isn't there so iterate to next condition.
1883
						continue;
1884
					} elseif ( $this->can_plugin_activate( $slug ) ) {
1885
						// There we go, activate the plugin.
1886
						activate_plugin( $plugin['file_path'] );
1887
					}
1888
				}
1889
			}
1890
		}
1891
1892
		/**
1893
		 * Forces plugin deactivation if the parameter 'force_deactivation'
1894
		 * is set to true.
1895
		 *
1896
		 * This allows theme authors to specify certain plugins that must be
1897
		 * deactivated upon switching from the current theme to another.
1898
		 *
1899
		 * Please take special care when using this parameter as it has the
1900
		 * potential to be harmful if not used correctly.
1901
		 *
1902
		 * @since 2.2.0
1903
		 */
1904
		public function force_deactivation() {
1905
			foreach ( $this->plugins as $slug => $plugin ) {
1906
				// Only proceed forward if the parameter is set to true and plugin is active.
1907
				if ( true === $plugin['force_deactivation'] && $this->is_plugin_active( $slug ) ) {
1908
					deactivate_plugins( $plugin['file_path'] );
1909
				}
1910
			}
1911
		}
1912
1913
		/**
1914
		 * Echo the current TGMPA version number to the page.
1915
		 */
1916
		public function show_tgmpa_version() {
1917
			echo '<p style="float: right; padding: 0em 1.5em 0.5em 0;"><strong><small>',
1918
				esc_html( sprintf( _x( 'TGMPA v%s', '%s = version number', 'tgmpa' ), self::TGMPA_VERSION ) ),
1919
				'</small></strong></p>';
1920
		}
1921
1922
		/**
1923
		 * Returns the singleton instance of the class.
1924
		 *
1925
		 * @since 2.4.0
1926
		 *
1927
		 * @return object The TGM_Plugin_Activation object.
1928
		 */
1929
		public static function get_instance() {
1930
			if ( ! isset( self::$instance ) && ! ( self::$instance instanceof self ) ) {
1931
				self::$instance = new self();
1932
			}
1933
1934
			return self::$instance;
1935
		}
1936
	}
1937
1938
	if ( ! function_exists( 'load_tgm_plugin_activation' ) ) {
1939
		/**
1940
		 * Ensure only one instance of the class is ever invoked.
1941
		 */
1942
		function load_tgm_plugin_activation() {
1943
			$GLOBALS['tgmpa'] = TGM_Plugin_Activation::get_instance();
1944
		}
1945
	}
1946
1947
	if ( did_action( 'plugins_loaded' ) ) {
1948
		load_tgm_plugin_activation();
1949
	} else {
1950
		add_action( 'plugins_loaded', 'load_tgm_plugin_activation' );
1951
	}
1952
}
1953
1954
if ( ! function_exists( 'tgmpa' ) ) {
1955
	/**
1956
	 * Helper function to register a collection of required plugins.
1957
	 *
1958
	 * @since 2.0.0
1959
	 * @api
1960
	 *
1961
	 * @param array $plugins An array of plugin arrays.
1962
	 * @param array $config  Optional. An array of configuration values.
1963
	 */
1964
	function tgmpa( $plugins, $config = array() ) {
1965
		$instance = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
1966
1967
		foreach ( $plugins as $plugin ) {
1968
			call_user_func( array( $instance, 'register' ), $plugin );
1969
		}
1970
1971
		if ( ! empty( $config ) && is_array( $config ) ) {
1972
			// Send out notices for deprecated arguments passed.
1973
			if ( isset( $config['notices'] ) ) {
1974
				_deprecated_argument( __FUNCTION__, '2.2.0', 'The `notices` config parameter was renamed to `has_notices` in TGMPA 2.2.0. Please adjust your configuration.' );
1975
				if ( ! isset( $config['has_notices'] ) ) {
1976
					$config['has_notices'] = $config['notices'];
1977
				}
1978
			}
1979
1980
			if ( isset( $config['parent_menu_slug'] ) ) {
1981
				_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.' );
1982
			}
1983
			if ( isset( $config['parent_url_slug'] ) ) {
1984
				_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.' );
1985
			}
1986
1987
			call_user_func( array( $instance, 'config' ), $config );
1988
		}
1989
	}
1990
}
1991
1992
/**
1993
 * WP_List_Table isn't always available. If it isn't available,
1994
 * we load it here.
1995
 *
1996
 * @since 2.2.0
1997
 */
1998
if ( ! class_exists( 'WP_List_Table' ) ) {
1999
	require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
2000
}
2001
2002
if ( ! class_exists( 'TGMPA_List_Table' ) ) {
2003
2004
	/**
2005
	 * List table class for handling plugins.
2006
	 *
2007
	 * Extends the WP_List_Table class to provide a future-compatible
2008
	 * way of listing out all required/recommended plugins.
2009
	 *
2010
	 * Gives users an interface similar to the Plugin Administration
2011
	 * area with similar (albeit stripped down) capabilities.
2012
	 *
2013
	 * This class also allows for the bulk install of plugins.
2014
	 *
2015
	 * @since 2.2.0
2016
	 *
2017
	 * @package TGM-Plugin-Activation
2018
	 * @author  Thomas Griffin
2019
	 * @author  Gary Jones
2020
	 */
2021
	class TGMPA_List_Table extends WP_List_Table {
2022
		/**
2023
		 * TGMPA instance.
2024
		 *
2025
		 * @since 2.5.0
2026
		 *
2027
		 * @var object
2028
		 */
2029
		protected $tgmpa;
2030
2031
		/**
2032
		 * The currently chosen view.
2033
		 *
2034
		 * @since 2.5.0
2035
		 *
2036
		 * @var string One of: 'all', 'install', 'update', 'activate'
2037
		 */
2038
		public $view_context = 'all';
2039
2040
		/**
2041
		 * The plugin counts for the various views.
2042
		 *
2043
		 * @since 2.5.0
2044
		 *
2045
		 * @var array
2046
		 */
2047
		protected $view_totals = array(
2048
			'all'      => 0,
2049
			'install'  => 0,
2050
			'update'   => 0,
2051
			'activate' => 0,
2052
		);
2053
2054
		/**
2055
		 * References parent constructor and sets defaults for class.
2056
		 *
2057
		 * @since 2.2.0
2058
		 */
2059
		public function __construct() {
2060
			$this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
2061
2062
			parent::__construct(
2063
				array(
2064
					'singular' => 'plugin',
2065
					'plural'   => 'plugins',
2066
					'ajax'     => false,
2067
				)
2068
			);
2069
2070
			if ( isset( $_REQUEST['plugin_status'] ) && in_array( $_REQUEST['plugin_status'], array( 'install', 'update', 'activate' ), true ) ) {
2071
				$this->view_context = sanitize_key( $_REQUEST['plugin_status'] );
2072
			}
2073
2074
			add_filter( 'tgmpa_table_data_items', array( $this, 'sort_table_items' ) );
2075
		}
2076
2077
		/**
2078
		 * Get a list of CSS classes for the <table> tag.
2079
		 *
2080
		 * Overruled to prevent the 'plural' argument from being added.
2081
		 *
2082
		 * @since 2.5.0
2083
		 *
2084
		 * @return array CSS classnames.
2085
		 */
2086
		public function get_table_classes() {
2087
			return array( 'widefat', 'fixed' );
2088
		}
2089
2090
		/**
2091
		 * Gathers and renames all of our plugin information to be used by WP_List_Table to create our table.
2092
		 *
2093
		 * @since 2.2.0
2094
		 *
2095
		 * @return array $table_data Information for use in table.
2096
		 */
2097
		protected function _gather_plugin_data() {
2098
			// Load thickbox for plugin links.
2099
			$this->tgmpa->admin_init();
2100
			$this->tgmpa->thickbox();
2101
2102
			// Categorize the plugins which have open actions.
2103
			$plugins = $this->categorize_plugins_to_views();
2104
2105
			// Set the counts for the view links.
2106
			$this->set_view_totals( $plugins );
2107
2108
			// Prep variables for use and grab list of all installed plugins.
2109
			$table_data = array();
2110
			$i          = 0;
2111
2112
			// Redirect to the 'all' view if no plugins were found for the selected view context.
2113
			if ( empty( $plugins[ $this->view_context ] ) ) {
2114
				$this->view_context = 'all';
2115
			}
2116
2117
			foreach ( $plugins[ $this->view_context ] as $slug => $plugin ) {
2118
				$table_data[ $i ]['sanitized_plugin']  = $plugin['name'];
2119
				$table_data[ $i ]['slug']              = $slug;
2120
				$table_data[ $i ]['plugin']            = '<strong>' . $this->tgmpa->get_info_link( $slug ) . '</strong>';
2121
				$table_data[ $i ]['source']            = $this->get_plugin_source_type_text( $plugin['source_type'] );
2122
				$table_data[ $i ]['type']              = $this->get_plugin_advise_type_text( $plugin['required'] );
2123
				$table_data[ $i ]['status']            = $this->get_plugin_status_text( $slug );
2124
				$table_data[ $i ]['installed_version'] = $this->tgmpa->get_installed_version( $slug );
2125
				$table_data[ $i ]['minimum_version']   = $plugin['version'];
2126
				$table_data[ $i ]['available_version'] = $this->tgmpa->does_plugin_have_update( $slug );
2127
2128
				// Prep the upgrade notice info.
2129
				$upgrade_notice = $this->tgmpa->get_upgrade_notice( $slug );
2130
				if ( ! empty( $upgrade_notice ) ) {
2131
					$table_data[ $i ]['upgrade_notice'] = $upgrade_notice;
2132
2133
					add_action( "tgmpa_after_plugin_row_$slug", array( $this, 'wp_plugin_update_row' ), 10, 2 );
2134
				}
2135
2136
				$table_data[ $i ] = apply_filters( 'tgmpa_table_data_item', $table_data[ $i ], $plugin );
2137
2138
				$i++;
2139
			}
2140
2141
			return $table_data;
2142
		}
2143
2144
		/**
2145
		 * Categorize the plugins which have open actions into views for the TGMPA page.
2146
		 *
2147
		 * @since 2.5.0
2148
		 */
2149
		protected function categorize_plugins_to_views() {
2150
			$plugins = array(
2151
				'all'      => array(), // Meaning: all plugins which still have open actions.
2152
				'install'  => array(),
2153
				'update'   => array(),
2154
				'activate' => array(),
2155
			);
2156
2157
			foreach ( $this->tgmpa->plugins as $slug => $plugin ) {
2158
				if ( $this->tgmpa->is_plugin_active( $slug ) && false === $this->tgmpa->does_plugin_have_update( $slug ) ) {
2159
					// No need to display plugins if they are installed, up-to-date and active.
2160
					continue;
2161
				} else {
2162
					$plugins['all'][ $slug ] = $plugin;
2163
2164
					if ( ! $this->tgmpa->is_plugin_installed( $slug ) ) {
2165
						$plugins['install'][ $slug ] = $plugin;
2166
					} else {
2167
						if ( false !== $this->tgmpa->does_plugin_have_update( $slug ) ) {
2168
							$plugins['update'][ $slug ] = $plugin;
2169
						}
2170
2171
						if ( $this->tgmpa->can_plugin_activate( $slug ) ) {
2172
							$plugins['activate'][ $slug ] = $plugin;
2173
						}
2174
					}
2175
				}
2176
			}
2177
2178
			return $plugins;
2179
		}
2180
2181
		/**
2182
		 * Set the counts for the view links.
2183
		 *
2184
		 * @since 2.5.0
2185
		 *
2186
		 * @param array $plugins Plugins order by view.
2187
		 */
2188
		protected function set_view_totals( $plugins ) {
2189
			foreach ( $plugins as $type => $list ) {
2190
				$this->view_totals[ $type ] = count( $list );
2191
			}
2192
		}
2193
2194
		/**
2195
		 * Get the plugin required/recommended text string.
2196
		 *
2197
		 * @since 2.5.0
2198
		 *
2199
		 * @param string $required Plugin required setting.
2200
		 * @return string
2201
		 */
2202
		protected function get_plugin_advise_type_text( $required ) {
2203
			if ( true === $required ) {
2204
				return __( 'Required', 'tgmpa' );
2205
			}
2206
2207
			return __( 'Recommended', 'tgmpa' );
2208
		}
2209
2210
		/**
2211
		 * Get the plugin source type text string.
2212
		 *
2213
		 * @since 2.5.0
2214
		 *
2215
		 * @param string $type Plugin type.
2216
		 * @return string
2217
		 */
2218
		protected function get_plugin_source_type_text( $type ) {
2219
			$string = '';
2220
2221
			switch ( $type ) {
2222
				case 'repo':
2223
					$string = __( 'WordPress Repository', 'tgmpa' );
2224
					break;
2225
				case 'external':
2226
					$string = __( 'External Source', 'tgmpa' );
2227
					break;
2228
				case 'bundled':
2229
					$string = __( 'Pre-Packaged', 'tgmpa' );
2230
					break;
2231
			}
2232
2233
			return $string;
2234
		}
2235
2236
		/**
2237
		 * Determine the plugin status message.
2238
		 *
2239
		 * @since 2.5.0
2240
		 *
2241
		 * @param string $slug Plugin slug.
2242
		 * @return string
2243
		 */
2244
		protected function get_plugin_status_text( $slug ) {
2245
			if ( ! $this->tgmpa->is_plugin_installed( $slug ) ) {
2246
				return __( 'Not Installed', 'tgmpa' );
2247
			}
2248
2249
			if ( ! $this->tgmpa->is_plugin_active( $slug ) ) {
2250
				$install_status = __( 'Installed But Not Activated', 'tgmpa' );
2251
			} else {
2252
				$install_status = __( 'Active', 'tgmpa' );
2253
			}
2254
2255
			$update_status = '';
2256
2257
			if ( $this->tgmpa->does_plugin_require_update( $slug ) && false === $this->tgmpa->does_plugin_have_update( $slug ) ) {
2258
				$update_status = __( 'Required Update not Available', 'tgmpa' );
2259
2260
			} elseif ( $this->tgmpa->does_plugin_require_update( $slug ) ) {
2261
				$update_status = __( 'Requires Update', 'tgmpa' );
2262
2263
			} elseif ( false !== $this->tgmpa->does_plugin_have_update( $slug ) ) {
2264
				$update_status = __( 'Update recommended', 'tgmpa' );
2265
			}
2266
2267
			if ( '' === $update_status ) {
2268
				return $install_status;
2269
			}
2270
2271
			return sprintf(
2272
				_x( '%1$s, %2$s', '%1$s = install status, %2$s = update status', 'tgmpa' ),
2273
				$install_status,
2274
				$update_status
2275
			);
2276
		}
2277
2278
		/**
2279
		 * Sort plugins by Required/Recommended type and by alphabetical plugin name within each type.
2280
		 *
2281
		 * @since 2.5.0
2282
		 *
2283
		 * @param array $items Prepared table items.
2284
		 * @return array Sorted table items.
2285
		 */
2286
		public function sort_table_items( $items ) {
2287
			$type = array();
2288
			$name = array();
2289
2290
			foreach ( $items as $i => $plugin ) {
2291
				$type[ $i ] = $plugin['type']; // Required / recommended.
2292
				$name[ $i ] = $plugin['sanitized_plugin'];
2293
			}
2294
2295
			array_multisort( $type, SORT_DESC, $name, SORT_ASC, $items );
2296
2297
			return $items;
2298
		}
2299
2300
		/**
2301
		 * Get an associative array ( id => link ) of the views available on this table.
2302
		 *
2303
		 * @since 2.5.0
2304
		 *
2305
		 * @return array
2306
		 */
2307
		public function get_views() {
2308
			$status_links = array();
2309
2310
			foreach ( $this->view_totals as $type => $count ) {
2311
				if ( $count < 1 ) {
2312
					continue;
2313
				}
2314
2315
				switch ( $type ) {
2316
					case 'all':
2317
						$text = _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $count, 'plugins', 'tgmpa' );
2318
						break;
2319
					case 'install':
2320
						$text = _n( 'To Install <span class="count">(%s)</span>', 'To Install <span class="count">(%s)</span>', $count, 'tgmpa' );
2321
						break;
2322
					case 'update':
2323
						$text = _n( 'Update Available <span class="count">(%s)</span>', 'Update Available <span class="count">(%s)</span>', $count, 'tgmpa' );
2324
						break;
2325
					case 'activate':
2326
						$text = _n( 'To Activate <span class="count">(%s)</span>', 'To Activate <span class="count">(%s)</span>', $count, 'tgmpa' );
2327
						break;
2328
					default:
2329
						$text = '';
2330
						break;
2331
				}
2332
2333
				if ( ! empty( $text ) ) {
2334
2335
					$status_links[ $type ] = sprintf(
2336
						'<a href="%s"%s>%s</a>',
2337
						esc_url( $this->tgmpa->get_tgmpa_status_url( $type ) ),
2338
						( $type === $this->view_context ) ? ' class="current"' : '',
2339
						sprintf( $text, number_format_i18n( $count ) )
2340
					);
2341
				}
2342
			}
2343
2344
			return $status_links;
2345
		}
2346
2347
		/**
2348
		 * Create default columns to display important plugin information
2349
		 * like type, action and status.
2350
		 *
2351
		 * @since 2.2.0
2352
		 *
2353
		 * @param array  $item        Array of item data.
2354
		 * @param string $column_name The name of the column.
2355
		 * @return string
2356
		 */
2357
		public function column_default( $item, $column_name ) {
2358
			return $item[ $column_name ];
2359
		}
2360
2361
		/**
2362
		 * Required for bulk installing.
2363
		 *
2364
		 * Adds a checkbox for each plugin.
2365
		 *
2366
		 * @since 2.2.0
2367
		 *
2368
		 * @param array $item Array of item data.
2369
		 * @return string The input checkbox with all necessary info.
2370
		 */
2371
		public function column_cb( $item ) {
2372
			return sprintf(
2373
				'<input type="checkbox" name="%1$s[]" value="%2$s" id="%3$s" />',
2374
				esc_attr( $this->_args['singular'] ),
2375
				esc_attr( $item['slug'] ),
2376
				esc_attr( $item['sanitized_plugin'] )
2377
			);
2378
		}
2379
2380
		/**
2381
		 * Create default title column along with the action links.
2382
		 *
2383
		 * @since 2.2.0
2384
		 *
2385
		 * @param array $item Array of item data.
2386
		 * @return string The plugin name and action links.
2387
		 */
2388
		public function column_plugin( $item ) {
2389
			return sprintf(
2390
				'%1$s %2$s',
2391
				$item['plugin'],
2392
				$this->row_actions( $this->get_row_actions( $item ), true )
2393
			);
2394
		}
2395
2396
		/**
2397
		 * Create version information column.
2398
		 *
2399
		 * @since 2.5.0
2400
		 *
2401
		 * @param array $item Array of item data.
2402
		 * @return string HTML-formatted version information.
2403
		 */
2404
		public function column_version( $item ) {
2405
			$output = array();
2406
2407
			if ( $this->tgmpa->is_plugin_installed( $item['slug'] ) ) {
2408
				$installed = ! empty( $item['installed_version'] ) ? $item['installed_version'] : _x( 'unknown', 'as in: "version nr unknown"', 'tgmpa' );
2409
2410
				$color = '';
2411
				if ( ! empty( $item['minimum_version'] ) && $this->tgmpa->does_plugin_require_update( $item['slug'] ) ) {
2412
					$color = ' color: #ff0000; font-weight: bold;';
2413
				}
2414
2415
				$output[] = sprintf(
2416
					'<p><span style="min-width: 32px; text-align: right; float: right;%1$s">%2$s</span>' . __( 'Installed version:', 'tgmpa' ) . '</p>',
2417
					$color,
2418
					$installed
2419
				);
2420
			}
2421
2422
			if ( ! empty( $item['minimum_version'] ) ) {
2423
				$output[] = sprintf(
2424
					'<p><span style="min-width: 32px; text-align: right; float: right;">%1$s</span>' . __( 'Minimum required version:', 'tgmpa' ) . '</p>',
2425
					$item['minimum_version']
2426
				);
2427
			}
2428
2429
			if ( ! empty( $item['available_version'] ) ) {
2430
				$color = '';
2431
				if ( ! empty( $item['minimum_version'] ) && version_compare( $item['available_version'], $item['minimum_version'], '>=' ) ) {
2432
					$color = ' color: #71C671; font-weight: bold;';
2433
				}
2434
2435
				$output[] = sprintf(
2436
					'<p><span style="min-width: 32px; text-align: right; float: right;%1$s">%2$s</span>' . __( 'Available version:', 'tgmpa' ) . '</p>',
2437
					$color,
2438
					$item['available_version']
2439
				);
2440
			}
2441
2442
			if ( empty( $output ) ) {
2443
				return '&nbsp;'; // Let's not break the table layout.
2444
			} else {
2445
				return implode( "\n", $output );
2446
			}
2447
		}
2448
2449
		/**
2450
		 * Sets default message within the plugins table if no plugins
2451
		 * are left for interaction.
2452
		 *
2453
		 * Hides the menu item to prevent the user from clicking and
2454
		 * getting a permissions error.
2455
		 *
2456
		 * @since 2.2.0
2457
		 */
2458
		public function no_items() {
2459
			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() ) );
2460
			echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>';
2461
		}
2462
2463
		/**
2464
		 * Output all the column information within the table.
2465
		 *
2466
		 * @since 2.2.0
2467
		 *
2468
		 * @return array $columns The column names.
2469
		 */
2470
		public function get_columns() {
2471
			$columns = array(
2472
				'cb'     => '<input type="checkbox" />',
2473
				'plugin' => __( 'Plugin', 'tgmpa' ),
2474
				'source' => __( 'Source', 'tgmpa' ),
2475
				'type'   => __( 'Type', 'tgmpa' ),
2476
			);
2477
2478
			if ( 'all' === $this->view_context || 'update' === $this->view_context ) {
2479
				$columns['version'] = __( 'Version', 'tgmpa' );
2480
				$columns['status']  = __( 'Status', 'tgmpa' );
2481
			}
2482
2483
			return apply_filters( 'tgmpa_table_columns', $columns );
2484
		}
2485
2486
		/**
2487
		 * Get name of default primary column
2488
		 *
2489
		 * @since 2.5.0 / WP 4.3+ compatibility
2490
		 * @access protected
2491
		 *
2492
		 * @return string
2493
		 */
2494
		protected function get_default_primary_column_name() {
2495
			return 'plugin';
2496
		}
2497
2498
		/**
2499
		 * Get the name of the primary column.
2500
		 *
2501
		 * @since 2.5.0 / WP 4.3+ compatibility
2502
		 * @access protected
2503
		 *
2504
		 * @return string The name of the primary column.
2505
		 */
2506
		protected function get_primary_column_name() {
2507
			if ( method_exists( 'WP_List_Table', 'get_primary_column_name' ) ) {
2508
				return parent::get_primary_column_name();
2509
			} else {
2510
				return $this->get_default_primary_column_name();
2511
			}
2512
		}
2513
2514
		/**
2515
		 * Get the actions which are relevant for a specific plugin row.
2516
		 *
2517
		 * @since 2.5.0
2518
		 *
2519
		 * @param array $item Array of item data.
2520
		 * @return array Array with relevant action links.
2521
		 */
2522
		protected function get_row_actions( $item ) {
2523
			$actions      = array();
2524
			$action_links = array();
2525
2526
			// Display the 'Install' action link if the plugin is not yet available.
2527
			if ( ! $this->tgmpa->is_plugin_installed( $item['slug'] ) ) {
2528
				$actions['install'] = _x( 'Install %2$s', '%2$s = plugin name in screen reader markup', 'tgmpa' );
2529
			} else {
2530
				// Display the 'Update' action link if an update is available and WP complies with plugin minimum.
2531
				if ( false !== $this->tgmpa->does_plugin_have_update( $item['slug'] ) && $this->tgmpa->can_plugin_update( $item['slug'] ) ) {
2532
					$actions['update'] = _x( 'Update %2$s', '%2$s = plugin name in screen reader markup', 'tgmpa' );
2533
				}
2534
2535
				// Display the 'Activate' action link, but only if the plugin meets the minimum version.
2536
				if ( $this->tgmpa->can_plugin_activate( $item['slug'] ) ) {
2537
					$actions['activate'] = _x( 'Activate %2$s', '%2$s = plugin name in screen reader markup', 'tgmpa' );
2538
				}
2539
			}
2540
2541
			// Create the actual links.
2542
			foreach ( $actions as $action => $text ) {
2543
				$nonce_url = wp_nonce_url(
2544
					add_query_arg(
2545
						array(
2546
							'plugin'           => urlencode( $item['slug'] ),
2547
							'tgmpa-' . $action => $action . '-plugin',
2548
						),
2549
						$this->tgmpa->get_tgmpa_url()
2550
					),
2551
					'tgmpa-' . $action,
2552
					'tgmpa-nonce'
2553
				);
2554
2555
				$action_links[ $action ] = sprintf(
2556
					'<a href="%1$s">' . esc_html( $text ) . '</a>',
2557
					esc_url( $nonce_url ),
2558
					'<span class="screen-reader-text">' . esc_html( $item['sanitized_plugin'] ) . '</span>'
2559
				);
2560
			}
2561
2562
			$prefix = ( defined( 'WP_NETWORK_ADMIN' ) && WP_NETWORK_ADMIN ) ? 'network_admin_' : '';
2563
			return apply_filters( "tgmpa_{$prefix}plugin_action_links", array_filter( $action_links ), $item['slug'], $item, $this->view_context );
2564
		}
2565
2566
		/**
2567
		 * Generates content for a single row of the table.
2568
		 *
2569
		 * @since 2.5.0
2570
		 *
2571
		 * @param object $item The current item.
2572
		 */
2573
		public function single_row( $item ) {
2574
			parent::single_row( $item );
2575
2576
			/**
2577
			 * Fires after each specific row in the TGMPA Plugins list table.
2578
			 *
2579
			 * The dynamic portion of the hook name, `$item['slug']`, refers to the slug
2580
			 * for the plugin.
2581
			 *
2582
			 * @since 2.5.0
2583
			 */
2584
			do_action( "tgmpa_after_plugin_row_{$item['slug']}", $item['slug'], $item, $this->view_context );
2585
		}
2586
2587
		/**
2588
		 * Show the upgrade notice below a plugin row if there is one.
2589
		 *
2590
		 * @since 2.5.0
2591
		 *
2592
		 * @see /wp-admin/includes/update.php
2593
		 *
2594
		 * @param string $slug Plugin slug.
2595
		 * @param array  $item The information available in this table row.
2596
		 * @return null Return early if upgrade notice is empty.
2597
		 */
2598
		public function wp_plugin_update_row( $slug, $item ) {
2599
			if ( empty( $item['upgrade_notice'] ) ) {
2600
				return;
2601
			}
2602
2603
			echo '
2604
				<tr class="plugin-update-tr">
2605
					<td colspan="', absint( $this->get_column_count() ), '" class="plugin-update colspanchange">
2606
						<div class="update-message">',
2607
							esc_html__( 'Upgrade message from the plugin author:', 'tgmpa' ),
2608
							' <strong>', wp_kses_data( $item['upgrade_notice'] ), '</strong>
2609
						</div>
2610
					</td>
2611
				</tr>';
2612
		}
2613
2614
		/**
2615
		 * Extra controls to be displayed between bulk actions and pagination.
2616
		 *
2617
		 * @since 2.5.0
2618
		 *
2619
		 * @param string $which 'top' or 'bottom' table navigation.
2620
		 */
2621
		public function extra_tablenav( $which ) {
2622
			if ( 'bottom' === $which ) {
2623
				$this->tgmpa->show_tgmpa_version();
2624
			}
2625
		}
2626
2627
		/**
2628
		 * Defines the bulk actions for handling registered plugins.
2629
		 *
2630
		 * @since 2.2.0
2631
		 *
2632
		 * @return array $actions The bulk actions for the plugin install table.
2633
		 */
2634
		public function get_bulk_actions() {
2635
2636
			$actions = array();
2637
2638
			if ( 'update' !== $this->view_context && 'activate' !== $this->view_context ) {
2639
				if ( current_user_can( 'install_plugins' ) ) {
2640
					$actions['tgmpa-bulk-install'] = __( 'Install', 'tgmpa' );
2641
				}
2642
			}
2643
2644
			if ( 'install' !== $this->view_context ) {
2645
				if ( current_user_can( 'update_plugins' ) ) {
2646
					$actions['tgmpa-bulk-update'] = __( 'Update', 'tgmpa' );
2647
				}
2648
				if ( current_user_can( 'activate_plugins' ) ) {
2649
					$actions['tgmpa-bulk-activate'] = __( 'Activate', 'tgmpa' );
2650
				}
2651
			}
2652
2653
			return $actions;
2654
		}
2655
2656
		/**
2657
		 * Processes bulk installation and activation actions.
2658
		 *
2659
		 * The bulk installation process looks for the $_POST information and passes that
2660
		 * through if a user has to use WP_Filesystem to enter their credentials.
2661
		 *
2662
		 * @since 2.2.0
2663
		 */
2664
		public function process_bulk_actions() {
2665
			// Bulk installation process.
2666
			if ( 'tgmpa-bulk-install' === $this->current_action() || 'tgmpa-bulk-update' === $this->current_action() ) {
2667
2668
				check_admin_referer( 'bulk-' . $this->_args['plural'] );
2669
2670
				$install_type = 'install';
2671
				if ( 'tgmpa-bulk-update' === $this->current_action() ) {
2672
					$install_type = 'update';
2673
				}
2674
2675
				$plugins_to_install = array();
2676
2677
				// Did user actually select any plugins to install/update ?
2678 View Code Duplication
				if ( empty( $_POST['plugin'] ) ) {
2679
					if ( 'install' === $install_type ) {
2680
						$message = __( 'No plugins were selected to be installed. No action taken.', 'tgmpa' );
2681
					} else {
2682
						$message = __( 'No plugins were selected to be updated. No action taken.', 'tgmpa' );
2683
					}
2684
2685
					echo '<div id="message" class="error"><p>', esc_html( $message ), '</p></div>';
2686
2687
					return false;
2688
				}
2689
2690
				if ( is_array( $_POST['plugin'] ) ) {
2691
					$plugins_to_install = (array) $_POST['plugin'];
2692
				} elseif ( is_string( $_POST['plugin'] ) ) {
2693
					// Received via Filesystem page - un-flatten array (WP bug #19643).
2694
					$plugins_to_install = explode( ',', $_POST['plugin'] );
2695
				}
2696
2697
				// Sanitize the received input.
2698
				$plugins_to_install = array_map( 'urldecode', $plugins_to_install );
2699
				$plugins_to_install = array_map( array( $this->tgmpa, 'sanitize_key' ), $plugins_to_install );
2700
2701
				// Validate the received input.
2702
				foreach ( $plugins_to_install as $key => $slug ) {
2703
					// Check if the plugin was registered with TGMPA and remove if not.
2704
					if ( ! isset( $this->tgmpa->plugins[ $slug ] ) ) {
2705
						unset( $plugins_to_install[ $key ] );
2706
						continue;
2707
					}
2708
2709
					// For install: make sure this is a plugin we *can* install and not one already installed.
2710
					if ( 'install' === $install_type && true === $this->tgmpa->is_plugin_installed( $slug ) ) {
2711
						unset( $plugins_to_install[ $key ] );
2712
					}
2713
2714
					// For updates: make sure this is a plugin we *can* update (update available and WP version ok).
2715
					if ( 'update' === $install_type && false === $this->tgmpa->is_plugin_updatetable( $slug ) ) {
2716
						unset( $plugins_to_install[ $key ] );
2717
					}
2718
				}
2719
2720
				// No need to proceed further if we have no plugins to handle.
2721 View Code Duplication
				if ( empty( $plugins_to_install ) ) {
2722
					if ( 'install' === $install_type ) {
2723
						$message = __( 'No plugins are available to be installed at this time.', 'tgmpa' );
2724
					} else {
2725
						$message = __( 'No plugins are available to be updated at this time.', 'tgmpa' );
2726
					}
2727
2728
					echo '<div id="message" class="error"><p>', esc_html( $message ), '</p></div>';
2729
2730
					return false;
2731
				}
2732
2733
				// Pass all necessary information if WP_Filesystem is needed.
2734
				$url = wp_nonce_url(
2735
					$this->tgmpa->get_tgmpa_url(),
2736
					'bulk-' . $this->_args['plural']
2737
				);
2738
2739
				// Give validated data back to $_POST which is the only place the filesystem looks for extra fields.
2740
				$_POST['plugin'] = implode( ',', $plugins_to_install ); // Work around for WP bug #19643.
2741
2742
				$method = ''; // Leave blank so WP_Filesystem can populate it as necessary.
2743
				$fields = array_keys( $_POST ); // Extra fields to pass to WP_Filesystem.
2744
2745 View Code Duplication
				if ( false === ( $creds = request_filesystem_credentials( esc_url_raw( $url ), $method, false, false, $fields ) ) ) {
2746
					return true; // Stop the normal page form from displaying, credential request form will be shown.
2747
				}
2748
2749
				// Now we have some credentials, setup WP_Filesystem.
2750 View Code Duplication
				if ( ! WP_Filesystem( $creds ) ) {
2751
					// Our credentials were no good, ask the user for them again.
2752
					request_filesystem_credentials( esc_url_raw( $url ), $method, true, false, $fields );
2753
2754
					return true;
2755
				}
2756
2757
				/* If we arrive here, we have the filesystem */
2758
2759
				// Store all information in arrays since we are processing a bulk installation.
2760
				$names      = array();
2761
				$sources    = array(); // Needed for installs.
2762
				$file_paths = array(); // Needed for upgrades.
2763
				$to_inject  = array(); // Information to inject into the update_plugins transient.
2764
2765
				// Prepare the data for validated plugins for the install/upgrade.
2766
				foreach ( $plugins_to_install as $slug ) {
2767
					$name   = $this->tgmpa->plugins[ $slug ]['name'];
2768
					$source = $this->tgmpa->get_download_url( $slug );
2769
2770
					if ( ! empty( $name ) && ! empty( $source ) ) {
2771
						$names[] = $name;
2772
2773
						switch ( $install_type ) {
2774
2775
							case 'install':
2776
								$sources[] = $source;
2777
								break;
2778
2779
							case 'update':
2780
								$file_paths[]                 = $this->tgmpa->plugins[ $slug ]['file_path'];
2781
								$to_inject[ $slug ]           = $this->tgmpa->plugins[ $slug ];
2782
								$to_inject[ $slug ]['source'] = $source;
2783
								break;
2784
						}
2785
					}
2786
				}
2787
				unset( $slug, $name, $source );
2788
2789
				// Create a new instance of TGMPA_Bulk_Installer.
2790
				$installer = new TGMPA_Bulk_Installer(
2791
					new TGMPA_Bulk_Installer_Skin(
2792
						array(
2793
							'url'          => esc_url_raw( $this->tgmpa->get_tgmpa_url() ),
2794
							'nonce'        => 'bulk-' . $this->_args['plural'],
2795
							'names'        => $names,
2796
							'install_type' => $install_type,
2797
						)
2798
					)
2799
				);
2800
2801
				// Wrap the install process with the appropriate HTML.
2802
				echo '<div class="tgmpa wrap">',
2803
					'<h2>', esc_html( get_admin_page_title() ), '</h2>';
2804
2805
				// Process the bulk installation submissions.
2806
				add_filter( 'upgrader_source_selection', array( $this->tgmpa, 'maybe_adjust_source_dir' ), 1, 3 );
2807
2808
				if ( 'tgmpa-bulk-update' === $this->current_action() ) {
2809
					// Inject our info into the update transient.
2810
					$this->tgmpa->inject_update_info( $to_inject );
2811
2812
					$installer->bulk_upgrade( $file_paths );
2813
				} else {
2814
					$installer->bulk_install( $sources );
2815
				}
2816
2817
				remove_filter( 'upgrader_source_selection', array( $this->tgmpa, 'maybe_adjust_source_dir' ), 1, 3 );
2818
2819
				echo '</div>';
2820
2821
				return true;
2822
			}
2823
2824
			// Bulk activation process.
2825
			if ( 'tgmpa-bulk-activate' === $this->current_action() ) {
2826
				check_admin_referer( 'bulk-' . $this->_args['plural'] );
2827
2828
				// Did user actually select any plugins to activate ?
2829
				if ( empty( $_POST['plugin'] ) ) {
2830
					echo '<div id="message" class="error"><p>', esc_html__( 'No plugins were selected to be activated. No action taken.', 'tgmpa' ), '</p></div>';
2831
2832
					return false;
2833
				}
2834
2835
				// Grab plugin data from $_POST.
2836
				$plugins = array();
2837
				if ( isset( $_POST['plugin'] ) ) {
2838
					$plugins = array_map( 'urldecode', (array) $_POST['plugin'] );
2839
					$plugins = array_map( array( $this->tgmpa, 'sanitize_key' ), $plugins );
2840
				}
2841
2842
				$plugins_to_activate = array();
2843
				$plugin_names        = array();
2844
2845
				// Grab the file paths for the selected & inactive plugins from the registration array.
2846
				foreach ( $plugins as $slug ) {
2847
					if ( $this->tgmpa->can_plugin_activate( $slug ) ) {
2848
						$plugins_to_activate[] = $this->tgmpa->plugins[ $slug ]['file_path'];
2849
						$plugin_names[]        = $this->tgmpa->plugins[ $slug ]['name'];
2850
					}
2851
				}
2852
				unset( $slug );
2853
2854
				// Return early if there are no plugins to activate.
2855
				if ( empty( $plugins_to_activate ) ) {
2856
					echo '<div id="message" class="error"><p>', esc_html__( 'No plugins are available to be activated at this time.', 'tgmpa' ), '</p></div>';
2857
2858
					return false;
2859
				}
2860
2861
				// Now we are good to go - let's start activating plugins.
2862
				$activate = activate_plugins( $plugins_to_activate );
2863
2864
				if ( is_wp_error( $activate ) ) {
2865
					echo '<div id="message" class="error"><p>', wp_kses_post( $activate->get_error_message() ), '</p></div>';
2866
				} else {
2867
					$count        = count( $plugin_names ); // Count so we can use _n function.
2868
					$plugin_names = array_map( array( 'TGMPA_Utils', 'wrap_in_strong' ), $plugin_names );
2869
					$last_plugin  = array_pop( $plugin_names ); // Pop off last name to prep for readability.
2870
					$imploded     = empty( $plugin_names ) ? $last_plugin : ( implode( ', ', $plugin_names ) . ' ' . esc_html_x( 'and', 'plugin A *and* plugin B', 'tgmpa' ) . ' ' . $last_plugin );
2871
2872
					printf( // WPCS: xss ok.
2873
						'<div id="message" class="updated"><p>%1$s %2$s.</p></div>',
2874
						esc_html( _n( 'The following plugin was activated successfully:', 'The following plugins were activated successfully:', $count, 'tgmpa' ) ),
2875
						$imploded
2876
					);
2877
2878
					// Update recently activated plugins option.
2879
					$recent = (array) get_option( 'recently_activated' );
2880
					foreach ( $plugins_to_activate as $plugin => $time ) {
2881
						if ( isset( $recent[ $plugin ] ) ) {
2882
							unset( $recent[ $plugin ] );
2883
						}
2884
					}
2885
					update_option( 'recently_activated', $recent );
2886
				}
2887
2888
				unset( $_POST ); // Reset the $_POST variable in case user wants to perform one action after another.
2889
2890
				return true;
2891
			}
2892
2893
			return false;
2894
		}
2895
2896
		/**
2897
		 * Prepares all of our information to be outputted into a usable table.
2898
		 *
2899
		 * @since 2.2.0
2900
		 */
2901
		public function prepare_items() {
2902
			$columns               = $this->get_columns(); // Get all necessary column information.
2903
			$hidden                = array(); // No columns to hide, but we must set as an array.
2904
			$sortable              = array(); // No reason to make sortable columns.
2905
			$primary               = $this->get_primary_column_name(); // Column which has the row actions.
2906
			$this->_column_headers = array( $columns, $hidden, $sortable, $primary ); // Get all necessary column headers.
2907
2908
			// Process our bulk activations here.
2909
			if ( 'tgmpa-bulk-activate' === $this->current_action() ) {
2910
				$this->process_bulk_actions();
2911
			}
2912
2913
			// Store all of our plugin data into $items array so WP_List_Table can use it.
2914
			$this->items = apply_filters( 'tgmpa_table_data_items', $this->_gather_plugin_data() );
2915
		}
2916
2917
		/* *********** DEPRECATED METHODS *********** */
2918
2919
		/**
2920
		 * Retrieve plugin data, given the plugin name.
2921
		 *
2922
		 * @since      2.2.0
2923
		 * @deprecated 2.5.0 use {@see TGM_Plugin_Activation::_get_plugin_data_from_name()} instead.
2924
		 * @see        TGM_Plugin_Activation::_get_plugin_data_from_name()
2925
		 *
2926
		 * @param string $name Name of the plugin, as it was registered.
2927
		 * @param string $data Optional. Array key of plugin data to return. Default is slug.
2928
		 * @return string|boolean Plugin slug if found, false otherwise.
2929
		 */
2930
		protected function _get_plugin_data_from_name( $name, $data = 'slug' ) {
2931
			_deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'TGM_Plugin_Activation::_get_plugin_data_from_name()' );
2932
2933
			return $this->tgmpa->_get_plugin_data_from_name( $name, $data );
2934
		}
2935
	}
2936
}
2937
2938
2939
if ( ! class_exists( 'TGM_Bulk_Installer' ) ) {
2940
2941
	/**
2942
	 * Hack: Prevent TGMPA v2.4.1- bulk installer class from being loaded if 2.4.1- is loaded after 2.5+.
2943
	 */
2944
	class TGM_Bulk_Installer {
2945
	}
2946
}
2947
if ( ! class_exists( 'TGM_Bulk_Installer_Skin' ) ) {
2948
2949
	/**
2950
	 * Hack: Prevent TGMPA v2.4.1- bulk installer skin class from being loaded if 2.4.1- is loaded after 2.5+.
2951
	 */
2952
	class TGM_Bulk_Installer_Skin {
2953
	}
2954
}
2955
2956
/**
2957
 * The WP_Upgrader file isn't always available. If it isn't available,
2958
 * we load it here.
2959
 *
2960
 * We check to make sure no action or activation keys are set so that WordPress
2961
 * does not try to re-include the class when processing upgrades or installs outside
2962
 * of the class.
2963
 *
2964
 * @since 2.2.0
2965
 */
2966
add_action( 'admin_init', 'tgmpa_load_bulk_installer' );
2967
if ( ! function_exists( 'tgmpa_load_bulk_installer' ) ) {
2968
	/**
2969
	 * Load bulk installer
2970
	 */
2971
	function tgmpa_load_bulk_installer() {
2972
		// Silently fail if 2.5+ is loaded *after* an older version.
2973
		if ( ! isset( $GLOBALS['tgmpa'] ) ) {
2974
			return;
2975
		}
2976
2977
		// Get TGMPA class instance.
2978
		$tgmpa_instance = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
2979
2980
		if ( isset( $_GET['page'] ) && $tgmpa_instance->menu === $_GET['page'] ) {
2981
			if ( ! class_exists( 'Plugin_Upgrader', false ) ) {
2982
				require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
2983
			}
2984
2985
			if ( ! class_exists( 'TGMPA_Bulk_Installer' ) ) {
2986
2987
				/**
2988
				 * Installer class to handle bulk plugin installations.
2989
				 *
2990
				 * Extends WP_Upgrader and customizes to suit the installation of multiple
2991
				 * plugins.
2992
				 *
2993
				 * @since 2.2.0
2994
				 *
2995
				 * @internal Since 2.5.0 the class is an extension of Plugin_Upgrader rather than WP_Upgrader
2996
				 * @internal Since 2.5.2 the class has been renamed from TGM_Bulk_Installer to TGMPA_Bulk_Installer.
2997
				 *           This was done to prevent backward compatibility issues with v2.3.6.
2998
				 *
2999
				 * @package TGM-Plugin-Activation
3000
				 * @author  Thomas Griffin
3001
				 * @author  Gary Jones
3002
				 */
3003
				class TGMPA_Bulk_Installer extends Plugin_Upgrader {
3004
					/**
3005
					 * Holds result of bulk plugin installation.
3006
					 *
3007
					 * @since 2.2.0
3008
					 *
3009
					 * @var string
3010
					 */
3011
					public $result;
3012
3013
					/**
3014
					 * Flag to check if bulk installation is occurring or not.
3015
					 *
3016
					 * @since 2.2.0
3017
					 *
3018
					 * @var boolean
3019
					 */
3020
					public $bulk = false;
3021
3022
					/**
3023
					 * TGMPA instance
3024
					 *
3025
					 * @since 2.5.0
3026
					 *
3027
					 * @var object
3028
					 */
3029
					protected $tgmpa;
3030
3031
					/**
3032
					 * Whether or not the destination directory needs to be cleared ( = on update).
3033
					 *
3034
					 * @since 2.5.0
3035
					 *
3036
					 * @var bool
3037
					 */
3038
					protected $clear_destination = false;
3039
3040
					/**
3041
					 * References parent constructor and sets defaults for class.
3042
					 *
3043
					 * @since 2.2.0
3044
					 *
3045
					 * @param \Bulk_Upgrader_Skin|null $skin Installer skin.
3046
					 */
3047
					public function __construct( $skin = null ) {
3048
						// Get TGMPA class instance.
3049
						$this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
3050
3051
						parent::__construct( $skin );
3052
3053
						if ( isset( $this->skin->options['install_type'] ) && 'update' === $this->skin->options['install_type'] ) {
3054
							$this->clear_destination = true;
3055
						}
3056
3057
						if ( $this->tgmpa->is_automatic ) {
3058
							$this->activate_strings();
3059
						}
3060
3061
						add_action( 'upgrader_process_complete', array( $this->tgmpa, 'populate_file_path' ) );
3062
					}
3063
3064
					/**
3065
					 * Sets the correct activation strings for the installer skin to use.
3066
					 *
3067
					 * @since 2.2.0
3068
					 */
3069
					public function activate_strings() {
3070
						$this->strings['activation_failed']  = __( 'Plugin activation failed.', 'tgmpa' );
3071
						$this->strings['activation_success'] = __( 'Plugin activated successfully.', 'tgmpa' );
3072
					}
3073
3074
					/**
3075
					 * Performs the actual installation of each plugin.
3076
					 *
3077
					 * @since 2.2.0
3078
					 *
3079
					 * @see WP_Upgrader::run()
3080
					 *
3081
					 * @param array $options The installation config options.
3082
					 * @return null|array Return early if error, array of installation data on success.
3083
					 */
3084
					public function run( $options ) {
3085
						$result = parent::run( $options );
3086
3087
						// Reset the strings in case we changed one during automatic activation.
3088
						if ( $this->tgmpa->is_automatic ) {
3089
							if ( 'update' === $this->skin->options['install_type'] ) {
3090
								$this->upgrade_strings();
3091
							} else {
3092
								$this->install_strings();
3093
							}
3094
						}
3095
3096
						return $result;
3097
					}
3098
3099
					/**
3100
					 * Processes the bulk installation of plugins.
3101
					 *
3102
					 * @since 2.2.0
3103
					 *
3104
					 * @internal This is basically a near identical copy of the WP Core Plugin_Upgrader::bulk_upgrade()
3105
					 * method, with minor adjustments to deal with new installs instead of upgrades.
3106
					 * For ease of future synchronizations, the adjustments are clearly commented, but no other
3107
					 * comments are added. Code style has been made to comply.
3108
					 *
3109
					 * @see Plugin_Upgrader::bulk_upgrade()
3110
					 * @see https://core.trac.wordpress.org/browser/tags/4.2.1/src/wp-admin/includes/class-wp-upgrader.php#L838
3111
					 *
3112
					 * @param array $plugins The plugin sources needed for installation.
3113
					 * @param array $args    Arbitrary passed extra arguments.
3114
					 * @return string|bool Install confirmation messages on success, false on failure.
3115
					 */
3116
					public function bulk_install( $plugins, $args = array() ) {
3117
						// [TGMPA + ] Hook auto-activation in.
3118
						add_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3119
3120
						$defaults    = array(
3121
							'clear_update_cache' => true,
3122
						);
3123
						$parsed_args = wp_parse_args( $args, $defaults );
3124
3125
						$this->init();
3126
						$this->bulk = true;
3127
3128
						$this->install_strings(); // [TGMPA + ] adjusted.
3129
3130
						/* [TGMPA - ] $current = get_site_transient( 'update_plugins' ); */
3131
3132
						/* [TGMPA - ] add_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'), 10, 4); */
3133
3134
						$this->skin->header();
3135
3136
						// Connect to the Filesystem first.
3137
						$res = $this->fs_connect( array( WP_CONTENT_DIR, WP_PLUGIN_DIR ) );
3138
						if ( ! $res ) {
3139
							$this->skin->footer();
3140
3141
							return false;
3142
						}
3143
3144
						$this->skin->bulk_header();
3145
3146
						// Only start maintenance mode if:
3147
						// - running Multisite and there are one or more plugins specified, OR
3148
						// - a plugin with an update available is currently active.
3149
						// @TODO: For multisite, maintenance mode should only kick in for individual sites if at all possible.
3150
						$maintenance = ( is_multisite() && ! empty( $plugins ) );
3151
3152
						/*
3153
						[TGMPA - ]
3154
						foreach ( $plugins as $plugin )
3155
							$maintenance = $maintenance || ( is_plugin_active( $plugin ) && isset( $current->response[ $plugin] ) );
3156
						*/
3157
						if ( $maintenance ) {
3158
							$this->maintenance_mode( true );
3159
						}
3160
3161
						$results = array();
3162
3163
						$this->update_count   = count( $plugins );
3164
						$this->update_current = 0;
3165
						foreach ( $plugins as $plugin ) {
3166
							$this->update_current++;
3167
3168
							/*
3169
							[TGMPA - ]
3170
							$this->skin->plugin_info = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin, false, true);
3171
3172
							if ( !isset( $current->response[ $plugin ] ) ) {
3173
								$this->skin->set_result('up_to_date');
3174
								$this->skin->before();
3175
								$this->skin->feedback('up_to_date');
3176
								$this->skin->after();
3177
								$results[$plugin] = true;
3178
								continue;
3179
							}
3180
3181
							// Get the URL to the zip file
3182
							$r = $current->response[ $plugin ];
3183
3184
							$this->skin->plugin_active = is_plugin_active($plugin);
3185
							*/
3186
3187
							$result = $this->run(
3188
								array(
3189
									'package'           => $plugin, // [TGMPA + ] adjusted.
3190
									'destination'       => WP_PLUGIN_DIR,
3191
									'clear_destination' => false, // [TGMPA + ] adjusted.
3192
									'clear_working'     => true,
3193
									'is_multi'          => true,
3194
									'hook_extra'        => array(
3195
										'plugin' => $plugin,
3196
									),
3197
								)
3198
							);
3199
3200
							$results[ $plugin ] = $this->result;
3201
3202
							// Prevent credentials auth screen from displaying multiple times.
3203
							if ( false === $result ) {
3204
								break;
3205
							}
3206
						} //end foreach $plugins
3207
3208
						$this->maintenance_mode( false );
3209
3210
						/**
3211
						 * Fires when the bulk upgrader process is complete.
3212
						 *
3213
						 * @since WP 3.6.0 / TGMPA 2.5.0
3214
						 *
3215
						 * @param Plugin_Upgrader $this Plugin_Upgrader instance. In other contexts, $this, might
3216
						 *                              be a Theme_Upgrader or Core_Upgrade instance.
3217
						 * @param array           $data {
3218
						 *     Array of bulk item update data.
3219
						 *
3220
						 *     @type string $action   Type of action. Default 'update'.
3221
						 *     @type string $type     Type of update process. Accepts 'plugin', 'theme', or 'core'.
3222
						 *     @type bool   $bulk     Whether the update process is a bulk update. Default true.
3223
						 *     @type array  $packages Array of plugin, theme, or core packages to update.
3224
						 * }
3225
						 */
3226
						do_action( 'upgrader_process_complete', $this, array(
3227
							'action'  => 'install', // [TGMPA + ] adjusted.
3228
							'type'    => 'plugin',
3229
							'bulk'    => true,
3230
							'plugins' => $plugins,
3231
						) );
3232
3233
						$this->skin->bulk_footer();
3234
3235
						$this->skin->footer();
3236
3237
						// Cleanup our hooks, in case something else does a upgrade on this connection.
3238
						/* [TGMPA - ] remove_filter('upgrader_clear_destination', array($this, 'delete_old_plugin')); */
3239
3240
						// [TGMPA + ] Remove our auto-activation hook.
3241
						remove_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3242
3243
						// Force refresh of plugin update information.
3244
						wp_clean_plugins_cache( $parsed_args['clear_update_cache'] );
3245
3246
						return $results;
3247
					}
3248
3249
					/**
3250
					 * Handle a bulk upgrade request.
3251
					 *
3252
					 * @since 2.5.0
3253
					 *
3254
					 * @see Plugin_Upgrader::bulk_upgrade()
3255
					 *
3256
					 * @param array $plugins The local WP file_path's of the plugins which should be upgraded.
3257
					 * @param array $args    Arbitrary passed extra arguments.
3258
					 * @return string|bool Install confirmation messages on success, false on failure.
3259
					 */
3260
					public function bulk_upgrade( $plugins, $args = array() ) {
3261
3262
						add_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3263
3264
						$result = parent::bulk_upgrade( $plugins, $args );
3265
3266
						remove_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3267
3268
						return $result;
3269
					}
3270
3271
					/**
3272
					 * Abuse a filter to auto-activate plugins after installation.
3273
					 *
3274
					 * Hooked into the 'upgrader_post_install' filter hook.
3275
					 *
3276
					 * @since 2.5.0
3277
					 *
3278
					 * @param bool $bool The value we need to give back (true).
3279
					 * @return bool
3280
					 */
3281
					public function auto_activate( $bool ) {
3282
						// Only process the activation of installed plugins if the automatic flag is set to true.
3283
						if ( $this->tgmpa->is_automatic ) {
3284
							// Flush plugins cache so the headers of the newly installed plugins will be read correctly.
3285
							wp_clean_plugins_cache();
3286
3287
							// Get the installed plugin file.
3288
							$plugin_info = $this->plugin_info();
3289
3290
							// Don't try to activate on upgrade of active plugin as WP will do this already.
3291
							if ( ! is_plugin_active( $plugin_info ) ) {
3292
								$activate = activate_plugin( $plugin_info );
3293
3294
								// Adjust the success string based on the activation result.
3295
								$this->strings['process_success'] = $this->strings['process_success'] . "<br />\n";
3296
3297
								if ( is_wp_error( $activate ) ) {
3298
									$this->skin->error( $activate );
3299
									$this->strings['process_success'] .= $this->strings['activation_failed'];
3300
								} else {
3301
									$this->strings['process_success'] .= $this->strings['activation_success'];
3302
								}
3303
							}
3304
						}
3305
3306
						return $bool;
3307
					}
3308
				}
3309
			}
3310
3311
			if ( ! class_exists( 'TGMPA_Bulk_Installer_Skin' ) ) {
3312
3313
				/**
3314
				 * Installer skin to set strings for the bulk plugin installations..
3315
				 *
3316
				 * Extends Bulk_Upgrader_Skin and customizes to suit the installation of multiple
3317
				 * plugins.
3318
				 *
3319
				 * @since 2.2.0
3320
				 *
3321
				 * @internal Since 2.5.2 the class has been renamed from TGM_Bulk_Installer_Skin to
3322
				 *           TGMPA_Bulk_Installer_Skin.
3323
				 *           This was done to prevent backward compatibility issues with v2.3.6.
3324
				 *
3325
				 * @see https://core.trac.wordpress.org/browser/trunk/src/wp-admin/includes/class-wp-upgrader-skins.php
3326
				 *
3327
				 * @package TGM-Plugin-Activation
3328
				 * @author  Thomas Griffin
3329
				 * @author  Gary Jones
3330
				 */
3331
				class TGMPA_Bulk_Installer_Skin extends Bulk_Upgrader_Skin {
3332
					/**
3333
					 * Holds plugin info for each individual plugin installation.
3334
					 *
3335
					 * @since 2.2.0
3336
					 *
3337
					 * @var array
3338
					 */
3339
					public $plugin_info = array();
3340
3341
					/**
3342
					 * Holds names of plugins that are undergoing bulk installations.
3343
					 *
3344
					 * @since 2.2.0
3345
					 *
3346
					 * @var array
3347
					 */
3348
					public $plugin_names = array();
3349
3350
					/**
3351
					 * Integer to use for iteration through each plugin installation.
3352
					 *
3353
					 * @since 2.2.0
3354
					 *
3355
					 * @var integer
3356
					 */
3357
					public $i = 0;
3358
3359
					/**
3360
					 * TGMPA instance
3361
					 *
3362
					 * @since 2.5.0
3363
					 *
3364
					 * @var object
3365
					 */
3366
					protected $tgmpa;
3367
3368
					/**
3369
					 * Constructor. Parses default args with new ones and extracts them for use.
3370
					 *
3371
					 * @since 2.2.0
3372
					 *
3373
					 * @param array $args Arguments to pass for use within the class.
3374
					 */
3375
					public function __construct( $args = array() ) {
3376
						// Get TGMPA class instance.
3377
						$this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
3378
3379
						// Parse default and new args.
3380
						$defaults = array(
3381
							'url'          => '',
3382
							'nonce'        => '',
3383
							'names'        => array(),
3384
							'install_type' => 'install',
3385
						);
3386
						$args     = wp_parse_args( $args, $defaults );
3387
3388
						// Set plugin names to $this->plugin_names property.
3389
						$this->plugin_names = $args['names'];
3390
3391
						// Extract the new args.
3392
						parent::__construct( $args );
3393
					}
3394
3395
					/**
3396
					 * Sets install skin strings for each individual plugin.
3397
					 *
3398
					 * Checks to see if the automatic activation flag is set and uses the
3399
					 * the proper strings accordingly.
3400
					 *
3401
					 * @since 2.2.0
3402
					 */
3403
					public function add_strings() {
3404
						if ( 'update' === $this->options['install_type'] ) {
3405
							parent::add_strings();
3406
							$this->upgrader->strings['skin_before_update_header'] = __( 'Updating Plugin %1$s (%2$d/%3$d)', 'tgmpa' );
3407
						} else {
3408
							$this->upgrader->strings['skin_update_failed_error'] = __( 'An error occurred while installing %1$s: <strong>%2$s</strong>.', 'tgmpa' );
3409
							$this->upgrader->strings['skin_update_failed']       = __( 'The installation of %1$s failed.', 'tgmpa' );
3410
3411
							if ( $this->tgmpa->is_automatic ) {
3412
								// Automatic activation strings.
3413
								$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' );
3414
								$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>';
3415
								$this->upgrader->strings['skin_upgrade_end']          = __( 'All installations and activations have been completed.', 'tgmpa' );
3416
								$this->upgrader->strings['skin_before_update_header'] = __( 'Installing and Activating Plugin %1$s (%2$d/%3$d)', 'tgmpa' );
3417
							} else {
3418
								// Default installation strings.
3419
								$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' );
3420
								$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>';
3421
								$this->upgrader->strings['skin_upgrade_end']          = __( 'All installations have been completed.', 'tgmpa' );
3422
								$this->upgrader->strings['skin_before_update_header'] = __( 'Installing Plugin %1$s (%2$d/%3$d)', 'tgmpa' );
3423
							}
3424
						}
3425
					}
3426
3427
					/**
3428
					 * Outputs the header strings and necessary JS before each plugin installation.
3429
					 *
3430
					 * @since 2.2.0
3431
					 *
3432
					 * @param string $title Unused in this implementation.
3433
					 */
3434
					public function before( $title = '' ) {
3435
						if ( empty( $title ) ) {
3436
							$title = esc_html( $this->plugin_names[ $this->i ] );
3437
						}
3438
						parent::before( $title );
3439
					}
3440
3441
					/**
3442
					 * Outputs the footer strings and necessary JS after each plugin installation.
3443
					 *
3444
					 * Checks for any errors and outputs them if they exist, else output
3445
					 * success strings.
3446
					 *
3447
					 * @since 2.2.0
3448
					 *
3449
					 * @param string $title Unused in this implementation.
3450
					 */
3451
					public function after( $title = '' ) {
3452
						if ( empty( $title ) ) {
3453
							$title = esc_html( $this->plugin_names[ $this->i ] );
3454
						}
3455
						parent::after( $title );
3456
3457
						$this->i++;
3458
					}
3459
3460
					/**
3461
					 * Outputs links after bulk plugin installation is complete.
3462
					 *
3463
					 * @since 2.2.0
3464
					 */
3465
					public function bulk_footer() {
3466
						// Serve up the string to say installations (and possibly activations) are complete.
3467
						parent::bulk_footer();
3468
3469
						// Flush plugins cache so we can make sure that the installed plugins list is always up to date.
3470
						wp_clean_plugins_cache();
3471
3472
						$this->tgmpa->show_tgmpa_version();
3473
3474
						// Display message based on if all plugins are now active or not.
3475
						$update_actions = array();
3476
3477
						if ( $this->tgmpa->is_tgmpa_complete() ) {
3478
							// All plugins are active, so we display the complete string and hide the menu to protect users.
3479
							echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>';
3480
							$update_actions['dashboard'] = sprintf(
3481
								esc_html( $this->tgmpa->strings['complete'] ),
3482
								'<a href="' . esc_url( self_admin_url() ) . '">' . esc_html__( 'Return to the Dashboard', 'tgmpa' ) . '</a>'
3483
							);
3484
						} else {
3485
							$update_actions['tgmpa_page'] = '<a href="' . esc_url( $this->tgmpa->get_tgmpa_url() ) . '" target="_parent">' . esc_html( $this->tgmpa->strings['return'] ) . '</a>';
3486
						}
3487
3488
						/**
3489
						 * Filter the list of action links available following bulk plugin installs/updates.
3490
						 *
3491
						 * @since 2.5.0
3492
						 *
3493
						 * @param array $update_actions Array of plugin action links.
3494
						 * @param array $plugin_info    Array of information for the last-handled plugin.
3495
						 */
3496
						$update_actions = apply_filters( 'tgmpa_update_bulk_plugins_complete_actions', $update_actions, $this->plugin_info );
3497
3498
						if ( ! empty( $update_actions ) ) {
3499
							$this->feedback( implode( ' | ', (array) $update_actions ) );
3500
						}
3501
					}
3502
3503
					/* *********** DEPRECATED METHODS *********** */
3504
3505
					/**
3506
					 * Flush header output buffer.
3507
					 *
3508
					 * @since      2.2.0
3509
					 * @deprecated 2.5.0 use {@see Bulk_Upgrader_Skin::flush_output()} instead
3510
					 * @see        Bulk_Upgrader_Skin::flush_output()
3511
					 */
3512
					public function before_flush_output() {
3513
						_deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'Bulk_Upgrader_Skin::flush_output()' );
3514
						$this->flush_output();
3515
					}
3516
3517
					/**
3518
					 * Flush footer output buffer and iterate $this->i to make sure the
3519
					 * installation strings reference the correct plugin.
3520
					 *
3521
					 * @since      2.2.0
3522
					 * @deprecated 2.5.0 use {@see Bulk_Upgrader_Skin::flush_output()} instead
3523
					 * @see        Bulk_Upgrader_Skin::flush_output()
3524
					 */
3525
					public function after_flush_output() {
3526
						_deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'Bulk_Upgrader_Skin::flush_output()' );
3527
						$this->flush_output();
3528
						$this->i++;
3529
					}
3530
				}
3531
			}
3532
		}
3533
	}
3534
}
3535
3536
if ( ! class_exists( 'TGMPA_Utils' ) ) {
3537
3538
	/**
3539
	 * Generic utilities for TGMPA.
3540
	 *
3541
	 * All methods are static, poor-dev name-spacing class wrapper.
3542
	 *
3543
	 * Class was called TGM_Utils in 2.5.0 but renamed TGMPA_Utils in 2.5.1 as this was conflicting with Soliloquy.
3544
	 *
3545
	 * @since 2.5.0
3546
	 *
3547
	 * @package TGM-Plugin-Activation
3548
	 * @author  Juliette Reinders Folmer
3549
	 */
3550
	class TGMPA_Utils {
3551
		/**
3552
		 * Whether the PHP filter extension is enabled.
3553
		 *
3554
		 * @see http://php.net/book.filter
3555
		 *
3556
		 * @since 2.5.0
3557
		 *
3558
		 * @static
3559
		 *
3560
		 * @var bool $has_filters True is the extension is enabled.
3561
		 */
3562
		public static $has_filters;
3563
3564
		/**
3565
		 * Wrap an arbitrary string in <em> tags. Meant to be used in combination with array_map().
3566
		 *
3567
		 * @since 2.5.0
3568
		 *
3569
		 * @static
3570
		 *
3571
		 * @param string $string Text to be wrapped.
3572
		 * @return string
3573
		 */
3574
		public static function wrap_in_em( $string ) {
3575
			return '<em>' . wp_kses_post( $string ) . '</em>';
3576
		}
3577
3578
		/**
3579
		 * Wrap an arbitrary string in <strong> tags. Meant to be used in combination with array_map().
3580
		 *
3581
		 * @since 2.5.0
3582
		 *
3583
		 * @static
3584
		 *
3585
		 * @param string $string Text to be wrapped.
3586
		 * @return string
3587
		 */
3588
		public static function wrap_in_strong( $string ) {
3589
			return '<strong>' . wp_kses_post( $string ) . '</strong>';
3590
		}
3591
3592
		/**
3593
		 * Helper function: Validate a value as boolean
3594
		 *
3595
		 * @since 2.5.0
3596
		 *
3597
		 * @static
3598
		 *
3599
		 * @param mixed $value Arbitrary value.
3600
		 * @return bool
3601
		 */
3602
		public static function validate_bool( $value ) {
3603
			if ( ! isset( self::$has_filters ) ) {
3604
				self::$has_filters = extension_loaded( 'filter' );
3605
			}
3606
3607
			if ( self::$has_filters ) {
3608
				return filter_var( $value, FILTER_VALIDATE_BOOLEAN );
3609
			} else {
3610
				return self::emulate_filter_bool( $value );
3611
			}
3612
		}
3613
3614
		/**
3615
		 * Helper function: Cast a value to bool
3616
		 *
3617
		 * @since 2.5.0
3618
		 *
3619
		 * @static
3620
		 *
3621
		 * @param mixed $value Value to cast.
3622
		 * @return bool
3623
		 */
3624
		protected static function emulate_filter_bool( $value ) {
3625
			// @codingStandardsIgnoreStart
3626
			static $true  = array(
3627
				'1',
3628
				'true', 'True', 'TRUE',
3629
				'y', 'Y',
3630
				'yes', 'Yes', 'YES',
3631
				'on', 'On', 'ON',
3632
			);
3633
			static $false = array(
3634
				'0',
3635
				'false', 'False', 'FALSE',
3636
				'n', 'N',
3637
				'no', 'No', 'NO',
3638
				'off', 'Off', 'OFF',
3639
			);
3640
			// @codingStandardsIgnoreEnd
3641
3642
			if ( is_bool( $value ) ) {
3643
				return $value;
3644
			} else if ( is_int( $value ) && ( 0 === $value || 1 === $value ) ) {
3645
				return (bool) $value;
3646
			} else if ( ( is_float( $value ) && ! is_nan( $value ) ) && ( (float) 0 === $value || (float) 1 === $value ) ) {
3647
				return (bool) $value;
3648
			} else if ( is_string( $value ) ) {
3649
				$value = trim( $value );
3650
				if ( in_array( $value, $true, true ) ) {
3651
					return true;
3652
				} else if ( in_array( $value, $false, true ) ) {
3653
					return false;
3654
				} else {
3655
					return false;
3656
				}
3657
			}
3658
3659
			return false;
3660
		}
3661
	} // End of class TGMPA_Utils
3662
} // End of class_exists wrapper
3663