Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/quick-paypal-payments/legacy/accounts.php
+++ b/quick-paypal-payments/legacy/accounts.php
@@ -13,9 +13,21 @@
}
/**
+ * Capabilities a role created from a public form may not carry.
+ *
+ * @return string[]
+ */
+function qpp_role_capabilities_refused() {
+ return array( 'manage_options', 'edit_others_posts', 'unfiltered_html', 'edit_users', 'promote_users', 'activate_plugins', 'publish_posts', 'publish_pages', 'upload_files' );
+}
+
+/**
* The roles a payment form may be allowed to create.
*
- * Administrator is deliberately absent. This creates an account from a form
+ * Administrator is deliberately absent, and so is any role that can edit other
+ * people's posts, post unfiltered HTML, manage the site, publish or upload. A
+ * published page is what lets a form's own price be honoured, so a role that
+ * publishes could set its own. This creates an account from a form
* anyone on the internet can submit, and the username is whatever they typed in
* the first name box, so an administrator here is a way to hand the site away.
* Anything else the site has is offered, including roles added by other plugins,
@@ -31,6 +43,10 @@
if ( 'administrator' === $slug ) {
continue;
}
+ $caps = isset( $role['capabilities'] ) && is_array( $role['capabilities'] ) ? array_filter( $role['capabilities'] ) : array();
+ if ( array_intersect( qpp_role_capabilities_refused(), array_keys( $caps ) ) ) {
+ continue;
+ }
$roles[ $slug ] = isset( $role['name'] ) ? $role['name'] : $slug;
}
}
--- a/quick-paypal-payments/legacy/captcha.php
+++ b/quick-paypal-payments/legacy/captcha.php
@@ -0,0 +1,74 @@
+<?php
+/**
+ * The spambot blocker sum: the answer is decided and checked by the server.
+ *
+ * Kept in its own file with no side effects at load time so it can be required
+ * directly by the test suite without booting the rest of the plugin.
+ *
+ * @package Quick_Paypal_Payments
+ */
+
+// Prevent direct access.
+if ( ! defined( 'ABSPATH' ) ) {
+ exit;
+}
+
+/**
+ * How long an issued sum can be answered, in seconds. The same as the form's
+ * own nonce, so a cached page goes stale no sooner than it already did.
+ */
+if ( ! defined( 'QPP_CAPTCHA_LIFETIME' ) ) {
+ define( 'QPP_CAPTCHA_LIFETIME', DAY_IN_SECONDS );
+}
+
+/**
+ * Signature for an answer and expiry time.
+ *
+ * @param int $answer The sum's answer.
+ * @param int $expires Unix time the sum stops being accepted.
+ *
+ * @return string
+ */
+function qpp_captcha_signature( $answer, $expires ) {
+ return hash_hmac( 'sha256', 'qpp_captcha|' . (int) $answer . '|' . (int) $expires, wp_salt( 'nonce' ) );
+}
+
+/**
+ * The hidden field value for a sum, carrying its expiry and signature but not
+ * its answer.
+ *
+ * @param int $answer The sum's answer.
+ * @param int|null $now Current time, for tests.
+ *
+ * @return string
+ */
+function qpp_captcha_token( $answer, $now = null ) {
+ $expires = ( null === $now ? time() : (int) $now ) + QPP_CAPTCHA_LIFETIME;
+
+ return $expires . '.' . qpp_captcha_signature( $answer, $expires );
+}
+
+/**
+ * Whether a typed answer is the answer to the sum the token was issued for.
+ *
+ * @param mixed $typed The buyer's answer.
+ * @param mixed $token The posted hidden field.
+ * @param int|null $now Current time, for tests.
+ *
+ * @return bool
+ */
+function qpp_captcha_answer_ok( $typed, $token, $now = null ) {
+ if ( ! is_scalar( $typed ) || ! is_string( $token ) ) {
+ return false;
+ }
+ $typed = trim( (string) $typed );
+ if ( ! preg_match( '/^-?d{1,3}$/', $typed ) || ! preg_match( '/^(d{1,12}).([0-9a-f]{64})$/', $token, $parts ) ) {
+ return false;
+ }
+ $now = null === $now ? time() : (int) $now;
+ if ( (int) $parts[1] < $now ) {
+ return false;
+ }
+
+ return hash_equals( qpp_captcha_signature( (int) $typed, (int) $parts[1] ), $parts[2] );
+}
--- a/quick-paypal-payments/legacy/csv-cell.php
+++ b/quick-paypal-payments/legacy/csv-cell.php
@@ -0,0 +1,52 @@
+<?php
+/**
+ * Cells for the payment records CSV export.
+ *
+ * Kept in its own file with no side effects at load time so it can be required
+ * directly by the test suite without booting the rest of the plugin.
+ *
+ * @package Quick_Paypal_Payments
+ */
+
+// Prevent direct access.
+if ( ! defined( 'ABSPATH' ) ) {
+ exit;
+}
+
+/**
+ * A value as it should go into the CSV export, always read as text.
+ *
+ * A spreadsheet reads a cell that starts with =, +, -, @, a tab or a carriage
+ * return as something to calculate. Such a value is given a leading apostrophe,
+ * which spreadsheets show as text and do not display. Numbers and phone numbers
+ * such as -5 or +44 20 7946 0000 are left as they are.
+ *
+ * @param mixed $value The stored value.
+ *
+ * @return string
+ */
+function qpp_csv_cell( $value ) {
+ if ( ! is_scalar( $value ) ) {
+ return '';
+ }
+ $value = (string) $value;
+ if ( '' === $value || false === strpos( "=+-@tr", $value[0] ) ) {
+ return $value;
+ }
+ if ( preg_match( '/^[+-]?[0-9][0-9 ().-]*$/', $value ) ) {
+ return $value;
+ }
+
+ return "'" . $value;
+}
+
+/**
+ * Every cell of a CSV row through qpp_csv_cell().
+ *
+ * @param array $cells The row.
+ *
+ * @return array
+ */
+function qpp_csv_row( array $cells ) {
+ return array_map( 'qpp_csv_cell', $cells );
+}
--- a/quick-paypal-payments/legacy/ipn-log-notice.php
+++ b/quick-paypal-payments/legacy/ipn-log-notice.php
@@ -0,0 +1,111 @@
+<?php
+/**
+ * A one-off reminder about an IPN debug log left on the server.
+ *
+ * Shown to administrators while a log file named by QPP_IPN_DEBUG_LOG_FILE or
+ * IPN_DEBUG_LOG_FILE exists, until each one dismisses it. The file is never
+ * read or deleted here; that stays the site owner's decision.
+ *
+ * @package Quick_Paypal_Payments
+ */
+
+if ( ! defined( 'ABSPATH' ) ) {
+ exit;
+}
+
+/**
+ * The debug log constants that are set, by name.
+ *
+ * @return array<string, string> constant name => path
+ */
+function qpp_ipn_log_configured_paths() {
+ $paths = array();
+ foreach ( array( 'QPP_IPN_DEBUG_LOG_FILE', 'IPN_DEBUG_LOG_FILE' ) as $name ) {
+ if ( defined( $name ) && is_string( constant( $name ) ) && '' !== constant( $name ) ) {
+ $paths[ $name ] = constant( $name );
+ }
+ }
+
+ return $paths;
+}
+
+/**
+ * The configured log files that exist, by constant name.
+ *
+ * @param array<string, string> $paths constant name => path.
+ *
+ * @return array<string, string>
+ */
+function qpp_ipn_log_existing_files( array $paths ) {
+ return array_filter(
+ $paths,
+ function ( $path ) {
+ return is_string( $path ) && '' !== $path && is_file( $path );
+ }
+ );
+}
+
+/**
+ * What a dismissal is recorded against, so a different log file shows again.
+ *
+ * @param array<string, string> $files constant name => path.
+ *
+ * @return string
+ */
+function qpp_ipn_log_notice_key( array $files ) {
+ ksort( $files );
+
+ return md5( wp_json_encode( $files ) );
+}
+
+/**
+ * The reminder for the current user and screen, or '' when it is not due.
+ *
+ * @param array<string, string> $paths constant name => path, normally qpp_ipn_log_configured_paths().
+ *
+ * @return string
+ */
+function qpp_ipn_log_notice( array $paths ) {
+ if ( ! current_user_can( 'manage_options' ) ) {
+ return '';
+ }
+ $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
+ $base = $screen ? (string) $screen->base : '';
+ if ( 'dashboard' !== $base && false === strpos( $base, 'quick-paypal-payments' ) ) {
+ return '';
+ }
+ $files = qpp_ipn_log_existing_files( $paths );
+ if ( empty( $files ) ) {
+ return '';
+ }
+ if ( get_user_meta( get_current_user_id(), 'qpp_ipn_log_notice_dismissed', true ) === qpp_ipn_log_notice_key( $files ) ) {
+ return '';
+ }
+
+ $out = '<div id="qpp-ipn-log-notice" class="notice notice-warning">';
+ foreach ( $files as $name => $path ) {
+ $out .= '<p>' . esc_html(
+ sprintf(
+ /* translators: %1$s is the log file path, %2$s is the name of the wp-config.php constant. */
+ __( 'Quick PayPal Payments: the IPN debug log at %1$s may contain buyers' personal data. Delete it if you no longer need it, and remove %2$s from wp-config.php when debugging is finished.', 'quick-paypal-payments' ),
+ $path,
+ $name
+ )
+ ) . '</p>';
+ }
+ $dismiss = wp_nonce_url( admin_url( 'admin-post.php?action=qpp_dismiss_ipn_log_notice' ), 'qpp_dismiss_ipn_log_notice' );
+ $out .= '<p><a class="button" href="' . esc_url( $dismiss ) . '">' . esc_html__( 'Dismiss', 'quick-paypal-payments' ) . '</a></p></div>';
+
+ return $out;
+}
+
+/**
+ * Records the dismissal for the current user, against the files now present.
+ *
+ * @param array<string, string> $paths constant name => path.
+ *
+ * @return void
+ */
+function qpp_ipn_log_notice_dismiss( array $paths ) {
+ update_user_meta( get_current_user_id(), 'qpp_ipn_log_notice_dismissed', qpp_ipn_log_notice_key( qpp_ipn_log_existing_files( $paths ) ) );
+}
--- a/quick-paypal-payments/legacy/ipn-verification.php
+++ b/quick-paypal-payments/legacy/ipn-verification.php
@@ -99,20 +99,38 @@
}
if ( ! in_array( $expected['receiver'], $receivers, true ) ) {
- return 'payment was received by ' . implode( '/', $receivers ) . ' but this form is configured for ' . $expected['receiver'];
+ return 'payment was received by a different PayPal account from the one this form is configured for';
}
/*
- * Which field carries the amount depends on the notification. A new
- * subscription is confirmed before any money moves and carries the
- * per-period amount in amount3. Everything else reports what was actually
- * received in mc_gross. Subscription notifications that are not payments at
- * all (cancellation, failure, end of term) must never mark an order paid.
+ * Which notice settles an order depends on what the order asked for. A
+ * subscription order is settled by its signup, the only notice that says
+ * what the buyer signed up to, and only when those are the terms the form
+ * offered. PayPal reports the per-period amount in mc_amount3 (amount3 on
+ * older notices). Its payments carry no terms at all, so they never settle
+ * a subscription order. A one-off order is settled by a completed payment,
+ * never by any subscription notice.
*/
- if ( 'subscr_signup' === $txn_type ) {
- $amount_field = 'amount3';
- } elseif ( 0 === strpos( $txn_type, 'subscr_' ) && 'subscr_payment' !== $txn_type ) {
+ $terms = isset( $expected['recurring'] ) && is_array( $expected['recurring'] ) ? $expected['recurring'] : null;
+
+ if ( 0 === strpos( $txn_type, 'subscr_' ) && ! in_array( $txn_type, array( 'subscr_signup', 'subscr_payment' ), true ) ) {
return 'notification type ' . $txn_type . ' is not a payment';
+ }
+
+ if ( null !== $terms ) {
+ if ( 'subscr_signup' !== $txn_type ) {
+ return 'a subscription order is settled by its signup, not by ' . ( '' === $txn_type ? 'a notice with no type' : $txn_type );
+ }
+
+ $terms_check = qpp_check_subscription_terms( $ipn, $terms );
+
+ if ( true !== $terms_check ) {
+ return $terms_check;
+ }
+
+ $amount_field = isset( $ipn['mc_amount3'] ) ? 'mc_amount3' : 'amount3';
+ } elseif ( 0 === strpos( $txn_type, 'subscr_' ) ) {
+ return 'notification type ' . $txn_type . ' does not settle a one-off order';
} else {
$amount_field = 'mc_gross';
$payment_status = isset( $ipn['payment_status'] ) ? trim( $ipn['payment_status'] ) : '';
@@ -122,26 +140,72 @@
}
}
- if ( '' !== $expected['currency'] && ! empty( $ipn['mc_currency'] ) ) {
+ if ( '' !== $expected['currency'] ) {
+ if ( empty( $ipn['mc_currency'] ) ) {
+ return 'IPN carried no currency to check against this order';
+ }
if ( strtoupper( trim( $ipn['mc_currency'] ) ) !== $expected['currency'] ) {
return 'paid in ' . strtoupper( trim( $ipn['mc_currency'] ) ) . ' but this order is in ' . $expected['currency'];
}
}
/*
- * A zero expected total means the form takes whatever amount the buyer
- * enters, so there is nothing to compare against.
+ * The expectation holds what the buyer was asked to pay, including an
+ * amount they typed in themselves. An order expecting nothing, or less,
+ * could be settled by paying nothing, so it never verifies.
*/
- if ( $expected['gross'] > 0 ) {
- if ( ! isset( $ipn[ $amount_field ] ) || ! is_numeric( $ipn[ $amount_field ] ) ) {
- return 'IPN carried no usable ' . $amount_field . ' to check the amount against';
+ if ( ! ( $expected['gross'] > 0 ) ) {
+ return 'this order has no amount to check the payment against';
+ }
+
+ if ( ! isset( $ipn[ $amount_field ] ) || ! is_numeric( $ipn[ $amount_field ] ) ) {
+ return 'IPN carried no usable ' . $amount_field . ' to check the amount against';
+ }
+
+ $paid = (float) $ipn[ $amount_field ];
+
+ // Half a cent of tolerance so rounding never rejects a good payment.
+ if ( $paid + 0.005 < $expected['gross'] ) {
+ return 'paid ' . $paid . ' but this order totals ' . $expected['gross'];
+ }
+
+ return true;
+}
+
+/**
+ * Check a subscription signup against the terms the order offered.
+ *
+ * @param array $ipn Raw IPN fields as posted by PayPal.
+ * @param array $terms Expected period3 and recur_times. Without recur_times the
+ * count is not checked, for an order stored before 6.0.7.
+ *
+ * @return true|string True when the terms match, otherwise the reason they do not.
+ */
+function qpp_check_subscription_terms( $ipn, $terms ) {
+
+ foreach ( array( 'mc_amount1', 'amount1', 'period1', 'mc_amount2', 'amount2', 'period2' ) as $key ) {
+ if ( isset( $ipn[ $key ] ) && '' !== trim( (string) $ipn[ $key ] ) ) {
+ return 'subscription has a trial period this form does not offer';
}
+ }
- $paid = (float) $ipn[ $amount_field ];
+ $want = qpp_ipn_normalise_period( isset( $terms['period3'] ) ? $terms['period3'] : '' );
+ $got = qpp_ipn_normalise_period( isset( $ipn['period3'] ) ? $ipn['period3'] : '' );
- // Half a cent of tolerance so rounding never rejects a good payment.
- if ( $paid + 0.005 < $expected['gross'] ) {
- return 'paid ' . $paid . ' but this order totals ' . $expected['gross'];
+ if ( '' === $want || $got !== $want ) {
+ return 'subscription bills every ' . ( '' === $got ? '(missing)' : $got ) . ' but this order offered every ' . $want;
+ }
+
+ if ( ! isset( $ipn['recurring'] ) || '1' !== trim( (string) $ipn['recurring'] ) ) {
+ return 'subscription does not recur';
+ }
+
+ if ( isset( $terms['recur_times'] ) ) {
+ $want_times = (int) $terms['recur_times'];
+ $got_times = isset( $ipn['recur_times'] ) ? (int) $ipn['recur_times'] : 0;
+
+ if ( $got_times !== $want_times ) {
+ return 'subscription runs for ' . $got_times . ' payments but this order offered ' . $want_times;
}
}
@@ -149,6 +213,39 @@
}
/**
+ * A billing period in one form, so "1 m" and "1 M" compare equal.
+ *
+ * @param mixed $period Period as PayPal or the form states it.
+ *
+ * @return string
+ */
+function qpp_ipn_normalise_period( $period ) {
+ return is_scalar( $period ) ? strtoupper( (string) preg_replace( '/s+/', ' ', trim( (string) $period ) ) ) : '';
+}
+
+/**
+ * The subscription terms a form offers now, for an order stored before the
+ * order recorded its own terms. Null for a form that does not recur.
+ *
+ * @param string $form_id Form id.
+ *
+ * @return array|null
+ */
+function qpp_ipn_form_subscription_terms( $form_id ) {
+
+ $qpp = qpp_get_stored_options( $form_id );
+
+ if ( empty( $qpp['userecurring'] ) ) {
+ return null;
+ }
+
+ // The number of payments may have been the buyer's choice, so it is not guessed.
+ return array(
+ 'period3' => '1 ' . strtoupper( (string) $qpp['recurring'] ),
+ );
+}
+
+/**
* Build the payment expected for an order.
*
* Prefers the record written when the order was created, which is what the
@@ -169,11 +266,28 @@
if ( is_array( $expectations ) && isset( $expectations[ $custom ] ) ) {
$stored = $expectations[ $custom ];
- return array(
+ $expectation = array(
'gross' => isset( $stored['gross'] ) ? (float) $stored['gross'] : 0.0,
'currency' => isset( $stored['currency'] ) ? strtoupper( (string) $stored['currency'] ) : '',
'receiver' => isset( $stored['receiver'] ) ? strtolower( trim( (string) $stored['receiver'] ) ) : '',
);
+
+ /*
+ * Orders record whether they are a subscription and on what terms.
+ * One stored by an earlier version records neither, so it is held to
+ * the terms its form offers now.
+ */
+ if ( isset( $stored['kind'] ) || isset( $stored['recurring'] ) ) {
+ $terms = isset( $stored['recurring'] ) && is_array( $stored['recurring'] ) ? $stored['recurring'] : null;
+ } else {
+ $terms = qpp_ipn_form_subscription_terms( $form_id );
+ }
+
+ if ( null !== $terms ) {
+ $expectation['recurring'] = $terms;
+ }
+
+ return $expectation;
}
$qpp_setup = qpp_get_stored_setup();
@@ -182,11 +296,19 @@
$receiver = ! empty( $send['email'] ) ? $send['email'] : ( isset( $qpp_setup['email'] ) ? $qpp_setup['email'] : '' );
- return array(
+ $expectation = array(
'gross' => isset( $order['field3'] ) ? (float) $order['field3'] : 0.0,
'currency' => isset( $currency[ $form_id ] ) ? strtoupper( substr( (string) $currency[ $form_id ], 0, 3 ) ) : '',
'receiver' => strtolower( trim( (string) $receiver ) ),
);
+
+ $terms = qpp_ipn_form_subscription_terms( $form_id );
+
+ if ( null !== $terms ) {
+ $expectation['recurring'] = $terms;
+ }
+
+ return $expectation;
}
/**
@@ -194,7 +316,8 @@
* check the payment against later.
*
* @param string $custom The order's PayPal custom token.
- * @param array $args Expected gross, currency, receiver and form id.
+ * @param array $args Expected gross, currency, receiver and form id, and for a
+ * subscription its terms in recurring (period3, recur_times).
*/
function qpp_store_ipn_expectation( $custom, $args ) {
@@ -213,9 +336,17 @@
'currency' => isset( $args['currency'] ) ? strtoupper( (string) $args['currency'] ) : '',
'receiver' => isset( $args['receiver'] ) ? strtolower( trim( (string) $args['receiver'] ) ) : '',
'form' => isset( $args['form'] ) ? (string) $args['form'] : '',
+ 'kind' => empty( $args['recurring'] ) ? 'payment' : 'subscription',
'created' => time(),
);
+ if ( ! empty( $args['recurring'] ) && is_array( $args['recurring'] ) ) {
+ $expectations[ $custom ]['recurring'] = array(
+ 'period3' => qpp_ipn_normalise_period( isset( $args['recurring']['period3'] ) ? $args['recurring']['period3'] : '' ),
+ 'recur_times' => isset( $args['recurring']['recur_times'] ) ? trim( (string) $args['recurring']['recur_times'] ) : '',
+ );
+ }
+
update_option( 'qpp_ipn_expectations', qpp_prune_ipn_expectations( $expectations ), false );
}
@@ -311,13 +442,11 @@
*/
function qpp_ipn_reject( $reason, $ipn ) {
- $txn = ! empty( $ipn['txn_id'] ) ? $ipn['txn_id'] : 'unknown';
+ $txn = ! empty( $ipn['txn_id'] ) ? qpp_ipn_log_value( $ipn['txn_id'] ) : 'unknown';
$message = 'Quick PayPal Payments: IPN rejected (txn ' . $txn . '): ' . $reason;
- if ( defined( 'QPP_IPN_DEBUG_LOG_FILE' ) && false !== QPP_IPN_DEBUG_LOG_FILE ) {
- error_log( gmdate( '[Y-m-d H:i e] ' ) . $message . PHP_EOL, 3, QPP_IPN_DEBUG_LOG_FILE );
- } elseif ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
- error_log( $message );
+ if ( ! qpp_ipn_log( $message ) && defined( 'WP_DEBUG' ) && WP_DEBUG ) {
+ error_log( $message ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug only, and the message holds no personal data.
}
/**
@@ -328,3 +457,161 @@
*/
do_action( 'qpp_ipn_rejected', $reason, $ipn );
}
+
+
+/**
+ * The IPN debug log file, or false when logging is off or the path is refused.
+ *
+ * QPP_IPN_DEBUG_LOG_FILE turns logging on. IPN_DEBUG_LOG_FILE is the older name
+ * and is still honoured.
+ *
+ * @return string|false
+ */
+function qpp_ipn_log_path() {
+ if ( defined( 'QPP_IPN_DEBUG_LOG_FILE' ) ) {
+ $path = QPP_IPN_DEBUG_LOG_FILE;
+ } elseif ( defined( 'IPN_DEBUG_LOG_FILE' ) ) {
+ $path = IPN_DEBUG_LOG_FILE;
+ } else {
+ return false;
+ }
+
+ return is_string( $path ) && qpp_ipn_log_path_allowed( $path ) ? $path : false;
+}
+
+/**
+ * Whether a debug log may be written at this path: an absolute path in an
+ * existing folder outside the WordPress install and its content folder.
+ *
+ * @param string $path Log file path.
+ * @param array $roots Folders the log may not be in; defaults to ABSPATH and WP_CONTENT_DIR.
+ *
+ * @return bool
+ */
+function qpp_ipn_log_path_allowed( $path, $roots = null ) {
+ if ( ! is_string( $path ) || '' === $path || ! preg_match( '#^(/|[A-Za-z]:[\\/])#', $path ) ) {
+ return false;
+ }
+ $dir = realpath( dirname( $path ) );
+ if ( false === $dir ) {
+ return false;
+ }
+ if ( null === $roots ) {
+ $roots = array( defined( 'ABSPATH' ) ? ABSPATH : '', defined( 'WP_CONTENT_DIR' ) ? WP_CONTENT_DIR : '' );
+ }
+ foreach ( $roots as $root ) {
+ $root = '' === $root ? false : realpath( $root );
+ if ( false !== $root && 0 === strpos( $dir . DIRECTORY_SEPARATOR, rtrim( $root, '/\' ) . DIRECTORY_SEPARATOR ) ) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+/**
+ * Write a line to the IPN debug log, if there is one.
+ *
+ * @param string $message What to log. Never personal data.
+ *
+ * @return bool Whether it was written.
+ */
+function qpp_ipn_log( $message ) {
+ $path = qpp_ipn_log_path();
+ if ( false === $path ) {
+ return false;
+ }
+
+ return error_log( gmdate( '[Y-m-d H:i e] ' ) . $message . PHP_EOL, 3, $path ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Opt-in debug log set by the site owner.
+}
+
+/**
+ * A value made safe for a single log line.
+ *
+ * @param mixed $value Value from an IPN.
+ *
+ * @return string
+ */
+function qpp_ipn_log_value( $value ) {
+ return is_scalar( $value ) ? substr( (string) preg_replace( '/[^A-Za-z0-9._-]/', '', (string) $value ), 0, 40 ) : '';
+}
+
+/**
+ * The fields of an IPN that may be logged: what identifies the transaction and
+ * its amount, nothing about the buyer.
+ *
+ * @param array $ipn IPN fields.
+ *
+ * @return string
+ */
+function qpp_ipn_log_summary( $ipn ) {
+ $parts = array();
+ foreach ( array( 'txn_id', 'txn_type', 'payment_status', 'mc_gross', 'mc_currency' ) as $key ) {
+ $parts[] = $key . '=' . ( isset( $ipn[ $key ] ) ? qpp_ipn_log_value( $ipn[ $key ] ) : '' );
+ }
+
+ return implode( ' ', $parts );
+}
+
+/**
+ * The option that holds an order's settlement lock while one request settles it.
+ *
+ * @param string $custom Order token.
+ *
+ * @return string
+ */
+function qpp_ipn_settlement_lock_key( $custom ) {
+ return 'qpp_ipn_lock_' . md5( (string) $custom );
+}
+
+/**
+ * Take the settlement lock for an order, so two deliveries of the same notice
+ * arriving together cannot both settle it.
+ *
+ * The insert is atomic in the database. add_option() is not usable here, since
+ * it overwrites a row another request inserted a moment earlier. A lock older
+ * than the time limit belongs to a request that died, and is taken over only if
+ * no other request has taken it over first.
+ *
+ * @param string $custom Order token.
+ *
+ * @return bool True when this request now holds the lock.
+ */
+function qpp_ipn_acquire_settlement_lock( $custom ) {
+ global $wpdb;
+
+ $key = qpp_ipn_settlement_lock_key( $custom );
+ $now = (string) time();
+
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- An atomic insert is the point; the options API cannot give one.
+ $taken = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO {$wpdb->options} (option_name, option_value, autoload) VALUES (%s, %s, 'no')", $key, $now ) );
+ wp_cache_delete( $key, 'options' );
+ wp_cache_delete( 'notoptions', 'options' );
+
+ if ( 1 === (int) $taken ) {
+ return true;
+ }
+
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Must read the row as stored now, not a cached copy.
+ $held_since = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $key ) );
+ $limit = (int) apply_filters( 'qpp_ipn_settlement_lock_timeout', 5 * MINUTE_IN_SECONDS );
+
+ if ( null === $held_since || (int) $held_since > time() - $limit ) {
+ return false;
+ }
+
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Compare and swap, so only one request takes over a stale lock.
+ $taken = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->options} SET option_value = %s WHERE option_name = %s AND option_value = %s", $now, $key, $held_since ) );
+ wp_cache_delete( $key, 'options' );
+
+ return 1 === (int) $taken;
+}
+
+/**
+ * Release an order's settlement lock.
+ *
+ * @param string $custom Order token.
+ */
+function qpp_ipn_release_settlement_lock( $custom ) {
+ delete_option( qpp_ipn_settlement_lock_key( $custom ) );
+}
--- a/quick-paypal-payments/legacy/messages.php
+++ b/quick-paypal-payments/legacy/messages.php
@@ -112,15 +112,18 @@
}
if ( isset( $_POST['Submit'] ) ) {
check_admin_referer( 'qpp_payments_form', 'qpp_payments_form_nonce' );
- $options = array(
- 'messageqty',
- 'messageorder',
- 'hidepaid',
- 'showaddress'
+ $allowed = array(
+ 'messageqty' => array('fifty', 'hundred', 'all'),
+ 'messageorder' => array('oldest', 'newest'),
+ 'hidepaid' => array('', 'checked'),
+ 'showaddress' => array('', 'checked'),
);
- foreach ( $options as $item ) {
+ foreach ( $allowed as $item => $values ) {
if ( isset( $_POST[$item] ) ) {
- $messageoptions[$item] = stripslashes( sanitize_text_field( $_POST[$item] ) );
+ $posted = sanitize_text_field( wp_unslash( $_POST[$item] ) );
+ if ( in_array( $posted, $values, true ) ) {
+ $messageoptions[$item] = $posted;
+ }
}
}
$messageoptions = qpp_merge_msg( $messageoptions );
@@ -142,6 +145,9 @@
* there is no listener, so this is the only route an order has to being
* paid at all.
*/
+ foreach ( $result['settled'] as $index ) {
+ qpp_check_coupon( qpp_get_element( $result['messages'][$index], 'field6' ), $id );
+ }
$send = qpp_get_stored_send( $id );
if ( qpp_should_create_user( $send, 'afterpayment' ) ) {
foreach ( $result['settled'] as $index ) {
@@ -166,9 +172,12 @@
}
if ( isset( $_POST['qpp_delete_selected'] ) ) {
check_admin_referer( 'qpp_download_form', 'qpp_download_form_nonce' );
- $id = sanitize_text_field( $_POST['formname'] );
+ $id = sanitize_text_field( wp_unslash( $_POST['formname'] ) );
$message = get_option( 'qpp_messages' . $id );
- if ( $message !== false ) {
+ if ( !is_array( $message ) ) {
+ $message = array();
+ }
+ if ( $message ) {
$count = count( $message );
for ($i = 0; $i <= $count; $i++) {
if ( isset( $_POST[$i] ) && 'checked' === sanitize_text_field( wp_unslash( $_POST[$i] ) ) ) {
@@ -193,8 +202,11 @@
if ( $messageoptions['messageqty'] == 'hundred' ) {
$showthismany = '100';
}
- ${$messageoptions['messageqty']} = "checked";
- ${$messageoptions['messageorder']} = "checked";
+ $fifty = ( 'fifty' === $messageoptions['messageqty'] ? 'checked' : '' );
+ $hundred = ( 'hundred' === $messageoptions['messageqty'] ? 'checked' : '' );
+ $all = ( 'all' === $messageoptions['messageqty'] ? 'checked' : '' );
+ $oldest = ( 'oldest' === $messageoptions['messageorder'] ? 'checked' : '' );
+ $newest = ( 'newest' === $messageoptions['messageorder'] ? 'checked' : '' );
$dashboard = '<form method="post" action="">';
$dashboard .= wp_nonce_field(
'qpp_payments_form',
@@ -202,7 +214,7 @@
true,
false
);
- $dashboard .= '<p><b>' . esc_html__( 'Show', 'quick-paypal-payments' ) . '</b> <input style="margin:0; padding:0; border:none;" type="radio" name="messageqty" value="fifty" "' . esc_attr( $fifty ) . ' /> 50
+ $dashboard .= '<p><b>' . esc_html__( 'Show', 'quick-paypal-payments' ) . '</b> <input style="margin:0; padding:0; border:none;" type="radio" name="messageqty" value="fifty" ' . esc_attr( $fifty ) . ' /> 50
<input style="margin:0; padding:0; border:none;" type="radio" name="messageqty" value="hundred" ' . esc_attr( $hundred ) . ' /> 100
<input style="margin:0; padding:0; border:none;" type="radio" name="messageqty" value="all" ' . esc_attr( $all ) . ' /> ' . esc_html__( 'all messages.', 'quick-paypal-payments' ) . '
<b>' . esc_html__( 'List', 'quick-paypal-payments' ) . '</b> <input style="margin:0; padding:0; border:none;" type="radio" name="messageorder" value="oldest" ' . esc_attr( $oldest ) . ' /> ' . esc_html__( 'oldest first', 'quick-paypal-payments' ) . '
--- a/quick-paypal-payments/legacy/output-escaping.php
+++ b/quick-paypal-payments/legacy/output-escaping.php
@@ -77,3 +77,21 @@
function qpp_esc_visitor_attr( $value ) {
return qpp_inert_shortcodes( esc_attr( (string) $value ) );
}
+
+/**
+ * A value a link supplies to prefill the form, cleaned as it is read.
+ *
+ * Square brackets have no place in a reference, an amount, an item number or a
+ * coupon code, so they are dropped here as well as escaped where the form is
+ * printed.
+ *
+ * @param mixed $value Value from the request, already unslashed.
+ * @return string
+ */
+function qpp_clean_prefill( $value ) {
+ if ( ! is_scalar( $value ) ) {
+ return '';
+ }
+
+ return str_replace( array( '[', ']' ), '', sanitize_text_field( (string) $value ) );
+}
--- a/quick-paypal-payments/legacy/payments-admin.php
+++ b/quick-paypal-payments/legacy/payments-admin.php
@@ -50,7 +50,7 @@
}
// Already settled, by IPN or by hand. Not an error, but not a change
// either, so it must not inflate the count the notice reports back.
- if ( isset( $messages[ $index ]['field18'] ) && 'Paid' === $messages[ $index ]['field18'] ) {
+ if ( qpp_order_is_paid( $messages[ $index ] ) ) {
continue;
}
$messages[ $index ] = qpp_settle_order( $messages[ $index ], 'manual' );
@@ -91,6 +91,49 @@
}
/**
+ * Whether a stored order row has been settled.
+ *
+ * A settled row keeps 'Paid' where its order token was, so the same marker is
+ * also the one value that must never be accepted as a token.
+ *
+ * @param array|mixed $row Stored payment row.
+ *
+ * @return bool
+ */
+function qpp_order_is_paid( $row ) {
+ return is_array( $row ) && isset( $row['field18'] ) && qpp_is_paid_marker( $row['field18'] );
+}
+
+/**
+ * The index of the unpaid order row holding a token, or false.
+ *
+ * @param array $messages Stored payment rows.
+ * @param string $custom Order token.
+ *
+ * @return int|false
+ */
+function qpp_find_unpaid_order( $messages, $custom ) {
+ foreach ( $messages as $index => $row ) {
+ if ( is_array( $row ) && isset( $row['field18'] ) && $row['field18'] === $custom && ! qpp_order_is_paid( $row ) ) {
+ return $index;
+ }
+ }
+
+ return false;
+}
+
+/**
+ * Whether a value is the settled marker, however it is cased or padded.
+ *
+ * @param mixed $value Token or field value.
+ *
+ * @return bool
+ */
+function qpp_is_paid_marker( $value ) {
+ return is_scalar( $value ) && 0 === strcasecmp( trim( (string) $value ), 'Paid' );
+}
+
+/**
* The payment status to show for a row on a site without the IPN listener.
*
* With IPN on, the list keeps its long standing status column, labelled from the
@@ -224,3 +267,16 @@
return $selected;
}
+
+/**
+ * The lines of a stored reference. A form with several products stores one
+ * "name x quantity" line per item, each ended by "</br>"; any other reference
+ * is a single line. Escape each line where it is printed.
+ *
+ * @param mixed $reference Stored reference.
+ *
+ * @return string[]
+ */
+function qpp_reference_lines( $reference ) {
+ return array_values( array_filter( array_map( 'trim', explode( '</br>', (string) $reference ) ), 'strlen' ) );
+}
--- a/quick-paypal-payments/legacy/quick-paypal-payments.php
+++ b/quick-paypal-payments/legacy/quick-paypal-payments.php
@@ -31,14 +31,15 @@
add_action( 'template_redirect', 'qpp_ipn' );
require_once __DIR__ . '/ipn-verification.php';
require_once __DIR__ . '/shortcode-attributes.php';
+require_once __DIR__ . '/shortcode-offer.php';
require_once __DIR__ . '/recurring-times.php';
require_once __DIR__ . '/form-name.php';
+require_once __DIR__ . '/csv-cell.php';
+require_once __DIR__ . '/captcha.php';
require_once __DIR__ . '/output-escaping.php';
add_action( 'wp_head', 'qpp_head_css' );
add_action( 'wp_ajax_qpp_validate_form', 'qpp_validate_form_callback' );
add_action( 'wp_ajax_nopriv_qpp_validate_form', 'qpp_validate_form_callback' );
-add_action( 'wp_ajax_qpp_process_payment', 'qpp_process_payment' );
-add_action( 'wp_ajax_nopriv_qpp_process_express_checkout_payment', 'qpp_process_express_checkout_payment' );
$qpp_end_loop = false;
$qpp_current_custom = '';
$qpp_attributes = array();
@@ -49,6 +50,7 @@
require_once plugin_dir_path( __FILE__ ) . '/payments-admin.php';
require_once plugin_dir_path( __FILE__ ) . '/free-gold-offer.php';
require_once plugin_dir_path( __FILE__ ) . '/review-prompt.php';
+require_once __DIR__ . '/ipn-log-notice.php';
require_once plugin_dir_path( __FILE__ ) . '/options.php';
/*
* Deferred to init. This file is required while the plugin is still loading, and
@@ -178,7 +180,7 @@
* form_id must also be the signed form, or the submission would be
* validated against one form's settings and priced with another's.
*/
- if ( false === $sc || qpp_get_element( $sc, 'form' ) !== $form ) {
+ if ( false === $sc || qpp_get_element( $sc, 'form' ) !== $form || !qpp_shortcode_attributes_are_offered( $sc ) ) {
$json->errors[] = (object) array(
'name' => 'form',
'error' => 'error',
@@ -186,7 +188,7 @@
echo json_encode( $json );
wp_die();
}
- $info = qpp_default_merge_v( $_POST );
+ $info = qpp_default_merge_v( wp_unslash( $_POST ) );
/*
* Always validate. Applying a coupon is an ordinary page post, never this
* ajax call, so a qppapply field here was only ever a way to skip
@@ -244,6 +246,21 @@
$combine,
$itemamount
);
+ /*
+ * PayPal cannot take nothing, and an order expecting nothing could
+ * be settled by paying nothing, so a coupon worth the whole order is
+ * refused, with a message saying why.
+ */
+ if ( !(qpp_payment_amount_due( $payment ) > 0) ) {
+ $json->success = false;
+ $json->blurb = esc_html__( 'This coupon covers the whole amount, so there is nothing to pay. Please contact us.', 'quick-paypal-payments' );
+ $json->errors[] = (object) array(
+ 'name' => 'couponblurb',
+ 'error' => 'error',
+ );
+ echo json_encode( $json );
+ wp_die();
+ }
$json->html = qpp_process_form(
$v,
$form,
@@ -378,7 +395,7 @@
*/
$d = array();
if ( isset( $_POST['qpp_payment_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['qpp_payment_nonce'] ) ), 'qpp_payment_form' ) ) {
- $d = qpp_sanitize( $_POST );
+ $d = qpp_sanitize( wp_unslash( $_POST ) );
}
global $qpp_attributes;
$atts = $qpp_attributes[$form];
@@ -624,14 +641,19 @@
Make sure this form is the form which is being submitted
*/
if ( isset( $_REQUEST['form_id'] ) && $_REQUEST['form_id'] == $form ) {
+ /*
+ * A payment link and a submitted form both arrive here. Only a value
+ * from the link is a prefill; what a buyer submits keeps its handling,
+ * so a choice such as "T-shirt [L]" reaches the order as chosen.
+ */
if ( isset( $_REQUEST["reference"] ) ) {
- $id = sanitize_text_field( $_REQUEST["reference"] );
+ $id = ( isset( $_POST["reference"] ) ? sanitize_text_field( wp_unslash( $_POST["reference"] ) ) : qpp_clean_prefill( wp_unslash( $_GET["reference"] ?? '' ) ) );
}
if ( isset( $_REQUEST["amount"] ) ) {
- $amount = sanitize_text_field( $_REQUEST["amount"] );
+ $amount = ( isset( $_POST["amount"] ) ? sanitize_text_field( wp_unslash( $_POST["amount"] ) ) : qpp_clean_prefill( wp_unslash( $_GET["amount"] ?? '' ) ) );
}
if ( isset( $_REQUEST["item"] ) ) {
- $qpp['stocklabel'] = sanitize_text_field( $_REQUEST["item"] );
+ $qpp['stocklabel'] = ( isset( $_POST["item"] ) ? sanitize_text_field( wp_unslash( $_POST["item"] ) ) : qpp_clean_prefill( wp_unslash( $_GET["item"] ?? '' ) ) );
}
/*
* A posted 'form' used to switch which form's settings applied, letting
@@ -687,7 +709,7 @@
*/
$d = array();
if ( isset( $_POST['qpp_payment_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['qpp_payment_nonce'] ) ), 'qpp_payment_form' ) ) {
- $d = qpp_sanitize( $_POST );
+ $d = qpp_sanitize( wp_unslash( $_POST ) );
}
for ($i = 1; $i <= 9; $i++) {
if ( isset( $d['qtyproduct' . $i] ) ) {
@@ -739,20 +761,21 @@
// Validate the coupon
if ( isset( $couponcode ) ) {
if ( $ticket = qpp_get_coupon( $couponcode, $form ) ) {
- // Is the coupon expired?
- if ( qpp_get_element( $ticket, 'expired' ) || 0 === qpp_get_element( $ticket, 'qty' ) ) {
+ // Is the coupon expired? An empty count means no limit. Any other
+ // count is a number of uses left, stored as an integer after a use
+ // and as a string by the settings screen.
+ $uses_left = trim( (string) qpp_get_element( $ticket, 'qty' ) );
+ if ( qpp_get_element( $ticket, 'expired' ) || '' !== $uses_left && (int) $uses_left <= 0 ) {
$v['couponerror'] = qpp_get_element( $coupon, 'couponexpired' );
} else {
// There is an available coupon
- if ( qpp_get_element( $ticket, 'qty', 0 ) !== 0 ) {
- $v['couponapplied'] = 'checked';
- $v['couponblurb'] = $couponcode;
- $v['coupon'] = array(
- 'type' => $ticket['type'],
- 'value' => $ticket['value'],
- 'code' => $ticket['code'],
- );
- }
+ $v['couponapplied'] = 'checked';
+ $v['couponblurb'] = $couponcode;
+ $v['coupon'] = array(
+ 'type' => $ticket['type'],
+ 'value' => $ticket['value'],
+ 'code' => $ticket['code'],
+ );
}
if ( !qpp_get_element( $v, 'couponapplied' ) && !qpp_get_element( $v, 'couponerror' ) ) {
$v['couponerror'] = qpp_get_element( $coupon, 'couponerror' );
@@ -779,7 +802,7 @@
'amount' => (float) qpp_format_amount( $currency[$form], $qpp, $check ),
'quantity' => (int) $d['qtyproduct' . $i],
);
- $total += $check * $d['qtyproduct' . $i];
+ $total += $check * (int) $d['qtyproduct' . $i];
}
}
} else {
@@ -861,13 +884,20 @@
}
/*
* A ?form= link picks which of the merchant's forms a plain [qpp] shows.
+ * A shortcode carrying any other attribute keeps its own form, so a price
+ * written for one form is never applied to another.
* Read only, from a link shared with customers, so no nonce applies; see
* the prefill note in qpp_display_form(). Applied here, before anything is
* read for the form, so the settings, the signed attributes and the posted
* form_id all name the same form.
*/
+ $qpp_other_atts = array_diff_key( array_filter( $atts, static function ( $value ) {
+ return '' !== (string) $value;
+ } ), array(
+ 'form' => true,
+ ) );
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read only choice of a configured form from a shareable link; no state change.
- if ( empty( $atts['form'] ) && isset( $_GET['form'] ) ) {
+ if ( empty( $atts['form'] ) && array() === $qpp_other_atts && isset( $_GET['form'] ) ) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- As above.
$atts['form'] = qpp_prefill_form_name( $qpp_setup, sanitize_text_field( wp_unslash( $_GET['form'] ) ) );
}
@@ -934,20 +964,33 @@
$combine,
$itemamount
);
- echo wp_kses( qpp_process_form(
- $v,
- $form,
- $payment,
- $combine,
- $itemamount
- ), qpp_allowed_html() );
- global $qpp_stripe_redirect;
- if ( !empty( $qpp_stripe_redirect ) ) {
- // Printed rather than enqueued: wp_kses() strips a script tag out of
- // the markup above, and the footer may already have gone out.
- wp_print_inline_script_tag( 'window.location.href = ' . wp_json_encode( $qpp_stripe_redirect ) . ';' );
+ // As the ajax submission: nothing due is never handed to PayPal.
+ if ( !(qpp_payment_amount_due( $payment ) > 0) ) {
+ $v['nothingdue'] = esc_html__( 'This coupon covers the whole amount, so there is nothing to pay. Please contact us.', 'quick-paypal-payments' );
+ $formerrors['couponblurb'] = 'error';
+ qpp_display_form(
+ $v,
+ $formerrors,
+ $form,
+ $atts,
+ $from_admin_settings
+ );
} else {
- wp_add_inline_script( 'qpp_script', 'document.getElementById("frmCart").submit()', 'after' );
+ echo wp_kses( qpp_process_form(
+ $v,
+ $form,
+ $payment,
+ $combine,
+ $itemamount
+ ), qpp_allowed_html() );
+ global $qpp_stripe_redirect;
+ if ( !empty( $qpp_stripe_redirect ) ) {
+ // Printed rather than enqueued: wp_kses() strips a script tag out of
+ // the markup above, and the footer may already have gone out.
+ wp_print_inline_script_tag( 'window.location.href = ' . wp_json_encode( $qpp_stripe_redirect ) . ';' );
+ } else {
+ wp_add_inline_script( 'qpp_script', 'document.getElementById("frmCart").submit()', 'after' );
+ }
}
}
} else {
@@ -955,10 +998,10 @@
$digit2 = wp_rand( 1, 10 );
if ( $digit2 >= $digit1 ) {
$v['thesum'] = "{$digit1} + {$digit2}";
- $v['answer'] = $digit1 + $digit2;
+ $v['answer'] = qpp_captcha_token( $digit1 + $digit2 );
} else {
$v['thesum'] = "{$digit1} - {$digit2}";
- $v['answer'] = $digit1 - $digit2;
+ $v['answer'] = qpp_captcha_token( $digit1 - $digit2 );
}
qpp_display_form(
$v,
@@ -1034,11 +1077,11 @@
* already been read and its attributes signed (QPP-60).
*/
if ( isset( $prefill['reference'] ) ) {
- $values['reference'] = sanitize_text_field( $prefill['reference'] );
+ $values['reference'] = qpp_clean_prefill( $prefill['reference'] );
$values['setref'] = true;
}
if ( isset( $prefill['coupon'] ) ) {
- $values['couponblurb'] = sanitize_text_field( $prefill['coupon'] );
+ $values['couponblurb'] = qpp_clean_prefill( $prefill['coupon'] );
$values['couponget'] = true;
}
$qpp_form = qpp_get_stored_setup();
@@ -1096,7 +1139,7 @@
*/
if ( count( array_filter( $errors ) ) > 0 || $values['noproduct'] ) {
wp_add_inline_script( 'qpp_script', 'document.querySelector("#qpp_reload").scrollIntoView()' );
- $content .= "<" . $hd . " class='qpp-header' id='qpp_reload' style='color:" . $style['error-colour'] . ";'>" . $error['errortitle'] . "</" . $hd . ">n <p class='qpp-blurb' style='color:" . $style['error-colour'] . ";'>" . $error['errorblurb'] . "</p>";
+ $content .= "<" . $hd . " class='qpp-header' id='qpp_reload' style='color:" . $style['error-colour'] . ";'>" . $error['errortitle'] . "</" . $hd . ">n <p class='qpp-blurb' style='color:" . $style['error-colour'] . ";'>" . (( qpp_get_element( $values, 'nothingdue' ) ? $values['nothingdue'] : $error['errorblurb'] )) . "</p>";
$arr = array(
'amount',
'reference',
@@ -1153,8 +1196,8 @@
$attr['post'] = get_the_ID();
$content .= '<input type="hidden" name="qpp_sc" value="' . esc_attr( qpp_sign_shortcode_attributes( $attr ) ) . '" />';
$content .= '<input type="hidden" name="form_id" value="' . esc_attr( $id ) . '" />';
- $content .= '<input type="hidden" name="currencybefore" value="' . $c['b'] . '" />';
- $content .= '<input type="hidden" name="currencyafter" value="' . $c['a'] . '" />';
+ $content .= '<input type="hidden" name="currencybefore" value="' . esc_attr( $c['b'] ) . '" />';
+ $content .= '<input type="hidden" name="currencyafter" value="' . esc_attr( $c['a'] ) . '" />';
$content .= wp_nonce_field(
'qpp_payment_form',
'qpp_payment_nonce',
@@ -1312,9 +1355,9 @@
$checked = 'checked';
}
if ( $item === reset( $arr ) ) {
- $content .= '<input type="radio" style="margin:0; padding: 0; border: none" name="option1" value="' . $item . '" id="' . $item . '" checked><label for="' . $item . '"> ' . $item . '</label>' . $br;
+ $content .= '<input type="radio" style="margin:0; padding: 0; border: none" name="option1" value="' . esc_attr( $item ) . '" id="' . esc_attr( $item ) . '" checked><label for="' . esc_attr( $item ) . '"> ' . esc_html( $item ) . '</label>' . $br;
} else {
- $content .= '<input type="radio" style="margin:0; padding: 0; border: none" name="option1" value="' . $item . '" id="' . $item . '" ' . $checked . '><label for="' . $item . '"> ' . $item . '</label>' . $br;
+ $content .= '<input type="radio" style="margin:0; padding: 0; border: none" name="option1" value="' . esc_attr( $item ) . '" id="' . esc_attr( $item ) . '" ' . $checked . '><label for="' . esc_attr( $item ) . '"> ' . esc_html( $item ) . '</label>' . $br;
}
}
$content .= '</p>';
@@ -1349,9 +1392,9 @@
if ( !empty( $qpp['mathscaption'] ) ) {
$content .= '<p class="input">' . $qpp['mathscaption'] . '</p>';
}
- $content .= '<p>' . wp_strip_all_tags( $values['thesum'] ) . ' = <input type="text" ' . $required . ' style="width:3em;font-size:100%;' . $errors['captcha'] . '" label="Sum" name="maths" value="' . esc_attr( $values['maths'] ) . '"></p>
- <input type="hidden" name="answer" value="' . wp_strip_all_tags( $values['answer'] ) . '" />
- <input type="hidden" name="thesum" value="' . wp_strip_all_tags( $values['thesum'] ) . '" />';
+ $content .= '<p>' . esc_html( wp_strip_all_tags( $values['thesum'] ) ) . ' = <input type="text" ' . $required . ' style="width:3em;font-size:100%;' . $errors['captcha'] . '" label="Sum" name="maths" value="' . esc_attr( $values['maths'] ) . '"></p>
+ <input type="hidden" name="answer" value="' . esc_attr( wp_strip_all_tags( $values['answer'] ) ) . '" />
+ <input type="hidden" name="thesum" value="' . esc_attr( wp_strip_all_tags( $values['thesum'] ) ) . '" />';
}
break;
case 'field9':
@@ -1366,7 +1409,7 @@
if ( $values['noproduct'] ) {
$content .= '<p style="color:' . $style['error-colour'] . ';">' . esc_html__( 'No products selected.', 'quick-paypal-payments' ) . '</p>';
} else {
- $content .= '<p style="color:' . $style['error-colour'] . ';">' . $values['couponerror'] . '</p>';
+ $content .= '<p style="color:' . esc_attr( $style['error-colour'] ) . ';">' . wp_kses_post( $values['couponerror'] ) . '</p>';
}
}
$content .= '<p>' . qpp_get_element( $values, 'couponget' ) . '</p>';
@@ -1395,7 +1438,7 @@
$required = ( !$errors['useterms'] ? 'border:' . $style['required-border'] . ';' : ' style="' . $errors['useterms'] . '"' );
$color = ( $errors['useterms'] ? ' style="color:' . $style['error-colour'] . ';" ' : '' );
$content .= '<p class="input">
- <input type="checkbox" style="margin:0; padding: 0;width:auto;" name="termschecked" value="checked" ' . qpp_get_element( $values, 'termschecked' ) . '>
+ <input type="checkbox" style="margin:0; padding: 0;width:auto;" name="termschecked" value="checked" ' . (( qpp_get_element( $values, 'termschecked' ) ? 'checked' : '' )) . '>
';
if ( $qpp['termsurl'] ) {
$content .= '<a class="qpp-terms" href="' . $qpp['termsurl'] . '"' . $target . '>' . $qpp['termsblurb'] . '</a></p>';
@@ -1542,7 +1585,7 @@
if ( $qpp['use_consent'] ) {
$required = ( !$errors['use_constent'] && $qpp['ruse_consent'] ? 'required' : '' );
$content .= '<p class="input ' . esc_attr( $required ) . '">
- <input ' . esc_attr( $required ) . ' type="checkbox" name="consent" value="checked" ' . qpp_get_element( $values, 'consent' ) . '>
+ <input ' . esc_attr( $required ) . ' type="checkbox" name="consent" value="checked" ' . (( qpp_get_element( $values, 'consent' ) ? 'checked' : '' )) . '>
' . $qpp['consentlabel'] . '</p>';
}
break;
@@ -1758,9 +1801,9 @@
$label = str_replace( '[cost]', $multiples['cost' . $i], $label );
if ( $multiples['product' . $i] ) {
if ( $multiples['use_quantity'] ) {
- $content .= '<div style="clear:both;"><span class="qpp-p-style" style="float:left;padding:7px 0">' . $label . '</span><span style="float:right;"><input type="text" style="width:4em;text-align:right" name="qtyproduct' . $i . '" id="qtyproduct' . $i . '" placeholder="' . $values['qtyproduct' . $i] . '" /></span></div>';
+ $content .= '<div style="clear:both;"><span class="qpp-p-style" style="float:left;padding:7px 0">' . $label . '</span><span style="float:right;"><input type="text" style="width:4em;text-align:right" name="qtyproduct' . $i . '" id="qtyproduct' . $i . '" placeholder="' . esc_attr( $values['qtyproduct' . $i] ) . '" /></span></div>';
} else {
- $content .= '<p><input type="checkbox" style="margin:0; padding: 0;width:auto;" name="qtyproduct' . $i . '" value="checked" ' . $values['qtyproduct' . $i] . '> ' . $label . '</p>';
+ $content .= '<p><input type="checkbox" style="margin:0; padding: 0;width:auto;" name="qtyproduct' . $i . '" value="checked" ' . (( !empty( $values['qtyproduct' . $i] ) ? 'checked' : '' )) . '> ' . $label . '</p>';
}
$content .= '<input type="hidden" name="product' . $i . '" value="' . $multiples['cost' . $i] . '" />';
}
@@ -1775,7 +1818,7 @@
$set = $data['amount']['value'];
$currency = $data['currency'];
$other = $data['other'];
- $otherinput = '<div id="otheramount">' . '<input type="text" label="' . ($other['instruction'] ?? '') . '" placeholder="' . ($other['instruction'] ?? '') . '" name="otheramount" style="display: none;" />' . '</div>' . '<input type="hidden" name="use_other_amount" value="false" />';
+ $otherinput = '<div id="otheramount">' . '<input type="text" label="' . esc_attr( $other['instruction'] ?? '' ) . '" placeholder="' . esc_attr( $other['instruction'] ?? '' ) . '" name="otheramount" style="display: none;" />' . '</div>' . '<input type="hidden" name="use_other_amount" value="false" />';
$returning = "";
if ( $other['use'] ) {
$choices[] = 'other';
@@ -1788,9 +1831,9 @@
$value = (float) $v;
$selected = ( $v == $set || $v == 'other' && $other['toggled'] ? ' selected="selected"' : '' );
if ( $v != 'other' ) {
- $returning .= "<option value='{$value}'{$selected}>{$display}</option>";
+ $returning .= '<option value="' . esc_attr( $value ) . '"' . $selected . '>' . esc_html( $display ) . '</option>';
} else {
- $returning .= "<option value='other'{$selected}>{$other['caption']}</option>";
+ $returning .= '<option value="other"' . $selected . '>' . esc_html( $other['caption'] ) . '</option>';
}
}
$returning .= '</select>';
@@ -1837,7 +1880,7 @@
$display = $value;
}
$selected = ( $value == $set ? ' selected='selected'' : '' );
- $returning .= "<option value='{$value}'{$selected}>{$display}</option>";
+ $returning .= '<option value="' . esc_attr( $value ) . '"' . $selected . '>' . esc_html( $display ) . '</option>';
}
$returning .= "</select>";
break;
@@ -1876,19 +1919,19 @@
if ( $blurb ) {
$content = '<p class="payment" >' . $blurb . '</p>';
}
- $content .= '<select name="' . $name . '">';
+ $content .= '<select name="' . esc_attr( $name ) . '">';
if ( !$combine ) {
foreach ( $arr as $item ) {
$selected = '';
if ( $values[$name] == $item ) {
$selected = 'selected';
}
- $content .= '<option value="' . $item . '" ' . $selected . '>' . $item . '</option>' . "rt";
+ $content .= '<option value="' . esc_attr( $item ) . '" ' . $selected . '>' . esc_html( $item ) . '</option>' . "rt";
}
} else {
foreach ( $arr as $item ) {
$selected = ( strrpos( $values['reference'], $item[0] ) !== false && $values['combine'] != 'initial' ? 'selected' : '' );
- $content .= '<option value="' . $item[0] . '&' . $item[1] . '" ' . $selected . '> ' . $item[0] . ' ' . $item[1] . '</option>';
+ $content .= '<option value="' . esc_attr( $item[0] . '&' . $item[1] ) . '" ' . $selected . '> ' . esc_html( $item[0] . ' ' . $item[1] ) . '</option>';
$selected = '';
}
}
@@ -1908,7 +1951,7 @@
if ( $values[$name . '_' . str_replace( ' ', '', $item )] == $item ) {
$checked = 'checked';
}
- $content .= '<label><input type="checkbox" style="margin:0; padding: 0; border: none" name="' . $name . '_' . str_replace( ' ', '', $item ) . '" value="' . $item . '" ' . $checked . '> ' . $item . '</label>' . $br;
+ $content .= '<label><input type="checkbox" style="margin:0; padding: 0; border: none" name="' . esc_attr( $name . '_' . str_replace( ' ', '', $item ) ) . '" value="' . esc_attr( $item ) . '" ' . $checked . '> ' . esc_html( $item ) . '</label>' . $br;
}
$content .= '</p>';
return $content;
@@ -1970,6 +2013,16 @@
$qpp = qpp_get_stored_options( $form );
$address = qpp_get_stored_address( $form );
$check = preg_replace( '/[^.,0-9]/', '', $v['amount'] );
+ /*
+ * The email is checked as typed, before it is cleaned: cleaning turns
+ * some invalid input into an address that looks valid. One address or
+ * none; anything else is an error and is never stored or sent to.
+ */
+ $typed_email = ( isset( $v['email'] ) ? trim( (string) $v['email'] ) : '' );
+ if ( '' !== $typed_email && $typed_email !== qpp_get_element( $qpp, 'emailblurb' ) && $typed_email !== qpp_get_element( $address, 'email' ) && '' === qpp_valid_buyer_email( $typed_email ) ) {
+ $errors['email'] = 'error';
+ $v['email'] = '';
+ }
$arr = array(
'amount' => 'absint',
'reference' => 'sanitize_text_field',
@@ -1995,8 +2048,9 @@
$checkmultiple = false;
$v['setpay'] = $v['setref'] = true;
for ($i = 1; $i <= 9; $i++) {
- if ( $v['qtyproduct' . $i] ) {
- if ( is_numeric( $v['qtyproduct' . $i] ) ) {
+ if ( !empty( $v['qtyproduct' . $i] ) ) {
+ // PayPal is sent whole quantities, so the order is priced on them too.
+ if ( is_scalar( $v['qtyproduct' . $i] ) && preg_match( '/^\s*\d+\s*$/', (string) $v['qtyproduct' . $i] ) ) {
$checkmultiple = true;
} elseif ( 'checked' === $v['qtyproduct' . $i] ) {
$checkmultiple = true;
@@ -2116,10 +2170,7 @@
}
if ( $qpp['captcha'] == 'checked' ) {
$v['maths'] = wp_strip_all_tags( $v['maths'] );
- if ( $v['maths'] != $v['answer'] ) {
- $errors['captcha'] = 'error';
- }
- if ( empty( $v['maths'] ) ) {
+ if ( !qpp_captcha_answer_ok( $v['maths'], $v['answer'] ) ) {
$errors['captcha'] = 'error';
}
}
@@ -2259,6 +2310,7 @@
}
}
if ( $qpp['use_multiples'] ) {
+ $details = '';
foreach ( $values['items'] as $k => $item ) {
if ( $item['quantity'] ) {
$details .= $item['item_name'] . ' x ' . $item['quantity'] . '</br>';
@@ -2287,12 +2339,18 @@
if ( !isset( $combined ) ) {
$combined = 0;
}
+ /*
+ * A single product is billed as its unit price times the quantity, the
+ * same figures the hand-off sends, so the order records what is charged.
+ */
+ $totalamount = ( $qpp['use_multiples'] ? (float) qpp_get_total( $values['items'] ) : round( $amount * $quantity, 2 ) );
$returning = array(
'reference' => (string) $values['reference'],
'custom' => (string) $custom,
'cost' => (float) $amount,
'quantity' => (int) $quantity,
- 'totalamount' => (float) qpp_get_total( $values['items'] ),
+ 'totalamount' => (float) $totalamount,
+ 'per_unit' => !$qpp['use_multiples'] && !$qpp['userecurring'],
'combined' => (float) $combined,
'handling' => (float) $multiple_handling,
'coupon' => (object) $c_array,
@@ -2305,6 +2363,31 @@
return (object) $returning;
}
+/**
+ * What an order asks the buyer to pay: items, less any coupon, plus handling.
+ *
+ * @param object $payment From qpp_process_values().
+ *
+ * @return float
+ */
+function qpp_payment_amount_due( $payment ) {
+ $due = (float) $payment->totalamount;
+ if ( !empty( $payment->coupon->use ) ) {
+ $discount = (float) $payment->coupon->value;
+ if ( 'percent' == $payment->coupon->type ) {
+ if ( !empty( $payment->per_unit ) ) {
+ // A single product sends the