Completed
Pull Request — develop (#690)
by
unknown
01:51
created

class-tgm-plugin-activation.php ➔ tgmpa_wpfavs_plugins()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 43
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 22
nc 6
nop 1
dl 0
loc 43
rs 6.7272
c 0
b 0
f 0
1
<?php
2
/**
3
 * Plugin installation and activation for WordPress themes.
4
 *
5
 * Please note that this is a drop-in library for a theme or plugin.
6
 * The authors of this library (Thomas, Gary and Juliette) are NOT responsible
7
 * for the support of your plugin or theme. Please contact the plugin
8
 * or theme author for support.
9
 *
10
 * @package   TGM-Plugin-Activation
11
 * @version   2.6.1
12
 * @link      http://tgmpluginactivation.com/
13
 * @author    Thomas Griffin, Gary Jones, Juliette Reinders Folmer
14
 * @copyright Copyright (c) 2011, Thomas Griffin
15
 * @license   GPL-2.0+
16
 */
17
18
/*
19
	Copyright 2011 Thomas Griffin (thomasgriffinmedia.com)
20
21
	This program is free software; you can redistribute it and/or modify
22
	it under the terms of the GNU General Public License, version 2, as
23
	published by the Free Software Foundation.
24
25
	This program is distributed in the hope that it will be useful,
26
	but WITHOUT ANY WARRANTY; without even the implied warranty of
27
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
28
	GNU General Public License for more details.
29
30
	You should have received a copy of the GNU General Public License
31
	along with this program; if not, write to the Free Software
32
	Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
33
*/
34
35
// Exit if accessed directly.
36
if ( ! defined( 'ABSPATH' ) ) {
37
	return;
38
}
39
40
if ( ! class_exists( 'TGM_Plugin_Activation' ) ) {
41
42
	/**
43
	 * Automatic plugin installation and activation library.
44
	 *
45
	 * Creates a way to automatically install and activate plugins from within themes.
46
	 * The plugins can be either bundled, downloaded from the WordPress
47
	 * Plugin Repository or downloaded from another external source.
48
	 *
49
	 * @since 1.0.0
50
	 *
51
	 * @package TGM-Plugin-Activation
52
	 * @author  Thomas Griffin
53
	 * @author  Gary Jones
54
	 */
55
	class TGM_Plugin_Activation {
56
		/**
57
		 * TGMPA version number.
58
		 *
59
		 * @since 2.5.0
60
		 *
61
		 * @const string Version number.
62
		 */
63
		const TGMPA_VERSION = '2.6.1';
64
65
		/**
66
		 * Regular expression to test if a URL is a WP plugin repo URL.
67
		 *
68
		 * @const string Regex.
69
		 *
70
		 * @since 2.5.0
71
		 */
72
		const WP_REPO_REGEX = '|^http[s]?://wordpress\.org/(?:extend/)?plugins/|';
73
74
		/**
75
		 * Arbitrary regular expression to test if a string starts with a URL.
76
		 *
77
		 * @const string Regex.
78
		 *
79
		 * @since 2.5.0
80
		 */
81
		const IS_URL_REGEX = '|^http[s]?://|';
82
83
		/**
84
		 * Holds a copy of itself, so it can be referenced by the class name.
85
		 *
86
		 * @since 1.0.0
87
		 *
88
		 * @var TGM_Plugin_Activation
89
		 */
90
		public static $instance;
91
92
		/**
93
		 * Holds arrays of plugin details.
94
		 *
95
		 * @since 1.0.0
96
		 * @since 2.5.0 the array has the plugin slug as an associative key.
97
		 *
98
		 * @var array
99
		 */
100
		public $plugins = array();
101
102
		/**
103
		 * Holds arrays of plugin names to use to sort the plugins array.
104
		 *
105
		 * @since 2.5.0
106
		 *
107
		 * @var array
108
		 */
109
		protected $sort_order = array();
110
111
		/**
112
		 * Whether any plugins have the 'force_activation' setting set to true.
113
		 *
114
		 * @since 2.5.0
115
		 *
116
		 * @var bool
117
		 */
118
		protected $has_forced_activation = false;
119
120
		/**
121
		 * Whether any plugins have the 'force_deactivation' setting set to true.
122
		 *
123
		 * @since 2.5.0
124
		 *
125
		 * @var bool
126
		 */
127
		protected $has_forced_deactivation = false;
128
129
		/**
130
		 * Name of the unique ID to hash notices.
131
		 *
132
		 * @since 2.4.0
133
		 *
134
		 * @var string
135
		 */
136
		public $id = 'tgmpa';
137
138
		/**
139
		 * Name of the query-string argument for the admin page.
140
		 *
141
		 * @since 1.0.0
142
		 *
143
		 * @var string
144
		 */
145
		protected $menu = 'tgmpa-install-plugins';
146
147
		/**
148
		 * Parent menu file slug.
149
		 *
150
		 * @since 2.5.0
151
		 *
152
		 * @var string
153
		 */
154
		public $parent_slug = 'themes.php';
155
156
		/**
157
		 * Capability needed to view the plugin installation menu item.
158
		 *
159
		 * @since 2.5.0
160
		 *
161
		 * @var string
162
		 */
163
		public $capability = 'edit_theme_options';
164
165
		/**
166
		 * Default absolute path to folder containing bundled plugin zip files.
167
		 *
168
		 * @since 2.0.0
169
		 *
170
		 * @var string Absolute path prefix to zip file location for bundled plugins. Default is empty string.
171
		 */
172
		public $default_path = '';
173
174
		/**
175
		 * Flag to show admin notices or not.
176
		 *
177
		 * @since 2.1.0
178
		 *
179
		 * @var boolean
180
		 */
181
		public $has_notices = true;
182
183
		/**
184
		 * Flag to determine if the user can dismiss the notice nag.
185
		 *
186
		 * @since 2.4.0
187
		 *
188
		 * @var boolean
189
		 */
190
		public $dismissable = true;
191
192
		/**
193
		 * Message to be output above nag notice if dismissable is false.
194
		 *
195
		 * @since 2.4.0
196
		 *
197
		 * @var string
198
		 */
199
		public $dismiss_msg = '';
200
201
		/**
202
		 * Flag to set automatic activation of plugins. Off by default.
203
		 *
204
		 * @since 2.2.0
205
		 *
206
		 * @var boolean
207
		 */
208
		public $is_automatic = false;
209
210
		/**
211
		 * Optional message to display before the plugins table.
212
		 *
213
		 * @since 2.2.0
214
		 *
215
		 * @var string Message filtered by wp_kses_post(). Default is empty string.
216
		 */
217
		public $message = '';
218
219
		/**
220
		 * Holds configurable array of strings.
221
		 *
222
		 * Default values are added in the constructor.
223
		 *
224
		 * @since 2.0.0
225
		 *
226
		 * @var array
227
		 */
228
		public $strings = array();
229
230
		/**
231
		 * Holds the version of WordPress.
232
		 *
233
		 * @since 2.4.0
234
		 *
235
		 * @var int
236
		 */
237
		public $wp_version;
238
239
		/**
240
		 * Holds the hook name for the admin page.
241
		 *
242
		 * @since 2.5.0
243
		 *
244
		 * @var string
245
		 */
246
		public $page_hook;
247
248
		/**
249
		 * Adds a reference of this object to $instance, populates default strings,
250
		 * does the tgmpa_init action hook, and hooks in the interactions to init.
251
		 *
252
		 * {@internal This method should be `protected`, but as too many TGMPA implementations
253
		 * haven't upgraded beyond v2.3.6 yet, this gives backward compatibility issues.
254
		 * Reverted back to public for the time being.}}
255
		 *
256
		 * @since 1.0.0
257
		 *
258
		 * @see TGM_Plugin_Activation::init()
259
		 */
260
		public function __construct() {
261
			// Set the current WordPress version.
262
			$this->wp_version = $GLOBALS['wp_version'];
263
264
			// Announce that the class is ready, and pass the object (for advanced use).
265
			do_action_ref_array( 'tgmpa_init', array( $this ) );
266
267
			/*
268
			 * Load our text domain and allow for overloading the fall-back file.
269
			 *
270
			 * {@internal IMPORTANT! If this code changes, review the regex in the custom TGMPA
271
			 * generator on the website.}}
272
			 */
273
			add_action( 'init', array( $this, 'load_textdomain' ), 5 );
274
			add_filter( 'load_textdomain_mofile', array( $this, 'overload_textdomain_mofile' ), 10, 2 );
275
276
			// When the rest of WP has loaded, kick-start the rest of the class.
277
			add_action( 'init', array( $this, 'init' ) );
278
		}
279
280
		/**
281
		 * Magic method to (not) set protected properties from outside of this class.
282
		 *
283
		 * {@internal hackedihack... There is a serious bug in v2.3.2 - 2.3.6  where the `menu` property
284
		 * is being assigned rather than tested in a conditional, effectively rendering it useless.
285
		 * This 'hack' prevents this from happening.}}
286
		 *
287
		 * @see https://github.com/TGMPA/TGM-Plugin-Activation/blob/2.3.6/tgm-plugin-activation/class-tgm-plugin-activation.php#L1593
288
		 *
289
		 * @since 2.5.2
290
		 *
291
		 * @param string $name  Name of an inaccessible property.
292
		 * @param mixed  $value Value to assign to the property.
293
		 * @return void  Silently fail to set the property when this is tried from outside of this class context.
294
		 *               (Inside this class context, the __set() method if not used as there is direct access.)
295
		 */
296
		public function __set( $name, $value ) {
297
			return;
298
		}
299
300
		/**
301
		 * Magic method to get the value of a protected property outside of this class context.
302
		 *
303
		 * @since 2.5.2
304
		 *
305
		 * @param string $name Name of an inaccessible property.
306
		 * @return mixed The property value.
307
		 */
308
		public function __get( $name ) {
309
			return $this->{$name};
310
		}
311
312
		/**
313
		 * Initialise the interactions between this class and WordPress.
314
		 *
315
		 * Hooks in three new methods for the class: admin_menu, notices and styles.
316
		 *
317
		 * @since 2.0.0
318
		 *
319
		 * @see TGM_Plugin_Activation::admin_menu()
320
		 * @see TGM_Plugin_Activation::notices()
321
		 * @see TGM_Plugin_Activation::styles()
322
		 */
323
		public function init() {
324
			/**
325
			 * By default TGMPA only loads on the WP back-end and not in an Ajax call. Using this filter
326
			 * you can overrule that behaviour.
327
			 *
328
			 * @since 2.5.0
329
			 *
330
			 * @param bool $load Whether or not TGMPA should load.
331
			 *                   Defaults to the return of `is_admin() && ! defined( 'DOING_AJAX' )`.
332
			 */
333
			if ( true !== apply_filters( 'tgmpa_load', ( is_admin() && ! defined( 'DOING_AJAX' ) ) ) ) {
334
				return;
335
			}
336
337
			// Load class strings.
338
			$this->strings = array(
339
				'page_title'                      => __( 'Install Required Plugins', 'tgmpa' ),
340
				'menu_title'                      => __( 'Install Plugins', 'tgmpa' ),
341
				/* translators: %s: plugin name. */
342
				'installing'                      => __( 'Installing Plugin: %s', 'tgmpa' ),
343
				/* translators: %s: plugin name. */
344
				'updating'                        => __( 'Updating Plugin: %s', 'tgmpa' ),
345
				'oops'                            => __( 'Something went wrong with the plugin API.', 'tgmpa' ),
346
				/* translators: 1: plugin name(s). */
347
				'notice_can_install_required'     => _n_noop(
348
					'This theme requires the following plugin: %1$s.',
349
					'This theme requires the following plugins: %1$s.',
350
					'tgmpa'
351
				),
352
				/* translators: 1: plugin name(s). */
353
				'notice_can_install_recommended'  => _n_noop(
354
					'This theme recommends the following plugin: %1$s.',
355
					'This theme recommends the following plugins: %1$s.',
356
					'tgmpa'
357
				),
358
				/* translators: 1: plugin name(s). */
359
				'notice_ask_to_update'            => _n_noop(
360
					'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.',
361
					'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.',
362
					'tgmpa'
363
				),
364
				/* translators: 1: plugin name(s). */
365
				'notice_ask_to_update_maybe'      => _n_noop(
366
					'There is an update available for: %1$s.',
367
					'There are updates available for the following plugins: %1$s.',
368
					'tgmpa'
369
				),
370
				/* translators: 1: plugin name(s). */
371
				'notice_can_activate_required'    => _n_noop(
372
					'The following required plugin is currently inactive: %1$s.',
373
					'The following required plugins are currently inactive: %1$s.',
374
					'tgmpa'
375
				),
376
				/* translators: 1: plugin name(s). */
377
				'notice_can_activate_recommended' => _n_noop(
378
					'The following recommended plugin is currently inactive: %1$s.',
379
					'The following recommended plugins are currently inactive: %1$s.',
380
					'tgmpa'
381
				),
382
				'install_link'                    => _n_noop(
383
					'Begin installing plugin',
384
					'Begin installing plugins',
385
					'tgmpa'
386
				),
387
				'update_link'                     => _n_noop(
388
					'Begin updating plugin',
389
					'Begin updating plugins',
390
					'tgmpa'
391
				),
392
				'activate_link'                   => _n_noop(
393
					'Begin activating plugin',
394
					'Begin activating plugins',
395
					'tgmpa'
396
				),
397
				'return'                          => __( 'Return to Required Plugins Installer', 'tgmpa' ),
398
				'dashboard'                       => __( 'Return to the Dashboard', 'tgmpa' ),
399
				'plugin_activated'                => __( 'Plugin activated successfully.', 'tgmpa' ),
400
				'activated_successfully'          => __( 'The following plugin was activated successfully:', 'tgmpa' ),
401
				/* translators: 1: plugin name. */
402
				'plugin_already_active'           => __( 'No action taken. Plugin %1$s was already active.', 'tgmpa' ),
403
				/* translators: 1: plugin name. */
404
				'plugin_needs_higher_version'     => __( 'Plugin not activated. A higher version of %s is needed for this theme. Please update the plugin.', 'tgmpa' ),
405
				/* translators: 1: dashboard link. */
406
				'complete'                        => __( 'All plugins installed and activated successfully. %1$s', 'tgmpa' ),
407
				'dismiss'                         => __( 'Dismiss this notice', 'tgmpa' ),
408
				'notice_cannot_install_activate'  => __( 'There are one or more required or recommended plugins to install, update or activate.', 'tgmpa' ),
409
				'contact_admin'                   => __( 'Please contact the administrator of this site for help.', 'tgmpa' ),
410
			);
411
412
			do_action( 'tgmpa_register' );
413
414
			/* After this point, the plugins should be registered and the configuration set. */
415
416
			// Proceed only if we have plugins to handle.
417
			if ( empty( $this->plugins ) || ! is_array( $this->plugins ) ) {
418
				return;
419
			}
420
421
			// Set up the menu and notices if we still have outstanding actions.
422
			if ( true !== $this->is_tgmpa_complete() ) {
423
				// Sort the plugins.
424
				array_multisort( $this->sort_order, SORT_ASC, $this->plugins );
425
426
				add_action( 'admin_menu', array( $this, 'admin_menu' ) );
427
				add_action( 'admin_head', array( $this, 'dismiss' ) );
428
429
				// Prevent the normal links from showing underneath a single install/update page.
430
				add_filter( 'install_plugin_complete_actions', array( $this, 'actions' ) );
431
				add_filter( 'update_plugin_complete_actions', array( $this, 'actions' ) );
432
433
				if ( $this->has_notices ) {
434
					add_action( 'admin_notices', array( $this, 'notices' ) );
435
					add_action( 'admin_init', array( $this, 'admin_init' ), 1 );
436
					add_action( 'admin_enqueue_scripts', array( $this, 'thickbox' ) );
437
				}
438
			}
439
440
			// If needed, filter plugin action links.
441
			add_action( 'load-plugins.php', array( $this, 'add_plugin_action_link_filters' ), 1 );
442
443
			// Make sure things get reset on switch theme.
444
			add_action( 'switch_theme', array( $this, 'flush_plugins_cache' ) );
445
446
			if ( $this->has_notices ) {
447
				add_action( 'switch_theme', array( $this, 'update_dismiss' ) );
448
			}
449
450
			// Setup the force activation hook.
451
			if ( true === $this->has_forced_activation ) {
452
				add_action( 'admin_init', array( $this, 'force_activation' ) );
453
			}
454
455
			// Setup the force deactivation hook.
456
			if ( true === $this->has_forced_deactivation ) {
457
				add_action( 'switch_theme', array( $this, 'force_deactivation' ) );
458
			}
459
460
			// Add CSS for the TGMPA admin page.
461
			add_action( 'admin_head', array( $this, 'admin_css' ) );
462
		}
463
464
		/**
465
		 * Load translations.
466
		 *
467
		 * @since 2.6.0
468
		 *
469
		 * (@internal Uses `load_theme_textdomain()` rather than `load_plugin_textdomain()` to
470
		 * get round the different ways of handling the path and deprecated notices being thrown
471
		 * and such. For plugins, the actual file name will be corrected by a filter.}}
472
		 *
473
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
474
		 * generator on the website.}}
475
		 */
476
		public function load_textdomain() {
477
			if ( is_textdomain_loaded( 'tgmpa' ) ) {
478
				return;
479
			}
480
481
			if ( false !== strpos( __FILE__, WP_PLUGIN_DIR ) || false !== strpos( __FILE__, WPMU_PLUGIN_DIR ) ) {
482
				// Plugin, we'll need to adjust the file name.
483
				add_action( 'load_textdomain_mofile', array( $this, 'correct_plugin_mofile' ), 10, 2 );
484
				load_theme_textdomain( 'tgmpa', dirname( __FILE__ ) . '/languages' );
485
				remove_action( 'load_textdomain_mofile', array( $this, 'correct_plugin_mofile' ), 10 );
486
			} else {
487
				load_theme_textdomain( 'tgmpa', dirname( __FILE__ ) . '/languages' );
488
			}
489
		}
490
491
		/**
492
		 * Correct the .mo file name for (must-use) plugins.
493
		 *
494
		 * Themese use `/path/{locale}.mo` while plugins use `/path/{text-domain}-{locale}.mo`.
495
		 *
496
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
497
		 * generator on the website.}}
498
		 *
499
		 * @since 2.6.0
500
		 *
501
		 * @param string $mofile Full path to the target mofile.
502
		 * @param string $domain The domain for which a language file is being loaded.
503
		 * @return string $mofile
504
		 */
505
		public function correct_plugin_mofile( $mofile, $domain ) {
506
			// Exit early if not our domain (just in case).
507
			if ( 'tgmpa' !== $domain ) {
508
				return $mofile;
509
			}
510
			return preg_replace( '`/([a-z]{2}_[A-Z]{2}.mo)$`', '/tgmpa-$1', $mofile );
511
		}
512
513
		/**
514
		 * Potentially overload the fall-back translation file for the current language.
515
		 *
516
		 * WP, by default since WP 3.7, will load a local translation first and if none
517
		 * can be found, will try and find a translation in the /wp-content/languages/ directory.
518
		 * As this library is theme/plugin agnostic, translation files for TGMPA can exist both
519
		 * in the WP_LANG_DIR /plugins/ subdirectory as well as in the /themes/ subdirectory.
520
		 *
521
		 * This method makes sure both directories are checked.
522
		 *
523
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
524
		 * generator on the website.}}
525
		 *
526
		 * @since 2.6.0
527
		 *
528
		 * @param string $mofile Full path to the target mofile.
529
		 * @param string $domain The domain for which a language file is being loaded.
530
		 * @return string $mofile
531
		 */
532
		public function overload_textdomain_mofile( $mofile, $domain ) {
533
			// Exit early if not our domain, not a WP_LANG_DIR load or if the file exists and is readable.
534
			if ( 'tgmpa' !== $domain || false === strpos( $mofile, WP_LANG_DIR ) || @is_readable( $mofile ) ) {
535
				return $mofile;
536
			}
537
538
			// Current fallback file is not valid, let's try the alternative option.
539
			if ( false !== strpos( $mofile, '/themes/' ) ) {
540
				return str_replace( '/themes/', '/plugins/', $mofile );
541
			} elseif ( false !== strpos( $mofile, '/plugins/' ) ) {
542
				return str_replace( '/plugins/', '/themes/', $mofile );
543
			} else {
544
				return $mofile;
545
			}
546
		}
547
548
		/**
549
		 * Hook in plugin action link filters for the WP native plugins page.
550
		 *
551
		 * - Prevent activation of plugins which don't meet the minimum version requirements.
552
		 * - Prevent deactivation of force-activated plugins.
553
		 * - Add update notice if update available.
554
		 *
555
		 * @since 2.5.0
556
		 */
557
		public function add_plugin_action_link_filters() {
558
			foreach ( $this->plugins as $slug => $plugin ) {
559
				if ( false === $this->can_plugin_activate( $slug ) ) {
560
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_activate' ), 20 );
561
				}
562
563
				if ( true === $plugin['force_activation'] ) {
564
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_deactivate' ), 20 );
565
				}
566
567
				if ( false !== $this->does_plugin_require_update( $slug ) ) {
568
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_update' ), 20 );
569
				}
570
			}
571
		}
572
573
		/**
574
		 * Remove the 'Activate' link on the WP native plugins page if the plugin does not meet the
575
		 * minimum version requirements.
576
		 *
577
		 * @since 2.5.0
578
		 *
579
		 * @param array $actions Action links.
580
		 * @return array
581
		 */
582
		public function filter_plugin_action_links_activate( $actions ) {
583
			unset( $actions['activate'] );
584
585
			return $actions;
586
		}
587
588
		/**
589
		 * Remove the 'Deactivate' link on the WP native plugins page if the plugin has been set to force activate.
590
		 *
591
		 * @since 2.5.0
592
		 *
593
		 * @param array $actions Action links.
594
		 * @return array
595
		 */
596
		public function filter_plugin_action_links_deactivate( $actions ) {
597
			unset( $actions['deactivate'] );
598
599
			return $actions;
600
		}
601
602
		/**
603
		 * Add a 'Requires update' link on the WP native plugins page if the plugin does not meet the
604
		 * minimum version requirements.
605
		 *
606
		 * @since 2.5.0
607
		 *
608
		 * @param array $actions Action links.
609
		 * @return array
610
		 */
611
		public function filter_plugin_action_links_update( $actions ) {
612
			$actions['update'] = sprintf(
613
				'<a href="%1$s" title="%2$s" class="edit">%3$s</a>',
614
				esc_url( $this->get_tgmpa_status_url( 'update' ) ),
615
				esc_attr__( 'This plugin needs to be updated to be compatible with your theme.', 'tgmpa' ),
616
				esc_html__( 'Update Required', 'tgmpa' )
617
			);
618
619
			return $actions;
620
		}
621
622
		/**
623
		 * Handles calls to show plugin information via links in the notices.
624
		 *
625
		 * We get the links in the admin notices to point to the TGMPA page, rather
626
		 * than the typical plugin-install.php file, so we can prepare everything
627
		 * beforehand.
628
		 *
629
		 * WP does not make it easy to show the plugin information in the thickbox -
630
		 * here we have to require a file that includes a function that does the
631
		 * main work of displaying it, enqueue some styles, set up some globals and
632
		 * finally call that function before exiting.
633
		 *
634
		 * Down right easy once you know how...
635
		 *
636
		 * Returns early if not the TGMPA page.
637
		 *
638
		 * @since 2.1.0
639
		 *
640
		 * @global string $tab Used as iframe div class names, helps with styling
641
		 * @global string $body_id Used as the iframe body ID, helps with styling
642
		 *
643
		 * @return null Returns early if not the TGMPA page.
644
		 */
645
		public function admin_init() {
646
			if ( ! $this->is_tgmpa_page() ) {
647
				return;
648
			}
649
650
			if ( isset( $_REQUEST['tab'] ) && 'plugin-information' === $_REQUEST['tab'] ) {
651
				// Needed for install_plugin_information().
652
				require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
653
654
				wp_enqueue_style( 'plugin-install' );
655
656
				global $tab, $body_id;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
657
				$body_id = 'plugin-information'; // WPCS: override ok, prefix ok.
658
				$tab     = 'plugin-information'; // WPCS: override ok.
659
660
				install_plugin_information();
661
662
				exit;
663
			}
664
		}
665
666
		/**
667
		 * Enqueue thickbox scripts/styles for plugin info.
668
		 *
669
		 * Thickbox is not automatically included on all admin pages, so we must
670
		 * manually enqueue it for those pages.
671
		 *
672
		 * Thickbox is only loaded if the user has not dismissed the admin
673
		 * notice or if there are any plugins left to install and activate.
674
		 *
675
		 * @since 2.1.0
676
		 */
677
		public function thickbox() {
678
			if ( ! get_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, true ) ) {
679
				add_thickbox();
680
			}
681
		}
682
683
		/**
684
		 * Adds submenu page if there are plugin actions to take.
685
		 *
686
		 * This method adds the submenu page letting users know that a required
687
		 * plugin needs to be installed.
688
		 *
689
		 * This page disappears once the plugin has been installed and activated.
690
		 *
691
		 * @since 1.0.0
692
		 *
693
		 * @see TGM_Plugin_Activation::init()
694
		 * @see TGM_Plugin_Activation::install_plugins_page()
695
		 *
696
		 * @return null Return early if user lacks capability to install a plugin.
697
		 */
698
		public function admin_menu() {
699
			// Make sure privileges are correct to see the page.
700
			if ( ! current_user_can( 'install_plugins' ) ) {
701
				return;
702
			}
703
704
			$args = apply_filters(
705
				'tgmpa_admin_menu_args',
706
				array(
707
					'parent_slug' => $this->parent_slug,                     // Parent Menu slug.
708
					'page_title'  => $this->strings['page_title'],           // Page title.
709
					'menu_title'  => $this->strings['menu_title'],           // Menu title.
710
					'capability'  => $this->capability,                      // Capability.
711
					'menu_slug'   => $this->menu,                            // Menu slug.
712
					'function'    => array( $this, 'install_plugins_page' ), // Callback.
713
				)
714
			);
715
716
			$this->add_admin_menu( $args );
717
		}
718
719
		/**
720
		 * Add the menu item.
721
		 *
722
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
723
		 * generator on the website.}}
724
		 *
725
		 * @since 2.5.0
726
		 *
727
		 * @param array $args Menu item configuration.
728
		 */
729
		protected function add_admin_menu( array $args ) {
730
			if ( has_filter( 'tgmpa_admin_menu_use_add_theme_page' ) ) {
731
				_deprecated_function( 'The "tgmpa_admin_menu_use_add_theme_page" filter', '2.5.0', esc_html__( 'Set the parent_slug config variable instead.', 'tgmpa' ) );
732
			}
733
734
			if ( 'themes.php' === $this->parent_slug ) {
735
				$this->page_hook = call_user_func( 'add_theme_page', $args['page_title'], $args['menu_title'], $args['capability'], $args['menu_slug'], $args['function'] );
736
			} else {
737
				$this->page_hook = call_user_func( 'add_submenu_page', $args['parent_slug'], $args['page_title'], $args['menu_title'], $args['capability'], $args['menu_slug'], $args['function'] );
738
			}
739
		}
740
741
		/**
742
		 * Echoes plugin installation form.
743
		 *
744
		 * This method is the callback for the admin_menu method function.
745
		 * This displays the admin page and form area where the user can select to install and activate the plugin.
746
		 * Aborts early if we're processing a plugin installation action.
747
		 *
748
		 * @since 1.0.0
749
		 *
750
		 * @return null Aborts early if we're processing a plugin installation action.
751
		 */
752
		public function install_plugins_page() {
753
			// Store new instance of plugin table in object.
754
			$plugin_table = new TGMPA_List_Table();
755
756
			// Return early if processing a plugin installation action.
757
			if ( ( ( 'tgmpa-bulk-install' === $plugin_table->current_action() || 'tgmpa-bulk-update' === $plugin_table->current_action() ) && $plugin_table->process_bulk_actions() ) || $this->do_plugin_install() ) {
758
				return;
759
			}
760
761
			// Force refresh of available plugin information so we'll know about manual updates/deletes.
762
			wp_clean_plugins_cache( false );
763
764
			?>
765
			<div class="tgmpa wrap">
766
				<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
767
				<?php $plugin_table->prepare_items(); ?>
768
769
				<?php
770
				if ( ! empty( $this->message ) && is_string( $this->message ) ) {
771
					echo wp_kses_post( $this->message );
772
				}
773
				?>
774
				<?php $plugin_table->views(); ?>
775
776
				<form id="tgmpa-plugins" action="" method="post">
777
					<input type="hidden" name="tgmpa-page" value="<?php echo esc_attr( $this->menu ); ?>" />
778
					<input type="hidden" name="plugin_status" value="<?php echo esc_attr( $plugin_table->view_context ); ?>" />
779
					<?php $plugin_table->display(); ?>
780
				</form>
781
			</div>
782
			<?php
783
		}
784
785
		/**
786
		 * Installs, updates or activates a plugin depending on the action link clicked by the user.
787
		 *
788
		 * Checks the $_GET variable to see which actions have been
789
		 * passed and responds with the appropriate method.
790
		 *
791
		 * Uses WP_Filesystem to process and handle the plugin installation
792
		 * method.
793
		 *
794
		 * @since 1.0.0
795
		 *
796
		 * @uses WP_Filesystem
797
		 * @uses WP_Error
798
		 * @uses WP_Upgrader
799
		 * @uses Plugin_Upgrader
800
		 * @uses Plugin_Installer_Skin
801
		 * @uses Plugin_Upgrader_Skin
802
		 *
803
		 * @return boolean True on success, false on failure.
804
		 */
805
		protected function do_plugin_install() {
0 ignored issues
show
Coding Style introduced by
function do_plugin_install() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
806
			if ( empty( $_GET['plugin'] ) ) {
807
				return false;
808
			}
809
810
			// All plugin information will be stored in an array for processing.
811
			$slug = $this->sanitize_key( urldecode( $_GET['plugin'] ) );
812
813
			if ( ! isset( $this->plugins[ $slug ] ) ) {
814
				return false;
815
			}
816
817
			// Was an install or upgrade action link clicked?
818
			if ( ( isset( $_GET['tgmpa-install'] ) && 'install-plugin' === $_GET['tgmpa-install'] ) || ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) ) {
819
820
				$install_type = 'install';
821
				if ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) {
822
					$install_type = 'update';
823
				}
824
825
				check_admin_referer( 'tgmpa-' . $install_type, 'tgmpa-nonce' );
826
827
				// Pass necessary information via URL if WP_Filesystem is needed.
828
				$url = wp_nonce_url(
829
					add_query_arg(
830
						array(
831
							'plugin'                 => urlencode( $slug ),
832
							'tgmpa-' . $install_type => $install_type . '-plugin',
833
						),
834
						$this->get_tgmpa_url()
835
					),
836
					'tgmpa-' . $install_type,
837
					'tgmpa-nonce'
838
				);
839
840
				$method = ''; // Leave blank so WP_Filesystem can populate it as necessary.
841
842
				$creds = request_filesystem_credentials( esc_url_raw( $url ), $method, false, false, array() );
843
				if ( false === $creds ) {
844
					return true;
845
				}
846
847
				if ( ! WP_Filesystem( $creds ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
848
					request_filesystem_credentials( esc_url_raw( $url ), $method, true, false, array() ); // Setup WP_Filesystem.
849
					return true;
850
				}
851
852
				/* If we arrive here, we have the filesystem. */
853
854
				// Prep variables for Plugin_Installer_Skin class.
855
				$extra         = array();
856
				$extra['slug'] = $slug; // Needed for potentially renaming of directory name.
857
				$source        = $this->get_download_url( $slug );
858
				$api           = ( 'repo' === $this->plugins[ $slug ]['source_type'] ) ? $this->get_plugins_api( $slug ) : null;
859
				$api           = ( false !== $api ) ? $api : null;
860
861
				$url = add_query_arg(
862
					array(
863
						'action' => $install_type . '-plugin',
864
						'plugin' => urlencode( $slug ),
865
					),
866
					'update.php'
867
				);
868
869
				if ( ! class_exists( 'Plugin_Upgrader', false ) ) {
870
					require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
871
				}
872
873
				$title     = ( 'update' === $install_type ) ? $this->strings['updating'] : $this->strings['installing'];
874
				$skin_args = array(
875
					'type'   => ( 'bundled' !== $this->plugins[ $slug ]['source_type'] ) ? 'web' : 'upload',
876
					'title'  => sprintf( $title, $this->plugins[ $slug ]['name'] ),
877
					'url'    => esc_url_raw( $url ),
878
					'nonce'  => $install_type . '-plugin_' . $slug,
879
					'plugin' => '',
880
					'api'    => $api,
881
					'extra'  => $extra,
882
				);
883
				unset( $title );
884
885
				if ( 'update' === $install_type ) {
886
					$skin_args['plugin'] = $this->plugins[ $slug ]['file_path'];
887
					$skin                = new Plugin_Upgrader_Skin( $skin_args );
888
				} else {
889
					$skin = new Plugin_Installer_Skin( $skin_args );
890
				}
891
892
				// Create a new instance of Plugin_Upgrader.
893
				$upgrader = new Plugin_Upgrader( $skin );
894
895
				// Perform the action and install the plugin from the $source urldecode().
896
				add_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1, 3 );
897
898
				if ( 'update' === $install_type ) {
899
					// Inject our info into the update transient.
900
					$to_inject                    = array(
901
						$slug => $this->plugins[ $slug ],
902
					);
903
					$to_inject[ $slug ]['source'] = $source;
904
					$this->inject_update_info( $to_inject );
905
906
					$upgrader->upgrade( $this->plugins[ $slug ]['file_path'] );
907
				} else {
908
					$upgrader->install( $source );
909
				}
910
911
				remove_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1 );
912
913
				// Make sure we have the correct file path now the plugin is installed/updated.
914
				$this->populate_file_path( $slug );
915
916
				// Only activate plugins if the config option is set to true and the plugin isn't
917
				// already active (upgrade).
918
				if ( $this->is_automatic && ! $this->is_plugin_active( $slug ) ) {
919
					$plugin_activate = $upgrader->plugin_info(); // Grab the plugin info from the Plugin_Upgrader method.
920
					if ( false === $this->activate_single_plugin( $plugin_activate, $slug, true ) ) {
921
						return true; // Finish execution of the function early as we encountered an error.
922
					}
923
				}
924
925
				$this->show_tgmpa_version();
926
927
				// Display message based on if all plugins are now active or not.
928
				if ( $this->is_tgmpa_complete() ) {
929
					echo '<p>', sprintf( esc_html( $this->strings['complete'] ), '<a href="' . esc_url( self_admin_url() ) . '">' . esc_html( $this->strings['dashboard'] ) . '</a>' ), '</p>';
930
					echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>';
931
				} else {
932
					echo '<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>';
933
				}
934
935
				return true;
936
			} elseif ( isset( $this->plugins[ $slug ]['file_path'], $_GET['tgmpa-activate'] ) && 'activate-plugin' === $_GET['tgmpa-activate'] ) {
937
				// Activate action link was clicked.
938
				check_admin_referer( 'tgmpa-activate', 'tgmpa-nonce' );
939
940
				if ( false === $this->activate_single_plugin( $this->plugins[ $slug ]['file_path'], $slug ) ) {
941
					return true; // Finish execution of the function early as we encountered an error.
942
				}
943
			}
944
945
			return false;
946
		}
947
948
		/**
949
		 * Inject information into the 'update_plugins' site transient as WP checks that before running an update.
950
		 *
951
		 * @since 2.5.0
952
		 *
953
		 * @param array $plugins The plugin information for the plugins which are to be updated.
954
		 */
955
		public function inject_update_info( $plugins ) {
956
			$repo_updates = get_site_transient( 'update_plugins' );
957
958
			if ( ! is_object( $repo_updates ) ) {
959
				$repo_updates = new stdClass();
960
			}
961
962
			foreach ( $plugins as $slug => $plugin ) {
963
				$file_path = $plugin['file_path'];
964
965
				if ( empty( $repo_updates->response[ $file_path ] ) ) {
966
					$repo_updates->response[ $file_path ] = new stdClass();
967
				}
968
969
				// We only really need to set package, but let's do all we can in case WP changes something.
970
				$repo_updates->response[ $file_path ]->slug        = $slug;
971
				$repo_updates->response[ $file_path ]->plugin      = $file_path;
972
				$repo_updates->response[ $file_path ]->new_version = $plugin['version'];
973
				$repo_updates->response[ $file_path ]->package     = $plugin['source'];
974
				if ( empty( $repo_updates->response[ $file_path ]->url ) && ! empty( $plugin['external_url'] ) ) {
975
					$repo_updates->response[ $file_path ]->url = $plugin['external_url'];
976
				}
977
			}
978
979
			set_site_transient( 'update_plugins', $repo_updates );
980
		}
981
982
		/**
983
		 * Adjust the plugin directory name if necessary.
984
		 *
985
		 * The final destination directory of a plugin is based on the subdirectory name found in the
986
		 * (un)zipped source. In some cases - most notably GitHub repository plugin downloads -, this
987
		 * subdirectory name is not the same as the expected slug and the plugin will not be recognized
988
		 * as installed. This is fixed by adjusting the temporary unzipped source subdirectory name to
989
		 * the expected plugin slug.
990
		 *
991
		 * @since 2.5.0
992
		 *
993
		 * @param string       $source        Path to upgrade/zip-file-name.tmp/subdirectory/.
994
		 * @param string       $remote_source Path to upgrade/zip-file-name.tmp.
995
		 * @param \WP_Upgrader $upgrader      Instance of the upgrader which installs the plugin.
996
		 * @return string $source
997
		 */
998
		public function maybe_adjust_source_dir( $source, $remote_source, $upgrader ) {
999
			if ( ! $this->is_tgmpa_page() || ! is_object( $GLOBALS['wp_filesystem'] ) ) {
1000
				return $source;
1001
			}
1002
1003
			// Check for single file plugins.
1004
			$source_files = array_keys( $GLOBALS['wp_filesystem']->dirlist( $remote_source ) );
1005
			if ( 1 === count( $source_files ) && false === $GLOBALS['wp_filesystem']->is_dir( $source ) ) {
1006
				return $source;
1007
			}
1008
1009
			// Multi-file plugin, let's see if the directory is correctly named.
1010
			$desired_slug = '';
1011
1012
			// Figure out what the slug is supposed to be.
1013
			if ( false === $upgrader->bulk && ! empty( $upgrader->skin->options['extra']['slug'] ) ) {
1014
				$desired_slug = $upgrader->skin->options['extra']['slug'];
1015
			} else {
1016
				// Bulk installer contains less info, so fall back on the info registered here.
1017
				foreach ( $this->plugins as $slug => $plugin ) {
1018
					if ( ! empty( $upgrader->skin->plugin_names[ $upgrader->skin->i ] ) && $plugin['name'] === $upgrader->skin->plugin_names[ $upgrader->skin->i ] ) {
1019
						$desired_slug = $slug;
1020
						break;
1021
					}
1022
				}
1023
				unset( $slug, $plugin );
1024
			}
1025
1026
			if ( ! empty( $desired_slug ) ) {
1027
				$subdir_name = untrailingslashit( str_replace( trailingslashit( $remote_source ), '', $source ) );
1028
1029
				if ( ! empty( $subdir_name ) && $subdir_name !== $desired_slug ) {
1030
					$from_path = untrailingslashit( $source );
1031
					$to_path   = trailingslashit( $remote_source ) . $desired_slug;
1032
1033
					if ( true === $GLOBALS['wp_filesystem']->move( $from_path, $to_path ) ) {
1034
						return trailingslashit( $to_path );
1035 View Code Duplication
					} else {
1036
						return new WP_Error(
1037
							'rename_failed',
1038
							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' ),
1039
							array(
1040
								'found'    => $subdir_name,
1041
								'expected' => $desired_slug,
1042
							)
1043
						);
1044
					}
1045 View Code Duplication
				} elseif ( empty( $subdir_name ) ) {
1046
					return new WP_Error(
1047
						'packaged_wrong',
1048
						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' ),
1049
						array(
1050
							'found'    => $subdir_name,
1051
							'expected' => $desired_slug,
1052
						)
1053
					);
1054
				}
1055
			}
1056
1057
			return $source;
1058
		}
1059
1060
		/**
1061
		 * Activate a single plugin and send feedback about the result to the screen.
1062
		 *
1063
		 * @since 2.5.0
1064
		 *
1065
		 * @param string $file_path Path within wp-plugins/ to main plugin file.
1066
		 * @param string $slug      Plugin slug.
1067
		 * @param bool   $automatic Whether this is an automatic activation after an install. Defaults to false.
1068
		 *                          This determines the styling of the output messages.
1069
		 * @return bool False if an error was encountered, true otherwise.
1070
		 */
1071
		protected function activate_single_plugin( $file_path, $slug, $automatic = false ) {
0 ignored issues
show
Coding Style introduced by
function activate_single_plugin() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
1072
			if ( $this->can_plugin_activate( $slug ) ) {
1073
				$activate = activate_plugin( $file_path );
1074
1075
				if ( is_wp_error( $activate ) ) {
1076
					echo '<div id="message" class="error"><p>', wp_kses_post( $activate->get_error_message() ), '</p></div>',
1077
						'<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>';
1078
1079
					return false; // End it here if there is an error with activation.
1080
				} else {
1081
					if ( ! $automatic ) {
1082
						// Make sure message doesn't display again if bulk activation is performed
1083
						// immediately after a single activation.
1084
						if ( ! isset( $_POST['action'] ) ) { // WPCS: CSRF OK.
1085
							echo '<div id="message" class="updated"><p>', esc_html( $this->strings['activated_successfully'] ), ' <strong>', esc_html( $this->plugins[ $slug ]['name'] ), '.</strong></p></div>';
1086
						}
1087
					} else {
1088
						// Simpler message layout for use on the plugin install page.
1089
						echo '<p>', esc_html( $this->strings['plugin_activated'] ), '</p>';
1090
					}
1091
				}
1092 View Code Duplication
			} elseif ( $this->is_plugin_active( $slug ) ) {
1093
				// No simpler message format provided as this message should never be encountered
1094
				// on the plugin install page.
1095
				echo '<div id="message" class="error"><p>',
1096
					sprintf(
1097
						esc_html( $this->strings['plugin_already_active'] ),
1098
						'<strong>' . esc_html( $this->plugins[ $slug ]['name'] ) . '</strong>'
1099
					),
1100
					'</p></div>';
1101
			} elseif ( $this->does_plugin_require_update( $slug ) ) {
1102
				if ( ! $automatic ) {
1103
					// Make sure message doesn't display again if bulk activation is performed
1104
					// immediately after a single activation.
1105 View Code Duplication
					if ( ! isset( $_POST['action'] ) ) { // WPCS: CSRF OK.
1106
						echo '<div id="message" class="error"><p>',
1107
							sprintf(
1108
								esc_html( $this->strings['plugin_needs_higher_version'] ),
1109
								'<strong>' . esc_html( $this->plugins[ $slug ]['name'] ) . '</strong>'
1110
							),
1111
							'</p></div>';
1112
					}
1113
				} else {
1114
					// Simpler message layout for use on the plugin install page.
1115
					echo '<p>', sprintf( esc_html( $this->strings['plugin_needs_higher_version'] ), esc_html( $this->plugins[ $slug ]['name'] ) ), '</p>';
1116
				}
1117
			}
1118
1119
			return true;
1120
		}
1121
1122
		/**
1123
		 * Echoes required plugin notice.
1124
		 *
1125
		 * Outputs a message telling users that a specific plugin is required for
1126
		 * their theme. If appropriate, it includes a link to the form page where
1127
		 * users can install and activate the plugin.
1128
		 *
1129
		 * Returns early if we're on the Install page.
1130
		 *
1131
		 * @since 1.0.0
1132
		 *
1133
		 * @global object $current_screen
1134
		 *
1135
		 * @return null Returns early if we're on the Install page.
1136
		 */
1137
		public function notices() {
1138
			// Remove nag on the install page / Return early if the nag message has been dismissed or user < author.
1139
			if ( ( $this->is_tgmpa_page() || $this->is_core_update_page() ) || get_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, true ) || ! current_user_can( apply_filters( 'tgmpa_show_admin_notice_capability', 'publish_posts' ) ) ) {
1140
				return;
1141
			}
1142
1143
			// Store for the plugin slugs by message type.
1144
			$message = array();
1145
1146
			// Initialize counters used to determine plurality of action link texts.
1147
			$install_link_count          = 0;
1148
			$update_link_count           = 0;
1149
			$activate_link_count         = 0;
1150
			$total_required_action_count = 0;
1151
1152
			foreach ( $this->plugins as $slug => $plugin ) {
1153
				if ( $this->is_plugin_active( $slug ) && false === $this->does_plugin_have_update( $slug ) ) {
1154
					continue;
1155
				}
1156
1157
				if ( ! $this->is_plugin_installed( $slug ) ) {
1158
					if ( current_user_can( 'install_plugins' ) ) {
1159
						$install_link_count++;
1160
1161
						if ( true === $plugin['required'] ) {
1162
							$message['notice_can_install_required'][] = $slug;
1163
						} else {
1164
							$message['notice_can_install_recommended'][] = $slug;
1165
						}
1166
					}
1167
					if ( true === $plugin['required'] ) {
1168
						$total_required_action_count++;
1169
					}
1170
				} else {
1171
					if ( ! $this->is_plugin_active( $slug ) && $this->can_plugin_activate( $slug ) ) {
1172
						if ( current_user_can( 'activate_plugins' ) ) {
1173
							$activate_link_count++;
1174
1175
							if ( true === $plugin['required'] ) {
1176
								$message['notice_can_activate_required'][] = $slug;
1177
							} else {
1178
								$message['notice_can_activate_recommended'][] = $slug;
1179
							}
1180
						}
1181
						if ( true === $plugin['required'] ) {
1182
							$total_required_action_count++;
1183
						}
1184
					}
1185
1186
					if ( $this->does_plugin_require_update( $slug ) || false !== $this->does_plugin_have_update( $slug ) ) {
1187
1188
						if ( current_user_can( 'update_plugins' ) ) {
1189
							$update_link_count++;
1190
1191
							if ( $this->does_plugin_require_update( $slug ) ) {
1192
								$message['notice_ask_to_update'][] = $slug;
1193
							} elseif ( false !== $this->does_plugin_have_update( $slug ) ) {
1194
								$message['notice_ask_to_update_maybe'][] = $slug;
1195
							}
1196
						}
1197
						if ( true === $plugin['required'] ) {
1198
							$total_required_action_count++;
1199
						}
1200
					}
1201
				}
1202
			}
1203
			unset( $slug, $plugin );
1204
1205
			// If we have notices to display, we move forward.
1206
			if ( ! empty( $message ) || $total_required_action_count > 0 ) {
1207
				krsort( $message ); // Sort messages.
1208
				$rendered = '';
1209
1210
				// As add_settings_error() wraps the final message in a <p> and as the final message can't be
1211
				// filtered, using <p>'s in our html would render invalid html output.
1212
				$line_template = '<span style="display: block; margin: 0.5em 0.5em 0 0; clear: both;">%s</span>' . "\n";
1213
1214
				if ( ! current_user_can( 'activate_plugins' ) && ! current_user_can( 'install_plugins' ) && ! current_user_can( 'update_plugins' ) ) {
1215
					$rendered  = esc_html( $this->strings['notice_cannot_install_activate'] ) . ' ' . esc_html( $this->strings['contact_admin'] );
1216
					$rendered .= $this->create_user_action_links_for_notice( 0, 0, 0, $line_template );
1217
				} else {
1218
1219
					// If dismissable is false and a message is set, output it now.
1220
					if ( ! $this->dismissable && ! empty( $this->dismiss_msg ) ) {
1221
						$rendered .= sprintf( $line_template, wp_kses_post( $this->dismiss_msg ) );
1222
					}
1223
1224
					// Render the individual message lines for the notice.
1225
					foreach ( $message as $type => $plugin_group ) {
1226
						$linked_plugins = array();
1227
1228
						// Get the external info link for a plugin if one is available.
1229
						foreach ( $plugin_group as $plugin_slug ) {
1230
							$linked_plugins[] = $this->get_info_link( $plugin_slug );
1231
						}
1232
						unset( $plugin_slug );
1233
1234
						$count          = count( $plugin_group );
1235
						$linked_plugins = array_map( array( 'TGMPA_Utils', 'wrap_in_em' ), $linked_plugins );
1236
						$last_plugin    = array_pop( $linked_plugins ); // Pop off last name to prep for readability.
1237
						$imploded       = empty( $linked_plugins ) ? $last_plugin : ( implode( ', ', $linked_plugins ) . ' ' . esc_html_x( 'and', 'plugin A *and* plugin B', 'tgmpa' ) . ' ' . $last_plugin );
1238
1239
						$rendered .= sprintf(
1240
							$line_template,
1241
							sprintf(
1242
								translate_nooped_plural( $this->strings[ $type ], $count, 'tgmpa' ),
1243
								$imploded,
1244
								$count
1245
							)
1246
						);
1247
1248
					}
1249
					unset( $type, $plugin_group, $linked_plugins, $count, $last_plugin, $imploded );
1250
1251
					$rendered .= $this->create_user_action_links_for_notice( $install_link_count, $update_link_count, $activate_link_count, $line_template );
1252
				}
1253
1254
				// Register the nag messages and prepare them to be processed.
1255
				add_settings_error( 'tgmpa', 'tgmpa', $rendered, $this->get_admin_notice_class() );
1256
			}
1257
1258
			// Admin options pages already output settings_errors, so this is to avoid duplication.
1259
			if ( 'options-general' !== $GLOBALS['current_screen']->parent_base ) {
1260
				$this->display_settings_errors();
1261
			}
1262
		}
1263
1264
		/**
1265
		 * Generate the user action links for the admin notice.
1266
		 *
1267
		 * @since 2.6.0
1268
		 *
1269
		 * @param int $install_count  Number of plugins to install.
1270
		 * @param int $update_count   Number of plugins to update.
1271
		 * @param int $activate_count Number of plugins to activate.
1272
		 * @param int $line_template  Template for the HTML tag to output a line.
1273
		 * @return string Action links.
1274
		 */
1275
		protected function create_user_action_links_for_notice( $install_count, $update_count, $activate_count, $line_template ) {
1276
			// Setup action links.
1277
			$action_links = array(
1278
				'install'  => '',
1279
				'update'   => '',
1280
				'activate' => '',
1281
				'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>' : '',
1282
			);
1283
1284
			$link_template = '<a href="%2$s">%1$s</a>';
1285
1286
			if ( current_user_can( 'install_plugins' ) ) {
1287
				if ( $install_count > 0 ) {
1288
					$action_links['install'] = sprintf(
1289
						$link_template,
1290
						translate_nooped_plural( $this->strings['install_link'], $install_count, 'tgmpa' ),
1291
						esc_url( $this->get_tgmpa_status_url( 'install' ) )
1292
					);
1293
				}
1294
				if ( $update_count > 0 ) {
1295
					$action_links['update'] = sprintf(
1296
						$link_template,
1297
						translate_nooped_plural( $this->strings['update_link'], $update_count, 'tgmpa' ),
1298
						esc_url( $this->get_tgmpa_status_url( 'update' ) )
1299
					);
1300
				}
1301
			}
1302
1303
			if ( current_user_can( 'activate_plugins' ) && $activate_count > 0 ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1304
				$action_links['activate'] = sprintf(
1305
					$link_template,
1306
					translate_nooped_plural( $this->strings['activate_link'], $activate_count, 'tgmpa' ),
1307
					esc_url( $this->get_tgmpa_status_url( 'activate' ) )
1308
				);
1309
			}
1310
1311
			$action_links = apply_filters( 'tgmpa_notice_action_links', $action_links );
1312
1313
			$action_links = array_filter( (array) $action_links ); // Remove any empty array items.
1314
1315
			if ( ! empty( $action_links ) ) {
1316
				$action_links = sprintf( $line_template, implode( ' | ', $action_links ) );
1317
				return apply_filters( 'tgmpa_notice_rendered_action_links', $action_links );
1318
			} else {
1319
				return '';
1320
			}
1321
		}
1322
1323
		/**
1324
		 * Get admin notice class.
1325
		 *
1326
		 * Work around all the changes to the various admin notice classes between WP 4.4 and 3.7
1327
		 * (lowest supported version by TGMPA).
1328
		 *
1329
		 * @since 2.6.0
1330
		 *
1331
		 * @return string
1332
		 */
1333
		protected function get_admin_notice_class() {
1334
			if ( ! empty( $this->strings['nag_type'] ) ) {
1335
				return sanitize_html_class( strtolower( $this->strings['nag_type'] ) );
1336
			} else {
1337
				if ( version_compare( $this->wp_version, '4.2', '>=' ) ) {
1338
					return 'notice-warning';
1339
				} elseif ( version_compare( $this->wp_version, '4.1', '>=' ) ) {
1340
					return 'notice';
1341
				} else {
1342
					return 'updated';
1343
				}
1344
			}
1345
		}
1346
1347
		/**
1348
		 * Display settings errors and remove those which have been displayed to avoid duplicate messages showing
1349
		 *
1350
		 * @since 2.5.0
1351
		 */
1352
		protected function display_settings_errors() {
1353
			global $wp_settings_errors;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
1354
1355
			settings_errors( 'tgmpa' );
1356
1357
			foreach ( (array) $wp_settings_errors as $key => $details ) {
1358
				if ( 'tgmpa' === $details['setting'] ) {
1359
					unset( $wp_settings_errors[ $key ] );
1360
					break;
1361
				}
1362
			}
1363
		}
1364
1365
		/**
1366
		 * Register dismissal of admin notices.
1367
		 *
1368
		 * Acts on the dismiss link in the admin nag messages.
1369
		 * If clicked, the admin notice disappears and will no longer be visible to this user.
1370
		 *
1371
		 * @since 2.1.0
1372
		 */
1373
		public function dismiss() {
1374
			if ( isset( $_GET['tgmpa-dismiss'] ) && check_admin_referer( 'tgmpa-dismiss-' . get_current_user_id() ) ) {
1375
				update_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, 1 );
1376
			}
1377
		}
1378
1379
		/**
1380
		 * Add individual plugin to our collection of plugins.
1381
		 *
1382
		 * If the required keys are not set or the plugin has already
1383
		 * been registered, the plugin is not added.
1384
		 *
1385
		 * @since 2.0.0
1386
		 *
1387
		 * @param array|null $plugin Array of plugin arguments or null if invalid argument.
1388
		 * @return null Return early if incorrect argument.
1389
		 */
1390
		public function register( $plugin ) {
1391
			if ( empty( $plugin['slug'] ) || empty( $plugin['name'] ) ) {
1392
				return;
1393
			}
1394
1395
			if ( empty( $plugin['slug'] ) || ! is_string( $plugin['slug'] ) || isset( $this->plugins[ $plugin['slug'] ] ) ) {
1396
				return;
1397
			}
1398
1399
			$defaults = array(
1400
				'name'               => '',      // String
1401
				'slug'               => '',      // String
1402
				'source'             => 'repo',  // String
1403
				'required'           => false,   // Boolean
1404
				'version'            => '',      // String
1405
				'force_activation'   => false,   // Boolean
1406
				'force_deactivation' => false,   // Boolean
1407
				'external_url'       => '',      // String
1408
				'is_callable'        => '',      // String|Array.
1409
			);
1410
1411
			// Prepare the received data.
1412
			$plugin = wp_parse_args( $plugin, $defaults );
1413
1414
			// Standardize the received slug.
1415
			$plugin['slug'] = $this->sanitize_key( $plugin['slug'] );
1416
1417
			// Forgive users for using string versions of booleans or floats for version number.
1418
			$plugin['version']            = (string) $plugin['version'];
1419
			$plugin['source']             = empty( $plugin['source'] ) ? 'repo' : $plugin['source'];
1420
			$plugin['required']           = TGMPA_Utils::validate_bool( $plugin['required'] );
1421
			$plugin['force_activation']   = TGMPA_Utils::validate_bool( $plugin['force_activation'] );
1422
			$plugin['force_deactivation'] = TGMPA_Utils::validate_bool( $plugin['force_deactivation'] );
1423
1424
			// Enrich the received data.
1425
			$plugin['file_path']   = $this->_get_plugin_basename_from_slug( $plugin['slug'] );
1426
			$plugin['source_type'] = $this->get_plugin_source_type( $plugin['source'] );
1427
1428
			// Set the class properties.
1429
			$this->plugins[ $plugin['slug'] ]    = $plugin;
1430
			$this->sort_order[ $plugin['slug'] ] = $plugin['name'];
1431
1432
			// Should we add the force activation hook ?
1433
			if ( true === $plugin['force_activation'] ) {
1434
				$this->has_forced_activation = true;
1435
			}
1436
1437
			// Should we add the force deactivation hook ?
1438
			if ( true === $plugin['force_deactivation'] ) {
1439
				$this->has_forced_deactivation = true;
1440
			}
1441
		}
1442
1443
		/**
1444
		 * Determine what type of source the plugin comes from.
1445
		 *
1446
		 * @since 2.5.0
1447
		 *
1448
		 * @param string $source The source of the plugin as provided, either empty (= WP repo), a file path
1449
		 *                       (= bundled) or an external URL.
1450
		 * @return string 'repo', 'external', or 'bundled'
1451
		 */
1452
		protected function get_plugin_source_type( $source ) {
1453
			if ( 'repo' === $source || preg_match( self::WP_REPO_REGEX, $source ) ) {
1454
				return 'repo';
1455
			} elseif ( preg_match( self::IS_URL_REGEX, $source ) ) {
1456
				return 'external';
1457
			} else {
1458
				return 'bundled';
1459
			}
1460
		}
1461
1462
		/**
1463
		 * Sanitizes a string key.
1464
		 *
1465
		 * Near duplicate of WP Core `sanitize_key()`. The difference is that uppercase characters *are*
1466
		 * allowed, so as not to break upgrade paths from non-standard bundled plugins using uppercase
1467
		 * characters in the plugin directory path/slug. Silly them.
1468
		 *
1469
		 * @see https://developer.wordpress.org/reference/hooks/sanitize_key/
1470
		 *
1471
		 * @since 2.5.0
1472
		 *
1473
		 * @param string $key String key.
1474
		 * @return string Sanitized key
1475
		 */
1476
		public function sanitize_key( $key ) {
1477
			$raw_key = $key;
1478
			$key     = preg_replace( '`[^A-Za-z0-9_-]`', '', $key );
1479
1480
			/**
1481
			 * Filter a sanitized key string.
1482
			 *
1483
			 * @since 2.5.0
1484
			 *
1485
			 * @param string $key     Sanitized key.
1486
			 * @param string $raw_key The key prior to sanitization.
1487
			 */
1488
			return apply_filters( 'tgmpa_sanitize_key', $key, $raw_key );
1489
		}
1490
1491
		/**
1492
		 * Amend default configuration settings.
1493
		 *
1494
		 * @since 2.0.0
1495
		 *
1496
		 * @param array $config Array of config options to pass as class properties.
1497
		 */
1498
		public function config( $config ) {
1499
			$keys = array(
1500
				'id',
1501
				'default_path',
1502
				'has_notices',
1503
				'dismissable',
1504
				'dismiss_msg',
1505
				'menu',
1506
				'parent_slug',
1507
				'capability',
1508
				'is_automatic',
1509
				'message',
1510
				'strings',
1511
			);
1512
1513
			foreach ( $keys as $key ) {
1514
				if ( isset( $config[ $key ] ) ) {
1515
					if ( is_array( $config[ $key ] ) ) {
1516
						$this->$key = array_merge( $this->$key, $config[ $key ] );
1517
					} else {
1518
						$this->$key = $config[ $key ];
1519
					}
1520
				}
1521
			}
1522
		}
1523
1524
		/**
1525
		 * Amend action link after plugin installation.
1526
		 *
1527
		 * @since 2.0.0
1528
		 *
1529
		 * @param array $install_actions Existing array of actions.
1530
		 * @return false|array Amended array of actions.
1531
		 */
1532
		public function actions( $install_actions ) {
1533
			// Remove action links on the TGMPA install page.
1534
			if ( $this->is_tgmpa_page() ) {
1535
				return false;
1536
			}
1537
1538
			return $install_actions;
1539
		}
1540
1541
		/**
1542
		 * Flushes the plugins cache on theme switch to prevent stale entries
1543
		 * from remaining in the plugin table.
1544
		 *
1545
		 * @since 2.4.0
1546
		 *
1547
		 * @param bool $clear_update_cache Optional. Whether to clear the Plugin updates cache.
1548
		 *                                 Parameter added in v2.5.0.
1549
		 */
1550
		public function flush_plugins_cache( $clear_update_cache = true ) {
1551
			wp_clean_plugins_cache( $clear_update_cache );
1552
		}
1553
1554
		/**
1555
		 * Set file_path key for each installed plugin.
1556
		 *
1557
		 * @since 2.1.0
1558
		 *
1559
		 * @param string $plugin_slug Optional. If set, only (re-)populates the file path for that specific plugin.
1560
		 *                            Parameter added in v2.5.0.
1561
		 */
1562
		public function populate_file_path( $plugin_slug = '' ) {
1563
			if ( ! empty( $plugin_slug ) && is_string( $plugin_slug ) && isset( $this->plugins[ $plugin_slug ] ) ) {
1564
				$this->plugins[ $plugin_slug ]['file_path'] = $this->_get_plugin_basename_from_slug( $plugin_slug );
1565
			} else {
1566
				// Add file_path key for all plugins.
1567
				foreach ( $this->plugins as $slug => $values ) {
1568
					$this->plugins[ $slug ]['file_path'] = $this->_get_plugin_basename_from_slug( $slug );
1569
				}
1570
			}
1571
		}
1572
1573
		/**
1574
		 * Helper function to extract the file path of the plugin file from the
1575
		 * plugin slug, if the plugin is installed.
1576
		 *
1577
		 * @since 2.0.0
1578
		 *
1579
		 * @param string $slug Plugin slug (typically folder name) as provided by the developer.
1580
		 * @return string Either file path for plugin if installed, or just the plugin slug.
1581
		 */
1582
		protected function _get_plugin_basename_from_slug( $slug ) {
0 ignored issues
show
Coding Style introduced by
function _get_plugin_basename_from_slug() does not seem to conform to the naming convention (^(?:[a-z]|__)[a-z_0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
1583
			$keys = array_keys( $this->get_plugins() );
1584
1585
			foreach ( $keys as $key ) {
1586
				if ( preg_match( '|^' . $slug . '/|', $key ) ) {
1587
					return $key;
1588
				}
1589
			}
1590
1591
			return $slug;
1592
		}
1593
1594
		/**
1595
		 * Retrieve plugin data, given the plugin name.
1596
		 *
1597
		 * Loops through the registered plugins looking for $name. If it finds it,
1598
		 * it returns the $data from that plugin. Otherwise, returns false.
1599
		 *
1600
		 * @since 2.1.0
1601
		 *
1602
		 * @param string $name Name of the plugin, as it was registered.
1603
		 * @param string $data Optional. Array key of plugin data to return. Default is slug.
1604
		 * @return string|boolean Plugin slug if found, false otherwise.
1605
		 */
1606
		public function _get_plugin_data_from_name( $name, $data = 'slug' ) {
0 ignored issues
show
Coding Style introduced by
function _get_plugin_data_from_name() does not seem to conform to the naming convention (^(?:[a-z]|__)[a-z_0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
1607
			foreach ( $this->plugins as $values ) {
1608
				if ( $name === $values['name'] && isset( $values[ $data ] ) ) {
1609
					return $values[ $data ];
1610
				}
1611
			}
1612
1613
			return false;
1614
		}
1615
1616
		/**
1617
		 * Retrieve the download URL for a package.
1618
		 *
1619
		 * @since 2.5.0
1620
		 *
1621
		 * @param string $slug Plugin slug.
1622
		 * @return string Plugin download URL or path to local file or empty string if undetermined.
1623
		 */
1624
		public function get_download_url( $slug ) {
1625
			$dl_source = '';
1626
1627
			switch ( $this->plugins[ $slug ]['source_type'] ) {
1628
				case 'repo':
1629
					return $this->get_wp_repo_download_url( $slug );
1630
				case 'external':
1631
					return $this->plugins[ $slug ]['source'];
1632
				case 'bundled':
1633
					return $this->default_path . $this->plugins[ $slug ]['source'];
1634
			}
1635
1636
			return $dl_source; // Should never happen.
1637
		}
1638
1639
		/**
1640
		 * Retrieve the download URL for a WP repo package.
1641
		 *
1642
		 * @since 2.5.0
1643
		 *
1644
		 * @param string $slug Plugin slug.
1645
		 * @return string Plugin download URL.
1646
		 */
1647
		protected function get_wp_repo_download_url( $slug ) {
1648
			$source = '';
1649
			$api    = $this->get_plugins_api( $slug );
1650
1651
			if ( false !== $api && isset( $api->download_link ) ) {
1652
				$source = $api->download_link;
1653
			}
1654
1655
			return $source;
1656
		}
1657
1658
		/**
1659
		 * Try to grab information from WordPress API.
1660
		 *
1661
		 * @since 2.5.0
1662
		 *
1663
		 * @param string $slug Plugin slug.
1664
		 * @return object Plugins_api response object on success, WP_Error on failure.
1665
		 */
1666
		protected function get_plugins_api( $slug ) {
1667
			static $api = array(); // Cache received responses.
1668
1669
			if ( ! isset( $api[ $slug ] ) ) {
1670
				if ( ! function_exists( 'plugins_api' ) ) {
1671
					require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
1672
				}
1673
1674
				$response = plugins_api(
1675
					'plugin_information',
1676
					array(
1677
						'slug'   => $slug,
1678
						'fields' => array(
1679
							'sections' => false,
1680
						),
1681
					)
1682
				);
1683
1684
				$api[ $slug ] = false;
1685
1686
				if ( is_wp_error( $response ) ) {
1687
					wp_die( esc_html( $this->strings['oops'] ) );
1688
				} else {
1689
					$api[ $slug ] = $response;
1690
				}
1691
			}
1692
1693
			return $api[ $slug ];
1694
		}
1695
1696
		/**
1697
		 * Retrieve a link to a plugin information page.
1698
		 *
1699
		 * @since 2.5.0
1700
		 *
1701
		 * @param string $slug Plugin slug.
1702
		 * @return string Fully formed html link to a plugin information page if available
1703
		 *                or the plugin name if not.
1704
		 */
1705
		public function get_info_link( $slug ) {
1706
			if ( ! empty( $this->plugins[ $slug ]['external_url'] ) && preg_match( self::IS_URL_REGEX, $this->plugins[ $slug ]['external_url'] ) ) {
1707
				$link = sprintf(
1708
					'<a href="%1$s" target="_blank">%2$s</a>',
1709
					esc_url( $this->plugins[ $slug ]['external_url'] ),
1710
					esc_html( $this->plugins[ $slug ]['name'] )
1711
				);
1712
			} elseif ( 'repo' === $this->plugins[ $slug ]['source_type'] ) {
1713
				$url = add_query_arg(
1714
					array(
1715
						'tab'       => 'plugin-information',
1716
						'plugin'    => urlencode( $slug ),
1717
						'TB_iframe' => 'true',
1718
						'width'     => '640',
1719
						'height'    => '500',
1720
					),
1721
					self_admin_url( 'plugin-install.php' )
1722
				);
1723
1724
				$link = sprintf(
1725
					'<a href="%1$s" class="thickbox">%2$s</a>',
1726
					esc_url( $url ),
1727
					esc_html( $this->plugins[ $slug ]['name'] )
1728
				);
1729
			} else {
1730
				$link = esc_html( $this->plugins[ $slug ]['name'] ); // No hyperlink.
1731
			}
1732
1733
			return $link;
1734
		}
1735
1736
		/**
1737
		 * Determine if we're on the TGMPA Install page.
1738
		 *
1739
		 * @since 2.1.0
1740
		 *
1741
		 * @return boolean True when on the TGMPA page, false otherwise.
1742
		 */
1743
		protected function is_tgmpa_page() {
1744
			return isset( $_GET['page'] ) && $this->menu === $_GET['page'];
1745
		}
1746
1747
		/**
1748
		 * Determine if we're on a WP Core installation/upgrade page.
1749
		 *
1750
		 * @since 2.6.0
1751
		 *
1752
		 * @return boolean True when on a WP Core installation/upgrade page, false otherwise.
1753
		 */
1754
		protected function is_core_update_page() {
1755
			// Current screen is not always available, most notably on the customizer screen.
1756
			if ( ! function_exists( 'get_current_screen' ) ) {
1757
				return false;
1758
			}
1759
1760
			$screen = get_current_screen();
1761
1762
			if ( 'update-core' === $screen->base ) {
1763
				// Core update screen.
1764
				return true;
1765
			} elseif ( 'plugins' === $screen->base && ! empty( $_POST['action'] ) ) { // WPCS: CSRF ok.
1766
				// Plugins bulk update screen.
1767
				return true;
1768
			} elseif ( 'update' === $screen->base && ! empty( $_POST['action'] ) ) { // WPCS: CSRF ok.
1769
				// Individual updates (ajax call).
1770
				return true;
1771
			}
1772
1773
			return false;
1774
		}
1775
1776
		/**
1777
		 * Retrieve the URL to the TGMPA Install page.
1778
		 *
1779
		 * I.e. depending on the config settings passed something along the lines of:
1780
		 * http://example.com/wp-admin/themes.php?page=tgmpa-install-plugins
1781
		 *
1782
		 * @since 2.5.0
1783
		 *
1784
		 * @return string Properly encoded URL (not escaped).
1785
		 */
1786
		public function get_tgmpa_url() {
1787
			static $url;
1788
1789
			if ( ! isset( $url ) ) {
1790
				$parent = $this->parent_slug;
1791
				if ( false === strpos( $parent, '.php' ) ) {
1792
					$parent = 'admin.php';
1793
				}
1794
				$url = add_query_arg(
1795
					array(
1796
						'page' => urlencode( $this->menu ),
1797
					),
1798
					self_admin_url( $parent )
1799
				);
1800
			}
1801
1802
			return $url;
1803
		}
1804
1805
		/**
1806
		 * Retrieve the URL to the TGMPA Install page for a specific plugin status (view).
1807
		 *
1808
		 * I.e. depending on the config settings passed something along the lines of:
1809
		 * http://example.com/wp-admin/themes.php?page=tgmpa-install-plugins&plugin_status=install
1810
		 *
1811
		 * @since 2.5.0
1812
		 *
1813
		 * @param string $status Plugin status - either 'install', 'update' or 'activate'.
1814
		 * @return string Properly encoded URL (not escaped).
1815
		 */
1816
		public function get_tgmpa_status_url( $status ) {
1817
			return add_query_arg(
1818
				array(
1819
					'plugin_status' => urlencode( $status ),
1820
				),
1821
				$this->get_tgmpa_url()
1822
			);
1823
		}
1824
1825
		/**
1826
		 * Determine whether there are open actions for plugins registered with TGMPA.
1827
		 *
1828
		 * @since 2.5.0
1829
		 *
1830
		 * @return bool True if complete, i.e. no outstanding actions. False otherwise.
1831
		 */
1832
		public function is_tgmpa_complete() {
1833
			$complete = true;
1834
			foreach ( $this->plugins as $slug => $plugin ) {
1835
				if ( ! $this->is_plugin_active( $slug ) || false !== $this->does_plugin_have_update( $slug ) ) {
1836
					$complete = false;
1837
					break;
1838
				}
1839
			}
1840
1841
			return $complete;
1842
		}
1843
1844
		/**
1845
		 * Check if a plugin is installed. Does not take must-use plugins into account.
1846
		 *
1847
		 * @since 2.5.0
1848
		 *
1849
		 * @param string $slug Plugin slug.
1850
		 * @return bool True if installed, false otherwise.
1851
		 */
1852
		public function is_plugin_installed( $slug ) {
1853
			$installed_plugins = $this->get_plugins(); // Retrieve a list of all installed plugins (WP cached).
1854
1855
			return ( ! empty( $installed_plugins[ $this->plugins[ $slug ]['file_path'] ] ) );
1856
		}
1857
1858
		/**
1859
		 * Check if a plugin is active.
1860
		 *
1861
		 * @since 2.5.0
1862
		 *
1863
		 * @param string $slug Plugin slug.
1864
		 * @return bool True if active, false otherwise.
1865
		 */
1866
		public function is_plugin_active( $slug ) {
1867
			return ( ( ! empty( $this->plugins[ $slug ]['is_callable'] ) && is_callable( $this->plugins[ $slug ]['is_callable'] ) ) || is_plugin_active( $this->plugins[ $slug ]['file_path'] ) );
1868
		}
1869
1870
		/**
1871
		 * Check if a plugin can be updated, i.e. if we have information on the minimum WP version required
1872
		 * available, check whether the current install meets them.
1873
		 *
1874
		 * @since 2.5.0
1875
		 *
1876
		 * @param string $slug Plugin slug.
1877
		 * @return bool True if OK to update, false otherwise.
1878
		 */
1879
		public function can_plugin_update( $slug ) {
0 ignored issues
show
Coding Style introduced by
function can_plugin_update() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
1880
			// We currently can't get reliable info on non-WP-repo plugins - issue #380.
1881
			if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) {
1882
				return true;
1883
			}
1884
1885
			$api = $this->get_plugins_api( $slug );
1886
1887
			if ( false !== $api && isset( $api->requires ) ) {
1888
				return version_compare( $this->wp_version, $api->requires, '>=' );
1889
			}
1890
1891
			// No usable info received from the plugins API, presume we can update.
1892
			return true;
1893
		}
1894
1895
		/**
1896
		 * Check to see if the plugin is 'updatetable', i.e. installed, with an update available
1897
		 * and no WP version requirements blocking it.
1898
		 *
1899
		 * @since 2.6.0
1900
		 *
1901
		 * @param string $slug Plugin slug.
1902
		 * @return bool True if OK to proceed with update, false otherwise.
1903
		 */
1904
		public function is_plugin_updatetable( $slug ) {
1905
			if ( ! $this->is_plugin_installed( $slug ) ) {
1906
				return false;
1907
			} else {
1908
				return ( false !== $this->does_plugin_have_update( $slug ) && $this->can_plugin_update( $slug ) );
1909
			}
1910
		}
1911
1912
		/**
1913
		 * Check if a plugin can be activated, i.e. is not currently active and meets the minimum
1914
		 * plugin version requirements set in TGMPA (if any).
1915
		 *
1916
		 * @since 2.5.0
1917
		 *
1918
		 * @param string $slug Plugin slug.
1919
		 * @return bool True if OK to activate, false otherwise.
1920
		 */
1921
		public function can_plugin_activate( $slug ) {
0 ignored issues
show
Coding Style introduced by
function can_plugin_activate() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
1922
			return ( ! $this->is_plugin_active( $slug ) && ! $this->does_plugin_require_update( $slug ) );
1923
		}
1924
1925
		/**
1926
		 * Retrieve the version number of an installed plugin.
1927
		 *
1928
		 * @since 2.5.0
1929
		 *
1930
		 * @param string $slug Plugin slug.
1931
		 * @return string Version number as string or an empty string if the plugin is not installed
1932
		 *                or version unknown (plugins which don't comply with the plugin header standard).
1933
		 */
1934
		public function get_installed_version( $slug ) {
1935
			$installed_plugins = $this->get_plugins(); // Retrieve a list of all installed plugins (WP cached).
1936
1937
			if ( ! empty( $installed_plugins[ $this->plugins[ $slug ]['file_path'] ]['Version'] ) ) {
1938
				return $installed_plugins[ $this->plugins[ $slug ]['file_path'] ]['Version'];
1939
			}
1940
1941
			return '';
1942
		}
1943
1944
		/**
1945
		 * Check whether a plugin complies with the minimum version requirements.
1946
		 *
1947
		 * @since 2.5.0
1948
		 *
1949
		 * @param string $slug Plugin slug.
1950
		 * @return bool True when a plugin needs to be updated, otherwise false.
1951
		 */
1952
		public function does_plugin_require_update( $slug ) {
0 ignored issues
show
Coding Style introduced by
function does_plugin_require_update() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
1953
			$installed_version = $this->get_installed_version( $slug );
1954
			$minimum_version   = $this->plugins[ $slug ]['version'];
1955
1956
			return version_compare( $minimum_version, $installed_version, '>' );
1957
		}
1958
1959
		/**
1960
		 * Check whether there is an update available for a plugin.
1961
		 *
1962
		 * @since 2.5.0
1963
		 *
1964
		 * @param string $slug Plugin slug.
1965
		 * @return false|string Version number string of the available update or false if no update available.
1966
		 */
1967
		public function does_plugin_have_update( $slug ) {
1968
			// Presume bundled and external plugins will point to a package which meets the minimum required version.
1969
			if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) {
1970
				if ( $this->does_plugin_require_update( $slug ) ) {
1971
					return $this->plugins[ $slug ]['version'];
1972
				}
1973
1974
				return false;
1975
			}
1976
1977
			$repo_updates = get_site_transient( 'update_plugins' );
1978
1979 View Code Duplication
			if ( isset( $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->new_version ) ) {
1980
				return $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->new_version;
1981
			}
1982
1983
			return false;
1984
		}
1985
1986
		/**
1987
		 * Retrieve potential upgrade notice for a plugin.
1988
		 *
1989
		 * @since 2.5.0
1990
		 *
1991
		 * @param string $slug Plugin slug.
1992
		 * @return string The upgrade notice or an empty string if no message was available or provided.
1993
		 */
1994
		public function get_upgrade_notice( $slug ) {
1995
			// We currently can't get reliable info on non-WP-repo plugins - issue #380.
1996
			if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) {
1997
				return '';
1998
			}
1999
2000
			$repo_updates = get_site_transient( 'update_plugins' );
2001
2002 View Code Duplication
			if ( ! empty( $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->upgrade_notice ) ) {
2003
				return $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->upgrade_notice;
2004
			}
2005
2006
			return '';
2007
		}
2008
2009
		/**
2010
		 * Wrapper around the core WP get_plugins function, making sure it's actually available.
2011
		 *
2012
		 * @since 2.5.0
2013
		 *
2014
		 * @param string $plugin_folder Optional. Relative path to single plugin folder.
2015
		 * @return array Array of installed plugins with plugin information.
2016
		 */
2017
		public function get_plugins( $plugin_folder = '' ) {
2018
			if ( ! function_exists( 'get_plugins' ) ) {
2019
				require_once ABSPATH . 'wp-admin/includes/plugin.php';
2020
			}
2021
2022
			return get_plugins( $plugin_folder );
2023
		}
2024
2025
		/**
2026
		 * Delete dismissable nag option when theme is switched.
2027
		 *
2028
		 * This ensures that the user(s) is/are again reminded via nag of required
2029
		 * and/or recommended plugins if they re-activate the theme.
2030
		 *
2031
		 * @since 2.1.1
2032
		 */
2033
		public function update_dismiss() {
2034
			delete_metadata( 'user', null, 'tgmpa_dismissed_notice_' . $this->id, null, true );
2035
		}
2036
2037
		/**
2038
		 * Forces plugin activation if the parameter 'force_activation' is
2039
		 * set to true.
2040
		 *
2041
		 * This allows theme authors to specify certain plugins that must be
2042
		 * active at all times while using the current theme.
2043
		 *
2044
		 * Please take special care when using this parameter as it has the
2045
		 * potential to be harmful if not used correctly. Setting this parameter
2046
		 * to true will not allow the specified plugin to be deactivated unless
2047
		 * the user switches themes.
2048
		 *
2049
		 * @since 2.2.0
2050
		 */
2051
		public function force_activation() {
2052
			foreach ( $this->plugins as $slug => $plugin ) {
2053
				if ( true === $plugin['force_activation'] ) {
2054
					if ( ! $this->is_plugin_installed( $slug ) ) {
2055
						// Oops, plugin isn't there so iterate to next condition.
2056
						continue;
2057
					} elseif ( $this->can_plugin_activate( $slug ) ) {
2058
						// There we go, activate the plugin.
2059
						activate_plugin( $plugin['file_path'] );
2060
					}
2061
				}
2062
			}
2063
		}
2064
2065
		/**
2066
		 * Forces plugin deactivation if the parameter 'force_deactivation'
2067
		 * is set to true and adds the plugin to the 'recently active' plugins list.
2068
		 *
2069
		 * This allows theme authors to specify certain plugins that must be
2070
		 * deactivated upon switching from the current theme to another.
2071
		 *
2072
		 * Please take special care when using this parameter as it has the
2073
		 * potential to be harmful if not used correctly.
2074
		 *
2075
		 * @since 2.2.0
2076
		 */
2077
		public function force_deactivation() {
2078
			$deactivated = array();
2079
2080
			foreach ( $this->plugins as $slug => $plugin ) {
2081
				/*
2082
				 * Only proceed forward if the parameter is set to true and plugin is active
2083
				 * as a 'normal' (not must-use) plugin.
2084
				 */
2085
				if ( true === $plugin['force_deactivation'] && is_plugin_active( $plugin['file_path'] ) ) {
2086
					deactivate_plugins( $plugin['file_path'] );
2087
					$deactivated[ $plugin['file_path'] ] = time();
2088
				}
2089
			}
2090
2091
			if ( ! empty( $deactivated ) ) {
2092
				update_option( 'recently_activated', $deactivated + (array) get_option( 'recently_activated' ) );
2093
			}
2094
		}
2095
2096
		/**
2097
		 * Echo the current TGMPA version number to the page.
2098
		 *
2099
		 * @since 2.5.0
2100
		 */
2101
		public function show_tgmpa_version() {
2102
			echo '<p style="float: right; padding: 0em 1.5em 0.5em 0;"><strong><small>',
2103
				esc_html(
2104
					sprintf(
2105
						/* translators: %s: version number */
2106
						__( 'TGMPA v%s', 'tgmpa' ),
2107
						self::TGMPA_VERSION
2108
					)
2109
				),
2110
				'</small></strong></p>';
2111
		}
2112
2113
		/**
2114
		 * Adds CSS to admin head.
2115
		 *
2116
		 * @since 2.6.2
2117
		 */
2118
		public function admin_css() {
2119
			if ( ! $this->is_tgmpa_page() ) {
2120
				return;
2121
			}
2122
2123
			echo '
2124
			<style>
2125
			#tgmpa-plugins .tgmpa-type-required > th {
2126
				border-left: 3px solid #dc3232;
2127
			}
2128
			</style>';
2129
		}
2130
2131
		/**
2132
		 * Returns the singleton instance of the class.
2133
		 *
2134
		 * @since 2.4.0
2135
		 *
2136
		 * @return \TGM_Plugin_Activation The TGM_Plugin_Activation object.
2137
		 */
2138
		public static function get_instance() {
2139
			if ( ! isset( self::$instance ) && ! ( self::$instance instanceof self ) ) {
2140
				self::$instance = new self();
2141
			}
2142
2143
			return self::$instance;
2144
		}
2145
	}
2146
2147
	if ( ! function_exists( 'load_tgm_plugin_activation' ) ) {
2148
		/**
2149
		 * Ensure only one instance of the class is ever invoked.
2150
		 *
2151
		 * @since 2.5.0
2152
		 */
2153
		function load_tgm_plugin_activation() {
2154
			$GLOBALS['tgmpa'] = TGM_Plugin_Activation::get_instance();
2155
		}
2156
	}
2157
2158
	if ( did_action( 'plugins_loaded' ) ) {
2159
		load_tgm_plugin_activation();
2160
	} else {
2161
		add_action( 'plugins_loaded', 'load_tgm_plugin_activation' );
2162
	}
2163
}
2164
2165
if ( ! function_exists( 'tgmpa' ) ) {
2166
	/**
2167
	 * Helper function to register a collection of required plugins.
2168
	 *
2169
	 * @since 2.0.0
2170
	 * @api
2171
	 *
2172
	 * @param array $plugins An array of plugin arrays.
2173
	 * @param array $config  Optional. An array of configuration values.
2174
	 */
2175
	function tgmpa( $plugins, $config = array() ) {
2176
		$instance = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
2177
2178
		foreach ( $plugins as $plugin ) {
2179
			call_user_func( array( $instance, 'register' ), $plugin );
2180
		}
2181
2182
		if ( ! empty( $config ) && is_array( $config ) ) {
2183
			// Send out notices for deprecated arguments passed.
2184
			if ( isset( $config['notices'] ) ) {
2185
				_deprecated_argument( __FUNCTION__, '2.2.0', 'The `notices` config parameter was renamed to `has_notices` in TGMPA 2.2.0. Please adjust your configuration.' );
2186
				if ( ! isset( $config['has_notices'] ) ) {
2187
					$config['has_notices'] = $config['notices'];
2188
				}
2189
			}
2190
2191
			if ( isset( $config['parent_menu_slug'] ) ) {
2192
				_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.' );
2193
			}
2194
			if ( isset( $config['parent_url_slug'] ) ) {
2195
				_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.' );
2196
			}
2197
2198
			call_user_func( array( $instance, 'config' ), $config );
2199
		}
2200
	}
2201
}
2202
2203
if ( ! function_exists( 'tgmpa_wpfavs_plugins' ) ) {
2204
	/**
2205
	 * Custom function that grabs plugins from https://wpfavs.com
2206
	 * from given token
2207
	 *
2208
	 * @since 2.7.0
2209
	 *
2210
	 * @param string $token Wp Fav token key.
2211
	 *
2212
	 * @return array
2213
	 */
2214
	function tgmpa_wpfavs_plugins( $token ) {
2215
		if ( empty( $token ) ) {
2216
			return array();
2217
		}
2218
2219
		$cache = json_decode( get_transient( 'tgmpa_wpfavs_plugins' ), true );
2220
2221
		if ( empty( $cache ) ) {
2222
			// Call the API.
2223
			$response = wp_remote_get( 'https://wpfavs.com/api/v1/wpfav/' . $token );
2224
2225
			// Make sure there are no errors.
2226
			if ( is_wp_error( $response ) ) {
2227
				return array();
2228
			}
2229
2230
			// Decode response.
2231
			$response = apply_filters( 'tgmpa_wpfav_api_response', json_decode( wp_remote_retrieve_body( $response ), true ) );
2232
2233
			// check for api errors.
2234
			if ( isset( $response['error'] ) ) {
2235
				return array();
2236
			}
2237
2238
			$plugins = array();
2239
			// create our plugins array.
2240
			if ( isset( $response['plugins'] ) ) {
2241
				foreach ( $response['plugins'] as $plugin ) {
2242
					$plugins[] = array(
2243
						'name'      => $plugin['name'],
2244
						'slug'      => $plugin['slug'],
2245
						'source'    => $plugin['data']['download_link'],
2246
					);
2247
				}
2248
			}
2249
			// in case user want to modify default array for example to pass required parameter.
2250
			$plugins = apply_filters( 'tgmpa_wpfavs_plugins', $plugins );
2251
			// save to cache.
2252
			set_transient( 'tgmpa_wpfavs_plugins', wp_json_encode( $plugins ), 1 * DAY_IN_SECONDS );
2253
			return $plugins;
2254
		}
2255
		return $cache;
2256
	}
2257
}
2258
2259
if ( ! function_exists( 'tgmpa_wp_plugins' ) ) {
2260
	/**
2261
	 * Custom function that grabs favorites plugins from https://wordpress.org
2262
	 * from given username
2263
	 *
2264
	 * @since 2.7.0
2265
	 *
2266
	 * @param string $username Wordpress.org username.
2267
	 *
2268
	 * @return array
2269
	 */
2270
	function tgmpa_wp_plugins( $username ) {
2271
		if ( empty( $username ) ) {
2272
			return array();
2273
		}
2274
2275
		$cache = json_decode( get_transient( 'tgmpa_wp_plugins' ), true );
2276
2277
		if ( empty( $cache ) ) {
2278
2279
			if ( ! function_exists( 'plugins_api' ) ) {
2280
				require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
2281
			}
2282
			// Call the API.
2283
			$response = plugins_api( 'query_plugins',
2284
				array(
2285
					'user' => $username,
2286
					'per_page' => 100,
2287
				)
2288
			);
2289
2290
			// Make sure there are no errors or there are plugins.
2291
			if ( is_wp_error( $response ) || empty( $response->plugins ) ) {
2292
				return array();
2293
			}
2294
2295
			$plugins = array();
2296
			// create our plugins array.
2297
			foreach ( $response->plugins as $plugin ) {
2298
				$plugins[] = array(
2299
					'name'      => $plugin->name,
2300
					'slug'      => $plugin->slug,
2301
				);
2302
			}
2303
2304
			// in case user want to modify default array for example to pass required parameter.
2305
			$plugins = apply_filters( 'tgmpa_wp_plugins', $plugins );
2306
			// save to cache.
2307
			set_transient( 'tgmpa_wp_plugins', wp_json_encode( $plugins ), 1 * DAY_IN_SECONDS );
2308
			return $plugins;
2309
		}
2310
		return $cache;
2311
	}
2312
}
2313
2314
/**
2315
 * WP_List_Table isn't always available. If it isn't available,
2316
 * we load it here.
2317
 *
2318
 * @since 2.2.0
2319
 */
2320
if ( ! class_exists( 'WP_List_Table' ) ) {
2321
	require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
2322
}
2323
2324
if ( ! class_exists( 'TGMPA_List_Table' ) ) {
2325
2326
	/**
2327
	 * List table class for handling plugins.
2328
	 *
2329
	 * Extends the WP_List_Table class to provide a future-compatible
2330
	 * way of listing out all required/recommended plugins.
2331
	 *
2332
	 * Gives users an interface similar to the Plugin Administration
2333
	 * area with similar (albeit stripped down) capabilities.
2334
	 *
2335
	 * This class also allows for the bulk install of plugins.
2336
	 *
2337
	 * @since 2.2.0
2338
	 *
2339
	 * @package TGM-Plugin-Activation
2340
	 * @author  Thomas Griffin
2341
	 * @author  Gary Jones
2342
	 */
2343
	class TGMPA_List_Table extends WP_List_Table {
2344
		/**
2345
		 * TGMPA instance.
2346
		 *
2347
		 * @since 2.5.0
2348
		 *
2349
		 * @var object
2350
		 */
2351
		protected $tgmpa;
2352
2353
		/**
2354
		 * The currently chosen view.
2355
		 *
2356
		 * @since 2.5.0
2357
		 *
2358
		 * @var string One of: 'all', 'install', 'update', 'activate'
2359
		 */
2360
		public $view_context = 'all';
2361
2362
		/**
2363
		 * The plugin counts for the various views.
2364
		 *
2365
		 * @since 2.5.0
2366
		 *
2367
		 * @var array
2368
		 */
2369
		protected $view_totals = array(
2370
			'all'      => 0,
2371
			'install'  => 0,
2372
			'update'   => 0,
2373
			'activate' => 0,
2374
		);
2375
2376
		/**
2377
		 * References parent constructor and sets defaults for class.
2378
		 *
2379
		 * @since 2.2.0
2380
		 */
2381
		public function __construct() {
2382
			$this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
2383
2384
			parent::__construct(
2385
				array(
2386
					'singular' => 'plugin',
2387
					'plural'   => 'plugins',
2388
					'ajax'     => false,
2389
				)
2390
			);
2391
2392
			if ( isset( $_REQUEST['plugin_status'] ) && in_array( $_REQUEST['plugin_status'], array( 'install', 'update', 'activate' ), true ) ) {
2393
				$this->view_context = sanitize_key( $_REQUEST['plugin_status'] );
2394
			}
2395
2396
			add_filter( 'tgmpa_table_data_items', array( $this, 'sort_table_items' ) );
2397
		}
2398
2399
		/**
2400
		 * Get a list of CSS classes for the <table> tag.
2401
		 *
2402
		 * Overruled to prevent the 'plural' argument from being added.
2403
		 *
2404
		 * @since 2.5.0
2405
		 *
2406
		 * @return array CSS classnames.
2407
		 */
2408
		public function get_table_classes() {
2409
			return array( 'widefat', 'fixed' );
2410
		}
2411
2412
		/**
2413
		 * Gathers and renames all of our plugin information to be used by WP_List_Table to create our table.
2414
		 *
2415
		 * @since 2.2.0
2416
		 *
2417
		 * @return array $table_data Information for use in table.
2418
		 */
2419
		protected function _gather_plugin_data() {
0 ignored issues
show
Coding Style introduced by
function _gather_plugin_data() does not seem to conform to the naming convention (^(?:[a-z]|__)[a-z_0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
2420
			// Load thickbox for plugin links.
2421
			$this->tgmpa->admin_init();
2422
			$this->tgmpa->thickbox();
2423
2424
			// Categorize the plugins which have open actions.
2425
			$plugins = $this->categorize_plugins_to_views();
2426
2427
			// Set the counts for the view links.
2428
			$this->set_view_totals( $plugins );
2429
2430
			// Prep variables for use and grab list of all installed plugins.
2431
			$table_data = array();
2432
			$i          = 0;
2433
2434
			// Redirect to the 'all' view if no plugins were found for the selected view context.
2435
			if ( empty( $plugins[ $this->view_context ] ) ) {
2436
				$this->view_context = 'all';
2437
			}
2438
2439
			foreach ( $plugins[ $this->view_context ] as $slug => $plugin ) {
2440
				$table_data[ $i ]['sanitized_plugin']  = $plugin['name'];
2441
				$table_data[ $i ]['slug']              = $slug;
2442
				$table_data[ $i ]['plugin']            = '<strong>' . $this->tgmpa->get_info_link( $slug ) . '</strong>';
2443
				$table_data[ $i ]['source']            = $this->get_plugin_source_type_text( $plugin['source_type'] );
2444
				$table_data[ $i ]['type']              = $this->get_plugin_advise_type_text( $plugin['required'] );
2445
				$table_data[ $i ]['status']            = $this->get_plugin_status_text( $slug );
2446
				$table_data[ $i ]['installed_version'] = $this->tgmpa->get_installed_version( $slug );
2447
				$table_data[ $i ]['minimum_version']   = $plugin['version'];
2448
				$table_data[ $i ]['available_version'] = $this->tgmpa->does_plugin_have_update( $slug );
2449
2450
				// Prep the upgrade notice info.
2451
				$upgrade_notice = $this->tgmpa->get_upgrade_notice( $slug );
2452
				if ( ! empty( $upgrade_notice ) ) {
2453
					$table_data[ $i ]['upgrade_notice'] = $upgrade_notice;
2454
2455
					add_action( "tgmpa_after_plugin_row_{$slug}", array( $this, 'wp_plugin_update_row' ), 10, 2 );
2456
				}
2457
2458
				$table_data[ $i ] = apply_filters( 'tgmpa_table_data_item', $table_data[ $i ], $plugin );
2459
2460
				$i++;
2461
			}
2462
2463
			return $table_data;
2464
		}
2465
2466
		/**
2467
		 * Categorize the plugins which have open actions into views for the TGMPA page.
2468
		 *
2469
		 * @since 2.5.0
2470
		 */
2471
		protected function categorize_plugins_to_views() {
2472
			$plugins = array(
2473
				'all'      => array(), // Meaning: all plugins which still have open actions.
2474
				'install'  => array(),
2475
				'update'   => array(),
2476
				'activate' => array(),
2477
			);
2478
2479
			foreach ( $this->tgmpa->plugins as $slug => $plugin ) {
2480
				if ( $this->tgmpa->is_plugin_active( $slug ) && false === $this->tgmpa->does_plugin_have_update( $slug ) ) {
2481
					// No need to display plugins if they are installed, up-to-date and active.
2482
					continue;
2483
				} else {
2484
					$plugins['all'][ $slug ] = $plugin;
2485
2486
					if ( ! $this->tgmpa->is_plugin_installed( $slug ) ) {
2487
						$plugins['install'][ $slug ] = $plugin;
2488
					} else {
2489
						if ( false !== $this->tgmpa->does_plugin_have_update( $slug ) ) {
2490
							$plugins['update'][ $slug ] = $plugin;
2491
						}
2492
2493
						if ( $this->tgmpa->can_plugin_activate( $slug ) ) {
2494
							$plugins['activate'][ $slug ] = $plugin;
2495
						}
2496
					}
2497
				}
2498
			}
2499
2500
			return $plugins;
2501
		}
2502
2503
		/**
2504
		 * Set the counts for the view links.
2505
		 *
2506
		 * @since 2.5.0
2507
		 *
2508
		 * @param array $plugins Plugins order by view.
2509
		 */
2510
		protected function set_view_totals( $plugins ) {
2511
			foreach ( $plugins as $type => $list ) {
2512
				$this->view_totals[ $type ] = count( $list );
2513
			}
2514
		}
2515
2516
		/**
2517
		 * Get the plugin required/recommended text string.
2518
		 *
2519
		 * @since 2.5.0
2520
		 *
2521
		 * @param string $required Plugin required setting.
2522
		 * @return string
2523
		 */
2524
		protected function get_plugin_advise_type_text( $required ) {
2525
			if ( true === $required ) {
2526
				return __( 'Required', 'tgmpa' );
2527
			}
2528
2529
			return __( 'Recommended', 'tgmpa' );
2530
		}
2531
2532
		/**
2533
		 * Get the plugin source type text string.
2534
		 *
2535
		 * @since 2.5.0
2536
		 *
2537
		 * @param string $type Plugin type.
2538
		 * @return string
2539
		 */
2540
		protected function get_plugin_source_type_text( $type ) {
2541
			$string = '';
2542
2543
			switch ( $type ) {
2544
				case 'repo':
2545
					$string = __( 'WordPress Repository', 'tgmpa' );
2546
					break;
2547
				case 'external':
2548
					$string = __( 'External Source', 'tgmpa' );
2549
					break;
2550
				case 'bundled':
2551
					$string = __( 'Pre-Packaged', 'tgmpa' );
2552
					break;
2553
			}
2554
2555
			return $string;
2556
		}
2557
2558
		/**
2559
		 * Determine the plugin status message.
2560
		 *
2561
		 * @since 2.5.0
2562
		 *
2563
		 * @param string $slug Plugin slug.
2564
		 * @return string
2565
		 */
2566
		protected function get_plugin_status_text( $slug ) {
2567
			if ( ! $this->tgmpa->is_plugin_installed( $slug ) ) {
2568
				return __( 'Not Installed', 'tgmpa' );
2569
			}
2570
2571
			if ( ! $this->tgmpa->is_plugin_active( $slug ) ) {
2572
				$install_status = __( 'Installed But Not Activated', 'tgmpa' );
2573
			} else {
2574
				$install_status = __( 'Active', 'tgmpa' );
2575
			}
2576
2577
			$update_status = '';
2578
2579
			if ( $this->tgmpa->does_plugin_require_update( $slug ) && false === $this->tgmpa->does_plugin_have_update( $slug ) ) {
2580
				$update_status = __( 'Required Update not Available', 'tgmpa' );
2581
2582
			} elseif ( $this->tgmpa->does_plugin_require_update( $slug ) ) {
2583
				$update_status = __( 'Requires Update', 'tgmpa' );
2584
2585
			} elseif ( false !== $this->tgmpa->does_plugin_have_update( $slug ) ) {
2586
				$update_status = __( 'Update recommended', 'tgmpa' );
2587
			}
2588
2589
			if ( '' === $update_status ) {
2590
				return $install_status;
2591
			}
2592
2593
			return sprintf(
2594
				/* translators: 1: install status, 2: update status */
2595
				_x( '%1$s, %2$s', 'Install/Update Status', 'tgmpa' ),
2596
				$install_status,
2597
				$update_status
2598
			);
2599
		}
2600
2601
		/**
2602
		 * Sort plugins by Required/Recommended type and by alphabetical plugin name within each type.
2603
		 *
2604
		 * @since 2.5.0
2605
		 *
2606
		 * @param array $items Prepared table items.
2607
		 * @return array Sorted table items.
2608
		 */
2609
		public function sort_table_items( $items ) {
2610
			$type = array();
2611
			$name = array();
2612
2613
			foreach ( $items as $i => $plugin ) {
2614
				$type[ $i ] = $plugin['type']; // Required / recommended.
2615
				$name[ $i ] = $plugin['sanitized_plugin'];
2616
			}
2617
2618
			array_multisort( $type, SORT_DESC, $name, SORT_ASC, $items );
2619
2620
			return $items;
2621
		}
2622
2623
		/**
2624
		 * Get an associative array ( id => link ) of the views available on this table.
2625
		 *
2626
		 * @since 2.5.0
2627
		 *
2628
		 * @return array
2629
		 */
2630
		public function get_views() {
2631
			$status_links = array();
2632
2633
			foreach ( $this->view_totals as $type => $count ) {
2634
				if ( $count < 1 ) {
2635
					continue;
2636
				}
2637
2638
				switch ( $type ) {
2639
					case 'all':
2640
						/* translators: 1: number of plugins. */
2641
						$text = _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $count, 'plugins', 'tgmpa' );
2642
						break;
2643
					case 'install':
2644
						/* translators: 1: number of plugins. */
2645
						$text = _n( 'To Install <span class="count">(%s)</span>', 'To Install <span class="count">(%s)</span>', $count, 'tgmpa' );
2646
						break;
2647
					case 'update':
2648
						/* translators: 1: number of plugins. */
2649
						$text = _n( 'Update Available <span class="count">(%s)</span>', 'Update Available <span class="count">(%s)</span>', $count, 'tgmpa' );
2650
						break;
2651
					case 'activate':
2652
						/* translators: 1: number of plugins. */
2653
						$text = _n( 'To Activate <span class="count">(%s)</span>', 'To Activate <span class="count">(%s)</span>', $count, 'tgmpa' );
2654
						break;
2655
					default:
2656
						$text = '';
2657
						break;
2658
				}
2659
2660
				if ( ! empty( $text ) ) {
2661
2662
					$status_links[ $type ] = sprintf(
2663
						'<a href="%s"%s>%s</a>',
2664
						esc_url( $this->tgmpa->get_tgmpa_status_url( $type ) ),
2665
						( $type === $this->view_context ) ? ' class="current"' : '',
2666
						sprintf( $text, number_format_i18n( $count ) )
2667
					);
2668
				}
2669
			}
2670
2671
			return $status_links;
2672
		}
2673
2674
		/**
2675
		 * Create default columns to display important plugin information
2676
		 * like type, action and status.
2677
		 *
2678
		 * @since 2.2.0
2679
		 *
2680
		 * @param array  $item        Array of item data.
2681
		 * @param string $column_name The name of the column.
2682
		 * @return string
2683
		 */
2684
		public function column_default( $item, $column_name ) {
2685
			return $item[ $column_name ];
2686
		}
2687
2688
		/**
2689
		 * Required for bulk installing.
2690
		 *
2691
		 * Adds a checkbox for each plugin.
2692
		 *
2693
		 * @since 2.2.0
2694
		 *
2695
		 * @param array $item Array of item data.
2696
		 * @return string The input checkbox with all necessary info.
2697
		 */
2698
		public function column_cb( $item ) {
2699
			return sprintf(
2700
				'<input type="checkbox" name="%1$s[]" value="%2$s" id="%3$s" />',
2701
				esc_attr( $this->_args['singular'] ),
2702
				esc_attr( $item['slug'] ),
2703
				esc_attr( $item['sanitized_plugin'] )
2704
			);
2705
		}
2706
2707
		/**
2708
		 * Create default title column along with the action links.
2709
		 *
2710
		 * @since 2.2.0
2711
		 *
2712
		 * @param array $item Array of item data.
2713
		 * @return string The plugin name and action links.
2714
		 */
2715
		public function column_plugin( $item ) {
2716
			return sprintf(
2717
				'%1$s %2$s',
2718
				$item['plugin'],
2719
				$this->row_actions( $this->get_row_actions( $item ), true )
2720
			);
2721
		}
2722
2723
		/**
2724
		 * Create version information column.
2725
		 *
2726
		 * @since 2.5.0
2727
		 *
2728
		 * @param array $item Array of item data.
2729
		 * @return string HTML-formatted version information.
2730
		 */
2731
		public function column_version( $item ) {
2732
			$output = array();
2733
2734
			if ( $this->tgmpa->is_plugin_installed( $item['slug'] ) ) {
2735
				$installed = ! empty( $item['installed_version'] ) ? $item['installed_version'] : _x( 'unknown', 'as in: "version nr unknown"', 'tgmpa' );
2736
2737
				$color = '';
2738
				if ( ! empty( $item['minimum_version'] ) && $this->tgmpa->does_plugin_require_update( $item['slug'] ) ) {
2739
					$color = ' color: #ff0000; font-weight: bold;';
2740
				}
2741
2742
				$output[] = sprintf(
2743
					'<p><span style="min-width: 32px; text-align: right; float: right;%1$s">%2$s</span>' . __( 'Installed version:', 'tgmpa' ) . '</p>',
2744
					$color,
2745
					$installed
2746
				);
2747
			}
2748
2749
			if ( ! empty( $item['minimum_version'] ) ) {
2750
				$output[] = sprintf(
2751
					'<p><span style="min-width: 32px; text-align: right; float: right;">%1$s</span>' . __( 'Minimum required version:', 'tgmpa' ) . '</p>',
2752
					$item['minimum_version']
2753
				);
2754
			}
2755
2756
			if ( ! empty( $item['available_version'] ) ) {
2757
				$color = '';
2758
				if ( ! empty( $item['minimum_version'] ) && version_compare( $item['available_version'], $item['minimum_version'], '>=' ) ) {
2759
					$color = ' color: #71C671; font-weight: bold;';
2760
				}
2761
2762
				$output[] = sprintf(
2763
					'<p><span style="min-width: 32px; text-align: right; float: right;%1$s">%2$s</span>' . __( 'Available version:', 'tgmpa' ) . '</p>',
2764
					$color,
2765
					$item['available_version']
2766
				);
2767
			}
2768
2769
			if ( empty( $output ) ) {
2770
				return '&nbsp;'; // Let's not break the table layout.
2771
			} else {
2772
				return implode( "\n", $output );
2773
			}
2774
		}
2775
2776
		/**
2777
		 * Sets default message within the plugins table if no plugins
2778
		 * are left for interaction.
2779
		 *
2780
		 * Hides the menu item to prevent the user from clicking and
2781
		 * getting a permissions error.
2782
		 *
2783
		 * @since 2.2.0
2784
		 */
2785
		public function no_items() {
2786
			echo esc_html__( 'No plugins to install, update or activate.', 'tgmpa' ) . ' <a href="' . esc_url( self_admin_url() ) . '"> ' . esc_html( $this->tgmpa->strings['dashboard'] ) . '</a>';
2787
			echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>';
2788
		}
2789
2790
		/**
2791
		 * Output all the column information within the table.
2792
		 *
2793
		 * @since 2.2.0
2794
		 *
2795
		 * @return array $columns The column names.
2796
		 */
2797
		public function get_columns() {
2798
			$columns = array(
2799
				'cb'     => '<input type="checkbox" />',
2800
				'plugin' => __( 'Plugin', 'tgmpa' ),
2801
				'source' => __( 'Source', 'tgmpa' ),
2802
				'type'   => __( 'Type', 'tgmpa' ),
2803
			);
2804
2805
			if ( 'all' === $this->view_context || 'update' === $this->view_context ) {
2806
				$columns['version'] = __( 'Version', 'tgmpa' );
2807
				$columns['status']  = __( 'Status', 'tgmpa' );
2808
			}
2809
2810
			return apply_filters( 'tgmpa_table_columns', $columns );
2811
		}
2812
2813
		/**
2814
		 * Get name of default primary column
2815
		 *
2816
		 * @since 2.5.0 / WP 4.3+ compatibility
2817
		 * @access protected
2818
		 *
2819
		 * @return string
2820
		 */
2821
		protected function get_default_primary_column_name() {
2822
			return 'plugin';
2823
		}
2824
2825
		/**
2826
		 * Get the name of the primary column.
2827
		 *
2828
		 * @since 2.5.0 / WP 4.3+ compatibility
2829
		 * @access protected
2830
		 *
2831
		 * @return string The name of the primary column.
2832
		 */
2833
		protected function get_primary_column_name() {
2834
			if ( method_exists( 'WP_List_Table', 'get_primary_column_name' ) ) {
2835
				return parent::get_primary_column_name();
2836
			} else {
2837
				return $this->get_default_primary_column_name();
2838
			}
2839
		}
2840
2841
		/**
2842
		 * Get the actions which are relevant for a specific plugin row.
2843
		 *
2844
		 * @since 2.5.0
2845
		 *
2846
		 * @param array $item Array of item data.
2847
		 * @return array Array with relevant action links.
2848
		 */
2849
		protected function get_row_actions( $item ) {
2850
			$actions      = array();
2851
			$action_links = array();
2852
2853
			// Display the 'Install' action link if the plugin is not yet available.
2854
			if ( ! $this->tgmpa->is_plugin_installed( $item['slug'] ) ) {
2855
				/* translators: %2$s: plugin name in screen reader markup */
2856
				$actions['install'] = __( 'Install %2$s', 'tgmpa' );
2857
			} else {
2858
				// Display the 'Update' action link if an update is available and WP complies with plugin minimum.
2859
				if ( false !== $this->tgmpa->does_plugin_have_update( $item['slug'] ) && $this->tgmpa->can_plugin_update( $item['slug'] ) ) {
2860
					/* translators: %2$s: plugin name in screen reader markup */
2861
					$actions['update'] = __( 'Update %2$s', 'tgmpa' );
2862
				}
2863
2864
				// Display the 'Activate' action link, but only if the plugin meets the minimum version.
2865
				if ( $this->tgmpa->can_plugin_activate( $item['slug'] ) ) {
2866
					/* translators: %2$s: plugin name in screen reader markup */
2867
					$actions['activate'] = __( 'Activate %2$s', 'tgmpa' );
2868
				}
2869
			}
2870
2871
			// Create the actual links.
2872
			foreach ( $actions as $action => $text ) {
2873
				$nonce_url = wp_nonce_url(
2874
					add_query_arg(
2875
						array(
2876
							'plugin'           => urlencode( $item['slug'] ),
2877
							'tgmpa-' . $action => $action . '-plugin',
2878
						),
2879
						$this->tgmpa->get_tgmpa_url()
2880
					),
2881
					'tgmpa-' . $action,
2882
					'tgmpa-nonce'
2883
				);
2884
2885
				$action_links[ $action ] = sprintf(
2886
					'<a href="%1$s">' . esc_html( $text ) . '</a>', // $text contains the second placeholder.
2887
					esc_url( $nonce_url ),
2888
					'<span class="screen-reader-text">' . esc_html( $item['sanitized_plugin'] ) . '</span>'
2889
				);
2890
			}
2891
2892
			$prefix = ( defined( 'WP_NETWORK_ADMIN' ) && WP_NETWORK_ADMIN ) ? 'network_admin_' : '';
2893
			return apply_filters( "tgmpa_{$prefix}plugin_action_links", array_filter( $action_links ), $item['slug'], $item, $this->view_context );
2894
		}
2895
2896
		/**
2897
		 * Generates content for a single row of the table.
2898
		 *
2899
		 * @since 2.5.0
2900
		 *
2901
		 * @param object $item The current item.
2902
		 */
2903
		public function single_row( $item ) {
2904
			echo '<tr class="' . esc_attr( 'tgmpa-type-' . strtolower( $item['type'] ) ) . '">';
2905
			$this->single_row_columns( $item );
2906
			echo '</tr>';
2907
2908
			/**
2909
			 * Fires after each specific row in the TGMPA Plugins list table.
2910
			 *
2911
			 * The dynamic portion of the hook name, `$item['slug']`, refers to the slug
2912
			 * for the plugin.
2913
			 *
2914
			 * @since 2.5.0
2915
			 */
2916
			do_action( "tgmpa_after_plugin_row_{$item['slug']}", $item['slug'], $item, $this->view_context );
2917
		}
2918
2919
		/**
2920
		 * Show the upgrade notice below a plugin row if there is one.
2921
		 *
2922
		 * @since 2.5.0
2923
		 *
2924
		 * @see /wp-admin/includes/update.php
2925
		 *
2926
		 * @param string $slug Plugin slug.
2927
		 * @param array  $item The information available in this table row.
2928
		 * @return null Return early if upgrade notice is empty.
2929
		 */
2930
		public function wp_plugin_update_row( $slug, $item ) {
2931
			if ( empty( $item['upgrade_notice'] ) ) {
2932
				return;
2933
			}
2934
2935
			echo '
2936
				<tr class="plugin-update-tr">
2937
					<td colspan="', absint( $this->get_column_count() ), '" class="plugin-update colspanchange">
2938
						<div class="update-message">',
2939
							esc_html__( 'Upgrade message from the plugin author:', 'tgmpa' ),
2940
							' <strong>', wp_kses_data( $item['upgrade_notice'] ), '</strong>
2941
						</div>
2942
					</td>
2943
				</tr>';
2944
		}
2945
2946
		/**
2947
		 * Extra controls to be displayed between bulk actions and pagination.
2948
		 *
2949
		 * @since 2.5.0
2950
		 *
2951
		 * @param string $which 'top' or 'bottom' table navigation.
2952
		 */
2953
		public function extra_tablenav( $which ) {
2954
			if ( 'bottom' === $which ) {
2955
				$this->tgmpa->show_tgmpa_version();
2956
			}
2957
		}
2958
2959
		/**
2960
		 * Defines the bulk actions for handling registered plugins.
2961
		 *
2962
		 * @since 2.2.0
2963
		 *
2964
		 * @return array $actions The bulk actions for the plugin install table.
2965
		 */
2966
		public function get_bulk_actions() {
2967
2968
			$actions = array();
2969
2970
			if ( 'update' !== $this->view_context && 'activate' !== $this->view_context ) {
2971
				if ( current_user_can( 'install_plugins' ) ) {
2972
					$actions['tgmpa-bulk-install'] = __( 'Install', 'tgmpa' );
2973
				}
2974
			}
2975
2976
			if ( 'install' !== $this->view_context ) {
2977
				if ( current_user_can( 'update_plugins' ) ) {
2978
					$actions['tgmpa-bulk-update'] = __( 'Update', 'tgmpa' );
2979
				}
2980
				if ( current_user_can( 'activate_plugins' ) ) {
2981
					$actions['tgmpa-bulk-activate'] = __( 'Activate', 'tgmpa' );
2982
				}
2983
			}
2984
2985
			return $actions;
2986
		}
2987
2988
		/**
2989
		 * Processes bulk installation and activation actions.
2990
		 *
2991
		 * The bulk installation process looks for the $_POST information and passes that
2992
		 * through if a user has to use WP_Filesystem to enter their credentials.
2993
		 *
2994
		 * @since 2.2.0
2995
		 */
2996
		public function process_bulk_actions() {
0 ignored issues
show
Coding Style introduced by
function process_bulk_actions() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
2997
			// Bulk installation process.
2998
			if ( 'tgmpa-bulk-install' === $this->current_action() || 'tgmpa-bulk-update' === $this->current_action() ) {
2999
3000
				check_admin_referer( 'bulk-' . $this->_args['plural'] );
3001
3002
				$install_type = 'install';
3003
				if ( 'tgmpa-bulk-update' === $this->current_action() ) {
3004
					$install_type = 'update';
3005
				}
3006
3007
				$plugins_to_install = array();
3008
3009
				// Did user actually select any plugins to install/update ?
3010 View Code Duplication
				if ( empty( $_POST['plugin'] ) ) {
3011
					if ( 'install' === $install_type ) {
3012
						$message = __( 'No plugins were selected to be installed. No action taken.', 'tgmpa' );
3013
					} else {
3014
						$message = __( 'No plugins were selected to be updated. No action taken.', 'tgmpa' );
3015
					}
3016
3017
					echo '<div id="message" class="error"><p>', esc_html( $message ), '</p></div>';
3018
3019
					return false;
3020
				}
3021
3022
				if ( is_array( $_POST['plugin'] ) ) {
3023
					$plugins_to_install = (array) $_POST['plugin'];
3024
				} elseif ( is_string( $_POST['plugin'] ) ) {
3025
					// Received via Filesystem page - un-flatten array (WP bug #19643).
3026
					$plugins_to_install = explode( ',', $_POST['plugin'] );
3027
				}
3028
3029
				// Sanitize the received input.
3030
				$plugins_to_install = array_map( 'urldecode', $plugins_to_install );
3031
				$plugins_to_install = array_map( array( $this->tgmpa, 'sanitize_key' ), $plugins_to_install );
3032
3033
				// Validate the received input.
3034
				foreach ( $plugins_to_install as $key => $slug ) {
3035
					// Check if the plugin was registered with TGMPA and remove if not.
3036
					if ( ! isset( $this->tgmpa->plugins[ $slug ] ) ) {
3037
						unset( $plugins_to_install[ $key ] );
3038
						continue;
3039
					}
3040
3041
					// For install: make sure this is a plugin we *can* install and not one already installed.
3042
					if ( 'install' === $install_type && true === $this->tgmpa->is_plugin_installed( $slug ) ) {
3043
						unset( $plugins_to_install[ $key ] );
3044
					}
3045
3046
					// For updates: make sure this is a plugin we *can* update (update available and WP version ok).
3047
					if ( 'update' === $install_type && false === $this->tgmpa->is_plugin_updatetable( $slug ) ) {
3048
						unset( $plugins_to_install[ $key ] );
3049
					}
3050
				}
3051
3052
				// No need to proceed further if we have no plugins to handle.
3053 View Code Duplication
				if ( empty( $plugins_to_install ) ) {
3054
					if ( 'install' === $install_type ) {
3055
						$message = __( 'No plugins are available to be installed at this time.', 'tgmpa' );
3056
					} else {
3057
						$message = __( 'No plugins are available to be updated at this time.', 'tgmpa' );
3058
					}
3059
3060
					echo '<div id="message" class="error"><p>', esc_html( $message ), '</p></div>';
3061
3062
					return false;
3063
				}
3064
3065
				// Pass all necessary information if WP_Filesystem is needed.
3066
				$url = wp_nonce_url(
3067
					$this->tgmpa->get_tgmpa_url(),
3068
					'bulk-' . $this->_args['plural']
3069
				);
3070
3071
				// Give validated data back to $_POST which is the only place the filesystem looks for extra fields.
3072
				$_POST['plugin'] = implode( ',', $plugins_to_install ); // Work around for WP bug #19643.
3073
3074
				$method = ''; // Leave blank so WP_Filesystem can populate it as necessary.
3075
				$fields = array_keys( $_POST ); // Extra fields to pass to WP_Filesystem.
3076
3077
				$creds = request_filesystem_credentials( esc_url_raw( $url ), $method, false, false, $fields );
3078
				if ( false === $creds ) {
3079
					return true; // Stop the normal page form from displaying, credential request form will be shown.
3080
				}
3081
3082
				// Now we have some credentials, setup WP_Filesystem.
3083
				if ( ! WP_Filesystem( $creds ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
3084
					// Our credentials were no good, ask the user for them again.
3085
					request_filesystem_credentials( esc_url_raw( $url ), $method, true, false, $fields );
3086
3087
					return true;
3088
				}
3089
3090
				/* If we arrive here, we have the filesystem */
3091
3092
				// Store all information in arrays since we are processing a bulk installation.
3093
				$names      = array();
3094
				$sources    = array(); // Needed for installs.
3095
				$file_paths = array(); // Needed for upgrades.
3096
				$to_inject  = array(); // Information to inject into the update_plugins transient.
3097
3098
				// Prepare the data for validated plugins for the install/upgrade.
3099
				foreach ( $plugins_to_install as $slug ) {
3100
					$name   = $this->tgmpa->plugins[ $slug ]['name'];
3101
					$source = $this->tgmpa->get_download_url( $slug );
3102
3103
					if ( ! empty( $name ) && ! empty( $source ) ) {
3104
						$names[] = $name;
3105
3106
						switch ( $install_type ) {
3107
3108
							case 'install':
3109
								$sources[] = $source;
3110
								break;
3111
3112
							case 'update':
3113
								$file_paths[]                 = $this->tgmpa->plugins[ $slug ]['file_path'];
3114
								$to_inject[ $slug ]           = $this->tgmpa->plugins[ $slug ];
3115
								$to_inject[ $slug ]['source'] = $source;
3116
								break;
3117
						}
3118
					}
3119
				}
3120
				unset( $slug, $name, $source );
3121
3122
				// Create a new instance of TGMPA_Bulk_Installer.
3123
				$installer = new TGMPA_Bulk_Installer(
3124
					new TGMPA_Bulk_Installer_Skin(
3125
						array(
3126
							'url'          => esc_url_raw( $this->tgmpa->get_tgmpa_url() ),
3127
							'nonce'        => 'bulk-' . $this->_args['plural'],
3128
							'names'        => $names,
3129
							'install_type' => $install_type,
3130
						)
3131
					)
3132
				);
3133
3134
				// Wrap the install process with the appropriate HTML.
3135
				echo '<div class="tgmpa">',
3136
					'<h2 style="font-size: 23px; font-weight: 400; line-height: 29px; margin: 0; padding: 9px 15px 4px 0;">', esc_html( get_admin_page_title() ), '</h2>
3137
					<div class="update-php" style="width: 100%; height: 98%; min-height: 850px; padding-top: 1px;">';
3138
3139
				// Process the bulk installation submissions.
3140
				add_filter( 'upgrader_source_selection', array( $this->tgmpa, 'maybe_adjust_source_dir' ), 1, 3 );
3141
3142
				if ( 'tgmpa-bulk-update' === $this->current_action() ) {
3143
					// Inject our info into the update transient.
3144
					$this->tgmpa->inject_update_info( $to_inject );
3145
3146
					$installer->bulk_upgrade( $file_paths );
3147
				} else {
3148
					$installer->bulk_install( $sources );
3149
				}
3150
3151
				remove_filter( 'upgrader_source_selection', array( $this->tgmpa, 'maybe_adjust_source_dir' ), 1 );
3152
3153
				echo '</div></div>';
3154
3155
				return true;
3156
			}
3157
3158
			// Bulk activation process.
3159
			if ( 'tgmpa-bulk-activate' === $this->current_action() ) {
3160
				check_admin_referer( 'bulk-' . $this->_args['plural'] );
3161
3162
				// Did user actually select any plugins to activate ?
3163
				if ( empty( $_POST['plugin'] ) ) {
3164
					echo '<div id="message" class="error"><p>', esc_html__( 'No plugins were selected to be activated. No action taken.', 'tgmpa' ), '</p></div>';
3165
3166
					return false;
3167
				}
3168
3169
				// Grab plugin data from $_POST.
3170
				$plugins = array();
3171
				if ( isset( $_POST['plugin'] ) ) {
3172
					$plugins = array_map( 'urldecode', (array) $_POST['plugin'] );
3173
					$plugins = array_map( array( $this->tgmpa, 'sanitize_key' ), $plugins );
3174
				}
3175
3176
				$plugins_to_activate = array();
3177
				$plugin_names        = array();
3178
3179
				// Grab the file paths for the selected & inactive plugins from the registration array.
3180
				foreach ( $plugins as $slug ) {
3181
					if ( $this->tgmpa->can_plugin_activate( $slug ) ) {
3182
						$plugins_to_activate[] = $this->tgmpa->plugins[ $slug ]['file_path'];
3183
						$plugin_names[]        = $this->tgmpa->plugins[ $slug ]['name'];
3184
					}
3185
				}
3186
				unset( $slug );
3187
3188
				// Return early if there are no plugins to activate.
3189
				if ( empty( $plugins_to_activate ) ) {
3190
					echo '<div id="message" class="error"><p>', esc_html__( 'No plugins are available to be activated at this time.', 'tgmpa' ), '</p></div>';
3191
3192
					return false;
3193
				}
3194
3195
				// Now we are good to go - let's start activating plugins.
3196
				$activate = activate_plugins( $plugins_to_activate );
3197
3198
				if ( is_wp_error( $activate ) ) {
3199
					echo '<div id="message" class="error"><p>', wp_kses_post( $activate->get_error_message() ), '</p></div>';
3200
				} else {
3201
					$count        = count( $plugin_names ); // Count so we can use _n function.
3202
					$plugin_names = array_map( array( 'TGMPA_Utils', 'wrap_in_strong' ), $plugin_names );
3203
					$last_plugin  = array_pop( $plugin_names ); // Pop off last name to prep for readability.
3204
					$imploded     = empty( $plugin_names ) ? $last_plugin : ( implode( ', ', $plugin_names ) . ' ' . esc_html_x( 'and', 'plugin A *and* plugin B', 'tgmpa' ) . ' ' . $last_plugin );
3205
3206
					printf( // WPCS: xss ok.
3207
						'<div id="message" class="updated"><p>%1$s %2$s.</p></div>',
3208
						esc_html( _n( 'The following plugin was activated successfully:', 'The following plugins were activated successfully:', $count, 'tgmpa' ) ),
3209
						$imploded
3210
					);
3211
3212
					// Update recently activated plugins option.
3213
					$recent = (array) get_option( 'recently_activated' );
3214
					foreach ( $plugins_to_activate as $plugin => $time ) {
3215
						if ( isset( $recent[ $plugin ] ) ) {
3216
							unset( $recent[ $plugin ] );
3217
						}
3218
					}
3219
					update_option( 'recently_activated', $recent );
3220
				}
3221
3222
				unset( $_POST ); // Reset the $_POST variable in case user wants to perform one action after another.
3223
3224
				return true;
3225
			}
3226
3227
			return false;
3228
		}
3229
3230
		/**
3231
		 * Prepares all of our information to be outputted into a usable table.
3232
		 *
3233
		 * @since 2.2.0
3234
		 */
3235
		public function prepare_items() {
3236
			$columns               = $this->get_columns(); // Get all necessary column information.
3237
			$hidden                = array(); // No columns to hide, but we must set as an array.
3238
			$sortable              = array(); // No reason to make sortable columns.
3239
			$primary               = $this->get_primary_column_name(); // Column which has the row actions.
3240
			$this->_column_headers = array( $columns, $hidden, $sortable, $primary ); // Get all necessary column headers.
3241
3242
			// Process our bulk activations here.
3243
			if ( 'tgmpa-bulk-activate' === $this->current_action() ) {
3244
				$this->process_bulk_actions();
3245
			}
3246
3247
			// Store all of our plugin data into $items array so WP_List_Table can use it.
3248
			$this->items = apply_filters( 'tgmpa_table_data_items', $this->_gather_plugin_data() );
3249
		}
3250
3251
		/* *********** DEPRECATED METHODS *********** */
3252
3253
		/**
3254
		 * Retrieve plugin data, given the plugin name.
3255
		 *
3256
		 * @since      2.2.0
3257
		 * @deprecated 2.5.0 use {@see TGM_Plugin_Activation::_get_plugin_data_from_name()} instead.
3258
		 * @see        TGM_Plugin_Activation::_get_plugin_data_from_name()
3259
		 *
3260
		 * @param string $name Name of the plugin, as it was registered.
3261
		 * @param string $data Optional. Array key of plugin data to return. Default is slug.
3262
		 * @return string|boolean Plugin slug if found, false otherwise.
3263
		 */
3264
		protected function _get_plugin_data_from_name( $name, $data = 'slug' ) {
0 ignored issues
show
Coding Style introduced by
function _get_plugin_data_from_name() does not seem to conform to the naming convention (^(?:[a-z]|__)[a-z_0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
3265
			_deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'TGM_Plugin_Activation::_get_plugin_data_from_name()' );
3266
3267
			return $this->tgmpa->_get_plugin_data_from_name( $name, $data );
3268
		}
3269
	}
3270
}
3271
3272
3273
if ( ! class_exists( 'TGM_Bulk_Installer' ) ) {
3274
3275
	/**
3276
	 * Hack: Prevent TGMPA v2.4.1- bulk installer class from being loaded if 2.4.1- is loaded after 2.5+.
3277
	 *
3278
	 * @since 2.5.2
3279
	 *
3280
	 * {@internal The TGMPA_Bulk_Installer class was originally called TGM_Bulk_Installer.
3281
	 *            For more information, see that class.}}
3282
	 */
3283
	class TGM_Bulk_Installer {
3284
	}
3285
}
3286
if ( ! class_exists( 'TGM_Bulk_Installer_Skin' ) ) {
3287
3288
	/**
3289
	 * Hack: Prevent TGMPA v2.4.1- bulk installer skin class from being loaded if 2.4.1- is loaded after 2.5+.
3290
	 *
3291
	 * @since 2.5.2
3292
	 *
3293
	 * {@internal The TGMPA_Bulk_Installer_Skin class was originally called TGM_Bulk_Installer_Skin.
3294
	 *            For more information, see that class.}}
3295
	 */
3296
	class TGM_Bulk_Installer_Skin {
3297
	}
3298
}
3299
3300
/**
3301
 * The WP_Upgrader file isn't always available. If it isn't available,
3302
 * we load it here.
3303
 *
3304
 * We check to make sure no action or activation keys are set so that WordPress
3305
 * does not try to re-include the class when processing upgrades or installs outside
3306
 * of the class.
3307
 *
3308
 * @since 2.2.0
3309
 */
3310
add_action( 'admin_init', 'tgmpa_load_bulk_installer' );
3311
if ( ! function_exists( 'tgmpa_load_bulk_installer' ) ) {
3312
	/**
3313
	 * Load bulk installer
3314
	 */
3315
	function tgmpa_load_bulk_installer() {
3316
		// Silently fail if 2.5+ is loaded *after* an older version.
3317
		if ( ! isset( $GLOBALS['tgmpa'] ) ) {
3318
			return;
3319
		}
3320
3321
		// Get TGMPA class instance.
3322
		$tgmpa_instance = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
3323
3324
		if ( isset( $_GET['page'] ) && $tgmpa_instance->menu === $_GET['page'] ) {
3325
			if ( ! class_exists( 'Plugin_Upgrader', false ) ) {
3326
				require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
3327
			}
3328
3329
			if ( ! class_exists( 'TGMPA_Bulk_Installer' ) ) {
3330
3331
				/**
3332
				 * Installer class to handle bulk plugin installations.
3333
				 *
3334
				 * Extends WP_Upgrader and customizes to suit the installation of multiple
3335
				 * plugins.
3336
				 *
3337
				 * @since 2.2.0
3338
				 *
3339
				 * {@internal Since 2.5.0 the class is an extension of Plugin_Upgrader rather than WP_Upgrader.}}
3340
				 * {@internal Since 2.5.2 the class has been renamed from TGM_Bulk_Installer to TGMPA_Bulk_Installer.
3341
				 *            This was done to prevent backward compatibility issues with v2.3.6.}}
3342
				 *
3343
				 * @package TGM-Plugin-Activation
3344
				 * @author  Thomas Griffin
3345
				 * @author  Gary Jones
3346
				 */
3347
				class TGMPA_Bulk_Installer extends Plugin_Upgrader {
3348
					/**
3349
					 * Holds result of bulk plugin installation.
3350
					 *
3351
					 * @since 2.2.0
3352
					 *
3353
					 * @var string
3354
					 */
3355
					public $result;
3356
3357
					/**
3358
					 * Flag to check if bulk installation is occurring or not.
3359
					 *
3360
					 * @since 2.2.0
3361
					 *
3362
					 * @var boolean
3363
					 */
3364
					public $bulk = false;
3365
3366
					/**
3367
					 * TGMPA instance
3368
					 *
3369
					 * @since 2.5.0
3370
					 *
3371
					 * @var object
3372
					 */
3373
					protected $tgmpa;
3374
3375
					/**
3376
					 * Whether or not the destination directory needs to be cleared ( = on update).
3377
					 *
3378
					 * @since 2.5.0
3379
					 *
3380
					 * @var bool
3381
					 */
3382
					protected $clear_destination = false;
3383
3384
					/**
3385
					 * References parent constructor and sets defaults for class.
3386
					 *
3387
					 * @since 2.2.0
3388
					 *
3389
					 * @param \Bulk_Upgrader_Skin|null $skin Installer skin.
3390
					 */
3391
					public function __construct( $skin = null ) {
3392
						// Get TGMPA class instance.
3393
						$this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
3394
3395
						parent::__construct( $skin );
3396
3397
						if ( isset( $this->skin->options['install_type'] ) && 'update' === $this->skin->options['install_type'] ) {
3398
							$this->clear_destination = true;
3399
						}
3400
3401
						if ( $this->tgmpa->is_automatic ) {
3402
							$this->activate_strings();
3403
						}
3404
3405
						add_action( 'upgrader_process_complete', array( $this->tgmpa, 'populate_file_path' ) );
3406
					}
3407
3408
					/**
3409
					 * Sets the correct activation strings for the installer skin to use.
3410
					 *
3411
					 * @since 2.2.0
3412
					 */
3413
					public function activate_strings() {
3414
						$this->strings['activation_failed']  = __( 'Plugin activation failed.', 'tgmpa' );
3415
						$this->strings['activation_success'] = __( 'Plugin activated successfully.', 'tgmpa' );
3416
					}
3417
3418
					/**
3419
					 * Performs the actual installation of each plugin.
3420
					 *
3421
					 * @since 2.2.0
3422
					 *
3423
					 * @see WP_Upgrader::run()
3424
					 *
3425
					 * @param array $options The installation config options.
3426
					 * @return null|array Return early if error, array of installation data on success.
3427
					 */
3428
					public function run( $options ) {
3429
						$result = parent::run( $options );
3430
3431
						// Reset the strings in case we changed one during automatic activation.
3432
						if ( $this->tgmpa->is_automatic ) {
3433
							if ( 'update' === $this->skin->options['install_type'] ) {
3434
								$this->upgrade_strings();
3435
							} else {
3436
								$this->install_strings();
3437
							}
3438
						}
3439
3440
						return $result;
3441
					}
3442
3443
					/**
3444
					 * Processes the bulk installation of plugins.
3445
					 *
3446
					 * @since 2.2.0
3447
					 *
3448
					 * {@internal This is basically a near identical copy of the WP Core
3449
					 * Plugin_Upgrader::bulk_upgrade() method, with minor adjustments to deal with
3450
					 * new installs instead of upgrades.
3451
					 * For ease of future synchronizations, the adjustments are clearly commented, but no other
3452
					 * comments are added. Code style has been made to comply.}}
3453
					 *
3454
					 * @see Plugin_Upgrader::bulk_upgrade()
3455
					 * @see https://core.trac.wordpress.org/browser/tags/4.2.1/src/wp-admin/includes/class-wp-upgrader.php#L838
3456
					 * (@internal Last synced: Dec 31st 2015 against https://core.trac.wordpress.org/browser/trunk?rev=36134}}
3457
					 *
3458
					 * @param array $plugins The plugin sources needed for installation.
3459
					 * @param array $args    Arbitrary passed extra arguments.
3460
					 * @return array|false   Install confirmation messages on success, false on failure.
3461
					 */
3462
					public function bulk_install( $plugins, $args = array() ) {
3463
						// [TGMPA + ] Hook auto-activation in.
3464
						add_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3465
3466
						$defaults    = array(
3467
							'clear_update_cache' => true,
3468
						);
3469
						$parsed_args = wp_parse_args( $args, $defaults );
3470
3471
						$this->init();
3472
						$this->bulk = true;
3473
3474
						$this->install_strings(); // [TGMPA + ] adjusted.
3475
3476
						/* [TGMPA - ] $current = get_site_transient( 'update_plugins' ); */
3477
3478
						/* [TGMPA - ] add_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'), 10, 4); */
3479
3480
						$this->skin->header();
3481
3482
						// Connect to the Filesystem first.
3483
						$res = $this->fs_connect( array( WP_CONTENT_DIR, WP_PLUGIN_DIR ) );
3484
						if ( ! $res ) {
3485
							$this->skin->footer();
3486
							return false;
3487
						}
3488
3489
						$this->skin->bulk_header();
3490
3491
						/*
3492
						 * Only start maintenance mode if:
3493
						 * - running Multisite and there are one or more plugins specified, OR
3494
						 * - a plugin with an update available is currently active.
3495
						 * @TODO: For multisite, maintenance mode should only kick in for individual sites if at all possible.
3496
						 */
3497
						$maintenance = ( is_multisite() && ! empty( $plugins ) );
3498
3499
						/*
3500
						[TGMPA - ]
3501
						foreach ( $plugins as $plugin )
3502
							$maintenance = $maintenance || ( is_plugin_active( $plugin ) && isset( $current->response[ $plugin] ) );
3503
						*/
3504
						if ( $maintenance ) {
3505
							$this->maintenance_mode( true );
3506
						}
3507
3508
						$results = array();
3509
3510
						$this->update_count   = count( $plugins );
3511
						$this->update_current = 0;
3512
						foreach ( $plugins as $plugin ) {
3513
							$this->update_current++;
3514
3515
							/*
3516
							[TGMPA - ]
3517
							$this->skin->plugin_info = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin, false, true);
3518
3519
							if ( !isset( $current->response[ $plugin ] ) ) {
3520
								$this->skin->set_result('up_to_date');
3521
								$this->skin->before();
3522
								$this->skin->feedback('up_to_date');
3523
								$this->skin->after();
3524
								$results[$plugin] = true;
3525
								continue;
3526
							}
3527
3528
							// Get the URL to the zip file.
3529
							$r = $current->response[ $plugin ];
3530
3531
							$this->skin->plugin_active = is_plugin_active($plugin);
3532
							*/
3533
3534
							$result = $this->run(
3535
								array(
3536
									'package'           => $plugin, // [TGMPA + ] adjusted.
3537
									'destination'       => WP_PLUGIN_DIR,
3538
									'clear_destination' => false, // [TGMPA + ] adjusted.
3539
									'clear_working'     => true,
3540
									'is_multi'          => true,
3541
									'hook_extra'        => array(
3542
										'plugin' => $plugin,
3543
									),
3544
								)
3545
							);
3546
3547
							$results[ $plugin ] = $this->result;
3548
3549
							// Prevent credentials auth screen from displaying multiple times.
3550
							if ( false === $result ) {
3551
								break;
3552
							}
3553
						}
3554
3555
						$this->maintenance_mode( false );
3556
3557
						/**
3558
						 * Fires when the bulk upgrader process is complete.
3559
						 *
3560
						 * @since WP 3.6.0 / TGMPA 2.5.0
3561
						 *
3562
						 * @param Plugin_Upgrader $this Plugin_Upgrader instance. In other contexts, $this, might
3563
						 *                              be a Theme_Upgrader or Core_Upgrade instance.
3564
						 * @param array           $data {
3565
						 *     Array of bulk item update data.
3566
						 *
3567
						 *     @type string $action   Type of action. Default 'update'.
3568
						 *     @type string $type     Type of update process. Accepts 'plugin', 'theme', or 'core'.
3569
						 *     @type bool   $bulk     Whether the update process is a bulk update. Default true.
3570
						 *     @type array  $packages Array of plugin, theme, or core packages to update.
3571
						 * }
3572
						 */
3573
						do_action( // WPCS: prefix OK.
3574
							'upgrader_process_complete',
3575
							$this,
3576
							array(
3577
								'action'  => 'install', // [TGMPA + ] adjusted.
3578
								'type'    => 'plugin',
3579
								'bulk'    => true,
3580
								'plugins' => $plugins,
3581
							)
3582
						);
3583
3584
						$this->skin->bulk_footer();
3585
3586
						$this->skin->footer();
3587
3588
						// Cleanup our hooks, in case something else does a upgrade on this connection.
3589
						/* [TGMPA - ] remove_filter('upgrader_clear_destination', array($this, 'delete_old_plugin')); */
3590
3591
						// [TGMPA + ] Remove our auto-activation hook.
3592
						remove_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3593
3594
						// Force refresh of plugin update information.
3595
						wp_clean_plugins_cache( $parsed_args['clear_update_cache'] );
3596
3597
						return $results;
3598
					}
3599
3600
					/**
3601
					 * Handle a bulk upgrade request.
3602
					 *
3603
					 * @since 2.5.0
3604
					 *
3605
					 * @see Plugin_Upgrader::bulk_upgrade()
3606
					 *
3607
					 * @param array $plugins The local WP file_path's of the plugins which should be upgraded.
3608
					 * @param array $args    Arbitrary passed extra arguments.
3609
					 * @return string|bool Install confirmation messages on success, false on failure.
3610
					 */
3611
					public function bulk_upgrade( $plugins, $args = array() ) {
3612
3613
						add_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3614
3615
						$result = parent::bulk_upgrade( $plugins, $args );
3616
3617
						remove_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3618
3619
						return $result;
3620
					}
3621
3622
					/**
3623
					 * Abuse a filter to auto-activate plugins after installation.
3624
					 *
3625
					 * Hooked into the 'upgrader_post_install' filter hook.
3626
					 *
3627
					 * @since 2.5.0
3628
					 *
3629
					 * @param bool $bool The value we need to give back (true).
3630
					 * @return bool
3631
					 */
3632
					public function auto_activate( $bool ) {
0 ignored issues
show
Coding Style introduced by
function auto_activate() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
3633
						// Only process the activation of installed plugins if the automatic flag is set to true.
3634
						if ( $this->tgmpa->is_automatic ) {
3635
							// Flush plugins cache so the headers of the newly installed plugins will be read correctly.
3636
							wp_clean_plugins_cache();
3637
3638
							// Get the installed plugin file.
3639
							$plugin_info = $this->plugin_info();
3640
3641
							// Don't try to activate on upgrade of active plugin as WP will do this already.
3642
							if ( ! is_plugin_active( $plugin_info ) ) {
3643
								$activate = activate_plugin( $plugin_info );
3644
3645
								// Adjust the success string based on the activation result.
3646
								$this->strings['process_success'] = $this->strings['process_success'] . "<br />\n";
3647
3648
								if ( is_wp_error( $activate ) ) {
3649
									$this->skin->error( $activate );
3650
									$this->strings['process_success'] .= $this->strings['activation_failed'];
3651
								} else {
3652
									$this->strings['process_success'] .= $this->strings['activation_success'];
3653
								}
3654
							}
3655
						}
3656
3657
						return $bool;
3658
					}
3659
				}
3660
			}
3661
3662
			if ( ! class_exists( 'TGMPA_Bulk_Installer_Skin' ) ) {
3663
3664
				/**
3665
				 * Installer skin to set strings for the bulk plugin installations..
3666
				 *
3667
				 * Extends Bulk_Upgrader_Skin and customizes to suit the installation of multiple
3668
				 * plugins.
3669
				 *
3670
				 * @since 2.2.0
3671
				 *
3672
				 * {@internal Since 2.5.2 the class has been renamed from TGM_Bulk_Installer_Skin to
3673
				 *            TGMPA_Bulk_Installer_Skin.
3674
				 *            This was done to prevent backward compatibility issues with v2.3.6.}}
3675
				 *
3676
				 * @see https://core.trac.wordpress.org/browser/trunk/src/wp-admin/includes/class-wp-upgrader-skins.php
3677
				 *
3678
				 * @package TGM-Plugin-Activation
3679
				 * @author  Thomas Griffin
3680
				 * @author  Gary Jones
3681
				 */
3682
				class TGMPA_Bulk_Installer_Skin extends Bulk_Upgrader_Skin {
3683
					/**
3684
					 * Holds plugin info for each individual plugin installation.
3685
					 *
3686
					 * @since 2.2.0
3687
					 *
3688
					 * @var array
3689
					 */
3690
					public $plugin_info = array();
3691
3692
					/**
3693
					 * Holds names of plugins that are undergoing bulk installations.
3694
					 *
3695
					 * @since 2.2.0
3696
					 *
3697
					 * @var array
3698
					 */
3699
					public $plugin_names = array();
3700
3701
					/**
3702
					 * Integer to use for iteration through each plugin installation.
3703
					 *
3704
					 * @since 2.2.0
3705
					 *
3706
					 * @var integer
3707
					 */
3708
					public $i = 0;
3709
3710
					/**
3711
					 * TGMPA instance
3712
					 *
3713
					 * @since 2.5.0
3714
					 *
3715
					 * @var object
3716
					 */
3717
					protected $tgmpa;
3718
3719
					/**
3720
					 * Constructor. Parses default args with new ones and extracts them for use.
3721
					 *
3722
					 * @since 2.2.0
3723
					 *
3724
					 * @param array $args Arguments to pass for use within the class.
3725
					 */
3726
					public function __construct( $args = array() ) {
3727
						// Get TGMPA class instance.
3728
						$this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
3729
3730
						// Parse default and new args.
3731
						$defaults = array(
3732
							'url'          => '',
3733
							'nonce'        => '',
3734
							'names'        => array(),
3735
							'install_type' => 'install',
3736
						);
3737
						$args     = wp_parse_args( $args, $defaults );
3738
3739
						// Set plugin names to $this->plugin_names property.
3740
						$this->plugin_names = $args['names'];
3741
3742
						// Extract the new args.
3743
						parent::__construct( $args );
3744
					}
3745
3746
					/**
3747
					 * Sets install skin strings for each individual plugin.
3748
					 *
3749
					 * Checks to see if the automatic activation flag is set and uses the
3750
					 * the proper strings accordingly.
3751
					 *
3752
					 * @since 2.2.0
3753
					 */
3754
					public function add_strings() {
3755
						if ( 'update' === $this->options['install_type'] ) {
3756
							parent::add_strings();
3757
							/* translators: 1: plugin name, 2: action number 3: total number of actions. */
3758
							$this->upgrader->strings['skin_before_update_header'] = __( 'Updating Plugin %1$s (%2$d/%3$d)', 'tgmpa' );
3759
						} else {
3760
							/* translators: 1: plugin name, 2: error message. */
3761
							$this->upgrader->strings['skin_update_failed_error'] = __( 'An error occurred while installing %1$s: <strong>%2$s</strong>.', 'tgmpa' );
3762
							/* translators: 1: plugin name. */
3763
							$this->upgrader->strings['skin_update_failed'] = __( 'The installation of %1$s failed.', 'tgmpa' );
3764
3765
							if ( $this->tgmpa->is_automatic ) {
3766
								// Automatic activation strings.
3767
								$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' );
3768
								/* translators: 1: plugin name. */
3769
								$this->upgrader->strings['skin_update_successful'] = __( '%1$s installed and activated successfully.', 'tgmpa' );
3770
								$this->upgrader->strings['skin_upgrade_end']       = __( 'All installations and activations have been completed.', 'tgmpa' );
3771
								/* translators: 1: plugin name, 2: action number 3: total number of actions. */
3772
								$this->upgrader->strings['skin_before_update_header'] = __( 'Installing and Activating Plugin %1$s (%2$d/%3$d)', 'tgmpa' );
3773
							} else {
3774
								// Default installation strings.
3775
								$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' );
3776
								/* translators: 1: plugin name. */
3777
								$this->upgrader->strings['skin_update_successful'] = __( '%1$s installed successfully.', 'tgmpa' );
3778
								$this->upgrader->strings['skin_upgrade_end']       = __( 'All installations have been completed.', 'tgmpa' );
3779
								/* translators: 1: plugin name, 2: action number 3: total number of actions. */
3780
								$this->upgrader->strings['skin_before_update_header'] = __( 'Installing Plugin %1$s (%2$d/%3$d)', 'tgmpa' );
3781
							}
3782
3783
							// Add "read more" link only for WP < 4.8.
3784
							if ( version_compare( $this->tgmpa->wp_version, '4.8', '<' ) ) {
3785
								$this->upgrader->strings['skin_update_successful'] .= ' <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>';
3786
							}
3787
						}
3788
					}
3789
3790
					/**
3791
					 * Outputs the header strings and necessary JS before each plugin installation.
3792
					 *
3793
					 * @since 2.2.0
3794
					 *
3795
					 * @param string $title Unused in this implementation.
3796
					 */
3797
					public function before( $title = '' ) {
3798
						if ( empty( $title ) ) {
3799
							$title = esc_html( $this->plugin_names[ $this->i ] );
3800
						}
3801
						parent::before( $title );
3802
					}
3803
3804
					/**
3805
					 * Outputs the footer strings and necessary JS after each plugin installation.
3806
					 *
3807
					 * Checks for any errors and outputs them if they exist, else output
3808
					 * success strings.
3809
					 *
3810
					 * @since 2.2.0
3811
					 *
3812
					 * @param string $title Unused in this implementation.
3813
					 */
3814
					public function after( $title = '' ) {
3815
						if ( empty( $title ) ) {
3816
							$title = esc_html( $this->plugin_names[ $this->i ] );
3817
						}
3818
						parent::after( $title );
3819
3820
						$this->i++;
3821
					}
3822
3823
					/**
3824
					 * Outputs links after bulk plugin installation is complete.
3825
					 *
3826
					 * @since 2.2.0
3827
					 */
3828
					public function bulk_footer() {
3829
						// Serve up the string to say installations (and possibly activations) are complete.
3830
						parent::bulk_footer();
3831
3832
						// Flush plugins cache so we can make sure that the installed plugins list is always up to date.
3833
						wp_clean_plugins_cache();
3834
3835
						$this->tgmpa->show_tgmpa_version();
3836
3837
						// Display message based on if all plugins are now active or not.
3838
						$update_actions = array();
3839
3840
						if ( $this->tgmpa->is_tgmpa_complete() ) {
3841
							// All plugins are active, so we display the complete string and hide the menu to protect users.
3842
							echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>';
3843
							$update_actions['dashboard'] = sprintf(
3844
								esc_html( $this->tgmpa->strings['complete'] ),
3845
								'<a href="' . esc_url( self_admin_url() ) . '">' . esc_html( $this->tgmpa->strings['dashboard'] ) . '</a>'
3846
							);
3847
						} else {
3848
							$update_actions['tgmpa_page'] = '<a href="' . esc_url( $this->tgmpa->get_tgmpa_url() ) . '" target="_parent">' . esc_html( $this->tgmpa->strings['return'] ) . '</a>';
3849
						}
3850
3851
						/**
3852
						 * Filter the list of action links available following bulk plugin installs/updates.
3853
						 *
3854
						 * @since 2.5.0
3855
						 *
3856
						 * @param array $update_actions Array of plugin action links.
3857
						 * @param array $plugin_info    Array of information for the last-handled plugin.
3858
						 */
3859
						$update_actions = apply_filters( 'tgmpa_update_bulk_plugins_complete_actions', $update_actions, $this->plugin_info );
3860
3861
						if ( ! empty( $update_actions ) ) {
3862
							$this->feedback( implode( ' | ', (array) $update_actions ) );
3863
						}
3864
					}
3865
3866
					/* *********** DEPRECATED METHODS *********** */
3867
3868
					/**
3869
					 * Flush header output buffer.
3870
					 *
3871
					 * @since      2.2.0
3872
					 * @deprecated 2.5.0 use {@see Bulk_Upgrader_Skin::flush_output()} instead
3873
					 * @see        Bulk_Upgrader_Skin::flush_output()
3874
					 */
3875
					public function before_flush_output() {
3876
						_deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'Bulk_Upgrader_Skin::flush_output()' );
3877
						$this->flush_output();
3878
					}
3879
3880
					/**
3881
					 * Flush footer output buffer and iterate $this->i to make sure the
3882
					 * installation strings reference the correct plugin.
3883
					 *
3884
					 * @since      2.2.0
3885
					 * @deprecated 2.5.0 use {@see Bulk_Upgrader_Skin::flush_output()} instead
3886
					 * @see        Bulk_Upgrader_Skin::flush_output()
3887
					 */
3888
					public function after_flush_output() {
3889
						_deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'Bulk_Upgrader_Skin::flush_output()' );
3890
						$this->flush_output();
3891
						$this->i++;
3892
					}
3893
				}
3894
			}
3895
		}
3896
	}
3897
}
3898
3899
if ( ! class_exists( 'TGMPA_Utils' ) ) {
3900
3901
	/**
3902
	 * Generic utilities for TGMPA.
3903
	 *
3904
	 * All methods are static, poor-dev name-spacing class wrapper.
3905
	 *
3906
	 * Class was called TGM_Utils in 2.5.0 but renamed TGMPA_Utils in 2.5.1 as this was conflicting with Soliloquy.
3907
	 *
3908
	 * @since 2.5.0
3909
	 *
3910
	 * @package TGM-Plugin-Activation
3911
	 * @author  Juliette Reinders Folmer
3912
	 */
3913
	class TGMPA_Utils {
3914
		/**
3915
		 * Whether the PHP filter extension is enabled.
3916
		 *
3917
		 * @see http://php.net/book.filter
3918
		 *
3919
		 * @since 2.5.0
3920
		 *
3921
		 * @static
3922
		 *
3923
		 * @var bool $has_filters True is the extension is enabled.
3924
		 */
3925
		public static $has_filters;
3926
3927
		/**
3928
		 * Wrap an arbitrary string in <em> tags. Meant to be used in combination with array_map().
3929
		 *
3930
		 * @since 2.5.0
3931
		 *
3932
		 * @static
3933
		 *
3934
		 * @param string $string Text to be wrapped.
3935
		 * @return string
3936
		 */
3937
		public static function wrap_in_em( $string ) {
3938
			return '<em>' . wp_kses_post( $string ) . '</em>';
3939
		}
3940
3941
		/**
3942
		 * Wrap an arbitrary string in <strong> tags. Meant to be used in combination with array_map().
3943
		 *
3944
		 * @since 2.5.0
3945
		 *
3946
		 * @static
3947
		 *
3948
		 * @param string $string Text to be wrapped.
3949
		 * @return string
3950
		 */
3951
		public static function wrap_in_strong( $string ) {
3952
			return '<strong>' . wp_kses_post( $string ) . '</strong>';
3953
		}
3954
3955
		/**
3956
		 * Helper function: Validate a value as boolean
3957
		 *
3958
		 * @since 2.5.0
3959
		 *
3960
		 * @static
3961
		 *
3962
		 * @param mixed $value Arbitrary value.
3963
		 * @return bool
3964
		 */
3965
		public static function validate_bool( $value ) {
3966
			if ( ! isset( self::$has_filters ) ) {
3967
				self::$has_filters = extension_loaded( 'filter' );
3968
			}
3969
3970
			if ( self::$has_filters ) {
3971
				return filter_var( $value, FILTER_VALIDATE_BOOLEAN );
3972
			} else {
3973
				return self::emulate_filter_bool( $value );
3974
			}
3975
		}
3976
3977
		/**
3978
		 * Helper function: Cast a value to bool
3979
		 *
3980
		 * @since 2.5.0
3981
		 *
3982
		 * @static
3983
		 *
3984
		 * @param mixed $value Value to cast.
3985
		 * @return bool
3986
		 */
3987
		protected static function emulate_filter_bool( $value ) {
3988
			// @codingStandardsIgnoreStart
3989
			static $true  = array(
3990
				'1',
3991
				'true', 'True', 'TRUE',
3992
				'y', 'Y',
3993
				'yes', 'Yes', 'YES',
3994
				'on', 'On', 'ON',
3995
			);
3996
			static $false = array(
3997
				'0',
3998
				'false', 'False', 'FALSE',
3999
				'n', 'N',
4000
				'no', 'No', 'NO',
4001
				'off', 'Off', 'OFF',
4002
			);
4003
			// @codingStandardsIgnoreEnd
4004
4005
			if ( is_bool( $value ) ) {
4006
				return $value;
4007
			} elseif ( is_int( $value ) && ( 0 === $value || 1 === $value ) ) {
4008
				return (bool) $value;
4009
			} elseif ( ( is_float( $value ) && ! is_nan( $value ) ) && ( (float) 0 === $value || (float) 1 === $value ) ) {
4010
				return (bool) $value;
4011
			} elseif ( is_string( $value ) ) {
4012
				$value = trim( $value );
4013
				if ( in_array( $value, $true, true ) ) {
4014
					return true;
4015
				} elseif ( in_array( $value, $false, true ) ) {
4016
					return false;
4017
				} else {
4018
					return false;
4019
				}
4020
			}
4021
4022
			return false;
4023
		}
4024
	} // End of class TGMPA_Utils
4025
}
4026