Completed
Push — master ( bf9b88...27918d )
by Stephanie
03:04
created

FrmAddon::test_transient()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 0
dl 0
loc 6
rs 9.4285
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
		$last_checked = get_site_option( $this->transient_key() );
174
		$seven_days_ago = date( 'Y-m-d H:i:s', strtotime('-7 days') );
175
176
		if ( ! $last_checked || $last_checked < $seven_days_ago ) {
177
			update_site_option( $this->transient_key(), date( 'Y-m-d H:i:s' ) ); // check weekly
178
			$response = $this->get_license_status();
179
			if ( $response['status'] == 'revoked' ) {
180
				$this->clear_license();
181
			}
182
		}
183
	}
184
185
	private function transient_key() {
186
		return 'frm_' . md5( sanitize_key( $this->license . '_' . $this->plugin_slug ) );
187
	}
188
189
	public static function activate() {
190
		FrmAppHelper::permission_check('frm_change_settings');
191
	 	check_ajax_referer( 'frm_ajax', 'nonce' );
192
193
		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...
194
			wp_die( __( 'Oops! You forgot to enter your license number.', 'formidable' ) );
195
		}
196
197
		$license = stripslashes( sanitize_text_field( $_POST['license'] ) );
1 ignored issue
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
198
		$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...
199
		$this_plugin = self::get_addon( $plugin_slug );
200
		$this_plugin->set_license( $license );
201
		$this_plugin->license = $license;
202
203
		$response = $this_plugin->get_license_status();
204
		$response['message'] = '';
205
		$response['success'] = false;
206
207
		if ( $response['error'] ) {
208
			$response['message'] = $response['status'];
209
		} else {
210
			$messages = $this_plugin->get_messages();
211
			if ( is_string( $response['status'] ) && isset( $messages[ $response['status'] ] ) ) {
212
				$response['message'] = $messages[ $response['status'] ];
213
			} else {
214
				$response['message'] = FrmAppHelper::kses( $response['status'], array( 'a' ) );
215
			}
216
217
			$is_valid = false;
218
			if ( $response['status'] == 'valid' ) {
219
				$is_valid = 'valid';
220
				$response['success'] = true;
221
			}
222
			$this_plugin->set_active( $is_valid );
223
		}
224
225
		echo json_encode( $response );
226
		wp_die();
227
	}
228
229
	private function get_license_status() {
230
		$response = array( 'status' => 'missing', 'error' => true );
231
		if ( empty( $this->license ) ) {
232
			$response['error'] = false;
233
			return $response;
234
		}
235
236
		try {
237
			$response['error'] = false;
238
			$license_data = $this->send_mothership_request( 'activate_license' );
239
240
			// $license_data->license will be either "valid" or "invalid"
241
			if ( is_array( $license_data ) ) {
242
				if ( in_array( $license_data['license'], array( 'valid', 'invalid' ) ) ) {
243
					$response['status'] = $license_data['license'];
244
				}
245
			} else {
246
				$response['status'] = $license_data;
247
			}
248
		} catch ( Exception $e ) {
249
			$response['status'] = $e->getMessage();
250
		}
251
252
		return $response;
253
	}
254
255
	private function get_messages() {
256
		return array(
257
			'valid'   => __( 'Your license has been activated. Enjoy!', 'formidable' ),
258
			'invalid' => __( 'That license key is invalid', 'formidable' ),
259
			'expired' => __( 'That license is expired', 'formidable' ),
260
			'revoked' => __( 'That license has been refunded', 'formidable' ),
261
			'no_activations_left' => __( 'That license has been used on too many sites', 'formidable' ),
262
			'invalid_item_id' => __( 'Oops! That is the wrong license key for this plugin.', 'formidable' ),
263
			'missing' => __( 'That license key is invalid', 'formidable' ),
264
		);
265
	}
266
267
	public static function deactivate() {
268
		FrmAppHelper::permission_check('frm_change_settings');
269
		check_ajax_referer( 'frm_ajax', 'nonce' );
270
271
		$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...
272
		$this_plugin = self::get_addon( $plugin_slug );
273
		$license = $this_plugin->get_license();
274
		$this_plugin->license = $license;
275
276
		$response = array( 'success' => false, 'message' => '' );
277
		try {
278
			// $license_data->license will be either "deactivated" or "failed"
279
			$license_data = $this_plugin->send_mothership_request( 'deactivate_license' );
280
			if ( is_array( $license_data ) && $license_data['license'] == 'deactivated' ) {
281
				$response['success'] = true;
282
				$response['message'] = __( 'That license was removed successfully', 'formidable' );
283
			} else {
284
				$response['message'] = __( 'There was an error deactivating your license.', 'formidable' );
285
			}
286
		} catch ( Exception $e ) {
287
			$response['message'] = $e->getMessage();
288
		}
289
290
		$this_plugin->clear_license();
291
292
		echo json_encode( $response );
293
		wp_die();
294
	}
295
296
	public function send_mothership_request( $action ) {
297
		$api_params = array(
298
			'edd_action' => $action,
299
			'license'    => $this->license,
300
			'url'        => home_url(),
301
		);
302
		if ( is_numeric( $this->download_id ) ) {
303
			$api_params['item_id'] = absint( $this->download_id );
304
		} else {
305
			$api_params['item_name'] = urlencode( $this->plugin_name );
306
		}
307
308
		$arg_array = array(
309
			'body'      => $api_params,
310
			'timeout'   => 25,
311
			'sslverify' => false,
312
			'user-agent' => $this->plugin_slug . '/' . $this->version . '; ' . get_bloginfo( 'url' ),
313
		);
314
315
		$resp = wp_remote_post( $this->store_url, $arg_array );
316
		$body = wp_remote_retrieve_body( $resp );
317
318
		$message = __( 'Your License Key was invalid', 'formidable' );
319
		if ( is_wp_error( $resp ) ) {
320
			$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>');
321
			$message .= ' ' . $resp->get_error_message();
322
		} else if ( $body == 'error' || is_wp_error( $body ) ) {
323
			$message = __( 'You had an HTTP error connecting to Formidable Pro\'s API', 'formidable' );
324
		} else {
325
			$json_res = json_decode( $body, true );
326
			if ( null !== $json_res ) {
327
				if ( is_array( $json_res ) && isset( $json_res['error'] ) ) {
328
					$message = $json_res['error'];
329
				} else {
330
					$message = $json_res;
331
				}
332
			} else if ( isset( $resp['response'] ) && isset( $resp['response']['code'] ) ) {
333
				$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...
334
			}
335
		}
336
337
		return $message;
338
	}
339
340
    public function manually_queue_update() {
341
        set_site_transient( 'update_plugins', null );
342
    }
343
}
344