Completed
Push — update/affiliate-code-tracking ( 5e3dbc...15c98b )
by
unknown
151:41 queued 141:12
created

Plugins   C

Complexity

Total Complexity 53

Size/Duplication

Total Lines 402
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 402
rs 6.96
c 0
b 0
f 0
wmc 53
lcom 2
cbo 2

12 Methods

Rating   Name   Duplication   Size   Complexity  
A name() 0 3 1
A init_listeners() 0 16 1
A init_before_send() 0 5 1
A populate_plugins() 0 7 2
C on_upgrader_completion() 0 80 15
A get_plugin_info() 0 8 3
B get_errors() 0 30 7
A check_plugin_edit() 0 24 5
C plugin_edit_ajax() 0 59 12
A delete_plugin() 0 19 2
A deleted_plugin() 0 4 1
A expand_plugin_data() 0 20 3

How to fix   Complexity   

Complex Class

Complex classes like Plugins often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Plugins, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Plugins sync module.
4
 *
5
 * @package automattic/jetpack-sync
6
 */
7
8
namespace Automattic\Jetpack\Sync\Modules;
9
10
use Automattic\Jetpack\Constants as Jetpack_Constants;
11
12
/**
13
 * Class to handle sync for plugins.
14
 */
15
class Plugins extends Module {
16
	/**
17
	 * Action handler callable.
18
	 *
19
	 * @access private
20
	 *
21
	 * @var callable
22
	 */
23
	private $action_handler;
24
25
	/**
26
	 * Information about plugins we store temporarily.
27
	 *
28
	 * @access private
29
	 *
30
	 * @var array
31
	 */
32
	private $plugin_info = array();
33
34
	/**
35
	 * List of all plugins in the installation.
36
	 *
37
	 * @access private
38
	 *
39
	 * @var array
40
	 */
41
	private $plugins = array();
42
43
	/**
44
	 * Sync module name.
45
	 *
46
	 * @access public
47
	 *
48
	 * @return string
49
	 */
50
	public function name() {
51
		return 'plugins';
52
	}
53
54
	/**
55
	 * Initialize plugins action listeners.
56
	 *
57
	 * @access public
58
	 *
59
	 * @param callable $callable Action handler callable.
60
	 */
61
	public function init_listeners( $callable ) {
62
		$this->action_handler = $callable;
63
64
		add_action( 'deleted_plugin', array( $this, 'deleted_plugin' ), 10, 2 );
65
		add_action( 'activated_plugin', $callable, 10, 2 );
66
		add_action( 'deactivated_plugin', $callable, 10, 2 );
67
		add_action( 'delete_plugin', array( $this, 'delete_plugin' ) );
68
		add_filter( 'upgrader_pre_install', array( $this, 'populate_plugins' ), 10, 1 );
69
		add_action( 'upgrader_process_complete', array( $this, 'on_upgrader_completion' ), 10, 2 );
70
		add_action( 'jetpack_plugin_installed', $callable, 10, 1 );
71
		add_action( 'jetpack_plugin_update_failed', $callable, 10, 4 );
72
		add_action( 'jetpack_plugins_updated', $callable, 10, 2 );
73
		add_action( 'admin_action_update', array( $this, 'check_plugin_edit' ) );
74
		add_action( 'jetpack_edited_plugin', $callable, 10, 2 );
75
		add_action( 'wp_ajax_edit-theme-plugin-file', array( $this, 'plugin_edit_ajax' ), 0 );
76
	}
77
78
	/**
79
	 * Initialize the module in the sender.
80
	 *
81
	 * @access public
82
	 */
83
	public function init_before_send() {
84
		add_filter( 'jetpack_sync_before_send_activated_plugin', array( $this, 'expand_plugin_data' ) );
85
		add_filter( 'jetpack_sync_before_send_deactivated_plugin', array( $this, 'expand_plugin_data' ) );
86
		// Note that we don't simply 'expand_plugin_data' on the 'delete_plugin' action here because the plugin file is deleted when that action finishes.
87
	}
88
89
	/**
90
	 * Fetch and populate all current plugins before upgrader installation.
91
	 *
92
	 * @access public
93
	 *
94
	 * @param bool|WP_Error $response Install response, true if successful, WP_Error if not.
95
	 */
96
	public function populate_plugins( $response ) {
97
		if ( ! function_exists( 'get_plugins' ) ) {
98
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
99
		}
100
		$this->plugins = get_plugins();
101
		return $response;
102
	}
103
104
	/**
105
	 * Handler for the upgrader success finishes.
106
	 *
107
	 * @access public
108
	 *
109
	 * @param \WP_Upgrader $upgrader Upgrader instance.
110
	 * @param array        $details  Array of bulk item update data.
111
	 */
112
	public function on_upgrader_completion( $upgrader, $details ) {
113
		if ( ! isset( $details['type'] ) ) {
114
			return;
115
		}
116
		if ( 'plugin' !== $details['type'] ) {
117
			return;
118
		}
119
120
		if ( ! isset( $details['action'] ) ) {
121
			return;
122
		}
123
124
		$plugins = ( isset( $details['plugins'] ) ? $details['plugins'] : null );
125
		if ( empty( $plugins ) ) {
126
			$plugins = ( isset( $details['plugin'] ) ? array( $details['plugin'] ) : null );
127
		}
128
129
		// For plugin installer.
130
		if ( empty( $plugins ) && method_exists( $upgrader, 'plugin_info' ) ) {
131
			$plugins = array( $upgrader->plugin_info() );
132
		}
133
134
		if ( empty( $plugins ) ) {
135
			return; // We shouldn't be here.
136
		}
137
138
		switch ( $details['action'] ) {
139
			case 'update':
140
				$state  = array(
141
					'is_autoupdate' => Jetpack_Constants::is_true( 'JETPACK_PLUGIN_AUTOUPDATE' ),
142
				);
143
				$errors = $this->get_errors( $upgrader->skin );
144
				if ( $errors ) {
145
					foreach ( $plugins as $slug ) {
146
						/**
147
						 * Sync that a plugin update failed
148
						 *
149
						 * @since  5.8.0
150
						 *
151
						 * @module sync
152
						 *
153
						 * @param string $plugin , Plugin slug
154
						 * @param        string  Error code
155
						 * @param        string  Error message
156
						 */
157
						do_action( 'jetpack_plugin_update_failed', $this->get_plugin_info( $slug ), $errors['code'], $errors['message'], $state );
158
					}
159
160
					return;
161
				}
162
				/**
163
				 * Sync that a plugin update
164
				 *
165
				 * @since  5.8.0
166
				 *
167
				 * @module sync
168
				 *
169
				 * @param array () $plugin, Plugin Data
170
				 */
171
				do_action( 'jetpack_plugins_updated', array_map( array( $this, 'get_plugin_info' ), $plugins ), $state );
172
				break;
173
			case 'install':
174
		}
175
176
		if ( 'install' === $details['action'] ) {
177
			/**
178
			 * Signals to the sync listener that a plugin was installed and a sync action
179
			 * reflecting the installation and the plugin info should be sent
180
			 *
181
			 * @since  5.8.0
182
			 *
183
			 * @module sync
184
			 *
185
			 * @param array () $plugin, Plugin Data
186
			 */
187
			do_action( 'jetpack_plugin_installed', array_map( array( $this, 'get_plugin_info' ), $plugins ) );
188
189
			return;
190
		}
191
	}
192
193
	/**
194
	 * Retrieve the plugin information by a plugin slug.
195
	 *
196
	 * @access private
197
	 *
198
	 * @param string $slug Plugin slug.
199
	 * @return array Plugin information.
200
	 */
201
	private function get_plugin_info( $slug ) {
202
		$plugins = get_plugins(); // Get the most up to date info.
203
		if ( isset( $plugins[ $slug ] ) ) {
204
			return array_merge( array( 'slug' => $slug ), $plugins[ $slug ] );
205
		};
206
		// Try grabbing the info from before the update.
207
		return isset( $this->plugins[ $slug ] ) ? array_merge( array( 'slug' => $slug ), $this->plugins[ $slug ] ) : array( 'slug' => $slug );
208
	}
209
210
	/**
211
	 * Retrieve upgrade errors.
212
	 *
213
	 * @access private
214
	 *
215
	 * @param \Automatic_Upgrader_Skin|\WP_Upgrader_Skin $skin The upgrader skin being used.
216
	 * @return array|boolean Error on error, false otherwise.
217
	 */
218
	private function get_errors( $skin ) {
219
		$errors = method_exists( $skin, 'get_errors' ) ? $skin->get_errors() : null;
220
		if ( is_wp_error( $errors ) ) {
221
			$error_code = $errors->get_error_code();
222
			if ( ! empty( $error_code ) ) {
223
				return array(
224
					'code'    => $error_code,
225
					'message' => $errors->get_error_message(),
226
				);
227
			}
228
		}
229
230
		if ( isset( $skin->result ) ) {
231
			$errors = $skin->result;
232
			if ( is_wp_error( $errors ) ) {
233
				return array(
234
					'code'    => $errors->get_error_code(),
235
					'message' => $errors->get_error_message(),
236
				);
237
			}
238
239
			if ( empty( $skin->result ) ) {
240
				return array(
241
					'code'    => 'unknown',
242
					'message' => __( 'Unknown Plugin Update Failure', 'jetpack' ),
243
				);
244
			}
245
		}
246
		return false;
247
	}
248
249
	/**
250
	 * Handle plugin edit in the administration.
251
	 *
252
	 * @access public
253
	 *
254
	 * @todo The `admin_action_update` hook is called only for logged in users, but maybe implement nonce verification?
255
	 */
256
	public function check_plugin_edit() {
257
		$screen = get_current_screen();
258
		// phpcs:ignore WordPress.Security.NonceVerification.Missing
259
		if ( 'plugin-editor' !== $screen->base || ! isset( $_POST['newcontent'] ) || ! isset( $_POST['plugin'] ) ) {
260
			return;
261
		}
262
263
		// phpcs:ignore WordPress.Security.NonceVerification.Missing
264
		$plugin  = $_POST['plugin'];
265
		$plugins = get_plugins();
266
		if ( ! isset( $plugins[ $plugin ] ) ) {
267
			return;
268
		}
269
270
		/**
271
		 * Helps Sync log that a plugin was edited
272
		 *
273
		 * @since 4.9.0
274
		 *
275
		 * @param string $plugin, Plugin slug
276
		 * @param mixed $plugins[ $plugin ], Array of plugin data
277
		 */
278
		do_action( 'jetpack_edited_plugin', $plugin, $plugins[ $plugin ] );
279
	}
280
281
	/**
282
	 * Handle plugin ajax edit in the administration.
283
	 *
284
	 * @access public
285
	 *
286
	 * @todo Update this method to use WP_Filesystem instead of fopen/fclose.
287
	 */
288
	public function plugin_edit_ajax() {
289
		// This validation is based on wp_edit_theme_plugin_file().
290
		$args = wp_unslash( $_POST );
291
		if ( empty( $args['file'] ) ) {
292
			return;
293
		}
294
295
		$file = $args['file'];
296
		if ( 0 !== validate_file( $file ) ) {
297
			return;
298
		}
299
300
		if ( ! isset( $args['newcontent'] ) ) {
301
			return;
302
		}
303
304
		if ( ! isset( $args['nonce'] ) ) {
305
			return;
306
		}
307
308
		if ( empty( $args['plugin'] ) ) {
309
			return;
310
		}
311
312
		$plugin = $args['plugin'];
313
		if ( ! current_user_can( 'edit_plugins' ) ) {
314
			return;
315
		}
316
317
		if ( ! wp_verify_nonce( $args['nonce'], 'edit-plugin_' . $file ) ) {
318
			return;
319
		}
320
		$plugins = get_plugins();
321
		if ( ! array_key_exists( $plugin, $plugins ) ) {
322
			return;
323
		}
324
325
		if ( 0 !== validate_file( $file, get_plugin_files( $plugin ) ) ) {
326
			return;
327
		}
328
329
		$real_file = WP_PLUGIN_DIR . '/' . $file;
330
331
		if ( ! is_writeable( $real_file ) ) {
332
			return;
333
		}
334
335
		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_fopen
336
		$file_pointer = fopen( $real_file, 'w+' );
337
		if ( false === $file_pointer ) {
338
			return;
339
		}
340
		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_fclose
341
		fclose( $file_pointer );
342
		/**
343
		 * This action is documented already in this file
344
		 */
345
		do_action( 'jetpack_edited_plugin', $plugin, $plugins[ $plugin ] );
346
	}
347
348
	/**
349
	 * Handle plugin deletion.
350
	 *
351
	 * @access public
352
	 *
353
	 * @param string $plugin_path Path to the plugin main file.
354
	 */
355
	public function delete_plugin( $plugin_path ) {
356
		$full_plugin_path = WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $plugin_path;
357
358
		// Checking for file existence because some sync plugin module tests simulate plugin installation and deletion without putting file on disk.
359
		if ( file_exists( $full_plugin_path ) ) {
360
			$all_plugin_data = get_plugin_data( $full_plugin_path );
361
			$data            = array(
362
				'name'    => $all_plugin_data['Name'],
363
				'version' => $all_plugin_data['Version'],
364
			);
365
		} else {
366
			$data = array(
367
				'name'    => $plugin_path,
368
				'version' => 'unknown',
369
			);
370
		}
371
372
		$this->plugin_info[ $plugin_path ] = $data;
373
	}
374
375
	/**
376
	 * Invoked after plugin deletion.
377
	 *
378
	 * @access public
379
	 *
380
	 * @param string  $plugin_path Path to the plugin main file.
381
	 * @param boolean $is_deleted  Whether the plugin was deleted successfully.
382
	 */
383
	public function deleted_plugin( $plugin_path, $is_deleted ) {
384
		call_user_func( $this->action_handler, $plugin_path, $is_deleted, $this->plugin_info[ $plugin_path ] );
385
		unset( $this->plugin_info[ $plugin_path ] );
386
	}
387
388
	/**
389
	 * Expand the plugins within a hook before they are serialized and sent to the server.
390
	 *
391
	 * @access public
392
	 *
393
	 * @param array $args The hook parameters.
394
	 * @return array $args The expanded hook parameters.
395
	 */
396
	public function expand_plugin_data( $args ) {
397
		$plugin_path = $args[0];
398
		$plugin_data = array();
399
400
		if ( ! function_exists( 'get_plugins' ) ) {
401
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
402
		}
403
		$all_plugins = get_plugins();
404
		if ( isset( $all_plugins[ $plugin_path ] ) ) {
405
			$all_plugin_data        = $all_plugins[ $plugin_path ];
406
			$plugin_data['name']    = $all_plugin_data['Name'];
407
			$plugin_data['version'] = $all_plugin_data['Version'];
408
		}
409
410
		return array(
411
			$args[0],
412
			$args[1],
413
			$plugin_data,
414
		);
415
	}
416
}
417