Completed
Push — pr/7794 ( cb7d3e...693e58 )
by George
09:28
created

Jetpack_JSON_API_Plugins_Endpoint   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 232
Duplicated Lines 1.29 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 3
loc 232
rs 8.3999
c 0
b 0
f 0
wmc 46
lcom 1
cbo 4

9 Methods

Rating   Name   Duplication   Size   Complexity  
A result() 0 11 3
D validate_input() 0 33 9
B validate_plugins() 3 17 6
B format_plugin() 0 29 4
B get_plugins() 0 24 5
B validate_network_wide() 0 13 5
A validate_plugin() 0 11 4
A get_plugin_updates() 0 7 2
C get_plugin_action_links() 0 39 8

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Jetpack_JSON_API_Plugins_Endpoint 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 Jetpack_JSON_API_Plugins_Endpoint, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * Base class for working with plugins.
5
 */
6
abstract class Jetpack_JSON_API_Plugins_Endpoint extends Jetpack_JSON_API_Endpoint {
7
8
	protected $plugins = array();
9
10
	protected $network_wide = false;
11
12
	protected $bulk = true;
13
	protected $log;
14
15
	static $_response_format = array(
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $_response_format.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
16
		'id'              => '(safehtml)  The plugin\'s ID',
17
		'slug'            => '(safehtml)  The plugin\'s .org slug',
18
		'active'          => '(boolean) The plugin status.',
19
		'update'          => '(object)  The plugin update info.',
20
		'name'            => '(safehtml)  The name of the plugin.',
21
		'plugin_url'      => '(url)  Link to the plugin\'s web site.',
22
		'version'         => '(safehtml)  The plugin version number.',
23
		'description'     => '(safehtml)  Description of what the plugin does and/or notes from the author',
24
		'author'          => '(safehtml)  The author\'s name',
25
		'author_url'      => '(url)  The authors web site address',
26
		'network'         => '(boolean) Whether the plugin can only be activated network wide.',
27
		'autoupdate'      => '(boolean) Whether the plugin is automatically updated',
28
		'autoupdate_translation' => '(boolean) Whether the plugin is automatically updating translations',
29
		'next_autoupdate' => '(string) Y-m-d H:i:s for next scheduled update event',
30
		'log'             => '(array:safehtml) An array of update log strings.',
31
		'uninstallable'   => '(boolean) Whether the plugin is unistallable.',
32
		'action_links'    => '(array) An array of action links that the plugin uses.',
33
	);
34
35
	protected function result() {
36
37
		$plugins = $this->get_plugins();
38
39
		if ( ! $this->bulk && ! empty( $plugins ) ) {
40
			return array_pop( $plugins );
41
		}
42
43
		return array( 'plugins' => $plugins );
44
45
	}
46
47
	protected function validate_input( $plugin ) {
48
49
		if ( is_wp_error( $error = parent::validate_input( $plugin ) ) ) {
50
			return $error;
51
		}
52
53
		if ( is_wp_error( $error = $this->validate_network_wide() ) ) {
54
			return $error;
55
		}
56
57
		$args = $this->input();
58
		// find out what plugin, or plugins we are dealing with
59
		// validate the requested plugins
60
		if ( ! isset( $plugin ) || empty( $plugin ) ) {
61
			if ( ! $args['plugins'] || empty( $args['plugins'] ) ) {
62
				return new WP_Error( 'missing_plugin', __( 'You are required to specify a plugin.', 'jetpack' ), 400 );
63
			}
64
			if ( is_array( $args['plugins'] ) ) {
65
				$this->plugins = $args['plugins'];
66
			} else {
67
				$this->plugins[] = $args['plugins'];
68
			}
69
		} else {
70
			$this->bulk = false;
71
			$this->plugins[] = urldecode( $plugin );
72
		}
73
74
		if ( is_wp_error( $error = $this->validate_plugins() ) ) {
75
			return $error;
76
		};
77
78
		return true;
79
	}
80
81
	/**
82
	 * Walks through submitted plugins to make sure they are valid
83
	 * @return bool|WP_Error
84
	 */
85
	protected function validate_plugins() {
86 View Code Duplication
		if ( empty( $this->plugins ) || ! is_array( $this->plugins ) ) {
87
			return new WP_Error( 'missing_plugins', __( 'No plugins found.', 'jetpack' ));
88
		}
89
		foreach( $this->plugins as $index => $plugin ) {
90
			if ( ! preg_match( "/\.php$/", $plugin ) ) {
91
				$plugin =  $plugin . '.php';
92
				$this->plugins[ $index ] = $plugin;
93
			}
94
			$valid = $this->validate_plugin( urldecode( $plugin ) ) ;
95
			if ( is_wp_error( $valid ) ) {
96
				return $valid;
97
			}
98
		}
99
100
		return true;
101
	}
102
103
	protected function format_plugin( $plugin_file, $plugin_data ) {
104
		$plugin = array();
105
		$plugin['id']              = preg_replace("/(.+)\.php$/", "$1", $plugin_file );
106
		$plugin['slug']            = Jetpack_Autoupdate::get_plugin_slug( $plugin_file );
107
		$plugin['active']          = Jetpack::is_plugin_active( $plugin_file );
108
		$plugin['name']            = $plugin_data['Name'];
109
		$plugin['plugin_url']      = $plugin_data['PluginURI'];
110
		$plugin['version']         = $plugin_data['Version'];
111
		$plugin['description']     = $plugin_data['Description'];
112
		$plugin['author']          = $plugin_data['Author'];
113
		$plugin['author_url']      = $plugin_data['AuthorURI'];
114
		$plugin['network']         = $plugin_data['Network'];
115
		$plugin['update']          = $this->get_plugin_updates( $plugin_file );
116
		$plugin['next_autoupdate'] = date( 'Y-m-d H:i:s', wp_next_scheduled( 'wp_maybe_auto_update' ) );
117
		$plugin['action_links']    = $this->get_plugin_action_links( $plugin_file );
118
119
		$autoupdate = in_array( $plugin_file, Jetpack_Options::get_option( 'autoupdate_plugins', array() ) );
120
		$plugin['autoupdate']      = $autoupdate;
121
122
		$autoupdate_translation = in_array( $plugin_file, Jetpack_Options::get_option( 'autoupdate_plugins_translations', array() ) );
123
		$plugin['autoupdate_translation'] = $autoupdate || $autoupdate_translation || Jetpack_Options::get_option( 'autoupdate_translations', false );
124
125
		$plugin['uninstallable']   = is_uninstallable_plugin( $plugin_file );
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 3 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...
126
127
		if ( ! empty ( $this->log[ $plugin_file ] ) ) {
128
			$plugin['log'] = $this->log[ $plugin_file ];
129
		}
130
		return $plugin;
131
	}
132
133
	protected function get_plugins() {
134
		// Do the admin_init action in order to capture plugin action links.
135
		// See get_plugin_action_links()
136
		/** This action is documented in wp-admin/admin.php */
137
		do_action( 'admin_init' );
138
		$plugins = array();
139
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
140
		$installed_plugins = apply_filters( 'all_plugins', get_plugins() );
141
		foreach( $this->plugins as $plugin ) {
142
			if ( ! isset( $installed_plugins[ $plugin ] ) )
143
				continue;
144
			$plugins[] = $this->format_plugin( $plugin, $installed_plugins[ $plugin ] );
145
		}
146
		$args = $this->query_args();
147
148
		if ( isset( $args['offset'] ) ) {
149
			$plugins = array_slice( $plugins, (int) $args['offset'] );
150
		}
151
		if ( isset( $args['limit'] ) ) {
152
			$plugins = array_slice( $plugins, 0, (int) $args['limit'] );
153
		}
154
155
		return $plugins;
156
	}
157
158
	protected function validate_network_wide() {
159
		$args = $this->input();
160
161
		if ( isset( $args['network_wide'] ) && $args['network_wide'] ) {
162
			$this->network_wide = true;
163
		}
164
165
		if ( $this->network_wide && ! current_user_can( 'manage_network_plugins' ) ) {
166
			return new WP_Error( 'unauthorized', __( 'This user is not authorized to manage plugins network wide.', 'jetpack' ), 403 );
167
		}
168
169
		return true;
170
	}
171
172
173
	protected function validate_plugin( $plugin ) {
174
		if ( ! isset( $plugin) || empty( $plugin ) ) {
175
			return new WP_Error( 'missing_plugin', __( 'You are required to specify a plugin to activate.', 'jetpack' ), 400 );
176
		}
177
178
		if ( is_wp_error( $error = validate_plugin( $plugin ) ) ) {
179
			return new WP_Error( 'unknown_plugin', $error->get_error_messages() , 404 );
180
		}
181
182
		return true;
183
	}
184
185
	protected function get_plugin_updates( $plugin_file ) {
186
		$plugin_updates = get_plugin_updates();
187
		if ( isset( $plugin_updates[ $plugin_file ] ) ){
188
			return $plugin_updates[ $plugin_file ]->update;
189
		}
190
		return null;
191
	}
192
193
	/**
194
	 * Get custom action link tags that the plugin is using
195
	 * Ref: https://codex.wordpress.org/Plugin_API/Filter_Reference/plugin_action_links_(plugin_file_name)
196
	 * @return array of plugin action links (key: link name value: url)
197
	 */
198
	 protected function get_plugin_action_links( $plugin_file ) {
199
		 $formatted_action_links = array();
200
201
		 // Some sites may have DOM disabled in PHP
202
		 if ( ! class_exists( 'DOMDocument' ) ) {
203
			 return $formatted_action_links;
204
		 }
205
206
		 $action_links = array();
207
		 /** This filter is documented in src/wp-admin/includes/class-wp-plugins-list-table.php */
208
		 $action_links = apply_filters( 'plugin_action_links', $action_links, $plugin_file, null, 'all' );
209
		 /** This filter is documented in src/wp-admin/includes/class-wp-plugins-list-table.php */
210
		 $action_links = apply_filters( "plugin_action_links_{$plugin_file}", $action_links, $plugin_file, null, 'all' );
211
		 if ( count( $action_links ) > 0 ) {
212
			 $dom_doc = new DOMDocument;
213
			 foreach( $action_links as $action_link ) {
214
				 $dom_doc->loadHTML( mb_convert_encoding( $action_link, 'HTML-ENTITIES', 'UTF-8' ) );
215
				 $link_elements = $dom_doc->getElementsByTagName( 'a' );
216
				 if ( $link_elements->length == 0 ) {
217
					 continue;
218
				 }
219
220
				 $link_element = $link_elements->item( 0 );
221
				 if ( $link_element->hasAttribute( 'href' ) && $link_element->nodeValue ) {
222
					 $link_url = trim( $link_element->getAttribute( 'href' ) );
223
224
					 // Add the full admin path to the url if the plugin did not provide it
225
					 $link_url_scheme = wp_parse_url( $link_url, PHP_URL_SCHEME );
226
					 if ( empty( $link_url_scheme ) ) {
227
						 $link_url = admin_url( $link_url );
228
					 }
229
230
					 $formatted_action_links[ $link_element->nodeValue ] = $link_url;
231
				 }
232
			 }
233
		 }
234
235
		 return $formatted_action_links;
236
	 }
237
}
238