PluginProbe
Easy Invoice – Invoice Generator, PDF Quotes & Payments / 2.4.0
Easy Invoice – Invoice Generator, PDF Quotes & Payments v2.4.0
2.4.0 2.4.1 2.3.8 2.3.7 2.3.6 2.3.5 2.3.4 2.3.3 2.3.2 2.3.1 2.2.0 2.1.21 2.1.20 2.1.19 2.1.18 2.1.0 2.1.1 2.1.10 2.1.11 2.1.12 2.1.13 2.1.14 2.1.15 2.1.16 2.1.2 All 57 releases
← All changes | includes/Admin/EasyInvoiceAjax.php +312 -80 2.3.6 → 2.4.0 View file →
@@ -102,10 +102,11 @@
102 102 $invoice_form_manager = new \EasyInvoice\Forms\Invoice\InvoiceFormManager();
103 103 $invoice_data = $invoice_form_manager->processFormData($raw_invoice_data);
104 104
105 105 if (!empty($invoice_data['errors'])) {
106 + // The toast is what the user sees; the field may sit on another tab.
106 107 wp_send_json_error([
107 - 'message' => 'Validation failed',
108 + 'message' => implode(' ', array_map('strval', $invoice_data['errors'])),
108 109 'errors' => $invoice_data['errors']
109 110 ]);
110 111 }
111 112
@@ -167,8 +168,17 @@
167 168 if (!$invoice) {
168 169 $this->sendError(__('Failed to create invoice', 'easy-invoice'));
169 170 }
170 171
172 + // The repository claimed a number under its lock (or generated the next
173 + // one when the number the builder peeked on page load was taken
174 + // meanwhile). Carry that claimed number into the form data: the
175 + // FormProcessor below writes every posted field, and the stale peek
176 + // would otherwise overwrite the claim — two builders open at once
177 + // then saved two documents with the same number.
178 + $invoice_data['data']['number'] = $invoice->getNumber();
179 + unset($invoice_data['data']['invoice_number']);
180 +
171 181 // Use FormProcessor to save form data to database
172 182 $form_processor = new \EasyInvoice\Forms\FormProcessor();
173 183 $all_fields = $invoice_form_manager->getAllFields();
174 184 $form_processor->saveFormDataToDatabase($invoice_data['data'], $all_fields, $invoice);
@@ -369,9 +379,12 @@
369 379 $this->sendError(__('You do not have permission to perform this action', 'easy-invoice'));
370 380 }
371 381
372 382 $client_id = isset($_POST['client_id']) ? intval($_POST['client_id']) : 0;
373 - $delete_associated_documents = isset($_POST['delete_associated_documents']) ? (bool)$_POST['delete_associated_documents'] : false;
383 + // The dialog posts the literal strings "true" / "false"; a bool cast
384 + // made "false" true, so "Delete client only" removed the documents too.
385 + $delete_associated_documents = isset($_POST['delete_associated_documents'])
386 + && filter_var(wp_unslash($_POST['delete_associated_documents']), FILTER_VALIDATE_BOOLEAN);
374 387
375 388 if ($client_id <= 0) {
376 389 $this->sendError(__('Invalid client ID', 'easy-invoice'));
377 390 }
@@ -398,18 +411,25 @@
398 411 "SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_key = '_easy_invoice_quote_client_id' AND meta_value = %d",
399 412 $client_id
400 413 ));
401 414
402 - $payment_count = $wpdb->get_var($wpdb->prepare(
403 - "SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_key = '_easy_payment_client_id' AND meta_value = %d",
404 - $client_id
405 - ));
415 + // Counted through the client's invoices, because that is the only
416 + // link there is: payments record '_invoice_id' and no client id.
417 + // This counted meta '_easy_payment_client_id', which nothing writes,
418 + // so the confirmation dialog told every user there were no payments
419 + // no matter how many there were.
420 + $payment_count = count(\EasyInvoice\Services\ClientLedger::paymentIds((int) $client_id));
406 421
407 422 $total_documents = $invoice_count + $quote_count + $payment_count;
408 423
409 424 if ($delete_associated_documents) {
410 425 // Delete all associated documents
411 - $this->log(sprintf('Deleting client %d with all associated documents (%d invoices, %d quotes, %d payments)',
426 + // error_log(), not $this->log(): no such method exists on this class or
427 + // any trait it uses, so both branches of this handler raised
428 + // "Call to undefined method" — deleting a client failed with a critical
429 + // error whichever option the administrator chose. Matches the logging
430 + // used elsewhere in the plugin.
431 + error_log(sprintf('Easy Invoice: deleting client %d with all associated documents (%d invoices, %d quotes, %d payments)',
412 432 $client_id, $invoice_count, $quote_count, $payment_count));
413 433
414 434 // Delete invoices
415 435 if ($invoice_count > 0) {
@@ -433,22 +453,56 @@
433 453 }
434 454 }
435 455
436 456 // Delete payments
437 - if ($payment_count > 0) {
438 - $payments = $wpdb->get_col($wpdb->prepare(
439 - "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_easy_invoice_payment_client_id' AND meta_value = %d",
440 - $client_id
441 - ));
442 - foreach ($payments as $payment_id) {
443 - wp_delete_post($payment_id, true);
444 - }
445 - }
457 + //
458 + // This queried '_easy_invoice_payment_client_id' while the matching
459 + // count above (and the meta cleanup below, and
460 + // ClientRepository::countClientPayments) all query
461 + // '_easy_payment_client_id' — so the count and the deletion disagreed
462 + // on which key identifies a client's payments. Unified on
463 + // '_easy_payment_client_id', the key the other three sites use.
464 + //
465 + // Payments are RETAINED, on purpose, and the message below says so.
466 + //
467 + // Neither of those meta keys is ever written: a payment stores
468 + // '_invoice_id' and carries no client id at all, so it is linked to
469 + // a client only through its invoice. Client deletion has therefore
470 + // never removed a payment, whatever the dialog implied.
471 + //
472 + // $payment_count is now resolved correctly through ClientLedger, so
473 + // the count is true even though the behaviour is unchanged. Making
474 + // the deletion true as well would destroy records this path has
475 + // never touched — a payment is the evidence money changed hands, and
476 + // the reasoning that stops InvoiceRetention deleting an issued
477 + // invoice applies to it. That is a deliberate decision to keep them,
478 + // not an oversight, so it is stated to the user rather than hidden.
446 479
447 - $message = sprintf(__('Client and all associated documents (%d total) deleted successfully', 'easy-invoice'), $total_documents);
480 + // Say what was kept as well as what went. "All associated documents
481 + // deleted" was never true where payments were concerned, and a
482 + // merchant who believes their payment records are gone will look
483 + // for them in the wrong place at the wrong time of year.
484 + $message = $payment_count > 0
485 + ? sprintf(
486 + /* translators: 1: number of documents deleted, 2: number of payment records kept. */
487 + _n(
488 + 'Client deleted, along with %1$d document. %2$d payment record was kept as a financial record.',
489 + 'Client deleted, along with %1$d documents. %2$d payment records were kept as financial records.',
490 + $payment_count,
491 + 'easy-invoice'
492 + ),
493 + $invoice_count + $quote_count,
494 + $payment_count
495 + )
496 + : sprintf(
497 + /* translators: %d: number of documents deleted. */
498 + __('Client and all associated documents (%d total) deleted successfully', 'easy-invoice'),
499 + $total_documents
500 + );
448 501 } else {
449 502 // Only remove client associations, preserve documents
450 - $this->log(sprintf('Removing client associations for client %d (%d invoices, %d quotes, %d payments)',
503 + // See the note on the other branch above.
504 + error_log(sprintf('Easy Invoice: removing client associations for client %d (%d invoices, %d quotes, %d payments)',
451 505 $client_id, $invoice_count, $quote_count, $payment_count));
452 506
453 507 // Remove client associations from invoices
454 508 if ($invoice_count > 0) {
@@ -473,8 +527,9 @@
473 527 ['meta_key' => '_easy_payment_client_id', 'meta_value' => $client_id]
474 528 );
475 529 }
476 530
531 + /* translators: %d: number of documents. */
477 532 $message = sprintf(__('Client deleted successfully. %d documents preserved but client associations removed.', 'easy-invoice'), $total_documents);
478 533 }
479 534
480 535 // Snapshot identity BEFORE delete — once wp_delete_user runs the
@@ -747,9 +802,9 @@
747 802 if ($result['success']) {
748 803 // Audit: who sent which invoice to which client, at what time.
749 804 if (function_exists('easy_invoice_audit_log')) {
750 805 easy_invoice_audit_log('invoice_sent', 'invoice', $invoice_id, [
751 - 'recipient' => method_exists($invoice, 'getCustomerEmail') ? $invoice->getCustomerEmail() : '',
806 + 'recipient' => is_callable([$invoice, 'getCustomerEmail']) ? $invoice->getCustomerEmail() : '',
752 807 'context' => 'new',
753 808 ]);
754 809 }
755 810 $this->sendSuccess(array(
@@ -794,9 +849,10 @@
794 849 'quote_data' => $quote->toArray(),
795 850 'download_url' => add_query_arg(array(
796 851 'action' => 'easy_invoice_generate_quote_pdf',
797 852 'quote_id' => $quote_id,
798 - 'nonce' => wp_create_nonce('generate_quote_pdf')
853 + // Bound to this quote — see the invoice equivalent above.
854 + 'nonce' => wp_create_nonce('generate_quote_pdf_' . $quote_id)
799 855 ), admin_url('admin-ajax.php'))
800 856 ));
801 857 }
802 858
@@ -822,9 +878,9 @@
822 878 $quote_data = $quote_form_manager->processFormData($raw_quote_data);
823 879
824 880 if (!empty($quote_data['errors'])) {
825 881 wp_send_json_error([
826 - 'message' => 'Validation failed',
882 + 'message' => implode(' ', array_map('strval', $quote_data['errors'])),
827 883 'errors' => $quote_data['errors']
828 884 ]);
829 885 }
830 886
@@ -892,8 +948,13 @@
892 948 if (!$quote) {
893 949 $this->sendError(__('Failed to create quote', 'easy-invoice'));
894 950 }
895 951
952 + // Same as invoices: keep the number the repository claimed, not the one
953 + // the builder peeked on page load (see saveInvoice()).
954 + $quote_data['data']['number'] = $quote->getNumber();
955 + unset($quote_data['data']['quote_number']);
956 +
896 957 // Use FormProcessor to save form data to database
897 958 $form_processor = new \EasyInvoice\Forms\FormProcessor();
898 959 $all_fields = $quote_form_manager->getAllFields();
899 960 $form_processor->saveFormDataToDatabase($quote_data['data'], $all_fields, $quote);
@@ -1079,23 +1140,27 @@
1079 1140 // Check if required fields are present
1080 1141 $required_fields = ['business_client_name', 'email', 'username'];
1081 1142 foreach ($required_fields as $field) {
1082 1143 if (!isset($_POST[$field]) || empty($_POST[$field])) {
1083 - $this->sendError(__('Missing required field: ' . $field, 'easy-invoice'));
1144 + /* translators: %s: form field name. */
1145 + $this->sendError(sprintf(__('Missing required field: %s', 'easy-invoice'), $field));
1084 1146 }
1085 1147 }
1086 1148
1087 1149 // Prepare client data
1150 + // Optional fields may be absent from the request entirely.
1151 + $post_text = static function ($key) { return isset($_POST[$key]) ? sanitize_text_field(wp_unslash($_POST[$key])) : ''; }; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- checked above.
1152 + $post_area = static function ($key) { return isset($_POST[$key]) ? sanitize_textarea_field(wp_unslash($_POST[$key])) : ''; }; // phpcs:ignore WordPress.Security.NonceVerification.Missing
1088 1153 $client_data = [
1089 - ClientFields::BUSINESS_CLIENT_NAME => sanitize_text_field($_POST['business_client_name']),
1090 - ClientFields::EMAIL => sanitize_email($_POST['email']),
1091 - ClientFields::USERNAME => sanitize_user($_POST['username']),
1092 - ClientFields::PASSWORD => $_POST['password'],
1093 - ClientFields::ADDRESS => sanitize_textarea_field($_POST['address']),
1094 - ClientFields::EXTRA_INFO => sanitize_textarea_field($_POST['extra_info']),
1095 - ClientFields::FIRST_NAME => sanitize_text_field($_POST['first_name']),
1096 - ClientFields::LAST_NAME => sanitize_text_field($_POST['last_name']),
1097 - ClientFields::WEBSITE => esc_url_raw($_POST['website']),
1154 + ClientFields::BUSINESS_CLIENT_NAME => $post_text('business_client_name'),
1155 + ClientFields::EMAIL => sanitize_email(wp_unslash(($_POST['email'] ?? ''))),
1156 + ClientFields::USERNAME => sanitize_user(wp_unslash(($_POST['username'] ?? ''))),
1157 + ClientFields::PASSWORD => isset($_POST['password']) ? (string) wp_unslash($_POST['password']) : '',
1158 + ClientFields::ADDRESS => $post_area('address'),
1159 + ClientFields::EXTRA_INFO => $post_area('extra_info'),
1160 + ClientFields::FIRST_NAME => $post_text('first_name'),
1161 + ClientFields::LAST_NAME => $post_text('last_name'),
1162 + ClientFields::WEBSITE => isset($_POST['website']) ? esc_url_raw(wp_unslash($_POST['website'])) : '',
1098 1163 ClientFields::PHONE => isset($_POST['phone']) ? sanitize_text_field($_POST['phone']) : '',
1099 1164 ];
1100 1165
1101 1166
@@ -1114,9 +1179,10 @@
1114 1179 // Create new client
1115 1180 $client = $repository->create($client_data);
1116 1181
1117 1182 if (!$client) {
1118 - $this->sendError(__('Failed to create client', 'easy-invoice'));
1183 + $reason = method_exists($repository, 'getLastError') ? $repository->getLastError() : '';
1184 + $this->sendError($reason !== '' ? $reason : __('Failed to create client', 'easy-invoice'));
1119 1185 }
1120 1186
1121 1187 $client_id = $client->getId();
1122 1188
@@ -1156,18 +1222,18 @@
1156 1222 }
1157 1223
1158 1224 // Prepare client data
1159 1225 $client_data = [
1160 - ClientFields::BUSINESS_CLIENT_NAME => sanitize_text_field($_POST['business_client_name']),
1161 - ClientFields::EMAIL => sanitize_email($_POST['email']),
1162 - ClientFields::USERNAME => sanitize_user($_POST['username']),
1163 - ClientFields::PASSWORD => $_POST['password'], // Keep password as is, don't sanitize
1164 - ClientFields::ADDRESS => sanitize_textarea_field($_POST['address']),
1226 + ClientFields::BUSINESS_CLIENT_NAME => sanitize_text_field(($_POST['business_client_name'] ?? '')),
1227 + ClientFields::EMAIL => sanitize_email(($_POST['email'] ?? '')),
1228 + ClientFields::USERNAME => sanitize_user(($_POST['username'] ?? '')),
1229 + ClientFields::PASSWORD => ($_POST['password'] ?? ''), // Keep password as is, don't sanitize
1230 + ClientFields::ADDRESS => sanitize_textarea_field(($_POST['address'] ?? '')),
1165 1231 ClientFields::PHONE => isset($_POST['phone']) ? sanitize_text_field($_POST['phone']) : '',
1166 - ClientFields::EXTRA_INFO => sanitize_textarea_field($_POST['extra_info']),
1167 - ClientFields::FIRST_NAME => sanitize_text_field($_POST['first_name']),
1168 - ClientFields::LAST_NAME => sanitize_text_field($_POST['last_name']),
1169 - ClientFields::WEBSITE => esc_url_raw($_POST['website'])
1232 + ClientFields::EXTRA_INFO => sanitize_textarea_field(($_POST['extra_info'] ?? '')),
1233 + ClientFields::FIRST_NAME => sanitize_text_field(($_POST['first_name'] ?? '')),
1234 + ClientFields::LAST_NAME => sanitize_text_field(($_POST['last_name'] ?? '')),
1235 + ClientFields::WEBSITE => esc_url_raw(($_POST['website'] ?? ''))
1170 1236 ];
1171 1237
1172 1238 // Remove empty values except password (password can be empty for updates)
1173 1239 $client_data = array_filter($client_data, function($value, $key) {
@@ -1281,8 +1347,9 @@
1281 1347 }
1282 1348 }
1283 1349
1284 1350 $this->sendSuccess(array(
1351 + /* translators: %d: number updated. */
1285 1352 'message' => sprintf(__('Updated %d invoices with missing data', 'easy-invoice'), $updated_count),
1286 1353 'updated_count' => $updated_count
1287 1354 ));
1288 1355 }
@@ -1300,21 +1367,30 @@
1300 1367 if (!$invoice_id) {
1301 1368 $this->sendError(__('Invalid invoice ID', 'easy-invoice'));
1302 1369 }
1303 1370
1304 - // Get invoice from repository (only published invoices for public access)
1305 1371 $repository = InvoiceServiceProvider::getInvoiceRepository();
1372 + $invoice = $repository->find($invoice_id);
1306 1373
1307 - // For admins, allow access to any invoice status
1308 - if (current_user_can('manage_options')) {
1309 - $invoice = $repository->find($invoice_id);
1310 - } else {
1311 - // For non-admins, only allow access to published invoices
1312 - $invoice = $repository->findPublished($invoice_id);
1374 + if (!$invoice) {
1375 + $this->sendError(__('Invoice not found', 'easy-invoice'));
1313 1376 }
1314 1377
1315 - if (!$invoice) {
1316 - $this->sendError(__('Invoice not found', 'easy-invoice'));
1378 + // Authorisation.
1379 + //
1380 + // This used to read: admins get find(), everyone else gets findPublished().
1381 + // That was not a check at all — Models\Invoice::save() writes every invoice
1382 + // with post_status 'publish' regardless of its workflow status, so
1383 + // findPublished() returned the same record find() would have, for anyone.
1384 + // This endpoint is registered for wp_ajax_nopriv, so the effective gate was
1385 + // the nonce alone and any caller holding one could pull the PDF data for an
1386 + // arbitrary invoice id, including drafts.
1387 + //
1388 + // Uses the same helper as the rest of the plugin so there is a single
1389 + // definition of who may see a document: valid ?ik= token, administrator, or
1390 + // the logged-in client the invoice is bound to.
1391 + if (!\EasyInvoice\Controllers\InvoiceController::canSubmitPaymentForInvoice($invoice_id, $invoice)) {
1392 + $this->sendError(__('You do not have permission to access this invoice', 'easy-invoice'));
1317 1393 }
1318 1394
1319 1395 // Get invoice data for PDF generation
1320 1396 $invoice_data = \EasyInvoice\Includes\Helpers\PdfHelper::getInvoiceDataForPdf($invoice);
@@ -1326,9 +1402,12 @@
1326 1402 'invoice_data' => $invoice_data,
1327 1403 'download_url' => add_query_arg(array(
1328 1404 'action' => 'easy_invoice_generate_pdf',
1329 1405 'invoice_id' => $invoice_id,
1330 - 'nonce' => wp_create_nonce('generate_pdf')
1406 + // Bound to this invoice: an unscoped 'generate_pdf' nonce could be
1407 + // taken from a document the caller may legitimately see and replayed
1408 + // against any other invoice id.
1409 + 'nonce' => wp_create_nonce('generate_pdf_' . $invoice_id)
1331 1410 ), admin_url('admin-ajax.php'))
1332 1411 ));
1333 1412 }
1334 1413
@@ -1346,19 +1425,21 @@
1346 1425 }
1347 1426
1348 1427 // Get invoice from repository (only published invoices for public access)
1349 1428 $repository = InvoiceServiceProvider::getInvoiceRepository();
1429 + $invoice = $repository->find($invoice_id);
1350 1430
1351 - // For admins, allow access to any invoice status
1352 - if (current_user_can('manage_options')) {
1353 - $invoice = $repository->find($invoice_id);
1354 - } else {
1355 - // For non-admins, only allow access to published invoices
1356 - $invoice = $repository->findPublished($invoice_id);
1431 + if (!$invoice) {
1432 + $this->sendError(__('Invoice not found', 'easy-invoice'));
1357 1433 }
1358 1434
1359 - if (!$invoice) {
1360 - $this->sendError(__('Invoice not found', 'easy-invoice'));
1435 + // Authorisation. The previous admin / findPublished() split was not a check:
1436 + // every invoice is saved with post_status 'publish', so findPublished()
1437 + // returned exactly what find() would, for any caller. This endpoint is
1438 + // registered nopriv, so without this an unauthorised caller could make the
1439 + // site email an arbitrary invoice out to its client. See downloadInvoicePdf().
1440 + if (!\EasyInvoice\Controllers\InvoiceController::canSubmitPaymentForInvoice($invoice_id, $invoice)) {
1441 + $this->sendError(__('You do not have permission to access this invoice', 'easy-invoice'));
1361 1442 }
1362 1443
1363 1444 // Use EmailManager to send the email
1364 1445 $email_manager = \EasyInvoice\Services\EmailManager::getInstance();
@@ -1385,17 +1466,18 @@
1385 1466 $this->sendError(__('Invalid quote ID', 'easy-invoice'));
1386 1467 }
1387 1468
1388 1469 $repository = \EasyInvoice\Providers\QuoteServiceProvider::getQuoteRepository();
1470 + $quote = $repository->find($quote_id);
1389 1471
1390 - if (current_user_can('manage_options')) {
1391 - $quote = $repository->find($quote_id);
1392 - } else {
1393 - $quote = $repository->findPublished($quote_id);
1472 + if (!$quote) {
1473 + $this->sendError(__('Quote not found', 'easy-invoice'));
1394 1474 }
1395 1475
1396 - if (!$quote) {
1397 - $this->sendError(__('Quote not found', 'easy-invoice'));
1476 + // Authorisation — same reasoning as the invoice path above. Quotes are also
1477 + // always stored with post_status 'publish', so findPublished() gated nothing.
1478 + if (!\EasyInvoice\Controllers\QuoteController::canActOnQuote($quote_id, $quote)) {
1479 + $this->sendError(__('You do not have permission to access this quote', 'easy-invoice'));
1398 1480 }
1399 1481
1400 1482 $email_manager = \EasyInvoice\Services\EmailManager::getInstance();
1401 1483 $result = $email_manager->sendQuoteEmail($quote, 'new');
@@ -1415,10 +1497,18 @@
1415 1497 /**
1416 1498 * Generate invoice PDF
1417 1499 */
1418 1500 public function generateInvoicePdf() {
1419 - // Verify nonce
1420 - $this->verifyNonce('generate_pdf');
1501 + // Explicitly bust intermediate caching on this admin-ajax URL. Some
1502 + // page-caching stacks (WP Rocket, LiteSpeed, Cloudflare full-page
1503 + // cache, some CDNs) will cache a 302 Location header keyed by URL —
1504 + // the URL always looks the same to the cache because both the nonce
1505 + // AND the target invoice-permalink change per user, so a first-hit
1506 + // response can be replayed to other users, breaking the redirect or
1507 + // returning a blank body.
1508 + nocache_headers();
1509 + header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
1510 + header('Pragma: no-cache');
1421 1511
1422 1512 // Get invoice ID
1423 1513 $invoice_id = isset($_REQUEST['invoice_id']) ? intval($_REQUEST['invoice_id']) : 0;
1424 1514
@@ -1425,8 +1515,57 @@
1425 1515 if (!$invoice_id) {
1426 1516 $this->sendError(__('Invalid invoice ID', 'easy-invoice'));
1427 1517 }
1428 1518
1519 + // Authorisation with graceful fallback.
1520 + //
1521 + // The original design gated this endpoint on a per-request WP
1522 + // nonce, which is fragile in real deployments: page-caching
1523 + // layers (WP Rocket, LiteSpeed, Cloudflare full-page cache)
1524 + // cache the intermediate JSON response that mints the URL,
1525 + // browser SameSite / ITP behaviour, and admin_url()
1526 + // scheme-mismatch after login can all cause wp_verify_nonce()
1527 + // to return false on the intended recipient's tab — leaving
1528 + // the user stranded on this admin-ajax URL with no download.
1529 + //
1530 + // Accept ANY of:
1531 + // 1. A valid `generate_pdf` nonce (fast path — most users,
1532 + // most of the time, when the session cookie survives).
1533 + // 2. An admin session (manage_options) — bypasses the nonce
1534 + // because the invoice-listing button that creates this
1535 + // URL is admin-only and the admin owns the request.
1536 + // 3. A valid per-invoice access token (?ik=<token>) — the
1537 + // same model canSubmitPaymentForInvoice uses, so emailed
1538 + // invoice links can also drive a session-less download.
1539 + // Only when all three paths fail do we refuse.
1540 + $authorized = false;
1541 +
1542 + // Match the same dual-key nonce lookup the removed verifyNonce()
1543 + // helper did — `nonce` (client-form format used by our JS) AND
1544 + // `_nonce` (standard WP form field name) — so any external
1545 + // caller of this endpoint that used _nonce still works.
1546 + $submitted_nonce = '';
1547 + if (isset($_REQUEST['nonce'])) {
1548 + $submitted_nonce = (string) $_REQUEST['nonce'];
1549 + } elseif (isset($_REQUEST['_nonce'])) {
1550 + $submitted_nonce = (string) $_REQUEST['_nonce'];
1551 + }
1552 + if ($submitted_nonce !== '' && wp_verify_nonce($submitted_nonce, 'generate_pdf_' . $invoice_id)) {
1553 + $authorized = true;
1554 + } elseif (current_user_can('manage_options')) {
1555 + $authorized = true;
1556 + } elseif (isset($_REQUEST['ik']) && is_string($_REQUEST['ik'])) {
1557 + $presented = sanitize_text_field(wp_unslash($_REQUEST['ik']));
1558 + $stored = (string) get_post_meta($invoice_id, '_easy_invoice_invoice_access_token', true);
1559 + if ($stored !== '' && $presented !== '' && hash_equals($stored, $presented)) {
1560 + $authorized = true;
1561 + }
1562 + }
1563 +
1564 + if (!$authorized) {
1565 + $this->sendError(__('Security check failed', 'easy-invoice'));
1566 + }
1567 +
1429 1568 // Get invoice from repository
1430 1569 $repository = InvoiceServiceProvider::getInvoiceRepository();
1431 1570
1432 1571 // For admins, allow access to any invoice status
@@ -1440,16 +1579,24 @@
1440 1579 if (!$invoice) {
1441 1580 $this->sendError(__('Invoice not found', 'easy-invoice'));
1442 1581 }
1443 1582
1444 - // Redirect to the invoice single page with PDF generation
1583 + // Redirect to the invoice single page with PDF generation.
1584 + // Forward the ?ik= access token onwards so the single-page
1585 + // template can also authorise the recipient (the same token
1586 + // that got us through Path 3 above).
1445 1587 $invoice_url = get_permalink($invoice_id);
1446 - if ($invoice_url) {
1447 - wp_redirect(add_query_arg('auto_download_pdf', '1', $invoice_url));
1448 - exit;
1449 - } else {
1588 + if (!$invoice_url) {
1450 1589 $this->sendError(__('Could not generate invoice URL', 'easy-invoice'));
1451 1590 }
1591 +
1592 + $target_args = ['auto_download_pdf' => '1'];
1593 + if (isset($_REQUEST['ik']) && is_string($_REQUEST['ik']) && $_REQUEST['ik'] !== '') {
1594 + $target_args['ik'] = sanitize_text_field(wp_unslash($_REQUEST['ik']));
1595 + }
1596 + $target_url = add_query_arg($target_args, $invoice_url);
1597 +
1598 + $this->redirectWithFallback($target_url);
1452 1599 }
1453 1600
1454 1601 /**
1455 1602 * Generate quote PDF
@@ -1454,10 +1601,12 @@
1454 1601 /**
1455 1602 * Generate quote PDF
1456 1603 */
1457 1604 public function generateQuotePdf() {
1458 - // Verify nonce
1459 - $this->verifyNonce('generate_quote_pdf');
1605 + // Same cache-busting as generateInvoicePdf — see comment there.
1606 + nocache_headers();
1607 + header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
1608 + header('Pragma: no-cache');
1460 1609
1461 1610 // Get quote ID
1462 1611 $quote_id = isset($_REQUEST['quote_id']) ? intval($_REQUEST['quote_id']) : 0;
1463 1612
@@ -1464,8 +1613,45 @@
1464 1613 if (!$quote_id) {
1465 1614 $this->sendError(__('Invalid quote ID', 'easy-invoice'));
1466 1615 }
1467 1616
1617 + // Authorisation with graceful fallback. Same three-path model
1618 + // as generateInvoicePdf — see that method's comment for the
1619 + // full rationale (nonce fragility across caching layers,
1620 + // cross-tab session cookie behaviour, etc.). Paths accepted:
1621 + //
1622 + // 1. Valid `generate_quote_pdf` nonce (fast path).
1623 + // 2. Admin session (manage_options) — the quote-listing
1624 + // button that mints this URL is admin-only.
1625 + // 3. Valid per-quote access token (?qk=<token>) — mirrors
1626 + // the CVE-2026-9021 model so emailed quote links can
1627 + // drive a session-less PDF download.
1628 + $authorized = false;
1629 +
1630 + // Same dual-key nonce lookup as the invoice handler — see
1631 + // generateInvoicePdf for the backward-compat rationale.
1632 + $submitted_nonce = '';
1633 + if (isset($_REQUEST['nonce'])) {
1634 + $submitted_nonce = (string) $_REQUEST['nonce'];
1635 + } elseif (isset($_REQUEST['_nonce'])) {
1636 + $submitted_nonce = (string) $_REQUEST['_nonce'];
1637 + }
1638 + if ($submitted_nonce !== '' && wp_verify_nonce($submitted_nonce, 'generate_quote_pdf_' . $quote_id)) {
1639 + $authorized = true;
1640 + } elseif (current_user_can('manage_options')) {
1641 + $authorized = true;
1642 + } elseif (isset($_REQUEST['qk']) && is_string($_REQUEST['qk'])) {
1643 + $presented = sanitize_text_field(wp_unslash($_REQUEST['qk']));
1644 + $stored = (string) get_post_meta($quote_id, '_easy_invoice_quote_access_token', true);
1645 + if ($stored !== '' && $presented !== '' && hash_equals($stored, $presented)) {
1646 + $authorized = true;
1647 + }
1648 + }
1649 +
1650 + if (!$authorized) {
1651 + $this->sendError(__('Security check failed', 'easy-invoice'));
1652 + }
1653 +
1468 1654 // Get quote from repository — mirror invoice PDF: only published quotes for non-admins (incl. nopriv).
1469 1655 $repository = \EasyInvoice\Providers\QuoteServiceProvider::getQuoteRepository();
1470 1656 if (current_user_can('manage_options')) {
1471 1657 $quote = $repository->find($quote_id);
@@ -1476,16 +1662,62 @@
1476 1662 if (!$quote) {
1477 1663 $this->sendError(__('Quote not found', 'easy-invoice'));
1478 1664 }
1479 1665
1480 - // Redirect to the quote single page with PDF generation
1666 + // Redirect to the quote single page with PDF generation.
1667 + // Forward the ?qk= access token so the single-page template
1668 + // can also authorise the recipient with the same key that
1669 + // got us through Path 3.
1481 1670 $quote_url = get_permalink($quote_id);
1482 - if ($quote_url) {
1483 - wp_redirect(add_query_arg('auto_download_pdf', '1', $quote_url));
1671 + if (!$quote_url) {
1672 + $this->sendError(__('Could not generate quote URL', 'easy-invoice'));
1673 + }
1674 +
1675 + $target_args = ['auto_download_pdf' => '1'];
1676 + if (isset($_REQUEST['qk']) && is_string($_REQUEST['qk']) && $_REQUEST['qk'] !== '') {
1677 + $target_args['qk'] = sanitize_text_field(wp_unslash($_REQUEST['qk']));
1678 + }
1679 + $target_url = add_query_arg($target_args, $quote_url);
1680 +
1681 + $this->redirectWithFallback($target_url);
1682 + }
1683 +
1684 + /**
1685 + * Redirect the current request to $url, with a client-side fallback
1686 + * when the server-side redirect can't fire.
1687 + *
1688 + * `wp_safe_redirect()` silently no-ops if headers have already been sent
1689 + * (BOM in a plugin file, plugin echoing during an action, PHP warning
1690 + * output, etc.). Because we also `exit;` immediately after, that failure
1691 + * mode produces a 200 OK with an empty body — the reported blank-page
1692 + * bug on the invoice-listing PDF download.
1693 + *
1694 + * This helper detects the headers-sent case and emits a minimal HTML
1695 + * document that redirects via meta-refresh (works with JS disabled) and
1696 + * `window.location.replace()` (JS-enabled, doesn't add a history entry).
1697 + * Both point at the same escaped URL so misconfigured stacks still get
1698 + * the user to the target page.
1699 + */
1700 + private function redirectWithFallback(string $url): void {
1701 + // Suppress cache one more time in case some plugin filtered our
1702 + // earlier headers away between then and now.
1703 + nocache_headers();
1704 +
1705 + if (!headers_sent()) {
1706 + wp_safe_redirect($url);
1484 1707 exit;
1485 - } else {
1486 - $this->sendError(__('Could not generate quote URL', 'easy-invoice'));
1487 1708 }
1709 +
1710 + // Fallback: server-side redirect impossible. Emit a client-side one.
1711 + $safe_url = esc_url_raw($url);
1712 + echo '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8">';
1713 + echo '<meta http-equiv="refresh" content="0; url=' . esc_attr($safe_url) . '">';
1714 + echo '<title>Redirecting…</title>';
1715 + echo '<script>window.location.replace(' . wp_json_encode($safe_url) . ');</script>';
1716 + echo '</head><body>';
1717 + echo '<p>Redirecting to <a href="' . esc_url($safe_url) . '">' . esc_html($safe_url) . '</a>…</p>';
1718 + echo '</body></html>';
1719 + exit;
1488 1720 }
1489 1721
1490 1722 /**
1491 1723 * Search clients for the dropdown
@@ -1568,9 +1800,9 @@
1568 1800 * Save additional CSS for invoice/quote
1569 1801 */
1570 1802 public function saveAdditionalCSS() {
1571 1803 // Verify nonce
1572 - if (!wp_verify_nonce($_POST['nonce'], 'save_additional_css_nonce')) {
1804 + if (!wp_verify_nonce(($_POST['nonce'] ?? ''), 'save_additional_css_nonce')) {
1573 1805 $this->sendError('Security check failed');
1574 1806 return;
1575 1807 }
1576 1808