Passed
Push — develop ( a578dd...775faa )
by Paul
03:23
created

GateKeeper::isPluginDependency()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace GeminiLabs\Pollux;
4
5
use Exception;
6
use GeminiLabs\Pollux\Config\Config;
7
use ReflectionClass;
8
9
class GateKeeper
10
{
11
	/**
12
	 * [plugin_file_path] => [plugin_name]|[plugin_version]|[plugin_url]
13
	 */
14
	const DEPENDENCIES = [
15
		'meta-box/meta-box.php' => 'Meta Box|4.11|https://wordpress.org/plugins/meta-box/',
16
	];
17
	const MIN_PHP_VERSION = '5.6.0';
18
	const MIN_WORDPRESS_VERSION = '4.7';
19
20
	public $errors = [];
21
22
	/**
23
	 * @var Application
24
	 */
25
	protected $app;
26
27
	/**
28
	 * @var Notice
29
	 */
30
	protected $notice;
31
32
	/**
33
	 * @var string
34
	 */
35
	protected $plugin;
36
37
	public function __construct( $plugin )
38
	{
39
		$this->plugin = $plugin;
40
41
		if( $this->canActivate() ) {
42
			add_action( 'admin_init', array( $this, 'init' ));
43
		}
44
		else {
45
			add_action( 'activated_plugin', array( $this, 'deactivate' ));
46
			add_action( 'admin_notices',    array( $this, 'deactivate' ));
47
		}
48
	}
49
50
	public function init()
51
	{
52
		$this->app = pollux_app();
53
		$this->notice = pollux_app()->make( 'Notice' );
54
55
		add_action( 'wp_ajax_pollux/dependency/activate', array( $this, 'ajaxActivatePlugin' ));
56
		add_action( 'wp_ajax_pollux/dependency/updated',  array( $this, 'ajaxIsPluginActive' ));
57
		add_action( 'admin_notices',                      array( $this, 'printNotices' ));
58
		add_action( 'current_screen',                     array( $this, 'setDependencyNotice' ));
59
	}
60
61
	/**
62
	 * @return void
63
	 */
64
	public function ajaxIsPluginActive()
65
	{
66
		check_ajax_referer( 'updates' );
67
		$plugin = filter_input( INPUT_POST, 'plugin' );
68
		if( !$this->isPluginDependency( $plugin )) {
69
			wp_send_json_error();
70
		}
71
		$status = [
72
			'updated' => $plugin,
73
			'pluginName' => $this->getPluginInformation( $plugin, 'name' ),
74
		];
75
		if( !$this->isPluginActive( $plugin )) {
76
			$actionUrl = self_admin_url( sprintf( 'plugins.php?action=activate&plugin=%s', $plugin ));
77
			$status['activateUrl'] = wp_nonce_url( $actionUrl, sprintf( 'activate-plugin_%s', $plugin ));
78
		}
79
		wp_send_json_success( $status );
80
	}
81
82
	/**
83
	 * @return void
84
	 */
85
	public function ajaxActivatePlugin()
86
	{
87
		check_ajax_referer( 'updates' );
88
		$plugin = filter_input( INPUT_POST, 'plugin' );
89
		if( !$this->isPluginDependency( $plugin ) || is_wp_error( activate_plugin( $plugin, null, is_network_admin(), true ))) {
90
			wp_send_json_error();
91
		}
92
		wp_send_json_success([
93
			'activate' => $plugin,
94
			'pluginName' => $this->getPluginInformation( $plugin, 'name' ),
95
			'slug' => $this->getPluginSlug( $plugin ),
96
		]);
97
	}
98
99
	/**
100
	 * @return bool
101
	 */
102
	public function canActivate()
103
	{
104
		return $this->hasValidPHPVersion() && $this->hasValidWPVersion();
105
	}
106
107
	/**
108
	 * @return void
109
	 * @action activated_plugin
110
	 * @action admin_notices
111
	 */
112
	public function deactivate( $plugin )
113
	{
114
		if( $plugin == $this->plugin ) {
115
			$this->redirect();
116
		}
117
		deactivate_plugins( $this->plugin );
118
		$addNotice = $this->hasValidPHPVersion()
119
			? 'addInvalidWPVersionNotice'
120
			: 'addInvalidPHPVersionNotice';
121
		$this->$addNotice();
122
	}
123
124
	/**
125
	 * @return void|null
126
	 */
127
	public function getDependencyAction()
128
	{
129
		if( get_current_screen()->id != 'settings_page_pollux' )return;
130
131
		$action = filter_input( INPUT_GET, 'action' );
132
		$plugin = filter_input( INPUT_GET, 'plugin' );
133
134
		if( $action == 'activate' ) {
135
			$this->activatePlugin( $plugin );
0 ignored issues
show
Bug introduced by
The method activatePlugin() does not exist on GeminiLabs\Pollux\GateKeeper. Did you maybe mean ajaxActivatePlugin()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
136
		}
137
		else if( $action == 'install' ) {
138
			$this->installPlugin( $plugin );
0 ignored issues
show
Bug introduced by
The method installPlugin() does not seem to exist on object<GeminiLabs\Pollux\GateKeeper>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
139
		}
140
		else if( filter_input( INPUT_GET, '_error_nonce' )) {
141
			wp_safe_redirect( remove_query_arg( '_error_nonce' ));
142
			exit;
143
		}
144
	}
145
146
	/**
147
	 * @return bool
148
	 */
149
	public function hasDependency( $plugin )
150
	{
151
		if( !$this->isPluginDependency( $plugin )) {
152
			return true;
153
		}
154
		return $this->isPluginInstalled( $plugin ) && $this->isPluginValid( $plugin );
155
	}
156
157
	/**
158
	 * @return bool
159
	 */
160
	public function hasValidPHPVersion()
161
	{
162
		return version_compare( PHP_VERSION, self::MIN_PHP_VERSION, '>=' );
163
	}
164
165
	/**
166
	 * @return bool
167
	 */
168
	public function hasValidWPVersion()
169
	{
170
		global $wp_version;
171
		return version_compare( $wp_version, self::MIN_WORDPRESS_VERSION, '>=' );
172
	}
173
174
	/**
175
	 * @return bool
176
	 */
177
	public function isPluginActive( $plugin )
178
	{
179
		return $this->catchError( $plugin, 'inactive',
180
			is_plugin_active( $plugin ) || array_key_exists( $plugin, $this->getMustUsePlugins() )
181
		);
182
	}
183
184
	/**
185
	 * @return bool
186
	 */
187
	public function isPluginDependency( $plugin )
188
	{
189
		return array_key_exists( $plugin, static::DEPENDENCIES );
190
	}
191
192
	/**
193
	 * @return bool
194
	 */
195
	public function isPluginInstalled( $plugin )
196
	{
197
		return $this->catchError( $plugin, 'not_found',
198
			array_key_exists( $plugin, $this->getAllPlugins() )
199
		);
200
	}
201
202
	/**
203
	 * @return bool
204
	 */
205
	public function isPluginValid( $plugin )
206
	{
207
		return $this->isPluginActive( $plugin ) && $this->isPluginVersionValid( $plugin );
208
	}
209
210
	/**
211
	 * @return bool
212
	 */
213
	public function isPluginVersionValid( $plugin )
214
	{
215
		if( !$this->isPluginDependency( $plugin )) {
216
			return true;
217
		}
218
		if( !$this->isPluginInstalled( $plugin )) {
219
			return false;
220
		}
221
		return $this->catchError( $plugin, 'wrong_version', version_compare(
222
			$this->getPluginRequirements( $plugin, 'version' ),
223
			$this->getAllPlugins()[$plugin]['Version'],
224
			'<='
225
		));
226
	}
227
228
	/**
229
	 * @return void
230
	 */
231
	public function printNotices()
232
	{
233
		foreach( $this->notice->all as $notice ) {
0 ignored issues
show
Documentation introduced by
The property all does not exist on object<GeminiLabs\Pollux\Notice>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
234
			echo $this->notice->generate( $notice );
235
		}
236
	}
237
238
	/**
239
	 * @return bool
240
	 */
241
	public function hasPendingDependencies()
242
	{
243
		foreach( static::DEPENDENCIES as $plugin => $data ) {
244
			if( !$this->isPluginDependency( $plugin ))continue;
245
			$this->isPluginActive( $plugin );
246
			$this->isPluginVersionValid( $plugin );
247
		}
248
		return !empty( $this->errors );
249
	}
250
251
	/**
252
	 * @return void|null
253
	 */
254
	public function setDependencyNotice()
255
	{
256
		if( get_current_screen()->id != 'settings_page_pollux'
257
			|| $this->app->config->disable_config
258
			|| !$this->hasPendingDependencies()
259
		)return;
260
261
		$plugins = '';
262
		$actions = '';
263
264
		foreach( $this->errors as $plugin => $errors ) {
265
			$plugins .= $this->getPluginLink( $plugin );
266
			if( in_array( 'not_found', $errors ) && current_user_can( 'install_plugins' )) {
267
				$actions .= $this->notice->installButton( $this->getPluginRequirements( $plugin ));
0 ignored issues
show
Bug introduced by
It seems like $this->getPluginRequirements($plugin) targeting GeminiLabs\Pollux\GateKe...getPluginRequirements() can also be of type string; however, GeminiLabs\Pollux\Notice::installButton() does only seem to accept array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
268
			}
269
			else if( in_array( 'wrong_version', $errors ) && current_user_can( 'update_plugins' )) {
270
				$actions .= $this->notice->updateButton( $this->getPluginInformation( $plugin ));
0 ignored issues
show
Bug introduced by
It seems like $this->getPluginInformation($plugin) targeting GeminiLabs\Pollux\GateKe...:getPluginInformation() can also be of type string; however, GeminiLabs\Pollux\Notice::updateButton() does only seem to accept array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
271
			}
272
			else if( in_array( 'inactive', $errors ) && current_user_can( 'activate_plugins' )) {
273
				$actions .= $this->notice->activateButton( $this->getPluginInformation( $plugin ));
0 ignored issues
show
Bug introduced by
It seems like $this->getPluginInformation($plugin) targeting GeminiLabs\Pollux\GateKe...:getPluginInformation() can also be of type string; however, GeminiLabs\Pollux\Notice::activateButton() does only seem to accept array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
274
			}
275
		}
276
		$this->notice->addWarning([
0 ignored issues
show
Documentation Bug introduced by
The method addWarning does not exist on object<GeminiLabs\Pollux\Notice>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
277
			sprintf( '<strong>%s</strong> %s', __( 'Pollux requires the latest version of the following plugins:', 'pollux' ), $plugins ),
278
			$actions,
279
		]);
280
	}
281
282
	/**
283
	 * @return void
284
	 */
285 View Code Duplication
	protected function addInvalidPHPVersionNotice()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
286
	{
287
		$this->notice->addError([
0 ignored issues
show
Documentation Bug introduced by
The method addError does not exist on object<GeminiLabs\Pollux\Notice>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
288
			$this->notice->title( __( 'The Pollux plugin was deactivated.', 'pollux' )),
289
			sprintf( __( 'Sorry, Pollux requires PHP %s or greater in order to work properly (your server is running PHP %s).', 'pollux' ), self::MIN_PHP_VERSION, PHP_VERSION ),
290
			__( 'Please contact your hosting provider or server administrator to upgrade the version of PHP running on your server, or find an alternate plugin.', 'pollux' ),
291
		]);
292
	}
293
294
	/**
295
	 * @return void
296
	 */
297 View Code Duplication
	protected function addInvalidWPVersionNotice()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
298
	{
299
		$this->notice->addError([
0 ignored issues
show
Documentation Bug introduced by
The method addError does not exist on object<GeminiLabs\Pollux\Notice>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
300
			$this->notice->title( __( 'The Pollux plugin was deactivated.', 'pollux' )),
301
			sprintf( __( 'Sorry, Pollux requires WordPress %s or greater in order to work properly.', 'pollux' ), self::MIN_WORDPRESS_VERSION ),
302
			$this->notice->button( __( 'Update WordPress', 'pollux' ), self_admin_url( 'update-core.php' )),
303
		]);
304
	}
305
306
	/**
307
	 * @param string $error
308
	 * @param bool $bool
0 ignored issues
show
Bug introduced by
There is no parameter named $bool. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
309
	 * @return bool
310
	 */
311
	protected function catchError( $plugin, $error, $isValid )
312
	{
313
		if( !$isValid ) {
314
			if( !isset( $this->errors[$plugin] )) {
315
				$this->errors[$plugin] = [];
316
			}
317
			$this->errors[$plugin] = array_keys( array_flip(
318
				array_merge( $this->errors[$plugin], [$error] )
319
			));
320
		}
321
		return $isValid;
322
	}
323
324
	/**
325
	 * @return array
326
	 */
327
	protected function getAllPlugins()
328
	{
329
		require_once ABSPATH . 'wp-admin/includes/plugin.php';
330
		return array_merge( get_plugins(), $this->getMustUsePlugins() );
331
	}
332
333
	/**
334
	 * @return array
335
	 */
336
	protected function getMustUsePlugins()
337
	{
338
		$plugins = get_mu_plugins();
339
		if( in_array( 'Bedrock Autoloader', array_column( $plugins, 'Name' ))) {
340
			$autoloadedPlugins = get_site_option( 'bedrock_autoloader' );
341
			if( !empty( $autoloadedPlugins['plugins'] )) {
342
				return array_merge( $plugins, $autoloadedPlugins['plugins'] );
343
			}
344
		}
345
		return $plugins;
346
	}
347
348
	/**
349
	 * @return array|false
350
	 */
351
	protected function getPlugin( $plugin )
352
	{
353
		if( $this->isPluginInstalled( $plugin )) {
354
			return $this->getAllPlugins()[$plugin];
355
		}
356
		return false;
357
	}
358
359
	/**
360
	 * @return array|string
361
	 */
362
	protected function getPluginData( $plugin, array $data, $key = null )
363
	{
364
		$data['plugin'] = $plugin;
365
		$data['slug'] = $this->getPluginSlug( $plugin );
366
		$data = array_change_key_case( $data );
367
		if( is_null( $key )) {
368
			return $data;
369
		}
370
		$key = strtolower( $key );
371
		return isset( $data[$key] )
372
			? $data[$key]
373
			: '';
374
	}
375
376
	/**
377
	 * @return array|string
378
	 */
379
	protected function getPluginInformation( $plugin, $key = null )
380
	{
381
		$data = $this->getPlugin( $plugin );
382
		if( is_array( $data )) {
383
			return $this->getPluginData( $plugin, $data, $key );
384
		}
385
		throw new Exception( sprintf( 'Plugin information not found for: %s', $plugin ));
386
	}
387
388
	/**
389
	 * @return string
390
	 */
391
	protected function getPluginLink( $plugin )
392
	{
393
		try {
394
			$data = $this->getPluginInformation( $plugin );
395
		}
396
		catch( Exception $e ) {
397
			$data = $this->getPluginRequirements( $plugin );
398
		}
399
		return sprintf( '<span class="plugin-%s"><a href="%s">%s</a></span>',
400
			$data['slug'],
401
			$data['pluginuri'],
402
			$data['name']
403
		);
404
	}
405
406
	/**
407
	 * @return array|string
408
	 */
409
	protected function getPluginRequirements( $plugin, $key = null )
410
	{
411
		$keys = ['Name', 'Version', 'PluginURI'];
412
		$index = array_search( $key, $keys, true );
0 ignored issues
show
Unused Code introduced by
$index is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
413
		$requirements = $this->isPluginDependency( $plugin )
414
			? array_pad( explode( '|', static::DEPENDENCIES[$plugin] ), 3, '' )
415
			: array_fill( 0, 3, '' );
416
		return $this->getPluginData( $plugin, array_combine( $keys, $requirements ), $key );
417
	}
418
419
	/**
420
	 * @return string
421
	 */
422
	protected function getPluginSlug( $plugin )
423
	{
424
		return substr( $plugin, 0, strrpos( $plugin, '/' ));
425
	}
426
427
	/**
428
	 * @return void
429
	 */
430
	protected function redirect()
431
	{
432
		wp_safe_redirect( self_admin_url( sprintf( 'plugins.php?plugin_status=%s&paged=%s&s=%s',
433
			filter_input( INPUT_GET, 'plugin_status' ),
434
			filter_input( INPUT_GET, 'paged' ),
435
			filter_input( INPUT_GET, 's' )
436
		)));
437
		exit;
438
	}
439
}
440