Passed
Push — master ( 59650c...0b7aa3 )
by Chris
11:04 queued 06:15
created

MonsterInsights_API_Auth   F

Complexity

Total Complexity 154

Size/Duplication

Total Lines 562
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 300
c 2
b 0
f 0
dl 0
loc 562
rs 2
wmc 154

21 Methods

Rating   Name   Duplication   Size   Complexity  
A is_installed() 0 5 1
C delete_auth() 0 42 15
A __construct() 0 15 1
A get_type() 0 3 2
A rauthenticate() 0 33 6
A verify_auth() 0 16 6
D maybe_authenticate() 0 50 16
A generate_tt() 0 2 1
D authenticate_listener() 0 66 19
A rotate_tt() 0 3 2
A uninstall_network_auth() 0 25 3
A get_tt() 0 8 4
A get_sitei() 0 16 5
D reauthenticate_listener() 0 67 18
A validate_tt() 0 3 1
F maybe_delete() 0 38 15
A is_network_admin() 0 2 2
A before_redirect() 0 13 4
C maybe_verify() 0 33 13
A get_route() 0 4 1
F maybe_reauthenticate() 0 50 19

How to fix   Complexity   

Complex Class

Complex classes like MonsterInsights_API_Auth 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.

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 MonsterInsights_API_Auth, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Google Client admin class.
4
 *
5
 * Handles retrieving whether a particular notice has been dismissed or not,
6
 * as well as marking a notice as dismissed.
7
 *
8
 * @since 7.0.0
9
 *
10
 * @package MonsterInsights
11
 * @subpackage GA Client
12
 * @author  Chris Christoff
13
 */
14
15
// Exit if accessed directly
16
if ( ! defined( 'ABSPATH' ) ) {
17
	exit;
18
}
19
20
final class MonsterInsights_API_Auth {
21
22
	/**
23
	 * Primary class constructor.
24
	 *
25
	 * @access public
26
	 * @since 7.0.0
27
	 */
28
	public function __construct() {
29
30
		// Authentication Actions
31
		add_action( 'wp_ajax_monsterinsights_maybe_authenticate',    array( $this, 'maybe_authenticate' ) );
32
		add_action( 'wp_ajax_monsterinsights_maybe_reauthenticate',  array( $this, 'maybe_reauthenticate' ) );
33
		add_action( 'wp_ajax_monsterinsights_maybe_verify',          array( $this, 'maybe_verify' ) );
34
		add_action( 'wp_ajax_monsterinsights_maybe_delete',          array( $this, 'maybe_delete' ) );
35
36
		add_action( 'admin_init',          							 array( $this, 'authenticate_listener' ) );
37
		add_action( 'admin_init',          							 array( $this, 'reauthenticate_listener' ) );
38
39
		add_action( 'wp_ajax_nopriv_monsterinsights_is_installed',    array( $this, 'is_installed' ) );
40
		add_action( 'wp_ajax_nopriv_monsterinsights_rauthenticate',   array( $this, 'rauthenticate' ) );
41
42
		add_filter( 'monsterinsights_maybe_authenticate_siteurl', array( $this, 'before_redirect' ) );
43
	}
44
45
	public function get_tt(){
46
		$tt = is_network_admin() ? get_site_option( 'monsterinsights_network_tt', '' ) : get_option( 'monsterinsights_site_tt', '' );
47
		if ( empty( $tt ) ) {
48
			// if TT is empty, generate a new one, save it and then return it
49
			$tt = $this->generate_tt();
50
			$this->is_network_admin() ? update_site_option( 'monsterinsights_network_tt', $tt ) : update_option( 'monsterinsights_site_tt', $tt );
51
		}
52
		return $tt;
53
	}
54
55
	public function rotate_tt(){
56
		$tt = $this->generate_tt();
57
		is_network_admin() ? update_site_option( 'monsterinsights_network_tt', $tt ) : update_option( 'monsterinsights_site_tt', $tt );
58
	}
59
60
	public function generate_tt(){
61
		return hash( 'sha512', wp_generate_password( 128, true, true ) . AUTH_SALT . uniqid( "", true ) );
62
	}
63
64
	public function validate_tt( $passed_tt = '' ) {
65
		$tt = $this->get_tt();
66
		return hash_equals( $tt, $passed_tt );
67
	}
68
69
	public function is_installed() {
70
		wp_send_json_success(
71
			array(
72
				'version'   => MONSTERINSIGHTS_VERSION,
73
				'pro'   	=> monsterinsights_is_pro_version(),
74
			)
75
		);
76
	}
77
78
	public function maybe_authenticate(){
79
80
		// Check nonce
81
		check_ajax_referer( 'mi-admin-nonce', 'nonce' );
82
83
		// current user can authenticate
84
		if ( ! current_user_can( 'monsterinsights_save_settings' ) ) {
85
			wp_send_json_error( array(	'message' => __( "You don't have permission to authenticate MonsterInsights.", 'google-analytics-for-wordpress' ) ) );
86
		}
87
88
		if ( ! empty( $_REQUEST['isnetwork'] ) && $_REQUEST['isnetwork'] ) {
89
			define( 'WP_NETWORK_ADMIN', true );
90
		}
91
92
		// Only for Pro users, require a license key to be entered first so we can link to things.
93
		if ( monsterinsights_is_pro_version() ) {
94
			$valid = is_network_admin() ? MonsterInsights()->license->is_network_licensed() : MonsterInsights()->license->is_site_licensed();
95
			if ( ! $valid ) {
96
				wp_send_json_error( array( 'message' => __( "Cannot authenticate. Please enter a valid, active license key for MonsterInsights Pro into the settings.", 'google-analytics-for-wordpress' ) ) );
97
			}
98
		}
99
100
		// we do not have a current auth
101
		if ( ! $this->is_network_admin() && MonsterInsights()->auth->is_authed() ) {
102
			wp_send_json_error( array(	'message' => __( "Cannot authenticate. Please re-authenticate.", 'google-analytics-for-wordpress' ) ) );
103
		} else if ( $this->is_network_admin() && MonsterInsights()->auth->is_network_authed() ) {
104
			wp_send_json_error( array(	'message' => __( "Cannot network authenticate. Please re-authenticate on the network settings panel.", 'google-analytics-for-wordpress' ) ) );
105
		}
106
107
		$sitei = $this->get_sitei();
108
		//update_network_option(  get_current_network_id(), 'monsterinsights_network_sitei', $sitei );
109
110
		$siteurl = add_query_arg( array(
111
			'tt'        => $this->get_tt(),
112
			'sitei'     => $sitei,
113
			'miversion' => MONSTERINSIGHTS_VERSION,
114
			'ajaxurl'   => admin_url( 'admin-ajax.php' ),
115
			'network'   => is_network_admin() ? 'network' : 'site',
116
			'siteurl'   => is_network_admin() ? network_admin_url() : site_url(),
117
			'return'    => is_network_admin() ? network_admin_url( 'admin.php?page=monsterinsights_network' ) : admin_url( 'admin.php?page=monsterinsights_settings' ),
118
			'testurl'   => 'https://' . monsterinsights_get_api_url() . 'test/',
119
		 ), $this->get_route( 'https://' . monsterinsights_get_api_url() . 'auth/new/{type}' ) );
120
121
		if ( monsterinsights_is_pro_version() ) {
122
			$key     = is_network_admin() ? MonsterInsights()->license->get_network_license_key() : MonsterInsights()->license->get_site_license_key();
123
			$siteurl = add_query_arg( 'license', $key, $siteurl );
124
		}
125
126
		$siteurl = apply_filters( 'monsterinsights_maybe_authenticate_siteurl', $siteurl );
127
		wp_send_json_success( array( 'redirect' => $siteurl ) );
128
	}
129
130
	public function rauthenticate() {
131
		// Check for missing params
132
		$reqd_args = array( 'key', 'token', 'ua', 'miview', 'a', 'w', 'p', 'tt', 'network' );
133
		foreach ( $reqd_args as $arg ) {
134
			if ( empty( $_REQUEST[$arg] ) ) {
135
				wp_send_json_error(
136
					array(
137
						'error'   => 'authenticate_missing_arg',
138
						'message' => 'Authenticate missing parameter: ' . $arg,
139
						'version'   => MONSTERINSIGHTS_VERSION,
140
						'pro'   	=> monsterinsights_is_pro_version(),
141
					)
142
				);
143
			}
144
		}
145
146
		if ( ! empty( $_REQUEST['network'] ) && 'network' === $_REQUEST['network'] ) {
147
			define( 'WP_NETWORK_ADMIN', true );
148
		}
149
150
		if ( ! $this->validate_tt( $_REQUEST['tt'] ) ) {
151
			wp_send_json_error(
152
				array(
153
					'error'   => 'authenticate_invalid_tt',
154
					'message' => 'Invalid TT sent',
155
					'version'   => MONSTERINSIGHTS_VERSION,
156
					'pro'   	=> monsterinsights_is_pro_version(),
157
				)
158
			);
159
		}
160
161
		// If the tt is validated, send a success response to trigger the regular auth process.
162
		wp_send_json_success();
163
	}
164
165
	public function authenticate_listener(){
166
		// Make sure it's for us
167
		if ( empty( $_REQUEST['mi-oauth-action'] ) || $_REQUEST['mi-oauth-action'] !== 'auth' ) {
168
			return;
169
		}
170
171
		// User can authenticate
172
		if ( ! current_user_can( 'monsterinsights_save_settings' ) ) {
173
			return;
174
		}
175
176
		// Invalid request
177
		if ( empty( $_REQUEST['tt'] ) || ! $this->validate_tt( $_REQUEST['tt'] ) ) {
178
			return;
179
		}
180
181
		// Make sure has required params
182
		if ( empty( $_REQUEST['key'] )      ||
183
			 empty( $_REQUEST['token'] )    ||
184
			 empty( $_REQUEST['ua'] )       ||
185
			 empty( $_REQUEST['miview'] )   ||
186
			 empty( $_REQUEST['a'] )        ||
187
			 empty( $_REQUEST['w'] )        ||
188
			 empty( $_REQUEST['p'] )
189
		) {
190
			return;
191
		}
192
193
		// Invalid UA code
194
		$ua = monsterinsights_is_valid_ua( $_REQUEST['ua'] );
195
		if ( empty( $ua ) ) {
196
			return;
197
		}
198
199
		$profile = array(
200
			'key'      => sanitize_text_field( $_REQUEST['key'] ),
201
			'token'    => sanitize_text_field( $_REQUEST['token'] ),
202
			'ua'       => monsterinsights_is_valid_ua( $_REQUEST['ua'] ),
203
			'viewname' => sanitize_text_field( $_REQUEST['miview'] ),
204
			'a'        => sanitize_text_field( $_REQUEST['a'] ), // AccountID
205
			'w'        => sanitize_text_field( $_REQUEST['w'] ), // PropertyID
206
			'p'        => sanitize_text_field( $_REQUEST['p'] ), // View ID
207
			'siteurl'  => site_url(),
208
			'neturl'   => network_admin_url(),
209
		);
210
211
		$worked = $this->verify_auth( $profile );
212
		if ( ! $worked || is_wp_error( $worked ) ) {
213
			return;
214
		}
215
216
		// Save Profile
217
		$this->is_network_admin() ? MonsterInsights()->auth->set_network_analytics_profile( $profile ) : MonsterInsights()->auth->set_analytics_profile( $profile );
0 ignored issues
show
Bug Best Practice introduced by
The property $auth is declared protected in MonsterInsights_Lite. Since you implement __get, consider adding a @property or @property-read.
Loading history...
218
219
		// Clear cache
220
		$where = $this->is_network_admin() ? 'network' : 'site';
221
		MonsterInsights()->reporting->delete_aggregate_data( $where );
222
223
		$url = $this->is_network_admin() ? network_admin_url( 'admin.php?page=monsterinsights_network' )  : admin_url( 'admin.php?page=monsterinsights_settings' ) ;
224
		$url = add_query_arg( array(
225
			 'mi_action' => 'auth',
226
			 'success'   => 'true',
227
			), $url );
228
		$url = apply_filters( 'monsterinsights_auth_success_redirect_url', $url );
229
		wp_safe_redirect( $url );
230
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
231
	}
232
233
	public function maybe_reauthenticate(){
234
235
		// Check nonce
236
		check_ajax_referer( 'mi-admin-nonce', 'nonce' );
237
238
		// current user can authenticate
239
		if ( ! current_user_can( 'monsterinsights_save_settings' ) ) {
240
			wp_send_json_error( array(	'message' => __( "You don't have permission to re-authenticate MonsterInsights.", 'google-analytics-for-wordpress' ) ) );
241
		}
242
243
		if ( ! empty( $_REQUEST['isnetwork'] ) && $_REQUEST['isnetwork'] ) {
244
			define( 'WP_NETWORK_ADMIN', true );
245
		}
246
247
		// Only for Pro users, require a license key to be entered first so we can link to things.
248
		if ( monsterinsights_is_pro_version() ) {
249
			$valid = is_network_admin() ? MonsterInsights()->license->is_network_licensed() : MonsterInsights()->license->is_site_licensed();
250
			if ( monsterinsights_is_pro_version() && ! $valid ) {
251
				wp_send_json_error( array( 'message' => __( "Cannot re-authenticate. Please enter a valid, active license key for MonsterInsights Pro into the settings.", 'google-analytics-for-wordpress' ) ) );
252
			}
253
		}
254
255
		// we do have a current auth
256
		if ( ! $this->is_network_admin() && ! MonsterInsights()->auth->is_authed() ) {
257
			wp_send_json_error( array(	'message' => __( "Cannot re-authenticate. Please authenticate.", 'google-analytics-for-wordpress' ) ) );
258
		} else if ( $this->is_network_admin() && ! MonsterInsights()->auth->is_network_authed() ) {
259
			wp_send_json_error( array(	'message' => __( "Cannot re-authenticate the network. Please authenticate on the network settings panel.", 'google-analytics-for-wordpress' ) ) );
260
		}
261
262
		$siteurl = add_query_arg( array(
263
			'tt'        => $this->get_tt(),
264
			'sitei'     => $this->get_sitei(),
265
			'miversion' => MONSTERINSIGHTS_VERSION,
266
			'ajaxurl'   => admin_url( 'admin-ajax.php' ),
267
			'network'   => is_network_admin() ? 'network' : 'site',
268
			'siteurl'   => is_network_admin() ? network_admin_url() : site_url(),
269
			'key'       => is_network_admin() ? MonsterInsights()->auth->get_network_key() : MonsterInsights()->auth->get_key(),
270
			'token'     => is_network_admin() ? MonsterInsights()->auth->get_network_token() : MonsterInsights()->auth->get_token(),
271
			'return'    => is_network_admin() ? network_admin_url( 'admin.php?page=monsterinsights_network' ) : admin_url( 'admin.php?page=monsterinsights_settings' ),
272
			'testurl'   => 'https://' . monsterinsights_get_api_url() . 'test/',
273
		 ), $this->get_route( 'https://' . monsterinsights_get_api_url() . 'auth/reauth/{type}' ) );
274
275
		if ( monsterinsights_is_pro_version() ) {
276
			$key     = is_network_admin() ? MonsterInsights()->license->get_network_license_key() : MonsterInsights()->license->get_site_license_key();
277
			$siteurl = add_query_arg( 'license', $key, $siteurl );
278
		}
279
280
		$siteurl = apply_filters( 'monsterinsights_maybe_authenticate_siteurl', $siteurl );
281
282
		wp_send_json_success( array( 'redirect' => $siteurl ) );
283
	}
284
285
	public function reauthenticate_listener(){
286
		// Make sure it's for us
287
		if ( empty( $_REQUEST['mi-oauth-action'] ) || $_REQUEST['mi-oauth-action'] !== 'reauth' ) {
288
			return;
289
		}
290
291
		// User can authenticate
292
		if ( ! current_user_can( 'monsterinsights_save_settings' ) ) {
293
			return;
294
		}
295
296
		// Invalid request
297
		if ( empty( $_REQUEST['tt'] ) || ! $this->validate_tt( $_REQUEST['tt'] ) ) {
298
			return;
299
		}
300
301
		// Make sure has required params
302
		if (
303
			 empty( $_REQUEST['ua'] )       ||
304
			 empty( $_REQUEST['miview'] )   ||
305
			 empty( $_REQUEST['a'] )        ||
306
			 empty( $_REQUEST['w'] )        ||
307
			 empty( $_REQUEST['p'] )
308
		) {
309
			return;
310
		}
311
312
		// Invalid UA code
313
		$ua = monsterinsights_is_valid_ua( $_REQUEST['ua'] );
314
		if ( empty( $ua ) ) {
315
			return;
316
		}
317
318
		// we do have a current auth
319
		$existing = $this->is_network_admin() ? MonsterInsights()->auth->get_network_analytics_profile() : MonsterInsights()->auth->get_analytics_profile();
0 ignored issues
show
Bug Best Practice introduced by
The property $auth is declared protected in MonsterInsights_Lite. Since you implement __get, consider adding a @property or @property-read.
Loading history...
320
		if ( empty( $existing['key'] ) || empty( $existing['token'] ) ) {
321
			return;
322
		}
323
324
		$profile = array(
325
			'key'      => $existing['key'],
326
			'token'    => $existing['token'],
327
			'ua'       => monsterinsights_is_valid_ua( $_REQUEST['ua'] ),
328
			'viewname' => sanitize_text_field( $_REQUEST['miview'] ),
329
			'a'        => sanitize_text_field( $_REQUEST['a'] ),
330
			'w'        => sanitize_text_field( $_REQUEST['w'] ),
331
			'p'        => sanitize_text_field( $_REQUEST['p'] ),
332
			'siteurl'  => site_url(),
333
			'neturl'   => network_admin_url(),
334
		);
335
336
		// Save Profile
337
		$this->is_network_admin() ? MonsterInsights()->auth->set_network_analytics_profile( $profile ) : MonsterInsights()->auth->set_analytics_profile( $profile );
338
339
		// Clear cache
340
		$where = $this->is_network_admin() ? 'network' : 'site';
341
		MonsterInsights()->reporting->delete_aggregate_data( $where );
342
343
		$url = $this->is_network_admin() ? network_admin_url( 'admin.php?page=monsterinsights_network' )  : admin_url( 'admin.php?page=monsterinsights_settings' ) ;
344
		$url = add_query_arg( array(
345
			 'mi_action' => 'reauth',
346
			 'success'   => 'true',
347
			), $url );
348
		$url = apply_filters( 'monsterinsights_reauth_success_redirect_url', $url );
349
350
		wp_safe_redirect( $url );
351
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
352
	}
353
354
	public function maybe_verify(){
355
356
		// Check nonce
357
		check_ajax_referer( 'mi-admin-nonce', 'nonce' );
358
359
		// current user can verify
360
		if ( ! current_user_can( 'monsterinsights_save_settings' ) ) {
361
			wp_send_json_error( array(	'message' => __( "You don't have permission to verify MonsterInsights.", 'google-analytics-for-wordpress' ) ) );
362
		}
363
364
		if ( ! empty( $_REQUEST['isnetwork'] ) && $_REQUEST['isnetwork'] ) {
365
			define( 'WP_NETWORK_ADMIN', true );
366
		}
367
368
		// we have an auth to verify
369
		if ( $this->is_network_admin() && ! MonsterInsights()->auth->is_network_authed() ) {
370
			wp_send_json_error( array(	'message' => __( "Cannot verify. Please authenticate.", 'google-analytics-for-wordpress' ) ) );
371
		} else if ( ! $this->is_network_admin() && ! MonsterInsights()->auth->is_authed() ) {
372
			wp_send_json_error( array(	'message' => __( "Cannot verify. Please authenticate.", 'google-analytics-for-wordpress' ) ) );
373
		}
374
375
		if ( monsterinsights_is_pro_version() ) {
376
			$valid = is_network_admin() ? MonsterInsights()->license->is_network_licensed() : MonsterInsights()->license->is_site_licensed();
377
			if ( ! $valid ) {
378
				wp_send_json_error( array( 'message' => __( "Cannot verify. Please enter a valid, active license key for MonsterInsights Pro into the settings.", 'google-analytics-for-wordpress' ) ) );
379
			}
380
		}
381
382
		$worked = $this->verify_auth();
383
		if ( $worked && ! is_wp_error(  $worked ) ) {
384
			wp_send_json_success( array( 'message' => __( "Successfully verified.", 'google-analytics-for-wordpress' ) ) );
385
		} else {
386
			wp_send_json_error( array( 'message' => __( "Could not verify.", 'google-analytics-for-wordpress' ) ) );
387
		}
388
	}
389
390
	public function verify_auth( $credentials = array() ){
391
		$creds = ! empty( $credentials ) ? $credentials : ( $this->is_network_admin() ? MonsterInsights()->auth->get_network_analytics_profile( true ) : MonsterInsights()->auth->get_analytics_profile( true ) );
0 ignored issues
show
Bug Best Practice introduced by
The property $auth is declared protected in MonsterInsights_Lite. Since you implement __get, consider adding a @property or @property-read.
Loading history...
392
393
		if ( empty( $creds['key'] ) ) {
394
			return new WP_Error( 'validation-error', sprintf( __( 'Verify auth key not passed', 'google-analytics-for-wordpress' ) ) );
395
		}
396
397
		$network = ! empty( $_REQUEST['network'] ) ? $_REQUEST['network'] === 'network' : $this->is_network_admin();
398
		$api   = new MonsterInsights_API_Request( $this->get_route( 'auth/verify/{type}/' ), array( 'network' => $network, 'tt' => $this->get_tt(), 'key' => $creds['key'], 'token' => $creds['token'], 'testurl'   => 'https://' . monsterinsights_get_api_url() . 'test/' ) );
399
		$ret   = $api->request();
400
401
		$this->rotate_tt();
402
		if ( is_wp_error( $ret ) ) {
403
			return $ret;
404
		} else {
405
			return true;
406
		}
407
	}
408
409
	public function maybe_delete(){
410
411
		// Check nonce
412
		check_ajax_referer( 'mi-admin-nonce', 'nonce' );
413
414
		// current user can delete
415
		if ( ! current_user_can( 'monsterinsights_save_settings' ) ) {
416
			wp_send_json_error( array(	'message' => __( "You don't have permission to deauthenticate MonsterInsights.", 'google-analytics-for-wordpress' ) ) );
417
		}
418
419
		if ( ! empty( $_REQUEST['isnetwork'] ) && $_REQUEST['isnetwork'] ) {
420
			define( 'WP_NETWORK_ADMIN', true );
421
		}
422
423
		// we have an auth to delete
424
		if ( $this->is_network_admin() && ! MonsterInsights()->auth->is_network_authed() ) {
425
			wp_send_json_error( array(	'message' => __( "Cannot deauthenticate. You are not currently authed.", 'google-analytics-for-wordpress' ) ) );
426
		} else if ( ! $this->is_network_admin() && ! MonsterInsights()->auth->is_authed() ) {
427
			wp_send_json_error( array(	'message' => __( "Cannot deauthenticate. You are not currently authed.", 'google-analytics-for-wordpress' ) ) );
428
		}
429
430
		if ( monsterinsights_is_pro_version() ) {
431
			$valid = is_network_admin() ? MonsterInsights()->license->is_network_licensed() : MonsterInsights()->license->is_site_licensed();
432
			if ( ! $valid ) {
433
				wp_send_json_error( array( 'message' => __( "Cannot deauthenticate. Please enter a valid, active license key for MonsterInsights Pro into the settings.", 'google-analytics-for-wordpress' ) ) );
434
			}
435
		}
436
437
		$force = ! empty( $_REQUEST['forcedelete'] ) && $_REQUEST['forcedelete'] === 'true';
438
439
		$worked = $this->delete_auth( $force );
440
		if ( $worked && ! is_wp_error(  $worked ) ) {
441
			wp_send_json_success( array( 'message' => __( "Successfully deauthenticated.", 'google-analytics-for-wordpress' ) ) );
442
		} else {
443
			if ( $force ) {
444
				wp_send_json_success( array( 'message' => __( "Successfully force deauthenticated.", 'google-analytics-for-wordpress' ) ) );
445
			} else {
446
				wp_send_json_error( array( 'message' => __( "Could not deauthenticate.", 'google-analytics-for-wordpress' ) ) );
447
			}
448
		}
449
	}
450
451
	public function delete_auth( $force = false ){
452
		if ( $this->is_network_admin() && ! MonsterInsights()->auth->is_network_authed() ) {
0 ignored issues
show
Bug Best Practice introduced by
The property $auth is declared protected in MonsterInsights_Lite. Since you implement __get, consider adding a @property or @property-read.
Loading history...
453
			return false;
454
		} else if ( ! $this->is_network_admin() && ! MonsterInsights()->auth->is_authed() ) {
455
			return false;
456
		}
457
458
		$creds = $this->is_network_admin() ? MonsterInsights()->auth->get_network_analytics_profile( true ) : MonsterInsights()->auth->get_analytics_profile( true );
459
460
		if ( empty( $creds['key'] ) ) {
461
			return false;
462
		}
463
464
		// If we have a new siteurl enabled option and the profile site doesn't match the current site, deactivate anyways
465
		if ( is_network_admin() ) {
466
			$siteurl = network_admin_url();
467
			if ( ! empty( $creds['neturl' ] ) && $creds['neturl'] !== $siteurl ) {
468
				MonsterInsights()->auth->delete_network_analytics_profile( true );
469
				return true;
470
			}
471
		} else {
472
			$siteurl = site_url();
473
			if ( ! empty( $creds['siteurl' ] ) && $creds['siteurl'] !== $siteurl ) {
474
				MonsterInsights()->auth->delete_analytics_profile( true );
475
				return true;
476
			}
477
		}
478
479
		$api   = new MonsterInsights_API_Request( $this->get_route( 'auth/delete/{type}/' ), array( 'network' => $this->is_network_admin(), 'tt' => $this->get_tt(), 'key' => $creds['key'], 'token' => $creds['token'], 'testurl'   => 'https://' . monsterinsights_get_api_url() . 'test/' ) );
480
		$ret   = $api->request();
481
482
		$this->rotate_tt();
483
		if ( is_wp_error( $ret ) && ! $force ) {
484
			return false;
485
		} else {
486
			if ( $this->is_network_admin() ) {
487
				MonsterInsights()->auth->delete_network_analytics_profile( true );
488
			} else {
489
				MonsterInsights()->auth->delete_analytics_profile( true );
490
491
			}
492
			return true;
493
		}
494
	}
495
496
	/**
497
	 * Function to delete network auth in the uninstall process where we can't check if is network admin.
498
	 *
499
	 * @return bool
500
	 */
501
	public function uninstall_network_auth() {
502
503
		if ( ! MonsterInsights()->auth->is_network_authed() ) {
0 ignored issues
show
Bug Best Practice introduced by
The property $auth is declared protected in MonsterInsights_Lite. Since you implement __get, consider adding a @property or @property-read.
Loading history...
504
			return false;
505
		}
506
507
		$creds = MonsterInsights()->auth->get_network_analytics_profile( true );
508
509
		$api = new MonsterInsights_API_Request( $this->get_route( 'auth/delete/{type}/' ), array(
510
			'network' => true,
511
			'tt'      => $this->get_tt(),
512
			'key'     => $creds['key'],
513
			'token'   => $creds['token'],
514
			'testurl'   => 'https://' . monsterinsights_get_api_url() . 'test/'
515
		) );
516
		// Force the network admin url otherwise this will fail not finding the url in relay.
517
		$api->site_url = network_admin_url();
0 ignored issues
show
Bug Best Practice introduced by
The property site_url does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
518
		$ret = $api->request();
519
520
		$this->rotate_tt();
521
		if ( is_wp_error( $ret ) ) {
522
			return false;
523
		} else {
524
			MonsterInsights()->auth->delete_network_analytics_profile( true );
525
			return true;
526
		}
527
	}
528
529
	public function get_type() {
530
		$base = monsterinsights_is_pro_version() ? 'pro' : 'lite';
531
		return apply_filters( 'monsterinsights_api_auth_get_type', $base );
532
	}
533
534
	public function get_route( $route = '' ) {
535
		$route = str_replace( '{type}', $this->get_type(), $route );
536
		$route = trailingslashit( $route );
537
		return $route;
538
	}
539
540
	public function is_network_admin() {
541
		return is_multisite() && is_network_admin();
542
	}
543
544
	public function get_sitei() {
545
		// $sitei = get_network_option(  get_current_network_id(), 'monsterinsights_network_sitei', false );
546
		// if ( ! empty( $sitei ) && strlen( $sitei ) >= 1 ) {
547
		// 	return $sitei;
548
		// }
549
550
		$auth_key        = defined( 'AUTH_KEY' )        ? AUTH_KEY 		  : '';
551
		$secure_auth_key = defined( 'SECURE_AUTH_KEY' ) ? SECURE_AUTH_KEY : '';
552
		$logged_in_key   = defined( 'LOGGED_IN_KEY' )   ? LOGGED_IN_KEY   : '';
553
554
		$sitei = $auth_key . $secure_auth_key . $logged_in_key;
555
		$sitei = preg_replace('/[^a-zA-Z0-9]/', '', $sitei );
556
		$sitei = sanitize_text_field( $sitei );
557
		$sitei = trim( $sitei );
558
		$sitei = ( strlen($sitei) > 30 ) ? substr($sitei, 0, 30 ) : $sitei;
559
		return $sitei;
560
	}
561
562
	/**
563
	 * Logic to run before serving the redirect url during auth.
564
	 *
565
	 * @param string $url
566
	 *
567
	 * @return string
568
	 */
569
	public function before_redirect( $url ) {
570
571
		// If Bad Behavior plugin is installed.
572
		if ( function_exists( 'bb2_read_settings' ) ) {
573
			// Make sure the offsite_forms option is enabled to allow auth.
574
			$bb_settings = get_option( 'bad_behavior_settings' );
575
			if ( empty( $bb_settings['offsite_forms'] ) || false === $bb_settings['offsite_forms'] ) {
576
				$bb_settings['offsite_forms'] = true;
577
				update_option( 'bad_behavior_settings', $bb_settings );
578
			}
579
		}
580
581
		return $url;
582
	}
583
}
584