Beispiel #1
0
/**
 * Process Purchase Form
 *
 * Handles the purchase form process.
 *
 * @access      private
 * @since       1.0
 * @return      void
 */
function give_process_purchase_form()
{
    do_action('give_pre_process_purchase');
    // Validate the form $_POST data
    $valid_data = give_purchase_form_validate_fields();
    // Allow themes and plugins to hook to errors
    do_action('give_checkout_error_checks', $valid_data, $_POST);
    $is_ajax = isset($_POST['give_ajax']);
    // Process the login form
    if (isset($_POST['give_login_submit'])) {
        give_process_form_login();
    }
    // Validate the user
    $user = give_get_purchase_form_user($valid_data);
    if (give_get_errors() || !$user) {
        if ($is_ajax) {
            do_action('give_ajax_checkout_errors');
            give_die();
        } else {
            return false;
        }
    }
    if ($is_ajax) {
        echo 'success';
        give_die();
    }
    // Setup user information
    $user_info = array('id' => $user['user_id'], 'email' => $user['user_email'], 'first_name' => $user['user_first'], 'last_name' => $user['user_last'], 'address' => $user['address']);
    $auth_key = defined('AUTH_KEY') ? AUTH_KEY : '';
    // Setup purchase information
    $purchase_data = array('price' => isset($_POST['give-amount']) ? (double) apply_filters('give_donation_total', give_sanitize_amount(give_format_amount($_POST['give-amount']))) : '0.00', 'purchase_key' => strtolower(md5($user['user_email'] . date('Y-m-d H:i:s') . $auth_key . uniqid('give', true))), 'user_email' => $user['user_email'], 'date' => date('Y-m-d H:i:s', current_time('timestamp')), 'user_info' => stripslashes_deep($user_info), 'post_data' => $_POST, 'gateway' => $valid_data['gateway'], 'card_info' => $valid_data['cc_info']);
    // Add the user data for hooks
    $valid_data['user'] = $user;
    // Allow themes and plugins to hook before the gateway
    do_action('give_checkout_before_gateway', $_POST, $user_info, $valid_data);
    // If the total amount in the cart is 0, send to the manual gateway. This emulates a free purchase
    if (!$purchase_data['price']) {
        // Revert to manual
        $purchase_data['gateway'] = 'manual';
        $_POST['give-gateway'] = 'manual';
    }
    // Allow the purchase data to be modified before it is sent to the gateway
    $purchase_data = apply_filters('give_purchase_data_before_gateway', $purchase_data, $valid_data);
    // Setup the data we're storing in the purchase session
    $session_data = $purchase_data;
    // Make sure credit card numbers are never stored in sessions
    unset($session_data['card_info']['card_number']);
    // Used for showing data to non logged-in users after purchase, and for other plugins needing purchase data.
    give_set_purchase_session($session_data);
    // Send info to the gateway for payment processing
    give_send_to_gateway($purchase_data['gateway'], $purchase_data);
    give_die();
}
/**
 * Validation donation amount. Note: Give handles validation minimum amount out-of-the-box.
 *
 * Check that a donation is above or below a maximum amount.
 *
 * @param $valid_data
 * @param $data
 */
function give_donations_validate_donation_amount($valid_data, $data)
{
    // Only validate the form with the IDs "754" and "586";
    // Remove "If" statement to validation for all forms
    // For a single form, use this instead:
    //	$forms = array( 1425 );
    //	if ( ! in_array( $data['give-form-id'], $forms ) ) {
    //		return;
    //	}
    $sanitized_amount = (int) give_sanitize_amount($data['give-amount']);
    $max_amount = 1000;
    //Check for message data
    if ($sanitized_amount >= $max_amount) {
        give_set_error('give_message', sprintf(__('Sorry, we can\'t accept donations more than %s.', 'give'), give_currency_filter(give_format_amount($max_amount))));
    }
}
Beispiel #3
0
/**
 * Displays a formatted goal for a donation form
 *
 * @since 1.0
 *
 * @param int  $form_id ID of the form price to show
 * @param bool $echo    Whether to echo or return the results
 *
 * @return void
 */
function give_goal($form_id = 0, $echo = true)
{
    if (empty($form_id)) {
        $form_id = get_the_ID();
    }
    $goal = give_get_form_goal($form_id);
    $goal = apply_filters('give_form_goal', give_sanitize_amount($goal), $form_id);
    $formatted_goal = '<span class="give_price" id="give_price_' . $form_id . '">' . $goal . '</span>';
    $formatted_goal = apply_filters('give_form_price_after_html', $formatted_goal, $form_id, $goal);
    if ($echo) {
        echo $formatted_goal;
    } else {
        return $formatted_goal;
    }
}
Beispiel #4
0
/**
 * Process PayPal Purchase.
 *
 * @since 1.0
 *
 * @param array $purchase_data Purchase Data
 *
 * @return void
 */
function give_process_paypal_purchase($purchase_data)
{
    if (!wp_verify_nonce($purchase_data['gateway_nonce'], 'give-gateway')) {
        wp_die(esc_html__('Nonce verification has failed.', 'give'), esc_html__('Error', 'give'), array('response' => 403));
    }
    $form_id = intval($purchase_data['post_data']['give-form-id']);
    $price_id = isset($purchase_data['post_data']['give-price-id']) ? $purchase_data['post_data']['give-price-id'] : '';
    // Collect payment data.
    $payment_data = array('price' => $purchase_data['price'], 'give_form_title' => $purchase_data['post_data']['give-form-title'], 'give_form_id' => $form_id, 'give_price_id' => $price_id, 'date' => $purchase_data['date'], 'user_email' => $purchase_data['user_email'], 'purchase_key' => $purchase_data['purchase_key'], 'currency' => give_get_currency(), 'user_info' => $purchase_data['user_info'], 'status' => 'pending', 'gateway' => 'paypal');
    // Record the pending payment.
    $payment_id = give_insert_payment($payment_data);
    // Check payment.
    if (!$payment_id) {
        // Record the error.
        give_record_gateway_error(esc_html__('Payment Error', 'give'), sprintf(esc_html__('Payment creation failed before sending donor to PayPal. Payment data: %s', 'give'), json_encode($payment_data)), $payment_id);
        // Problems? Send back.
        give_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['give-gateway']);
    } else {
        // Only send to PayPal if the pending payment is created successfully.
        $listener_url = add_query_arg('give-listener', 'IPN', home_url('index.php'));
        // Get the success url.
        $return_url = add_query_arg(array('payment-confirmation' => 'paypal', 'payment-id' => $payment_id), get_permalink(give_get_option('success_page')));
        // Get the PayPal redirect uri.
        $paypal_redirect = trailingslashit(give_get_paypal_redirect()) . '?';
        //Item name - pass level name if variable priced.
        $item_name = $purchase_data['post_data']['give-form-title'];
        //Verify has variable prices.
        if (give_has_variable_prices($form_id) && isset($purchase_data['post_data']['give-price-id'])) {
            $item_price_level_text = give_get_price_option_name($form_id, $purchase_data['post_data']['give-price-id']);
            $price_level_amount = give_get_price_option_amount($form_id, $purchase_data['post_data']['give-price-id']);
            //Donation given doesn't match selected level (must be a custom amount).
            if ($price_level_amount != give_sanitize_amount($purchase_data['price'])) {
                $custom_amount_text = get_post_meta($form_id, '_give_custom_amount_text', true);
                //user custom amount text if any, fallback to default if not.
                $item_name .= ' - ' . (!empty($custom_amount_text) ? $custom_amount_text : esc_html__('Custom Amount', 'give'));
            } elseif (!empty($item_price_level_text)) {
                $item_name .= ' - ' . $item_price_level_text;
            }
        } elseif (give_get_form_price($form_id) !== give_sanitize_amount($purchase_data['price'])) {
            $custom_amount_text = get_post_meta($form_id, '_give_custom_amount_text', true);
            //user custom amount text if any, fallback to default if not.
            $item_name .= ' - ' . (!empty($custom_amount_text) ? $custom_amount_text : esc_html__('Custom Amount', 'give'));
        }
        // Setup PayPal API params.
        $paypal_args = array('business' => give_get_option('paypal_email', false), 'first_name' => $purchase_data['user_info']['first_name'], 'last_name' => $purchase_data['user_info']['last_name'], 'email' => $purchase_data['user_email'], 'invoice' => $purchase_data['purchase_key'], 'amount' => $purchase_data['price'], 'item_name' => stripslashes($item_name), 'no_shipping' => '1', 'shipping' => '0', 'no_note' => '1', 'currency_code' => give_get_currency(), 'charset' => get_bloginfo('charset'), 'custom' => $payment_id, 'rm' => '2', 'return' => $return_url, 'cancel_return' => give_get_failed_transaction_uri('?payment-id=' . $payment_id), 'notify_url' => $listener_url, 'page_style' => give_get_paypal_page_style(), 'cbt' => get_bloginfo('name'), 'bn' => 'givewp_SP');
        //Add user address if present.
        if (!empty($purchase_data['user_info']['address'])) {
            $paypal_args['address1'] = isset($purchase_data['user_info']['address']['line1']) ? $purchase_data['user_info']['address']['line1'] : '';
            $paypal_args['address2'] = isset($purchase_data['user_info']['address']['line2']) ? $purchase_data['user_info']['address']['line2'] : '';
            $paypal_args['city'] = isset($purchase_data['user_info']['address']['city']) ? $purchase_data['user_info']['address']['city'] : '';
            $paypal_args['state'] = isset($purchase_data['user_info']['address']['state']) ? $purchase_data['user_info']['address']['state'] : '';
            $paypal_args['country'] = isset($purchase_data['user_info']['address']['country']) ? $purchase_data['user_info']['address']['country'] : '';
        }
        //Donations or regular transactions?
        if (give_get_option('paypal_button_type') === 'standard') {
            $paypal_extra_args = array('cmd' => '_xclick');
        } else {
            $paypal_extra_args = array('cmd' => '_donations');
        }
        $paypal_args = array_merge($paypal_extra_args, $paypal_args);
        $paypal_args = apply_filters('give_paypal_redirect_args', $paypal_args, $purchase_data);
        // Build query.
        $paypal_redirect .= http_build_query($paypal_args);
        // Fix for some sites that encode the entities.
        $paypal_redirect = str_replace('&amp;', '&', $paypal_redirect);
        // Redirect to PayPal.
        wp_redirect($paypal_redirect);
        exit;
    }
}
Beispiel #5
0
/**
 * Auto set correct donation level id on basis of amount.
 *
 * Note: If amount does not match to donation level amount then level id will be auto select to first match level id on basis of amount.
 *
 * @param array $valid_data
 * @param array $data
 *
 * @return bool
 */
function give_validate_multi_donation_form_level($valid_data, $data)
{
    /* @var Give_Donate_Form $form*/
    $form = new Give_Donate_Form($data['give-form-id']);
    $donation_level_matched = false;
    if ($form->is_multi_type_donation_form()) {
        // Bailout.
        if (!($variable_prices = $form->get_prices())) {
            return false;
        }
        // Sanitize donation amount.
        $data['give-amount'] = give_sanitize_amount($data['give-amount']);
        // Get number of decimals.
        $default_decimals = give_get_price_decimals();
        if ($data['give-amount'] === give_sanitize_amount(give_get_price_option_amount($data['give-form-id'], $data['give-price-id']), $default_decimals)) {
            return true;
        }
        // Find correct donation level from all donation levels.
        foreach ($variable_prices as $variable_price) {
            // Sanitize level amount.
            $variable_price['_give_amount'] = give_sanitize_amount($variable_price['_give_amount'], $default_decimals);
            // Set first match donation level ID.
            if ($data['give-amount'] === $variable_price['_give_amount']) {
                $_POST['give-price-id'] = $variable_price['_give_id']['level_id'];
                $donation_level_matched = true;
                break;
            }
        }
        // If donation amount is not find in donation levels then check if form has custom donation feature enable or not.
        // If yes then set price id to custom if amount is greater then custom minimum amount (if any).
        if (!$donation_level_matched && 'yes' === get_post_meta($data['give-form-id'], '_give_custom_amount', true)) {
            // Sanitize custom minimum amount.
            $custom_minimum_amount = give_sanitize_amount(get_post_meta($data['give-form-id'], '_give_custom_amount_minimum', true), $default_decimals);
            if ($data['give-amount'] >= $custom_minimum_amount) {
                $_POST['give-price-id'] = 'custom';
                $donation_level_matched = true;
            }
        }
    }
    return $donation_level_matched ? true : false;
}
Beispiel #6
0
/**
 * Get Purchase Status for User
 *
 * Retrieves the purchase count and the total amount spent for a specific user
 *
 * @access      public
 * @since       1.0
 *
 * @param       $user int|string - the ID or email of the donor to retrieve stats for
 *
 * @return      array
 */
function give_get_purchase_stats_by_user($user = '')
{
    if (is_email($user)) {
        $field = 'email';
    } elseif (is_numeric($user)) {
        $field = 'user_id';
    }
    $stats = array();
    $customer = Give()->customers->get_customer_by($field, $user);
    if ($customer) {
        $customer = new Give_Customer($customer->id);
        $stats['purchases'] = absint($customer->purchase_count);
        $stats['total_spent'] = give_sanitize_amount($customer->purchase_value);
    }
    return (array) apply_filters('give_purchase_stats_by_user', $stats, $user);
}
Beispiel #7
0
/**
 * Get Price ID
 *
 * Retrieves the Price ID when provided a proper form ID and price (donation) total
 *
 * @param $form_id
 * @param $price
 *
 * @return string $price_id
 */
function give_get_price_id($form_id, $price)
{
    $price_id = 0;
    if (give_has_variable_prices($form_id)) {
        $levels = maybe_unserialize(get_post_meta($form_id, '_give_donation_levels', true));
        foreach ($levels as $level) {
            $level_amount = (double) give_sanitize_amount($level['_give_amount']);
            //check that this indeed the recurring price
            if ($level_amount == $price) {
                $price_id = $level['_give_id']['level_id'];
            }
        }
    }
    return $price_id;
}
Beispiel #8
0
/**
 * Donation Form Validate Minimum Donation Amount
 *
 * @access      private
 * @since       1.3.6
 * @return      bool
 */
function give_verify_minimum_price()
{
    $amount = give_sanitize_amount($_REQUEST['give-amount']);
    $form_id = $_REQUEST['give-form-id'];
    $price_id = isset($_REQUEST['give-price-id']) ? $_REQUEST['give-price-id'] : 0;
    $variable_prices = give_has_variable_prices($form_id);
    if ($variable_prices && !empty($price_id)) {
        $price_level_amount = give_get_price_option_amount($form_id, $price_id);
        if ($price_level_amount == $amount) {
            return true;
        }
    }
    $minimum = give_get_form_minimum_price($form_id);
    if ($minimum > $amount) {
        return false;
    }
    return true;
}
 /**
  * Add a donation to a given payment
  *
  * @since  1.5
  * @access public
  *
  * @param  int   $form_id The donation form to add
  * @param  array $args Other arguments to pass to the function
  * @param  array $options List of donation options
  *
  * @return bool           True when successful, false otherwise
  */
 public function add_donation($form_id = 0, $args = array(), $options = array())
 {
     $donation = new Give_Donate_Form($form_id);
     // Bail if this post isn't a give donation form
     if (!$donation || $donation->post_type !== 'give_forms') {
         return false;
     }
     // Set some defaults
     $defaults = array('price' => false, 'price_id' => false, 'fees' => array());
     $args = wp_parse_args(apply_filters('give_payment_add_donation_args', $args, $donation->ID), $defaults);
     // Allow overriding the price
     if (false !== $args['price']) {
         $item_price = $args['price'];
     } else {
         // Deal with variable pricing
         if (give_has_variable_prices($donation->ID)) {
             $prices = maybe_unserialize(get_post_meta($form_id, '_give_donation_levels', true));
             $item_price = '';
             //Loop through prices
             foreach ($prices as $price) {
                 //Find a match between price_id and level_id
                 //First verify array keys exists THEN make the match
                 if (isset($args['price_id']) && isset($price['_give_id']['level_id']) && $args['price_id'] == $price['_give_id']['level_id']) {
                     $item_price = $price['_give_amount'];
                 }
             }
             //Fallback to the lowest price point
             if ($item_price == '') {
                 $item_price = give_get_lowest_price_option($donation->ID);
                 $args['price_id'] = give_get_lowest_price_id($donation->ID);
             }
         } else {
             //Simple form price
             $item_price = give_get_form_price($donation->ID);
         }
     }
     // Sanitizing the price here so we don't have a dozen calls later
     $item_price = give_sanitize_amount($item_price);
     $total = round($item_price, give_currency_decimal_filter());
     //Add Options
     $default_options = array();
     if (false !== $args['price_id']) {
         $default_options['price_id'] = (int) $args['price_id'];
     }
     $options = wp_parse_args($options, $default_options);
     // Do not allow totals to go negative
     if ($total < 0) {
         $total = 0;
     }
     $donation = array('name' => $donation->post_title, 'id' => $donation->ID, 'price' => round($total, give_currency_decimal_filter()), 'subtotal' => round($total, give_currency_decimal_filter()), 'fees' => $args['fees'], 'price_id' => $args['price_id'], 'action' => 'add', 'options' => $options);
     $this->pending['donations'][] = $donation;
     $this->increase_subtotal($total);
     return true;
 }
Beispiel #10
0
/**
 * Process bulk edit actions via AJAX
 *
 * @since 1.0
 * @return void
 */
function give_save_bulk_edit()
{
    $post_ids = isset($_POST['post_ids']) && !empty($_POST['post_ids']) ? $_POST['post_ids'] : array();
    if (!empty($post_ids) && is_array($post_ids)) {
        $price = isset($_POST['price']) ? strip_tags(stripslashes($_POST['price'])) : 0;
        foreach ($post_ids as $post_id) {
            if (!current_user_can('edit_post', $post_id)) {
                continue;
            }
            if (!empty($price)) {
                update_post_meta($post_id, '_give_set_price', give_sanitize_amount($price));
            }
        }
    }
    die;
}
 /**
  * Retrieve the goal
  *
  * @since  1.0
  * @access public
  *
  * @return float  Goal.
  */
 public function get_goal()
 {
     if (!isset($this->goal)) {
         $this->goal = get_post_meta($this->ID, '_give_set_goal', true);
         if ($this->goal) {
             $this->goal = give_sanitize_amount($this->goal);
         } else {
             $this->goal = 0;
         }
     }
     return apply_filters('give_get_set_goal', $this->goal, $this->ID);
 }
Beispiel #12
0
/**
 *
 * Process the payment details edit
 *
 * @access      private
 *
 * @param $data
 *
 * @since       1.0
 * @return      void
 *
 */
function give_update_payment_details($data)
{
    if (!current_user_can('edit_give_payments', $data['give_payment_id'])) {
        wp_die(__('You do not have permission to edit this payment record', 'give'), __('Error', 'give'), array('response' => 403));
    }
    check_admin_referer('give_update_payment_details_nonce');
    // Retrieve the payment ID
    $payment_id = absint($data['give_payment_id']);
    // Retrieve existing payment meta
    $meta = give_get_payment_meta($payment_id);
    $user_info = give_get_payment_meta_user_info($payment_id);
    $status = $data['give-payment-status'];
    $user_id = isset($data['give-payment-user-id']) ? intval($data['give-payment-user-id']) : '';
    $date = sanitize_text_field($data['give-payment-date']);
    $hour = sanitize_text_field($data['give-payment-time-hour']);
    $form_id = give_get_payment_form_id($payment_id);
    // Restrict to our high and low
    if ($hour > 23) {
        $hour = 23;
    } elseif ($hour < 0) {
        $hour = 00;
    }
    $minute = sanitize_text_field($data['give-payment-time-min']);
    // Restrict to our high and low
    if ($minute > 59) {
        $minute = 59;
    } elseif ($minute < 0) {
        $minute = 00;
    }
    $address = array_map('trim', $data['give-payment-address'][0]);
    $date = date('Y-m-d', strtotime($date)) . ' ' . $hour . ':' . $minute . ':00';
    $curr_total = give_sanitize_amount(give_get_payment_amount($payment_id));
    $new_total = give_sanitize_amount($_POST['give-payment-total']);
    $curr_customer_id = sanitize_text_field($data['give-current-customer']);
    $new_customer_id = sanitize_text_field($data['customer-id']);
    do_action('give_update_edited_purchase', $payment_id);
    // Update main payment record
    $updated = wp_update_post(array('ID' => $payment_id, 'edit_date' => true, 'post_date' => $date));
    if (0 === $updated) {
        wp_die(esc_attr__('Error Updating Payment', 'give'), esc_attr__('Error', 'give'), array('response' => 400));
    }
    $customer_changed = false;
    if (isset($data['give-new-customer']) && $data['give-new-customer'] == '1') {
        $email = isset($data['give-new-customer-email']) ? sanitize_text_field($data['give-new-customer-email']) : '';
        $names = isset($data['give-new-customer-name']) ? sanitize_text_field($data['give-new-customer-name']) : '';
        if (empty($email) || empty($names)) {
            wp_die(esc_attr__('New Customers require a name and email address', 'give'));
        }
        $customer = new Give_Customer($email);
        if (empty($customer->id)) {
            $customer_data = array('name' => $names, 'email' => $email);
            $user_id = email_exists($email);
            if (false !== $user_id) {
                $customer_data['user_id'] = $user_id;
            }
            if (!$customer->create($customer_data)) {
                // Failed to crete the new customer, assume the previous customer
                $customer_changed = false;
                $customer = new Give_Customer($curr_customer_id);
                give_set_error('give-payment-new-customer-fail', __('Error creating new customer', 'give'));
            }
        }
        $new_customer_id = $customer->id;
        $previous_customer = new Give_Customer($curr_customer_id);
        $customer_changed = true;
    } elseif ($curr_customer_id !== $new_customer_id) {
        $customer = new Give_Customer($new_customer_id);
        $email = $customer->email;
        $names = $customer->name;
        $previous_customer = new Give_Customer($curr_customer_id);
        $customer_changed = true;
    } else {
        $customer = new Give_Customer($curr_customer_id);
        $email = $customer->email;
        $names = $customer->name;
    }
    // Setup first and last name from input values
    $names = explode(' ', $names);
    $first_name = !empty($names[0]) ? $names[0] : '';
    $last_name = '';
    if (!empty($names[1])) {
        unset($names[0]);
        $last_name = implode(' ', $names);
    }
    if ($customer_changed) {
        // Remove the stats and payment from the previous customer and attach it to the new customer
        $previous_customer->remove_payment($payment_id, false);
        $customer->attach_payment($payment_id, false);
        // If purchase was completed and not ever refunded, adjust stats of customers
        if ('revoked' == $status || 'publish' == $status) {
            $previous_customer->decrease_purchase_count();
            $previous_customer->decrease_value($new_total);
            $customer->increase_purchase_count();
            $customer->increase_value($new_total);
        }
        update_post_meta($payment_id, '_give_payment_customer_id', $customer->id);
    }
    // Set new meta values
    $user_info['id'] = $customer->user_id;
    $user_info['email'] = $customer->email;
    $user_info['first_name'] = $first_name;
    $user_info['last_name'] = $last_name;
    $user_info['address'] = $address;
    $meta['user_info'] = $user_info;
    // Check for payment notes
    if (!empty($data['give-payment-note'])) {
        $note = wp_kses($data['give-payment-note'], array());
        give_insert_payment_note($payment_id, $note);
    }
    // Set new status
    give_update_payment_status($payment_id, $status);
    give_update_payment_meta($payment_id, '_give_payment_user_id', $customer->user_id);
    give_update_payment_meta($payment_id, '_give_payment_user_email', $customer->email);
    give_update_payment_meta($payment_id, '_give_payment_meta', $meta);
    give_update_payment_meta($payment_id, '_give_payment_total', $new_total);
    // Adjust total store earnings if the payment total has been changed
    if ($new_total !== $curr_total && ('publish' == $status || 'revoked' == $status)) {
        if ($new_total > $curr_total) {
            // Increase if our new total is higher
            $difference = $new_total - $curr_total;
            give_increase_total_earnings($difference);
            $form = new Give_Donate_Form($form_id);
            $form->increase_earnings($difference);
        } elseif ($curr_total > $new_total) {
            // Decrease if our new total is lower
            $difference = $curr_total - $new_total;
            give_decrease_total_earnings($difference);
            $form = new Give_Donate_Form($form_id);
            $form->decrease_earnings($difference);
        }
    }
    do_action('give_updated_edited_purchase', $payment_id);
    wp_safe_redirect(admin_url('edit.php?post_type=give_forms&page=give-payment-history&view=view-order-details&give-message=payment-updated&id=' . $payment_id));
    exit;
}
Beispiel #13
0
/**
 *
 * Process the payment details edit
 *
 * @access      private
 *
 * @param array $data
 *
 * @since       1.0
 * @return      void
 *
 */
function give_update_payment_details($data)
{
    if (!current_user_can('edit_give_payments', $data['give_payment_id'])) {
        wp_die(esc_html__('You do not have permission to edit payment records.', 'give'), esc_html__('Error', 'give'), array('response' => 403));
    }
    check_admin_referer('give_update_payment_details_nonce');
    // Retrieve the payment ID
    $payment_id = absint($data['give_payment_id']);
    /* @var Give_Payment $payment */
    $payment = new Give_Payment($payment_id);
    // Retrieve existing payment meta
    $meta = $payment->get_meta();
    $user_info = $payment->user_info;
    $status = $data['give-payment-status'];
    $date = sanitize_text_field($data['give-payment-date']);
    $hour = sanitize_text_field($data['give-payment-time-hour']);
    // Restrict to our high and low
    if ($hour > 23) {
        $hour = 23;
    } elseif ($hour < 0) {
        $hour = 00;
    }
    $minute = sanitize_text_field($data['give-payment-time-min']);
    // Restrict to our high and low
    if ($minute > 59) {
        $minute = 59;
    } elseif ($minute < 0) {
        $minute = 00;
    }
    $address = array_map('trim', $data['give-payment-address'][0]);
    $curr_total = give_sanitize_amount($payment->total);
    $new_total = give_sanitize_amount($data['give-payment-total']);
    $date = date('Y-m-d', strtotime($date)) . ' ' . $hour . ':' . $minute . ':00';
    $curr_customer_id = sanitize_text_field($data['give-current-customer']);
    $new_customer_id = sanitize_text_field($data['customer-id']);
    /**
     * Fires before updating edited purchase.
     *
     * @since 1.0
     *
     * @param int $payment_id The ID of the payment.
     */
    do_action('give_update_edited_purchase', $payment_id);
    $payment->date = $date;
    $updated = $payment->save();
    if (0 === $updated) {
        wp_die(esc_html__('Error Updating Payment.', 'give'), esc_html__('Error', 'give'), array('response' => 400));
    }
    $customer_changed = false;
    if (isset($data['give-new-customer']) && $data['give-new-customer'] == '1') {
        $email = isset($data['give-new-customer-email']) ? sanitize_text_field($data['give-new-customer-email']) : '';
        $names = isset($data['give-new-customer-name']) ? sanitize_text_field($data['give-new-customer-name']) : '';
        if (empty($email) || empty($names)) {
            wp_die(esc_html__('New Customers require a name and email address.', 'give'), esc_html__('Error', 'give'), array('response' => 400));
        }
        $customer = new Give_Customer($email);
        if (empty($customer->id)) {
            $customer_data = array('name' => $names, 'email' => $email);
            $user_id = email_exists($email);
            if (false !== $user_id) {
                $customer_data['user_id'] = $user_id;
            }
            if (!$customer->create($customer_data)) {
                // Failed to crete the new donor, assume the previous donor
                $customer_changed = false;
                $customer = new Give_Customer($curr_customer_id);
                give_set_error('give-payment-new-customer-fail', esc_html__('Error creating new donor.', 'give'));
            }
        }
        $new_customer_id = $customer->id;
        $previous_customer = new Give_Customer($curr_customer_id);
        $customer_changed = true;
    } elseif ($curr_customer_id !== $new_customer_id) {
        $customer = new Give_Customer($new_customer_id);
        $email = $customer->email;
        $names = $customer->name;
        $previous_customer = new Give_Customer($curr_customer_id);
        $customer_changed = true;
    } else {
        $customer = new Give_Customer($curr_customer_id);
        $email = $customer->email;
        $names = $customer->name;
    }
    // Setup first and last name from input values
    $names = explode(' ', $names);
    $first_name = !empty($names[0]) ? $names[0] : '';
    $last_name = '';
    if (!empty($names[1])) {
        unset($names[0]);
        $last_name = implode(' ', $names);
    }
    if ($customer_changed) {
        // Remove the stats and payment from the previous customer and attach it to the new customer
        $previous_customer->remove_payment($payment_id, false);
        $customer->attach_payment($payment_id, false);
        if ('publish' == $status) {
            // Reduce previous user donation count and amount.
            $previous_customer->decrease_purchase_count();
            $previous_customer->decrease_value($curr_total);
            // If purchase was completed adjust stats of new customers.
            $customer->increase_purchase_count();
            $customer->increase_value($new_total);
        }
        $payment->customer_id = $customer->id;
    } else {
        if ('publish' === $status) {
            // Update user donation stat.
            $customer->update_donation_value($curr_total, $new_total);
        }
    }
    // Set new meta values
    $payment->user_id = $customer->user_id;
    $payment->email = $customer->email;
    $payment->first_name = $first_name;
    $payment->last_name = $last_name;
    $payment->address = $address;
    $payment->total = $new_total;
    // Check for payment notes
    if (!empty($data['give-payment-note'])) {
        $note = wp_kses($data['give-payment-note'], array());
        give_insert_payment_note($payment_id, $note);
    }
    // Set new status
    $payment->status = $status;
    // Adjust total store earnings if the payment total has been changed
    if ($new_total !== $curr_total && 'publish' == $status) {
        if ($new_total > $curr_total) {
            // Increase if our new total is higher
            $difference = $new_total - $curr_total;
            give_increase_total_earnings($difference);
        } elseif ($curr_total > $new_total) {
            // Decrease if our new total is lower
            $difference = $curr_total - $new_total;
            give_decrease_total_earnings($difference);
        }
    }
    $payment->save();
    // Get new give form ID.
    $new_form_id = absint($data['forms']);
    $current_form_id = absint($payment->get_meta('_give_payment_form_id'));
    // We are adding payment transfer code in last to remove any conflict with above functionality.
    // For example: above code will automatically handle form stat (increase/decrease) when payment status changes.
    /* Check if user want to transfer current payment to new give form id. */
    if ($new_form_id != $current_form_id) {
        // Get new give form title.
        $new_form_title = get_the_title($new_form_id);
        // Update new give form data in payment data.
        $payment_meta = $payment->get_meta();
        $payment_meta['form_title'] = $new_form_title;
        $payment_meta['form_id'] = $new_form_id;
        // Update price id post meta data for set donation form.
        if (!give_has_variable_prices($new_form_id)) {
            $payment_meta['price_id'] = '';
        }
        // Update payment give form meta data.
        $payment->update_meta('_give_payment_form_id', $new_form_id);
        $payment->update_meta('_give_payment_form_title', $new_form_title);
        $payment->update_meta('_give_payment_meta', $payment_meta);
        // Update price id payment metadata.
        if (!give_has_variable_prices($new_form_id)) {
            $payment->update_meta('_give_payment_price_id', '');
        }
        // If purchase was completed, adjust stats of forms
        if ('publish' == $status) {
            // Decrease sale of old give form. For other payment status
            $current_form = new Give_Donate_Form($current_form_id);
            $current_form->decrease_sales();
            $current_form->decrease_earnings($curr_total);
            // Increase sale of new give form.
            $new_form = new Give_Donate_Form($new_form_id);
            $new_form->increase_sales();
            $new_form->increase_earnings($new_total);
        }
        // Re setup payment to update new meta value in object.
        $payment->update_payment_setup($payment->ID);
    }
    // Update price id if current form is variable form.
    if (!empty($data['give-variable-price']) && give_has_variable_prices($payment->form_id)) {
        // Get payment meta data.
        $payment_meta = $payment->get_meta();
        // Set payment id to empty string if variable price id is negative ( i.e. custom amount feature enabled ).
        $data['give-variable-price'] = 'custom' === $data['give-variable-price'] ? 'custom' : 0 < $data['give-variable-price'] ? $data['give-variable-price'] : '';
        // Update payment meta data.
        $payment_meta['price_id'] = $data['give-variable-price'];
        // Update payment give form meta data.
        $payment->update_meta('_give_payment_price_id', $data['give-variable-price']);
        $payment->update_meta('_give_payment_meta', $payment_meta);
        // Re setup payment to update new meta value in object.
        $payment->update_payment_setup($payment->ID);
    }
    /**
     * Fires after updating edited purchase.
     *
     * @since 1.0
     *
     * @param int $payment_id The ID of the payment.
     */
    do_action('give_updated_edited_purchase', $payment_id);
    wp_safe_redirect(admin_url('edit.php?post_type=give_forms&page=give-payment-history&view=view-order-details&give-message=payment-updated&id=' . $payment_id));
    exit;
}
Beispiel #14
0
/**
 * Sanitize price file value
 *
 * @since 1.6
 *
 * @param string $value
 * @param array  $field_args
 * @param object $field
 *
 * @return mixed
 */
function give_sanitize_price_field_value($value, $field_args, $field)
{
    return give_sanitize_amount($value);
}