function column_default($item, $column_name)
 {
     switch ($column_name) {
         case 'rate':
             $download = get_post_meta($item['ID'], '_download_id', true);
             $type = eddc_get_commission_type($download);
             if ('percentage' == $type) {
                 return $item[$column_name] . '%';
             } else {
                 return edd_currency_filter(edd_sanitize_amount($item[$column_name]));
             }
         case 'status':
             return $item[$column_name];
         case 'amount':
             return edd_currency_filter(edd_format_amount($item[$column_name]));
         case 'date':
             return date_i18n(get_option('date_format'), strtotime(get_post_field('post_date', $item['ID'])));
         case 'download':
             $download = !empty($item['download']) ? $item['download'] : false;
             return $download ? '<a href="' . esc_url(add_query_arg('download', $download)) . '" title="' . __('View all commissions for this item', 'eddc') . '">' . get_the_title($download) . '</a>' . (!empty($item['variation']) ? ' - ' . $item['variation'] : '') : '';
         case 'payment':
             $payment = get_post_meta($item['ID'], '_edd_commission_payment_id', true);
             return $payment ? '<a href="' . esc_url(admin_url('edit.php?post_type=download&page=edd-payment-history&view=view-order-details&id=' . $payment)) . '" title="' . __('View payment details', 'eddc') . '">#' . $payment . '</a> - ' . edd_get_payment_status(get_post($payment), true) : '';
         default:
             return print_r($item, true);
             //Show the whole array for troubleshooting purposes
     }
 }
/**
 * Price
 *
 * Displays a formatted price for a download.
 *
 * @access      public
 * @since       1.0
 * @param       int $download_id the ID of the download price to show
 * @param		bool whether to echo or return the results
* @return       void
*/
function edd_price($download_id, $echo = true)
{
    if (edd_has_variable_prices($download_id)) {
        $prices = edd_get_variable_prices($download_id);
        // return the lowest price
        $price_float = 0;
        foreach ($prices as $key => $value) {
            if ((double) $prices[$key]['amount'] < $price_float or $price_float == 0) {
                $price_float = (double) $prices[$key]['amount'];
            }
        }
        $price = edd_sanitize_amount($price_float);
    } else {
        $price = edd_get_download_price($download_id);
    }
    if (edd_use_taxes() && edd_taxes_on_prices()) {
        $price += edd_calculate_tax($price);
    }
    $price = apply_filters('edd_download_price', $price, $download_id);
    $price = '<span class="edd_price" id="edd_price_' . $download_id . '">' . $price . '</span>';
    if ($echo) {
        echo $price;
    } else {
        return $price;
    }
}
Example #3
0
 public function output_data($data, $query_mode, $api_object)
 {
     if ('commissions' != $query_mode) {
         return $data;
     }
     $user_id = $api_object->get_user();
     $data['unpaid'] = array();
     $data['paid'] = array();
     $unpaid = eddc_get_unpaid_commissions(array('user_id' => $user_id, 'number' => 30, 'paged' => $api_object->get_paged()));
     if (!empty($unpaid)) {
         foreach ($unpaid as $commission) {
             $commission_meta = get_post_meta($commission->ID, '_edd_commission_info', true);
             $data['unpaid'][] = array('amount' => edd_sanitize_amount($commission_meta['amount']), 'rate' => $commission_meta['rate'], 'currency' => $commission_meta['currency'], 'item' => get_the_title(get_post_meta($commission->ID, '_download_id', true)), 'date' => $commission->post_date);
         }
     }
     $paid = eddc_get_paid_commissions(array('user_id' => $user_id, 'number' => 30, 'paged' => $api_object->get_paged()));
     if (!empty($paid)) {
         foreach ($paid as $commission) {
             $commission_meta = get_post_meta($commission->ID, '_edd_commission_info', true);
             $data['paid'][] = array('amount' => edd_sanitize_amount($commission_meta['amount']), 'rate' => $commission_meta['rate'], 'currency' => $commission_meta['currency'], 'item' => get_the_title(get_post_meta($commission->ID, '_download_id', true)), 'date' => $commission->post_date);
         }
     }
     $data['totals'] = array('unpaid' => eddc_get_unpaid_totals($user_id), 'paid' => eddc_get_paid_totals($user_id));
     return $data;
 }
/**
 * Get final price of a download after discount
 * 
 * Modified From:
 * includes/download-functions.php -> edd_price()
 * Modified Parts:
 * Remove the price as a number, without the html formatting.
 * 
 * @param  int   $download_id ID of the download
 * @return float              Download price
 */
function vp_edd_fd_get_calculated_price($download_id)
{
    if (edd_has_variable_prices($download_id)) {
        $prices = edd_get_variable_prices($download_id);
        // Return the lowest price
        $price_float = 0;
        foreach ($prices as $key => $value) {
            if ((double) $prices[$key]['amount'] < $price_float or $price_float == 0) {
                $price_float = (double) $prices[$key]['amount'];
            }
        }
        $price = edd_sanitize_amount($price_float);
    } else {
        $price = edd_get_download_price($download_id);
    }
    if (edd_use_taxes() && edd_taxes_on_prices()) {
        $price += edd_calculate_tax($price);
    }
    return $price;
}
/**
 * Gets the total tax amount for the cart contents
 *
 * @since 1.2.3
 *
 * @return mixed|void Total tax amount
 */
function edd_get_cart_tax()
{
    $cart_tax = 0;
    $items = edd_get_cart_content_details();
    if ($items) {
        $taxes = wp_list_pluck($items, 'tax');
        if (is_array($taxes)) {
            $cart_tax = array_sum($taxes);
        }
    }
    $cart_tax += edd_get_cart_fee_tax();
    return apply_filters('edd_get_cart_tax', edd_sanitize_amount($cart_tax));
}
Example #6
0
/**
 * Sanitize the variable prices
 *
 * Ensures prices are correctly mapped to an array starting with an index of 0
 *
 * @since 1.4.2
 * @param array $prices Variable prices
 * @return array $prices Array of the remapped variable prices
 */
function edd_sanitize_variable_prices_save($prices)
{
    foreach ($prices as $id => $price) {
        if (empty($price['amount']) && empty($price['name'])) {
            unset($prices[$id]);
            continue;
        } elseif (empty($price['amount'])) {
            $price['amount'] = 0;
        }
        $prices[$id]['amount'] = edd_sanitize_amount($price['amount']);
    }
    return $prices;
}
/**
 * Displays the incentive discount row on the cart
 *
 * @since		1.0.1
 * @return		void
 */
function edd_wallet_cart_items_renewal_row()
{
    $incentive_type = edd_get_option('edd_wallet_incentive_type', 'flatrate');
    $incentive_amount = edd_get_option('edd_wallet_incentive_amount', 0);
    $incentive_description = edd_get_option('edd_wallet_incentive_description', __('Wallet Discount', 'edd-wallet'));
    if ($incentive_amount <= 0) {
        return;
    }
    if (!EDD()->session->get('wallet_has_incentives')) {
        return;
    }
    if ($incentive_type == 'percent') {
        $discount = $incentive_amount . '%';
    } else {
        $discount = edd_currency_filter(edd_sanitize_amount($incentive_amount * edd_get_cart_quantity()));
    }
    ?>
	<tr class="edd_cart_footer_row edd_wallet_incentive_row">
		<td colspan="3"><?php 
    printf(__('%1$s: %2$s', 'edd-wallet'), $incentive_description, $discount);
    ?>
</td>
	</tr>
<?php 
}
 /**
  * Create sample purchase data for your EDD site
  *
  * ## OPTIONS
  *
  * --number: The number of purchases to create
  * --status=<status>: The status to create purchases as
  * --id=<product_id>: A specific product to create purchase data for
  * --price_id=<price_id>: A price ID of the specified product
  *
  * ## EXAMPLES
  *
  * wp edd payments create --number=10 --status=completed
  * wp edd payments create --number=10 --id=103
  */
 public function payments($args, $assoc_args)
 {
     $error = false;
     // At some point we'll likely add another action for payments
     if (!isset($args) || count($args) == 0) {
         $error = __('No action specified, did you mean', 'easy-digital-downloads');
     } elseif (isset($args) && !in_array('create', $args)) {
         $error = __('Invalid action specified, did you mean', 'easy-digital-downloads');
     }
     if ($error) {
         foreach ($assoc_args as $key => $value) {
             $query .= ' --' . $key . '=' . $value;
         }
         WP_CLI::error(sprintf($error . ' %s?', 'wp edd payments create' . $query));
         return;
     }
     // Setup some defaults
     $number = 1;
     $status = 'complete';
     $id = false;
     $price_id = false;
     if (count($assoc_args) > 0) {
         $number = array_key_exists('number', $assoc_args) ? absint($assoc_args['number']) : $number;
         $id = array_key_exists('id', $assoc_args) ? absint($assoc_args['id']) : $id;
         $price_id = array_key_exists('price_id', $assoc_args) ? absint($assoc_args['id']) : false;
         $tax = array_key_exists('tax', $assoc_args) ? floatval($assoc_args['tax']) : 0;
         $email = array_key_exists('email', $assoc_args) ? sanitize_email($assoc_args['email']) : '*****@*****.**';
         $fname = array_key_exists('fname', $assoc_args) ? sanitize_text_field($assoc_args['fname']) : 'Pippin';
         $lname = array_key_exists('lname', $assoc_args) ? sanitize_text_field($assoc_args['lname']) : 'Williamson';
         // Status requires a bit more validation
         if (array_key_exists('status', $assoc_args)) {
             $stati = array('publish', 'complete', 'pending', 'refunded', 'revoked', 'failed', 'abandoned', 'preapproval', 'cancelled');
             if (in_array($assoc_args['status'], $stati)) {
                 $status = $assoc_args['status'] == 'complete' ? 'publish' : $assoc_args['status'];
             } else {
                 WP_CLI::warning(sprintf(__("Invalid status '%s', defaulting to 'complete'", 'easy-digital-downloads'), $assoc_args['status']));
             }
         }
     }
     // Build the user info array
     $user_info = array('id' => 0, 'email' => $email, 'first_name' => $fname, 'last_name' => $lname, 'discount' => 'none');
     for ($i = 0; $i < $number; $i++) {
         $products = array();
         $total = 0;
         // No specified product
         if (!$id) {
             $products = get_posts(array('post_type' => 'download', 'orderby' => 'rand', 'order' => 'ASC', 'posts_per_page' => 1));
         } else {
             $product = get_post($id);
             if ($product->post_type != 'download') {
                 WP_CLI::error(__('Specified ID is not a product', 'easy-digital-downloads'));
                 return;
             }
             $products[] = $product;
         }
         $cart_details = array();
         // Create the purchases
         foreach ($products as $key => $download) {
             if (!is_a($download, 'WP_Post')) {
                 continue;
             }
             $options = array();
             $final_downloads = array();
             // Deal with variable pricing
             if (edd_has_variable_prices($download->ID)) {
                 $prices = edd_get_variable_prices($download->ID);
                 if (false === $price_id || !array_key_exists($price_id, (array) $prices)) {
                     $price_id = rand(0, count($prices) - 1);
                 }
                 $item_price = $prices[$price_id]['amount'];
                 $options['price_id'] = $price_id;
             } else {
                 $item_price = edd_get_download_price($download->ID);
             }
             $item_number = array('id' => $download->ID, 'quantity' => 1, 'options' => $options);
             $cart_details[$key] = array('name' => $download->post_title, 'id' => $download->ID, 'item_number' => $item_number, 'item_price' => edd_sanitize_amount($item_price), 'subtotal' => edd_sanitize_amount($item_price), 'price' => edd_sanitize_amount($item_price), 'quantity' => 1, 'discount' => 0, 'tax' => $tax);
             $final_downloads[$key] = $item_number;
             $total += $item_price;
         }
         $purchase_data = array('price' => edd_sanitize_amount($total), 'tax' => 0, 'purchase_key' => strtolower(md5(uniqid())), 'user_email' => $email, 'user_info' => $user_info, 'currency' => edd_get_currency(), 'downloads' => $final_downloads, 'cart_details' => $cart_details, 'status' => 'pending');
         $payment_id = edd_insert_payment($purchase_data);
         remove_action('edd_complete_purchase', 'edd_trigger_purchase_receipt', 999);
         if ($status != 'pending') {
             edd_update_payment_status($payment_id, $status);
         }
     }
     WP_CLI::success(sprintf(__('Created %s payments', 'easy-digital-downloads'), $number));
     return;
 }
/**
 * Process bulk edit actions via AJAX
 *
 * @since 1.4.4
 * @return void
 */
function edd_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 (!empty($price)) {
                update_post_meta($post_id, 'edd_price', edd_sanitize_amount($price));
            }
        }
    }
    die;
}
 /**
  * Retrieve the price
  *
  * @since 2.2
  * @return float
  */
 public function get_price()
 {
     if (!isset($this->price)) {
         $this->price = get_post_meta($this->ID, 'edd_price', true);
         if ($this->price) {
             $this->price = edd_sanitize_amount($this->price);
         } else {
             $this->price = 0;
         }
     }
     /**
      * Override the download price.
      *
      * @since 2.2
      *
      * @param string $price The download price(s).
      * @param string|int $id The downloads ID.
      */
     return apply_filters('edd_get_download_price', $this->price, $this->ID);
 }
Example #11
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;
}
/**
 * Update Edited Purchase
 *
 * Updates the purchase data for a payment.
 * Used primarily for adding new downloads to a purchase.
 *
 * @since 1.0
 * @param $data Arguments passed
 * @return void
 */
function edd_update_edited_purchase($data)
{
    if (wp_verify_nonce($data['edd-payment-nonce'], 'edd_payment_nonce')) {
        $payment_id = $_POST['payment-id'];
        $payment_data = edd_get_payment_meta($payment_id);
        if (isset($_POST['edd-purchased-downloads'])) {
            $download_list = array();
            foreach ($_POST['edd-purchased-downloads'] as $key => $download) {
                if (isset($download['options']['price_id'])) {
                    $download_list[] = array('id' => $key, 'options' => array('price_id' => $download['options']['price_id']));
                } else {
                    $download_list[] = array('id' => $download);
                }
            }
            $payment_data['downloads'] = serialize($download_list);
        }
        $user_info = maybe_unserialize($payment_data['user_info']);
        $user_info['email'] = strip_tags($_POST['edd-buyer-email']);
        $user_info['user_id'] = strip_tags(intval($_POST['edd-buyer-user-id']));
        $payment_data['user_info'] = serialize($user_info);
        update_post_meta($payment_id, '_edd_payment_meta', $payment_data);
        update_post_meta($payment_id, '_edd_payment_user_email', strip_tags($_POST['edd-buyer-email']));
        update_post_meta($payment_id, '_edd_payment_user_id', strip_tags(intval($_POST['edd-buyer-user-id'])));
        if (!empty($_POST['edd-payment-note'])) {
            $note = wp_kses($_POST['edd-payment-note'], array());
            $note_id = edd_insert_payment_note($payment_id, $note);
        }
        if (!empty($_POST['edd-payment-amount'])) {
            update_post_meta($payment_id, '_edd_payment_total', sanitize_text_field(edd_sanitize_amount($_POST['edd-payment-amount'])));
        }
        if (!empty($_POST['edd-unlimited-downloads'])) {
            add_post_meta($payment_id, '_unlimited_file_downloads', '1');
        } else {
            delete_post_meta($payment_id, '_unlimited_file_downloads');
        }
        if ($_POST['edd-old-status'] != $_POST['edd-payment-status']) {
            edd_update_payment_status($payment_id, $_POST['edd-payment-status']);
        }
        if ($_POST['edd-payment-status'] == 'publish' && isset($_POST['edd-payment-send-email'])) {
            // Send the purchase receipt
            edd_email_purchase_receipt($payment_id, false);
        }
        do_action('edd_update_edited_purchase', $payment_id);
    }
}
/**
 * Custom pledge level fix.
 *
 * If there is a custom price, figure out the difference
 * between that, and the price level they have chosen. Store
 * the differene in the cart item meta, so it can be added to
 * the total in the future.
 *
 * @since Astoundify Crowdfunding 1.6
 *
 * @param array $cart_item The current cart item to be added.
 * @return array $cart_item The modified cart item.
 */
function atcf_edd_add_to_cart_item($cart_item)
{
    if (isset($_POST['post_data'])) {
        $post_data = array();
        parse_str($_POST['post_data'], $post_data);
        $custom_price = $post_data['atcf_custom_price'];
    } else {
        $custom_price = $_POST['atcf_custom_price'];
    }
    $custom_price = edd_sanitize_amount($custom_price);
    $price = edd_get_cart_item_price($cart_item['id'], $cart_item['options'], edd_prices_include_tax());
    if ($custom_price > $price) {
        $cart_item['options']['atcf_extra_price'] = $custom_price - $price;
    }
    return $cart_item;
}
function eddc_generate_payout_file($data)
{
    if (wp_verify_nonce($data['eddc-payout-nonce'], 'eddc-payout-nonce')) {
        $from = !empty($data['from']) ? sanitize_text_field($data['from']) : date('m/d/Y', strtotime('-1 month'));
        $to = !empty($data['to']) ? sanitize_text_field($data['to']) : date('m/d/Y');
        $from = explode('/', $from);
        $to = explode('/', $to);
        $args = array('number' => -1, 'query_args' => array('date_query' => array('after' => array('year' => $from[2], 'month' => $from[0], 'day' => $from[1]), 'before' => array('year' => $to[2], 'month' => $to[0], 'day' => $to[1]), 'inclusive' => true)));
        $commissions = eddc_get_unpaid_commissions($args);
        if ($commissions) {
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename=edd-commission-payout-' . date('m-d-Y') . '.csv');
            header("Pragma: no-cache");
            header("Expires: 0");
            $payouts = array();
            foreach ($commissions as $commission) {
                $commission_meta = get_post_meta($commission->ID, '_edd_commission_info', true);
                $user_id = $commission_meta['user_id'];
                $user = get_userdata($user_id);
                $custom_paypal = get_user_meta($user_id, 'eddc_user_paypal', true);
                $email = is_email($custom_paypal) ? $custom_paypal : $user->user_email;
                if (array_key_exists($email, $payouts)) {
                    $payouts[$email]['amount'] += $commission_meta['amount'];
                } else {
                    $payouts[$email] = array('amount' => $commission_meta['amount'], 'currency' => $commission_meta['currency']);
                }
                eddc_set_commission_status($commission->ID, 'paid');
            }
            if ($payouts) {
                foreach ($payouts as $key => $payout) {
                    echo $key . ",";
                    echo edd_sanitize_amount(number_format($payout['amount'], 2)) . ",";
                    echo $payout['currency'];
                    echo "\r\n";
                }
            }
        } else {
            wp_die(__('No commissions to be paid', 'eddc'), __('Error'));
        }
        die;
    }
}
    /**
     * Display the widget content.
     *
     * @since 1.0
     *
     * @param array $args Display arguments including before_widget and after_widget.
     * @param array $instance The settings for the particular instance of the widget
     */
    function widget($args, $instance)
    {
        // Merge with defaults
        $instance = wp_parse_args((array) $instance, $this->defaults);
        // Return early if we have no download ID or no variable prices
        if (!isset($instance['download']) || !edd_has_variable_prices(absint($instance['download']))) {
            return;
        }
        // Set the download ID
        $download_id = absint($instance['download']);
        // Get the variable price options
        $prices = edd_get_variable_prices($download_id);
        // Get the featured price option
        $featured = isset($instance['price_variation']) && !empty($instance['price_variation']) ? absint($instance['price_variation']) : false;
        echo $args['before_widget'];
        ?>

		<section class="pricing-section <?php 
        if ($featured) {
            echo 'featured-price';
        }
        ?>
">
			<div class="pricing-table-wrap">
				<?php 
        foreach ($prices as $key => $price) {
            ?>
					<div itemscope class="pricing-table <?php 
            if ($key == $featured) {
                echo 'featured';
            }
            ?>
">
						<div class="pricing-table-top">
							<div class="pricing-table-price"><?php 
            echo apply_filters('edd_download_price', edd_sanitize_amount($price['amount']), $download_id, $key);
            ?>
</div>
							<div class="pricing-table-price-desc"><?php 
            echo $price['name'];
            ?>
</div>
						</div>
						<div class="pricing-table-features">
							<div class="download-details download-aside">
								<div class="download-features" itemprop="itemCondition">
									<ul>
									<?php 
            $list_items = checkout_edd_download_details_list_items($download_id, $key);
            if ($list_items) {
                foreach ($list_items as $item) {
                    echo '<li class="price-feature">' . $item . '</li>';
                }
            }
            $list_item_all_prices = checkout_edd_download_details_list_items($download_id, 'all');
            if ($list_item_all_prices) {
                foreach ($list_item_all_prices as $list_item) {
                    echo '<li class="all-prices-feature">' . $list_item . '</li>';
                }
            }
            ?>
										</ul>
									</div>
								</div>
							<a class="button" href="<?php 
            echo edd_get_checkout_uri();
            ?>
?edd_action=add_to_cart&amp;download_id=<?php 
            echo absint($download_id);
            ?>
&amp;edd_options%5Bprice_id%5D=<?php 
            echo absint($key);
            ?>
" title="<?php 
            echo esc_attr($price['name']);
            ?>
">
								<?php 
            _e('Buy Now', 'checkout');
            ?>
							</a>
						</div>
					</div>
				<?php 
        }
        ?>
			</div>

			<?php 
        if ($instance['footnotes']) {
            ?>
				<div class="pricing-table-footnotes">
					<?php 
            echo $instance['footnotes'];
            ?>
				</div>
			<?php 
        }
        ?>
		</section><!-- .pricing-section -->

		<?php 
        echo $args['after_widget'];
    }
Example #16
0
/**
 * Contribute now list options
 * @return void
**/
function wpo_campaign_contribute_options_custom($prices, $type, $download_id)
{
    $campaign = atcf_get_campaign($download_id);
    $uid = wpo_makeid();
    ?>
	<div class="edd_price_options <?php 
    echo $campaign->is_active() ? 'active' : 'expired';
    ?>
" <?php 
    echo $campaign->is_donations_only() ? 'style="display: none"' : null;
    ?>
>
		<ul>
			<?php 
    foreach ($prices as $key => $price) {
        ?>
				<?php 
        $amount = $price['amount'];
        $limit = isset($price['limit']) ? $price['limit'] : '';
        $bought = isset($price['bought']) ? $price['bought'] : 0;
        $allgone = false;
        if ($bought == absint($limit) && '' != $limit) {
            $allgone = true;
        }
        if (edd_use_taxes() && edd_taxes_on_prices()) {
            $amount += edd_calculate_tax($amount);
        }
        ?>
				<li class="atcf-price-option pledge-level <?php 
        echo $allgone ? 'inactive' : null;
        ?>
"  data-pri="<?php 
        echo edd_sanitize_amount($amount);
        ?>
"  data-price="<?php 
        echo edd_sanitize_amount($amount);
        ?>
-<?php 
        echo esc_attr($key);
        ?>
">
					<div class="clear">
						<h3><label><!-- <label for="<?php 
        echo esc_attr('edd_price_option_' . $download_id . '_' . $key);
        ?>
"> -->
							<?php 
        if ($campaign->is_active()) {
            if (!$allgone) {
                printf('<input type="radio" name="edd_options[price_id][]" id="%1$s" class="%2$s edd_price_options_input" value="%3$s"/>', esc_attr('edd_price_option_' . $download_id . '_' . $key . '_' . $uid), esc_attr('edd_price_option_' . $download_id), esc_attr($key));
            }
        }
        ?>
  
							<?php 
        echo edd_currency_filter(edd_format_amount($amount));
        ?>
						</label></h3>
						
						<div class="backers hidden">
							<div class="backer-count">
								<i class="icon-user"></i> <?php 
        printf(_n('1 Backer', '%1$s Backers', $bought, 'atcf'), $bought);
        ?>
							</div>
							<?php 
        if ('' != $limit && !$allgone) {
            ?>
								<small class="limit"><?php 
            printf(__('Limit of %d &mdash; %d remaining', 'atcf'), $limit, $limit - $bought);
            ?>
</small>
							<?php 
        } elseif ($allgone) {
            ?>
								<small class="gone"><?php 
            _e('All gone!', 'atcf');
            ?>
</small>
							<?php 
        }
        ?>
						</div>

					</div>
					<?php 
        //echo wpautop( wp_kses_data( $price[ 'name' ] ) );
        ?>
				</li>

			<?php 
    }
    ?>
			<li class="price-custom">
				<div class="campaign-price-input">
					<div class="price-wrapper"><span class="title"><?php 
    _e('Amount: ', TEXTDOMAIN);
    ?>
</span><input type="text" name="atcf_custom_price" value="" /></div>
				</div>	
			</li>

		</ul>
	</div><!--end .edd_price_options-->
<?php 
}
 /**
  * Add a download to a given payment
  *
  * @since 2.5
  * @param int  $download_id The download to add
  * @param int  $args Other arguments to pass to the function
  * @return void
  */
 public function add_download($download_id = 0, $args = array(), $options = array())
 {
     $download = new EDD_Download($download_id);
     // Bail if this post isn't a download
     if (!$download || $download->post_type !== 'download') {
         return false;
     }
     // Set some defaults
     $defaults = array('quantity' => 1, 'price_id' => false, 'item_price' => 0.0, 'discount' => 0, 'tax' => 0.0, 'fees' => array());
     $args = wp_parse_args(apply_filters('edd_payment_add_download_args', $args, $download->ID), $defaults);
     // Allow overriding the price
     if ($args['item_price']) {
         $item_price = $args['item_price'];
     } else {
         // Deal with variable pricing
         if (edd_has_variable_prices($download->ID)) {
             $prices = get_post_meta($download->ID, 'edd_variable_prices', true);
             if ($args['price_id'] && array_key_exists($args['price_id'], (array) $prices)) {
                 $item_price = $prices[$args['price_id']]['amount'];
             } else {
                 $item_price = edd_get_lowest_price_option($download->ID);
                 $args['price_id'] = edd_get_lowest_price_id($download->ID);
             }
         } else {
             $item_price = edd_get_download_price($download->ID);
         }
     }
     // Sanitizing the price here so we don't have a dozen calls later
     $item_price = edd_sanitize_amount($item_price);
     $quantity = edd_item_quantities_enabled() ? absint($args['quantity']) : 1;
     $amount = round($item_price * $quantity, edd_currency_decimal_filter());
     if (!empty($args['fees'])) {
         foreach ($args['fees'] as $key => $fee) {
             if (empty($fee['download_id'])) {
                 $args['fees'][$key]['download_id'] = $download_id;
             }
             $this->add_fee($args['fees'][$key], false);
         }
     }
     // Setup the downloads meta item
     $new_download = array('id' => $download->ID, 'quantity' => $quantity, 'fees' => $args['fees']);
     $default_options = array('quantity' => $quantity);
     if (!empty($args['price_id'])) {
         $default_options['price_id'] = (int) $args['price_id'];
     }
     $options = wp_parse_args($options, $default_options);
     $new_download['options'] = $options;
     $this->downloads[] = $new_download;
     $discount = $args['discount'];
     $subtotal = $amount;
     $tax = $args['tax'];
     if (edd_prices_include_tax()) {
         $subtotal -= round($tax, edd_currency_decimal_filter());
     }
     $total = $subtotal - $discount + $tax;
     // Do not allow totals to go negatve
     if ($total < 0) {
         $total = 0;
     }
     // Silly item_number array
     $item_number = array('id' => $download->ID, 'quantity' => $quantity, 'options' => $options);
     $this->cart_details[] = array('name' => $download->post_title, 'id' => $download->ID, 'item_number' => $item_number, 'item_price' => round($item_price, edd_currency_decimal_filter()), 'quantity' => $quantity, 'discount' => $discount, 'subtotal' => round($subtotal, edd_currency_decimal_filter()), 'tax' => round($tax, edd_currency_decimal_filter()), 'fees' => $args['fees'], 'price' => round($total, edd_currency_decimal_filter()));
     $added_download = end($this->cart_details);
     $added_download['action'] = 'add';
     $this->pending['downloads'][] = $added_download;
     reset($this->cart_details);
     $this->increase_subtotal($subtotal - $discount);
     $this->increase_tax($tax);
     return true;
 }
 /**
  * Perform some sanitization on the amount field including not allowing negative values by default
  *
  * @since  2.6.5
  * @param  float $price The price to sanitize
  * @return float        A sanitized price
  */
 public function sanitize_price($price)
 {
     $allow_negative_prices = apply_filters('edd_allow_negative_prices', false);
     if (!$allow_negative_prices && $price < 0) {
         $price = 0;
     }
     return edd_sanitize_amount($price);
 }
/**
 * Campaign Configuration
 *
 * Hook into EDD Download Information and add a bit more stuff.
 * These are all things that can be updated while the campaign runs/before
 * being published.
 *
 * @since Astoundify Crowdfunding 0.1-alpha
 *
 * @return void
 */
function _atcf_metabox_campaign_info()
{
    global $post, $edd_options, $wp_locale;
    /** Verification Field */
    wp_nonce_field('cf', 'cf-save');
    $campaign = atcf_get_campaign($post);
    $end_date = $campaign->end_date();
    if (!$end_date && !$campaign->is_endless()) {
        $min = isset($edd_options['atcf_campaign_length_min']) ? $edd_options['atcf_campaign_length_min'] : 14;
        $max = isset($edd_options['atcf_campaign_length_max']) ? $edd_options['atcf_campaign_length_max'] : 48;
        $start = apply_filters('atcf_shortcode_submit_field_length_start', round(($min + $max) / 2));
        $end_date = date('Y-m-d h:i:s', time() + $start * 86400);
    }
    $jj = mysql2date('d', $end_date);
    $mm = mysql2date('m', $end_date);
    $aa = mysql2date('Y', $end_date);
    $hh = mysql2date('H', $end_date);
    $mn = mysql2date('i', $end_date);
    $ss = mysql2date('s', $end_date);
    do_action('atcf_metabox_campaign_info_before', $campaign);
    $types = atcf_campaign_types();
    ?>
	<p>
		<label for="_campaign_featured">
			<input type="checkbox" name="_campaign_featured" id="_campaign_featured" value="1" <?php 
    checked(1, $campaign->featured());
    ?>
 />
			<?php 
    _e('Featured campaign', 'atcf');
    ?>
		</label>
	</p>

	<p>
		<label for="_campaign_physical">
			<input type="checkbox" name="_campaign_physical" id="_campaign_physical" value="1" <?php 
    checked(1, $campaign->needs_shipping());
    ?>
 />
			<?php 
    _e('Collect shipping information on checkout', 'atcf');
    ?>
		</label>
	</p>

	<p>
		<strong><?php 
    _e('Funding Type:', 'atcf');
    ?>
</strong>
	</p>

	<p>
		<?php 
    foreach (atcf_campaign_types_active() as $key => $desc) {
        ?>
		<label for="campaign_type[<?php 
        echo esc_attr($key);
        ?>
]"><input type="radio" name="campaign_type" id="campaign_type[<?php 
        echo esc_attr($key);
        ?>
]" value="<?php 
        echo esc_attr($key);
        ?>
" <?php 
        checked($key, $campaign->type());
        ?>
 /> <strong><?php 
        echo $types[$key]['title'];
        ?>
</strong> &mdash; <?php 
        echo $types[$key]['description'];
        ?>
</label><br />
		<?php 
    }
    ?>
	</p>

	<p>
		<?php 
    $goal_args = array('name' => 'campaign_goal', 'value' => esc_attr(edd_format_amount(edd_sanitize_amount($campaign->goal(false)))), 'class' => 'edd-price-field');
    if ('before' == edd_get_option('currency_position', 'before')) {
        echo edd_currency_filter('');
        echo EDD()->html->text($goal_args);
    } else {
        echo EDD()->html->text($goal_args);
        echo edd_currency_filter('');
    }
    ?>
	</p>
	<p>
		<label for="campaign_location"><strong><?php 
    _e('Location:', 'atcf');
    ?>
</strong></label><br />
		<input type="text" name="campaign_location" id="campaign_location" value="<?php 
    echo esc_attr($campaign->location());
    ?>
" class="regular-text" />
	</p>

	<p>
		<label for="campaign_author"><strong><?php 
    _e('Author:', 'atcf');
    ?>
</strong></label><br />
		<input type="text" name="campaign_author" id="campaign_author" value="<?php 
    echo esc_attr($campaign->author());
    ?>
" class="regular-text" />
	</p>

	<p>
		<label for="campaign_email"><strong><?php 
    _e('Contact Email:', 'atcf');
    ?>
</strong></label><br />
		<input type="text" name="campaign_contact_email" id="campaign_contact_email" value="<?php 
    echo esc_attr($campaign->contact_email());
    ?>
" class="regular-text" />
	</p>

	<style>#end-aa { width: 3.4em } #end-jj, #end-hh, #end-mn { width: 2em; }</style>

	<p>
		<strong><?php 
    _e('End Date:', 'atcf');
    ?>
</strong><br />

		<select id="end-mm" name="end-mm">
			<?php 
    for ($i = 1; $i < 13; $i = $i + 1) {
        $monthnum = zeroise($i, 2);
        ?>
				<option value="<?php 
        echo $monthnum;
        ?>
" <?php 
        selected($monthnum, $mm);
        ?>
>
				<?php 
        printf('%1$s-%2$s', $monthnum, $wp_locale->get_month_abbrev($wp_locale->get_month($i)));
        ?>
				</option>
			<?php 
    }
    ?>
		</select>

		<input type="text" id="end-jj" name="end-jj" value="<?php 
    echo esc_attr($jj);
    ?>
" size="2" maxlength="2" autocomplete="off" />,
		<input type="text" id="end-aa" name="end-aa" value="<?php 
    echo esc_attr($aa);
    ?>
" size="4" maxlength="4" autocomplete="off" /> @
		<input type="text" id="end-hh" name="end-hh" value="<?php 
    echo esc_attr($hh);
    ?>
" size="2" maxlength="2" autocomplete="off" /> :
		<input type="text" id="end-mn" name="end-mn" value="<?php 
    echo esc_attr($mn);
    ?>
" size="2" maxlength="2" autocomplete="off" />
		<input type="hidden" id="end-ss" name="end-ss" value="<?php 
    echo esc_attr($ss);
    ?>
" />
		<input type="hidden" id="campaign_end_date" name="campaign_end_date" value="1" />
	</p>

	<p>
		<label for="campaign_endless">
			<input type="checkbox" name="campaign_endless" id="campaign_endless" value="1" <?php 
    checked(1, $campaign->is_endless());
    ?>
> <?php 
    printf(__('This %s never ends', 'atcf'), strtolower(edd_get_label_singular()));
    ?>
		</label>
	</p>
<?php 
    do_action('atcf_metabox_campaign_info_after', $campaign);
}
 /**
  * Sanitize the variable prices
  *
  * Ensures prices are correctly mapped to an array starting with an index of 0
  *
  * @since 2.5
  * @param array $prices Variable prices
  * @return array $prices Array of the remapped variable prices
  */
 function sanitize_variable_prices($prices = array())
 {
     $prices = $this->remove_blank_rows($prices);
     if (!is_array($prices)) {
         return array();
     }
     foreach ($prices as $id => $price) {
         if (empty($price['amount']) && empty($price['name'])) {
             unset($prices[$id]);
             continue;
         } elseif (empty($price['amount'])) {
             $price['amount'] = 0;
         }
         $prices[$id]['amount'] = edd_sanitize_amount($price['amount']);
     }
     return $prices;
 }
 /**
  * Calculate the total fee amount
  *
  * Can be negative
  *
  * @access public
  * @since 1.5
  * @uses EDD_Fees::get_fees()
  * @uses EDD_Fees::has_fees()
  * @param int $download_id The download ID whose fees to retrieve
  * @return float $total Total fee amount
  */
 public function total($download_id = 0)
 {
     $fees = $this->get_fees('all', $download_id);
     $total = (double) 0.0;
     if ($this->has_fees('all')) {
         foreach ($fees as $fee) {
             $total += edd_sanitize_amount($fee['amount']);
         }
     }
     return edd_sanitize_amount($total);
 }
 /**
  * Process a step
  *
  * @since 2.6
  * @return bool
  */
 public function process_step()
 {
     $more = false;
     if (!$this->can_import()) {
         wp_die(__('You do not have permission to import data.', 'edd'), __('Error', 'edd'), array('response' => 403));
     }
     $csv = new parseCSV();
     $csv->auto($this->file);
     if ($csv->data) {
         $i = 0;
         $more = true;
         foreach ($csv->data as $key => $row) {
             // Done with this batch
             if ($i >= 19) {
                 break;
             }
             // Import Download
             $args = array('post_type' => 'download', 'post_title' => '', 'post_name' => '', 'post_status' => '', 'post_author' => '', 'post_date' => '', 'post_content' => '', 'post_excerpt' => '');
             foreach ($args as $key => $field) {
                 if (!empty($this->field_mapping[$key]) && !empty($row[$this->field_mapping[$key]])) {
                     $args[$key] = $row[$this->field_mapping[$key]];
                 }
             }
             $download_id = wp_insert_post($args);
             // setup categories
             if (!empty($row[$this->field_mapping['categories']])) {
                 $categories = $this->str_to_array($row[$this->field_mapping['categories']]);
                 if (!empty($categories)) {
                     wp_set_object_terms($download_id, $terms, 'download_category');
                 }
             }
             // setup tags
             if (!empty($row[$this->field_mapping['tags']])) {
                 $tags = $this->str_to_array($row[$this->field_mapping['tags']]);
                 if (!empty($tags)) {
                     wp_set_object_terms($download_id, $terms, 'download_tag');
                 }
             }
             // setup price(s)
             if (!empty($row[$this->field_mapping['price']])) {
                 $price = $row[$this->field_mapping['price']];
                 if (is_numeric($price)) {
                     update_post_meta($download_id, 'edd_price', edd_sanitize_amount($price));
                 } else {
                     $prices = $this->str_to_array($price);
                     if (!empty($prices)) {
                         $variable_prices = array();
                         foreach ($prices as $price) {
                             // See if this matches the EDD Download export for variable prices
                             if (false !== strpos($price, ':')) {
                                 $price = array_map('trim', explode(':', $price));
                                 $variable_prices[] = array('name' => $price[0], 'amount' => $price[1]);
                             }
                         }
                         update_post_meta($download_id, 'edd_variable_prices', $variable_prices);
                     }
                 }
             }
             // setup files
             // setup other metadata
             // Once download is imported, remove row
             unset($csv->data[$key]);
             $i++;
         }
         $csv->save();
     }
     return $more;
 }
Example #23
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', '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;
}
 /**
  * Calculate the total fee amount
  *
  * Can be negative
  *
  * @access public
  * @since 1.5
  * @uses EDD_Fees::get_fees()
  * @uses EDD_Fees::has_fees()
  * @return float $total Total fee amount
  */
 public function total()
 {
     $fees = $this->get_fees();
     $total = (double) 0.0;
     if ($this->has_fees()) {
         foreach ($fees as $fee) {
             $total += $fee['amount'];
         }
     }
     return edd_sanitize_amount($total);
 }
/**
 * Process PayPal Purchase
 *
 * @since 1.0
 * @param array   $purchase_data Purchase Data
 * @return void
 */
function edd_process_paypal_purchase($purchase_data)
{
    if (!wp_verify_nonce($purchase_data['gateway_nonce'], 'edd-gateway')) {
        wp_die(__('Nonce verification has failed', 'edd'), __('Error', 'edd'), array('response' => 403));
    }
    // Collect payment data
    $payment_data = array('price' => $purchase_data['price'], 'date' => $purchase_data['date'], 'user_email' => $purchase_data['user_email'], 'purchase_key' => $purchase_data['purchase_key'], 'currency' => edd_get_currency(), 'downloads' => $purchase_data['downloads'], 'user_info' => $purchase_data['user_info'], 'cart_details' => $purchase_data['cart_details'], 'gateway' => 'paypal', 'status' => !empty($purchase_data['buy_now']) ? 'private' : 'pending');
    // Record the pending payment
    $payment = edd_insert_payment($payment_data);
    // Check payment
    if (!$payment) {
        // Record the error
        edd_record_gateway_error(__('Payment Error', 'edd'), sprintf(__('Payment creation failed before sending buyer to PayPal. Payment data: %s', 'edd'), json_encode($payment_data)), $payment);
        // Problems? send back
        edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
    } else {
        // Only send to PayPal if the pending payment is created successfully
        $listener_url = add_query_arg('edd-listener', 'IPN', home_url('index.php'));
        // Get the success url
        $return_url = add_query_arg(array('payment-confirmation' => 'paypal', 'payment-id' => $payment), get_permalink(edd_get_option('success_page', false)));
        // Get the PayPal redirect uri
        $paypal_redirect = trailingslashit(edd_get_paypal_redirect()) . '?';
        // Setup PayPal arguments
        $paypal_args = array('business' => edd_get_option('paypal_email', false), 'email' => $purchase_data['user_email'], 'first_name' => $purchase_data['user_info']['first_name'], 'last_name' => $purchase_data['user_info']['last_name'], 'invoice' => $purchase_data['purchase_key'], 'no_shipping' => '1', 'shipping' => '0', 'no_note' => '1', 'currency_code' => edd_get_currency(), 'charset' => get_bloginfo('charset'), 'custom' => $payment, 'rm' => '2', 'return' => $return_url, 'cancel_return' => edd_get_failed_transaction_uri('?payment-id=' . $payment), 'notify_url' => $listener_url, 'page_style' => edd_get_paypal_page_style(), 'cbt' => get_bloginfo('name'), 'bn' => 'EasyDigitalDownloads_SP');
        if (!empty($purchase_data['user_info']['address'])) {
            $paypal_args['address1'] = $purchase_data['user_info']['address']['line1'];
            $paypal_args['address2'] = $purchase_data['user_info']['address']['line2'];
            $paypal_args['city'] = $purchase_data['user_info']['address']['city'];
            $paypal_args['country'] = $purchase_data['user_info']['address']['country'];
        }
        $paypal_extra_args = array('cmd' => '_cart', 'upload' => '1');
        $paypal_args = array_merge($paypal_extra_args, $paypal_args);
        // Add cart items
        $i = 1;
        foreach ($purchase_data['cart_details'] as $item) {
            $item_amount = round($item['subtotal'] / $item['quantity'] - $item['discount'] / $item['quantity'], 2);
            if ($item_amount <= 0) {
                $item_amount = 0;
            }
            $paypal_args['item_name_' . $i] = stripslashes_deep(html_entity_decode(edd_get_cart_item_name($item), ENT_COMPAT, 'UTF-8'));
            $paypal_args['quantity_' . $i] = $item['quantity'];
            $paypal_args['amount_' . $i] = $item_amount;
            if (edd_use_skus()) {
                $paypal_args['item_number_' . $i] = edd_get_download_sku($item['id']);
            }
            $i++;
        }
        // Calculate discount
        $discounted_amount = 0.0;
        if (!empty($purchase_data['fees'])) {
            $i = empty($i) ? 1 : $i;
            foreach ($purchase_data['fees'] as $fee) {
                if (floatval($fee['amount']) > '0') {
                    // this is a positive fee
                    $paypal_args['item_name_' . $i] = stripslashes_deep(html_entity_decode(wp_strip_all_tags($fee['label']), ENT_COMPAT, 'UTF-8'));
                    $paypal_args['quantity_' . $i] = '1';
                    $paypal_args['amount_' . $i] = edd_sanitize_amount($fee['amount']);
                    $i++;
                } else {
                    // This is a negative fee (discount)
                    $discounted_amount += abs($fee['amount']);
                }
            }
        }
        if ($discounted_amount > '0') {
            $paypal_args['discount_amount_cart'] = edd_sanitize_amount($discounted_amount);
        }
        // Add taxes to the cart
        if (edd_use_taxes()) {
            $paypal_args['tax_cart'] = edd_sanitize_amount($purchase_data['tax']);
        }
        $paypal_args = apply_filters('edd_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);
        // Get rid of cart contents
        edd_empty_cart();
        // Redirect to PayPal
        wp_redirect($paypal_redirect);
        exit;
    }
}
 /**
  * Get Downloads Earning Points 
  * 
  * Handles to return earning points for download
  * 
  * @package Easy Digital Downloads - Points and Rewards
  * @since 1.0.0
  **/
 public function edd_points_get_earning_points($downloadid, $priceoptions = array(), $checkout = false)
 {
     //if this function called from checkout page then use third parameter to TRUE
     global $edd_options;
     $earningpointsbyuser = 0;
     //check if price is for checkout page
     if (!empty($checkout)) {
         //if checkout page
         $edd_price = edd_get_cart_item_price($downloadid, $priceoptions);
     } else {
         //if not is checkout page
         if (edd_has_variable_prices($downloadid)) {
             //check product price is varible pricing enable or not
             $prices = edd_get_variable_prices($downloadid);
             $edd_price = edd_sanitize_amount($prices[0]['amount']);
         } else {
             //get download price
             $edd_price = edd_get_download_price($downloadid);
         }
         //end else
     }
     //end else
     //get download points for download level from meta box
     $downloadearnpoints = $this->edd_points_get_download_earn_points($downloadid);
     if (is_numeric($downloadearnpoints)) {
         return $downloadearnpoints;
     }
     //check if points of download are set in category level
     $downloadearnpoints = $this->edd_points_get_category_earn_points($downloadid);
     if (is_numeric($downloadearnpoints)) {
         return $downloadearnpoints;
     }
     //calculate the earn points from price
     $earningpointsbyuser = $this->edd_points_calculate_earn_points_from_price($edd_price);
     // get download points based on global setting
     return $earningpointsbyuser;
 }
 /**
  * save the input values when the submission form is submitted
  *
  * @since 2.0
  *
  * @return void
  */
 function edd_fes_simple_shipping_save_custom_fields($post_id)
 {
     if (isset($_POST['edd_simple_shipping']) && isset($_POST['edd_simple_shipping']['enabled'])) {
         $domestic = !empty($_POST['edd_simple_shipping']['domestic']) ? edd_sanitize_amount($_POST['edd_simple_shipping']['domestic']) : 0;
         $international = !empty($_POST['edd_simple_shipping']['international']) ? edd_sanitize_amount($_POST['edd_simple_shipping']['international']) : 0;
         update_post_meta($post_id, '_edd_enable_shipping', '1');
         update_post_meta($post_id, '_edd_shipping_domestic', $domestic);
         update_post_meta($post_id, '_edd_shipping_international', $international);
         $prices = edd_get_variable_prices($post_id);
         if (!empty($prices)) {
             foreach ($prices as $price_id => $price) {
                 $prices[$price_id]['shipping'] = '1';
             }
             update_post_meta($post_id, 'edd_variable_prices', $prices);
         }
     } else {
         delete_post_meta($post_id, '_edd_enable_shipping');
     }
 }
/**
 * Get Purchase Status for User
 *
 * Retrieves the purchase count and the total amount spent for a specific user
 *
 * @access      public
 * @since       1.6
 * @param       $user int|string - the ID or email of the customer to retrieve stats for
 * @param       $mode string - "test" or "live"
 * @return      array
 */
function edd_get_purchase_stats_by_user($user = '')
{
    if (is_email($user)) {
        $field = 'email';
    } elseif (is_numeric($user)) {
        $field = 'user_id';
    }
    $customer = EDD()->customers->get_by($field, $user);
    $stats['purchases'] = absint($customer->purchase_count);
    $stats['total_spent'] = edd_sanitize_amount($customer->purchase_value);
    return (array) apply_filters('edd_purchase_stats_by_user', $stats, $user);
}
/**
 * Retrieves most expensive price option of a variable priced download
 *
 * @since 1.4.4
 * @param int $download_id ID of the download
 * @return float Amount of the highest price
 */
function edd_get_highest_price_option($download_id = 0)
{
    if (empty($download_id)) {
        $download_id = get_the_ID();
    }
    if (!edd_has_variable_prices($download_id)) {
        return edd_get_download_price($download_id);
    }
    $prices = edd_get_variable_prices($download_id);
    $high = 0.0;
    if (!empty($prices)) {
        $max = 0;
        foreach ($prices as $key => $price) {
            if (empty($price['amount'])) {
                continue;
            }
            $max = max($max, $price['amount']);
            if ($price['amount'] == $max) {
                $max_id = $key;
            }
        }
        $high = $prices[$max_id]['amount'];
    }
    return edd_sanitize_amount($high);
}
/**
 * Convert Price
 * 
 * Handles to return converted price
 * with appropriate method which is seleted
 * in backend
 *
 * @package Easy Digital Downloads - Currency Converter
 * @since 1.0.0
 **/
function edd_currency_get_converted_price($price)
{
    global $edd_options;
    $edd_currency = edd_get_currency();
    $stored_currency = edd_currency_get_stored_currency();
    $exchange_rates = edd_currency_get_exchange_rates();
    $base_rate = edd_currency_get_exchange_base_rates();
    $price = edd_sanitize_amount($price);
    // sanitized amount by stripping out thousands separators
    if (isset($exchange_rates[$stored_currency])) {
        // removed code from version 1.0.4
        //check base currency & base rates are same or not
        /*if( $edd_currency == $base_rate ) {
        			$price = $price * $exchange_rates[$stored_currency];
        		} elseif( $stored_currency == $base_rate ) { 
        			$price = $price / $exchange_rates[$edd_currency];
        		} else {*/
        $price = $price / $exchange_rates[$edd_currency];
        $price = $price * $exchange_rates[$stored_currency];
        //}
    }
    return apply_filters('edd_currnency_get_convert_price', edd_format_amount($price));
}