Completed
Push — master ( b54fe3...253e75 )
by Stephanie
02:40
created

FrmAddon   D

Complexity

Total Complexity 85

Size/Duplication

Total Lines 392
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 392
rs 4.8717
c 0
b 0
f 0
wmc 85
lcom 1
cbo 2

28 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 15 3
A load_hooks() 0 4 1
A insert_installed_addon() 0 4 1
A get_addon() 0 8 2
B edd_plugin_updater() 0 27 4
A get_license() 0 7 2
B activate_defined_license() 0 11 5
A get_defined_license() 0 4 2
A set_license() 0 3 1
A is_time_to_auto_activate() 0 4 2
A set_auto_activate_time() 0 3 1
A is_active() 0 3 1
A clear_license() 0 6 1
A set_active() 0 4 1
A show_license_message() 0 8 1
D clear_expired_download() 0 36 10
B is_current_version() 0 12 7
A has_been_cleared() 0 4 2
A cleared_plugins() 0 3 1
B is_license_revoked() 0 16 7
A transient_key() 0 3 1
A activate() 0 16 3
B activate_license() 0 28 5
B get_license_status() 0 25 5
A get_messages() 0 11 1
B deactivate() 0 28 4
D send_mothership_request() 0 43 10
A manually_queue_update() 0 3 1

How to fix   Complexity   

Complex Class

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

1
<?php
2
3
if ( ! defined( 'ABSPATH' ) ) {
4
	die( 'You are not allowed to call this page directly.' );
5
}
6
7
class FrmAddon {
8
	public $store_url = 'https://formidableforms.com';
9
	public $download_id;
10
	public $plugin_file;
11
	public $plugin_folder;
12
	public $plugin_name;
13
	public $plugin_slug;
14
	public $option_name;
15
	public $version;
16
	public $author = 'Strategy11';
17
	private $license;
18
19
	public function __construct() {
20
21
		if ( empty( $this->plugin_slug ) ) {
22
			$this->plugin_slug = preg_replace( '/[^a-zA-Z0-9_\s]/', '', str_replace( ' ', '_', strtolower( $this->plugin_name ) ) );
23
		}
24
		if ( empty( $this->option_name ) ) {
25
			$this->option_name = 'edd_' . $this->plugin_slug . '_license_';
26
		}
27
28
		$this->plugin_folder = plugin_basename( $this->plugin_file );
29
		$this->license = $this->get_license();
30
31
		add_filter( 'frm_installed_addons', array( &$this, 'insert_installed_addon' ) );
32
		$this->edd_plugin_updater();
33
	}
34
35
	public static function load_hooks() {
36
		add_filter( 'frm_include_addon_page', '__return_true' );
37
		//new static();
38
	}
39
40
	public function insert_installed_addon( $plugins ) {
41
		$plugins[ $this->plugin_slug ] = $this;
42
		return $plugins;
43
	}
44
45
	public static function get_addon( $plugin_slug ) {
46
		$plugins = apply_filters( 'frm_installed_addons', array() );
47
		$plugin = false;
48
		if ( isset( $plugins[ $plugin_slug ] ) ) {
49
			$plugin = $plugins[ $plugin_slug ];
50
		}
51
		return $plugin;
52
	}
53
54
	public function edd_plugin_updater() {
55
56
		$this->is_license_revoked();
57
		$license = $this->license;
58
59
		if ( empty( $license ) ) {
60
			add_action( 'after_plugin_row_' . plugin_basename( $this->plugin_file ), array( $this, 'show_license_message' ), 10, 2 );
61
		} else {
62
63
			// setup the updater
64
			$api_data = array(
65
				'version' 	=> $this->version,
66
				'license' 	=> $license,
67
				'author' 	=> $this->author,
68
			);
69
			if ( is_numeric( $this->download_id ) ) {
70
				$api_data['item_id'] = $this->download_id;
71
			}
72
73
			$edd = new FrmEDD_SL_Plugin_Updater( $this->store_url, $this->plugin_file, $api_data );
74
			if ( $this->plugin_folder == 'formidable/formidable.php' ) {
75
				remove_filter( 'plugins_api', array( $edd, 'plugins_api_filter' ), 10, 3 );
76
			}
77
78
			add_filter( 'site_transient_update_plugins', array( &$this, 'clear_expired_download' ) );
79
		}
80
	}
81
82
	public function get_license() {
83
		$license = trim( get_option( $this->option_name . 'key' ) );
84
		if ( empty( $license ) ) {
85
			$license = $this->activate_defined_license();
86
		}
87
		return $license;
88
	}
89
90
	/**
91
	 * Activate the license in wp-config.php
92
	 * @since 2.03.11
93
	 */
94
	public function activate_defined_license() {
95
		$license = $this->get_defined_license();
96
		if ( ! empty( $license ) && ! $this->is_active() && $this->is_time_to_auto_activate() ) {
97
			$response = $this->activate_license( $license );
98
			$this->set_auto_activate_time();
99
			if ( ! $response['success'] ) {
100
				$license = '';
101
			}
102
		}
103
		return $license;
104
	}
105
106
	/**
107
	 * Check the wp-config.php for the license key
108
	 * @since 2.03.11
109
	 */
110
	public function get_defined_license() {
111
		$consant_name = 'FRM_' . strtoupper( $this->plugin_slug ) . '_LICENSE';
112
		return defined( $consant_name ) ? constant( $consant_name ) : false;
113
	}
114
115
	public function set_license( $license ) {
116
		update_option( $this->option_name . 'key', $license );
117
	}
118
119
	/**
120
	 * If the license is in the config, limit the frequency of checks.
121
	 * The license may be entered incorrectly, so we don't want to check on every page load.
122
	 * @since 2.03.11
123
	 */
124
	private function is_time_to_auto_activate() {
125
		$last_try = get_option( $this->option_name .'last_activate' );
126
		return ( ! $last_try || $last_try < strtotime('-1 day') );
127
	}
128
129
	private function set_auto_activate_time() {
130
		update_option( $this->option_name . 'last_activate', time() );
131
	}
132
133
	public function is_active() {
134
		return get_option( $this->option_name . 'active' );
135
	}
136
137
	public function clear_license() {
138
		delete_option( $this->option_name . 'active' );
139
		delete_option( $this->option_name . 'key' );
140
		delete_site_transient( $this->transient_key() );
141
		delete_transient('frm_api_licence');
142
	}
143
144
	public function set_active( $is_active ) {
145
		update_option( $this->option_name . 'active', $is_active );
146
		delete_transient('frm_api_licence');
147
	}
148
149
	public function show_license_message( $file, $plugin ) {
150
		$wp_list_table = _get_list_table( 'WP_Plugins_List_Table' );
151
		echo '<tr class="plugin-update-tr active"><td colspan="' . esc_attr( $wp_list_table->get_column_count() ) . '" class="plugin-update colspanchange"><div class="update-message">';
152
		echo sprintf( __( 'Your %1$s license key is missing. Please add it on the %2$slicenses page%3$s.', 'formidable' ), $this->plugin_name, '<a href="' . esc_url( admin_url('admin.php?page=formidable-settings&t=licenses_settings' ) ) . '">', '</a>' );
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'sprintf'
Loading history...
153
		$id = sanitize_title( $plugin['Name'] );
154
		echo '<script type="text/javascript">var d = document.getElementById("' . esc_attr( $id ) . '");if ( d !== null ){ d.className = d.className + " update"; }</script>';
155
		echo '</div></td></tr>';
156
	}
157
158
	public function clear_expired_download( $transient ) {
159
		if ( ! is_object( $transient ) ) {
160
			return $transient;
161
		}
162
163
		if ( $this->is_current_version( $transient ) ) {
164
			//make sure it doesn't show there is an update if plugin is up-to-date
165
			if ( isset( $transient->response[ $this->plugin_folder ] ) ) {
166
				unset( $transient->response[ $this->plugin_folder ] );
167
			}
168
		} else if ( isset( $transient->response ) && isset( $transient->response[ $this->plugin_folder ] ) ) {
169
			$cache_key = 'edd_plugin_' . md5( sanitize_key( $this->license . $this->version ) . '_get_version' );
170
			$version_info = get_transient( $cache_key );
171
172
			$expiration = get_option( '_transient_timeout_' . $cache_key );
173
			if ( $expiration === false ) {
174
				// make sure transients don't stick around on some sites
175
				$version_info = false;
176
			}
177
178
			if ( $version_info !== false && version_compare( $version_info->new_version, $this->version, '>' ) ) {
179
				$transient->response[ $this->plugin_folder ] = $version_info;
180
			} else {
181
				delete_transient( $cache_key );
182
				if ( ! $this->has_been_cleared() ) {
183
					// if the transient has expired, clear the update and trigger it again
184
					$this->cleared_plugins();
185
					$this->manually_queue_update();
186
				}
187
188
				unset( $transient->response[ $this->plugin_folder ] );
189
			}
190
		}
191
192
		return $transient;
193
	}
194
195
	private function is_current_version( $transient ) {
196
		if ( empty( $transient->checked ) || ! isset( $transient->checked[ $this->plugin_folder ] ) ) {
197
			return false;
198
		}
199
200
		$response = ! isset( $transient->response ) || empty( $transient->response );
201
		if ( $response ) {
202
			return true;
203
		}
204
205
		return isset( $transient->response ) && isset( $transient->response[ $this->plugin_folder ] ) && $transient->checked[ $this->plugin_folder ] == $transient->response[ $this->plugin_folder ]->new_version;
206
	}
207
208
	private function has_been_cleared() {
209
		$last_cleared = get_option( 'frm_last_cleared' );
210
		return ( $last_cleared && $last_cleared > date( 'Y-m-d H:i:s', strtotime('-5 minutes') ) );
211
	}
212
213
	private function cleared_plugins() {
214
		update_option( 'frm_last_cleared', date('Y-m-d H:i:s') );
215
	}
216
217
	private function is_license_revoked() {
218
		if ( empty( $this->license ) || empty( $this->plugin_slug ) || isset( $_POST['license'] ) ) {
219
			return;
220
		}
221
222
		$last_checked = get_site_option( $this->transient_key() );
223
		$seven_days_ago = date( 'Y-m-d H:i:s', strtotime('-7 days') );
224
225
		if ( ! $last_checked || $last_checked < $seven_days_ago ) {
226
			update_site_option( $this->transient_key(), date( 'Y-m-d H:i:s' ) ); // check weekly
227
			$response = $this->get_license_status();
228
			if ( $response['status'] == 'revoked' ) {
229
				$this->clear_license();
230
			}
231
		}
232
	}
233
234
	private function transient_key() {
235
		return 'frm_' . md5( sanitize_key( $this->license . '_' . $this->plugin_slug ) );
236
	}
237
238
	public static function activate() {
239
		FrmAppHelper::permission_check('frm_change_settings');
240
	 	check_ajax_referer( 'frm_ajax', 'nonce' );
241
242
		if ( ! isset( $_POST['license'] ) || empty( $_POST['license'] ) ) {
243
			wp_die( __( 'Oops! You forgot to enter your license number.', 'formidable' ) );
244
		}
245
246
		$license = stripslashes( sanitize_text_field( $_POST['license'] ) );
247
		$plugin_slug = sanitize_text_field( $_POST['plugin'] );
248
		$this_plugin = self::get_addon( $plugin_slug );
249
		$response = $this_plugin->activate_license( $license );
250
251
		echo json_encode( $response );
252
		wp_die();
253
	}
254
255
	private function activate_license( $license ) {
256
		$this->set_license( $license );
257
		$this->license = $license;
258
259
		$response = $this->get_license_status();
260
		$response['message'] = '';
261
		$response['success'] = false;
262
263
		if ( $response['error'] ) {
264
			$response['message'] = $response['status'];
265
		} else {
266
			$messages = $this->get_messages();
267
			if ( is_string( $response['status'] ) && isset( $messages[ $response['status'] ] ) ) {
268
				$response['message'] = $messages[ $response['status'] ];
269
			} else {
270
				$response['message'] = FrmAppHelper::kses( $response['status'], array( 'a' ) );
271
			}
272
273
			$is_valid = false;
274
			if ( $response['status'] == 'valid' ) {
275
				$is_valid = 'valid';
276
				$response['success'] = true;
277
			}
278
			$this->set_active( $is_valid );
279
		}
280
281
		return $response;
282
	}
283
284
	private function get_license_status() {
285
		$response = array( 'status' => 'missing', 'error' => true );
286
		if ( empty( $this->license ) ) {
287
			$response['error'] = false;
288
			return $response;
289
		}
290
291
		try {
292
			$response['error'] = false;
293
			$license_data = $this->send_mothership_request( 'activate_license' );
294
295
			// $license_data->license will be either "valid" or "invalid"
296
			if ( is_array( $license_data ) ) {
297
				if ( in_array( $license_data['license'], array( 'valid', 'invalid' ) ) ) {
298
					$response['status'] = $license_data['license'];
299
				}
300
			} else {
301
				$response['status'] = $license_data;
302
			}
303
		} catch ( Exception $e ) {
304
			$response['status'] = $e->getMessage();
305
		}
306
307
		return $response;
308
	}
309
310
	private function get_messages() {
311
		return array(
312
			'valid'   => __( 'Your license has been activated. Enjoy!', 'formidable' ),
313
			'invalid' => __( 'That license key is invalid', 'formidable' ),
314
			'expired' => __( 'That license is expired', 'formidable' ),
315
			'revoked' => __( 'That license has been refunded', 'formidable' ),
316
			'no_activations_left' => __( 'That license has been used on too many sites', 'formidable' ),
317
			'invalid_item_id' => __( 'Oops! That is the wrong license key for this plugin.', 'formidable' ),
318
			'missing' => __( 'That license key is invalid', 'formidable' ),
319
		);
320
	}
321
322
	public static function deactivate() {
323
		FrmAppHelper::permission_check('frm_change_settings');
324
		check_ajax_referer( 'frm_ajax', 'nonce' );
325
326
		$plugin_slug = sanitize_text_field( $_POST['plugin'] );
327
		$this_plugin = self::get_addon( $plugin_slug );
328
		$license = $this_plugin->get_license();
329
		$this_plugin->license = $license;
330
331
		$response = array( 'success' => false, 'message' => '' );
332
		try {
333
			// $license_data->license will be either "deactivated" or "failed"
334
			$license_data = $this_plugin->send_mothership_request( 'deactivate_license' );
335
			if ( is_array( $license_data ) && $license_data['license'] == 'deactivated' ) {
336
				$response['success'] = true;
337
				$response['message'] = __( 'That license was removed successfully', 'formidable' );
338
			} else {
339
				$response['message'] = __( 'There was an error deactivating your license.', 'formidable' );
340
			}
341
		} catch ( Exception $e ) {
342
			$response['message'] = $e->getMessage();
343
		}
344
345
		$this_plugin->clear_license();
346
347
		echo json_encode( $response );
348
		wp_die();
349
	}
350
351
	public function send_mothership_request( $action ) {
352
		$api_params = array(
353
			'edd_action' => $action,
354
			'license'    => $this->license,
355
			'url'        => home_url(),
356
		);
357
		if ( is_numeric( $this->download_id ) ) {
358
			$api_params['item_id'] = absint( $this->download_id );
359
		} else {
360
			$api_params['item_name'] = urlencode( $this->plugin_name );
361
		}
362
363
		$arg_array = array(
364
			'body'      => $api_params,
365
			'timeout'   => 25,
366
			'sslverify' => false,
367
			'user-agent' => $this->plugin_slug . '/' . $this->version . '; ' . get_bloginfo( 'url' ),
368
		);
369
370
		$resp = wp_remote_post( $this->store_url, $arg_array );
371
		$body = wp_remote_retrieve_body( $resp );
372
373
		$message = __( 'Your License Key was invalid', 'formidable' );
374
		if ( is_wp_error( $resp ) ) {
375
			$message = sprintf( __( 'You had an error communicating with the Formidable API. %1$sClick here%2$s for more information.', 'formidable' ), '<a href="https://formidableforms.com/knowledgebase/why-cant-i-activate-formidable-pro/" target="_blank">', '</a>');
376
			$message .= ' ' . $resp->get_error_message();
377
		} else if ( $body == 'error' || is_wp_error( $body ) ) {
378
			$message = __( 'You had an HTTP error connecting to the Formidable API', 'formidable' );
379
		} else {
380
			$json_res = json_decode( $body, true );
381
			if ( null !== $json_res ) {
382
				if ( is_array( $json_res ) && isset( $json_res['error'] ) ) {
383
					$message = $json_res['error'];
384
				} else {
385
					$message = $json_res;
386
				}
387
			} else if ( isset( $resp['response'] ) && isset( $resp['response']['code'] ) ) {
388
				$message = sprintf( __( 'There was a %1$s error: %2$s', 'formidable' ), $resp['response']['code'], $resp['response']['message'] . ' ' . $resp['body'] );
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$resp'
Loading history...
389
			}
390
		}
391
392
		return $message;
393
	}
394
395
    public function manually_queue_update() {
396
        set_site_transient( 'update_plugins', null );
397
    }
398
}
399