PluginProbe
SureDonation – Donation Forms, Fundraising Campaigns & Donor Management / 1.2.0
SureDonation – Donation Forms, Fundraising Campaigns & Donor Management v1.2.0
1.6.1 1.6.0 1.5.1 1.5.0 1.4.0 1.3.0 trunk 0.0.1 1.0.0 1.1.0 1.1.1 1.1.2 1.2.0
suredonation / inc / pdf / receipt-generator.php

receipt-generator.php in SureDonation – Donation Forms, Fundraising Campaigns & Donor Management 1.2.0, at inc/pdf/receipt-generator.php

336 lines 12.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * PDF Receipt Generator.
4 *
5 * Generates PDF donation receipts using the mPDF library.
6 *
7 * @package SureDonation
8 */
9
10 namespace SureDonation\Inc\Pdf;
11
12 use SureDonation\Inc\Database\Tables\Donations;
13 use SureDonation\Inc\Database\Tables\Donors;
14 use SureDonation\Inc\Helper;
15
16 // Exit if accessed directly.
17 if ( ! defined( 'ABSPATH' ) ) {
18 exit;
19 }
20
21 /**
22 * Receipt_Generator class.
23 *
24 * @since 1.0.0
25 */
26 class Receipt_Generator {
27 /**
28 * Get an existing receipt PDF or generate a new one.
29 *
30 * @param int $donation_id Donation ID.
31 * @return string|false File path on success, false on failure.
32 * @since 1.0.0
33 */
34 public static function get_or_generate( $donation_id ) {
35 $donation = Donations::get( $donation_id );
36
37 if ( ! $donation ) {
38 return false;
39 }
40
41 // Check if a cached PDF exists.
42 $existing_relative = $donation['receipt_pdf_url'] ?? '';
43
44 if ( ! empty( $existing_relative ) ) {
45 $existing_path = self::relative_to_path( Helper::get_string_value( $existing_relative ) );
46
47 if ( $existing_path && file_exists( $existing_path ) ) {
48 return $existing_path;
49 }
50 }
51
52 return self::generate( $donation_id );
53 }
54
55 /**
56 * Generate a PDF receipt for a donation.
57 *
58 * @param int $donation_id Donation ID.
59 * @return string|false File path on success, false on failure.
60 * @since 1.0.0
61 */
62 public static function generate( $donation_id ) {
63 if ( ! Pdf_Utils::check_if_library_exists() || ! Pdf_Utils::is_php_compatible() ) {
64 return false;
65 }
66
67 // Load the mPDF autoloader.
68 require_once Pdf_Utils::get_library_path() . '/vendor/autoload.php';
69
70 $donation = Donations::get( $donation_id );
71
72 if ( ! $donation ) {
73 return false;
74 }
75
76 $donor_id = Helper::get_integer_value( $donation['donor_id'] ?? 0 );
77 $donor = $donor_id ? Donors::get( $donor_id ) : null;
78
79 $campaign_id = Helper::get_integer_value( $donation['campaign_id'] ?? 0 );
80 $campaign_title = $campaign_id ? (string) get_the_title( $campaign_id ) : '';
81
82 // Build the receipt HTML.
83 $html = self::build_receipt_html( $donation, $donor, $campaign_title );
84
85 /**
86 * Filter the receipt HTML before PDF generation.
87 *
88 * SECURITY NOTE: The returned HTML is passed directly to mPDF's WriteHTML().
89 * mPDF can process <img> tags with file:// URIs and load external resources.
90 * Ensure any modifications only use trusted, escaped content.
91 *
92 * @param string $html Receipt HTML.
93 * @param array $donation Donation data.
94 * @param array|null $donor Donor data.
95 * @since 1.0.0
96 */
97 $html = apply_filters( 'suredonation_receipt_html', $html, $donation, $donor );
98
99 // Ensure receipts directory exists.
100 Pdf_Utils::ensure_receipts_dir();
101
102 $receipts_dir = Pdf_Utils::get_receipts_dir();
103 $filename = sprintf( 'suredonation-receipt-%d-%s.pdf', $donation_id, wp_generate_password( 8, false ) );
104 $filepath = $receipts_dir . '/' . $filename;
105
106 try {
107 $mpdf = new \Mpdf\Mpdf( self::get_mpdf_config() );
108 $mpdf->WriteHTML( $html );
109 $mpdf->Output( $filepath, \Mpdf\Output\Destination::FILE );
110 } catch ( \Exception $e ) {
111 return false;
112 }
113
114 // Store the relative path in the donation record (portable across domain changes).
115 $upload_dir = wp_upload_dir();
116 $relative_path = str_replace( $upload_dir['basedir'] . '/', '', $filepath );
117 Donations::update( $donation_id, [ 'receipt_pdf_url' => $relative_path ] );
118
119 return $filepath;
120 }
121
122 /**
123 * Delete a receipt PDF file by its stored uploads-relative path.
124 *
125 * Used by the personal-data eraser: the receipt is generated from the donor's
126 * name/email/address, so an erasure must remove the file from disk, not just
127 * the database columns.
128 *
129 * @since 1.2.0
130 * @param string $relative_path Relative path within the uploads directory.
131 * @return bool True when no file remains (deleted or never existed), false when it survived deletion.
132 */
133 public static function delete_receipt( $relative_path ) {
134 $filepath = self::relative_to_path( $relative_path );
135
136 if ( false === $filepath || ! file_exists( $filepath ) ) {
137 return true;
138 }
139
140 wp_delete_file( $filepath );
141
142 // Re-check with is_file() (not file_exists()) — wp_delete_file() has a
143 // filesystem side effect PHPStan can't see, so re-calling the already
144 // narrowed file_exists() reads as always-false to it.
145 clearstatcache( true, $filepath );
146
147 return ! is_file( $filepath );
148 }
149
150 /**
151 * Get the mPDF configuration.
152 *
153 * @return array<string,mixed>
154 * @since 1.0.0
155 */
156 private static function get_mpdf_config() {
157 return [
158 'mode' => 'utf-8',
159 'format' => 'A4',
160 'orientation' => 'P',
161 'margin_left' => 15,
162 'margin_right' => 15,
163 'margin_top' => 15,
164 'margin_bottom' => 15,
165 'default_font' => 'dejavusans',
166 'tempDir' => Pdf_Utils::get_temp_dir(),
167 // mPDF defaults allow <img src="file:///..."> and remote http(s)
168 // resource fetching. The receipt HTML is server-templated with
169 // escaped fields, but the suredonation_receipt_html filter (and
170 // any future ucfirst-only gateway label) would still surface
171 // donor / gateway data into HTML that mPDF processes. Disable
172 // the dangerous resource-loading defaults so a malicious string
173 // in any rendered field can't become SSRF (remote fetch) or
174 // LFI (local file read into the PDF) regardless of the source.
175 'allow_remote_dir_in_links_filesystem' => false,
176 'curlAllowUnsafeSslRequests' => false,
177 ];
178 }
179
180 /**
181 * Build the receipt HTML template.
182 *
183 * @param array<string, mixed> $donation Donation data.
184 * @param array<string, mixed>|null $donor Donor data.
185 * @param string $campaign_title Campaign title.
186 * @return string HTML content.
187 * @since 1.0.0
188 */
189 private static function build_receipt_html( $donation, $donor, $campaign_title ) {
190 $site_name = esc_html( get_bloginfo( 'name' ) );
191 $site_url = esc_url( site_url() );
192
193 $donation_id = Helper::get_integer_value( $donation['id'] ?? 0 );
194 $donor_name = esc_html( Helper::get_string_value( $donor['name'] ?? '' ) );
195 $donor_email = esc_html( Helper::get_string_value( $donor['email'] ?? '' ) );
196 $payment_status = esc_html( ucfirst( Helper::get_string_value( $donation['payment_status'] ?? '' ) ) );
197 $payment_method = esc_html( ucfirst( Helper::get_string_value( $donation['gateway'] ?? '' ) ) );
198 $transaction_id = esc_html( Helper::get_string_value( $donation['transaction_id'] ?? '' ) );
199 $currency = Helper::get_string_value( $donation['currency'] ?? 'USD' );
200 $total = Helper::get_float_value( $donation['amount'] ?? 0 );
201 $fees_covered = Helper::get_float_value( $donation['fees_covered'] ?? 0 );
202 $amount = $total - $fees_covered;
203 $date = Helper::get_string_value( $donation['created_at'] ?? '' );
204
205 if ( ! empty( $date ) ) {
206 $date_format = Helper::get_string_value( get_option( 'date_format' ) );
207 $timestamp = strtotime( $date );
208 $formatted_date = false !== $timestamp ? wp_date( $date_format, $timestamp ) : false;
209 $date = is_string( $formatted_date ) ? $formatted_date : $date;
210 }
211
212 $campaign_title = esc_html( $campaign_title );
213
214 // Format amounts.
215 $formatted_amount = self::format_currency( $amount, $currency );
216 $formatted_fees = self::format_currency( $fees_covered, $currency );
217 $formatted_total = self::format_currency( $total, $currency );
218
219 // Build transaction ID row.
220 $transaction_row = '';
221 if ( ! empty( $transaction_id ) ) {
222 $transaction_row = sprintf(
223 '<tr><td style="padding:10px 12px;border-bottom:1px solid #e5e7eb;color:#6b7280;font-size:13px;">%s</td>
224 <td style="padding:10px 12px;border-bottom:1px solid #e5e7eb;font-size:13px;color:#111827;">%s</td></tr>',
225 esc_html__( 'Transaction ID', 'suredonation' ),
226 $transaction_id
227 );
228 }
229
230 // Build fees row.
231 $fees_row = '';
232 if ( $fees_covered > 0 ) {
233 $fees_row = sprintf(
234 '<tr><td style="padding:10px 12px;border-bottom:1px solid #e5e7eb;color:#6b7280;font-size:13px;">%s</td>
235 <td style="padding:10px 12px;border-bottom:1px solid #e5e7eb;font-size:13px;color:#111827;">%s</td></tr>',
236 esc_html__( 'Fees Covered', 'suredonation' ),
237 $formatted_fees
238 );
239 }
240
241 return '
242 <div style="max-width:560px;margin:0 auto;font-family:DejaVu Sans,sans-serif;color:#111827;">
243 <div style="text-align:center;margin-bottom:24px;padding-bottom:20px;border-bottom:2px solid #e5e7eb;">
244 <h1 style="font-size:20px;margin:0 0 4px;color:#111827;">' . $site_name . '</h1>
245 <p style="color:#6b7280;font-size:13px;margin:0;">' . esc_html__( 'Donation Receipt', 'suredonation' ) . '</p>
246 </div>
247
248 <p style="color:#6b7280;font-size:12px;margin:0 0 16px;text-align:right;">'
249 . esc_html__( 'Receipt', 'suredonation' ) . ' #' . $donation_id . '</p>
250
251 <table style="width:100%;border-collapse:collapse;margin-bottom:20px;border:1px solid #e5e7eb;border-radius:6px;">
252 <tr><td style="padding:10px 12px;border-bottom:1px solid #e5e7eb;color:#6b7280;font-size:13px;width:40%;">'
253 . esc_html__( 'Donor Name', 'suredonation' ) . '</td>
254 <td style="padding:10px 12px;border-bottom:1px solid #e5e7eb;font-size:13px;color:#111827;">' . $donor_name . '</td></tr>
255 <tr><td style="padding:10px 12px;border-bottom:1px solid #e5e7eb;color:#6b7280;font-size:13px;">'
256 . esc_html__( 'Donor Email', 'suredonation' ) . '</td>
257 <td style="padding:10px 12px;border-bottom:1px solid #e5e7eb;font-size:13px;color:#111827;">' . $donor_email . '</td></tr>
258 </table>
259
260 <table style="width:100%;border-collapse:collapse;margin-bottom:20px;border:1px solid #e5e7eb;border-radius:6px;">
261 <tr><td style="padding:10px 12px;border-bottom:1px solid #e5e7eb;color:#6b7280;font-size:13px;width:40%;">'
262 . esc_html__( 'Campaign Name', 'suredonation' ) . '</td>
263 <td style="padding:10px 12px;border-bottom:1px solid #e5e7eb;font-size:13px;color:#111827;">' . $campaign_title . '</td></tr>
264 <tr><td style="padding:10px 12px;border-bottom:1px solid #e5e7eb;color:#6b7280;font-size:13px;">'
265 . esc_html__( 'Payment Status', 'suredonation' ) . '</td>
266 <td style="padding:10px 12px;border-bottom:1px solid #e5e7eb;font-size:13px;color:#111827;">' . $payment_status . '</td></tr>
267 <tr><td style="padding:10px 12px;border-bottom:1px solid #e5e7eb;color:#6b7280;font-size:13px;">'
268 . esc_html__( 'Payment Method', 'suredonation' ) . '</td>
269 <td style="padding:10px 12px;border-bottom:1px solid #e5e7eb;font-size:13px;color:#111827;">' . $payment_method . '</td></tr>
270 ' . $transaction_row . '
271 <tr><td style="padding:10px 12px;border-bottom:1px solid #e5e7eb;color:#6b7280;font-size:13px;">'
272 . esc_html__( 'Donation Amount', 'suredonation' ) . '</td>
273 <td style="padding:10px 12px;border-bottom:1px solid #e5e7eb;font-size:13px;color:#111827;">' . $formatted_amount . '</td></tr>
274 ' . $fees_row . '
275 <tr><td style="padding:10px 12px;background:#f9fafb;font-weight:bold;color:#111827;font-size:13px;">'
276 . esc_html__( 'Donation Total', 'suredonation' ) . '</td>
277 <td style="padding:10px 12px;background:#f9fafb;font-weight:bold;font-size:13px;color:#111827;">' . $formatted_total . '</td></tr>
278 </table>
279
280 <p style="color:#6b7280;font-size:12px;margin:0 0 4px;">'
281 . esc_html__( 'Date', 'suredonation' ) . ': ' . esc_html( $date ) . '</p>
282
283 <div style="margin-top:30px;padding-top:16px;border-top:1px solid #e5e7eb;text-align:center;">
284 <p style="color:#9ca3af;font-size:11px;margin:0;">'
285 . sprintf(
286 /* translators: 1: Site name, 2: Site URL. */
287 esc_html__( 'Generated by %1$s · %2$s', 'suredonation' ),
288 $site_name,
289 $site_url
290 ) . '</p>
291 </div>
292 </div>';
293 }
294
295 /**
296 * Format a monetary amount with currency symbol.
297 *
298 * @param float $amount Amount to format.
299 * @param string $currency Currency code.
300 * @return string Formatted amount.
301 * @since 1.0.0
302 */
303 private static function format_currency( $amount, $currency = 'USD' ) {
304 $symbols = [
305 'USD' => '$',
306 'EUR' => '€',
307 'GBP' => '£',
308 'CAD' => 'CA$',
309 'AUD' => 'A$',
310 'INR' => '₹',
311 'JPY' => '¥',
312 ];
313
314 $symbol = $symbols[ strtoupper( $currency ) ] ?? esc_html( $currency ) . ' ';
315
316 return $symbol . number_format( $amount, 2 );
317 }
318
319 /**
320 * Convert a relative path to an absolute file path.
321 *
322 * @param string $relative_path Relative path within the uploads directory.
323 * @return string|false Absolute file path or false.
324 * @since 1.0.0
325 */
326 private static function relative_to_path( $relative_path ) {
327 if ( empty( $relative_path ) ) {
328 return false;
329 }
330
331 $upload_dir = wp_upload_dir();
332
333 return $upload_dir['basedir'] . '/' . $relative_path;
334 }
335 }
336