/**
  * 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;
 }
 /**
  * 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()
 {
     if ($this->step == 1) {
         $this->delete_data('edd_temp_recount_earnings');
     }
     $total = get_option('edd_temp_recount_earnings', false);
     if (false === $total) {
         $total = (double) 0;
         $this->store_data('edd_temp_recount_earnings', $total);
     }
     $accepted_statuses = apply_filters('edd_recount_accepted_statuses', array('publish', 'revoked'));
     $args = apply_filters('edd_recount_earnings_args', array('number' => $this->per_step, 'page' => $this->step, 'status' => $accepted_statuses, 'fields' => 'ids'));
     $payments = edd_get_payments($args);
     if (!empty($payments)) {
         foreach ($payments as $payment) {
             $total += edd_get_payment_amount($payment);
         }
         if ($total < 0) {
             $totals = 0;
         }
         $total = round($total, edd_currency_decimal_filter());
         $this->store_data('edd_temp_recount_earnings', $total);
         return true;
     }
     update_option('edd_earnings_total', $total);
     set_transient('edd_earnings_total', $total, 86400);
     return false;
 }
 /**
  * Get the Export Data
  *
  * @access public
  * @since 1.4.4
  * @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()
 {
     global $wpdb, $edd_options;
     $data = array();
     $payments = edd_get_payments(array('offset' => 0, 'number' => -1, 'mode' => edd_is_test_mode() ? 'test' : 'live', 'status' => isset($_POST['edd_export_payment_status']) ? $_POST['edd_export_payment_status'] : 'any', 'month' => isset($_POST['month']) ? absint($_POST['month']) : date('n'), 'year' => isset($_POST['year']) ? absint($_POST['year']) : date('Y')));
     foreach ($payments as $payment) {
         $payment_meta = edd_get_payment_meta($payment->ID);
         $user_info = edd_get_payment_meta_user_info($payment->ID);
         $downloads = edd_get_payment_meta_cart_details($payment->ID);
         $total = isset($payment_meta['amount']) ? $payment_meta['amount'] : 0.0;
         $user_id = isset($user_info['id']) && $user_info['id'] != -1 ? $user_info['id'] : $user_info['email'];
         $products = '';
         $skus = '';
         if ($downloads) {
             foreach ($downloads as $key => $download) {
                 // Download ID
                 $id = isset($payment_meta['cart_details']) ? $download['id'] : $download;
                 // If the download has variable prices, override the default price
                 $price_override = isset($payment_meta['cart_details']) ? $download['price'] : null;
                 $price = edd_get_download_final_price($id, $user_info, $price_override);
                 // Display the Downoad Name
                 $products .= get_the_title($id) . ' - ';
                 if (edd_use_skus()) {
                     $sku = edd_get_download_sku($id);
                     if (!empty($sku)) {
                         $skus .= $sku;
                     }
                 }
                 if (isset($downloads[$key]['item_number']) && isset($downloads[$key]['item_number']['options'])) {
                     $price_options = $downloads[$key]['item_number']['options'];
                     if (isset($price_options['price_id'])) {
                         $products .= edd_get_price_option_name($id, $price_options['price_id']) . ' - ';
                     }
                 }
                 $products .= html_entity_decode(edd_currency_filter($price));
                 if ($key != count($downloads) - 1) {
                     $products .= ' / ';
                     if (edd_use_skus()) {
                         $skus .= ' / ';
                     }
                 }
             }
         }
         if (is_numeric($user_id)) {
             $user = get_userdata($user_id);
         } else {
             $user = false;
         }
         $data[] = array('id' => $payment->ID, 'email' => $payment_meta['email'], 'first' => $user_info['first_name'], 'last' => $user_info['last_name'], 'products' => $products, 'skus' => $skus, 'amount' => html_entity_decode(edd_format_amount($total)), 'tax' => html_entity_decode(edd_get_payment_tax($payment->ID, $payment_meta)), 'discount' => isset($user_info['discount']) && $user_info['discount'] != 'none' ? $user_info['discount'] : __('none', 'edd'), 'gateway' => edd_get_gateway_admin_label(get_post_meta($payment->ID, '_edd_payment_gateway', true)), 'key' => $payment_meta['key'], 'date' => $payment->post_date, 'user' => $user ? $user->display_name : __('guest', 'edd'), 'status' => edd_get_payment_status($payment, true));
         if (!edd_use_skus()) {
             unset($data['skus']);
         }
     }
     $data = apply_filters('edd_export_get_data', $data);
     $data = apply_filters('edd_export_get_data_' . $this->export_type, $data);
     return $data;
 }
/**
 * Count Payments
 *
 * Returns the total number of payments recorded.
 *
 * @access      public
 * @since       1.0 
 * @return      integer
*/
function edd_count_payments($mode, $user = null)
{
    $payments = edd_get_payments(array('offset' => 0, 'number' => -1, 'mode' => $mode, 'orderby' => 'ID', 'order' => 'DESC', 'user' => $user));
    $count = 0;
    if ($payments) {
        $count = count($payments);
    }
    return $count;
}
/**
 * Count Payments
 *
 * Returns the total number of payments recorded.
 *
 * @access      public
 * @since       1.0
 * @deprecated 	1.2
 * @return      integer
*/
function edd_count_payments($mode, $user = null)
{
    _edd_deprecated_function(__FUNCTION__, '1.2');
    $payments = edd_get_payments(array('offset' => 0, 'number' => -1, 'mode' => $mode, 'orderby' => 'ID', 'order' => 'DESC', 'user' => $user));
    $count = 0;
    if ($payments) {
        $count = count($payments);
    }
    return $count;
}
 /**
  * Get the Export Data
  *
  * @access public
  * @since 2.5.3
  * @global object $wpdb Used to query the database using the WordPress
  *   Database API
  * @return array $data The data for the CSV file
  */
 public function send_data()
 {
     $data = array();
     $args = array('number' => 30, 'page' => $this->step, 'status' => 'publish');
     if (!empty($this->start) || !empty($this->end)) {
         $args['date_query'] = array(array('after' => date('Y-n-d H:i:s', strtotime($this->start)), 'before' => date('Y-n-d H:i:s', strtotime($this->end)), 'inclusive' => true));
     }
     $payments = edd_get_payments($args);
     if ($payments) {
         $mailchimp_ecommerce = new EDD_MC_Ecommerce_360();
         foreach ($payments as $payment) {
             $mailchimp_ecommerce->record_ecommerce360_purchase($payment->ID);
         }
         return true;
     }
     return false;
 }
/**
 * Display Upgrade Notices
 *
 * @since 1.3.1
 * @return void
*/
function edd_show_upgrade_notices()
{
    if (isset($_GET['page']) && $_GET['page'] == 'edd-upgrades') {
        return;
    }
    // Don't show notices on the upgrades page
    $edd_version = get_option('edd_version');
    if (!$edd_version) {
        // 1.3 is the first version to use this option so we must add it
        $edd_version = '1.3';
    }
    $edd_version = preg_replace('/[^0-9.].*/', '', $edd_version);
    if (!get_option('edd_payment_totals_upgraded') && !get_option('edd_version')) {
        if (wp_count_posts('edd_payment')->publish < 1) {
            return;
        }
        // No payment exist yet
        // The payment history needs updated for version 1.2
        $url = add_query_arg('edd-action', 'upgrade_payments');
        $upgrade_notice = sprintf(__('The Payment History needs to be updated. %s', 'edd'), '<a href="' . wp_nonce_url($url, 'edd_upgrade_payments_nonce') . '">' . __('Click to Upgrade', 'edd') . '</a>');
        add_settings_error('edd-notices', 'edd-payments-upgrade', $upgrade_notice, 'error');
    }
    if (version_compare($edd_version, '1.3.2', '<') && !get_option('edd_logs_upgraded')) {
        printf('<div class="updated"><p>' . esc_html__('The Purchase and File Download History in Easy Digital Downloads needs to be upgraded, click %shere%s to start the upgrade.', 'edd') . '</p></div>', '<a href="' . esc_url(admin_url('options.php?page=edd-upgrades')) . '">', '</a>');
    }
    if (version_compare($edd_version, '1.3.4', '<') || version_compare($edd_version, '1.4', '<')) {
        printf('<div class="updated"><p>' . esc_html__('Easy Digital Downloads needs to upgrade the plugin pages, click %shere%s to start the upgrade.', 'edd') . '</p></div>', '<a href="' . esc_url(admin_url('options.php?page=edd-upgrades')) . '">', '</a>');
    }
    if (version_compare($edd_version, '1.5', '<')) {
        printf('<div class="updated"><p>' . esc_html__('Easy Digital Downloads needs to upgrade the database, click %shere%s to start the upgrade.', 'edd') . '</p></div>', '<a href="' . esc_url(admin_url('options.php?page=edd-upgrades')) . '">', '</a>');
    }
    if (version_compare($edd_version, '2.0', '<')) {
        printf('<div class="updated"><p>' . esc_html__('Easy Digital Downloads needs to upgrade the database, click %shere%s to start the upgrade.', 'edd') . '</p></div>', '<a href="' . esc_url(admin_url('options.php?page=edd-upgrades')) . '">', '</a>');
    }
    if (EDD()->session->get('upgrade_sequential') && edd_get_payments()) {
        printf('<div class="updated"><p>' . __('Easy Digital Downloads needs to upgrade past order numbers to make them sequential, click <a href="%s">here</a> to start the upgrade.', 'edd') . '</p></div>', admin_url('index.php?page=edd-upgrades&edd-upgrade=upgrade_sequential_payment_numbers'));
    }
    if (version_compare($edd_version, '2.1', '<')) {
        printf('<div class="updated"><p>' . esc_html__('Easy Digital Downloads needs to upgrade the customer database, click %shere%s to start the upgrade.', 'edd') . '</p></div>', '<a href="' . esc_url(admin_url('index.php?page=edd-upgrades&edd-upgrade=upgrade_customers_db')) . '">', '</a>');
    }
}
/**
 * Remove sale logs from refunded orders
 *
 * @since  2.4.3
 * @return void
 */
function edd_remove_refunded_sale_logs()
{
    global $wpdb, $edd_logs;
    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;
    $total = isset($_GET['total']) ? absint($_GET['total']) : edd_count_payments()->refunded;
    $refunds = edd_get_payments(array('status' => 'refunded', 'number' => 20, 'page' => $step));
    if (!empty($refunds)) {
        // Refunded Payments found so process them
        foreach ($refunds as $refund) {
            if ('refunded' !== $refund->post_status) {
                continue;
                // Just to be safe
            }
            // Remove related sale log entries
            $edd_logs->delete_logs(null, 'sale', array(array('key' => '_edd_log_payment_id', 'value' => $refund->ID)));
        }
        $step++;
        $redirect = add_query_arg(array('page' => 'edd-upgrades', 'edd-upgrade' => 'remove_refunded_sale_logs', 'step' => $step, 'total' => $total), admin_url('index.php'));
        wp_redirect($redirect);
        exit;
    } else {
        // No more refunded payments found, finish up
        update_option('edd_version', preg_replace('/[^0-9.].*/', '', EDD_VERSION));
        edd_set_upgrade_complete('remove_refunded_sale_logs');
        delete_option('edd_doing_upgrade');
        wp_redirect(admin_url());
        exit;
    }
}
 /**
  * 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);
     }
 }
 /**
  * Retrieve all the data for all the payments
  *
  * @access public
  * @since 1.4
  * @return array $payment_data Array of all the data for the payments
  */
 public function payments_data()
 {
     $payments_data = array();
     if (isset($_GET['paged'])) {
         $page = $_GET['paged'];
     } else {
         $page = 1;
     }
     $per_page = $this->per_page;
     $mode = edd_is_test_mode() ? 'test' : 'live';
     $orderby = isset($_GET['orderby']) ? $_GET['orderby'] : 'ID';
     $order = isset($_GET['order']) ? $_GET['order'] : 'DESC';
     $order_inverse = $order == 'DESC' ? 'ASC' : 'DESC';
     $order_class = strtolower($order_inverse);
     $user = isset($_GET['user']) ? $_GET['user'] : null;
     $status = isset($_GET['status']) ? $_GET['status'] : 'any';
     $meta_key = isset($_GET['meta_key']) ? $_GET['meta_key'] : null;
     $year = isset($_GET['year']) ? $_GET['year'] : null;
     $month = isset($_GET['m']) ? $_GET['m'] : null;
     $day = isset($_GET['day']) ? $_GET['day'] : null;
     $search = isset($_GET['s']) ? sanitize_text_field($_GET['s']) : null;
     $payments = edd_get_payments(array('number' => $per_page, 'page' => isset($_GET['paged']) ? $_GET['paged'] : null, 'mode' => $mode, 'orderby' => $orderby, 'order' => $order, 'user' => $user, 'status' => $status, 'meta_key' => $meta_key, 'year' => $year, 'month' => $month, 'day' => $day, 's' => $search));
     if ($payments) {
         foreach ($payments as $payment) {
             $user_info = edd_get_payment_meta_user_info($payment->ID);
             $cart_details = edd_get_payment_meta_cart_details($payment->ID);
             $user_id = isset($user_info['ID']) && $user_info['ID'] != -1 ? $user_info['ID'] : $user_info['email'];
             $payments_data[] = array('ID' => $payment->ID, 'email' => edd_get_payment_user_email($payment->ID), 'products' => $cart_details, 'amount' => edd_get_payment_amount($payment->ID), 'date' => $payment->post_date, 'user' => $user_id, 'status' => $payment->post_status);
         }
     }
     return $payments_data;
 }
/**
 * Sales Summary Dashboard Widget
 *
 * @access      private
 * @author      Sunny Ratilal
 * @since       1.2.2
*/
function edd_dashboard_sales_widget()
{
    $top_selling_args = array('post_type' => 'download', 'posts_per_page' => 1, 'post_status' => 'publish', 'meta_key' => '_edd_download_sales', 'meta_compare' => '>', 'meta_value' => 0, 'orderby' => 'meta_value_num', 'cache_results' => false, 'update_post_term_cache' => false, 'no_found_rows' => true, 'order' => 'DESC');
    $top_selling = get_posts($top_selling_args);
    ?>
	<div class="table table_current_month">
		<p class="sub"><?php 
    _e('Current Month', 'edd');
    ?>
</p>
		<table>
			<tbody>
				<tr class="first">
					<td class="first b"><?php 
    echo edd_currency_filter(edd_format_amount(edd_get_earnings_by_date(null, date('n'), date('Y'))));
    ?>
</td>
					<td class="t monthly_earnings"><?php 
    _e('Earnings', 'edd');
    ?>
</td>
				</tr>
				<tr>
					<?php 
    $monthly_sales = edd_get_sales_by_date(null, date('n'), date('Y'));
    ?>
					<td class="first b"><?php 
    echo $monthly_sales;
    ?>
</td>
					<td class="t monthly_sales"><?php 
    echo _n('Sale', 'Sales', $monthly_sales, 'edd');
    ?>
</td>
				</tr>
			</tbody>
		</table>
		<p class="label_heading"><?php 
    _e('Last Month', 'edd');
    ?>
</p>
		<div>
			<?php 
    echo __('Earnings', 'edd') . ':&nbsp;<span class="edd_price_label">' . edd_currency_filter(edd_format_amount(edd_get_earnings_by_date(null, date('n') - 1, date('Y')))) . '</span>';
    ?>
		</div>
		<div>
			<?php 
    $last_month_sales = edd_get_sales_by_date(null, date('n') - 1, date('Y'));
    ?>
			<?php 
    echo _n('Sale', 'Sales', $last_month_sales, 'edd') . ':&nbsp;' . '<span class="edd_price_label">' . $last_month_sales . '</span>';
    ?>
		</div>
	</div>
	<div class="table table_totals">
		<p class="sub"><?php 
    _e('Totals', 'edd');
    ?>
</p>
		<table>
			<tbody>
				<tr class="first">
					<td class="b b-earnings"><?php 
    echo edd_currency_filter(edd_format_amount(edd_get_total_earnings()));
    ?>
</td>
					<td class="last t earnings"><?php 
    _e('Total Earnings', 'edd');
    ?>
</td>
				</tr>
				<tr>
					<td class="b b-sales"><?php 
    echo edd_get_total_sales();
    ?>
</td>
					<td class="last t sales"><?php 
    _e('Total Sales', 'edd');
    ?>
</td>
				</tr>
			</tbody>
		</table>
		<?php 
    if ($top_selling) {
        foreach ($top_selling as $list) {
            ?>
				<p class="lifetime_best_selling label_heading"><?php 
            _e('Lifetime Best Selling', 'edd');
            ?>
</p>
				<p><span class="lifetime_best_selling_label"><?php 
            echo edd_get_download_sales_stats($list->ID);
            ?>
</span> <a href="<?php 
            echo get_permalink($list->ID);
            ?>
"><?php 
            echo get_the_title($list->ID);
            ?>
</a></p>
		<?php 
        }
    }
    ?>
	</div>
	<div style="clear: both"></div>
	<?php 
    $payments = edd_get_payments(array('number' => 5, 'mode' => 'live', 'orderby' => 'post_date', 'order' => 'DESC', 'user' => null, 'status' => 'publish', 'meta_key' => null));
    if ($payments) {
        ?>
	<p class="edd_dashboard_widget_subheading"><?php 
        _e('Recent Purchases', 'edd');
        ?>
</p>
	<div class="table recent_purchases">
		<table>
			<tbody>
				<?php 
        foreach ($payments as $payment) {
            $payment_meta = edd_get_payment_meta($payment->ID);
            ?>
				<tr>
					<td><?php 
            echo get_the_title($payment->ID);
            ?>
 - (<?php 
            echo $payment_meta['email'];
            ?>
) - <span class="edd_price_label"><?php 
            echo edd_currency_filter(edd_format_amount(edd_get_payment_amount($payment->ID)));
            ?>
</span> - <a href="#TB_inline?width=640&amp;inlineId=purchased-files-<?php 
            echo $payment->ID;
            ?>
" class="thickbox" title="<?php 
            printf(__('Purchase Details for Payment #%s', 'edd'), $payment->ID);
            ?>
 "><?php 
            _e('View Order Details', 'edd');
            ?>
</a>
						<div id="purchased-files-<?php 
            echo $payment->ID;
            ?>
" style="display:none;">
							<?php 
            $cart_items = edd_get_payment_meta_cart_details($payment->ID);
            if (empty($cart_items) || !$cart_items) {
                $cart_items = maybe_unserialize($payment_meta['downloads']);
            }
            ?>
							<h4><?php 
            echo _n(__('Purchased File', 'edd'), __('Purchased Files', 'edd'), count($cart_items));
            ?>
</h4>
							<ul class="purchased-files-list">
							<?php 
            if ($cart_items) {
                foreach ($cart_items as $key => $cart_item) {
                    echo '<li>';
                    $id = isset($payment_meta['cart_details']) ? $cart_item['id'] : $cart_item;
                    $price_override = isset($payment_meta['cart_details']) ? $cart_item['price'] : null;
                    $user_info = edd_get_payment_meta_user_info($payment->ID);
                    $price = edd_get_download_final_price($id, $user_info, $price_override);
                    echo '<a href="' . admin_url('post.php?post=' . $id . '&action=edit') . '" target="_blank">' . get_the_title($id) . '</a>';
                    echo ' - ';
                    if (isset($cart_items[$key]['item_number'])) {
                        $price_options = $cart_items[$key]['item_number']['options'];
                        if (isset($price_options['price_id'])) {
                            echo edd_get_price_option_name($id, $price_options['price_id']);
                            echo ' - ';
                        }
                    }
                    echo edd_currency_filter(edd_format_amount($price));
                    echo '</li>';
                }
            }
            ?>
							</ul>
							<?php 
            $payment_date = strtotime($payment->post_date);
            ?>
							<p><?php 
            echo __('Date and Time:', 'edd') . ' ' . date_i18n(get_option('date_format'), $payment_date) . ' ' . date_i18n(get_option('time_format'), $payment_date);
            ?>
							<p><?php 
            echo __('Discount used:', 'edd') . ' ';
            if (isset($user_info['discount']) && $user_info['discount'] != 'none') {
                echo $user_info['discount'];
            } else {
                _e('none', 'edd');
            }
            ?>
							<p><?php 
            echo __('Total:', 'edd') . ' ' . edd_currency_filter(edd_format_amount(edd_get_payment_amount($payment->ID)));
            ?>
</p>

							<div class="purcase-personal-details">
								<h4><?php 
            _e('Buyer\'s Personal Details:', 'edd');
            ?>
</h4>
								<ul>
									<li><?php 
            echo __('Name:', 'edd') . ' ' . $user_info['first_name'] . ' ' . $user_info['last_name'];
            ?>
</li>
									<li><?php 
            echo __('Email:', 'edd') . ' ' . $payment_meta['email'];
            ?>
</li>
									<?php 
            do_action('edd_payment_personal_details_list', $payment_meta, $user_info);
            ?>
								</ul>
							</div>
							<?php 
            $gateway = edd_get_payment_gateway($payment->ID);
            if ($gateway) {
                ?>
							<div class="payment-method">
								<h4><?php 
                _e('Payment Method:', 'edd');
                ?>
</h4>
								<span class="payment-method-name"><?php 
                echo edd_get_gateway_admin_label($gateway);
                ?>
</span>
							</div>
							<?php 
            }
            ?>
							<div class="purchase-key-wrap">
								<h4><?php 
            _e('Purchase Key', 'edd');
            ?>
</h4>
								<span class="purchase-key"><?php 
            echo $payment_meta['key'];
            ?>
</span>
							</div>
							<p><a id="edd-close-purchase-details" class="button-secondary" onclick="tb_remove();" title="<?php 
            _e('Close', 'edd');
            ?>
"><?php 
            _e('Close', 'edd');
            ?>
</a></p>
						</div>
					</td>
				</tr>
				<?php 
        }
        // end foreach
        ?>
			</tbody>
		</table>
	</div>
	<?php 
    }
    // end if
}
 /**
  * Apply Points to Previous Orders
  * 
  * Handles to apply points to previous orders
  *
  * @package Easy Digital Downloads - Points and Rewards
  * @since 1.0.0
  */
 public function edd_points_apply_for_previous_orders()
 {
     if (isset($_GET['points_action']) && $_GET['points_action'] == 'apply_points' && isset($_GET['page']) && $_GET['page'] == 'edd-settings') {
         // perform the action in manageable chunks
         $success_count = 0;
         $paymentmode = edd_is_test_mode() ? 'test' : 'live';
         $paymentargs = array('mode' => $paymentmode, 'fields' => 'ids', 'status' => 'publish', 'posts_per_page' => '-1', 'meta_query' => array(array('key' => '_edd_points_order_earned', 'compare' => 'NOT EXISTS')));
         // grab a set of order ids for existing orders with no earned points set
         $payment_ids = edd_get_payments($paymentargs);
         // otherwise go through the results and set the order numbers
         if (is_array($payment_ids)) {
             foreach ($payment_ids as $payment_id) {
                 $payment = get_post($payment_id);
                 $payment_data = edd_get_payment_meta($payment_id);
                 // get cartdata from older order
                 $cartdata = edd_get_payment_meta_cart_details($payment_id);
                 //get cartdata points
                 $checkoutpoints = $this->model->edd_points_get_user_checkout_points($cartdata);
                 //check checkout points should not empty which has redeemed by buyer
                 if (!empty($checkoutpoints)) {
                     //get user points label
                     $pointlable = $this->model->edd_points_get_points_label($checkoutpoints);
                     $post_data = array('post_title' => sprintf(__('%s earned for purchasing the downloads.', 'eddpoints'), $pointlable), 'post_content' => sprintf(__('Get %s for purchasing the downloads.', 'eddpoints'), $pointlable), 'post_author' => $payment->post_author);
                     $log_meta = array('userpoint' => $checkoutpoints, 'events' => 'earned_purchase', 'operation' => 'add');
                     //insert entry in log
                     $this->logs->edd_points_insert_logs($post_data, $log_meta);
                     //update user points
                     edd_points_add_points_to_user($checkoutpoints, $payment->post_author);
                     // set order meta, regardless of whether any points were earned, just so we know the process took place
                     update_post_meta($payment_id, '_edd_points_order_earned', $checkoutpoints);
                 }
                 $success_count++;
             }
             //end foreach loop
         }
         //end if check retrive payment ids are array
         $redirectargs = array('post_type' => 'download', 'page' => 'edd-settings', 'tab' => 'extensions', 'settings-updated' => 'apply_points', 'success_count' => $success_count, 'points_action' => false);
         $redirect_url = add_query_arg($redirectargs, admin_url('edit.php'));
         wp_redirect($redirect_url);
         exit;
     }
     //end if check if there is fulfilling condition proper for applying discount for previous orders
 }
/**
 * Updates week-old+ 'pending' orders to 'abandoned'
 *
 * @since 1.6
 * @return void
*/
function edd_mark_abandoned_orders()
{
    $args = array('status' => 'pending', 'number' => -1);
    add_filter('posts_where', 'edd_filter_where_older_than_week');
    $payments = edd_get_payments($args);
    remove_filter('posts_where', 'edd_filter_where_older_than_week');
    if ($payments) {
        foreach ($payments as $payment) {
            if ('pending' === $payment->post_status) {
                edd_update_payment_status($payment->ID, 'abandoned');
            }
        }
    }
}
/**
 * Looks up purchases by email that match the registering user
 *
 * This is for users that purchased as a guest and then came
 * back and created an account.
 *
 * @access      public
 * @since       1.6
 * @param       $user_id INT - the new user's ID
 * @return      void
 */
function edd_add_past_purchases_to_new_user($user_id)
{
    $email = get_user_meta($user_id, 'user_email', true);
    $mode = edd_is_test_mode() ? 'test' : 'live';
    $payments = edd_get_payments(array('s' => $email, 'mode' => $mode));
    if ($payments) {
        foreach ($payments as $payment) {
            if (intval(edd_get_payment_user_id($payment->ID)) > 0) {
                continue;
            }
            // This payment already associated with an account
            $meta = edd_get_payment_meta($payment->ID);
            $meta['user_info'] = maybe_unserialize($meta['user_info']);
            $meta['user_info']['id'] = $user_id;
            $meta['user_info'] = serialize($meta['user_info']);
            // Store the updated user ID in the payment meta
            update_post_meta($payment->ID, '_edd_payment_meta', $meta);
        }
    }
}
 /**
  * Get the Export Data
  *
  * @access public
  * @since 2.4
  * @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()
 {
     global $wpdb;
     $data = array();
     $args = array('number' => 30, 'page' => $this->step, 'status' => $this->status);
     if (!empty($this->start) || !empty($this->end)) {
         $args['date_query'] = array(array('after' => date('Y-n-d H:i:s', strtotime($this->start)), 'before' => date('Y-n-d H:i:s', strtotime($this->end)), 'inclusive' => true));
     }
     //echo json_encode($args ); exit;
     $payments = edd_get_payments($args);
     if ($payments) {
         foreach ($payments as $payment) {
             $payment_meta = edd_get_payment_meta($payment->ID);
             $user_info = edd_get_payment_meta_user_info($payment->ID);
             $downloads = edd_get_payment_meta_cart_details($payment->ID);
             $total = edd_get_payment_amount($payment->ID);
             $user_id = isset($user_info['id']) && $user_info['id'] != -1 ? $user_info['id'] : $user_info['email'];
             $products = '';
             $skus = '';
             if ($downloads) {
                 foreach ($downloads as $key => $download) {
                     // Download ID
                     $id = isset($payment_meta['cart_details']) ? $download['id'] : $download;
                     // If the download has variable prices, override the default price
                     $price_override = isset($payment_meta['cart_details']) ? $download['price'] : null;
                     $price = edd_get_download_final_price($id, $user_info, $price_override);
                     // Display the Downoad Name
                     $products .= get_the_title($id) . ' - ';
                     if (edd_use_skus()) {
                         $sku = edd_get_download_sku($id);
                         if (!empty($sku)) {
                             $skus .= $sku;
                         }
                     }
                     if (isset($downloads[$key]['item_number']) && isset($downloads[$key]['item_number']['options'])) {
                         $price_options = $downloads[$key]['item_number']['options'];
                         if (isset($price_options['price_id'])) {
                             $products .= edd_get_price_option_name($id, $price_options['price_id'], $payment->ID) . ' - ';
                         }
                     }
                     $products .= html_entity_decode(edd_currency_filter($price));
                     if ($key != count($downloads) - 1) {
                         $products .= ' / ';
                         if (edd_use_skus()) {
                             $skus .= ' / ';
                         }
                     }
                 }
             }
             if (is_numeric($user_id)) {
                 $user = get_userdata($user_id);
             } else {
                 $user = false;
             }
             $data[] = array('id' => $payment->ID, 'seq_id' => edd_get_payment_number($payment->ID), 'email' => $payment_meta['email'], 'first' => $user_info['first_name'], 'last' => $user_info['last_name'], 'address1' => isset($user_info['address']['line1']) ? $user_info['address']['line1'] : '', 'address2' => isset($user_info['address']['line2']) ? $user_info['address']['line2'] : '', 'city' => isset($user_info['address']['city']) ? $user_info['address']['city'] : '', 'state' => isset($user_info['address']['state']) ? $user_info['address']['state'] : '', 'country' => isset($user_info['address']['country']) ? $user_info['address']['country'] : '', 'zip' => isset($user_info['address']['zip']) ? $user_info['address']['zip'] : '', 'products' => $products, 'skus' => $skus, 'amount' => html_entity_decode(edd_format_amount($total)), 'tax' => html_entity_decode(edd_format_amount(edd_get_payment_tax($payment->ID, $payment_meta))), 'discount' => isset($user_info['discount']) && $user_info['discount'] != 'none' ? $user_info['discount'] : __('none', 'edd'), 'gateway' => edd_get_gateway_admin_label(get_post_meta($payment->ID, '_edd_payment_gateway', true)), 'trans_id' => edd_get_payment_transaction_id($payment->ID), 'key' => $payment_meta['key'], 'date' => $payment->post_date, 'user' => $user ? $user->display_name : __('guest', 'edd'), 'status' => edd_get_payment_status($payment, true));
         }
         $data = apply_filters('edd_export_get_data', $data);
         $data = apply_filters('edd_export_get_data_' . $this->export_type, $data);
         return $data;
     }
     return false;
 }
/**
 * Sales Summary Dashboard Widget
 *
 * Builds and renders the Sales Summary dashboard widget. This widget displays
 * the current month's sales and earnings, total sales and earnings best selling
 * downloads as well as recent purchases made on your EDD Store.
 *
 * @author Sunny Ratilal
 * @since 1.2.2
 * @return void
 */
function edd_dashboard_sales_widget()
{
    $top_selling_args = array('post_type' => 'download', 'posts_per_page' => 1, 'post_status' => 'publish', 'meta_key' => '_edd_download_sales', 'meta_compare' => '>', 'meta_value' => 0, 'orderby' => 'meta_value_num', 'update_post_term_cache' => false, 'order' => 'DESC');
    $top_selling = get_posts($top_selling_args);
    ?>
	<div class="edd_dashboard_widget">
		<div class="table table_left table_current_month">
			<p class="sub"><?php 
    _e('Current Month', 'edd');
    ?>
</p>
			<table>
				<tbody>
					<tr class="first">
						<td class="first b"><?php 
    echo edd_currency_filter(edd_format_amount(edd_get_earnings_by_date(null, date('n'), date('Y'))));
    ?>
</td>
						<td class="t monthly_earnings"><?php 
    _e('Earnings', 'edd');
    ?>
</td>
					</tr>
					<tr>
						<?php 
    $monthly_sales = edd_get_sales_by_date(null, date('n'), date('Y'));
    ?>
						<td class="first b"><?php 
    echo $monthly_sales;
    ?>
</td>
						<td class="t monthly_sales"><?php 
    echo _n('Sale', 'Sales', $monthly_sales, 'edd');
    ?>
</td>
					</tr>
				</tbody>
			</table>
			<p class="label_heading"><?php 
    _e('Last Month', 'edd');
    ?>
</p>
			<?php 
    $previous_month = date('n') == 1 ? 12 : date('n') - 1;
    $previous_year = $previous_month == 12 ? date('Y') - 1 : date('Y');
    ?>
			<div>
				<?php 
    echo __('Earnings', 'edd') . ':&nbsp;<span class="edd_price_label">' . edd_currency_filter(edd_format_amount(edd_get_earnings_by_date(null, $previous_month, $previous_year))) . '</span>';
    ?>
			</div>
			<div>
				<?php 
    $last_month_sales = edd_get_sales_by_date(null, $previous_month, $previous_year);
    ?>
				<?php 
    echo _n('Sale', 'Sales', $last_month_sales, 'edd') . ':&nbsp;' . '<span class="edd_price_label">' . $last_month_sales . '</span>';
    ?>
			</div>
		</div>
		<div class="table table_right table_totals">
			<p class="sub"><?php 
    _e('Totals', 'edd');
    ?>
</p>
			<table>
				<tbody>
					<tr class="first">
						<td class="b b-earnings"><?php 
    echo edd_currency_filter(edd_format_amount(edd_get_total_earnings()));
    ?>
</td>
						<td class="last t earnings"><?php 
    _e('Total Earnings', 'edd');
    ?>
</td>
					</tr>
					<tr>
						<td class="b b-sales"><?php 
    echo edd_get_total_sales();
    ?>
</td>
						<td class="last t sales"><?php 
    _e('Total Sales', 'edd');
    ?>
</td>
					</tr>
				</tbody>
			</table>
			<?php 
    if ($top_selling) {
        foreach ($top_selling as $list) {
            ?>
					<p class="lifetime_best_selling label_heading"><?php 
            _e('Lifetime Best Selling', 'edd');
            ?>
</p>
					<p><span class="lifetime_best_selling_label"><?php 
            echo edd_get_download_sales_stats($list->ID);
            ?>
</span> <a href="<?php 
            echo get_permalink($list->ID);
            ?>
"><?php 
            echo get_the_title($list->ID);
            ?>
</a></p>
			<?php 
        }
    }
    ?>
		</div>
		<div style="clear: both"></div>
		<?php 
    $payments = edd_get_payments(array('number' => 5, 'mode' => 'live', 'orderby' => 'post_date', 'order' => 'DESC', 'user' => null, 'status' => 'publish', 'meta_key' => null, 'fields' => 'ids'));
    if ($payments) {
        ?>
		<p class="edd_dashboard_widget_subheading"><?php 
        _e('Recent Purchases', 'edd');
        ?>
</p>
		<div class="table recent_purchases">
			<table>
				<tbody>
					<?php 
        foreach ($payments as $payment) {
            $payment_meta = edd_get_payment_meta($payment);
            ?>
					<tr>
						<td>
							<?php 
            echo get_the_title($payment);
            ?>
 - (<?php 
            echo $payment_meta['email'];
            ?>
) - <span class="edd_price_label"><?php 
            echo edd_currency_filter(edd_format_amount(edd_get_payment_amount($payment)));
            ?>
</span> - <a href="<?php 
            echo add_query_arg('id', $payment, admin_url('edit.php?post_type=download&page=edd-payment-history&edd-action=view-order-details'));
            ?>
" title="<?php 
            printf(__('Purchase Details for Payment #%s', 'edd'), $payment);
            ?>
 "><?php 
            _e('View Order Details', 'edd');
            ?>
</a>
						</td>
					</tr>
					<?php 
        }
        // End foreach
        ?>
				</tbody>
			</table>
		</div>
		<?php 
    }
    // End if
    ?>
	</div>
	<?php 
}
/**
 * Looks up purchases by email that match the registering user
 *
 * This is for users that purchased as a guest and then came
 * back and created an account.
 *
 * @access      public
 * @since       1.6
 * @param       $user_id INT - the new user's ID
 * @return      void
 */
function edd_add_past_purchases_to_new_user($user_id)
{
    $email = get_the_author_meta('user_email', $user_id);
    $payments = edd_get_payments(array('s' => $email));
    if ($payments) {
        foreach ($payments as $payment) {
            if (intval(edd_get_payment_user_id($payment->ID)) > 0) {
                continue;
            }
            // This payment already associated with an account
            $meta = edd_get_payment_meta($payment->ID);
            $meta['user_info'] = maybe_unserialize($meta['user_info']);
            $meta['user_info']['id'] = $user_id;
            $meta['user_info'] = $meta['user_info'];
            // Store the updated user ID in the payment meta
            edd_update_payment_meta($payment->ID, '_edd_payment_meta', $meta);
            edd_update_payment_meta($payment->ID, '_edd_payment_user_id', $user_id);
        }
    }
}
/**
 * Calculates the total amount spent by a user
 *
 * @access      public
 * @since       1.3
 * @param       $user mixed - ID or email
 * @return      float - the total amount the user has spent
*/
function edd_purchase_total_of_user($user = null)
{
    $args = array('number' => -1, 'mode' => 'live', 'user' => $user, 'status' => 'publish');
    $customer_purchases = edd_get_payments($args);
    $amount = get_transient(md5('edd_customer_total_' . $user));
    if (false === $amount) {
        $amount = 0;
        if ($customer_purchases) {
            foreach ($customer_purchases as $purchase) {
                $amount += edd_get_payment_amount($purchase->ID);
            }
        }
        set_transient(md5('edd_customer_total_' . $user), $amount);
    }
    return $amount;
}
/**
 * Get Total Earnings
 *
 * @access      public
 * @since       1.1.9
 * @return      float
*/
function edd_get_total_earnings()
{
    $total = (double) 0;
    $payments = get_transient('edd_total_earnings');
    if (false === $payments) {
        $payments = edd_get_payments(array('offset' => 0, 'number' => -1, 'mode' => 'live', 'orderby' => 'ID', 'order' => 'DESC', 'user' => null, 'status' => 'publish'));
        set_transient('edd_total_earnings', $payments, 3600);
    }
    if ($payments) {
        foreach ($payments as $payment) {
            $meta = get_post_meta($payment->ID, '_edd_payment_meta', true);
            $total += $meta['amount'];
        }
    }
    return edd_currency_filter($total);
}
/**
 * Display Upgrade Notices
 *
 * @since 1.3.1
 * @return void
*/
function edd_show_upgrade_notices()
{
    if (isset($_GET['page']) && $_GET['page'] == 'edd-upgrades') {
        return;
    }
    // Don't show notices on the upgrades page
    $edd_version = get_option('edd_version');
    if (!$edd_version) {
        // 1.3 is the first version to use this option so we must add it
        $edd_version = '1.3';
    }
    $edd_version = preg_replace('/[^0-9.].*/', '', $edd_version);
    if (!get_option('edd_payment_totals_upgraded') && !get_option('edd_version')) {
        if (wp_count_posts('edd_payment')->publish < 1) {
            return;
        }
        // No payment exist yet
        // The payment history needs updated for version 1.2
        $url = add_query_arg('edd-action', 'upgrade_payments');
        $upgrade_notice = sprintf(__('The Payment History needs to be updated. %s', 'edd'), '<a href="' . wp_nonce_url($url, 'edd_upgrade_payments_nonce') . '">' . __('Click to Upgrade', 'edd') . '</a>');
        add_settings_error('edd-notices', 'edd-payments-upgrade', $upgrade_notice, 'error');
    }
    if (version_compare($edd_version, '1.3.2', '<') && !get_option('edd_logs_upgraded')) {
        printf('<div class="updated"><p>' . esc_html__('The Purchase and File Download History in Easy Digital Downloads needs to be upgraded, click %shere%s to start the upgrade.', 'edd') . '</p></div>', '<a href="' . esc_url(admin_url('options.php?page=edd-upgrades')) . '">', '</a>');
    }
    if (version_compare($edd_version, '1.3.4', '<') || version_compare($edd_version, '1.4', '<')) {
        printf('<div class="updated"><p>' . esc_html__('Easy Digital Downloads needs to upgrade the plugin pages, click %shere%s to start the upgrade.', 'edd') . '</p></div>', '<a href="' . esc_url(admin_url('options.php?page=edd-upgrades')) . '">', '</a>');
    }
    if (version_compare($edd_version, '1.5', '<')) {
        printf('<div class="updated"><p>' . esc_html__('Easy Digital Downloads needs to upgrade the database, click %shere%s to start the upgrade.', 'edd') . '</p></div>', '<a href="' . esc_url(admin_url('options.php?page=edd-upgrades')) . '">', '</a>');
    }
    if (version_compare($edd_version, '2.0', '<')) {
        printf('<div class="updated"><p>' . esc_html__('Easy Digital Downloads needs to upgrade the database, click %shere%s to start the upgrade.', 'edd') . '</p></div>', '<a href="' . esc_url(admin_url('options.php?page=edd-upgrades')) . '">', '</a>');
    }
    // Sequential Orders was the first stepped upgrade, so check if we have a stalled upgrade
    $resume_upgrade = edd_maybe_resume_upgrade();
    if (!empty($resume_upgrade)) {
        $resume_url = add_query_arg($resume_upgrade, admin_url('index.php'));
        printf('<div class="error"><p>' . __('Easy Digital Downloads needs to complete a database upgrade that was previously started, click <a href="%s">here</a> to resume the upgrade.', 'edd') . '</p></div>', esc_url($resume_url));
    } else {
        // Include all 'Stepped' upgrade process notices in this else statement,
        // to avoid having a pending, and new upgrade suggested at the same time
        if (EDD()->session->get('upgrade_sequential') && edd_get_payments()) {
            printf('<div class="updated"><p>' . __('Easy Digital Downloads needs to upgrade past order numbers to make them sequential, click <a href="%s">here</a> to start the upgrade.', 'edd') . '</p></div>', admin_url('index.php?page=edd-upgrades&edd-upgrade=upgrade_sequential_payment_numbers'));
        }
        if (version_compare($edd_version, '2.1', '<')) {
            printf('<div class="updated"><p>' . esc_html__('Easy Digital Downloads needs to upgrade the customer database, click %shere%s to start the upgrade.', 'edd') . '</p></div>', '<a href="' . esc_url(admin_url('index.php?page=edd-upgrades&edd-upgrade=upgrade_customers_db')) . '">', '</a>');
        }
        if (version_compare($edd_version, '2.2.6', '<')) {
            printf('<div class="updated"><p>' . __('Easy Digital Downloads needs to upgrade the payment database, click <a href="%s">here</a> to start the upgrade.', 'edd') . '</p></div>', esc_url(admin_url('index.php?page=edd-upgrades&edd-upgrade=upgrade_payments_price_logs_db')));
        }
        if (version_compare($edd_version, '2.3', '<') || !edd_has_upgrade_completed('upgrade_customer_payments_association')) {
            printf('<div class="updated"><p>' . __('Easy Digital Downloads needs to upgrade the customer database, click <a href="%s">here</a> to start the upgrade.', 'edd') . '</p></div>', esc_url(admin_url('index.php?page=edd-upgrades&edd-upgrade=upgrade_customer_payments_association')));
        }
        if (version_compare($edd_version, '2.3', '<') || !edd_has_upgrade_completed('upgrade_payment_taxes')) {
            printf('<div class="updated"><p>' . __('Easy Digital Downloads needs to upgrade the payment database, click <a href="%s">here</a> to start the upgrade.', 'edd') . '</p></div>', esc_url(admin_url('index.php?page=edd-upgrades&edd-upgrade=upgrade_payment_taxes')));
        }
        if (version_compare($edd_version, '2.4', '<') || !edd_has_upgrade_completed('upgrade_user_api_keys')) {
            printf('<div class="updated"><p>' . __('Easy Digital Downloads needs to upgrade the API Key database, click <a href="%s">here</a> to start the upgrade.', 'edd') . '</p></div>', esc_url(admin_url('index.php?page=edd-upgrades&edd-upgrade=upgrade_user_api_keys')));
        }
        /*
         *  NOTICE:
         *
         *  When adding new upgrade notices, please be sure to put the action into the upgrades array during install:
         *  /includes/install.php @ Appox Line 156
         *
         */
        // End 'Stepped' upgrade process notices
    }
}
 /**
  * Retrieves Recent Sales
  *
  * @access public
  * @since  1.5
  * @return array
  */
 public function get_recent_sales()
 {
     $sales = array();
     $query = edd_get_payments(array('number' => $this->per_page(), 'page' => $this->get_paged(), 'status' => 'publish'));
     if ($query) {
         $i = 0;
         foreach ($query as $payment) {
             $payment_meta = edd_get_payment_meta($payment->ID);
             $user_info = edd_get_payment_meta_user_info($payment->ID);
             $cart_items = edd_get_payment_meta_cart_details($payment->ID);
             $sales['sales'][$i]['ID'] = $payment->ID;
             $sales['sales'][$i]['key'] = edd_get_payment_key($payment->ID);
             $sales['sales'][$i]['subtotal'] = edd_get_payment_subtotal($payment->ID);
             $sales['sales'][$i]['tax'] = edd_get_payment_tax($payment->ID);
             $sales['sales'][$i]['fees'] = edd_get_payment_fees($payment->ID);
             $sales['sales'][$i]['total'] = edd_get_payment_amount($payment->ID);
             $sales['sales'][$i]['gateway'] = edd_get_payment_gateway($payment->ID);
             $sales['sales'][$i]['email'] = edd_get_payment_user_email($payment->ID);
             $sales['sales'][$i]['date'] = $payment->post_date;
             $sales['sales'][$i]['products'] = array();
             $c = 0;
             foreach ($cart_items as $key => $item) {
                 $price_override = isset($payment_meta['cart_details']) ? $item['price'] : null;
                 $price = edd_get_download_final_price($item['id'], $user_info, $price_override);
                 if (isset($cart_items[$key]['item_number'])) {
                     $price_name = '';
                     $price_options = $cart_items[$key]['item_number']['options'];
                     if (isset($price_options['price_id'])) {
                         $price_name = edd_get_price_option_name($item['id'], $price_options['price_id'], $payment->ID);
                     }
                 }
                 $sales['sales'][$i]['products'][$c]['name'] = get_the_title($item['id']);
                 $sales['sales'][$i]['products'][$c]['price'] = $price;
                 $sales['sales'][$i]['products'][$c]['price_name'] = $price_name;
                 $c++;
             }
             $i++;
         }
     }
     return $sales;
 }
/**
 * Get Total Cross-sell/Upsell Earnings
 *
 * @since 1.1
 * @return float $total Total earnings
 */
function edd_csau_get_total_earnings($type)
{
    $total = get_option('edd_' . $type . '_earnings_total', 0);
    // If no total stored in DB, use old method of calculating total earnings
    if (!$total) {
        $total = get_transient('edd_' . $type . '_earnings_total');
        if (false === $total) {
            $total = (double) 0;
            $args = apply_filters('edd_get_total_' . $type . '_earnings_args', array('offset' => 0, 'number' => -1, 'mode' => 'live', 'status' => array('publish', 'revoked'), 'fields' => 'ids'));
            $payments = edd_get_payments($args);
            if ($payments) {
                foreach ($payments as $payment) {
                    $total += edd_csau_get_payment_amount($payment, $type);
                }
            }
            // Cache results for 1 day. This cache is cleared automatically when a payment is made
            set_transient('edd_' . $type . '_earnings_total', $total, 86400);
            // Store the total for the first time
            update_option('edd_' . $type . '_earnings_total', $total);
        }
    }
    if ($total < 0) {
        $total = 0;
        // Don't ever show negative earnings
    }
    return apply_filters('edd_' . $type . '_total_earnings', round($total, 2), $type);
}
/**
 * Get Total Earnings
 *
 * @since 1.2
 * @return float $total Total earnings
 */
function edd_get_total_earnings()
{
    $total = get_option('edd_earnings_total', 0);
    // If no total stored in DB, use old method of calculating total earnings
    if (!$total) {
        global $wpdb;
        $total = get_transient('edd_earnings_total');
        if (false === $total) {
            $total = (double) 0;
            $args = apply_filters('edd_get_total_earnings_args', array('offset' => 0, 'number' => -1, 'status' => array('publish', 'revoked'), 'fields' => 'ids'));
            $payments = edd_get_payments($args);
            if ($payments) {
                /*
                 * If performing a purchase, we need to skip the very last payment in the database, since it calls
                 * edd_increase_total_earnings() on completion, which results in duplicated earnings for the very
                 * first purchase
                 */
                if (did_action('edd_update_payment_status')) {
                    array_pop($payments);
                }
                if (!empty($payments)) {
                    $payments = implode(',', $payments);
                    $total += $wpdb->get_var("SELECT SUM(meta_value) FROM {$wpdb->postmeta} WHERE meta_key = '_edd_payment_total' AND post_id IN({$payments})");
                }
            }
            // Cache results for 1 day. This cache is cleared automatically when a payment is made
            set_transient('edd_earnings_total', $total, 86400);
            // Store the total for the first time
            update_option('edd_earnings_total', $total);
        }
    }
    if ($total < 0) {
        $total = 0;
        // Don't ever show negative earnings
    }
    return apply_filters('edd_total_earnings', round($total, edd_currency_decimal_filter()));
}
/**
 * Looks up purchases by email that match the registering user
 *
 * This is for users that purchased as a guest and then came
 * back and created an account.
 *
 * @access      public
 * @since       1.6
 * @param       $user_id INT - the new user's ID
 * @return      void
 */
function edd_add_past_purchases_to_new_user($user_id)
{
    $email = get_the_author_meta('user_email', $user_id);
    $payments = edd_get_payments(array('s' => $email));
    if ($payments) {
        // Set a flag to force the account to be verified before purchase history can be accessed
        edd_set_user_to_pending($user_id);
        edd_send_user_verification_email($user_id);
        foreach ($payments as $payment) {
            if (intval(edd_get_payment_user_id($payment->ID)) > 0) {
                continue;
                // This payment already associated with an account
            }
            $meta = edd_get_payment_meta($payment->ID);
            $meta['user_info'] = maybe_unserialize($meta['user_info']);
            $meta['user_info']['id'] = $user_id;
            $meta['user_info'] = $meta['user_info'];
            // Store the updated user ID in the payment meta
            edd_update_payment_meta($payment->ID, '_edd_payment_meta', $meta);
            edd_update_payment_meta($payment->ID, '_edd_payment_user_id', $user_id);
        }
    }
}
Example #25
0
 public function get_all_orders($user_id = 0, $status = array())
 {
     $published_products = EDD_FES()->vendors->get_published_products($user_id);
     if (!$published_products) {
         return array();
     }
     $published_products = wp_list_pluck($published_products, 'ID');
     $paged = get_query_var('paged') ? get_query_var('paged') : 1;
     $args = array('download' => $published_products, 'output' => 'edd_payment', 'mode' => 'all', 'posts_per_page' => 10, 'orderby' => 'post_date', 'order' => 'DESC', 'paged' => $paged);
     $args = apply_filters('fes_get_all_orders_args', $args);
     $payments = edd_get_payments($args);
     if (!$payments) {
         return array();
     }
     // nothing fancy with this for now
     return $payments;
 }
 /**
  * Gets all customers who've purchased a specific download
  *
  * @param $id
  *
  * @return array
  */
 function get_customers($id)
 {
     $args = array('download' => $id);
     $payments = edd_get_payments($args);
     $customers = array();
     foreach ($payments as $payment) {
         $customer_email = edd_get_payment_user_email($payment->ID);
         if (!in_array($customer_email, $customers)) {
             $customers[] = $customer_email;
         }
     }
     return $customers;
 }
 /**
  * Retrieves Recent Sales
  *
  * @access public
  * @since  1.5
  * @return array
  */
 public function get_recent_sales()
 {
     global $wp_query;
     $sales = array();
     if (!user_can($this->user_id, 'view_shop_reports') && !$this->override) {
         return $sales;
     }
     if (isset($wp_query->query_vars['id'])) {
         $query = array();
         $query[] = new EDD_Payment($wp_query->query_vars['id']);
     } elseif (isset($wp_query->query_vars['purchasekey'])) {
         $query = array();
         $query[] = edd_get_payment_by('key', $wp_query->query_vars['purchasekey']);
     } elseif (isset($wp_query->query_vars['email'])) {
         $query = edd_get_payments(array('fields' => 'ids', 'meta_key' => '_edd_payment_user_email', 'meta_value' => $wp_query->query_vars['email'], 'number' => $this->per_page(), 'page' => $this->get_paged(), 'status' => 'publish'));
     } else {
         $query = edd_get_payments(array('fields' => 'ids', 'number' => $this->per_page(), 'page' => $this->get_paged(), 'status' => 'publish'));
     }
     if ($query) {
         $i = 0;
         foreach ($query as $payment) {
             if (is_numeric($payment)) {
                 $payment = new EDD_Payment($payment);
             }
             $payment_meta = $payment->get_meta();
             $user_info = $payment->user_info;
             $sales['sales'][$i]['ID'] = $payment->number;
             $sales['sales'][$i]['transaction_id'] = $payment->transaction_id;
             $sales['sales'][$i]['key'] = $payment->key;
             $sales['sales'][$i]['discount'] = !empty($payment->discounts) ? explode(',', $payment->discounts) : array();
             $sales['sales'][$i]['subtotal'] = $payment->subtotal;
             $sales['sales'][$i]['tax'] = $payment->tax;
             $sales['sales'][$i]['fees'] = $payment->fees;
             $sales['sales'][$i]['total'] = $payment->total;
             $sales['sales'][$i]['gateway'] = $payment->gateway;
             $sales['sales'][$i]['email'] = $payment->email;
             $sales['sales'][$i]['date'] = $payment->date;
             $sales['sales'][$i]['products'] = array();
             $c = 0;
             foreach ($payment->cart_details as $key => $item) {
                 $item_id = isset($item['id']) ? $item['id'] : $item;
                 $price = isset($item['price']) ? $item['price'] : false;
                 $price_id = isset($item['item_number']['options']['price_id']) ? $item['item_number']['options']['price_id'] : null;
                 $quantity = isset($item['quantity']) && $item['quantity'] > 0 ? $item['quantity'] : 1;
                 if (!$price) {
                     // This function is only used on payments with near 1.0 cart data structure
                     $price = edd_get_download_final_price($item_id, $user_info, null);
                 }
                 $price_name = '';
                 if (isset($item['item_number']) && isset($item['item_number']['options'])) {
                     $price_options = $item['item_number']['options'];
                     if (isset($price_options['price_id'])) {
                         $price_name = edd_get_price_option_name($item_id, $price_options['price_id'], $payment->ID);
                     }
                 }
                 $sales['sales'][$i]['products'][$c]['id'] = $item_id;
                 $sales['sales'][$i]['products'][$c]['quantity'] = $quantity;
                 $sales['sales'][$i]['products'][$c]['name'] = get_the_title($item_id);
                 $sales['sales'][$i]['products'][$c]['price'] = $price;
                 $sales['sales'][$i]['products'][$c]['price_name'] = $price_name;
                 $c++;
             }
             $i++;
         }
     }
     return $sales;
 }
/**
 * Updates all old payments, prior to 1.2, with new
 * meta for the total purchase amount
 *
 * This is so that payments can be queried by their totals
 *
 * @since 1.2
 * @param array $data Arguments passed
 * @return void
*/
function edd_update_old_payments_with_totals($data)
{
    if (!wp_verify_nonce($data['_wpnonce'], 'edd_upgrade_payments_nonce')) {
        return;
    }
    if (get_option('edd_payment_totals_upgraded')) {
        return;
    }
    $payments = edd_get_payments(array('offset' => 0, 'number' => -1, 'mode' => 'all'));
    if ($payments) {
        foreach ($payments as $payment) {
            $meta = edd_get_payment_meta($payment->ID);
            update_post_meta($payment->ID, '_edd_payment_total', $meta['amount']);
        }
    }
    add_option('edd_payment_totals_upgraded', 1);
}
Example #29
0
/**
 * View a customer
 *
 * @since  2.3
 * @param  $customer The Customer object being displayed
 * @return void
 */
function edd_customers_view($customer)
{
    $customer_edit_role = apply_filters('edd_edit_customers_role', 'edit_shop_payments');
    ?>

	<?php 
    do_action('edd_customer_card_top', $customer);
    ?>

	<div class="info-wrapper customer-section">

		<form id="edit-customer-info" method="post" action="<?php 
    echo admin_url('edit.php?post_type=download&page=edd-customers&view=overview&id=' . $customer->id);
    ?>
">

			<div class="customer-info">

				<div class="avatar-wrap left" id="customer-avatar">
					<?php 
    echo get_avatar($customer->email);
    ?>
<br />
					<?php 
    if (current_user_can($customer_edit_role)) {
        ?>
						<span class="info-item editable customer-edit-link"><a title="<?php 
        _e('Edit Customer', 'edd');
        ?>
" href="#" id="edit-customer"><?php 
        _e('Edit Customer', 'edd');
        ?>
</a></span>
					<?php 
    }
    ?>
				</div>

				<div class="customer-id right">
					#<?php 
    echo $customer->id;
    ?>
				</div>

				<div class="customer-address-wrapper right">
				<?php 
    if (isset($customer->user_id) && $customer->user_id > 0) {
        ?>

					<?php 
        $address = get_user_meta($customer->user_id, '_edd_user_address', true);
        $defaults = array('line1' => '', 'line2' => '', 'city' => '', 'state' => '', 'country' => '', 'zip' => '');
        $address = wp_parse_args($address, $defaults);
        ?>

					<?php 
        if (!empty($address)) {
            ?>
					<strong><?php 
            _e('Customer Address', 'edd');
            ?>
</strong>
					<span class="customer-address info-item editable">
						<span class="info-item" data-key="line1"><?php 
            echo $address['line1'];
            ?>
</span>
						<span class="info-item" data-key="line2"><?php 
            echo $address['line2'];
            ?>
</span>
						<span class="info-item" data-key="city"><?php 
            echo $address['city'];
            ?>
</span>
						<span class="info-item" data-key="state"><?php 
            echo $address['state'];
            ?>
</span>
						<span class="info-item" data-key="country"><?php 
            echo $address['country'];
            ?>
</span>
						<span class="info-item" data-key="zip"><?php 
            echo $address['zip'];
            ?>
</span>
					</span>
					<?php 
        }
        ?>
					<span class="customer-address info-item edit-item">
						<input class="info-item" type="text" data-key="line1" name="customerinfo[line1]" placeholder="<?php 
        _e('Address 1', 'edd');
        ?>
" value="<?php 
        echo $address['line1'];
        ?>
" />
						<input class="info-item" type="text" data-key="line2" name="customerinfo[line2]" placeholder="<?php 
        _e('Address 2', 'edd');
        ?>
" value="<?php 
        echo $address['line2'];
        ?>
" />
						<input class="info-item" type="text" data-key="city" name="customerinfo[city]" placeholder="<?php 
        _e('City', 'edd');
        ?>
" value="<?php 
        echo $address['city'];
        ?>
" />
						<select data-key="country" name="customerinfo[country]" id="billing_country" class="billing_country edd-select edit-item">
							<?php 
        $selected_country = $address['country'];
        $countries = edd_get_country_list();
        foreach ($countries as $country_code => $country) {
            echo '<option value="' . esc_attr($country_code) . '"' . selected($country_code, $selected_country, false) . '>' . $country . '</option>';
        }
        ?>
						</select>
						<?php 
        $selected_state = edd_get_shop_state();
        $states = edd_get_shop_states($selected_country);
        $selected_state = isset($address['state']) ? $address['state'] : $selected_state;
        if (!empty($states)) {
            ?>
						<select data-key="state" name="customerinfo[state]" id="card_state" class="card_state edd-select info-item">
							<?php 
            foreach ($states as $state_code => $state) {
                echo '<option value="' . $state_code . '"' . selected($state_code, $selected_state, false) . '>' . $state . '</option>';
            }
            ?>
						</select>
						<?php 
        } else {
            ?>
						<input type="text" size="6" data-key="state" name="customerinfo[state]" id="card_state" class="card_state edd-input info-item" placeholder="<?php 
            _e('State / Province', 'edd');
            ?>
"/>
						<?php 
        }
        ?>
						<input class="info-item" type="text" data-key="zip" name="customerinfo[zip]" placeholder="<?php 
        _e('Postal', 'edd');
        ?>
" value="<?php 
        echo $address['zip'];
        ?>
" />
					</span>
				<?php 
    }
    ?>
				</div>

				<div class="customer-main-wrapper left">

					<span class="customer-name info-item edit-item"><input size="15" data-key="name" name="customerinfo[name]" type="text" value="<?php 
    echo esc_attr($customer->name);
    ?>
" placeholder="<?php 
    _e('Customer Name', 'edd');
    ?>
" /></span>
					<span class="customer-name info-item editable"><span data-key="name"><?php 
    echo $customer->name;
    ?>
</span></span>
					<span class="customer-name info-item edit-item"><input size="20" data-key="email" name="customerinfo[email]" type="text" value="<?php 
    echo $customer->email;
    ?>
" placeholder="<?php 
    _e('Customer Email', 'edd');
    ?>
" /></span>
					<span class="customer-email info-item editable" data-key="email"><?php 
    echo $customer->email;
    ?>
</span>
					<span class="customer-since info-item">
						<?php 
    _e('Customer since', 'edd');
    ?>
						<?php 
    echo date_i18n(get_option('date_format'), strtotime($customer->date_created));
    ?>
					</span>
					<span class="customer-user-id info-item edit-item">
						<?php 
    $user_id = $customer->user_id > 0 ? $customer->user_id : '';
    $data_atts = array('key' => 'user_login', 'exclude' => $user_id);
    $user_args = array('name' => 'customerinfo[user_login]', 'class' => 'edd-user-dropdown', 'data' => $data_atts);
    if (!empty($user_id)) {
        $userdata = get_userdata($user_id);
        $user_args['value'] = $userdata->user_login;
    }
    echo EDD()->html->ajax_user_search($user_args);
    ?>
						<input type="hidden" name="customerinfo[user_id]" data-key="user_id" value="<?php 
    echo $customer->user_id;
    ?>
" />
					</span>

					<span class="customer-user-id info-item editable">
						<?php 
    _e('User ID', 'edd');
    ?>
:&nbsp;
						<?php 
    if (intval($customer->user_id) > 0) {
        ?>
							<span data-key="user_id"><?php 
        echo $customer->user_id;
        ?>
</span>
						<?php 
    } else {
        ?>
							<span data-key="user_id"><?php 
        _e('none', 'edd');
        ?>
</span>
						<?php 
    }
    ?>
						<?php 
    if (current_user_can($customer_edit_role) && intval($customer->user_id) > 0) {
        ?>
							<span class="disconnect-user"> - <a id="disconnect-customer" href="#disconnect" title="<?php 
        _e('Disconnects the current user ID from this customer record', 'edd');
        ?>
"><?php 
        _e('Disconnect User', 'edd');
        ?>
</a></span>
						<?php 
    }
    ?>
					</span>

				</div>

			</div>

			<span id="customer-edit-actions" class="edit-item">
				<input type="hidden" data-key="id" name="customerinfo[id]" value="<?php 
    echo $customer->id;
    ?>
" />
				<?php 
    wp_nonce_field('edit-customer', '_wpnonce', false, true);
    ?>
				<input type="hidden" name="edd_action" value="edit-customer" />
				<input type="submit" id="edd-edit-customer-save" class="button-secondary" value="<?php 
    _e('Update Customer', 'edd');
    ?>
" />
				<a id="edd-edit-customer-cancel" href="" class="delete"><?php 
    _e('Cancel', 'edd');
    ?>
</a>
			</span>

		</form>
	</div>

	<?php 
    do_action('edd_customer_before_stats', $customer);
    ?>

	<div id="customer-stats-wrapper" class="customer-section">
		<ul>
			<li>
				<a title="<?php 
    _e('View All Purchases', 'edd');
    ?>
" href="<?php 
    echo admin_url('edit.php?post_type=download&page=edd-payment-history&user='******'%d Completed Sale', '%d Completed Sales', $customer->purchase_count, 'edd'), $customer->purchase_count);
    ?>
				</a>
			</li>
			<li>
				<span class="dashicons dashicons-chart-area"></span>
				<?php 
    echo edd_currency_filter(edd_format_amount($customer->purchase_value));
    ?>
 <?php 
    _e('Lifetime Value', 'edd');
    ?>
			</li>
			<?php 
    do_action('edd_customer_stats_list', $customer);
    ?>
		</ul>
	</div>

	<?php 
    do_action('edd_customer_before_tables_wrapper', $customer);
    ?>

	<div id="customer-tables-wrapper" class="customer-section">

		<?php 
    do_action('edd_customer_before_tables', $customer);
    ?>

		<h3><?php 
    _e('Recent Payments', 'edd');
    ?>
</h3>
		<?php 
    $payment_ids = explode(',', $customer->payment_ids);
    $payments = edd_get_payments(array('post__in' => $payment_ids));
    $payments = array_slice($payments, 0, 10);
    ?>
		<table class="wp-list-table widefat striped payments">
			<thead>
				<tr>
					<th><?php 
    _e('ID', 'edd');
    ?>
</th>
					<th><?php 
    _e('Amount', 'edd');
    ?>
</th>
					<th><?php 
    _e('Date', 'edd');
    ?>
</th>
					<th><?php 
    _e('Status', 'edd');
    ?>
</th>
					<th><?php 
    _e('Actions', 'edd');
    ?>
</th>
				</tr>
			</thead>
			<tbody>
				<?php 
    if (!empty($payments)) {
        ?>
					<?php 
        foreach ($payments as $payment) {
            ?>
						<tr>
							<td><?php 
            echo $payment->ID;
            ?>
</td>
							<td><?php 
            echo edd_payment_amount($payment->ID);
            ?>
</td>
							<td><?php 
            echo date_i18n(get_option('date_format'), strtotime($payment->post_date));
            ?>
</td>
							<td><?php 
            echo edd_get_payment_status($payment, true);
            ?>
</td>
							<td>
								<a title="<?php 
            _e('View Details for Payment', 'edd');
            echo ' ' . $payment->ID;
            ?>
" href="<?php 
            echo admin_url('edit.php?post_type=download&page=edd-payment-history&view=view-order-details&id=' . $payment->ID);
            ?>
">
									<?php 
            _e('View Details', 'edd');
            ?>
								</a>
								<?php 
            do_action('edd_customer_recent_purcahses_actions', $customer, $payment);
            ?>
							</td>
						</tr>
					<?php 
        }
        ?>
				<?php 
    } else {
        ?>
					<tr><td colspan="5"><?php 
        _e('No Payments Found', 'edd');
        ?>
</td></tr>
				<?php 
    }
    ?>
			</tbody>
		</table>

		<h3><?php 
    printf(__('Purchased %s', 'edd'), edd_get_label_plural());
    ?>
</h3>
		<?php 
    $downloads = edd_get_users_purchased_products($customer->email);
    ?>
		<table class="wp-list-table widefat striped downloads">
			<thead>
				<tr>
					<th><?php 
    echo edd_get_label_singular();
    ?>
</th>
					<th width="120px"><?php 
    _e('Actions', 'edd');
    ?>
</th>
				</tr>
			</thead>
			<tbody>
				<?php 
    if (!empty($downloads)) {
        ?>
					<?php 
        foreach ($downloads as $download) {
            ?>
						<tr>
							<td><?php 
            echo $download->post_title;
            ?>
</td>
							<td>
								<a title="<?php 
            echo esc_attr(sprintf(__('View %s', 'edd'), $download->post_title));
            ?>
" href="<?php 
            echo esc_url(admin_url('post.php?action=edit&post=' . $download->ID));
            ?>
">
									<?php 
            printf(__('View %s', 'edd'), edd_get_label_singular());
            ?>
								</a>
							</td>
						</tr>
					<?php 
        }
        ?>
				<?php 
    } else {
        ?>
					<tr><td colspan="2"><?php 
        printf(__('No %s Found', 'edd'), edd_get_label_plural());
        ?>
</td></tr>
				<?php 
    }
    ?>
			</tbody>
		</table>

		<?php 
    do_action('edd_customer_after_tables', $customer);
    ?>

	</div>

	<?php 
    do_action('edd_customer_card_bottom', $customer);
    ?>

	<?php 
}
/**
 * Campaign Contributinos
 *
 * @since Astoundify Crowdfunding 1.4
 *
 * @return void
 */
function atcf_shortcode_profile_contributions($user)
{
    global $edd_options;
    $contributions = edd_get_payments(array('user' => $user->ID, 'status' => atcf_has_preapproval_gateway() ? array('preapproval', 'publish') : 'publish', 'mode' => edd_is_test_mode() ? 'test' : 'live'));
    if (empty($contributions)) {
        return;
    }
    ?>
	<h3 class="atcf-profile-section your-campaigns"><?php 
    _e('Your Contributions', 'atcf');
    ?>
</h3>

	<ul class="atcf-profile-contributinos">
		<?php 
    foreach ($contributions as $contribution) {
        ?>
		<?php 
        $payment_data = edd_get_payment_meta($contribution->ID);
        $cart = edd_get_payment_meta_cart_details($contribution->ID);
        $key = edd_get_payment_key($contribution->ID);
        ?>
		<?php 
        if ($cart) {
            ?>
		<li>
			<?php 
            foreach ($cart as $download) {
                ?>
			<?php 
                printf(_x('<a href="%s">%s</a> pledge to <a href="%s">%s</a>', 'price for download (payment history)', 'atcf'), add_query_arg('payment_key', $key, get_permalink($edd_options['success_page'])), edd_currency_filter(edd_format_amount($download['price'])), get_permalink($download['id']), $download['name']);
                ?>
			<?php 
            }
            ?>
		</li>
		<?php 
        }
        ?>
		<?php 
    }
    ?>
	</ul>
<?php 
}