Test Failed
Push — travis/4010 ( cd7197 )
by Ravinder
12:19
created

give-stripe-helpers.php ➔ give_stripe_get_custom_ffm_fields()   C

Complexity

Conditions 16
Paths 3

Size

Total Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 16
nc 3
nop 2
dl 0
loc 59
rs 5.5666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Give - Stripe Core Helpers
4
 *
5
 * @since 2.5.0
6
 *
7
 * @package    Give
8
 * @subpackage Stripe Core
9
 * @copyright  Copyright (c) 2019, GiveWP
10
 * @license    https://opensource.org/licenses/gpl-license GNU Public License
11
 */
12
13
// Exit, if accessed directly.
14
if ( ! defined( 'ABSPATH' ) ) {
15
	exit;
16
}
17
18
/**
19
 * This function is used to fetch the secret key based on the test mode status.
20
 *
21
 * @since 2.5.0
22
 *
23
 * @return void
24
 */
25
function give_stripe_get_secret_key() {
26
27
	$secret_key = trim( give_get_option( 'live_secret_key' ) );
28
29
	// Update secret key, if test mode is enabled.
30
	if ( give_is_test_mode() ) {
31
		$secret_key = trim( give_get_option( 'test_secret_key' ) );
32
	}
33
34
	return $secret_key;
35
}
36
37
/**
38
 * Is Stripe Checkout Enabled?
39
 *
40
 * @since 2.5.0
41
 *
42
 * @return bool
43
 */
44
function give_stripe_is_checkout_enabled() {
45
	return give_is_setting_enabled( give_get_option( 'stripe_checkout_enabled', 'disabled' ) );
46
}
47
48
/**
49
 * Get Settings for the Stripe account connected via Connect API.
50
 *
51
 * @since 2.5.0
52
 *
53
 * @return mixed
54
 */
55
function give_stripe_get_connect_settings() {
56
57
	$options = array(
58
		'connected_status'     => give_get_option( 'give_stripe_connected' ),
59
		'user_id'              => give_get_option( 'give_stripe_user_id' ),
60
		'access_token'         => give_get_option( 'live_secret_key' ),
61
		'access_token_test'    => give_get_option( 'test_secret_key' ),
62
		'publishable_key'      => give_get_option( 'live_publishable_key' ),
63
		'publishable_key_test' => give_get_option( 'test_publishable_key' ),
64
	);
65
66
	/**
67
	 * This filter hook is used to override the existing stripe connect settings stored in DB.
68
	 *
69
	 * @param array $options List of Stripe Connect settings required to make functionality work.
70
	 *
71
	 * @since 2.5.0
72
	 */
73
	return apply_filters( 'give_stripe_get_connect_settings', $options );
74
}
75
76
/**
77
 * Is Stripe connected using Connect API?
78
 *
79
 * @since 2.5.0
80
 *
81
 * @return bool
82
 */
83
function give_stripe_is_connected() {
84
85
	$settings = give_stripe_get_connect_settings();
86
87
	$user_api_keys_enabled = give_is_setting_enabled( give_get_option( 'stripe_user_api_keys' ) );
88
89
	// Return false, if manual API keys are used to configure Stripe.
90
	if ( $user_api_keys_enabled ) {
91
		return false;
92
	}
93
94
	// Check all the necessary options.
95
	if (
96
		! empty( $settings['connected_status'] ) && '1' === $settings['connected_status']
97
		&& ! empty( $settings['user_id'] )
98
		&& ! empty( $settings['access_token'] )
99
		&& ! empty( $settings['access_token_test'] )
100
		&& ! empty( $settings['publishable_key'] )
101
		&& ! empty( $settings['publishable_key_test'] )
102
	) {
103
		return true;
104
	}
105
106
	// Default return value.
107
	return false;
108
}
109
110
/**
111
 * This function will return connected account options.
112
 *
113
 * @since 2.5.0
114
 *
115
 * @return array
116
 */
117
function give_stripe_get_connected_account_options() {
118
119
	$args = array();
120
121
	if ( give_stripe_is_connected() ) {
122
		$args['stripe_account'] = give_get_option( 'give_stripe_user_id' );
123
	}
124
125
	return $args;
126
}
127
128
/**
129
 * Displays Stripe Connect Button.
130
 *
131
 * @since 2.5.0
132
 *
133
 * @return void
134
 */
135
function give_stripe_connect_button() {
136
137
	$connected = give_get_option( 'give_stripe_connected' );
138
139
	// Prepare Stripe Connect URL.
140
	$link = add_query_arg(
141
		array(
142
			'stripe_action'         => 'connect',
143
			'mode'                  => give_is_test_mode() ? 'test' : 'live',
144
			'return_url'            => rawurlencode( admin_url( 'edit.php?post_type=give_forms&page=give-settings&tab=gateways&section=stripe-settings' ) ),
145
			'website_url'           => get_bloginfo( 'url' ),
146
			'give_stripe_connected' => ! empty( $connected ) ? '1' : '0',
147
		),
148
		esc_url_raw( 'https://connect.givewp.com/stripe/connect.php' )
149
	);
150
151
	return sprintf(
152
		'<a href="%1$s" id="give-stripe-connect"><span>%2$s</span></a>',
153
		esc_url( $link ),
154
        esc_html__( 'Connect with Stripe', 'give' )
155
	);
156
}
157
158
/**
159
 * Stripe Disconnect URL.
160
 *
161
 * @since 2.5.0
162
 *
163
 * @return void
164
 */
165
function give_stripe_disconnect_url() {
166
167
	// Prepare Stripe Disconnect URL.
168
	$link = add_query_arg(
169
		array(
170
			'stripe_action'  => 'disconnect',
171
			'mode'           => give_is_test_mode() ? 'test' : 'live',
172
			'stripe_user_id' => give_get_option( 'give_stripe_user_id' ),
173
			'return_url'     => rawurlencode( admin_url( 'edit.php?post_type=give_forms&page=give-settings&tab=gateways&section=stripe-settings' ) ),
174
		),
175
		esc_url_raw( 'https://connect.givewp.com/stripe/connect.php' )
176
	);
177
178
	echo esc_url( $link );
179
}
180
181
/**
182
 * Get Publishable Key.
183
 *
184
 * @since 2.5.0
185
 *
186
 * @return string
187
 */
188
function give_stripe_get_publishable_key() {
189
190
	$publishable_key = give_get_option( 'live_publishable_key' );
191
192
	if ( give_is_test_mode() ) {
193
		$publishable_key = give_get_option( 'test_publishable_key' );
194
	}
195
196
	return $publishable_key;
197
}
198
199
/**
200
 * Delete all the Give settings options for Stripe Connect.
201
 *
202
 * @since 2.5.0
203
 *
204
 * @return void
205
 */
206
function give_stripe_connect_delete_options() {
207
208
	// Disconnection successful.
209
	// Remove the connect options within the db.
210
	give_delete_option( 'give_stripe_connected' );
211
	give_delete_option( 'give_stripe_user_id' );
212
	give_delete_option( 'live_secret_key' );
213
	give_delete_option( 'test_secret_key' );
214
	give_delete_option( 'live_publishable_key' );
215
	give_delete_option( 'test_publishable_key' );
216
	give_delete_option( "give_stripe_is_live_webhook_exists" );
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal give_stripe_is_live_webhook_exists does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
217
	give_delete_option( "give_stripe_is_test_webhook_exists" );
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal give_stripe_is_test_webhook_exists does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
218
	give_delete_option( "give_stripe_live_webhook_id" );
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal give_stripe_live_webhook_id does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
219
	give_delete_option( "give_stripe_test_webhook_id" );
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal give_stripe_test_webhook_id does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
220
}
221
222
/**
223
 * This function will prepare JSON for default base styles.
224
 *
225
 * @since 2.5.0
226
 *
227
 * @return mixed|string
228
 */
229
function give_stripe_get_default_base_styles() {
230
231
	$float_labels = give_is_float_labels_enabled(
232
		array(
233
			'form_id' => get_the_ID(),
234
		)
235
	);
236
237
	return wp_json_encode(
238
		array(
239
			'color'             => '#32325D',
240
			'fontWeight'        => 500,
241
			'fontSize'          => '16px',
242
			'fontSmoothing'     => 'antialiased',
243
			'::placeholder'     => array(
244
				'color' => $float_labels ? '#CCCCCC' : '#222222',
245
			),
246
			':-webkit-autofill' => array(
247
				'color' => '#e39f48',
248
			),
249
		)
250
	);
251
}
252
253
/**
254
 * This function is used to get the stripe styles.
255
 *
256
 * @since 2.5.0
257
 *
258
 * @return mixed
259
 */
260
function give_stripe_get_stripe_styles() {
261
262
	$default_styles = array(
263
		'base'     => give_stripe_get_default_base_styles(),
264
		'empty'    => false,
265
		'invalid'  => false,
266
		'complete' => false,
267
	);
268
269
	return give_get_option( 'stripe_styles', $default_styles );
0 ignored issues
show
Documentation introduced by
$default_styles is of type array<string,*,{"base":"...e","complete":"false"}>, but the function expects a string|boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
270
}
271
272
/**
273
 * Get Base Styles for Stripe Elements CC Fields.
274
 *
275
 * @since 2.5.0
276
 *
277
 * @return object
278
 */
279
function give_stripe_get_element_base_styles() {
280
281
	$stripe_styles = give_stripe_get_stripe_styles();
282
	$base_styles   = json_decode( $stripe_styles['base'] );
283
284
	return (object) apply_filters( 'give_stripe_get_element_base_styles', $base_styles );
285
}
286
287
/**
288
 * Get Complete Styles for Stripe Elements CC Fields.
289
 *
290
 * @since 2.5.0
291
 *
292
 * @return object
293
 */
294
function give_stripe_get_element_complete_styles() {
295
296
	$stripe_styles   = give_stripe_get_stripe_styles();
297
	$complete_styles = json_decode( $stripe_styles['complete'] );
298
299
	return (object) apply_filters( 'give_stripe_get_element_complete_styles', $complete_styles );
300
}
301
302
/**
303
 * Get Invalid Styles for Stripe Elements CC Fields.
304
 *
305
 * @since 2.5.0
306
 *
307
 * @return object
308
 */
309
function give_stripe_get_element_invalid_styles() {
310
311
	$stripe_styles  = give_stripe_get_stripe_styles();
312
	$invalid_styles = json_decode( $stripe_styles['invalid'] );
313
314
	return (object) apply_filters( 'give_stripe_get_element_invalid_styles', $invalid_styles );
315
}
316
317
/**
318
 * Get Empty Styles for Stripe Elements CC Fields.
319
 *
320
 * @since 2.5.0
321
 *
322
 * @return object
323
 */
324
function give_stripe_get_element_empty_styles() {
325
326
	$stripe_styles = give_stripe_get_stripe_styles();
327
	$empty_styles  = json_decode( $stripe_styles['empty'] );
328
329
	return (object) apply_filters( 'give_stripe_get_element_empty_styles', $empty_styles );
330
}
331
332
/**
333
 * Get Stripe Element Font Styles.
334
 *
335
 * @since 2.5.0
336
 *
337
 * @return string
338
 */
339
function give_stripe_get_element_font_styles() {
340
341
	$font_styles  = '';
0 ignored issues
show
Unused Code introduced by
$font_styles is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
342
	$stripe_fonts = give_get_option( 'stripe_fonts', 'google_fonts' );
343
344
	if ( 'custom_fonts' === $stripe_fonts ) {
345
		$custom_fonts_attributes = give_get_option( 'stripe_custom_fonts' );
346
		$font_styles = json_decode( $custom_fonts_attributes );
347
	} else {
348
		$font_styles = array(
349
			'cssSrc' => give_get_option( 'stripe_google_fonts_url' ),
350
		);
351
	}
352
353
	if ( empty( $font_styles ) ) {
354
		$font_styles = array();
355
	}
356
357
	return apply_filters( 'give_stripe_get_element_font_styles', $font_styles );
358
359
}
360
361
/**
362
 * Get Preferred Locale based on the selection of language.
363
 *
364
 * @since 2.5.0
365
 *
366
 * @return string
367
 */
368
function give_stripe_get_preferred_locale() {
369
370
	$language_code = substr( get_locale(), 0, 2 ); // Get the lowercase language code. For Example, en, es, de.
371
372
	// Return "no" as accepted parameter for norwegian language code "nb" && "nn".
373
	$language_code = in_array( $language_code, array( 'nb', 'nn' ), true ) ? 'no' : $language_code;
374
375
	return apply_filters( 'give_stripe_elements_preferred_locale', $language_code );
376
}
377
378
/**
379
 * Look up the stripe customer id in user meta, and look to recurring if not found yet.
380
 *
381
 * @since 2.5.0
382
 *
383
 * @param int $user_id_or_email The user ID or email to look up.
384
 *
385
 * @return string Stripe customer ID.
386
 */
387
function give_stripe_get_customer_id( $user_id_or_email ) {
388
389
	$user_id            = 0;
390
	$stripe_customer_id = '';
391
392
	// First check the customer meta of purchase email.
393 View Code Duplication
	if ( class_exists( 'Give_DB_Donor_Meta' ) && is_email( $user_id_or_email ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
394
		$donor              = new Give_Donor( $user_id_or_email );
395
		$stripe_customer_id = $donor->get_meta( give_stripe_get_customer_key() );
396
	}
397
398
	// If not found via email, check user_id.
399 View Code Duplication
	if ( class_exists( 'Give_DB_Donor_Meta' ) && empty( $stripe_customer_id ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
400
		$donor              = new Give_Donor( $user_id, true );
401
		$stripe_customer_id = $donor->get_meta( give_stripe_get_customer_key() );
402
	}
403
404
	// Get user ID from customer.
405
	if ( is_email( $user_id_or_email ) && empty( $stripe_customer_id ) ) {
406
407
		$donor = new Give_Donor( $user_id_or_email );
408
		// Pull user ID from customer object.
409
		if ( $donor->id > 0 && ! empty( $donor->user_id ) ) {
410
			$user_id = $donor->user_id;
411
		}
412
	} else {
413
		// This is a user ID passed.
414
		$user_id = $user_id_or_email;
415
	}
416
417
	// If no Stripe customer ID found in customer meta move to wp user meta.
418
	if ( empty( $stripe_customer_id ) && ! empty( $user_id ) ) {
419
420
		$stripe_customer_id = get_user_meta( $user_id, give_stripe_get_customer_key(), true );
0 ignored issues
show
introduced by
get_user_meta() usage is highly discouraged, check VIP documentation on "Working with wp_users"
Loading history...
421
422
	} elseif ( empty( $stripe_customer_id ) && class_exists( 'Give_Recurring_Subscriber' ) ) {
423
424
		// Not found in customer meta or user meta, check Recurring data.
425
		$by_user_id = is_int( $user_id_or_email ) ? true : false;
426
		$subscriber = new Give_Recurring_Subscriber( $user_id_or_email, $by_user_id );
427
428
		if ( $subscriber->id > 0 ) {
429
430
			$verified = false;
431
432
			if ( ( $by_user_id && $user_id_or_email == $subscriber->user_id ) ) {
433
				// If the user ID given, matches that of the subscriber.
434
				$verified = true;
435
			} else {
436
				// If the email used is the same as the primary email.
437
				if ( $subscriber->email == $user_id_or_email ) {
438
					$verified = true;
439
				}
440
441
				// If the email is in the Give's Additional emails.
442
				if ( property_exists( $subscriber, 'emails' ) && in_array( $user_id_or_email, $subscriber->emails ) ) {
443
					$verified = true;
444
				}
445
			}
446
447
			if ( $verified ) {
448
449
				// Backwards compatibility from changed method name.
450
				// We changed the method name in recurring.
451
				if ( method_exists( $subscriber, 'get_recurring_donor_id' ) ) {
452
					$stripe_customer_id = $subscriber->get_recurring_donor_id( 'stripe' );
453
				} elseif ( method_exists( $subscriber, 'get_recurring_customer_id' ) ) {
454
					$stripe_customer_id = $subscriber->get_recurring_customer_id( 'stripe' );
455
				}
456
			}
457
		}
458
459
		if ( ! empty( $stripe_customer_id ) ) {
460
			update_user_meta( $subscriber->user_id, give_stripe_get_customer_key(), $stripe_customer_id );
0 ignored issues
show
introduced by
update_user_meta() usage is highly discouraged, check VIP documentation on "Working with wp_users"
Loading history...
461
		}
462
	}// End if().
463
464
	return $stripe_customer_id;
465
466
}
467
468
/**
469
 * Get the meta key for storing Stripe customer IDs in.
470
 *
471
 * @since 2.5.0
472
 *
473
 * @return string $key
474
 */
475
function give_stripe_get_customer_key() {
476
477
	$key = '_give_stripe_customer_id';
478
479
	if ( give_is_test_mode() ) {
480
		$key .= '_test';
481
	}
482
483
	return $key;
484
}
485
486
/**
487
 * Determines if the shop is using a zero-decimal currency.
488
 *
489
 * @since 2.5.0
490
 *
491
 * @return bool
492
 */
493
function give_stripe_is_zero_decimal_currency() {
494
495
	$ret      = false;
496
	$currency = give_get_currency();
497
498
	switch ( $currency ) {
499
		case 'BIF':
500
		case 'CLP':
501
		case 'DJF':
502
		case 'GNF':
503
		case 'JPY':
504
		case 'KMF':
505
		case 'KRW':
506
		case 'MGA':
507
		case 'PYG':
508
		case 'RWF':
509
		case 'VND':
510
		case 'VUV':
511
		case 'XAF':
512
		case 'XOF':
513
		case 'XPF':
514
			$ret = true;
515
			break;
516
	}
517
518
	return $ret;
519
}
520
521
/**
522
 * Get Statement Descriptor.
523
 *
524
 * Create the Statement Description.
525
 *
526
 * @see https://stripe.com/docs/api/php#create_charge-statement_descriptor
527
 *
528
 * @since 2.5.0
529
 *
530
 * @param array $data List of posted variable while submitting donation.
531
 *
532
 * @return mixed
533
 */
534
function give_stripe_get_statement_descriptor( $data = array() ) {
535
536
	$descriptor_option = give_get_option( 'stripe_statement_descriptor', get_bloginfo( 'name' ) );
537
538
	// Clean the statement descriptor.
539
	$unsupported_characters = array( '<', '>', '"', '\'' );
540
	$statement_descriptor   = mb_substr( $descriptor_option, 0, 22 );
541
	$statement_descriptor   = str_replace( $unsupported_characters, '', $statement_descriptor );
542
543
	return apply_filters( 'give_stripe_statement_descriptor', $statement_descriptor, $data );
544
545
}
546
547
/**
548
 * Get the sequential order number of donation.
549
 *
550
 * @since 2.5.0
551
 *
552
 * @param integer $donation_or_post_id Donation or wp post id.
553
 * @param bool    $check_enabled       Check if sequential-ordering_status is activated or not.
554
 *
555
 * @return bool|string
556
 */
557
function give_stripe_get_sequential_id( $donation_or_post_id, $check_enabled = true ) {
558
	// Check if enabled.
559
	if ( true === $check_enabled ) {
560
		$sequential_ordering = give_get_option( 'sequential-ordering_status' );
561
562
		if ( ! give_is_setting_enabled( $sequential_ordering ) ) {
563
			return false;
564
		}
565
	}
566
567
	return Give()->seq_donation_number->get_serial_code( $donation_or_post_id );
568
}
569
570
/**
571
 * Get Custom FFM Fields.
572
 *
573
 * @param int $form_id     Donation Form ID.
574
 * @param int $donation_id Donation ID.
575
 *
576
 * @since 2.5.0
577
 *
578
 * @return array
579
 */
580
function give_stripe_get_custom_ffm_fields( $form_id, $donation_id = 0 ) {
581
582
	// Bail out, if FFM add-on is not active.
583
	if ( ! class_exists( 'Give_Form_Fields_Manager' ) ) {
584
		return array();
585
	}
586
587
	$ffm_meta     = array();
588
	$ffm_required = array();
589
	$ffm_optional = array();
590
	$field_label  = '';
591
	$ffm_fields   = give_get_meta( $form_id, 'give-form-fields', true );
592
593
	if ( is_array( $ffm_fields ) && count( $ffm_fields ) > 0 ) {
594
595
		// Loop through ffm fields.
596
		foreach ( $ffm_fields as $field ) {
597
598
			if ( $donation_id > 0 ) {
599
				$field_value = give_get_meta( $donation_id, $field['name'], true );
600
			} elseif ( ! empty( $_POST[ $field['name'] ] ) ) { // WPCS: input var ok, sanitization ok, CSRF ok.
601
				$field_value = give_clean( $_POST[ $field['name'] ] ); // WPCS: input var ok, sanitization ok, CSRF ok.
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-sanitized input variable: $_POST
Loading history...
602
				$field_value = give_stripe_ffm_field_value_to_str( $field_value );
603
604
			} else {
605
				$field_value = __( '-- N/A --', 'give' );
606
			}
607
608
			// Strip the number of characters below 450 for custom fields value input when passed to metadata.
609
			if ( strlen( $field_value ) > 450 ) {
610
				$field_value = substr( $field_value, 0, 450 ) . '...';
611
			}
612
613
			if ( ! empty( $field['label'] ) ) {
614
				$field_label = strlen( $field['label'] ) > 25
615
					? trim( substr( $field['label'], 0, 25 ) ) . '...'
616
					: $field['label'];
617
			} elseif ( ! empty( $field['name'] ) ) {
618
				$field_label = strlen( $field['name'] ) > 25
619
					? trim( substr( $field['name'], 0, 25 ) ) . '...'
620
					: $field['name'];
621
			}
622
623
			// Make sure that the required fields are at the top.
624
			$required_field = ! empty( $field['required'] ) ? $field['required'] : '';
625
			if ( give_is_setting_enabled( $required_field ) ) {
626
				$ffm_required[ $field_label ] = is_array( $field_value ) ? implode( ' | ', $field_value ) : $field_value;
627
			} else {
628
				$ffm_optional[ $field_label ] = is_array( $field_value ) ? implode( ' | ', $field_value ) : $field_value;
629
			}
630
631
			$ffm_meta = array_merge( $ffm_required, $ffm_optional );
632
633
		} // End foreach().
634
	} // End if().
635
636
	return $ffm_meta;
637
638
}
639
640
/**
641
 * This function is used to set application information to Stripe.
642
 *
643
 * @since 2.5.0
644
 *
645
 * @return void
646
 */
647
function give_stripe_set_app_info() {
648
649
	try {
650
651
		/**
652
		 * This filter hook is used to change the application name when Stripe add-on is used.
653
		 *
654
		 * Note: This filter hook is for internal purposes only.
655
		 *
656
		 * @since 2.5.0
657
		 */
658
		$application_name = apply_filters( 'give_stripe_get_application_name', 'Give Core' );
659
660
		/**
661
		 * This filter hook is used to chnage the application version when Stripe add-on is used.
662
		 *
663
		 * Note: This filter hook is for internal purposes only.
664
		 *
665
		 * @since 2.5.0
666
		 */
667
		$application_version = apply_filters( 'give_stripe_get_application_version', GIVE_VERSION );
668
669
		\Stripe\Stripe::setAppInfo(
670
			$application_name,
671
			$application_version,
672
			esc_url_raw( 'https://givewp.com' ),
673
			'pp_partner_DKj75W1QYBxBLK' // Partner ID.
674
		);
675
	} catch ( \Stripe\Error\Base $e ) {
676
		Give_Stripe_Logger::log_error( $e, $this->id );
677
	} catch ( Exception $e ) {
678
679
		give_record_gateway_error(
680
			__( 'Stripe Error', 'give' ),
681
			sprintf(
682
				/* translators: %s Exception Error Message */
683
				__( 'Unable to set application information to Stripe. Details: %s', 'give' ),
684
				$e->getMessage()
685
			)
686
		);
687
688
		give_set_error( 'stripe_app_info_error', __( 'Unable to set application information to Stripe. Please try again.', 'give' ) );
689
	} // End try().
690
691
}
692
693
/**
694
 * This function is used to get application fee percentage.
695
 *
696
 * Note: This function is for internal purpose only.
697
 *
698
 * @since 2.5.0
699
 *
700
 * @return int
701
 */
702
function give_stripe_get_application_fee_percentage() {
703
	return 2;
704
}
705
706
/**
707
 * This function is used to calculate application fee amount.
708
 *
709
 * @param int $amount Donation amount.
710
 *
711
 * @since 2.5.0
712
 *
713
 * @return int
714
 */
715
function give_stripe_get_application_fee_amount( $amount ) {
716
	return $amount * give_stripe_get_application_fee_percentage() / 100;
717
}
718
719
/**
720
 * This function is used to fetch the donation id by meta key.
721
 *
722
 * @param string $id   Any String.
723
 * @param string $type intent_id/client_secret
724
 *
725
 * @since 2.5.0
726
 *
727
 * @return void
728
 */
729
function give_stripe_get_donation_id_by( $id, $type ) {
730
731
	global $wpdb;
732
733
	$donation_id = 0;
734
735
	switch ( $type ) {
736
		case 'intent_id':
737
			$donation_id = $wpdb->get_var( $wpdb->prepare( "SELECT donation_id FROM {$wpdb->donationmeta} WHERE meta_key = '_give_stripe_payment_intent_id' AND meta_value = %s LIMIT 1", $id ) );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
738
			break;
739
740
		case 'client_secret':
741
			$donation_id = $wpdb->get_var( $wpdb->prepare( "SELECT donation_id FROM {$wpdb->donationmeta} WHERE meta_key = '_give_stripe_payment_intent_client_secret' AND meta_value = %s LIMIT 1", $id ) );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
742
			break;
743
	}
744
745
	return $donation_id;
746
747
}
748
749
/**
750
 * This function is used to set Stripe API Key.
751
 *
752
 * @since 2.5.0
753
 *
754
 * @return void
755
 */
756
function give_stripe_set_api_key() {
757
758
    try {
759
760
		// Fetch secret key.
761
        $secret_key = give_stripe_get_secret_key();
762
763
		// Set App Info.
764
		give_stripe_set_app_info();
765
766
        // Set secret key.
767
		\Stripe\Stripe::setApiKey( $secret_key );
768
769
	} catch ( \Stripe\Error\Base $e ) {
770
771
		// Log Error.
772
		$this->log_error( $e );
773
774
	} catch ( Exception $e ) {
775
776
		// Something went wrong outside of Stripe.
777
		give_record_gateway_error(
778
			__( 'Stripe Error', 'give' ),
779
			sprintf(
780
			/* translators: %s Exception Message Body */
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 16 spaces, but found 12.
Loading history...
781
				__( 'Unable to set Stripe API Key. Details: %s', 'give' ),
782
				$e->getMessage()
783
			)
784
		);
785
		give_set_error( 'stripe_error', __( 'An error occurred while processing the donation. Please try again.', 'give' ) );
786
787
		// Send donor back to donation form page.
788
		give_send_back_to_checkout( '?payment-mode=' . give_clean( $_GET['payment-mode'] ) );
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_GET
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_GET
Loading history...
789
790
	}
791
792
}
793
794
/**
795
 * This function is used to fetch the webhook key used to store in options table.
796
 *
797
 * @since 2.5.0
798
 *
799
 * @return string
800
 */
801
function give_stripe_get_webhook_key() {
802
803
	$mode = give_stripe_get_payment_mode();
804
805
	return "give_stripe_{$mode}_webhook_id";
806
}
807
808
/**
809
 * This function is used to fetch the webhook id which is stored in DB, if the webhook is set on Stripe.
810
 *
811
 * @since 2.5.0
812
 *
813
 * @return string
814
 */
815
function give_stripe_get_webhook_id() {
816
817
    $key = give_stripe_get_webhook_key();
818
819
	return trim( give_get_option( $key ) );
820
}
821
822
/**
823
 * This function is used to fetch the webhook id which is stored in DB, if the webhook is set on Stripe.
824
 *
825
 * @since 2.5.0
826
 *
827
 * @return string
828
 */
829
function give_stripe_delete_webhook_id() {
830
831
    $key = give_stripe_get_webhook_key();
832
833
	return trim( give_delete_option( $key ) );
834
}
835
836
/**
837
 * This function is used to get the payment mode text. For example, "test" or "live"
838
 *
839
 * @since 2.5.0
840
 *
841
 * @return string
842
 */
843
function give_stripe_get_payment_mode() {
844
845
    $mode = 'live';
846
847
    if ( give_is_test_mode() ) {
848
        $mode = 'test';
849
    }
850
851
    return $mode;
852
}
853
854
/**
855
 * This function will be used to convert upto 2 dimensional array to string as per FFM add-on Repeater field needs.
856
 *
857
 * This function is for internal purpose only.
858
 *
859
 * @param array|string $data Data to be converted to string.
860
 *
861
 * @since 2.5.0
862
 *
863
 * @return array|string
864
 */
865
function give_stripe_ffm_field_value_to_str( $data ) {
866
867
	if ( is_array( $data ) && count( $data ) > 0 ) {
868
		$count = 0;
869
		foreach ( $data as $item ) {
870
			if ( is_array( $item ) && count( $item ) > 0 ) {
871
				$data[ $count ] = implode( ',', $item );
872
			}
873
874
			$count ++;
875
		}
876
877
		$data = implode( '|', $data );
878
	}
879
880
	return $data;
881
}
882
883
/**
884
 * This function will be used to get Stripe transaction id link.
885
 *
886
 * @param int    $donation_id    Donation ID.
887
 * @param string $transaction_id Stripe Transaction ID.
888
 *
889
 * @since 2.5.0
890
 *
891
 * @return string
892
 */
893
function give_stripe_get_transaction_link( $donation_id, $transaction_id = '' ) {
894
895
	// If empty transaction id then get transaction id from donation id.
896
	if ( empty( $transaction_id ) ) {
897
		$transaction_id = give_get_payment_transaction_id( $donation_id );
898
	}
899
900
	$transaction_link = sprintf(
901
		'<a href="%1$s" target="_blank">%2$s</a>',
902
		give_stripe_get_transaction_url( $transaction_id ),
903
		$transaction_id
904
	);
905
906
	return $transaction_link;
907
}
908
909
/**
910
 * This function will return stripe transaction url.
911
 *
912
 * @param string $transaction_id Stripe Transaction ID.
913
 *
914
 * @since 2.5.0
915
 *
916
 * @return string
917
 */
918
function give_stripe_get_transaction_url( $transaction_id ) {
919
920
	$mode = '';
921
922
	if ( give_is_test_mode() ) {
923
		$mode = 'test/';
924
	}
925
926
	$transaction_url = esc_url_raw( "https://dashboard.stripe.com/{$mode}payments/{$transaction_id}" );
927
928
	return $transaction_url;
929
}
930
931
/**
932
 * This function will record errors under Stripe Log.
933
 *
934
 * @param string $title   Log Title.
935
 * @param string $message Log Message.
936
 * @param int    $parent  Parent.
937
 *
938
 * @since 2.5.0
939
 *
940
 * @return int
941
 */
942
function give_stripe_record_log( $title = '', $message = '', $parent = 0 ) {
943
	$title = empty( $title ) ? esc_html__( 'Stripe Error', 'give' ) : $title;
944
945
	return give_record_log( $title, $message, $parent, 'stripe' );
946
}
947
948
/**
949
 * Check if notice dismissed by admin user or not.
950
 *
951
 * @since  2.5.0
952
 *
953
 * @return bool
954
 */
955
function give_stripe_is_connect_banner_dismissed() {
956
957
	$current_user        = wp_get_current_user();
958
	$is_notice_dismissed = false;
959
960
	if ( get_transient( "give_hide_stripe_connect_notice_{$current_user->ID}" ) ) {
961
		$is_notice_dismissed = true;
962
	}
963
964
	return $is_notice_dismissed;
965
}
966