/**
  * Get the Export Data
  *
  * @access public
  * @since 2.5
  * @global object $wpdb Used to query the database using the WordPress
  *   Database API
  * @return array $data The data for the CSV file
  */
 public function get_data()
 {
     $args = array('number' => $this->per_step, 'offset' => $this->per_step * ($this->step - 1), 'orderby' => 'id', 'order' => 'DESC');
     $customers = EDD()->customers->get_customers($args);
     if ($customers) {
         foreach ($customers as $customer) {
             $attached_payment_ids = explode(',', $customer->payment_ids);
             $attached_args = array('post__in' => $attached_payment_ids, 'number' => -1);
             $attached_payments = edd_get_payments($attached_args);
             $unattached_args = array('post__not_in' => $attached_payment_ids, 'number' => -1, 'meta_query' => array(array('key' => '_edd_payment_user_email', 'value' => $customer->email, 'compare' => '=')));
             $unattached_payments = edd_get_payments($unattached_args);
             $payments = array_merge($attached_payments, $unattached_payments);
             $purchase_value = 0.0;
             $purchase_count = 0;
             $payment_ids = array();
             if ($payments) {
                 foreach ($payments as $payment) {
                     if ('publish' == $payment->post_status || 'revoked' == $payment->post_status) {
                         $purchase_value += edd_get_payment_amount($payment->ID);
                         $purchase_count++;
                     }
                     $payment_ids[] = $payment->ID;
                 }
             }
             $payment_ids = implode(',', $payment_ids);
             $customer_update_data = array('purchase_count' => $purchase_count, 'purchase_value' => $purchase_value, 'payment_ids' => $payment_ids);
             $customer_instance = new EDD_Customer($customer->id);
             $customer_instance->update($customer_update_data);
         }
         return true;
     }
     return false;
 }
 /**
  * Withdraw funds from wallet
  *
  * @access		public
  * @since		1.0.1
  * @param		mixed $user The user ID or email
  * @param		float $amount The amount to withdraw
  * @param		string $type The type of deposit
  * @param		int $payment_id The ID of a given payment
  * @return		mixed
  */
 public function withdraw($user, $amount, $type = 'withdrawal', $payment_id = 0)
 {
     if (is_email($user) || strpos($user, '@') !== false) {
         $user = get_user_by('email', $user);
         $user = $user->ID;
     }
     $value = $this->balance($user);
     $value -= $amount;
     // Update the user wallet
     update_user_meta($user, '_edd_wallet_value', $value);
     // Record the deposit
     $args = array('user_id' => $user, 'payment_id' => $payment_id, 'type' => $type, 'amount' => $amount);
     $item = edd_wallet()->db->add($args);
     // Override customer value increase
     $customer = new EDD_Customer($user);
     $customer->decrease_value($amount);
     do_action('edd_wallet_withdraw', $args);
     return $item;
 }
Example #3
0
/**
 * Complete a purchase
 *
 * Performs all necessary actions to complete a purchase.
 * Triggered by the edd_update_payment_status() function.
 *
 * @since 1.0.8.3
 * @param int $payment_id the ID number of the payment
 * @param string $new_status the status of the payment, probably "publish"
 * @param string $old_status the status of the payment prior to being marked as "complete", probably "pending"
 * @return void
*/
function edd_complete_purchase($payment_id, $new_status, $old_status)
{
    if ($old_status == 'publish' || $old_status == 'complete') {
        return;
        // Make sure that payments are only completed once
    }
    // Make sure the payment completion is only processed when new status is complete
    if ($new_status != 'publish' && $new_status != 'complete') {
        return;
    }
    $payment = new EDD_Payment($payment_id);
    $creation_date = get_post_field('post_date', $payment_id, 'raw');
    $completed_date = $payment->completed_date;
    $user_info = $payment->user_info;
    $customer_id = $payment->customer_id;
    $amount = $payment->total;
    $cart_details = $payment->cart_details;
    do_action('edd_pre_complete_purchase', $payment_id);
    if (is_array($cart_details)) {
        // Increase purchase count and earnings
        foreach ($cart_details as $cart_index => $download) {
            // "bundle" or "default"
            $download_type = edd_get_download_type($download['id']);
            $price_id = isset($download['item_number']['options']['price_id']) ? (int) $download['item_number']['options']['price_id'] : false;
            // Increase earnings and fire actions once per quantity number
            for ($i = 0; $i < $download['quantity']; $i++) {
                // Ensure these actions only run once, ever
                if (empty($completed_date)) {
                    edd_record_sale_in_log($download['id'], $payment_id, $price_id, $creation_date);
                    do_action('edd_complete_download_purchase', $download['id'], $payment_id, $download_type, $download, $cart_index);
                }
            }
            // Increase the earnings for this download ID
            edd_increase_earnings($download['id'], $download['price']);
            edd_increase_purchase_count($download['id'], $download['quantity']);
        }
        // Clear the total earnings cache
        delete_transient('edd_earnings_total');
        // Clear the This Month earnings (this_monththis_month is NOT a typo)
        delete_transient(md5('edd_earnings_this_monththis_month'));
        delete_transient(md5('edd_earnings_todaytoday'));
    }
    // Increase the customer's purchase stats
    $customer = new EDD_Customer($customer_id);
    $customer->increase_purchase_count();
    $customer->increase_value($amount);
    edd_increase_total_earnings($amount);
    // Check for discount codes and increment their use counts
    if (!empty($user_info['discount']) && $user_info['discount'] !== 'none') {
        $discounts = array_map('trim', explode(',', $user_info['discount']));
        if (!empty($discounts)) {
            foreach ($discounts as $code) {
                edd_increase_discount_usage($code);
            }
        }
    }
    // Ensure this action only runs once ever
    if (empty($completed_date)) {
        // Save the completed date
        $payment->completed_date = current_time('mysql');
        $payment->save();
        do_action('edd_complete_purchase', $payment_id);
    }
    // Empty the shopping cart
    edd_empty_cart();
}
/**
 * Disconnect a user ID from a customer
 *
 * @since  2.3
 * @param  array $args Array of arguements
 * @return bool        If the disconnect was sucessful
 */
function edd_disconnect_customer_user_id($args)
{
    $customer_edit_role = apply_filters('edd_edit_customers_role', 'edit_shop_payments');
    if (!is_admin() || !current_user_can($customer_edit_role)) {
        wp_die(__('You do not have permission to edit this customer.', 'edd'));
    }
    if (empty($args)) {
        return;
    }
    $customer_id = (int) $args['customer_id'];
    $nonce = $args['_wpnonce'];
    if (!wp_verify_nonce($nonce, 'edit-customer')) {
        wp_die(__('Cheatin\' eh?!', 'edd'));
    }
    $customer = new EDD_Customer($customer_id);
    if (empty($customer->id)) {
        return false;
    }
    do_action('edd_pre_customer_disconnect_user_id', $customer_id, $customer->user_id);
    $customer_args = array('user_id' => 0);
    if ($customer->update($customer_args)) {
        global $wpdb;
        if (!empty($customer->payment_ids)) {
            $wpdb->query("UPDATE {$wpdb->postmeta} SET meta_value = 0 WHERE meta_key = '_edd_payment_user_id' AND post_id IN ( {$customer->payment_ids} )");
        }
        $output['success'] = true;
    } else {
        $output['success'] = false;
        edd_set_error('edd-disconnect-user-fail', __('Failed to disconnect user from customer', 'edd'));
    }
    do_action('edd_post_customer_disconnect_user_id', $customer_id);
    if (defined('DOING_AJAX') && DOING_AJAX) {
        header('Content-Type: application/json');
        echo json_encode($output);
        wp_die();
    }
    return $output;
}
/**
 * Process web accept (one time) payment IPNs
 *
 * @since 1.3.4
 * @param array   $data IPN Data
 * @return void
 */
function edd_process_paypal_web_accept_and_cart($data, $payment_id)
{
    if ($data['txn_type'] != 'web_accept' && $data['txn_type'] != 'cart' && $data['payment_status'] != 'Refunded') {
        return;
    }
    if (empty($payment_id)) {
        return;
    }
    $payment = new EDD_Payment($payment_id);
    // Collect payment details
    $purchase_key = isset($data['invoice']) ? $data['invoice'] : $data['item_number'];
    $paypal_amount = $data['mc_gross'];
    $payment_status = strtolower($data['payment_status']);
    $currency_code = strtolower($data['mc_currency']);
    $business_email = isset($data['business']) && is_email($data['business']) ? trim($data['business']) : trim($data['receiver_email']);
    if ($payment->gateway != 'paypal') {
        return;
        // this isn't a PayPal standard IPN
    }
    // Verify payment recipient
    if (strcasecmp($business_email, trim(edd_get_option('paypal_email', false))) != 0) {
        edd_record_gateway_error(__('IPN Error', 'easy-digital-downloads'), sprintf(__('Invalid business email in IPN response. IPN data: %s', 'easy-digital-downloads'), json_encode($data)), $payment_id);
        edd_update_payment_status($payment_id, 'failed');
        edd_insert_payment_note($payment_id, __('Payment failed due to invalid PayPal business email.', 'easy-digital-downloads'));
        return;
    }
    // Verify payment currency
    if ($currency_code != strtolower($payment->currency)) {
        edd_record_gateway_error(__('IPN Error', 'easy-digital-downloads'), sprintf(__('Invalid currency in IPN response. IPN data: %s', 'easy-digital-downloads'), json_encode($data)), $payment_id);
        edd_update_payment_status($payment_id, 'failed');
        edd_insert_payment_note($payment_id, __('Payment failed due to invalid currency in PayPal IPN.', 'easy-digital-downloads'));
        return;
    }
    if (empty($payment->email)) {
        // This runs when a Buy Now purchase was made. It bypasses checkout so no personal info is collected until PayPal
        // Setup and store the customers's details
        $address = array();
        $address['line1'] = !empty($data['address_street']) ? sanitize_text_field($data['address_street']) : false;
        $address['city'] = !empty($data['address_city']) ? sanitize_text_field($data['address_city']) : false;
        $address['state'] = !empty($data['address_state']) ? sanitize_text_field($data['address_state']) : false;
        $address['country'] = !empty($data['address_country_code']) ? sanitize_text_field($data['address_country_code']) : false;
        $address['zip'] = !empty($data['address_zip']) ? sanitize_text_field($data['address_zip']) : false;
        $payment->email = sanitize_text_field($data['payer_email']);
        $payment->first_name = sanitize_text_field($data['first_name']);
        $payment->last_name = sanitize_text_field($data['last_name']);
        $payment->address = $address;
        if (empty($payment->customer_id)) {
            $customer = new EDD_Customer($payment->email);
            if (!$customer || $customer->id < 1) {
                $customer->create(array('email' => $payment->email, 'name' => $payment->first_name . ' ' . $payment->last_name, 'user_id' => $payment->user_id));
            }
            $payment->customer_id = $customer->id;
        }
        $payment->save();
    }
    if ($payment_status == 'refunded' || $payment_status == 'reversed') {
        // Process a refund
        edd_process_paypal_refund($data, $payment_id);
    } else {
        if (get_post_status($payment_id) == 'publish') {
            return;
            // Only complete payments once
        }
        // Retrieve the total purchase amount (before PayPal)
        $payment_amount = edd_get_payment_amount($payment_id);
        if (number_format((double) $paypal_amount, 2) < number_format((double) $payment_amount, 2)) {
            // The prices don't match
            edd_record_gateway_error(__('IPN Error', 'easy-digital-downloads'), sprintf(__('Invalid payment amount in IPN response. IPN data: %s', 'easy-digital-downloads'), json_encode($data)), $payment_id);
            edd_update_payment_status($payment_id, 'failed');
            edd_insert_payment_note($payment_id, __('Payment failed due to invalid amount in PayPal IPN.', 'easy-digital-downloads'));
            return;
        }
        if ($purchase_key != edd_get_payment_key($payment_id)) {
            // Purchase keys don't match
            edd_record_gateway_error(__('IPN Error', 'easy-digital-downloads'), sprintf(__('Invalid purchase key in IPN response. IPN data: %s', 'easy-digital-downloads'), json_encode($data)), $payment_id);
            edd_update_payment_status($payment_id, 'failed');
            edd_insert_payment_note($payment_id, __('Payment failed due to invalid purchase key in PayPal IPN.', 'easy-digital-downloads'));
            return;
        }
        if ('completed' == $payment_status || edd_is_test_mode()) {
            edd_insert_payment_note($payment_id, sprintf(__('PayPal Transaction ID: %s', 'easy-digital-downloads'), $data['txn_id']));
            edd_set_payment_transaction_id($payment_id, $data['txn_id']);
            edd_update_payment_status($payment_id, 'publish');
        } else {
            if ('pending' == $payment_status && isset($data['pending_reason'])) {
                // Look for possible pending reasons, such as an echeck
                $note = '';
                switch (strtolower($data['pending_reason'])) {
                    case 'echeck':
                        $note = __('Payment made via eCheck and will clear automatically in 5-8 days', 'easy-digital-downloads');
                        break;
                    case 'address':
                        $note = __('Payment requires a confirmed customer address and must be accepted manually through PayPal', 'easy-digital-downloads');
                        break;
                    case 'intl':
                        $note = __('Payment must be accepted manually through PayPal due to international account regulations', 'easy-digital-downloads');
                        break;
                    case 'multi-currency':
                        $note = __('Payment received in non-shop currency and must be accepted manually through PayPal', 'easy-digital-downloads');
                        break;
                    case 'paymentreview':
                    case 'regulatory_review':
                        $note = __('Payment is being reviewed by PayPal staff as high-risk or in possible violation of government regulations', 'easy-digital-downloads');
                        break;
                    case 'unilateral':
                        $note = __('Payment was sent to non-confirmed or non-registered email address.', 'easy-digital-downloads');
                        break;
                    case 'upgrade':
                        $note = __('PayPal account must be upgraded before this payment can be accepted', 'easy-digital-downloads');
                        break;
                    case 'verify':
                        $note = __('PayPal account is not verified. Verify account in order to accept this payment', 'easy-digital-downloads');
                        break;
                    case 'other':
                        $note = __('Payment is pending for unknown reasons. Contact PayPal support for assistance', 'easy-digital-downloads');
                        break;
                }
                if (!empty($note)) {
                    edd_insert_payment_note($payment_id, $note);
                }
            }
        }
    }
}
/**
 * Process the payment details edit
 *
 * @access      private
 * @since       1.9
 * @return      void
*/
function edd_update_payment_details($data)
{
    if (!current_user_can('edit_shop_payments', $data['edd_payment_id'])) {
        wp_die(__('You do not have permission to edit this payment record', 'easy-digital-downloads'), __('Error', 'easy-digital-downloads'), array('response' => 403));
    }
    check_admin_referer('edd_update_payment_details_nonce');
    // Retrieve the payment ID
    $payment_id = absint($data['edd_payment_id']);
    $payment = new EDD_Payment($payment_id);
    // Retrieve existing payment meta
    $meta = $payment->get_meta();
    $user_info = $payment->user_info;
    $status = $data['edd-payment-status'];
    $unlimited = isset($data['edd-unlimited-downloads']) ? '1' : '';
    $date = sanitize_text_field($data['edd-payment-date']);
    $hour = sanitize_text_field($data['edd-payment-time-hour']);
    // Restrict to our high and low
    if ($hour > 23) {
        $hour = 23;
    } elseif ($hour < 0) {
        $hour = 00;
    }
    $minute = sanitize_text_field($data['edd-payment-time-min']);
    // Restrict to our high and low
    if ($minute > 59) {
        $minute = 59;
    } elseif ($minute < 0) {
        $minute = 00;
    }
    $address = array_map('trim', $data['edd-payment-address'][0]);
    $curr_total = edd_sanitize_amount($payment->total);
    $new_total = edd_sanitize_amount($_POST['edd-payment-total']);
    $tax = isset($_POST['edd-payment-tax']) ? edd_sanitize_amount($_POST['edd-payment-tax']) : 0;
    $date = date('Y-m-d', strtotime($date)) . ' ' . $hour . ':' . $minute . ':00';
    $curr_customer_id = sanitize_text_field($data['edd-current-customer']);
    $new_customer_id = sanitize_text_field($data['customer-id']);
    // Setup purchased Downloads and price options
    $updated_downloads = isset($_POST['edd-payment-details-downloads']) ? $_POST['edd-payment-details-downloads'] : false;
    if ($updated_downloads && !empty($_POST['edd-payment-downloads-changed'])) {
        foreach ($updated_downloads as $download) {
            // If this item doesn't have a log yet, add one for each quantity count
            $has_log = absint($download['has_log']);
            $has_log = empty($has_log) ? false : true;
            if ($has_log) {
                continue;
            }
            if (empty($download['item_price'])) {
                $download['item_price'] = 0.0;
            }
            $item_price = $download['item_price'];
            $download_id = absint($download['id']);
            $quantity = absint($download['quantity']) > 0 ? absint($download['quantity']) : 1;
            $price_id = false;
            if (edd_has_variable_prices($download_id) && isset($download['price_id'])) {
                $price_id = absint($download['price_id']);
            }
            // Set some defaults
            $args = array('quantity' => $quantity, 'item_price' => $item_price, 'price_id' => $price_id);
            $payment->add_download($download_id, $args);
        }
        $deleted_downloads = json_decode(stripcslashes($data['edd-payment-removed']), true);
        foreach ($deleted_downloads as $deleted_download) {
            $deleted_download = $deleted_download[0];
            if (empty($deleted_download['id'])) {
                continue;
            }
            $price_id = empty($deleted_download['price_id']) ? 0 : (int) $deleted_download['price_id'];
            $args = array('quantity' => (int) $deleted_download['quantity'], 'price_id' => (int) $price_id, 'item_price' => (double) $deleted_download['amount']);
            $payment->remove_download($deleted_download['id'], $args);
            do_action('edd_remove_download_from_payment', $payment_id, $deleted_download['id']);
        }
    }
    do_action('edd_update_edited_purchase', $payment_id);
    $payment->date = $date;
    $updated = $payment->save();
    if (0 === $updated) {
        wp_die(__('Error Updating Payment', 'easy-digital-downloads'), __('Error', 'easy-digital-downloads'), array('response' => 400));
    }
    $customer_changed = false;
    if (isset($data['edd-new-customer']) && $data['edd-new-customer'] == '1') {
        $email = isset($data['edd-new-customer-email']) ? sanitize_text_field($data['edd-new-customer-email']) : '';
        $names = isset($data['edd-new-customer-name']) ? sanitize_text_field($data['edd-new-customer-name']) : '';
        if (empty($email) || empty($names)) {
            wp_die(__('New Customers require a name and email address', 'easy-digital-downloads'));
        }
        $customer = new EDD_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 EDD_Customer($curr_customer_id);
                edd_set_error('edd-payment-new-customer-fail', __('Error creating new customer', 'easy-digital-downloads'));
            }
        }
        $new_customer_id = $customer->id;
        $previous_customer = new EDD_Customer($curr_customer_id);
        $customer_changed = true;
    } elseif ($curr_customer_id !== $new_customer_id) {
        $customer = new EDD_Customer($new_customer_id);
        $email = $customer->email;
        $names = $customer->name;
        $previous_customer = new EDD_Customer($curr_customer_id);
        $customer_changed = true;
    } else {
        $customer = new EDD_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);
        }
        $payment->customer_id = $customer->id;
    }
    // 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;
    $payment->tax = $tax;
    $payment->has_unlimited_downloads = $unlimited;
    // Check for payment notes
    if (!empty($data['edd-payment-note'])) {
        $note = wp_kses($data['edd-payment-note'], array());
        edd_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 || 'revoked' == $status)) {
        if ($new_total > $curr_total) {
            // Increase if our new total is higher
            $difference = $new_total - $curr_total;
            edd_increase_total_earnings($difference);
        } elseif ($curr_total > $new_total) {
            // Decrease if our new total is lower
            $difference = $curr_total - $new_total;
            edd_decrease_total_earnings($difference);
        }
    }
    $payment->save();
    do_action('edd_updated_edited_purchase', $payment_id);
    wp_safe_redirect(admin_url('edit.php?post_type=download&page=edd-payment-history&view=view-order-details&edd-message=payment-updated&id=' . $payment_id));
    exit;
}
 /**
  * Decrements customer purchase stats
  *
  * @access  public
  * @since   2.1
  */
 public function decrement_stats($customer_id = 0, $amount = 0.0)
 {
     $customer = new EDD_Customer($customer_id);
     if (!$customer) {
         return false;
     }
     $decreased_count = $customer->decrease_purchase_count();
     $decreased_value = $customer->decrease_value($amount);
     return $decreased_count && $decreased_value ? true : false;
 }
 /**
  * One items have been set, an update is needed to save them to the database.
  *
  * @return bool  True of the save occured, false if it failed or wasn't needed
  */
 public function save()
 {
     $saved = false;
     if (empty($this->ID)) {
         $payment_id = $this->insert_payment();
         if (false === $payment_id) {
             $saved = false;
         } else {
             $this->ID = $payment_id;
         }
     }
     if ($this->ID !== $this->_ID) {
         $this->ID = $this->_ID;
     }
     // If we have something pending, let's save it
     if (!empty($this->pending)) {
         $total_increase = 0;
         $total_decrease = 0;
         foreach ($this->pending as $key => $value) {
             switch ($key) {
                 case 'downloads':
                     // Update totals for pending downloads
                     foreach ($this->pending[$key] as $item) {
                         switch ($item['action']) {
                             case 'add':
                                 $price = $item['price'];
                                 $taxes = $item['tax'];
                                 if ('publish' === $this->status || 'complete' === $this->status || 'revoked' === $this->status) {
                                     // Add sales logs
                                     $log_date = date('Y-m-d G:i:s', current_time('timestamp', true));
                                     $price_id = isset($item['item_number']['options']['price_id']) ? $item['item_number']['options']['price_id'] : 0;
                                     $y = 0;
                                     while ($y < $item['quantity']) {
                                         edd_record_sale_in_log($item['id'], $this->ID, $price_id, $log_date);
                                         $y++;
                                     }
                                     $download = new EDD_Download($item['id']);
                                     $download->increase_sales($item['quantity']);
                                     $download->increase_earnings($price);
                                     $total_increase += $price;
                                 }
                                 break;
                             case 'remove':
                                 $log_args = array('post_type' => 'edd_log', 'post_parent' => $item['id'], 'numberposts' => $item['quantity'], 'meta_query' => array(array('key' => '_edd_log_payment_id', 'value' => $this->ID, 'compare' => '='), array('key' => '_edd_log_price_id', 'value' => $item['price_id'], 'compare' => '=')));
                                 $found_logs = get_posts($log_args);
                                 foreach ($found_logs as $log) {
                                     wp_delete_post($log->ID, true);
                                 }
                                 if ('publish' === $this->status || 'complete' === $this->status || 'revoked' === $this->status) {
                                     $download = new EDD_Download($item['id']);
                                     $download->decrease_sales($item['quantity']);
                                     $download->decrease_earnings($item['amount']);
                                     $total_decrease += $item['amount'];
                                 }
                                 break;
                         }
                     }
                     break;
                 case 'fees':
                     if (!empty($this->pending[$key])) {
                         foreach ($this->pending[$key] as $fee) {
                             switch ($fee['action']) {
                                 case 'add':
                                     $total_increase += $fee['amount'];
                                     break;
                                 case 'remove':
                                     $total_decrease += $fee['amount'];
                                     break;
                             }
                         }
                     }
                     break;
                 case 'status':
                     $this->update_status($this->status);
                     break;
                 case 'gateway':
                     $this->update_meta('_edd_payment_gateway', $this->gateway);
                     break;
                 case 'mode':
                     $this->update_meta('_edd_payment_mode', $this->mode);
                     break;
                 case 'transaction_id':
                     $this->update_meta('_edd_payment_transaction_id', $this->transaction_id);
                     break;
                 case 'ip':
                     $this->update_meta('_edd_payment_user_ip', $this->ip);
                     break;
                 case 'customer_id':
                     $this->update_meta('_edd_payment_customer_id', $this->customer_id);
                     break;
                 case 'user_id':
                     $this->update_meta('_edd_payment_user_id', $this->user_id);
                     break;
                 case 'first_name':
                     $this->user_info['first_name'] = $this->first_name;
                     break;
                 case 'last_name':
                     $this->user_info['last_name'] = $this->last_name;
                     break;
                 case 'discounts':
                     $this->user_info['discount'] = $this->discounts;
                     break;
                 case 'address':
                     $this->user_info['address'] = $this->address;
                     break;
                 case 'email':
                     $this->update_meta('_edd_payment_user_email', $this->email);
                     break;
                 case 'key':
                     $this->update_meta('_edd_payment_purchase_key', $this->key);
                     break;
                 case 'number':
                     $this->update_meta('_edd_payment_number', $this->number);
                     break;
                 case 'completed_date':
                     $this->update_meta('_edd_completed_date', $this->completed_date);
                     break;
                 case 'has_unlimited_downloads':
                     $this->update_meta('_edd_payment_unlimited_downloads', $this->has_unlimited_downloads);
                     break;
                 case 'parent_payment':
                     $args = array('ID' => $this->ID, 'post_parent' => $this->parent_payment);
                     wp_update_post($args);
                     break;
                 default:
                     do_action('edd_payment_save', $this, $key);
                     break;
             }
         }
         if ('pending' !== $this->status) {
             $customer = new EDD_Customer($this->customer_id);
             $total_change = $total_increase - $total_decrease;
             if ($total_change < 0) {
                 $total_chnage = -$total_change;
                 // Decrease the customer's purchase stats
                 $customer->decrease_value($total_change);
                 edd_decrease_total_earnings($total_change);
             } else {
                 if ($total_change > 0) {
                     // Increase the customer's purchase stats
                     $customer->increase_value($total_change);
                     edd_increase_total_earnings($total_change);
                 }
             }
         }
         $this->update_meta('_edd_payment_total', $this->total);
         $this->update_meta('_edd_payment_tax', $this->tax);
         $new_meta = array('downloads' => $this->downloads, 'cart_details' => $this->cart_details, 'fees' => $this->fees, 'currency' => $this->currency, 'user_info' => $this->user_info);
         $meta = $this->get_meta();
         $merged_meta = array_merge($meta, $new_meta);
         // Only save the payment meta if it's changed
         if (md5(serialize($meta)) !== md5(serialize($merged_meta))) {
             $updated = $this->update_meta('_edd_payment_meta', $merged_meta);
             if (false !== $updated) {
                 $saved = true;
             }
         }
         $this->pending = array();
         $saved = true;
     }
     if (true === $saved) {
         $this->setup_payment($this->ID);
     }
     return $saved;
 }
/**
 * When a user is deleted, detach that user id from the customer record
 *
 * @since  2.5
 * @param  int $user_id The User ID being deleted
 * @return bool         If the detachment was successful
 */
function edd_detach_deleted_user($user_id)
{
    $customer = new EDD_Customer($user_id, true);
    $detached = false;
    if ($customer->id > 0) {
        $detached = $customer->update(array('user_id' => 0));
    }
    do_action('edd_detach_deleted_user', $user_id, $customer, $detached);
    return $detached;
}
 /**
  * Used during the process of moving to refunded or pending, to decrement stats
  *
  * @since  2.5.10
  * @param  bool   $alter_store_earnings          If the method should alter the store earnings
  * @param  bool   $alter_customer_value          If the method should reduce the customer value
  * @param  bool   $alter_customer_purchase_count If the method should reduce the customer's purchase count
  * @return void
  */
 private function maybe_alter_stats($alter_store_earnings, $alter_customer_value, $alter_customer_purchase_count)
 {
     edd_undo_purchase(false, $this->ID);
     // Decrease store earnings
     if (true === $alter_store_earnings) {
         edd_decrease_total_earnings($this->total);
     }
     // Decrement the stats for the customer
     if (!empty($this->customer_id)) {
         $customer = new EDD_Customer($this->customer_id);
         if (true === $alter_customer_value) {
             $customer->decrease_value($this->total);
         }
         if (true === $alter_customer_purchase_count) {
             $customer->decrease_purchase_count();
         }
     }
 }
 public static function create_payment($data)
 {
     if (wp_verify_nonce($data['edd_create_payment_nonce'], 'edd_create_payment_nonce')) {
         global $edd_options;
         $data['downloads'] = array_values($data['downloads']);
         if ($data['downloads'][0]['id'] == 0) {
             wp_die(sprintf(__('Please select at least one %s to add to the payment.', 'edd-manual-purchases'), edd_get_label_singular()));
         }
         $by_user_id = false;
         if (!empty($data['email'])) {
             $user = strip_tags(trim($data['email']));
             $by_user_id = false;
         } elseif (empty($data['email']) && !empty($data['customer'])) {
             $user = strip_tags(trim($data['customer']));
         } else {
             $user = null;
         }
         if (null == $user) {
             wp_die(__('Please select a customer or create a new one.', 'edd-manual-purchases'));
         }
         $payment = new EDD_Payment();
         $customer = new EDD_Customer($user, $by_user_id);
         $user_id = $by_user_id == true ? $user : 0;
         $email = $by_user_id == false ? $user : '';
         $first = isset($data['first']) ? sanitize_text_field($data['first']) : '';
         $last = isset($data['last']) ? sanitize_text_field($data['last']) : '';
         if (!$customer->id > 0) {
             $user = $by_user_id == false ? get_user_by('email', $user) : get_user_by('id', $user);
             if ($user) {
                 $user_id = $user->ID;
                 $email = $user->user_email;
             }
             $customer->create(array('email' => $email, 'name' => $first . ' ' . $last, 'user_id' => $user_id));
         } else {
             $email = $customer->email;
         }
         $total = 0.0;
         $payment->customer_id = $customer->id;
         $payment->user_id = $user_id;
         $payment->first_name = $first;
         $payment->last_name = $last;
         $payment->email = $email;
         // Make sure the user info data is set
         $payment->user_info = array('first_name' => $first, 'last_name' => $last, 'id' => $user_id, 'email' => $email);
         $cart_details = array();
         $total = 0;
         foreach ($data['downloads'] as $key => $download) {
             // calculate total purchase cost
             if (isset($download['price_id']) && empty($download['amount'])) {
                 $prices = get_post_meta($download['id'], 'edd_variable_prices', true);
                 $price_key = $download['options']['price_id'];
                 $item_price = $prices[$download['price_id']]['amount'];
             } elseif (empty($download['amount'])) {
                 $item_price = edd_get_download_price($download['id']);
             }
             $item_tax = $args = array('quantity' => !empty($download['quantity']) ? absint($download['quantity']) : 1, 'price_id' => isset($download['price_id']) ? $download['price_id'] : null, 'item_price' => !empty($download['amount']) ? edd_sanitize_amount($download['amount']) : $item_price);
             $args['tax'] = !empty($download['tax']) ? edd_sanitize_amount($download['tax'] * $args['quantity']) : 0;
             $payment->add_download($download['id'], $args);
             $total += $args['item_price'] * $args['quantity'];
         }
         if (!empty($data['amount'])) {
             $total = edd_sanitize_amount(strip_tags(trim($data['amount'])));
             $payment->total = $total;
         }
         // if we are using Wallet, ensure the customer can afford this purchase
         if (!empty($data['wallet']) && class_exists('EDD_Wallet') && $user_id > 0) {
             $wallet_value = edd_wallet()->wallet->balance($user_id);
             if ($wallet_value < $total) {
                 wp_die(__('The customer does not have sufficient funds in their wallet to pay for this purchase.', 'edd-manual-purchases'));
             }
         }
         $date = !empty($data['date']) ? date('Y-m-d H:i:s', strtotime(strip_tags(trim($data['date'])))) : false;
         if (!$date) {
             $date = date('Y-m-d H:i:s', current_time('timestamp'));
         }
         if (strtotime($date, time()) > time()) {
             $date = date('Y-m-d H:i:s', current_time('timestamp'));
         }
         $payment->date = $date;
         $payment->status = 'pending';
         $payment->currency = edd_get_currency();
         $payment->gateway = sanitize_text_field($_POST['gateway']);
         $payment->mode = edd_is_test_mode() ? 'test' : 'live';
         if (!empty($_POST['transaction_id'])) {
             $payment->transaction_id = sanitize_text_field($_POST['transaction_id']);
         }
         $payment->save();
         if (!isset($data['receipt'])) {
             remove_action('edd_complete_purchase', 'edd_trigger_purchase_receipt', 999);
         }
         if (isset($_POST['status']) && 'pending' !== $_POST['status']) {
             $payment->status = $_POST['status'];
             $payment->save();
         }
         if (!empty($data['wallet']) && class_exists('EDD_Wallet') && $user_id > 0) {
             // Update the user wallet
             edd_wallet()->wallet->withdraw($user_id, $total, 'withdrawal', $payment->ID);
         }
         if (!empty($data['shipped'])) {
             update_post_meta($payment->ID, '_edd_payment_shipping_status', '2');
         }
         wp_redirect(admin_url('edit.php?post_type=download&page=edd-payment-history&edd-message=payment_created'));
         exit;
     }
 }
/**
 * Process the 'remove' URL on the profile editor when customers wish to remove an email address
 *
 * @since  2.6
 * @return void
 */
function edd_process_profile_editor_remove_email()
{
    if (!is_user_logged_in()) {
        return false;
    }
    // Pending users can't edit their profile
    if (edd_user_pending_verification()) {
        return false;
    }
    // Nonce security
    if (!wp_verify_nonce($_GET['_wpnonce'], 'edd-remove-customer-email')) {
        return false;
    }
    if (empty($_GET['email']) || !is_email($_GET['email'])) {
        return false;
    }
    $customer = new EDD_Customer(get_current_user_id(), true);
    if ($customer->remove_email($_GET['email'])) {
        $url = add_query_arg('updated', true, $_GET['redirect']);
        $user = wp_get_current_user();
        $user_login = !empty($user->user_login) ? $user->user_login : '******';
        $customer_note = __(sprintf('Email address %s removed by %s', $_GET['email'], $user_login), 'easy-digital-downloads');
        $customer->add_note($customer_note);
    } else {
        edd_set_error('profile-remove-email-failure', __('Error removing email address from profile. Please try again later.', 'easy-digital-downloads'));
        $url = $_GET['redirect'];
    }
    wp_safe_redirect($url);
    exit;
}
 private function set_customer($row)
 {
     global $wpdb;
     if (!empty($this->field_mapping['email']) && !empty($row[$this->field_mapping['email']])) {
         $email = sanitize_text_field($row[$this->field_mapping['email']]);
     }
     // Look for a customer from the canonical source, if any
     if (!empty($this->field_mapping['customer_id']) && !empty($row[$this->field_mapping['customer_id']])) {
         $canonical_id = absint($row[$this->field_mapping['customer_id']]);
         $mapped_id = $wpdb->get_var($wpdb->prepare("SELECT customer_id FROM {$wpdb->customermeta} WHERE meta_key = '_canonical_import_id' AND meta_value = %d LIMIT 1", $canonical_id));
     }
     if (!empty($mapped_id)) {
         $customer = new EDD_Customer($mapped_id);
     }
     if (empty($mapped_id) || !$customer->id > 0) {
         // Look for a customer based on provided ID, if any
         if (!empty($this->field_mapping['customer_id']) && !empty($row[$this->field_mapping['customer_id']])) {
             $customer_id = absint($row[$this->field_mapping['customer_id']]);
             $customer_by_id = new EDD_Customer($customer_id);
         }
         // Now look for a customer based on provided email
         if (!empty($email)) {
             $customer_by_email = new EDD_Customer($email);
         }
         // Now compare customer records. If they don't match, customer_id will be stored in meta and we will use the customer that matches the email
         if ((empty($customer_by_id) || $customer_by_id->id !== $customer_by_email->id) && !empty($customer_by_email)) {
             $customer = $customer_by_email;
         } else {
             if (!empty($customer_by_id)) {
                 $customer = $customer_by_id;
                 if (!empty($email)) {
                     $customer->add_email($email);
                 }
             }
         }
         // Make sure we found a customer. Create one if not.
         if (empty($customer->id)) {
             if (!is_a($customer, 'EDD_Customer')) {
                 $customer = new EDD_Customer();
             }
             $first_name = '';
             $last_name = '';
             if (!empty($this->field_mapping['first_name']) && !empty($row[$this->field_mapping['first_name']])) {
                 $first_name = sanitize_text_field($row[$this->field_mapping['first_name']]);
             }
             if (!empty($this->field_mapping['last_name']) && !empty($row[$this->field_mapping['last_name']])) {
                 $last_name = sanitize_text_field($row[$this->field_mapping['last_name']]);
             }
             $customer->create(array('name' => $first_name . ' ' . $last_name, 'email' => $email));
             if (!empty($canonical_id) && (int) $canonical_id !== (int) $customer->id) {
                 $customer->update_meta('_canonical_import_id', $canonical_id);
             }
         }
     }
     if ($email && $email != $customer->email) {
         $customer->add_email($email);
     }
     return $customer->id;
 }
 /**
  * When a payment is set to a status of 'refunded' process the necessary actions to reduce stats
  *
  * @since  2.5.7
  * @access private
  * @return void
  */
 private function process_refund()
 {
     global $edd_logs;
     $process_refund = true;
     // If the payment was not in publish or revoked status, don't decrement stats as they were never incremented
     if ('publish' != $this->old_status && 'revoked' != $this->old_status || 'refunded' != $this->status) {
         $process_refund = false;
     }
     // Allow extensions to filter for their own payment types, Example: Recurring Payments
     $process_refund = apply_filters('edd_should_process_refund', $process_refund, $this);
     if (false === $process_refund) {
         return;
     }
     do_action('edd_pre_refund_payment', $this);
     edd_undo_purchase(false, $this->ID);
     // Decrease store earnings
     $maybe_decrease_store_earnings = apply_filters('edd_decrease_store_earnings_on_refund', true, $this);
     if (true === $maybe_decrease_store_earnings) {
         edd_decrease_total_earnings($this->total);
     }
     // Decrement the stats for the customer
     if (!empty($this->customer_id)) {
         $customer = new EDD_Customer($this->customer_id);
         $maybe_decrease_value = apply_filters('edd_decrease_customer_value_on_refund', true, $this);
         if (true === $maybe_decrease_value) {
             $customer->decrease_value($this->total);
         }
         $maybe_decrease_purchase_count = apply_filters('edd_decrease_customer_purchase_count_on_refund', true, $this);
         if (true === $maybe_decrease_purchase_count) {
             $customer->decrease_purchase_count();
         }
     }
     // Remove related sale log entries
     $edd_logs->delete_logs(null, 'sale', array(array('key' => '_edd_log_payment_id', 'value' => $this->ID)));
     // Clear the This Month earnings (this_monththis_month is NOT a typo)
     delete_transient(md5('edd_earnings_this_monththis_month'));
     do_action('edd_post_refund_payment', $this);
 }
/**
 * Run the upgrade for the customers to find all payment attachments
 *
 * @since  2.3
 * @return void
 */
function edd_v23_upgrade_customer_purchases()
{
    global $wpdb;
    if (!current_user_can('manage_shop_settings')) {
        wp_die(__('You do not have permission to do shop upgrades', 'edd'), __('Error', 'edd'), array('response' => 403));
    }
    ignore_user_abort(true);
    if (!edd_is_func_disabled('set_time_limit') && !ini_get('safe_mode')) {
        @set_time_limit(0);
    }
    $step = isset($_GET['step']) ? absint($_GET['step']) : 1;
    $number = 50;
    $offset = $step == 1 ? 0 : ($step - 1) * $number;
    if ($step < 2) {
        // Check if we have any payments before moving on
        $sql = "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'edd_payment' LIMIT 1";
        $has_payments = $wpdb->get_col($sql);
        if (empty($has_payments)) {
            // We had no payments, just complete
            update_option('edd_version', preg_replace('/[^0-9.].*/', '', EDD_VERSION));
            edd_set_upgrade_complete('upgrade_customer_payments_association');
            delete_option('edd_doing_upgrade');
            wp_redirect(admin_url());
            exit;
        }
    }
    $total = isset($_GET['total']) ? absint($_GET['total']) : false;
    if (empty($total) || $total <= 1) {
        $total = EDD()->customers->count();
    }
    $customers = EDD()->customers->get_customers(array('number' => $number, 'offset' => $offset));
    if (!empty($customers)) {
        foreach ($customers as $customer) {
            // Get payments by email and user ID
            $select = "SELECT ID FROM {$wpdb->posts} p ";
            $join = "LEFT JOIN {$wpdb->postmeta} m ON p.ID = m.post_id ";
            $where = "WHERE p.post_type = 'edd_payment' ";
            if (!empty($customer->user_id) && intval($customer->user_id) > 0) {
                $where .= "AND ( ( m.meta_key = '_edd_payment_user_email' AND m.meta_value = '{$customer->email}' ) OR ( m.meta_key = '_edd_payment_customer_id' AND m.meta_value = '{$customer->id}' ) OR ( m.meta_key = '_edd_payment_user_id' AND m.meta_value = '{$customer->user_id}' ) )";
            } else {
                $where .= "AND ( ( m.meta_key = '_edd_payment_user_email' AND m.meta_value = '{$customer->email}' ) OR ( m.meta_key = '_edd_payment_customer_id' AND m.meta_value = '{$customer->id}' ) ) ";
            }
            $sql = $select . $join . $where;
            $found_payments = $wpdb->get_col($sql);
            $unique_payment_ids = array_unique(array_filter($found_payments));
            if (!empty($unique_payment_ids)) {
                $unique_ids_string = implode(',', $unique_payment_ids);
                $customer_data = array('payment_ids' => $unique_ids_string);
                $purchase_value_sql = "SELECT SUM( m.meta_value ) FROM {$wpdb->postmeta} m LEFT JOIN {$wpdb->posts} p ON m.post_id = p.ID WHERE m.post_id IN ( {$unique_ids_string} ) AND p.post_status IN ( 'publish', 'revoked' ) AND m.meta_key = '_edd_payment_total'";
                $purchase_value = $wpdb->get_col($purchase_value_sql);
                $purchase_count_sql = "SELECT COUNT( m.post_id ) FROM {$wpdb->postmeta} m LEFT JOIN {$wpdb->posts} p ON m.post_id = p.ID WHERE m.post_id IN ( {$unique_ids_string} ) AND p.post_status IN ( 'publish', 'revoked' ) AND m.meta_key = '_edd_payment_total'";
                $purchase_count = $wpdb->get_col($purchase_count_sql);
                if (!empty($purchase_value) && !empty($purchase_count)) {
                    $purchase_value = $purchase_value[0];
                    $purchase_count = $purchase_count[0];
                    $customer_data['purchase_count'] = $purchase_count;
                    $customer_data['purchase_value'] = $purchase_value;
                }
            } else {
                $customer_data['purchase_count'] = 0;
                $customer_data['purchase_value'] = 0;
                $customer_data['payment_ids'] = '';
            }
            if (!empty($customer_data)) {
                $customer = new EDD_Customer($customer->id);
                $customer->update($customer_data);
            }
        }
        // More Payments found so upgrade them
        $step++;
        $redirect = add_query_arg(array('page' => 'edd-upgrades', 'edd-upgrade' => 'upgrade_customer_payments_association', 'step' => $step, 'number' => $number, 'total' => $total), admin_url('index.php'));
        wp_redirect($redirect);
        exit;
    } else {
        // No more customers found, finish up
        update_option('edd_version', preg_replace('/[^0-9.].*/', '', EDD_VERSION));
        edd_set_upgrade_complete('upgrade_customer_payments_association');
        delete_option('edd_doing_upgrade');
        wp_redirect(admin_url());
        exit;
    }
}
Example #16
0
/**
 * Process the payment details edit
 *
 * @access      private
 * @since       1.9
 * @return      void
*/
function edd_update_payment_details($data)
{
    if (!current_user_can('edit_shop_payments', $data['edd_payment_id'])) {
        wp_die(__('You do not have permission to edit this payment record', 'edd'), __('Error', 'edd'), array('response' => 403));
    }
    check_admin_referer('edd_update_payment_details_nonce');
    // Retrieve the payment ID
    $payment_id = absint($data['edd_payment_id']);
    // Retrieve existing payment meta
    $meta = edd_get_payment_meta($payment_id);
    $user_info = edd_get_payment_meta_user_info($payment_id);
    $status = $data['edd-payment-status'];
    $unlimited = isset($data['edd-unlimited-downloads']) ? '1' : '';
    $date = sanitize_text_field($data['edd-payment-date']);
    $hour = sanitize_text_field($data['edd-payment-time-hour']);
    // Restrict to our high and low
    if ($hour > 23) {
        $hour = 23;
    } elseif ($hour < 0) {
        $hour = 00;
    }
    $minute = sanitize_text_field($data['edd-payment-time-min']);
    // Restrict to our high and low
    if ($minute > 59) {
        $minute = 59;
    } elseif ($minute < 0) {
        $minute = 00;
    }
    $address = array_map('trim', $data['edd-payment-address'][0]);
    $curr_total = edd_sanitize_amount(edd_get_payment_amount($payment_id));
    $new_total = edd_sanitize_amount($_POST['edd-payment-total']);
    $tax = isset($_POST['edd-payment-tax']) ? edd_sanitize_amount($_POST['edd-payment-tax']) : 0;
    $date = date('Y-m-d', strtotime($date)) . ' ' . $hour . ':' . $minute . ':00';
    $curr_customer_id = sanitize_text_field($data['edd-current-customer']);
    $new_customer_id = sanitize_text_field($data['customer-id']);
    // Setup purchased Downloads and price options
    $updated_downloads = isset($_POST['edd-payment-details-downloads']) ? $_POST['edd-payment-details-downloads'] : false;
    if ($updated_downloads && !empty($_POST['edd-payment-downloads-changed'])) {
        $downloads = array();
        $cart_details = array();
        $i = 0;
        foreach ($updated_downloads as $download) {
            if (empty($download['amount'])) {
                $download['amount'] = '0.00';
            }
            $item = array();
            $item['id'] = absint($download['id']);
            $item['quantity'] = absint($download['quantity']) > 0 ? absint($download['quantity']) : 1;
            $price_id = (int) $download['price_id'];
            $has_log = absint($download['has_log']);
            if ($price_id !== false && edd_has_variable_prices($item['id'])) {
                $item['options'] = array('price_id' => $price_id);
            }
            $downloads[] = $item;
            $cart_item = array();
            $cart_item['item_number'] = $item;
            $item_price = round($download['amount'] / $item['quantity'], edd_currency_decimal_filter());
            $cart_details[$i] = array('name' => get_the_title($download['id']), 'id' => $download['id'], 'item_number' => $item, 'price' => $download['amount'], 'item_price' => $item_price, 'subtotal' => $download['amount'], 'quantity' => $download['quantity'], 'discount' => 0, 'tax' => 0);
            // If this item doesn't have a log yet, add one for each quantity count
            if (empty($has_log)) {
                $log_date = date('Y-m-d G:i:s', current_time('timestamp', true));
                $price_id = $price_id !== false ? $price_id : 0;
                $y = 0;
                while ($y < $download['quantity']) {
                    edd_record_sale_in_log($download['id'], $payment_id, $price_id, $log_date);
                    $y++;
                }
                edd_increase_purchase_count($download['id'], $download['quantity']);
                edd_increase_earnings($download['id'], $download['amount']);
            }
            $i++;
        }
        $meta['downloads'] = $downloads;
        $meta['cart_details'] = $cart_details;
        $deleted_downloads = json_decode(stripcslashes($data['edd-payment-removed']), true);
        foreach ($deleted_downloads as $deleted_download) {
            $deleted_download = $deleted_download[0];
            if (empty($deleted_download['id'])) {
                continue;
            }
            $price_id = empty($deleted_download['price_id']) ? 0 : (int) $deleted_download['price_id'];
            $log_args = array('post_type' => 'edd_log', 'post_parent' => $deleted_download['id'], 'numberposts' => $deleted_download['quantity'], 'meta_query' => array(array('key' => '_edd_log_payment_id', 'value' => $payment_id, 'compare' => '='), array('key' => '_edd_log_price_id', 'value' => $price_id, 'compare' => '=')));
            $found_logs = get_posts($log_args);
            foreach ($found_logs as $log) {
                wp_delete_post($log->ID, true);
            }
            edd_decrease_purchase_count($deleted_download['id'], $deleted_download['quantity']);
            edd_decrease_earnings($deleted_download['id'], $deleted_download['amount']);
            do_action('edd_remove_download_from_payment', $payment_id, $deleted_download['id']);
        }
    }
    do_action('edd_update_edited_purchase', $payment_id);
    // Update main payment record
    $updated = wp_update_post(array('ID' => $payment_id, 'post_date' => $date));
    if (0 === $updated) {
        wp_die(__('Error Updating Payment', 'edd'), __('Error', 'edd'), array('response' => 400));
    }
    $customer_changed = false;
    if (isset($data['edd-new-customer']) && $data['edd-new-customer'] == '1') {
        $email = isset($data['edd-new-customer-email']) ? sanitize_text_field($data['edd-new-customer-email']) : '';
        $names = isset($data['edd-new-customer-name']) ? sanitize_text_field($data['edd-new-customer-name']) : '';
        if (empty($email) || empty($names)) {
            wp_die(__('New Customers require a name and email address', 'edd'));
        }
        $customer = new EDD_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 EDD_Customer($curr_customer_id);
                edd_set_error('edd-payment-new-customer-fail', __('Error creating new customer', 'edd'));
            }
        }
        $new_customer_id = $customer->id;
        $previous_customer = new EDD_Customer($curr_customer_id);
        $customer_changed = true;
    } elseif ($curr_customer_id !== $new_customer_id) {
        $customer = new EDD_Customer($new_customer_id);
        $email = $customer->email;
        $names = $customer->name;
        $previous_customer = new EDD_Customer($curr_customer_id);
        $customer_changed = true;
    } else {
        $customer = new EDD_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, '_edd_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;
    $meta['tax'] = $tax;
    // Check for payment notes
    if (!empty($data['edd-payment-note'])) {
        $note = wp_kses($data['edd-payment-note'], array());
        edd_insert_payment_note($payment_id, $note);
    }
    // Set new status
    edd_update_payment_status($payment_id, $status);
    edd_update_payment_meta($payment_id, '_edd_payment_user_id', $customer->user_id);
    edd_update_payment_meta($payment_id, '_edd_payment_user_email', $customer->email);
    edd_update_payment_meta($payment_id, '_edd_payment_meta', $meta);
    edd_update_payment_meta($payment_id, '_edd_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;
            edd_increase_total_earnings($difference);
        } elseif ($curr_total > $new_total) {
            // Decrease if our new total is lower
            $difference = $curr_total - $new_total;
            edd_decrease_total_earnings($difference);
        }
    }
    edd_update_payment_meta($payment_id, '_edd_payment_downloads', $new_total);
    edd_update_payment_meta($payment_id, '_edd_payment_unlimited_downloads', $unlimited);
    do_action('edd_updated_edited_purchase', $payment_id);
    wp_safe_redirect(admin_url('edit.php?post_type=download&page=edd-payment-history&view=view-order-details&edd-message=payment-updated&id=' . $payment_id));
    exit;
}
 /**
  * Processes the supplied payment data to possibly register a user
  *
  * @since  1.3.3
  * @param  array   $payment_data The Payment data
  * @param  int     $payment_id   The payment ID
  * @return int|WP_Error          The User ID created or an instance of WP_Error if the insert fails
  */
 public function create_user($payment_data = array(), $payment_id = 0)
 {
     // User account already associated
     if ($payment_data['user_info']['id'] > 0) {
         return false;
     }
     // User account already exists
     if (get_user_by('email', $payment_data['user_info']['email'])) {
         return false;
     }
     $user_name = sanitize_user($payment_data['user_info']['email']);
     // Username already exists
     if (username_exists($user_name)) {
         return false;
     }
     // Okay we need to create a user and possibly log them in
     // Since this filter existed before, we must send in a $payment_id, which we default to false if none is supplied
     $user_args = apply_filters('edd_auto_register_insert_user_args', array('user_login' => $user_name, 'user_pass' => wp_generate_password(32), 'user_email' => $payment_data['user_info']['email'], 'first_name' => $payment_data['user_info']['first_name'], 'last_name' => $payment_data['user_info']['last_name'], 'user_registered' => date('Y-m-d H:i:s'), 'role' => get_option('default_role')), $payment_id, $payment_data);
     // Insert new user
     $user_id = wp_insert_user($user_args);
     if (!is_wp_error($user_id)) {
         // Allow themes and plugins to hook
         do_action('edd_auto_register_insert_user', $user_id, $user_args, $payment_id);
         $maybe_login_user = function_exists('did_action') && did_action('edd_purchase');
         $maybe_login_user = apply_filters('edd_auto_register_login_user', $maybe_login_user);
         if (true === $maybe_login_user) {
             edd_log_user_in($user_id, $user_args['user_login'], $user_args['user_pass']);
         }
         $customer = new EDD_Customer($payment_data['user_info']['email']);
         $customer->update(array('user_id' => $user_id));
     }
     return $user_id;
 }
/**
 * Process Profile Updater Form
 *
 * Processes the profile updater form by updating the necessary fields
 *
 * @since 1.4
 * @author Sunny Ratilal
 * @param array $data Data sent from the profile editor
 * @return void
 */
function edd_process_profile_editor_updates($data)
{
    // Profile field change request
    if (empty($_POST['edd_profile_editor_submit']) && !is_user_logged_in()) {
        return false;
    }
    // Pending users can't edit their profile
    if (edd_user_pending_verification()) {
        return false;
    }
    // Nonce security
    if (!wp_verify_nonce($data['edd_profile_editor_nonce'], 'edd-profile-editor-nonce')) {
        return false;
    }
    $user_id = get_current_user_id();
    $old_user_data = get_userdata($user_id);
    $display_name = isset($data['edd_display_name']) ? sanitize_text_field($data['edd_display_name']) : $old_user_data->display_name;
    $first_name = isset($data['edd_first_name']) ? sanitize_text_field($data['edd_first_name']) : $old_user_data->first_name;
    $last_name = isset($data['edd_last_name']) ? sanitize_text_field($data['edd_last_name']) : $old_user_data->last_name;
    $email = isset($data['edd_email']) ? sanitize_email($data['edd_email']) : $old_user_data->user_email;
    $line1 = isset($data['edd_address_line1']) ? sanitize_text_field($data['edd_address_line1']) : '';
    $line2 = isset($data['edd_address_line2']) ? sanitize_text_field($data['edd_address_line2']) : '';
    $city = isset($data['edd_address_city']) ? sanitize_text_field($data['edd_address_city']) : '';
    $state = isset($data['edd_address_state']) ? sanitize_text_field($data['edd_address_state']) : '';
    $zip = isset($data['edd_address_zip']) ? sanitize_text_field($data['edd_address_zip']) : '';
    $country = isset($data['edd_address_country']) ? sanitize_text_field($data['edd_address_country']) : '';
    $userdata = array('ID' => $user_id, 'first_name' => $first_name, 'last_name' => $last_name, 'display_name' => $display_name, 'user_email' => $email);
    $address = array('line1' => $line1, 'line2' => $line2, 'city' => $city, 'state' => $state, 'zip' => $zip, 'country' => $country);
    do_action('edd_pre_update_user_profile', $user_id, $userdata);
    // New password
    if (!empty($data['edd_new_user_pass1'])) {
        if ($data['edd_new_user_pass1'] !== $data['edd_new_user_pass2']) {
            edd_set_error('password_mismatch', __('The passwords you entered do not match. Please try again.', 'easy-digital-downloads'));
        } else {
            $userdata['user_pass'] = $data['edd_new_user_pass1'];
        }
    }
    // Make sure the new email doesn't belong to another user
    if ($email != $old_user_data->user_email) {
        // Make sure the new email is valid
        if (!is_email($email)) {
            edd_set_error('email_invalid', __('The email you entered is invalid. Please enter a valid email.', 'easy-digital-downloads'));
        }
        // Make sure the new email doesn't belong to another user
        if (email_exists($email)) {
            edd_set_error('email_exists', __('The email you entered belongs to another user. Please use another.', 'easy-digital-downloads'));
        }
    }
    // Check for errors
    $errors = edd_get_errors();
    if ($errors) {
        // Send back to the profile editor if there are errors
        wp_redirect($data['edd_redirect']);
        edd_die();
    }
    // Update the user
    $meta = update_user_meta($user_id, '_edd_user_address', $address);
    $updated = wp_update_user($userdata);
    // Possibly update the customer
    $customer = new EDD_Customer($user_id, true);
    if ($customer->id > 0) {
        $update_args = array('name' => $first_name . ' ' . $last_name);
        $customer->update($update_args);
    }
    if ($updated) {
        do_action('edd_user_profile_updated', $user_id, $userdata);
        wp_redirect(add_query_arg('updated', 'true', $data['edd_redirect']));
        edd_die();
    }
}
/**
 * Deletes a Purchase
 *
 * @since 1.0
 * @global $edd_logs
 *
 * @uses EDD_Logging::delete_logs()
 *
 * @param int $payment_id Payment ID (default: 0)
 * @param bool $update_customer If we should update the customer stats (default:true)
 * @param bool $delete_download_logs If we should remove all file download logs associated with the payment (default:false)
 *
 * @return void
 */
function edd_delete_purchase($payment_id = 0, $update_customer = true, $delete_download_logs = false)
{
    global $edd_logs;
    $post = get_post($payment_id);
    if (!$post) {
        return;
    }
    $downloads = edd_get_payment_meta_downloads($payment_id);
    if (is_array($downloads)) {
        // Update sale counts and earnings for all purchased products
        foreach ($downloads as $download) {
            edd_undo_purchase($download['id'], $payment_id);
        }
    }
    $amount = edd_get_payment_amount($payment_id);
    $status = $post->post_status;
    $customer_id = edd_get_payment_customer_id($payment_id);
    $customer = new EDD_Customer($customer_id);
    if ($status == 'revoked' || $status == 'publish') {
        // Only decrease earnings if they haven't already been decreased (or were never increased for this payment)
        edd_decrease_total_earnings($amount);
        // Clear the This Month earnings (this_monththis_month is NOT a typo)
        delete_transient(md5('edd_earnings_this_monththis_month'));
        if ($customer->id && $update_customer) {
            // Decrement the stats for the customer
            $customer->decrease_purchase_count();
            $customer->decrease_value($amount);
        }
    }
    do_action('edd_payment_delete', $payment_id);
    if ($customer->id && $update_customer) {
        // Remove the payment ID from the customer
        $customer->remove_payment($payment_id);
    }
    // Remove the payment
    wp_delete_post($payment_id, true);
    // Remove related sale log entries
    $edd_logs->delete_logs(null, 'sale', array(array('key' => '_edd_log_payment_id', 'value' => $payment_id)));
    if ($delete_download_logs) {
        $edd_logs->delete_logs(null, 'file_download', array(array('key' => '_edd_log_payment_id', 'value' => $payment_id)));
    }
    do_action('edd_payment_deleted', $payment_id);
}
/**
 * Reduces earnings and sales stats when a purchase is refunded
 *
 * @since 1.8.2
 * @param $data Arguments passed
 * @return void
 */
function edd_undo_purchase_on_refund($payment_id, $new_status, $old_status)
{
    global $edd_logs;
    if ('publish' != $old_status && 'revoked' != $old_status) {
        return;
    }
    if ('refunded' != $new_status) {
        return;
    }
    $payment = new EDD_Payment($payment_id);
    $downloads = $payment->cart_details;
    if ($downloads) {
        foreach ($downloads as $download) {
            edd_undo_purchase($download['id'], $payment->ID);
        }
    }
    // Decrease store earnings
    edd_decrease_total_earnings($payment->total);
    // Decrement the stats for the customer
    if (!empty($payment->customer_id)) {
        $customer = new EDD_Customer($payment->customer_id);
        $customer->decrease_value($payment->total);
        $customer->decrease_purchase_count();
    }
    // Remove related sale log entries
    $edd_logs->delete_logs(null, 'sale', array(array('key' => '_edd_log_payment_id', 'value' => $payment->ID)));
    // Clear the This Month earnings (this_monththis_month is NOT a typo)
    delete_transient(md5('edd_earnings_this_monththis_month'));
}
 /**
  * Maybe create a user when payment is created
  *
  * @since 1.3
  */
 public function maybe_insert_user($payment_id, $payment_data)
 {
     // User account already associated
     if ($payment_data['user_info']['id'] > 0) {
         return;
     }
     // User account already exists
     if (get_user_by('email', $payment_data['user_info']['email'])) {
         return;
     }
     $user_name = sanitize_user($payment_data['user_info']['email']);
     // Username already exists
     if (username_exists($user_name)) {
         return;
     }
     // Okay we need to create a user and possibly log them in
     $user_args = apply_filters('edd_auto_register_insert_user_args', array('user_login' => $user_name, 'user_pass' => wp_generate_password(32), 'user_email' => $payment_data['user_info']['email'], 'first_name' => $payment_data['user_info']['first_name'], 'last_name' => $payment_data['user_info']['last_name'], 'user_registered' => date('Y-m-d H:i:s'), 'role' => get_option('default_role')), $payment_id, $payment_data);
     // Insert new user
     $user_id = wp_insert_user($user_args);
     // Validate inserted user
     if (is_wp_error($user_id)) {
         return;
     }
     $payment_meta = edd_get_payment_meta($payment_id);
     $payment_meta['user_info']['id'] = $user_id;
     edd_update_payment_meta($payment_id, '_edd_payment_user_id', $user_id);
     edd_update_payment_meta($payment_id, '_edd_payment_meta', $payment_meta);
     $customer = new EDD_Customer($payment_data['user_info']['email']);
     $customer->update(array('user_id' => $user_id));
     // Allow themes and plugins to hook
     do_action('edd_auto_register_insert_user', $user_id, $user_args, $payment_id);
     if (function_exists('did_action') && did_action('edd_purchase')) {
         // Only log user in if processing checkout screen
         edd_log_user_in($user_id, $user_args['user_login'], $user_args['user_pass']);
     }
 }
 /**
  * Zero out the data on step one
  *
  * @access public
  * @since 2.5
  * @return void
  */
 public function pre_fetch()
 {
     if ($this->step === 1) {
         // Before we start, let's zero out the customer's data
         $customer = new EDD_Customer($this->customer_id);
         $customer->update(array('purchase_value' => edd_format_amount(0), 'purchase_count' => 0));
         $attached_payment_ids = explode(',', $customer->payment_ids);
         $attached_args = array('post__in' => $attached_payment_ids, 'number' => -1);
         $attached_payments = edd_get_payments($attached_args);
         $unattached_args = array('post__not_in' => $attached_payment_ids, 'number' => -1, 'meta_query' => array(array('key' => '_edd_payment_user_email', 'value' => $customer->email)));
         $unattached_payments = edd_get_payments($unattached_args);
         $payments = array_merge($attached_payments, $unattached_payments);
         $this->store_data('edd_recount_customer_payments_' . $customer->id, $payments);
     }
 }
/**
 * Reduces earnings and sales stats when a purchase is refunded
 *
 * @since 1.8.2
 * @param $data Arguments passed
 * @return void
 */
function edd_undo_purchase_on_refund($payment_id, $new_status, $old_status)
{
    if ('publish' != $old_status && 'revoked' != $old_status) {
        return;
    }
    if ('refunded' != $new_status) {
        return;
    }
    $downloads = edd_get_payment_meta_cart_details($payment_id);
    if ($downloads) {
        foreach ($downloads as $download) {
            edd_undo_purchase($download['id'], $payment_id);
        }
    }
    // Decrease store earnings
    $amount = edd_get_payment_amount($payment_id);
    edd_decrease_total_earnings($amount);
    // Decrement the stats for the customer
    $customer_id = edd_get_payment_customer_id($payment_id);
    if ($customer_id) {
        $customer = new EDD_Customer($customer_id);
        $customer->decrease_value($amount);
        $customer->decrease_purchase_count();
    }
    // Clear the This Month earnings (this_monththis_month is NOT a typo)
    delete_transient(md5('edd_earnings_this_monththis_month'));
}
/**
 * Attach the newly created user_id to a customer, if one exists
 *
 * @since  2.4.6
 * @param  int $user_id The User ID that was created
 * @return void
 */
function edd_connect_existing_customer_to_new_user($user_id)
{
    $email = get_the_author_meta('user_email', $user_id);
    // Update the user ID on the customer
    $customer = new EDD_Customer($email);
    if ($customer->id > 0) {
        $customer->update(array('user_id' => $user_id));
    }
}