Completed
Pull Request — master (#553)
by Devin
30:13 queued 13:44
created

Give_Email_Access::init()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 29
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 29
rs 8.439
cc 6
eloc 15
nc 5
nop 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 18 and the first side effect is on line 13.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

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

Loading history...
2
/**
3
 * Class for allowing donors access to their donation w/o logging in;
4
 *
5
 * Based on the work from Matt Gibbs - https://github.com/FacetWP/edd-no-logins
6
 *
7
 * @package     Give
8
 * @copyright   Copyright (c) 2016, WordImpress
9
 * @license     http://opensource.org/licenses/gpl-2.0.php GNU Public License
10
 * @since       1.4
11
 */
12
13
defined( 'ABSPATH' ) or exit;
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
14
15
/**
16
 * Class Give_Email_Access
17
 */
18
class Give_Email_Access {
19
20
	public $token_exists = false;
21
	public $token_email = false;
22
	public $token = false;
23
	public $error = '';
24
25
	private static $instance;
0 ignored issues
show
Unused Code introduced by
The property $instance is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
26
27
	private $verify_throttle;
28
29
	/**
30
	 * Give_Email_Access constructor.
31
	 */
32
	function __construct() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
33
34
		// get it started
35
		add_action( 'init', array( $this, 'init' ) );
36
	}
37
38
39
	/**
40
	 * Register defaults and filters
41
	 */
42
	function init() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
43
44
		$is_enabled = give_get_option( 'email_access' );
45
46
		//Non-logged in users only
47
		if ( is_user_logged_in() || $is_enabled !== 'on' || is_admin() ) {
48
			return;
49
		}
50
51
		//Are db columns setup?
52
		$is_setup = give_get_option( 'email_access_installed' );
53
		if ( empty( $is_setup ) ) {
54
			$this->create_columns();
55
		}
56
57
		// Timeouts
58
		$this->verify_throttle  = apply_filters( 'give_nl_verify_throttle', 300 );
59
		$this->token_expiration = apply_filters( 'give_nl_token_expiration', 7200 );
0 ignored issues
show
Bug introduced by
The property token_expiration does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
60
61
		// Setup login
62
		$this->check_for_token();
63
64
		if ( $this->token_exists ) {
65
			add_filter( 'give_can_view_receipt', '__return_true' );
66
			add_filter( 'give_user_pending_verification', '__return_false' );
67
			add_filter( 'give_get_success_page_uri', array( $this, 'give_success_page_uri' ) );
68
			add_filter( 'give_get_users_purchases_args', array( $this, 'users_purchases_args' ) );
69
		}
70
	}
71
72
	/**
73
	 * Prevent email spamming
74
	 *
75
	 * @param $customer_id
76
	 *
77
	 * @return bool
78
	 */
79
	function can_send_email( $customer_id ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
80
		global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
81
82
		// Prevent multiple emails within X minutes
83
		$throttle = date( 'Y-m-d H:i:s', time() - $this->verify_throttle );
84
85
		// Does a user row exist?
86
		$exists = (int) $wpdb->get_var(
87
			$wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}give_customers WHERE id = %d", $customer_id )
88
		);
89
90
		if ( 0 < $exists ) {
91
			$row_id = (int) $wpdb->get_var(
92
				$wpdb->prepare( "SELECT id FROM {$wpdb->prefix}give_customers WHERE id = %d AND (verify_throttle < %s OR verify_key = '') LIMIT 1", $customer_id, $throttle )
93
			);
94
95
			if ( $row_id < 1 ) {
96
				give_set_error( 'give_email_access_attempts_exhausted', __( 'Please wait a few minutes before requesting a new email access link.', 'give' ) );
97
98
				return false;
99
			}
100
		}
101
102
		return true;
103
	}
104
105
106
	/**
107
	 * Send the user's token
108
	 *
109
	 * @param $customer_id
110
	 * @param $email
111
	 */
112
	function send_email( $customer_id, $email ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
113
114
		$verify_key = wp_generate_password( 20, false );
115
116
		// Generate a new verify key
117
		$this->set_verify_key( $customer_id, $email, $verify_key );
118
119
		// Get the purchase history URL
120
		$page_id = give_get_option( 'history_page' );
121
122
		$access_url = add_query_arg( array(
123
			'give_nl' => $verify_key,
124
		), get_permalink( $page_id ) );
125
126
		//Nice subject and message
127
		$subject = apply_filters( 'give_email_access_token_subject', sprintf( __( 'Your Access Link to %1$s', 'give' ), get_bloginfo( 'name' ) ) );
128
129
		$message = __( 'You or someone in your organization requested an access link be sent to this email address. This is a temporary access link for you to view your donation information. Click on the link below to view:', 'give' ) . "\n\n";
130
131
		$message .= '<a href="' . esc_url( $access_url ) . '" target="_blank">' . __( 'Access My Donation Details', 'give' ) . ' &raquo;</a>';
132
133
		$message .= "\n\n";
134
		$message .= "\n\n";
135
		$message .= __( 'Sincerely,', 'give' );
136
		$message .= "\n" . get_bloginfo( 'name' ) . "\n";
137
138
		$message = apply_filters( 'give_email_access_token_message', $message );
139
140
141
		// Send the email
142
		Give()->emails->__set( 'heading', apply_filters( 'give_email_access_token_heading', __( 'Your Access Link', 'give' ) ) );
143
		Give()->emails->send( $email, $subject, $message );
144
145
	}
146
147
148
	/**
149
	 * Has the user authenticated?
150
	 */
151
	function check_for_token() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
152
153
		$token = isset( $_GET['give_nl'] ) ? $_GET['give_nl'] : '';
154
155
		// Check for cookie
156
		if ( empty( $token ) ) {
157
			$token = isset( $_COOKIE['give_nl'] ) ? $_COOKIE['give_nl'] : '';
158
		}
159
160
		if ( ! empty( $token ) ) {
161
			if ( ! $this->is_valid_token( $token ) ) {
162
				if ( ! $this->is_valid_verify_key( $token ) ) {
163
					return;
164
				}
165
			}
166
167
			$this->token_exists = true;
168
			// Set cookie
169
			setcookie( 'give_nl', $token );
170
		}
171
	}
172
173
	/**
174
	 * Is this a valid token?
175
	 *
176
	 * @param $token
177
	 *
178
	 * @return bool
179
	 */
180
	function is_valid_token( $token ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
181
182
		global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
183
184
		// Make sure token isn't expired
185
		$expires = date( 'Y-m-d H:i:s', time() - $this->token_expiration );
186
187
		$email = $wpdb->get_var(
188
			$wpdb->prepare( "SELECT email FROM {$wpdb->prefix}give_customers WHERE token = %s AND verify_throttle >= %s LIMIT 1", $token, $expires )
189
		);
190
191
		if ( ! empty( $email ) ) {
192
			$this->token_email = $email;
193
			$this->token       = $token;
194
195
			return true;
196
		}
197
198
		//Set error only if email access form isn't being submitted
199
		if ( ! isset( $_POST['give_email'] ) && ! isset( $_POST['_wpnonce'] ) ) {
200
			give_set_error( 'give_email_token_expired', apply_filters( 'give_email_token_expired_message', 'Sorry, your access token has expired. Please request a new one below:', 'give' ) );
201
		}
202
203
204
		return false;
205
206
	}
207
208
	/**
209
	 * Add the verify key to DB
210
	 *
211
	 * @param $customer_id
212
	 * @param $email
213
	 * @param $verify_key
214
	 */
215
	function set_verify_key( $customer_id, $email, $verify_key ) {
0 ignored issues
show
Unused Code introduced by
The parameter $email is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
216
		global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
217
218
		$now = date( 'Y-m-d H:i:s' );
219
220
		// Insert or update?
221
		$row_id = (int) $wpdb->get_var(
222
			$wpdb->prepare( "SELECT id FROM {$wpdb->prefix}give_customers WHERE id = %d LIMIT 1", $customer_id )
223
		);
224
225
		// Update
226
		if ( ! empty( $row_id ) ) {
227
			$wpdb->query(
228
				$wpdb->prepare( "UPDATE {$wpdb->prefix}give_customers SET verify_key = %s, verify_throttle = %s WHERE id = %d LIMIT 1", $verify_key, $now, $row_id )
229
			);
230
		} // Insert
231
		else {
232
			$wpdb->query(
233
				$wpdb->prepare( "INSERT INTO {$wpdb->prefix}give_customers ( verify_key, verify_throttle) VALUES (%s, %s)", $verify_key, $now )
234
			);
235
		}
236
	}
237
238
	/**
239
	 * Is this a valid verify key?
240
	 */
241
	function is_valid_verify_key( $token ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
242
		global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
243
244
		// See if the verify_key exists
245
		$row = $wpdb->get_row(
246
			$wpdb->prepare( "SELECT id, email FROM {$wpdb->prefix}give_customers WHERE verify_key = %s LIMIT 1", $token )
247
		);
248
249
		$now = date( 'Y-m-d H:i:s' );
250
251
		// Set token
252
		if ( ! empty( $row ) ) {
253
			$wpdb->query(
254
				$wpdb->prepare( "UPDATE {$wpdb->prefix}give_customers SET verify_key = '', token = %s, verify_throttle = %s WHERE id = %d LIMIT 1", $token, $now, $row->id )
255
			);
256
257
			$this->token_email = $row->email;
258
			$this->token       = $token;
259
260
			return true;
261
		}
262
263
		return false;
264
	}
265
266
267
	/**
268
	 * Append the token to Give purchase links
269
	 *
270
	 * @param $uri
271
	 *
272
	 * @return string
273
	 */
274
	function give_success_page_uri( $uri ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
275
		if ( $this->token_exists ) {
276
			return add_query_arg( array( 'give_nl' => $this->token ), $uri );
277
		}
278
	}
279
280
281
	/**
282
	 * Force Give to find transactions by purchase email, not user ID
283
	 *
284
	 * @param $args
285
	 *
286
	 * @return mixed
287
	 */
288
	function users_purchases_args( $args ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
289
		$args['user'] = $this->token_email;
290
291
		return $args;
292
	}
293
294
295
	/**
296
	 * Create Columns
297
	 *
298
	 * @description Create the necessary columns for email access
299
	 */
300
	function create_columns() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
301
302
		global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
303
304
		//Create columns in customers table
305
		$query = $wpdb->query( "ALTER TABLE {$wpdb->prefix}give_customers ADD `token` VARCHAR(255) CHARACTER SET utf8 NOT NULL, ADD `verify_key` VARCHAR(255) CHARACTER SET utf8 NOT NULL AFTER `token`, ADD `verify_throttle` DATETIME NOT NULL AFTER `verify_key`" );
306
307
		//Columns added properly
308
		if ( $query ) {
309
			give_update_option( 'email_access_installed', 1 );
310
		}
311
312
	}
313
314
315
}