Completed
Pull Request — develop (#569)
by
unknown
02:13
created

TGMPA_Bulk_Installer::bulk_upgrade()   A

Complexity

Conditions 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 10
rs 9.4285
cc 1
1
<?php
2
/**
3
 * Plugin installation and activation for WordPress themes.
4
 *
5
 * Please note that this is a drop-in library for a theme or plugin.
6
 * The authors of this library (Thomas, Gary and Juliette) are NOT responsible
7
 * for the support of your plugin or theme. Please contact the plugin
8
 * or theme author for support.
9
 *
10
 * @package   TGM-Plugin-Activation
11
 * @version   2.5.2
12
 * @link      http://tgmpluginactivation.com/
13
 * @author    Thomas Griffin, Gary Jones, Juliette Reinders Folmer
14
 * @copyright Copyright (c) 2011, Thomas Griffin
15
 * @license   GPL-2.0+
16
 */
17
18
/*
19
	Copyright 2011 Thomas Griffin (thomasgriffinmedia.com)
20
21
	This program is free software; you can redistribute it and/or modify
22
	it under the terms of the GNU General Public License, version 2, as
23
	published by the Free Software Foundation.
24
25
	This program is distributed in the hope that it will be useful,
26
	but WITHOUT ANY WARRANTY; without even the implied warranty of
27
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
28
	GNU General Public License for more details.
29
30
	You should have received a copy of the GNU General Public License
31
	along with this program; if not, write to the Free Software
32
	Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
33
*/
34
35
if ( ! class_exists( 'TGM_Plugin_Activation' ) ) {
36
37
	/**
38
	 * Automatic plugin installation and activation library.
39
	 *
40
	 * Creates a way to automatically install and activate plugins from within themes.
41
	 * The plugins can be either bundled, downloaded from the WordPress
42
	 * Plugin Repository or downloaded from another external source.
43
	 *
44
	 * @since 1.0.0
45
	 *
46
	 * @package TGM-Plugin-Activation
47
	 * @author  Thomas Griffin
48
	 * @author  Gary Jones
49
	 */
50
	class TGM_Plugin_Activation {
51
		/**
52
		 * TGMPA version number.
53
		 *
54
		 * @since 2.5.0
55
		 *
56
		 * @const string Version number.
57
		 */
58
		const TGMPA_VERSION = '2.5.2';
59
60
		/**
61
		 * Regular expression to test if a URL is a WP plugin repo URL.
62
		 *
63
		 * @const string Regex.
64
		 *
65
		 * @since 2.5.0
66
		 */
67
		const WP_REPO_REGEX = '|^http[s]?://wordpress\.org/(?:extend/)?plugins/|';
68
69
		/**
70
		 * Arbitrary regular expression to test if a string starts with a URL.
71
		 *
72
		 * @const string Regex.
73
		 *
74
		 * @since 2.5.0
75
		 */
76
		const IS_URL_REGEX = '|^http[s]?://|';
77
78
		/**
79
		 * Holds a copy of itself, so it can be referenced by the class name.
80
		 *
81
		 * @since 1.0.0
82
		 *
83
		 * @var TGM_Plugin_Activation
84
		 */
85
		public static $instance;
86
87
		/**
88
		 * Holds arrays of plugin details.
89
		 *
90
		 * @since 1.0.0
91
		 *
92
		 * @since 2.5.0 the array has the plugin slug as an associative key.
93
		 *
94
		 * @var array
95
		 */
96
		public $plugins = array();
97
98
		/**
99
		 * Holds array of plugins that force activated.
100
		 *
101
		 * @since 2.5.3
102
		 *
103
		 * @var array
104
		 */
105
		public $force_activated_plugins = array();
106
107
		/**
108
		 * Holds arrays of plugin names to use to sort the plugins array.
109
		 *
110
		 * @since 2.5.0
111
		 *
112
		 * @var array
113
		 */
114
		protected $sort_order = array();
115
116
		/**
117
		 * Whether any plugins have the 'force_activation' setting set to true.
118
		 *
119
		 * @since 2.5.0
120
		 *
121
		 * @var bool
122
		 */
123
		protected $has_forced_activation = false;
124
125
		/**
126
		 * Whether any plugins have the 'force_deactivation' setting set to true.
127
		 *
128
		 * @since 2.5.0
129
		 *
130
		 * @var bool
131
		 */
132
		protected $has_forced_deactivation = false;
133
134
		/**
135
		 * Name of the unique ID to hash notices.
136
		 *
137
		 * @since 2.4.0
138
		 *
139
		 * @var string
140
		 */
141
		public $id = 'tgmpa';
142
143
		/**
144
		 * Name of the query-string argument for the admin page.
145
		 *
146
		 * @since 1.0.0
147
		 *
148
		 * @var string
149
		 */
150
		protected $menu = 'tgmpa-install-plugins';
151
152
		/**
153
		 * Parent menu file slug.
154
		 *
155
		 * @since 2.5.0
156
		 *
157
		 * @var string
158
		 */
159
		public $parent_slug = 'themes.php';
160
161
		/**
162
		 * Capability needed to view the plugin installation menu item.
163
		 *
164
		 * @since 2.5.0
165
		 *
166
		 * @var string
167
		 */
168
		public $capability = 'edit_theme_options';
169
170
		/**
171
		 * Default absolute path to folder containing bundled plugin zip files.
172
		 *
173
		 * @since 2.0.0
174
		 *
175
		 * @var string Absolute path prefix to zip file location for bundled plugins. Default is empty string.
176
		 */
177
		public $default_path = '';
178
179
		/**
180
		 * Flag to show admin notices or not.
181
		 *
182
		 * @since 2.1.0
183
		 *
184
		 * @var boolean
185
		 */
186
		public $has_notices = true;
187
188
		/**
189
		 * Flag to determine if the user can dismiss the notice nag.
190
		 *
191
		 * @since 2.4.0
192
		 *
193
		 * @var boolean
194
		 */
195
		public $dismissable = true;
196
197
		/**
198
		 * Message to be output above nag notice if dismissable is false.
199
		 *
200
		 * @since 2.4.0
201
		 *
202
		 * @var string
203
		 */
204
		public $dismiss_msg = '';
205
206
		/**
207
		 * Flag to set automatic activation of plugins. Off by default.
208
		 *
209
		 * @since 2.2.0
210
		 *
211
		 * @var boolean
212
		 */
213
		public $is_automatic = false;
214
215
		/**
216
		 * Optional message to display before the plugins table.
217
		 *
218
		 * @since 2.2.0
219
		 *
220
		 * @var string Message filtered by wp_kses_post(). Default is empty string.
221
		 */
222
		public $message = '';
223
224
		/**
225
		 * Holds configurable array of strings.
226
		 *
227
		 * Default values are added in the constructor.
228
		 *
229
		 * @since 2.0.0
230
		 *
231
		 * @var array
232
		 */
233
		public $strings = array();
234
235
		/**
236
		 * Holds the version of WordPress.
237
		 *
238
		 * @since 2.4.0
239
		 *
240
		 * @var int
241
		 */
242
		public $wp_version;
243
244
		/**
245
		 * Holds the hook name for the admin page.
246
		 *
247
		 * @since 2.5.0
248
		 *
249
		 * @var string
250
		 */
251
		public $page_hook;
252
253
		/**
254
		 * Adds a reference of this object to $instance, populates default strings,
255
		 * does the tgmpa_init action hook, and hooks in the interactions to init.
256
		 *
257
		 * {@internal This method should be `protected`, but as too many TGMPA implementations
258
		 * haven't upgraded beyond v2.3.6 yet, this gives backward compatibility issues.
259
		 * Reverted back to public for the time being.}}
260
		 *
261
		 * @since 1.0.0
262
		 *
263
		 * @see TGM_Plugin_Activation::init()
264
		 */
265
		public function __construct() {
266
			// Set the current WordPress version.
267
			$this->wp_version = $GLOBALS['wp_version'];
268
269
			// Announce that the class is ready, and pass the object (for advanced use).
270
			do_action_ref_array( 'tgmpa_init', array( $this ) );
271
272
			/*
273
			 * Load our text domain and allow for overloading the fall-back file.
274
			 *
275
			 * {@internal IMPORTANT! If this code changes, review the regex in the custom TGMPA
276
			 * generator on the website.}}
277
			 */
278
			add_action( 'init', array( $this, 'load_textdomain' ), 5 );
279
			add_filter( 'load_textdomain_mofile', array( $this, 'overload_textdomain_mofile' ), 10, 2 );
280
281
			// When the rest of WP has loaded, kick-start the rest of the class.
282
			add_action( 'init', array( $this, 'init' ) );
283
		}
284
285
		/**
286
		 * Magic method to (not) set protected properties from outside of this class.
287
		 *
288
		 * {@internal hackedihack... There is a serious bug in v2.3.2 - 2.3.6  where the `menu` property
289
		 * is being assigned rather than tested in a conditional, effectively rendering it useless.
290
		 * This 'hack' prevents this from happening.}}
291
		 *
292
		 * @see https://github.com/TGMPA/TGM-Plugin-Activation/blob/2.3.6/tgm-plugin-activation/class-tgm-plugin-activation.php#L1593
293
		 *
294
		 * @param string $name  Name of an inaccessible property.
295
		 * @param mixed  $value Value to assign to the property.
296
		 * @return void  Silently fail to set the property when this is tried from outside of this class context.
297
		 *               (Inside this class context, the __set() method if not used as there is direct access.)
298
		 */
299
		public function __set( $name, $value ) {
300
			return;
301
		}
302
303
		/**
304
		 * Magic method to get the value of a protected property outside of this class context.
305
		 *
306
		 * @param string $name Name of an inaccessible property.
307
		 * @return mixed The property value.
308
		 */
309
		public function __get( $name ) {
310
			return $this->{$name};
311
		}
312
313
		/**
314
		 * Initialise the interactions between this class and WordPress.
315
		 *
316
		 * Hooks in three new methods for the class: admin_menu, notices and styles.
317
		 *
318
		 * @since 2.0.0
319
		 *
320
		 * @see TGM_Plugin_Activation::admin_menu()
321
		 * @see TGM_Plugin_Activation::notices()
322
		 * @see TGM_Plugin_Activation::styles()
323
		 */
324
		public function init() {
325
			/**
326
			 * By default TGMPA only loads on the WP back-end and not in an Ajax call. Using this filter
327
			 * you can overrule that behaviour.
328
			 *
329
			 * @since 2.5.0
330
			 *
331
			 * @param bool $load Whether or not TGMPA should load.
332
			 *                   Defaults to the return of `is_admin() && ! defined( 'DOING_AJAX' )`.
333
			 */
334
			if ( true !== apply_filters( 'tgmpa_load', ( is_admin() && ! defined( 'DOING_AJAX' ) ) ) ) {
335
				return;
336
			}
337
338
			// Load class strings.
339
			$this->strings = array(
340
				'page_title'                      => __( 'Install Required Plugins', 'tgmpa' ),
341
				'menu_title'                      => __( 'Install Plugins', 'tgmpa' ),
342
				/* translators: %s: plugin name. */
343
				'installing'                      => __( 'Installing Plugin: %s', 'tgmpa' ),
344
				/* translators: %s: plugin name. */
345
				'updating'                        => __( 'Updating Plugin: %s', 'tgmpa' ),
346
				'oops'                            => __( 'Something went wrong with the plugin API.', 'tgmpa' ),
347
				'notice_can_install_required'     => _n_noop(
348
					/* translators: 1: plugin name(s). */
349
					'This theme requires the following plugin: %1$s.',
350
					'This theme requires the following plugins: %1$s.',
351
					'tgmpa'
352
				),
353
				'notice_can_install_recommended'  => _n_noop(
354
					/* translators: 1: plugin name(s). */
355
					'This theme recommends the following plugin: %1$s.',
356
					'This theme recommends the following plugins: %1$s.',
357
					'tgmpa'
358
				),
359
				'notice_ask_to_update'            => _n_noop(
360
					/* translators: 1: plugin name(s). */
361
					'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.',
362
					'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.',
363
					'tgmpa'
364
				),
365
				'notice_ask_to_update_maybe'      => _n_noop(
366
					/* translators: 1: plugin name(s). */
367
					'There is an update available for: %1$s.',
368
					'There are updates available for the following plugins: %1$s.',
369
					'tgmpa'
370
				),
371
				'notice_can_activate_required'    => _n_noop(
372
					/* translators: 1: plugin name(s). */
373
					'The following required plugin is currently inactive: %1$s.',
374
					'The following required plugins are currently inactive: %1$s.',
375
					'tgmpa'
376
				),
377
				'notice_can_activate_recommended' => _n_noop(
378
					/* translators: 1: plugin name(s). */
379
					'The following recommended plugin is currently inactive: %1$s.',
380
					'The following recommended plugins are currently inactive: %1$s.',
381
					'tgmpa'
382
				),
383
				'notice_force_activation'        => _n_noop(
384
					'The following plugin has been automatically activated because it is required by the current theme: %s', 'The following plugins have been automatically activated because they are required by the current theme: %s'
385
				),
386
				'install_link'                    => _n_noop(
387
					'Begin installing plugin',
388
					'Begin installing plugins',
389
					'tgmpa'
390
				),
391
				'update_link'                     => _n_noop(
392
					'Begin updating plugin',
393
					'Begin updating plugins',
394
					'tgmpa'
395
				),
396
				'activate_link'                   => _n_noop(
397
					'Begin activating plugin',
398
					'Begin activating plugins',
399
					'tgmpa'
400
				),
401
				'return'                          => __( 'Return to Required Plugins Installer', 'tgmpa' ),
402
				'dashboard'                       => __( 'Return to the Dashboard', 'tgmpa' ),
403
				'plugin_activated'                => __( 'Plugin activated successfully.', 'tgmpa' ),
404
				'activated_successfully'          => __( 'The following plugin was activated successfully:', 'tgmpa' ),
405
				/* translators: 1: plugin name. */
406
				'plugin_already_active'           => __( 'No action taken. Plugin %1$s was already active.', 'tgmpa' ),
407
				/* translators: 1: plugin name. */
408
				'plugin_needs_higher_version'     => __( 'Plugin not activated. A higher version of %s is needed for this theme. Please update the plugin.', 'tgmpa' ),
409
				/* translators: 1: dashboard link. */
410
				'complete'                        => __( 'All plugins installed and activated successfully. %1$s', 'tgmpa' ),
411
				'dismiss'                         => __( 'Dismiss this notice', 'tgmpa' ),
412
				'notice_cannot_install_activate'  => __( 'There are one or more required or recommended plugins to install, update or activate.', 'tgmpa' ),
413
				'contact_admin'                   => __( 'Please contact the administrator of this site for help.', 'tgmpa' ),
414
			);
415
416
			do_action( 'tgmpa_register' );
417
418
			/* After this point, the plugins should be registered and the configuration set. */
419
420
			// Proceed only if we have plugins to handle.
421
			if ( empty( $this->plugins ) || ! is_array( $this->plugins ) ) {
422
				return;
423
			}
424
425
			// Set up the menu and notices if we still have outstanding actions.
426
			if ( true !== $this->is_tgmpa_complete() ) {
427
				// Sort the plugins.
428
				array_multisort( $this->sort_order, SORT_ASC, $this->plugins );
429
430
				add_action( 'admin_menu', array( $this, 'admin_menu' ) );
431
				add_action( 'admin_head', array( $this, 'dismiss' ) );
432
433
				// Prevent the normal links from showing underneath a single install/update page.
434
				add_filter( 'install_plugin_complete_actions', array( $this, 'actions' ) );
435
				add_filter( 'update_plugin_complete_actions', array( $this, 'actions' ) );
436
437
				if ( $this->has_notices ) {
438
					add_action( 'admin_notices', array( $this, 'notices' ) );
439
					add_action( 'admin_init', array( $this, 'admin_init' ), 1 );
440
					add_action( 'admin_enqueue_scripts', array( $this, 'thickbox' ) );
441
				}
442
			}
443
444
			// If needed, filter plugin action links.
445
			add_action( 'load-plugins.php', array( $this, 'add_plugin_action_link_filters' ), 1 );
446
447
			// Make sure things get reset on switch theme.
448
			add_action( 'switch_theme', array( $this, 'flush_plugins_cache' ) );
449
450
			if ( $this->has_notices ) {
451
				add_action( 'switch_theme', array( $this, 'update_dismiss' ) );
452
			}
453
454
			// Setup the force activation hook.
455
			if ( true === $this->has_forced_activation ) {
456
				add_action( 'admin_init', array( $this, 'force_activation' ) );
457
			}
458
459
			// Setup the force deactivation hook.
460
			if ( true === $this->has_forced_deactivation ) {
461
				add_action( 'switch_theme', array( $this, 'force_deactivation' ) );
462
			}
463
		}
464
465
		/**
466
		 * Load translations.
467
		 *
468
		 * @since 2.x.x
469
		 *
470
		 * (@internal Uses `load_theme_textdomain()` rather than `load_plugin_textdomain()` to
471
		 * get round the different ways of handling the path and deprecated notices being thrown
472
		 * and such. For plugins, the actual file name will be corrected by a filter.}}
473
		 *
474
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
475
		 * generator on the website.}}
476
		 */
477
		public function load_textdomain() {
478
			if ( is_textdomain_loaded( 'tgmpa' ) ) {
479
				return;
480
			}
481
482
			if ( false !== strpos( __FILE__, WP_PLUGIN_DIR ) || false !== strpos( __FILE__, WPMU_PLUGIN_DIR ) ) {
483
				// Plugin, we'll need to adjust the file name.
484
				add_action( 'load_textdomain_mofile', array( $this, 'correct_plugin_mofile' ), 10, 2 );
485
				load_theme_textdomain( 'tgmpa', dirname( __FILE__ ) . '/languages' );
486
				remove_action( 'load_textdomain_mofile', array( $this, 'correct_plugin_mofile' ), 10 );
487
			} else {
488
				load_theme_textdomain( 'tgmpa', dirname( __FILE__ ) . '/languages' );
489
			}
490
		}
491
492
		/**
493
		 * Correct the .mo file name for (must-use) plugins.
494
		 *
495
		 * Themese use `/path/{locale}.mo` while plugins use `/path/{text-domain}-{locale}.mo`.
496
		 *
497
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
498
		 * generator on the website.}}
499
		 *
500
		 * @since 2.x.x
501
		 *
502
		 * @param string $mofile Full path to the target mofile.
503
		 * @param string $domain The domain for which a language file is being loaded.
504
		 * @return string $mofile
505
		 */
506
		public function correct_plugin_mofile( $mofile, $domain ) {
507
			// Exit early if not our domain (just in case).
508
			if ( 'tgmpa' !== $domain ) {
509
				return $mofile;
510
			}
511
			return preg_replace( '`/([a-z]{2}_[A-Z]{2}.mo)$`', '/tgmpa-$1', $mofile );
512
		}
513
514
		/**
515
		 * Potentially overload the fall-back translation file for the current language.
516
		 *
517
		 * WP, by default since WP 3.7, will load a local translation first and if none
518
		 * can be found, will try and find a translation in the /wp-content/languages/ directory.
519
		 * As this library is theme/plugin agnostic, translation files for TGMPA can exist both
520
		 * in the WP_LANG_DIR /plugins/ subdirectory as well as in the /themes/ subdirectory.
521
		 *
522
		 * This method makes sure both directories are checked.
523
		 *
524
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
525
		 * generator on the website.}}
526
		 *
527
		 * @since 2.x.x
528
		 *
529
		 * @param string $mofile Full path to the target mofile.
530
		 * @param string $domain The domain for which a language file is being loaded.
531
		 * @return string $mofile
532
		 */
533
		public function overload_textdomain_mofile( $mofile, $domain ) {
534
			// Exit early if not our domain, not a WP_LANG_DIR load or if the file exists and is readable.
535
			if ( 'tgmpa' !== $domain || false === strpos( $mofile, WP_LANG_DIR ) || @is_readable( $mofile ) ) {
536
				return $mofile;
537
			}
538
539
			// Current fallback file is not valid, let's try the alternative option.
540
			if ( false !== strpos( $mofile, '/themes/' ) ) {
541
				return str_replace( '/themes/', '/plugins/', $mofile );
542
			} elseif ( false !== strpos( $mofile, '/plugins/' ) ) {
543
				return str_replace( '/plugins/', '/themes/', $mofile );
544
			} else {
545
				return $mofile;
546
			}
547
		}
548
549
		/**
550
		 * Hook in plugin action link filters for the WP native plugins page.
551
		 *
552
		 * - Prevent activation of plugins which don't meet the minimum version requirements.
553
		 * - Prevent deactivation of force-activated plugins.
554
		 * - Add update notice if update available.
555
		 *
556
		 * @since 2.5.0
557
		 */
558
		public function add_plugin_action_link_filters() {
559
			foreach ( $this->plugins as $slug => $plugin ) {
560
				if ( false === $this->can_plugin_activate( $slug ) ) {
561
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_activate' ), 20 );
562
				}
563
564
				if ( true === $plugin['force_activation'] ) {
565
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_deactivate' ), 20 );
566
				}
567
568
				if ( false !== $this->does_plugin_require_update( $slug ) ) {
569
					add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_update' ), 20 );
570
				}
571
			}
572
		}
573
574
		/**
575
		 * Remove the 'Activate' link on the WP native plugins page if the plugin does not meet the
576
		 * minimum version requirements.
577
		 *
578
		 * @since 2.5.0
579
		 *
580
		 * @param array $actions Action links.
581
		 * @return array
582
		 */
583
		public function filter_plugin_action_links_activate( $actions ) {
584
			unset( $actions['activate'] );
585
586
			return $actions;
587
		}
588
589
		/**
590
		 * Remove the 'Deactivate' link on the WP native plugins page if the plugin has been set to force activate.
591
		 *
592
		 * @since 2.5.0
593
		 *
594
		 * @param array $actions Action links.
595
		 * @return array
596
		 */
597
		public function filter_plugin_action_links_deactivate( $actions ) {
598
			unset( $actions['deactivate'] );
599
600
			return $actions;
601
		}
602
603
		/**
604
		 * Add a 'Requires update' link on the WP native plugins page if the plugin does not meet the
605
		 * minimum version requirements.
606
		 *
607
		 * @since 2.5.0
608
		 *
609
		 * @param array $actions Action links.
610
		 * @return array
611
		 */
612
		public function filter_plugin_action_links_update( $actions ) {
613
			$actions['update'] = sprintf(
614
				'<a href="%1$s" title="%2$s" class="edit">%3$s</a>',
615
				esc_url( $this->get_tgmpa_status_url( 'update' ) ),
616
				esc_attr__( 'This plugin needs to be updated to be compatible with your theme.', 'tgmpa' ),
617
				esc_html__( 'Update Required', 'tgmpa' )
618
			);
619
620
			return $actions;
621
		}
622
623
		/**
624
		 * Handles calls to show plugin information via links in the notices.
625
		 *
626
		 * We get the links in the admin notices to point to the TGMPA page, rather
627
		 * than the typical plugin-install.php file, so we can prepare everything
628
		 * beforehand.
629
		 *
630
		 * WP does not make it easy to show the plugin information in the thickbox -
631
		 * here we have to require a file that includes a function that does the
632
		 * main work of displaying it, enqueue some styles, set up some globals and
633
		 * finally call that function before exiting.
634
		 *
635
		 * Down right easy once you know how...
636
		 *
637
		 * Returns early if not the TGMPA page.
638
		 *
639
		 * @since 2.1.0
640
		 *
641
		 * @global string $tab Used as iframe div class names, helps with styling
642
		 * @global string $body_id Used as the iframe body ID, helps with styling
643
		 *
644
		 * @return null Returns early if not the TGMPA page.
645
		 */
646
		public function admin_init() {
647
			if ( ! $this->is_tgmpa_page() ) {
648
				return;
649
			}
650
651
			if ( isset( $_REQUEST['tab'] ) && 'plugin-information' === $_REQUEST['tab'] ) {
652
				// Needed for install_plugin_information().
653
				require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
654
655
				wp_enqueue_style( 'plugin-install' );
656
657
				global $tab, $body_id;
658
				$body_id = 'plugin-information';
659
				// @codingStandardsIgnoreStart
660
				$tab     = 'plugin-information';
661
				// @codingStandardsIgnoreEnd
662
663
				install_plugin_information();
664
665
				exit;
666
			}
667
		}
668
669
		/**
670
		 * Enqueue thickbox scripts/styles for plugin info.
671
		 *
672
		 * Thickbox is not automatically included on all admin pages, so we must
673
		 * manually enqueue it for those pages.
674
		 *
675
		 * Thickbox is only loaded if the user has not dismissed the admin
676
		 * notice or if there are any plugins left to install and activate.
677
		 *
678
		 * @since 2.1.0
679
		 */
680
		public function thickbox() {
681
			if ( ! get_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, true ) ) {
682
				add_thickbox();
683
			}
684
		}
685
686
		/**
687
		 * Adds submenu page if there are plugin actions to take.
688
		 *
689
		 * This method adds the submenu page letting users know that a required
690
		 * plugin needs to be installed.
691
		 *
692
		 * This page disappears once the plugin has been installed and activated.
693
		 *
694
		 * @since 1.0.0
695
		 *
696
		 * @see TGM_Plugin_Activation::init()
697
		 * @see TGM_Plugin_Activation::install_plugins_page()
698
		 *
699
		 * @return null Return early if user lacks capability to install a plugin.
700
		 */
701
		public function admin_menu() {
702
			// Make sure privileges are correct to see the page.
703
			if ( ! current_user_can( 'install_plugins' ) ) {
704
				return;
705
			}
706
707
			$args = apply_filters(
708
				'tgmpa_admin_menu_args',
709
				array(
710
					'parent_slug' => $this->parent_slug,                     // Parent Menu slug.
711
					'page_title'  => $this->strings['page_title'],           // Page title.
712
					'menu_title'  => $this->strings['menu_title'],           // Menu title.
713
					'capability'  => $this->capability,                      // Capability.
714
					'menu_slug'   => $this->menu,                            // Menu slug.
715
					'function'    => array( $this, 'install_plugins_page' ), // Callback.
716
				)
717
			);
718
719
			$this->add_admin_menu( $args );
720
		}
721
722
		/**
723
		 * Add the menu item.
724
		 *
725
		 * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA
726
		 * generator on the website.}}
727
		 *
728
		 * @since 2.5.0
729
		 *
730
		 * @param array $args Menu item configuration.
731
		 */
732
		protected function add_admin_menu( array $args ) {
733
			if ( has_filter( 'tgmpa_admin_menu_use_add_theme_page' ) ) {
734
				_deprecated_function( 'The "tgmpa_admin_menu_use_add_theme_page" filter', '2.5.0', esc_html__( 'Set the parent_slug config variable instead.', 'tgmpa' ) );
735
			}
736
737
			if ( 'themes.php' === $this->parent_slug ) {
738
				$this->page_hook = call_user_func( 'add_theme_page', $args['page_title'], $args['menu_title'], $args['capability'], $args['menu_slug'], $args['function'] );
739
			} else {
740
				$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'] );
741
			}
742
		}
743
744
		/**
745
		 * Echoes plugin installation form.
746
		 *
747
		 * This method is the callback for the admin_menu method function.
748
		 * This displays the admin page and form area where the user can select to install and activate the plugin.
749
		 * Aborts early if we're processing a plugin installation action.
750
		 *
751
		 * @since 1.0.0
752
		 *
753
		 * @return null Aborts early if we're processing a plugin installation action.
754
		 */
755
		public function install_plugins_page() {
756
			// Store new instance of plugin table in object.
757
			$plugin_table = new TGMPA_List_Table;
758
759
			// Return early if processing a plugin installation action.
760
			if ( ( ( 'tgmpa-bulk-install' === $plugin_table->current_action() || 'tgmpa-bulk-update' === $plugin_table->current_action() ) && $plugin_table->process_bulk_actions() ) || $this->do_plugin_install() ) {
761
				return;
762
			}
763
764
			// Force refresh of available plugin information so we'll know about manual updates/deletes.
765
			wp_clean_plugins_cache( false );
766
767
			?>
768
			<div class="tgmpa wrap">
769
				<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
770
				<?php $plugin_table->prepare_items(); ?>
771
772
				<?php
773
				if ( ! empty( $this->message ) && is_string( $this->message ) ) {
774
					echo wp_kses_post( $this->message );
775
				}
776
				?>
777
				<?php $plugin_table->views(); ?>
778
779
				<form id="tgmpa-plugins" action="" method="post">
780
					<input type="hidden" name="tgmpa-page" value="<?php echo esc_attr( $this->menu ); ?>" />
781
					<input type="hidden" name="plugin_status" value="<?php echo esc_attr( $plugin_table->view_context ); ?>" />
782
					<?php $plugin_table->display(); ?>
783
				</form>
784
			</div>
785
			<?php
786
		}
787
788
		/**
789
		 * Installs, updates or activates a plugin depending on the action link clicked by the user.
790
		 *
791
		 * Checks the $_GET variable to see which actions have been
792
		 * passed and responds with the appropriate method.
793
		 *
794
		 * Uses WP_Filesystem to process and handle the plugin installation
795
		 * method.
796
		 *
797
		 * @since 1.0.0
798
		 *
799
		 * @uses WP_Filesystem
800
		 * @uses WP_Error
801
		 * @uses WP_Upgrader
802
		 * @uses Plugin_Upgrader
803
		 * @uses Plugin_Installer_Skin
804
		 * @uses Plugin_Upgrader_Skin
805
		 *
806
		 * @return boolean True on success, false on failure.
807
		 */
808
		protected function do_plugin_install() {
809
			if ( empty( $_GET['plugin'] ) ) {
810
				return false;
811
			}
812
813
			// All plugin information will be stored in an array for processing.
814
			$slug = $this->sanitize_key( urldecode( $_GET['plugin'] ) );
815
816
			if ( ! isset( $this->plugins[ $slug ] ) ) {
817
				return false;
818
			}
819
820
			// Was an install or upgrade action link clicked?
821
			if ( ( isset( $_GET['tgmpa-install'] ) && 'install-plugin' === $_GET['tgmpa-install'] ) || ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) ) {
822
823
				$install_type = 'install';
824
				if ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) {
825
					$install_type = 'update';
826
				}
827
828
				check_admin_referer( 'tgmpa-' . $install_type, 'tgmpa-nonce' );
829
830
				// Pass necessary information via URL if WP_Filesystem is needed.
831
				$url = wp_nonce_url(
832
					add_query_arg(
833
						array(
834
							'plugin'                 => urlencode( $slug ),
835
							'tgmpa-' . $install_type => $install_type . '-plugin',
836
						),
837
						$this->get_tgmpa_url()
838
					),
839
					'tgmpa-' . $install_type,
840
					'tgmpa-nonce'
841
				);
842
843
				$method = ''; // Leave blank so WP_Filesystem can populate it as necessary.
844
845
				if ( false === ( $creds = request_filesystem_credentials( esc_url_raw( $url ), $method, false, false, array() ) ) ) {
846
					return true;
847
				}
848
849 View Code Duplication
				if ( ! WP_Filesystem( $creds ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
850
					request_filesystem_credentials( esc_url_raw( $url ), $method, true, false, array() ); // Setup WP_Filesystem.
851
					return true;
852
				}
853
854
				/* If we arrive here, we have the filesystem. */
855
856
				// Prep variables for Plugin_Installer_Skin class.
857
				$extra         = array();
858
				$extra['slug'] = $slug; // Needed for potentially renaming of directory name.
859
				$source        = $this->get_download_url( $slug );
860
				$api           = ( 'repo' === $this->plugins[ $slug ]['source_type'] ) ? $this->get_plugins_api( $slug ) : null;
861
				$api           = ( false !== $api ) ? $api : null;
862
863
				$url = add_query_arg(
864
					array(
865
						'action' => $install_type . '-plugin',
866
						'plugin' => urlencode( $slug ),
867
					),
868
					'update.php'
869
				);
870
871
				if ( ! class_exists( 'Plugin_Upgrader', false ) ) {
872
					require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
873
				}
874
875
				$title     = ( 'update' === $install_type ) ? $this->strings['updating'] : $this->strings['installing'];
876
				$skin_args = array(
877
					'type'   => ( 'bundled' !== $this->plugins[ $slug ]['source_type'] ) ? 'web' : 'upload',
878
					'title'  => sprintf( $title, $this->plugins[ $slug ]['name'] ),
879
					'url'    => esc_url_raw( $url ),
880
					'nonce'  => $install_type . '-plugin_' . $slug,
881
					'plugin' => '',
882
					'api'    => $api,
883
					'extra'  => $extra,
884
				);
885
				unset( $title );
886
887
				if ( 'update' === $install_type ) {
888
					$skin_args['plugin'] = $this->plugins[ $slug ]['file_path'];
889
					$skin                = new Plugin_Upgrader_Skin( $skin_args );
890
				} else {
891
					$skin = new Plugin_Installer_Skin( $skin_args );
892
				}
893
894
				// Create a new instance of Plugin_Upgrader.
895
				$upgrader = new Plugin_Upgrader( $skin );
896
897
				// Perform the action and install the plugin from the $source urldecode().
898
				add_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1, 3 );
899
900
				if ( 'update' === $install_type ) {
901
					// Inject our info into the update transient.
902
					$to_inject                    = array( $slug => $this->plugins[ $slug ] );
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__( 'Return to the Dashboard', 'tgmpa' ) . '</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 = untrailingslashit( $source );
1031
					$to   = trailingslashit( $remote_source ) . $desired_slug;
1032
1033
					if ( true === $GLOBALS['wp_filesystem']->move( $from, $to ) ) {
1034
						return trailingslashit( $to );
1035 View Code Duplication
					} else {
1036
						return new WP_Error( 'rename_failed', esc_html__( 'The remote plugin package does not contain a folder with the desired slug and renaming did not work.', 'tgmpa' ) . ' ' . esc_html__( 'Please contact the plugin provider and ask them to package their plugin according to the WordPress guidelines.', 'tgmpa' ), array( 'found' => $subdir_name, 'expected' => $desired_slug ) );
1037
					}
1038 View Code Duplication
				} elseif ( empty( $subdir_name ) ) {
1039
					return new WP_Error( 'packaged_wrong', esc_html__( 'The remote plugin package consists of more than one file, but the files are not packaged in a folder.', 'tgmpa' ) . ' ' . esc_html__( 'Please contact the plugin provider and ask them to package their plugin according to the WordPress guidelines.', 'tgmpa' ), array( 'found' => $subdir_name, 'expected' => $desired_slug ) );
1040
				}
1041
			}
1042
1043
			return $source;
1044
		}
1045
1046
		/**
1047
		 * Activate a single plugin and send feedback about the result to the screen.
1048
		 *
1049
		 * @since 2.5.0
1050
		 *
1051
		 * @param string $file_path Path within wp-plugins/ to main plugin file.
1052
		 * @param string $slug      Plugin slug.
1053
		 * @param bool   $automatic Whether this is an automatic activation after an install. Defaults to false.
1054
		 *                          This determines the styling of the output messages.
1055
		 * @return bool False if an error was encountered, true otherwise.
1056
		 */
1057
		protected function activate_single_plugin( $file_path, $slug, $automatic = false ) {
1058
			if ( $this->can_plugin_activate( $slug ) ) {
1059
				$activate = activate_plugin( $file_path );
1060
1061
				if ( is_wp_error( $activate ) ) {
1062
					echo '<div id="message" class="error"><p>', wp_kses_post( $activate->get_error_message() ), '</p></div>',
1063
						'<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>';
1064
1065
					return false; // End it here if there is an error with activation.
1066
				} else {
1067
					if ( ! $automatic ) {
1068
						// Make sure message doesn't display again if bulk activation is performed
1069
						// immediately after a single activation.
1070
						if ( ! isset( $_POST['action'] ) ) { // WPCS: CSRF OK.
1071
							echo '<div id="message" class="updated"><p>', esc_html( $this->strings['activated_successfully'] ), ' <strong>', esc_html( $this->plugins[ $slug ]['name'] ), '.</strong></p></div>';
1072
						}
1073
					} else {
1074
						// Simpler message layout for use on the plugin install page.
1075
						echo '<p>', esc_html( $this->strings['plugin_activated'] ), '</p>';
1076
					}
1077
				}
1078 View Code Duplication
			} elseif ( $this->is_plugin_active( $slug ) ) {
1079
				// No simpler message format provided as this message should never be encountered
1080
				// on the plugin install page.
1081
				echo '<div id="message" class="error"><p>',
1082
					sprintf(
1083
						esc_html( $this->strings['plugin_already_active'] ),
1084
						'<strong>' . esc_html( $this->plugins[ $slug ]['name'] ) . '</strong>'
1085
					),
1086
					'</p></div>';
1087
			} elseif ( $this->does_plugin_require_update( $slug ) ) {
1088
				if ( ! $automatic ) {
1089
					// Make sure message doesn't display again if bulk activation is performed
1090
					// immediately after a single activation.
1091 View Code Duplication
					if ( ! isset( $_POST['action'] ) ) { // WPCS: CSRF OK.
1092
						echo '<div id="message" class="error"><p>',
1093
							sprintf(
1094
								esc_html( $this->strings['plugin_needs_higher_version'] ),
1095
								'<strong>' . esc_html( $this->plugins[ $slug ]['name'] ) . '</strong>'
1096
							),
1097
							'</p></div>';
1098
					}
1099
				} else {
1100
					// Simpler message layout for use on the plugin install page.
1101
					echo '<p>', sprintf( esc_html( $this->strings['plugin_needs_higher_version'] ), esc_html( $this->plugins[ $slug ]['name'] ) ), '</p>';
1102
				}
1103
			}
1104
1105
			return true;
1106
		}
1107
1108
		/**
1109
		 * Echoes required plugin notice.
1110
		 *
1111
		 * Outputs a message telling users that a specific plugin is required for
1112
		 * their theme. If appropriate, it includes a link to the form page where
1113
		 * users can install and activate the plugin.
1114
		 *
1115
		 * Returns early if we're on the Install page.
1116
		 *
1117
		 * @since 1.0.0
1118
		 *
1119
		 * @global object $current_screen
1120
		 *
1121
		 * @return null Returns early if we're on the Install page.
1122
		 */
1123
		public function notices() {
1124
			// Remove nag on the install page / Return early if the nag message has been dismissed or user < author.
1125
			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' ) ) ) {
1126
				return;
1127
			}
1128
1129
			// Store for the plugin slugs by message type.
1130
			$message = array();
1131
1132
			// Initialize counters used to determine plurality of action link texts.
1133
			$install_link_count          = 0;
1134
			$update_link_count           = 0;
1135
			$activate_link_count         = 0;
1136
			$total_required_action_count = 0;
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $total_required_action_count exceeds the maximum configured length of 25.

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

Loading history...
1137
1138
			foreach ( $this->plugins as $slug => $plugin ) {
1139
				$force_activated = in_array( $slug, $this->force_activated_plugins );
1140
1141
				if ( $this->is_plugin_active( $slug ) && false === $this->does_plugin_have_update( $slug ) && ! $force_activated ) {
1142
					continue;
1143
				}
1144
1145
				if ( $force_activated ) {
1146
					$message['notice_force_activation'][] = $slug;
1147
				} else if ( ! $this->is_plugin_installed( $slug ) ) {
1148
					if ( current_user_can( 'install_plugins' ) ) {
1149
						$install_link_count++;
1150
1151
						if ( true === $plugin['required'] ) {
1152
							$message['notice_can_install_required'][] = $slug;
1153
						} else {
1154
							$message['notice_can_install_recommended'][] = $slug;
1155
						}
1156
					}
1157
					if ( true === $plugin['required'] ) {
1158
						$total_required_action_count++;
1159
					}
1160
				} else {
1161
					if ( ! $this->is_plugin_active( $slug ) && $this->can_plugin_activate( $slug ) ) {
1162
						if ( current_user_can( 'activate_plugins' ) ) {
1163
							$activate_link_count++;
1164
1165
							if ( true === $plugin['required'] ) {
1166
								$message['notice_can_activate_required'][] = $slug;
1167
							} else {
1168
								$message['notice_can_activate_recommended'][] = $slug;
1169
							}
1170
						}
1171
						if ( true === $plugin['required'] ) {
1172
							$total_required_action_count++;
1173
						}
1174
					}
1175
1176
					if ( $this->does_plugin_require_update( $slug ) || false !== $this->does_plugin_have_update( $slug ) ) {
1177
1178
						if ( current_user_can( 'update_plugins' ) ) {
1179
							$update_link_count++;
1180
1181
							if ( $this->does_plugin_require_update( $slug ) ) {
1182
								$message['notice_ask_to_update'][] = $slug;
1183
							} elseif ( false !== $this->does_plugin_have_update( $slug ) ) {
1184
								$message['notice_ask_to_update_maybe'][] = $slug;
1185
							}
1186
						}
1187
						if ( true === $plugin['required'] ) {
1188
							$total_required_action_count++;
1189
						}
1190
					}
1191
				}
1192
			}
1193
			unset( $slug, $plugin );
1194
1195
			// If we have notices to display, we move forward.
1196
			if ( ! empty( $message ) || $total_required_action_count > 0 ) {
1197
				krsort( $message ); // Sort messages.
1198
				$rendered = '';
1199
1200
				// As add_settings_error() wraps the final message in a <p> and as the final message can't be
1201
				// filtered, using <p>'s in our html would render invalid html output.
1202
				$line_template = '<span style="display: block; margin: 0.5em 0.5em 0 0; clear: both;">%s</span>' . "\n";
1203
1204
				if ( ! current_user_can( 'activate_plugins' ) && ! current_user_can( 'install_plugins' ) && ! current_user_can( 'update_plugins' ) ) {
1205
					$rendered = esc_html__( $this->strings['notice_cannot_install_activate'] ) . ' ' . esc_html__( $this->strings['contact_admin'] );
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 2 spaces but found 1 space

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

To visualize

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

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

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

will produce no issues.

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

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

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

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

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1891
			}
1892
		}
1893
1894
		/**
1895
		 * Check if a plugin can be activated, i.e. is not currently active and meets the minimum
1896
		 * plugin version requirements set in TGMPA (if any).
1897
		 *
1898
		 * @since 2.5.0
1899
		 *
1900
		 * @param string $slug Plugin slug.
1901
		 * @return bool True if OK to activate, false otherwise.
1902
		 */
1903
		public function can_plugin_activate( $slug ) {
1904
			return ( ! $this->is_plugin_active( $slug ) && ! $this->does_plugin_require_update( $slug ) );
1905
		}
1906
1907
		/**
1908
		 * Retrieve the version number of an installed plugin.
1909
		 *
1910
		 * @since 2.5.0
1911
		 *
1912
		 * @param string $slug Plugin slug.
1913
		 * @return string Version number as string or an empty string if the plugin is not installed
1914
		 *                or version unknown (plugins which don't comply with the plugin header standard).
1915
		 */
1916
		public function get_installed_version( $slug ) {
1917
			$installed_plugins = $this->get_plugins(); // Retrieve a list of all installed plugins (WP cached).
1918
1919
			if ( ! empty( $installed_plugins[ $this->plugins[ $slug ]['file_path'] ]['Version'] ) ) {
1920
				return $installed_plugins[ $this->plugins[ $slug ]['file_path'] ]['Version'];
1921
			}
1922
1923
			return '';
1924
		}
1925
1926
		/**
1927
		 * Check whether a plugin complies with the minimum version requirements.
1928
		 *
1929
		 * @since 2.5.0
1930
		 *
1931
		 * @param string $slug Plugin slug.
1932
		 * @return bool True when a plugin needs to be updated, otherwise false.
1933
		 */
1934
		public function does_plugin_require_update( $slug ) {
1935
			$installed_version = $this->get_installed_version( $slug );
1936
			$minimum_version   = $this->plugins[ $slug ]['version'];
1937
1938
			return version_compare( $minimum_version, $installed_version, '>' );
1939
		}
1940
1941
		/**
1942
		 * Check whether there is an update available for a plugin.
1943
		 *
1944
		 * @since 2.5.0
1945
		 *
1946
		 * @param string $slug Plugin slug.
1947
		 * @return false|string Version number string of the available update or false if no update available.
1948
		 */
1949
		public function does_plugin_have_update( $slug ) {
1950
			// Presume bundled and external plugins will point to a package which meets the minimum required version.
1951
			if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) {
1952
				if ( $this->does_plugin_require_update( $slug ) ) {
1953
					return $this->plugins[ $slug ]['version'];
1954
				}
1955
1956
				return false;
1957
			}
1958
1959
			$repo_updates = get_site_transient( 'update_plugins' );
1960
1961 View Code Duplication
			if ( isset( $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->new_version ) ) {
1962
				return $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->new_version;
1963
			}
1964
1965
			return false;
1966
		}
1967
1968
		/**
1969
		 * Retrieve potential upgrade notice for a plugin.
1970
		 *
1971
		 * @since 2.5.0
1972
		 *
1973
		 * @param string $slug Plugin slug.
1974
		 * @return string The upgrade notice or an empty string if no message was available or provided.
1975
		 */
1976
		public function get_upgrade_notice( $slug ) {
1977
			// We currently can't get reliable info on non-WP-repo plugins - issue #380.
1978
			if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) {
1979
				return '';
1980
			}
1981
1982
			$repo_updates = get_site_transient( 'update_plugins' );
1983
1984 View Code Duplication
			if ( ! empty( $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->upgrade_notice ) ) {
1985
				return $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->upgrade_notice;
1986
			}
1987
1988
			return '';
1989
		}
1990
1991
		/**
1992
		 * Wrapper around the core WP get_plugins function, making sure it's actually available.
1993
		 *
1994
		 * @since 2.5.0
1995
		 *
1996
		 * @param string $plugin_folder Optional. Relative path to single plugin folder.
1997
		 * @return array Array of installed plugins with plugin information.
1998
		 */
1999
		public function get_plugins( $plugin_folder = '' ) {
2000
			if ( ! function_exists( 'get_plugins' ) ) {
2001
				require_once ABSPATH . 'wp-admin/includes/plugin.php';
2002
			}
2003
2004
			return get_plugins( $plugin_folder );
2005
		}
2006
2007
		/**
2008
		 * Delete dismissable nag option when theme is switched.
2009
		 *
2010
		 * This ensures that the user(s) is/are again reminded via nag of required
2011
		 * and/or recommended plugins if they re-activate the theme.
2012
		 *
2013
		 * @since 2.1.1
2014
		 */
2015
		public function update_dismiss() {
2016
			delete_metadata( 'user', null, 'tgmpa_dismissed_notice_' . $this->id, null, true );
2017
		}
2018
2019
		/**
2020
		 * Forces plugin activation if the parameter 'force_activation' is
2021
		 * set to true.
2022
		 *
2023
		 * This allows theme authors to specify certain plugins that must be
2024
		 * active at all times while using the current theme.
2025
		 *
2026
		 * Please take special care when using this parameter as it has the
2027
		 * potential to be harmful if not used correctly. Setting this parameter
2028
		 * to true will not allow the specified plugin to be deactivated unless
2029
		 * the user switches themes.
2030
		 *
2031
		 * @since 2.2.0
2032
		 */
2033
		public function force_activation() {
2034
			foreach ( $this->plugins as $slug => $plugin ) {
2035
				if ( true === $plugin['force_activation'] ) {
2036
					if ( ! $this->is_plugin_installed( $slug ) ) {
2037
						// Oops, plugin isn't there so iterate to next condition.
2038
						continue;
2039
					} elseif ( $this->can_plugin_activate( $slug ) ) {
2040
						// There we go, activate the plugin.
2041
						activate_plugin( $plugin['file_path'] );
2042
						$this->force_activated_plugins[] = $slug;
2043
					}
2044
				}
2045
			}
2046
		}
2047
2048
		/**
2049
		 * Forces plugin deactivation if the parameter 'force_deactivation'
2050
		 * is set to true.
2051
		 *
2052
		 * This allows theme authors to specify certain plugins that must be
2053
		 * deactivated upon switching from the current theme to another.
2054
		 *
2055
		 * Please take special care when using this parameter as it has the
2056
		 * potential to be harmful if not used correctly.
2057
		 *
2058
		 * @since 2.2.0
2059
		 */
2060
		public function force_deactivation() {
2061
			foreach ( $this->plugins as $slug => $plugin ) {
2062
				// Only proceed forward if the parameter is set to true and plugin is active.
2063
				if ( true === $plugin['force_deactivation'] && $this->is_plugin_active( $slug ) ) {
2064
					deactivate_plugins( $plugin['file_path'] );
2065
				}
2066
			}
2067
		}
2068
2069
		/**
2070
		 * Echo the current TGMPA version number to the page.
2071
		 */
2072
		public function show_tgmpa_version() {
2073
			echo '<p style="float: right; padding: 0em 1.5em 0.5em 0;"><strong><small>',
2074
				esc_html(
2075
					sprintf(
2076
						/* translators: %s: version number */
2077
						__( 'TGMPA v%s', 'tgmpa' ),
2078
						self::TGMPA_VERSION
2079
					)
2080
				),
2081
				'</small></strong></p>';
2082
		}
2083
2084
		/**
2085
		 * Returns the singleton instance of the class.
2086
		 *
2087
		 * @since 2.4.0
2088
		 *
2089
		 * @return object The TGM_Plugin_Activation object.
2090
		 */
2091
		public static function get_instance() {
2092
			if ( ! isset( self::$instance ) && ! ( self::$instance instanceof self ) ) {
2093
				self::$instance = new self();
2094
			}
2095
2096
			return self::$instance;
2097
		}
2098
	}
2099
2100
	if ( ! function_exists( 'load_tgm_plugin_activation' ) ) {
2101
		/**
2102
		 * Ensure only one instance of the class is ever invoked.
2103
		 */
2104
		function load_tgm_plugin_activation() {
2105
			$GLOBALS['tgmpa'] = TGM_Plugin_Activation::get_instance();
2106
		}
2107
	}
2108
2109
	if ( did_action( 'plugins_loaded' ) ) {
2110
		load_tgm_plugin_activation();
2111
	} else {
2112
		add_action( 'plugins_loaded', 'load_tgm_plugin_activation' );
2113
	}
2114
}
2115
2116
if ( ! function_exists( 'tgmpa' ) ) {
2117
	/**
2118
	 * Helper function to register a collection of required plugins.
2119
	 *
2120
	 * @since 2.0.0
2121
	 * @api
2122
	 *
2123
	 * @param array $plugins An array of plugin arrays.
2124
	 * @param array $config  Optional. An array of configuration values.
2125
	 */
2126
	function tgmpa( $plugins, $config = array() ) {
2127
		$instance = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
2128
2129
		foreach ( $plugins as $plugin ) {
2130
			call_user_func( array( $instance, 'register' ), $plugin );
2131
		}
2132
2133
		if ( ! empty( $config ) && is_array( $config ) ) {
2134
			// Send out notices for deprecated arguments passed.
2135
			if ( isset( $config['notices'] ) ) {
2136
				_deprecated_argument( __FUNCTION__, '2.2.0', 'The `notices` config parameter was renamed to `has_notices` in TGMPA 2.2.0. Please adjust your configuration.' );
2137
				if ( ! isset( $config['has_notices'] ) ) {
2138
					$config['has_notices'] = $config['notices'];
2139
				}
2140
			}
2141
2142
			if ( isset( $config['parent_menu_slug'] ) ) {
2143
				_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.' );
2144
			}
2145
			if ( isset( $config['parent_url_slug'] ) ) {
2146
				_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.' );
2147
			}
2148
2149
			call_user_func( array( $instance, 'config' ), $config );
2150
		}
2151
	}
2152
}
2153
2154
/**
2155
 * WP_List_Table isn't always available. If it isn't available,
2156
 * we load it here.
2157
 *
2158
 * @since 2.2.0
2159
 */
2160
if ( ! class_exists( 'WP_List_Table' ) ) {
2161
	require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
2162
}
2163
2164
if ( ! class_exists( 'TGMPA_List_Table' ) ) {
2165
2166
	/**
2167
	 * List table class for handling plugins.
2168
	 *
2169
	 * Extends the WP_List_Table class to provide a future-compatible
2170
	 * way of listing out all required/recommended plugins.
2171
	 *
2172
	 * Gives users an interface similar to the Plugin Administration
2173
	 * area with similar (albeit stripped down) capabilities.
2174
	 *
2175
	 * This class also allows for the bulk install of plugins.
2176
	 *
2177
	 * @since 2.2.0
2178
	 *
2179
	 * @package TGM-Plugin-Activation
2180
	 * @author  Thomas Griffin
2181
	 * @author  Gary Jones
2182
	 */
2183
	class TGMPA_List_Table extends WP_List_Table {
2184
		/**
2185
		 * TGMPA instance.
2186
		 *
2187
		 * @since 2.5.0
2188
		 *
2189
		 * @var object
2190
		 */
2191
		protected $tgmpa;
2192
2193
		/**
2194
		 * The currently chosen view.
2195
		 *
2196
		 * @since 2.5.0
2197
		 *
2198
		 * @var string One of: 'all', 'install', 'update', 'activate'
2199
		 */
2200
		public $view_context = 'all';
2201
2202
		/**
2203
		 * The plugin counts for the various views.
2204
		 *
2205
		 * @since 2.5.0
2206
		 *
2207
		 * @var array
2208
		 */
2209
		protected $view_totals = array(
2210
			'all'      => 0,
2211
			'install'  => 0,
2212
			'update'   => 0,
2213
			'activate' => 0,
2214
		);
2215
2216
		/**
2217
		 * References parent constructor and sets defaults for class.
2218
		 *
2219
		 * @since 2.2.0
2220
		 */
2221
		public function __construct() {
2222
			$this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
2223
2224
			parent::__construct(
2225
				array(
2226
					'singular' => 'plugin',
2227
					'plural'   => 'plugins',
2228
					'ajax'     => false,
2229
				)
2230
			);
2231
2232
			if ( isset( $_REQUEST['plugin_status'] ) && in_array( $_REQUEST['plugin_status'], array( 'install', 'update', 'activate' ), true ) ) {
2233
				$this->view_context = sanitize_key( $_REQUEST['plugin_status'] );
2234
			}
2235
2236
			add_filter( 'tgmpa_table_data_items', array( $this, 'sort_table_items' ) );
2237
		}
2238
2239
		/**
2240
		 * Get a list of CSS classes for the <table> tag.
2241
		 *
2242
		 * Overruled to prevent the 'plural' argument from being added.
2243
		 *
2244
		 * @since 2.5.0
2245
		 *
2246
		 * @return array CSS classnames.
2247
		 */
2248
		public function get_table_classes() {
2249
			return array( 'widefat', 'fixed' );
2250
		}
2251
2252
		/**
2253
		 * Gathers and renames all of our plugin information to be used by WP_List_Table to create our table.
2254
		 *
2255
		 * @since 2.2.0
2256
		 *
2257
		 * @return array $table_data Information for use in table.
2258
		 */
2259
		protected function _gather_plugin_data() {
2260
			// Load thickbox for plugin links.
2261
			$this->tgmpa->admin_init();
2262
			$this->tgmpa->thickbox();
2263
2264
			// Categorize the plugins which have open actions.
2265
			$plugins = $this->categorize_plugins_to_views();
2266
2267
			// Set the counts for the view links.
2268
			$this->set_view_totals( $plugins );
2269
2270
			// Prep variables for use and grab list of all installed plugins.
2271
			$table_data = array();
2272
			$i          = 0;
2273
2274
			// Redirect to the 'all' view if no plugins were found for the selected view context.
2275
			if ( empty( $plugins[ $this->view_context ] ) ) {
2276
				$this->view_context = 'all';
2277
			}
2278
2279
			foreach ( $plugins[ $this->view_context ] as $slug => $plugin ) {
2280
				$table_data[ $i ]['sanitized_plugin']  = $plugin['name'];
2281
				$table_data[ $i ]['slug']              = $slug;
2282
				$table_data[ $i ]['plugin']            = '<strong>' . $this->tgmpa->get_info_link( $slug ) . '</strong>';
2283
				$table_data[ $i ]['source']            = $this->get_plugin_source_type_text( $plugin['source_type'] );
2284
				$table_data[ $i ]['type']              = $this->get_plugin_advise_type_text( $plugin['required'] );
2285
				$table_data[ $i ]['status']            = $this->get_plugin_status_text( $slug );
2286
				$table_data[ $i ]['installed_version'] = $this->tgmpa->get_installed_version( $slug );
2287
				$table_data[ $i ]['minimum_version']   = $plugin['version'];
2288
				$table_data[ $i ]['available_version'] = $this->tgmpa->does_plugin_have_update( $slug );
2289
2290
				// Prep the upgrade notice info.
2291
				$upgrade_notice = $this->tgmpa->get_upgrade_notice( $slug );
2292
				if ( ! empty( $upgrade_notice ) ) {
2293
					$table_data[ $i ]['upgrade_notice'] = $upgrade_notice;
2294
2295
					add_action( "tgmpa_after_plugin_row_$slug", array( $this, 'wp_plugin_update_row' ), 10, 2 );
2296
				}
2297
2298
				$table_data[ $i ] = apply_filters( 'tgmpa_table_data_item', $table_data[ $i ], $plugin );
2299
2300
				$i++;
2301
			}
2302
2303
			return $table_data;
2304
		}
2305
2306
		/**
2307
		 * Categorize the plugins which have open actions into views for the TGMPA page.
2308
		 *
2309
		 * @since 2.5.0
2310
		 */
2311
		protected function categorize_plugins_to_views() {
2312
			$plugins = array(
2313
				'all'      => array(), // Meaning: all plugins which still have open actions.
2314
				'install'  => array(),
2315
				'update'   => array(),
2316
				'activate' => array(),
2317
			);
2318
2319
			foreach ( $this->tgmpa->plugins as $slug => $plugin ) {
2320
				if ( $this->tgmpa->is_plugin_active( $slug ) && false === $this->tgmpa->does_plugin_have_update( $slug ) ) {
2321
					// No need to display plugins if they are installed, up-to-date and active.
2322
					continue;
2323
				} else {
2324
					$plugins['all'][ $slug ] = $plugin;
2325
2326
					if ( ! $this->tgmpa->is_plugin_installed( $slug ) ) {
2327
						$plugins['install'][ $slug ] = $plugin;
2328
					} else {
2329
						if ( false !== $this->tgmpa->does_plugin_have_update( $slug ) ) {
2330
							$plugins['update'][ $slug ] = $plugin;
2331
						}
2332
2333
						if ( $this->tgmpa->can_plugin_activate( $slug ) ) {
2334
							$plugins['activate'][ $slug ] = $plugin;
2335
						}
2336
					}
2337
				}
2338
			}
2339
2340
			return $plugins;
2341
		}
2342
2343
		/**
2344
		 * Set the counts for the view links.
2345
		 *
2346
		 * @since 2.5.0
2347
		 *
2348
		 * @param array $plugins Plugins order by view.
2349
		 */
2350
		protected function set_view_totals( $plugins ) {
2351
			foreach ( $plugins as $type => $list ) {
2352
				$this->view_totals[ $type ] = count( $list );
2353
			}
2354
		}
2355
2356
		/**
2357
		 * Get the plugin required/recommended text string.
2358
		 *
2359
		 * @since 2.5.0
2360
		 *
2361
		 * @param string $required Plugin required setting.
2362
		 * @return string
2363
		 */
2364
		protected function get_plugin_advise_type_text( $required ) {
2365
			if ( true === $required ) {
2366
				return __( 'Required', 'tgmpa' );
2367
			}
2368
2369
			return __( 'Recommended', 'tgmpa' );
2370
		}
2371
2372
		/**
2373
		 * Get the plugin source type text string.
2374
		 *
2375
		 * @since 2.5.0
2376
		 *
2377
		 * @param string $type Plugin type.
2378
		 * @return string
2379
		 */
2380
		protected function get_plugin_source_type_text( $type ) {
2381
			$string = '';
2382
2383
			switch ( $type ) {
2384
				case 'repo':
2385
					$string = __( 'WordPress Repository', 'tgmpa' );
2386
					break;
2387
				case 'external':
2388
					$string = __( 'External Source', 'tgmpa' );
2389
					break;
2390
				case 'bundled':
2391
					$string = __( 'Pre-Packaged', 'tgmpa' );
2392
					break;
2393
			}
2394
2395
			return $string;
2396
		}
2397
2398
		/**
2399
		 * Determine the plugin status message.
2400
		 *
2401
		 * @since 2.5.0
2402
		 *
2403
		 * @param string $slug Plugin slug.
2404
		 * @return string
2405
		 */
2406
		protected function get_plugin_status_text( $slug ) {
2407
			if ( ! $this->tgmpa->is_plugin_installed( $slug ) ) {
2408
				return __( 'Not Installed', 'tgmpa' );
2409
			}
2410
2411
			if ( ! $this->tgmpa->is_plugin_active( $slug ) ) {
2412
				$install_status = __( 'Installed But Not Activated', 'tgmpa' );
2413
			} else {
2414
				$install_status = __( 'Active', 'tgmpa' );
2415
			}
2416
2417
			$update_status = '';
2418
2419
			if ( $this->tgmpa->does_plugin_require_update( $slug ) && false === $this->tgmpa->does_plugin_have_update( $slug ) ) {
2420
				$update_status = __( 'Required Update not Available', 'tgmpa' );
2421
2422
			} elseif ( $this->tgmpa->does_plugin_require_update( $slug ) ) {
2423
				$update_status = __( 'Requires Update', 'tgmpa' );
2424
2425
			} elseif ( false !== $this->tgmpa->does_plugin_have_update( $slug ) ) {
2426
				$update_status = __( 'Update recommended', 'tgmpa' );
2427
			}
2428
2429
			if ( '' === $update_status ) {
2430
				return $install_status;
2431
			}
2432
2433
			return sprintf(
2434
				/* translators: 1: install status, 2: update status */
2435
				_x( '%1$s, %2$s', 'Install/Update Status', 'tgmpa' ),
2436
				$install_status,
2437
				$update_status
2438
			);
2439
		}
2440
2441
		/**
2442
		 * Sort plugins by Required/Recommended type and by alphabetical plugin name within each type.
2443
		 *
2444
		 * @since 2.5.0
2445
		 *
2446
		 * @param array $items Prepared table items.
2447
		 * @return array Sorted table items.
2448
		 */
2449
		public function sort_table_items( $items ) {
2450
			$type = array();
2451
			$name = array();
2452
2453
			foreach ( $items as $i => $plugin ) {
2454
				$type[ $i ] = $plugin['type']; // Required / recommended.
2455
				$name[ $i ] = $plugin['sanitized_plugin'];
2456
			}
2457
2458
			array_multisort( $type, SORT_DESC, $name, SORT_ASC, $items );
2459
2460
			return $items;
2461
		}
2462
2463
		/**
2464
		 * Get an associative array ( id => link ) of the views available on this table.
2465
		 *
2466
		 * @since 2.5.0
2467
		 *
2468
		 * @return array
2469
		 */
2470
		public function get_views() {
2471
			$status_links = array();
2472
2473
			foreach ( $this->view_totals as $type => $count ) {
2474
				if ( $count < 1 ) {
2475
					continue;
2476
				}
2477
2478
				switch ( $type ) {
2479
					case 'all':
2480
						/* translators: 1: number of plugins. */
2481
						$text = _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $count, 'plugins', 'tgmpa' );
2482
						break;
2483
					case 'install':
2484
						/* translators: 1: number of plugins. */
2485
						$text = _n( 'To Install <span class="count">(%s)</span>', 'To Install <span class="count">(%s)</span>', $count, 'tgmpa' );
2486
						break;
2487
					case 'update':
2488
						/* translators: 1: number of plugins. */
2489
						$text = _n( 'Update Available <span class="count">(%s)</span>', 'Update Available <span class="count">(%s)</span>', $count, 'tgmpa' );
2490
						break;
2491
					case 'activate':
2492
						/* translators: 1: number of plugins. */
2493
						$text = _n( 'To Activate <span class="count">(%s)</span>', 'To Activate <span class="count">(%s)</span>', $count, 'tgmpa' );
2494
						break;
2495
					default:
2496
						$text = '';
2497
						break;
2498
				}
2499
2500
				if ( ! empty( $text ) ) {
2501
2502
					$status_links[ $type ] = sprintf(
2503
						'<a href="%s"%s>%s</a>',
2504
						esc_url( $this->tgmpa->get_tgmpa_status_url( $type ) ),
2505
						( $type === $this->view_context ) ? ' class="current"' : '',
2506
						sprintf( $text, number_format_i18n( $count ) )
2507
					);
2508
				}
2509
			}
2510
2511
			return $status_links;
2512
		}
2513
2514
		/**
2515
		 * Create default columns to display important plugin information
2516
		 * like type, action and status.
2517
		 *
2518
		 * @since 2.2.0
2519
		 *
2520
		 * @param array  $item        Array of item data.
2521
		 * @param string $column_name The name of the column.
2522
		 * @return string
2523
		 */
2524
		public function column_default( $item, $column_name ) {
2525
			return $item[ $column_name ];
2526
		}
2527
2528
		/**
2529
		 * Required for bulk installing.
2530
		 *
2531
		 * Adds a checkbox for each plugin.
2532
		 *
2533
		 * @since 2.2.0
2534
		 *
2535
		 * @param array $item Array of item data.
2536
		 * @return string The input checkbox with all necessary info.
2537
		 */
2538
		public function column_cb( $item ) {
2539
			return sprintf(
2540
				'<input type="checkbox" name="%1$s[]" value="%2$s" id="%3$s" />',
2541
				esc_attr( $this->_args['singular'] ),
2542
				esc_attr( $item['slug'] ),
2543
				esc_attr( $item['sanitized_plugin'] )
2544
			);
2545
		}
2546
2547
		/**
2548
		 * Create default title column along with the action links.
2549
		 *
2550
		 * @since 2.2.0
2551
		 *
2552
		 * @param array $item Array of item data.
2553
		 * @return string The plugin name and action links.
2554
		 */
2555
		public function column_plugin( $item ) {
2556
			return sprintf(
2557
				'%1$s %2$s',
2558
				$item['plugin'],
2559
				$this->row_actions( $this->get_row_actions( $item ), true )
2560
			);
2561
		}
2562
2563
		/**
2564
		 * Create version information column.
2565
		 *
2566
		 * @since 2.5.0
2567
		 *
2568
		 * @param array $item Array of item data.
2569
		 * @return string HTML-formatted version information.
2570
		 */
2571
		public function column_version( $item ) {
2572
			$output = array();
2573
2574
			if ( $this->tgmpa->is_plugin_installed( $item['slug'] ) ) {
2575
				$installed = ! empty( $item['installed_version'] ) ? $item['installed_version'] : _x( 'unknown', 'as in: "version nr unknown"', 'tgmpa' );
2576
2577
				$color = '';
2578
				if ( ! empty( $item['minimum_version'] ) && $this->tgmpa->does_plugin_require_update( $item['slug'] ) ) {
2579
					$color = ' color: #ff0000; font-weight: bold;';
2580
				}
2581
2582
				$output[] = sprintf(
2583
					'<p><span style="min-width: 32px; text-align: right; float: right;%1$s">%2$s</span>' . __( 'Installed version:', 'tgmpa' ) . '</p>',
2584
					$color,
2585
					$installed
2586
				);
2587
			}
2588
2589
			if ( ! empty( $item['minimum_version'] ) ) {
2590
				$output[] = sprintf(
2591
					'<p><span style="min-width: 32px; text-align: right; float: right;">%1$s</span>' . __( 'Minimum required version:', 'tgmpa' ) . '</p>',
2592
					$item['minimum_version']
2593
				);
2594
			}
2595
2596
			if ( ! empty( $item['available_version'] ) ) {
2597
				$color = '';
2598
				if ( ! empty( $item['minimum_version'] ) && version_compare( $item['available_version'], $item['minimum_version'], '>=' ) ) {
2599
					$color = ' color: #71C671; font-weight: bold;';
2600
				}
2601
2602
				$output[] = sprintf(
2603
					'<p><span style="min-width: 32px; text-align: right; float: right;%1$s">%2$s</span>' . __( 'Available version:', 'tgmpa' ) . '</p>',
2604
					$color,
2605
					$item['available_version']
2606
				);
2607
			}
2608
2609
			if ( empty( $output ) ) {
2610
				return '&nbsp;'; // Let's not break the table layout.
2611
			} else {
2612
				return implode( "\n", $output );
2613
			}
2614
		}
2615
2616
		/**
2617
		 * Sets default message within the plugins table if no plugins
2618
		 * are left for interaction.
2619
		 *
2620
		 * Hides the menu item to prevent the user from clicking and
2621
		 * getting a permissions error.
2622
		 *
2623
		 * @since 2.2.0
2624
		 */
2625
		public function no_items() {
2626
			echo esc_html__( 'No plugins to install, update or activate.', 'tgmpa' ) . ' <a href="' . esc_url( self_admin_url() ) . '"> ' . esc_html__( 'Return to the Dashboard', 'tgmpa' ) . '</a>';
2627
			echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>';
2628
		}
2629
2630
		/**
2631
		 * Output all the column information within the table.
2632
		 *
2633
		 * @since 2.2.0
2634
		 *
2635
		 * @return array $columns The column names.
2636
		 */
2637
		public function get_columns() {
2638
			$columns = array(
2639
				'cb'     => '<input type="checkbox" />',
2640
				'plugin' => __( 'Plugin', 'tgmpa' ),
2641
				'source' => __( 'Source', 'tgmpa' ),
2642
				'type'   => __( 'Type', 'tgmpa' ),
2643
			);
2644
2645
			if ( 'all' === $this->view_context || 'update' === $this->view_context ) {
2646
				$columns['version'] = __( 'Version', 'tgmpa' );
2647
				$columns['status']  = __( 'Status', 'tgmpa' );
2648
			}
2649
2650
			return apply_filters( 'tgmpa_table_columns', $columns );
2651
		}
2652
2653
		/**
2654
		 * Get name of default primary column
2655
		 *
2656
		 * @since 2.5.0 / WP 4.3+ compatibility
2657
		 * @access protected
2658
		 *
2659
		 * @return string
2660
		 */
2661
		protected function get_default_primary_column_name() {
2662
			return 'plugin';
2663
		}
2664
2665
		/**
2666
		 * Get the name of the primary column.
2667
		 *
2668
		 * @since 2.5.0 / WP 4.3+ compatibility
2669
		 * @access protected
2670
		 *
2671
		 * @return string The name of the primary column.
2672
		 */
2673
		protected function get_primary_column_name() {
2674
			if ( method_exists( 'WP_List_Table', 'get_primary_column_name' ) ) {
2675
				return parent::get_primary_column_name();
2676
			} else {
2677
				return $this->get_default_primary_column_name();
2678
			}
2679
		}
2680
2681
		/**
2682
		 * Get the actions which are relevant for a specific plugin row.
2683
		 *
2684
		 * @since 2.5.0
2685
		 *
2686
		 * @param array $item Array of item data.
2687
		 * @return array Array with relevant action links.
2688
		 */
2689
		protected function get_row_actions( $item ) {
2690
			$actions      = array();
2691
			$action_links = array();
2692
2693
			// Display the 'Install' action link if the plugin is not yet available.
2694
			if ( ! $this->tgmpa->is_plugin_installed( $item['slug'] ) ) {
2695
				/* translators: %s: plugin name in screen reader markup */
2696
				$actions['install'] = __( 'Install %s', 'tgmpa' );
2697
			} else {
2698
				// Display the 'Update' action link if an update is available and WP complies with plugin minimum.
2699
				if ( false !== $this->tgmpa->does_plugin_have_update( $item['slug'] ) && $this->tgmpa->can_plugin_update( $item['slug'] ) ) {
2700
					/* translators: %s: plugin name in screen reader markup */
2701
					$actions['update'] = __( 'Update %s', 'tgmpa' );
2702
				}
2703
2704
				// Display the 'Activate' action link, but only if the plugin meets the minimum version.
2705
				if ( $this->tgmpa->can_plugin_activate( $item['slug'] ) ) {
2706
					/* translators: %s: plugin name in screen reader markup */
2707
					$actions['activate'] = __( 'Activate %s', 'tgmpa' );
2708
				}
2709
			}
2710
2711
			// Create the actual links.
2712
			foreach ( $actions as $action => $text ) {
2713
				$nonce_url = wp_nonce_url(
2714
					add_query_arg(
2715
						array(
2716
							'plugin'           => urlencode( $item['slug'] ),
2717
							'tgmpa-' . $action => $action . '-plugin',
2718
						),
2719
						$this->tgmpa->get_tgmpa_url()
2720
					),
2721
					'tgmpa-' . $action,
2722
					'tgmpa-nonce'
2723
				);
2724
2725
				$action_links[ $action ] = sprintf(
2726
					'<a href="%1$s">' . esc_html( $text ) . '</a>',
2727
					esc_url( $nonce_url ),
2728
					'<span class="screen-reader-text">' . esc_html( $item['sanitized_plugin'] ) . '</span>'
2729
				);
2730
			}
2731
2732
			$prefix = ( defined( 'WP_NETWORK_ADMIN' ) && WP_NETWORK_ADMIN ) ? 'network_admin_' : '';
2733
			return apply_filters( "tgmpa_{$prefix}plugin_action_links", array_filter( $action_links ), $item['slug'], $item, $this->view_context );
2734
		}
2735
2736
		/**
2737
		 * Generates content for a single row of the table.
2738
		 *
2739
		 * @since 2.5.0
2740
		 *
2741
		 * @param object $item The current item.
2742
		 */
2743
		public function single_row( $item ) {
2744
			parent::single_row( $item );
2745
2746
			/**
2747
			 * Fires after each specific row in the TGMPA Plugins list table.
2748
			 *
2749
			 * The dynamic portion of the hook name, `$item['slug']`, refers to the slug
2750
			 * for the plugin.
2751
			 *
2752
			 * @since 2.5.0
2753
			 */
2754
			do_action( "tgmpa_after_plugin_row_{$item['slug']}", $item['slug'], $item, $this->view_context );
2755
		}
2756
2757
		/**
2758
		 * Show the upgrade notice below a plugin row if there is one.
2759
		 *
2760
		 * @since 2.5.0
2761
		 *
2762
		 * @see /wp-admin/includes/update.php
2763
		 *
2764
		 * @param string $slug Plugin slug.
2765
		 * @param array  $item The information available in this table row.
2766
		 * @return null Return early if upgrade notice is empty.
2767
		 */
2768
		public function wp_plugin_update_row( $slug, $item ) {
2769
			if ( empty( $item['upgrade_notice'] ) ) {
2770
				return;
2771
			}
2772
2773
			echo '
2774
				<tr class="plugin-update-tr">
2775
					<td colspan="', absint( $this->get_column_count() ), '" class="plugin-update colspanchange">
2776
						<div class="update-message">',
2777
							esc_html__( 'Upgrade message from the plugin author:', 'tgmpa' ),
2778
							' <strong>', wp_kses_data( $item['upgrade_notice'] ), '</strong>
2779
						</div>
2780
					</td>
2781
				</tr>';
2782
		}
2783
2784
		/**
2785
		 * Extra controls to be displayed between bulk actions and pagination.
2786
		 *
2787
		 * @since 2.5.0
2788
		 *
2789
		 * @param string $which 'top' or 'bottom' table navigation.
2790
		 */
2791
		public function extra_tablenav( $which ) {
2792
			if ( 'bottom' === $which ) {
2793
				$this->tgmpa->show_tgmpa_version();
2794
			}
2795
		}
2796
2797
		/**
2798
		 * Defines the bulk actions for handling registered plugins.
2799
		 *
2800
		 * @since 2.2.0
2801
		 *
2802
		 * @return array $actions The bulk actions for the plugin install table.
2803
		 */
2804
		public function get_bulk_actions() {
2805
2806
			$actions = array();
2807
2808
			if ( 'update' !== $this->view_context && 'activate' !== $this->view_context ) {
2809
				if ( current_user_can( 'install_plugins' ) ) {
2810
					$actions['tgmpa-bulk-install'] = __( 'Install', 'tgmpa' );
2811
				}
2812
			}
2813
2814
			if ( 'install' !== $this->view_context ) {
2815
				if ( current_user_can( 'update_plugins' ) ) {
2816
					$actions['tgmpa-bulk-update'] = __( 'Update', 'tgmpa' );
2817
				}
2818
				if ( current_user_can( 'activate_plugins' ) ) {
2819
					$actions['tgmpa-bulk-activate'] = __( 'Activate', 'tgmpa' );
2820
				}
2821
			}
2822
2823
			return $actions;
2824
		}
2825
2826
		/**
2827
		 * Processes bulk installation and activation actions.
2828
		 *
2829
		 * The bulk installation process looks for the $_POST information and passes that
2830
		 * through if a user has to use WP_Filesystem to enter their credentials.
2831
		 *
2832
		 * @since 2.2.0
2833
		 */
2834
		public function process_bulk_actions() {
2835
			// Bulk installation process.
2836
			if ( 'tgmpa-bulk-install' === $this->current_action() || 'tgmpa-bulk-update' === $this->current_action() ) {
2837
2838
				check_admin_referer( 'bulk-' . $this->_args['plural'] );
2839
2840
				$install_type = 'install';
2841
				if ( 'tgmpa-bulk-update' === $this->current_action() ) {
2842
					$install_type = 'update';
2843
				}
2844
2845
				$plugins_to_install = array();
2846
2847
				// Did user actually select any plugins to install/update ?
2848 View Code Duplication
				if ( empty( $_POST['plugin'] ) ) {
2849
					if ( 'install' === $install_type ) {
2850
						$message = __( 'No plugins were selected to be installed. No action taken.', 'tgmpa' );
2851
					} else {
2852
						$message = __( 'No plugins were selected to be updated. No action taken.', 'tgmpa' );
2853
					}
2854
2855
					echo '<div id="message" class="error"><p>', esc_html( $message ), '</p></div>';
2856
2857
					return false;
2858
				}
2859
2860
				if ( is_array( $_POST['plugin'] ) ) {
2861
					$plugins_to_install = (array) $_POST['plugin'];
2862
				} elseif ( is_string( $_POST['plugin'] ) ) {
2863
					// Received via Filesystem page - un-flatten array (WP bug #19643).
2864
					$plugins_to_install = explode( ',', $_POST['plugin'] );
2865
				}
2866
2867
				// Sanitize the received input.
2868
				$plugins_to_install = array_map( 'urldecode', $plugins_to_install );
2869
				$plugins_to_install = array_map( array( $this->tgmpa, 'sanitize_key' ), $plugins_to_install );
2870
2871
				// Validate the received input.
2872
				foreach ( $plugins_to_install as $key => $slug ) {
2873
					// Check if the plugin was registered with TGMPA and remove if not.
2874
					if ( ! isset( $this->tgmpa->plugins[ $slug ] ) ) {
2875
						unset( $plugins_to_install[ $key ] );
2876
						continue;
2877
					}
2878
2879
					// For install: make sure this is a plugin we *can* install and not one already installed.
2880
					if ( 'install' === $install_type && true === $this->tgmpa->is_plugin_installed( $slug ) ) {
2881
						unset( $plugins_to_install[ $key ] );
2882
					}
2883
2884
					// For updates: make sure this is a plugin we *can* update (update available and WP version ok).
2885
					if ( 'update' === $install_type && false === $this->tgmpa->is_plugin_updatetable( $slug ) ) {
2886
						unset( $plugins_to_install[ $key ] );
2887
					}
2888
				}
2889
2890
				// No need to proceed further if we have no plugins to handle.
2891 View Code Duplication
				if ( empty( $plugins_to_install ) ) {
2892
					if ( 'install' === $install_type ) {
2893
						$message = __( 'No plugins are available to be installed at this time.', 'tgmpa' );
2894
					} else {
2895
						$message = __( 'No plugins are available to be updated at this time.', 'tgmpa' );
2896
					}
2897
2898
					echo '<div id="message" class="error"><p>', esc_html( $message ), '</p></div>';
2899
2900
					return false;
2901
				}
2902
2903
				// Pass all necessary information if WP_Filesystem is needed.
2904
				$url = wp_nonce_url(
2905
					$this->tgmpa->get_tgmpa_url(),
2906
					'bulk-' . $this->_args['plural']
2907
				);
2908
2909
				// Give validated data back to $_POST which is the only place the filesystem looks for extra fields.
2910
				$_POST['plugin'] = implode( ',', $plugins_to_install ); // Work around for WP bug #19643.
2911
2912
				$method = ''; // Leave blank so WP_Filesystem can populate it as necessary.
2913
				$fields = array_keys( $_POST ); // Extra fields to pass to WP_Filesystem.
2914
2915 View Code Duplication
				if ( false === ( $creds = request_filesystem_credentials( esc_url_raw( $url ), $method, false, false, $fields ) ) ) {
2916
					return true; // Stop the normal page form from displaying, credential request form will be shown.
2917
				}
2918
2919
				// Now we have some credentials, setup WP_Filesystem.
2920 View Code Duplication
				if ( ! WP_Filesystem( $creds ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
2921
					// Our credentials were no good, ask the user for them again.
2922
					request_filesystem_credentials( esc_url_raw( $url ), $method, true, false, $fields );
2923
2924
					return true;
2925
				}
2926
2927
				/* If we arrive here, we have the filesystem */
2928
2929
				// Store all information in arrays since we are processing a bulk installation.
2930
				$names      = array();
2931
				$sources    = array(); // Needed for installs.
2932
				$file_paths = array(); // Needed for upgrades.
2933
				$to_inject  = array(); // Information to inject into the update_plugins transient.
2934
2935
				// Prepare the data for validated plugins for the install/upgrade.
2936
				foreach ( $plugins_to_install as $slug ) {
2937
					$name   = $this->tgmpa->plugins[ $slug ]['name'];
2938
					$source = $this->tgmpa->get_download_url( $slug );
2939
2940
					if ( ! empty( $name ) && ! empty( $source ) ) {
2941
						$names[] = $name;
2942
2943
						switch ( $install_type ) {
2944
2945
							case 'install':
2946
								$sources[] = $source;
2947
								break;
2948
2949
							case 'update':
2950
								$file_paths[]                 = $this->tgmpa->plugins[ $slug ]['file_path'];
2951
								$to_inject[ $slug ]           = $this->tgmpa->plugins[ $slug ];
2952
								$to_inject[ $slug ]['source'] = $source;
2953
								break;
2954
						}
2955
					}
2956
				}
2957
				unset( $slug, $name, $source );
2958
2959
				// Create a new instance of TGMPA_Bulk_Installer.
2960
				$installer = new TGMPA_Bulk_Installer(
2961
					new TGMPA_Bulk_Installer_Skin(
2962
						array(
2963
							'url'          => esc_url_raw( $this->tgmpa->get_tgmpa_url() ),
2964
							'nonce'        => 'bulk-' . $this->_args['plural'],
2965
							'names'        => $names,
2966
							'install_type' => $install_type,
2967
						)
2968
					)
2969
				);
2970
2971
				// Wrap the install process with the appropriate HTML.
2972
				echo '<div class="tgmpa">',
2973
					'<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>
2974
					<div class="update-php" style="width: 100%; height: 98%; min-height: 850px; padding-top: 1px;">';
2975
2976
				// Process the bulk installation submissions.
2977
				add_filter( 'upgrader_source_selection', array( $this->tgmpa, 'maybe_adjust_source_dir' ), 1, 3 );
2978
2979
				if ( 'tgmpa-bulk-update' === $this->current_action() ) {
2980
					// Inject our info into the update transient.
2981
					$this->tgmpa->inject_update_info( $to_inject );
2982
2983
					$installer->bulk_upgrade( $file_paths );
2984
				} else {
2985
					$installer->bulk_install( $sources );
2986
				}
2987
2988
				remove_filter( 'upgrader_source_selection', array( $this->tgmpa, 'maybe_adjust_source_dir' ), 1 );
2989
2990
				echo '</div></div>';
2991
2992
				return true;
2993
			}
2994
2995
			// Bulk activation process.
2996
			if ( 'tgmpa-bulk-activate' === $this->current_action() ) {
2997
				check_admin_referer( 'bulk-' . $this->_args['plural'] );
2998
2999
				// Did user actually select any plugins to activate ?
3000
				if ( empty( $_POST['plugin'] ) ) {
3001
					echo '<div id="message" class="error"><p>', esc_html__( 'No plugins were selected to be activated. No action taken.', 'tgmpa' ), '</p></div>';
3002
3003
					return false;
3004
				}
3005
3006
				// Grab plugin data from $_POST.
3007
				$plugins = array();
3008
				if ( isset( $_POST['plugin'] ) ) {
3009
					$plugins = array_map( 'urldecode', (array) $_POST['plugin'] );
3010
					$plugins = array_map( array( $this->tgmpa, 'sanitize_key' ), $plugins );
3011
				}
3012
3013
				$plugins_to_activate = array();
3014
				$plugin_names        = array();
3015
3016
				// Grab the file paths for the selected & inactive plugins from the registration array.
3017
				foreach ( $plugins as $slug ) {
3018
					if ( $this->tgmpa->can_plugin_activate( $slug ) ) {
3019
						$plugins_to_activate[] = $this->tgmpa->plugins[ $slug ]['file_path'];
3020
						$plugin_names[]        = $this->tgmpa->plugins[ $slug ]['name'];
3021
					}
3022
				}
3023
				unset( $slug );
3024
3025
				// Return early if there are no plugins to activate.
3026
				if ( empty( $plugins_to_activate ) ) {
3027
					echo '<div id="message" class="error"><p>', esc_html__( 'No plugins are available to be activated at this time.', 'tgmpa' ), '</p></div>';
3028
3029
					return false;
3030
				}
3031
3032
				// Now we are good to go - let's start activating plugins.
3033
				$activate = activate_plugins( $plugins_to_activate );
3034
3035
				if ( is_wp_error( $activate ) ) {
3036
					echo '<div id="message" class="error"><p>', wp_kses_post( $activate->get_error_message() ), '</p></div>';
3037
				} else {
3038
					$count        = count( $plugin_names ); // Count so we can use _n function.
3039
					$plugin_names = array_map( array( 'TGMPA_Utils', 'wrap_in_strong' ), $plugin_names );
3040
					$last_plugin  = array_pop( $plugin_names ); // Pop off last name to prep for readability.
3041
					$imploded     = empty( $plugin_names ) ? $last_plugin : ( implode( ', ', $plugin_names ) . ' ' . esc_html_x( 'and', 'plugin A *and* plugin B', 'tgmpa' ) . ' ' . $last_plugin );
3042
3043
					printf( // WPCS: xss ok.
3044
						'<div id="message" class="updated"><p>%1$s %2$s.</p></div>',
3045
						esc_html( _n( 'The following plugin was activated successfully:', 'The following plugins were activated successfully:', $count, 'tgmpa' ) ),
3046
						$imploded
3047
					);
3048
3049
					// Update recently activated plugins option.
3050
					$recent = (array) get_option( 'recently_activated' );
3051
					foreach ( $plugins_to_activate as $plugin => $time ) {
3052
						if ( isset( $recent[ $plugin ] ) ) {
3053
							unset( $recent[ $plugin ] );
3054
						}
3055
					}
3056
					update_option( 'recently_activated', $recent );
3057
				}
3058
3059
				unset( $_POST ); // Reset the $_POST variable in case user wants to perform one action after another.
3060
3061
				return true;
3062
			}
3063
3064
			return false;
3065
		}
3066
3067
		/**
3068
		 * Prepares all of our information to be outputted into a usable table.
3069
		 *
3070
		 * @since 2.2.0
3071
		 */
3072
		public function prepare_items() {
3073
			$columns               = $this->get_columns(); // Get all necessary column information.
3074
			$hidden                = array(); // No columns to hide, but we must set as an array.
3075
			$sortable              = array(); // No reason to make sortable columns.
3076
			$primary               = $this->get_primary_column_name(); // Column which has the row actions.
3077
			$this->_column_headers = array( $columns, $hidden, $sortable, $primary ); // Get all necessary column headers.
3078
3079
			// Process our bulk activations here.
3080
			if ( 'tgmpa-bulk-activate' === $this->current_action() ) {
3081
				$this->process_bulk_actions();
3082
			}
3083
3084
			// Store all of our plugin data into $items array so WP_List_Table can use it.
3085
			$this->items = apply_filters( 'tgmpa_table_data_items', $this->_gather_plugin_data() );
3086
		}
3087
3088
		/* *********** DEPRECATED METHODS *********** */
3089
3090
		/**
3091
		 * Retrieve plugin data, given the plugin name.
3092
		 *
3093
		 * @since      2.2.0
3094
		 * @deprecated 2.5.0 use {@see TGM_Plugin_Activation::_get_plugin_data_from_name()} instead.
3095
		 * @see        TGM_Plugin_Activation::_get_plugin_data_from_name()
3096
		 *
3097
		 * @param string $name Name of the plugin, as it was registered.
3098
		 * @param string $data Optional. Array key of plugin data to return. Default is slug.
3099
		 * @return string|boolean Plugin slug if found, false otherwise.
3100
		 */
3101
		protected function _get_plugin_data_from_name( $name, $data = 'slug' ) {
3102
			_deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'TGM_Plugin_Activation::_get_plugin_data_from_name()' );
3103
3104
			return $this->tgmpa->_get_plugin_data_from_name( $name, $data );
3105
		}
3106
	}
3107
}
3108
3109
3110
if ( ! class_exists( 'TGM_Bulk_Installer' ) ) {
3111
3112
	/**
3113
	 * Hack: Prevent TGMPA v2.4.1- bulk installer class from being loaded if 2.4.1- is loaded after 2.5+.
3114
	 */
3115
	class TGM_Bulk_Installer {
3116
	}
3117
}
3118
if ( ! class_exists( 'TGM_Bulk_Installer_Skin' ) ) {
3119
3120
	/**
3121
	 * Hack: Prevent TGMPA v2.4.1- bulk installer skin class from being loaded if 2.4.1- is loaded after 2.5+.
3122
	 */
3123
	class TGM_Bulk_Installer_Skin {
3124
	}
3125
}
3126
3127
/**
3128
 * The WP_Upgrader file isn't always available. If it isn't available,
3129
 * we load it here.
3130
 *
3131
 * We check to make sure no action or activation keys are set so that WordPress
3132
 * does not try to re-include the class when processing upgrades or installs outside
3133
 * of the class.
3134
 *
3135
 * @since 2.2.0
3136
 */
3137
add_action( 'admin_init', 'tgmpa_load_bulk_installer' );
3138
if ( ! function_exists( 'tgmpa_load_bulk_installer' ) ) {
3139
	/**
3140
	 * Load bulk installer
3141
	 */
3142
	function tgmpa_load_bulk_installer() {
3143
		// Silently fail if 2.5+ is loaded *after* an older version.
3144
		if ( ! isset( $GLOBALS['tgmpa'] ) ) {
3145
			return;
3146
		}
3147
3148
		// Get TGMPA class instance.
3149
		$tgmpa_instance = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
3150
3151
		if ( isset( $_GET['page'] ) && $tgmpa_instance->menu === $_GET['page'] ) {
3152
			if ( ! class_exists( 'Plugin_Upgrader', false ) ) {
3153
				require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
3154
			}
3155
3156
			if ( ! class_exists( 'TGMPA_Bulk_Installer' ) ) {
3157
3158
				/**
3159
				 * Installer class to handle bulk plugin installations.
3160
				 *
3161
				 * Extends WP_Upgrader and customizes to suit the installation of multiple
3162
				 * plugins.
3163
				 *
3164
				 * @since 2.2.0
3165
				 *
3166
				 * {@internal Since 2.5.0 the class is an extension of Plugin_Upgrader rather than WP_Upgrader.}}
3167
				 * {@internal Since 2.5.2 the class has been renamed from TGM_Bulk_Installer to TGMPA_Bulk_Installer.
3168
				 *            This was done to prevent backward compatibility issues with v2.3.6.}}
3169
				 *
3170
				 * @package TGM-Plugin-Activation
3171
				 * @author  Thomas Griffin
3172
				 * @author  Gary Jones
3173
				 */
3174
				class TGMPA_Bulk_Installer extends Plugin_Upgrader {
3175
					/**
3176
					 * Holds result of bulk plugin installation.
3177
					 *
3178
					 * @since 2.2.0
3179
					 *
3180
					 * @var string
3181
					 */
3182
					public $result;
3183
3184
					/**
3185
					 * Flag to check if bulk installation is occurring or not.
3186
					 *
3187
					 * @since 2.2.0
3188
					 *
3189
					 * @var boolean
3190
					 */
3191
					public $bulk = false;
3192
3193
					/**
3194
					 * TGMPA instance
3195
					 *
3196
					 * @since 2.5.0
3197
					 *
3198
					 * @var object
3199
					 */
3200
					protected $tgmpa;
3201
3202
					/**
3203
					 * Whether or not the destination directory needs to be cleared ( = on update).
3204
					 *
3205
					 * @since 2.5.0
3206
					 *
3207
					 * @var bool
3208
					 */
3209
					protected $clear_destination = false;
3210
3211
					/**
3212
					 * References parent constructor and sets defaults for class.
3213
					 *
3214
					 * @since 2.2.0
3215
					 *
3216
					 * @param \Bulk_Upgrader_Skin|null $skin Installer skin.
3217
					 */
3218
					public function __construct( $skin = null ) {
3219
						// Get TGMPA class instance.
3220
						$this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
3221
3222
						parent::__construct( $skin );
3223
3224
						if ( isset( $this->skin->options['install_type'] ) && 'update' === $this->skin->options['install_type'] ) {
3225
							$this->clear_destination = true;
3226
						}
3227
3228
						if ( $this->tgmpa->is_automatic ) {
3229
							$this->activate_strings();
3230
						}
3231
3232
						add_action( 'upgrader_process_complete', array( $this->tgmpa, 'populate_file_path' ) );
3233
					}
3234
3235
					/**
3236
					 * Sets the correct activation strings for the installer skin to use.
3237
					 *
3238
					 * @since 2.2.0
3239
					 */
3240
					public function activate_strings() {
3241
						$this->strings['activation_failed']  = __( 'Plugin activation failed.', 'tgmpa' );
3242
						$this->strings['activation_success'] = __( 'Plugin activated successfully.', 'tgmpa' );
3243
					}
3244
3245
					/**
3246
					 * Performs the actual installation of each plugin.
3247
					 *
3248
					 * @since 2.2.0
3249
					 *
3250
					 * @see WP_Upgrader::run()
3251
					 *
3252
					 * @param array $options The installation config options.
3253
					 * @return null|array Return early if error, array of installation data on success.
3254
					 */
3255
					public function run( $options ) {
3256
						$result = parent::run( $options );
3257
3258
						// Reset the strings in case we changed one during automatic activation.
3259
						if ( $this->tgmpa->is_automatic ) {
3260
							if ( 'update' === $this->skin->options['install_type'] ) {
3261
								$this->upgrade_strings();
3262
							} else {
3263
								$this->install_strings();
3264
							}
3265
						}
3266
3267
						return $result;
3268
					}
3269
3270
					/**
3271
					 * Processes the bulk installation of plugins.
3272
					 *
3273
					 * @since 2.2.0
3274
					 *
3275
					 * {@internal This is basically a near identical copy of the WP Core
3276
					 * Plugin_Upgrader::bulk_upgrade() method, with minor adjustments to deal with
3277
					 * new installs instead of upgrades.
3278
					 * For ease of future synchronizations, the adjustments are clearly commented, but no other
3279
					 * comments are added. Code style has been made to comply.}}
3280
					 *
3281
					 * @see Plugin_Upgrader::bulk_upgrade()
3282
					 * @see https://core.trac.wordpress.org/browser/tags/4.2.1/src/wp-admin/includes/class-wp-upgrader.php#L838
3283
					 * (@internal Last synced: Dec 31st 2015 against https://core.trac.wordpress.org/browser/trunk?rev=36134}}
3284
					 *
3285
					 * @param array $plugins The plugin sources needed for installation.
3286
					 * @param array $args    Arbitrary passed extra arguments.
3287
					 * @return string|bool Install confirmation messages on success, false on failure.
3288
					 */
3289
					public function bulk_install( $plugins, $args = array() ) {
3290
						// [TGMPA + ] Hook auto-activation in.
3291
						add_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3292
3293
						$defaults    = array(
3294
							'clear_update_cache' => true,
3295
						);
3296
						$parsed_args = wp_parse_args( $args, $defaults );
3297
3298
						$this->init();
3299
						$this->bulk = true;
3300
3301
						$this->install_strings(); // [TGMPA + ] adjusted.
3302
3303
						/* [TGMPA - ] $current = get_site_transient( 'update_plugins' ); */
3304
3305
						/* [TGMPA - ] add_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'), 10, 4); */
3306
3307
						$this->skin->header();
3308
3309
						// Connect to the Filesystem first.
3310
						$res = $this->fs_connect( array( WP_CONTENT_DIR, WP_PLUGIN_DIR ) );
3311
						if ( ! $res ) {
3312
							$this->skin->footer();
3313
							return false;
3314
						}
3315
3316
						$this->skin->bulk_header();
3317
3318
						/*
3319
						 * Only start maintenance mode if:
3320
						 * - running Multisite and there are one or more plugins specified, OR
3321
						 * - a plugin with an update available is currently active.
3322
						 * @TODO: For multisite, maintenance mode should only kick in for individual sites if at all possible.
3323
						 */
3324
						$maintenance = ( is_multisite() && ! empty( $plugins ) );
3325
3326
						/*
3327
						[TGMPA - ]
3328
						foreach ( $plugins as $plugin )
3329
							$maintenance = $maintenance || ( is_plugin_active( $plugin ) && isset( $current->response[ $plugin] ) );
3330
						*/
3331
						if ( $maintenance ) {
3332
							$this->maintenance_mode( true );
3333
						}
3334
3335
						$results = array();
3336
3337
						$this->update_count   = count( $plugins );
3338
						$this->update_current = 0;
3339
						foreach ( $plugins as $plugin ) {
3340
							$this->update_current++;
3341
3342
							/*
3343
							[TGMPA - ]
3344
							$this->skin->plugin_info = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin, false, true);
3345
3346
							if ( !isset( $current->response[ $plugin ] ) ) {
3347
								$this->skin->set_result('up_to_date');
3348
								$this->skin->before();
3349
								$this->skin->feedback('up_to_date');
3350
								$this->skin->after();
3351
								$results[$plugin] = true;
3352
								continue;
3353
							}
3354
3355
							// Get the URL to the zip file.
3356
							$r = $current->response[ $plugin ];
3357
3358
							$this->skin->plugin_active = is_plugin_active($plugin);
3359
							*/
3360
3361
							$result = $this->run(
3362
								array(
3363
									'package'           => $plugin, // [TGMPA + ] adjusted.
3364
									'destination'       => WP_PLUGIN_DIR,
3365
									'clear_destination' => false, // [TGMPA + ] adjusted.
3366
									'clear_working'     => true,
3367
									'is_multi'          => true,
3368
									'hook_extra'        => array(
3369
										'plugin' => $plugin,
3370
									),
3371
								)
3372
							);
3373
3374
							$results[ $plugin ] = $this->result;
3375
3376
							// Prevent credentials auth screen from displaying multiple times.
3377
							if ( false === $result ) {
3378
								break;
3379
							}
3380
						} //end foreach $plugins
3381
3382
						$this->maintenance_mode( false );
3383
3384
						/**
3385
						 * Fires when the bulk upgrader process is complete.
3386
						 *
3387
						 * @since WP 3.6.0 / TGMPA 2.5.0
3388
						 *
3389
						 * @param Plugin_Upgrader $this Plugin_Upgrader instance. In other contexts, $this, might
3390
						 *                              be a Theme_Upgrader or Core_Upgrade instance.
3391
						 * @param array           $data {
3392
						 *     Array of bulk item update data.
3393
						 *
3394
						 *     @type string $action   Type of action. Default 'update'.
3395
						 *     @type string $type     Type of update process. Accepts 'plugin', 'theme', or 'core'.
3396
						 *     @type bool   $bulk     Whether the update process is a bulk update. Default true.
3397
						 *     @type array  $packages Array of plugin, theme, or core packages to update.
3398
						 * }
3399
						 */
3400
						do_action( 'upgrader_process_complete', $this, array(
3401
							'action'  => 'install', // [TGMPA + ] adjusted.
3402
							'type'    => 'plugin',
3403
							'bulk'    => true,
3404
							'plugins' => $plugins,
3405
						) );
3406
3407
						$this->skin->bulk_footer();
3408
3409
						$this->skin->footer();
3410
3411
						// Cleanup our hooks, in case something else does a upgrade on this connection.
3412
						/* [TGMPA - ] remove_filter('upgrader_clear_destination', array($this, 'delete_old_plugin')); */
3413
3414
						// [TGMPA + ] Remove our auto-activation hook.
3415
						remove_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3416
3417
						// Force refresh of plugin update information.
3418
						wp_clean_plugins_cache( $parsed_args['clear_update_cache'] );
3419
3420
						return $results;
3421
					}
3422
3423
					/**
3424
					 * Handle a bulk upgrade request.
3425
					 *
3426
					 * @since 2.5.0
3427
					 *
3428
					 * @see Plugin_Upgrader::bulk_upgrade()
3429
					 *
3430
					 * @param array $plugins The local WP file_path's of the plugins which should be upgraded.
3431
					 * @param array $args    Arbitrary passed extra arguments.
3432
					 * @return string|bool Install confirmation messages on success, false on failure.
3433
					 */
3434
					public function bulk_upgrade( $plugins, $args = array() ) {
3435
3436
						add_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3437
3438
						$result = parent::bulk_upgrade( $plugins, $args );
3439
3440
						remove_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 );
3441
3442
						return $result;
3443
					}
3444
3445
					/**
3446
					 * Abuse a filter to auto-activate plugins after installation.
3447
					 *
3448
					 * Hooked into the 'upgrader_post_install' filter hook.
3449
					 *
3450
					 * @since 2.5.0
3451
					 *
3452
					 * @param bool $bool The value we need to give back (true).
3453
					 * @return bool
3454
					 */
3455
					public function auto_activate( $bool ) {
3456
						// Only process the activation of installed plugins if the automatic flag is set to true.
3457
						if ( $this->tgmpa->is_automatic ) {
3458
							// Flush plugins cache so the headers of the newly installed plugins will be read correctly.
3459
							wp_clean_plugins_cache();
3460
3461
							// Get the installed plugin file.
3462
							$plugin_info = $this->plugin_info();
3463
3464
							// Don't try to activate on upgrade of active plugin as WP will do this already.
3465
							if ( ! is_plugin_active( $plugin_info ) ) {
3466
								$activate = activate_plugin( $plugin_info );
3467
3468
								// Adjust the success string based on the activation result.
3469
								$this->strings['process_success'] = $this->strings['process_success'] . "<br />\n";
3470
3471
								if ( is_wp_error( $activate ) ) {
3472
									$this->skin->error( $activate );
3473
									$this->strings['process_success'] .= $this->strings['activation_failed'];
3474
								} else {
3475
									$this->strings['process_success'] .= $this->strings['activation_success'];
3476
								}
3477
							}
3478
						}
3479
3480
						return $bool;
3481
					}
3482
				}
3483
			}
3484
3485
			if ( ! class_exists( 'TGMPA_Bulk_Installer_Skin' ) ) {
3486
3487
				/**
3488
				 * Installer skin to set strings for the bulk plugin installations..
3489
				 *
3490
				 * Extends Bulk_Upgrader_Skin and customizes to suit the installation of multiple
3491
				 * plugins.
3492
				 *
3493
				 * @since 2.2.0
3494
				 *
3495
				 * {@internal Since 2.5.2 the class has been renamed from TGM_Bulk_Installer_Skin to
3496
				 *           TGMPA_Bulk_Installer_Skin.
3497
				 *           This was done to prevent backward compatibility issues with v2.3.6.}}
3498
				 *
3499
				 * @see https://core.trac.wordpress.org/browser/trunk/src/wp-admin/includes/class-wp-upgrader-skins.php
3500
				 *
3501
				 * @package TGM-Plugin-Activation
3502
				 * @author  Thomas Griffin
3503
				 * @author  Gary Jones
3504
				 */
3505
				class TGMPA_Bulk_Installer_Skin extends Bulk_Upgrader_Skin {
3506
					/**
3507
					 * Holds plugin info for each individual plugin installation.
3508
					 *
3509
					 * @since 2.2.0
3510
					 *
3511
					 * @var array
3512
					 */
3513
					public $plugin_info = array();
3514
3515
					/**
3516
					 * Holds names of plugins that are undergoing bulk installations.
3517
					 *
3518
					 * @since 2.2.0
3519
					 *
3520
					 * @var array
3521
					 */
3522
					public $plugin_names = array();
3523
3524
					/**
3525
					 * Integer to use for iteration through each plugin installation.
3526
					 *
3527
					 * @since 2.2.0
3528
					 *
3529
					 * @var integer
3530
					 */
3531
					public $i = 0;
3532
3533
					/**
3534
					 * TGMPA instance
3535
					 *
3536
					 * @since 2.5.0
3537
					 *
3538
					 * @var object
3539
					 */
3540
					protected $tgmpa;
3541
3542
					/**
3543
					 * Constructor. Parses default args with new ones and extracts them for use.
3544
					 *
3545
					 * @since 2.2.0
3546
					 *
3547
					 * @param array $args Arguments to pass for use within the class.
3548
					 */
3549
					public function __construct( $args = array() ) {
3550
						// Get TGMPA class instance.
3551
						$this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) );
3552
3553
						// Parse default and new args.
3554
						$defaults = array(
3555
							'url'          => '',
3556
							'nonce'        => '',
3557
							'names'        => array(),
3558
							'install_type' => 'install',
3559
						);
3560
						$args     = wp_parse_args( $args, $defaults );
3561
3562
						// Set plugin names to $this->plugin_names property.
3563
						$this->plugin_names = $args['names'];
3564
3565
						// Extract the new args.
3566
						parent::__construct( $args );
3567
					}
3568
3569
					/**
3570
					 * Sets install skin strings for each individual plugin.
3571
					 *
3572
					 * Checks to see if the automatic activation flag is set and uses the
3573
					 * the proper strings accordingly.
3574
					 *
3575
					 * @since 2.2.0
3576
					 */
3577
					public function add_strings() {
3578
						if ( 'update' === $this->options['install_type'] ) {
3579
							parent::add_strings();
3580
							/* translators: 1: plugin name, 2: action number 3: total number of actions. */
3581
							$this->upgrader->strings['skin_before_update_header'] = __( 'Updating Plugin %1$s (%2$d/%3$d)', 'tgmpa' );
3582
						} else {
3583
							/* translators: 1: plugin name, 2: error message. */
3584
							$this->upgrader->strings['skin_update_failed_error'] = __( 'An error occurred while installing %1$s: <strong>%2$s</strong>.', 'tgmpa' );
3585
							/* translators: 1: plugin name. */
3586
							$this->upgrader->strings['skin_update_failed']       = __( 'The installation of %1$s failed.', 'tgmpa' );
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 7 spaces

This check looks for improperly formatted assignments.

Every assignment must have exactly one space before and one space after the equals operator.

To illustrate:

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

will have no issues, while

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

will report issues in lines 1 and 2.

Loading history...
3587
3588
							if ( $this->tgmpa->is_automatic ) {
3589
								// Automatic activation strings.
3590
								$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' );
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 8 spaces

This check looks for improperly formatted assignments.

Every assignment must have exactly one space before and one space after the equals operator.

To illustrate:

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

will have no issues, while

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

will report issues in lines 1 and 2.

Loading history...
3591
								/* translators: 1: plugin name. */
3592
								$this->upgrader->strings['skin_update_successful']    = __( '%1$s installed and activated successfully.', 'tgmpa' ) . ' <a href="#" class="hide-if-no-js" onclick="%2$s"><span>' . esc_html__( 'Show Details', 'tgmpa' ) . '</span><span class="hidden">' . esc_html__( 'Hide Details', 'tgmpa' ) . '</span>.</a>';
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 1 space but found 4 spaces

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

To visualize

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

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

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

will produce no issues.

Loading history...
3593
								$this->upgrader->strings['skin_upgrade_end']          = __( 'All installations and activations have been completed.', 'tgmpa' );
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 7 spaces but found 10 spaces

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

To visualize

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

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

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

will produce no issues.

Loading history...
3594
								/* translators: 1: plugin name, 2: action number 3: total number of actions. */
3595
								$this->upgrader->strings['skin_before_update_header'] = __( 'Installing and Activating Plugin %1$s (%2$d/%3$d)', 'tgmpa' );
3596
							} else {
3597
								// Default installation strings.
3598
								$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' );
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 8 spaces

This check looks for improperly formatted assignments.

Every assignment must have exactly one space before and one space after the equals operator.

To illustrate:

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

will have no issues, while

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

will report issues in lines 1 and 2.

Loading history...
3599
								/* translators: 1: plugin name. */
3600
								$this->upgrader->strings['skin_update_successful']    = esc_html__( '%1$s installed successfully.', 'tgmpa' ) . ' <a href="#" class="hide-if-no-js" onclick="%2$s"><span>' . esc_html__( 'Show Details', 'tgmpa' ) . '</span><span class="hidden">' . esc_html__( 'Hide Details', 'tgmpa' ) . '</span>.</a>';
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 1 space but found 4 spaces

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

To visualize

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

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

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

will produce no issues.

Loading history...
3601
								$this->upgrader->strings['skin_upgrade_end']          = __( 'All installations have been completed.', 'tgmpa' );
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 7 spaces but found 10 spaces

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

To visualize

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

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

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

will produce no issues.

Loading history...
3602
								/* translators: 1: plugin name, 2: action number 3: total number of actions. */
3603
								$this->upgrader->strings['skin_before_update_header'] = __( 'Installing Plugin %1$s (%2$d/%3$d)', 'tgmpa' );
3604
							}
3605
						}
3606
					}
3607
3608
					/**
3609
					 * Outputs the header strings and necessary JS before each plugin installation.
3610
					 *
3611
					 * @since 2.2.0
3612
					 *
3613
					 * @param string $title Unused in this implementation.
3614
					 */
3615
					public function before( $title = '' ) {
3616
						if ( empty( $title ) ) {
3617
							$title = esc_html( $this->plugin_names[ $this->i ] );
3618
						}
3619
						parent::before( $title );
3620
					}
3621
3622
					/**
3623
					 * Outputs the footer strings and necessary JS after each plugin installation.
3624
					 *
3625
					 * Checks for any errors and outputs them if they exist, else output
3626
					 * success strings.
3627
					 *
3628
					 * @since 2.2.0
3629
					 *
3630
					 * @param string $title Unused in this implementation.
3631
					 */
3632
					public function after( $title = '' ) {
3633
						if ( empty( $title ) ) {
3634
							$title = esc_html( $this->plugin_names[ $this->i ] );
3635
						}
3636
						parent::after( $title );
3637
3638
						$this->i++;
3639
					}
3640
3641
					/**
3642
					 * Outputs links after bulk plugin installation is complete.
3643
					 *
3644
					 * @since 2.2.0
3645
					 */
3646
					public function bulk_footer() {
3647
						// Serve up the string to say installations (and possibly activations) are complete.
3648
						parent::bulk_footer();
3649
3650
						// Flush plugins cache so we can make sure that the installed plugins list is always up to date.
3651
						wp_clean_plugins_cache();
3652
3653
						$this->tgmpa->show_tgmpa_version();
3654
3655
						// Display message based on if all plugins are now active or not.
3656
						$update_actions = array();
3657
3658
						if ( $this->tgmpa->is_tgmpa_complete() ) {
3659
							// All plugins are active, so we display the complete string and hide the menu to protect users.
3660
							echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>';
3661
							$update_actions['dashboard'] = sprintf(
3662
								esc_html( $this->tgmpa->strings['complete'] ),
3663
								'<a href="' . esc_url( self_admin_url() ) . '">' . esc_html__( 'Return to the Dashboard', 'tgmpa' ) . '</a>'
3664
							);
3665
						} else {
3666
							$update_actions['tgmpa_page'] = '<a href="' . esc_url( $this->tgmpa->get_tgmpa_url() ) . '" target="_parent">' . esc_html( $this->tgmpa->strings['return'] ) . '</a>';
3667
						}
3668
3669
						/**
3670
						 * Filter the list of action links available following bulk plugin installs/updates.
3671
						 *
3672
						 * @since 2.5.0
3673
						 *
3674
						 * @param array $update_actions Array of plugin action links.
3675
						 * @param array $plugin_info    Array of information for the last-handled plugin.
3676
						 */
3677
						$update_actions = apply_filters( 'tgmpa_update_bulk_plugins_complete_actions', $update_actions, $this->plugin_info );
3678
3679
						if ( ! empty( $update_actions ) ) {
3680
							$this->feedback( implode( ' | ', (array) $update_actions ) );
3681
						}
3682
					}
3683
3684
					/* *********** DEPRECATED METHODS *********** */
3685
3686
					/**
3687
					 * Flush header output buffer.
3688
					 *
3689
					 * @since      2.2.0
3690
					 * @deprecated 2.5.0 use {@see Bulk_Upgrader_Skin::flush_output()} instead
3691
					 * @see        Bulk_Upgrader_Skin::flush_output()
3692
					 */
3693
					public function before_flush_output() {
3694
						_deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'Bulk_Upgrader_Skin::flush_output()' );
3695
						$this->flush_output();
3696
					}
3697
3698
					/**
3699
					 * Flush footer output buffer and iterate $this->i to make sure the
3700
					 * installation strings reference the correct plugin.
3701
					 *
3702
					 * @since      2.2.0
3703
					 * @deprecated 2.5.0 use {@see Bulk_Upgrader_Skin::flush_output()} instead
3704
					 * @see        Bulk_Upgrader_Skin::flush_output()
3705
					 */
3706
					public function after_flush_output() {
3707
						_deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'Bulk_Upgrader_Skin::flush_output()' );
3708
						$this->flush_output();
3709
						$this->i++;
3710
					}
3711
				}
3712
			}
3713
		}
3714
	}
3715
}
3716
3717
if ( ! class_exists( 'TGMPA_Utils' ) ) {
3718
3719
	/**
3720
	 * Generic utilities for TGMPA.
3721
	 *
3722
	 * All methods are static, poor-dev name-spacing class wrapper.
3723
	 *
3724
	 * Class was called TGM_Utils in 2.5.0 but renamed TGMPA_Utils in 2.5.1 as this was conflicting with Soliloquy.
3725
	 *
3726
	 * @since 2.5.0
3727
	 *
3728
	 * @package TGM-Plugin-Activation
3729
	 * @author  Juliette Reinders Folmer
3730
	 */
3731
	class TGMPA_Utils {
3732
		/**
3733
		 * Whether the PHP filter extension is enabled.
3734
		 *
3735
		 * @see http://php.net/book.filter
3736
		 *
3737
		 * @since 2.5.0
3738
		 *
3739
		 * @static
3740
		 *
3741
		 * @var bool $has_filters True is the extension is enabled.
3742
		 */
3743
		public static $has_filters;
3744
3745
		/**
3746
		 * Wrap an arbitrary string in <em> tags. Meant to be used in combination with array_map().
3747
		 *
3748
		 * @since 2.5.0
3749
		 *
3750
		 * @static
3751
		 *
3752
		 * @param string $string Text to be wrapped.
3753
		 * @return string
3754
		 */
3755
		public static function wrap_in_em( $string ) {
3756
			return '<em>' . wp_kses_post( $string ) . '</em>';
3757
		}
3758
3759
		/**
3760
		 * Wrap an arbitrary string in <strong> tags. Meant to be used in combination with array_map().
3761
		 *
3762
		 * @since 2.5.0
3763
		 *
3764
		 * @static
3765
		 *
3766
		 * @param string $string Text to be wrapped.
3767
		 * @return string
3768
		 */
3769
		public static function wrap_in_strong( $string ) {
3770
			return '<strong>' . wp_kses_post( $string ) . '</strong>';
3771
		}
3772
3773
		/**
3774
		 * Helper function: Validate a value as boolean
3775
		 *
3776
		 * @since 2.5.0
3777
		 *
3778
		 * @static
3779
		 *
3780
		 * @param mixed $value Arbitrary value.
3781
		 * @return bool
3782
		 */
3783
		public static function validate_bool( $value ) {
3784
			if ( ! isset( self::$has_filters ) ) {
3785
				self::$has_filters = extension_loaded( 'filter' );
3786
			}
3787
3788
			if ( self::$has_filters ) {
3789
				return filter_var( $value, FILTER_VALIDATE_BOOLEAN );
3790
			} else {
3791
				return self::emulate_filter_bool( $value );
3792
			}
3793
		}
3794
3795
		/**
3796
		 * Helper function: Cast a value to bool
3797
		 *
3798
		 * @since 2.5.0
3799
		 *
3800
		 * @static
3801
		 *
3802
		 * @param mixed $value Value to cast.
3803
		 * @return bool
3804
		 */
3805
		protected static function emulate_filter_bool( $value ) {
3806
			// @codingStandardsIgnoreStart
3807
			static $true  = array(
3808
				'1',
3809
				'true', 'True', 'TRUE',
3810
				'y', 'Y',
3811
				'yes', 'Yes', 'YES',
3812
				'on', 'On', 'ON',
3813
			);
3814
			static $false = array(
3815
				'0',
3816
				'false', 'False', 'FALSE',
3817
				'n', 'N',
3818
				'no', 'No', 'NO',
3819
				'off', 'Off', 'OFF',
3820
			);
3821
			// @codingStandardsIgnoreEnd
3822
3823
			if ( is_bool( $value ) ) {
3824
				return $value;
3825
			} else if ( is_int( $value ) && ( 0 === $value || 1 === $value ) ) {
3826
				return (bool) $value;
3827
			} else if ( ( is_float( $value ) && ! is_nan( $value ) ) && ( (float) 0 === $value || (float) 1 === $value ) ) {
3828
				return (bool) $value;
3829
			} else if ( is_string( $value ) ) {
3830
				$value = trim( $value );
3831
				if ( in_array( $value, $true, true ) ) {
3832
					return true;
3833
				} else if ( in_array( $value, $false, true ) ) {
3834
					return false;
3835
				} else {
3836
					return false;
3837
				}
3838
			}
3839
3840
			return false;
3841
		}
3842
	} // End of class TGMPA_Utils
3843
} // End of class_exists wrapper
3844