Completed
Push — master ( 500e14...68958b )
by Stephanie
03:58
created

FrmAddon::is_license_revoked()   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 9
nc 4
nop 0
dl 0
loc 15
rs 8.2222
c 0
b 0
f 0
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://formidablepro.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
		return trim( get_option( $this->option_name . 'key' ) );
84
	}
85
86
	public function set_license( $license ) {
87
		update_option( $this->option_name . 'key', $license );
88
	}
89
90
	public function clear_license() {
91
		delete_option( $this->option_name . 'active' );
92
		delete_option( $this->option_name . 'key' );
93
		delete_site_transient( $this->transient_key() );
94
	}
95
96
	public function set_active( $is_active ) {
97
		update_option( $this->option_name . 'active', $is_active );
98
	}
99
100
	public function show_license_message( $file, $plugin ) {
101
		$wp_list_table = _get_list_table( 'WP_Plugins_List_Table' );
102
		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">';
103
		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...
104
		$id = sanitize_title( $plugin['Name'] );
105
		echo '<script type="text/javascript">var d = document.getElementById("' . esc_attr( $id ) . '");if ( d !== null ){ d.className = d.className + " update"; }</script>';
106
		echo '</div></td></tr>';
107
	}
108
109
	public function clear_expired_download( $transient ) {
110
		if ( ! is_object( $transient ) ) {
111
			return $transient;
112
		}
113
114
		if ( $this->is_current_version( $transient ) ) {
115
			//make sure it doesn't show there is an update if plugin is up-to-date
116
			if ( isset( $transient->response[ $this->plugin_folder ] ) ) {
117
				unset( $transient->response[ $this->plugin_folder ] );
118
			}
119
		} else if ( isset( $transient->response ) && isset( $transient->response[ $this->plugin_folder ] ) ) {
120
			$cache_key = 'edd_plugin_' . md5( sanitize_key( $this->license . $this->version ) . '_get_version' );
121
			$version_info = get_transient( $cache_key );
122
123
			$expiration = get_option( '_transient_timeout_' . $cache_key );
124
			if ( $expiration === false ) {
125
				// make sure transients don't stick around on some sites
126
				$version_info = false;
127
			}
128
129
			if ( $version_info !== false && version_compare( $version_info->new_version, $this->version, '>' ) ) {
130
				$transient->response[ $this->plugin_folder ] = $version_info;
131
			} else {
132
				delete_transient( $cache_key );
133
				if ( ! $this->has_been_cleared() ) {
134
					// if the transient has expired, clear the update and trigger it again
135
					$this->cleared_plugins();
136
					$this->manually_queue_update();
137
				}
138
139
				unset( $transient->response[ $this->plugin_folder ] );
140
			}
141
		}
142
143
		return $transient;
144
	}
145
146
	private function is_current_version( $transient ) {
147
		if ( empty( $transient->checked ) || ! isset( $transient->checked[ $this->plugin_folder ] ) ) {
148
			return false;
149
		}
150
151
		$response = ! isset( $transient->response ) || empty( $transient->response );
152
		if ( $response ) {
153
			return true;
154
		}
155
156
		return isset( $transient->response ) && isset( $transient->response[ $this->plugin_folder ] ) && $transient->checked[ $this->plugin_folder ] == $transient->response[ $this->plugin_folder ]->new_version;
157
	}
158
159
	private function has_been_cleared() {
160
		$last_cleared = get_option( 'frm_last_cleared' );
161
		return ( $last_cleared && $last_cleared > date( 'Y-m-d H:i:s', strtotime('-5 minutes') ) );
162
	}
163
164
	private function cleared_plugins() {
165
		update_option( 'frm_last_cleared', date('Y-m-d H:i:s') );
166
	}
167
168
	private function is_license_revoked() {
169
		if ( empty( $this->license ) || empty( $this->plugin_slug ) || isset( $_POST['license'] ) ) {
170
			return;
171
		}
172
173
		$license_status = get_site_transient( $this->transient_key() );
174
175
		if ( $license_status === false && $this->test_transient() ) {
176
			$response = $this->get_license_status();
177
			set_site_transient( $this->transient_key(), $response, 60 * 60 * 24 * 7 ); // check weekly
178
			if ( $response['status'] == 'revoked' ) {
179
				$this->clear_license();
180
			}
181
		}
182
	}
183
184
	private function transient_key() {
185
		return 'frm_' . md5( sanitize_key( $this->license . '_' . $this->plugin_slug ) );
186
	}
187
188
	private static function test_transient() {
189
		$key = 'frm_test';
190
		set_site_transient( $key, $key, 120 );
191
		$transient = get_site_transient( $key );
192
		return ( $transient ) ? true : false;
193
	}
194
195
	public static function activate() {
196
		FrmAppHelper::permission_check('frm_change_settings');
197
	 	check_ajax_referer( 'frm_ajax', 'nonce' );
198
199
		if ( ! isset( $_POST['license'] ) || empty( $_POST['license'] ) ) {
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
200
			wp_die( __( 'Oops! You forgot to enter your license number.', 'formidable' ) );
201
		}
202
203
		$license = stripslashes( sanitize_text_field( $_POST['license'] ) );
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
204
		$plugin_slug = sanitize_text_field( $_POST['plugin'] );
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_POST
Loading history...
205
		$this_plugin = self::get_addon( $plugin_slug );
206
		$this_plugin->set_license( $license );
207
		$this_plugin->license = $license;
208
209
		$response = $this_plugin->get_license_status();
210
		$response['message'] = '';
211
		$response['success'] = false;
212
213
		if ( $response['error'] ) {
214
			$response['message'] = $response['status'];
215
		} else {
216
			$messages = $this_plugin->get_messages();
217
			if ( is_string( $response['status'] ) && isset( $messages[ $response['status'] ] ) ) {
218
				$response['message'] = $messages[ $response['status'] ];
219
			} else {
220
				$response['message'] = FrmAppHelper::kses( $response['status'], array( 'a' ) );
221
			}
222
223
			$is_valid = false;
224
			if ( $response['status'] == 'valid' ) {
225
				$is_valid = 'valid';
226
				$response['success'] = true;
227
			}
228
			$this_plugin->set_active( $is_valid );
229
		}
230
231
		echo json_encode( $response );
232
		wp_die();
233
	}
234
235
	private function get_license_status() {
236
		$response = array( 'status' => 'missing', 'error' => true );
237
		if ( empty( $this->license ) ) {
238
			$response['error'] = false;
239
			return $response;
240
		}
241
242
		try {
243
			$response['error'] = false;
244
			$license_data = $this->send_mothership_request( 'activate_license' );
245
246
			// $license_data->license will be either "valid" or "invalid"
247
			if ( is_array( $license_data ) ) {
248
				if ( in_array( $license_data['license'], array( 'valid', 'invalid' ) ) ) {
249
					$response['status'] = $license_data['license'];
250
				}
251
			} else {
252
				$response['status'] = $license_data;
253
			}
254
		} catch ( Exception $e ) {
255
			$response['status'] = $e->getMessage();
256
		}
257
258
		return $response;
259
	}
260
261
	private function get_messages() {
262
		return array(
263
			'valid'   => __( 'Your license has been activated. Enjoy!', 'formidable' ),
264
			'invalid' => __( 'That license key is invalid', 'formidable' ),
265
			'expired' => __( 'That license is expired', 'formidable' ),
266
			'revoked' => __( 'That license has been refunded', 'formidable' ),
267
			'no_activations_left' => __( 'That license has been used on too many sites', 'formidable' ),
268
			'invalid_item_id' => __( 'Oops! That is the wrong license key for this plugin.', 'formidable' ),
269
			'missing' => __( 'That license key is invalid', 'formidable' ),
270
		);
271
	}
272
273
	public static function deactivate() {
274
		FrmAppHelper::permission_check('frm_change_settings');
275
		check_ajax_referer( 'frm_ajax', 'nonce' );
276
277
		$plugin_slug = sanitize_text_field( $_POST['plugin'] );
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_POST
Loading history...
278
		$this_plugin = self::get_addon( $plugin_slug );
279
		$license = $this_plugin->get_license();
280
		$this_plugin->license = $license;
281
282
		$response = array( 'success' => false, 'message' => '' );
283
		try {
284
			// $license_data->license will be either "deactivated" or "failed"
285
			$license_data = $this_plugin->send_mothership_request( 'deactivate_license' );
286
			if ( is_array( $license_data ) && $license_data['license'] == 'deactivated' ) {
287
				$response['success'] = true;
288
				$response['message'] = __( 'That license was removed successfully', 'formidable' );
289
			} else {
290
				$response['message'] = __( 'There was an error deactivating your license.', 'formidable' );
291
			}
292
		} catch ( Exception $e ) {
293
			$response['message'] = $e->getMessage();
294
		}
295
296
		$this_plugin->clear_license();
297
298
		echo json_encode( $response );
299
		wp_die();
300
	}
301
302
	public function send_mothership_request( $action ) {
303
		$api_params = array(
304
			'edd_action' => $action,
305
			'license'    => $this->license,
306
			'item_name'  => urlencode( $this->plugin_name ),
307
			'url'        => home_url(),
308
		);
309
		if ( is_numeric( $this->download_id ) ) {
310
			$api_params['item_id'] = absint( $this->download_id );
311
		}
312
313
		$arg_array = array(
314
			'body'      => $api_params,
315
			'timeout'   => 25,
316
			'sslverify' => false,
317
			'user-agent' => $this->plugin_slug . '/' . $this->version . '; ' . get_bloginfo( 'url' ),
318
		);
319
320
		$resp = wp_remote_post( $this->store_url, $arg_array );
321
		$body = wp_remote_retrieve_body( $resp );
322
323
		$message = __( 'Your License Key was invalid', 'formidable' );
324
		if ( is_wp_error( $resp ) ) {
325
			$message = sprintf( __( 'You had an error communicating with Formidable Pro\'s API. %1$sClick here%2$s for more information.', 'formidable' ), '<a href="http://formidablepro.com/knowledgebase/why-cant-i-activate-formidable-pro/" target="_blank">', '</a>');
326
			$message .= ' ' . $resp->get_error_message();
327
		} else if ( $body == 'error' || is_wp_error( $body ) ) {
328
			$message = __( 'You had an HTTP error connecting to Formidable Pro\'s API', 'formidable' );
329
		} else {
330
			$json_res = json_decode( $body, true );
331
			if ( null !== $json_res ) {
332
				if ( is_array( $json_res ) && isset( $json_res['error'] ) ) {
333
					$message = $json_res['error'];
334
				} else {
335
					$message = $json_res;
336
				}
337
			} else if ( isset( $resp['response'] ) && isset( $resp['response']['code'] ) ) {
338
				$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...
339
			}
340
		}
341
342
		return $message;
343
	}
344
345
    public function manually_queue_update() {
346
        set_site_transient( 'update_plugins', null );
347
    }
348
}
349