Completed
Pull Request — master (#859)
by Devin
19:40
created

template.php ➔ give_display_email_template_preview()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 40
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 25.7188

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 6
eloc 17
c 5
b 0
f 0
nc 7
nop 0
dl 0
loc 40
rs 8.439
ccs 2
cts 11
cp 0.1818
crap 25.7188
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 26 and the first side effect is on line 14.

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
 * Email Template
4
 *
5
 * @package     Give
6
 * @subpackage  Emails
7
 * @copyright   Copyright (c) 2016, WordImpress
8
 * @license     http://opensource.org/licenses/gpl-2.0.php GNU Public License
9
 * @since       1.0
10
 */
11
12
// Exit if accessed directly
13
if ( ! defined( 'ABSPATH' ) ) {
14
	exit;
15
}
16
17
/**
18
 * Gets all the email templates that have been registered. The list is extendable
19
 * and more templates can be added.
20
 *
21
 * This is simply a wrapper to Give_Email_Templates->get_templates()
22
 *
23
 * @since 1.0
24
 * @return array $templates All the registered email templates.
25
 */
26
function give_get_email_templates() {
27
	$templates = new Give_Emails;
28
29
	return $templates->get_templates();
30
}
31
32
/**
33
 * Email Template Tags.
34
 *
35
 * @since 1.0
36
 *
37
 * @param string $message Message with the template tags.
38
 * @param array  $payment_data Payment Data.
39
 * @param int    $payment_id Payment ID.
40
 * @param bool   $admin_notice Whether or not this is a notification email.
41
 *
42
 * @return string $message Fully formatted message
43
 */
44
function give_email_template_tags( $message, $payment_data, $payment_id, $admin_notice = false ) {
0 ignored issues
show
Unused Code introduced by
The parameter $payment_data 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...
Unused Code introduced by
The parameter $admin_notice 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...
45
	return give_do_email_tags( $message, $payment_id );
46
}
47
48
/**
49
 * Email Preview Template Tags.
50
 *
51
 * Provides sample content for the preview email functionality within settings > email.
52
 *
53
 * @since 1.0
54
 *
55
 * @param string $message Email message with template tags
56
 *
57
 * @return string $message Fully formatted message
58
 */
59
function give_email_preview_template_tags( $message ) {
60
61
	$price = give_currency_filter( give_format_amount( 10.50 ) );
62
63
	$gateway = 'PayPal';
64
65
	$receipt_id = strtolower( md5( uniqid() ) );
66
67
	$payment_id = rand( 1, 100 );
68
69
	$receipt_link = sprintf(
70
		'<a href="%1$s">%2$s</a>',
71
		esc_url( add_query_arg( array( 'payment_key' => $receipt_id, 'give_action' => 'view_receipt' ), home_url() ) ),
72
		esc_html__( 'View the receipt in your browser &raquo;', 'give' )
73
	);
74
75
	$user = wp_get_current_user();
76
77
	$message = str_replace( '{name}', $user->display_name, $message );
78
	$message = str_replace( '{fullname}', $user->display_name, $message );
79
	$message = str_replace( '{username}', $user->user_login, $message );
80
	$message = str_replace( '{date}', date( get_option( 'date_format' ), current_time( 'timestamp' ) ), $message );
81
	$message = str_replace( '{price}', $price, $message );
82
	$message = str_replace( '{donation}', esc_html__( 'Sample Donation Form Title', 'give' ), $message );
83
	$message = str_replace( '{receipt_id}', $receipt_id, $message );
84
	$message = str_replace( '{payment_method}', $gateway, $message );
85
	$message = str_replace( '{sitename}', get_bloginfo( 'name' ), $message );
86
	$message = str_replace( '{payment_id}', $payment_id, $message );
87
	$message = str_replace( '{receipt_link}', $receipt_link, $message );
88
	$message = str_replace( '{pdf_receipt}', '<a href="#">Download Receipt</a>', $message );
89
90
	return wpautop( apply_filters( 'give_email_preview_template_tags', $message ) );
91
}
92
93
/**
94
 * Filter for Email Template Preview Buttons.
95
 *
96
 * @param array $array
97
 *
98
 * @access private
99
 * @since  1.0
100
 * @return array|bool
101
 */
102
function give_email_template_preview( $array ) {
103
104
	if ( ! current_user_can( 'manage_give_settings' ) ) {
105
		return false;
106
	}
107
	$custom_field = array(
108
		'name' => esc_html__( 'Preview Email', 'give' ),
109
		'desc' => esc_html__( 'Click the buttons to preview emails.', 'give' ),
110
		'id'   => 'give_email_preview_buttons',
111
		'type' => 'email_preview_buttons'
112
	);
113
114
	return give_settings_array_insert( $array, 'donation_subject', array( $custom_field ) );
115
116
}
117
118
add_filter( 'give_settings_emails', 'give_email_template_preview' );
119
120
/**
121
 * Output Email Template Preview Buttons.
122
 *
123
 * @access private
124
 * @since  1.0
125
 * @return array
126
 */
127
function give_email_preview_buttons_callback() {
128
	ob_start();
129
	?>
130
	<a href="<?php echo esc_url( add_query_arg( array( 'give_action' => 'preview_email' ), home_url() ) ); ?>" class="button-secondary" target="_blank" title="<?php esc_attr_e( 'Donation Receipt Preview', 'give' ); ?> "><?php esc_html_e( 'Preview Donation Receipt', 'give' ); ?></a>
131
	<a href="<?php echo wp_nonce_url( add_query_arg( array(
132
		'give_action'  => 'send_test_email',
133
		'give-message' => 'sent-test-email',
134
		'tag'          => 'emails'
135
	) ), 'give-test-email' ); ?>" title="<?php esc_attr_e( 'This will send a demo donation receipt to the emails listed below.', 'give' ); ?>" class="button-secondary"><?php esc_html_e( 'Send Test Email', 'give' ); ?></a>
136
	<?php
137
	echo ob_get_clean();
138
}
139
140
/**
141
 * Displays the email preview
142
 *
143
 * @since 1.0
144
 * @return void
145
 */
146
function give_display_email_template_preview() {
147
148
	if ( empty( $_GET['give_action'] ) ) {
149
		return;
150
	}
151
152
	if ( 'preview_email' !== $_GET['give_action'] ) {
153
		return;
154
	}
155
156
	if ( ! current_user_can( 'manage_give_settings' ) ) {
157
		return;
158
	}
159
160
161
	Give()->emails->heading = esc_html__( 'Donation Receipt', 'give' );
0 ignored issues
show
Documentation introduced by
The property $heading is declared private in Give_Emails. Since you implemented __set(), maybe consider adding a @property or @property-write annotation. This makes it easier for IDEs to provide auto-completion.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
162
163
	$payment_id = (int) isset( $_GET['preview_id'] ) ? $_GET['preview_id'] : '';
164
165
	echo give_get_preview_email_header();
166
167
	//Are we previewing an actual payment?
168
	if ( ! empty( $payment_id ) ) {
169
170
		$content = give_get_email_body_content( $payment_id );
171
172
		$preview_content = give_do_email_tags( $content, $payment_id );
173
174
	} else {
175
176
		//No payment ID, use sample preview content
177
		$preview_content = give_email_preview_template_tags( give_get_email_body_content( 0, array() ) );
178
	}
179
180
181
	echo Give()->emails->build_email( $preview_content );
182
183 42
	exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The function give_display_email_template_preview() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
184
185 42
}
186
187 42
add_action( 'init', 'give_display_email_template_preview' );
188
189 42
/**
190
 * Email Template Body.
191 42
 *
192
 * @since 1.0
193 42
 *
194
 * @param int   $payment_id Payment ID
195
 * @param array $payment_data Payment Data
196
 *
197
 * @return string $email_body Body of the email
198
 */
199
function give_get_email_body_content( $payment_id = 0, $payment_data = array() ) {
200
201
	$default_email_body = give_get_default_donation_receipt_email();
202
203
	$email_content = give_get_option( 'donation_receipt' );
204
	$email_content = isset( $email_content ) ? stripslashes( $email_content ) : $default_email_body;
205
206
	$email_body = wpautop( $email_content );
207
208
	$email_body = apply_filters( 'give_donation_receipt_' . Give()->emails->get_template(), $email_body, $payment_id, $payment_data );
209
210 42
	return apply_filters( 'give_donation_receipt', $email_body, $payment_id, $payment_data );
211
}
212 42
213 42
/**
214
 * Donation Notification Template Body.
215 42
 *
216 41
 * @since  1.0
217 41
 *
218 42
 * @param int   $payment_id Payment ID
219 1
 * @param array $payment_data Payment Data
220 1
 *
221
 * @return string $email_body Body of the email
222
 */
223
function give_get_donation_notification_body_content( $payment_id = 0, $payment_data = array() ) {
224 42
225
	$user_info = maybe_unserialize( $payment_data['user_info'] );
226 42
	$email     = give_get_payment_user_email( $payment_id );
227 42
228
	if ( isset( $user_info['id'] ) && $user_info['id'] > 0 ) {
229 42
		$user_data = get_userdata( $user_info['id'] );
230 42
		$name      = $user_data->display_name;
231 42
	} elseif ( isset( $user_info['first_name'] ) && isset( $user_info['last_name'] ) ) {
232
		$name = $user_info['first_name'] . ' ' . $user_info['last_name'];
233 42
	} else {
234 42
		$name = $email;
235 42
	}
236
237 42
	$gateway = give_get_gateway_admin_label( get_post_meta( $payment_id, '_give_payment_gateway', true ) );
238
239 42
	$default_email_body = esc_html__( 'Hello', 'give' ) . "\n\n";
240
	$default_email_body .= esc_html__( 'A donation has been made.', 'give' ) . "\n\n";
241 42
	/* translators: %s: form plural label */
242
	$default_email_body .= sprintf( esc_html__( '%s sold:', 'give' ), give_get_forms_label_plural() ) . "\n\n";
243 42
	$default_email_body .= esc_html__( 'Donor:', 'give' ) . ' ' . html_entity_decode( $name, ENT_COMPAT, 'UTF-8' ) . "\n";
244
	$default_email_body .= esc_html__( 'Amount:', 'give' ) . ' ' . html_entity_decode( give_currency_filter( give_format_amount( give_get_payment_amount( $payment_id ) ) ), ENT_COMPAT, 'UTF-8' ) . "\n";
245
	$default_email_body .= esc_html__( 'Payment Method:', 'give' ) . ' ' . $gateway . "\n\n";
246
	$default_email_body .= esc_html__( 'Thank you', 'give' );
247
248
	$email = give_get_option( 'donation_notification' );
249
	$email = isset( $email ) ? stripslashes( $email ) : $default_email_body;
250
251
	$email_body = give_do_email_tags( $email, $payment_id );
252
253
	return apply_filters( 'give_donation_notification', wpautop( $email_body ), $payment_id, $payment_data );
254
}
255
256
/**
257
 * Render Receipt in the Browser.
258
 *
259
 * A link is added to the Donation Receipt to view the email in the browser and
260
 * this function renders the Donation Receipt in the browser. It overrides the
261
 * Purchase Receipt template and provides its only styling.
262
 *
263
 * @since  1.0
264
 */
265
function give_render_receipt_in_browser() {
266
	if ( ! isset( $_GET['payment_key'] ) ) {
267
		wp_die( esc_html__( 'Missing donation payment key.', 'give' ), esc_html__( 'Error', 'give' ), array( 'response' => 400 ) );
268
	}
269
270
	$key = urlencode( $_GET['payment_key'] );
271
272
	ob_start();
273
	//Disallows caching of the page
274
	header( "Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . " GMT" );
275
	header( "Cache-Control: no-store, no-cache, must-revalidate" ); // HTTP/1.1
276
	header( "Cache-Control: post-check=0, pre-check=0", false );
277
	header( "Pragma: no-cache" ); // HTTP/1.0
278
	header( "Expires: Sat, 23 Oct 1977 05:00:00 PST" ); // Date in the past
279
	?>
280
	<!DOCTYPE html>
281
	<html lang="en">
282
	<head>
283
		<?php do_action( 'give_receipt_head' ); ?>
284
	</head>
285
	<body class="<?php echo apply_filters( 'give_receipt_page_body_class', 'give_receipt_page' ); ?>">
286
287
	<div id="give_receipt_wrapper">
288
		<?php do_action( 'give_render_receipt_in_browser_before' ); ?>
289
		<?php echo do_shortcode( '[give_receipt payment_key=' . $key . ']' ); ?>
290
		<?php do_action( 'give_render_receipt_in_browser_after' ); ?>
291
	</div>
292
293
	<?php do_action( 'give_receipt_footer' ); ?>
294
	</body>
295
	</html>
296
	<?php
297
	echo ob_get_clean();
298
	die();
0 ignored issues
show
Coding Style Compatibility introduced by
The function give_render_receipt_in_browser() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
299
}
300
301
add_action( 'give_view_receipt', 'give_render_receipt_in_browser' );
302
303
304
/**
305
 * Give Preview Email Header.
306
 *
307
 * Displays a header bar with the ability to change transactions to preview actual data within the preview. Will not display if
308
 *
309
 * @since 1.6
310
 *
311
 */
312
function give_get_preview_email_header() {
313
314
	//Payment receipt switcher
315
	$payment_count = give_count_payments()->publish;
316
	$payment_id    = (int) isset( $_GET['preview_id'] ) ? $_GET['preview_id'] : '';
317
318
	if ( $payment_count <= 0 ) {
319
		return false;
320
	}
321
322
	//Get payments.
323
	$payments = new Give_Payments_Query( array(
324
		'number' => 100
325
	) );
326
	$payments = $payments->get_payments();
327
	$options  = array();
328
329
	//Provide nice human readable options.
330
	if ( $payments ) {
331
		$options[0] =
332
			/* translators: %s: transaction singular label */
333
			esc_html__( '- Select a transaction -', 'give' );
334
		foreach ( $payments as $payment ) {
335
336
			$options[ $payment->ID ] = esc_html( '#' . $payment->ID . ' - ' . $payment->email . ' - ' . $payment->form_title );
337
338
		}
339
	} else {
340
		$options[0] = esc_html__( 'No Transactions Found', 'give' );
341
	}
342
343
	//Start constructing HTML output.
344
	$transaction_header = '<div style="margin:0;padding:10px 0;width:100%;background-color:#FFF;border-bottom:1px solid #eee; text-align:center;">';
345
346
	//Inline JS function for switching transactions.
347
	$transaction_header .= '<script>
348
				 function change_preview(){
349
				  var transactions = document.getElementById("give_preview_email_payment_id");
350
			        var selected_trans = transactions.options[transactions.selectedIndex];
351
				        console.log(selected_trans);
352
				        if (selected_trans){
353
				            var url_string = "' . get_bloginfo( 'url' ) . '?give_action=preview_email&preview_id=" + selected_trans.value;
354
				                window.location = url_string;
355
				        }
356
				    }
357
			    </script>';
358
359
	$transaction_header .= '<label for="give_preview_email_payment_id" style="font-size:12px;color:#333;margin:0 4px 0 0;">' . esc_html__( 'Preview email with a transaction:', 'give' ) . '</label>';
360
361
	//The select field with 100 latest transactions
362
	$transaction_header .= Give()->html->select( array(
363
		'name'             => 'preview_email_payment_id',
364
		'selected'         => $payment_id,
365
		'id'               => 'give_preview_email_payment_id',
366
		'class'            => 'give-preview-email-payment-id',
367
		'options'          => $options,
368
		'chosen'           => false,
369
		'select_atts'      => 'onchange="change_preview()">',
370
		'show_option_all'  => false,
371
		'show_option_none' => false
372
	) );
373
374
	//Closing tag
375
	$transaction_header .= '</div>';
376
377
	return apply_filters( 'give_preview_email_receipt_header', $transaction_header );
378
379
}
380
381
382
/**
383
 * Give Receipt Head Content
384
 *
385
 * @since 1.6
386
 * @return string
387
 */
388
function give_receipt_head_content() {
389
390
	//Title.
391
	$output = '<title>' . esc_html__( 'Donation Receipt', 'give' ) . '</title>';
392
393
	//Meta.
394
	$output .= '<meta charset="utf-8"/>
395
		<!-- Further disallowing of caching of this page -->
396
		<meta charset="utf-8"/>
397
		<meta http-equiv="cache-control" content="max-age=0"/>
398
		<meta http-equiv="cache-control" content="no-cache"/>
399
		<meta http-equiv="expires" content="0"/>
400
		<meta http-equiv="expires" content="Tue, 23 Oct 1977 05:00:00 PST"/>
401
		<meta http-equiv="pragma" content="no-cache"/>
402
		<meta name="robots" content="noindex, nofollow"/>';
403
404
	//CSS
405
	$output .= '<link rel="stylesheet" href="' . give_get_stylesheet_uri() . '?ver=' . GIVE_VERSION . '">';
406
407
	echo apply_filters( 'give_receipt_head_content', $output );
408
409
}
410
411
add_action( 'give_receipt_head', 'give_receipt_head_content' );