/**
 * Upgrades all commission records to use a taxonomy for tracking the status of the commission
 *
 * @since 2.8
 * @return void
 */
function eddcr_upgrade_post_meta()
{
    if (!current_user_can('manage_shop_settings')) {
        return;
    }
    define('EDDCR_DOING_UPGRADES', true);
    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;
    $args = array('posts_per_page' => 20, 'paged' => $step, 'status' => 'any', 'order' => 'ASC', 'post_type' => 'any', 'fields' => 'ids', 'meta_key' => '_edd_cr_restricted_to');
    $items = get_posts($args);
    if ($items) {
        // items found so upgrade them
        foreach ($items as $post_id) {
            $restricted_to = get_post_meta($post_id, '_edd_cr_restricted_to', true);
            $price_id = get_post_meta($post_id, '_edd_cr_restricted_to_variable', true);
            $args = array();
            $args[] = array('download' => $restricted_to, 'price_id' => $price_id);
            update_post_meta($post_id, '_edd_cr_restricted_to', $args);
            add_post_meta($restricted_to, '_edd_cr_protected_post', $post_id);
        }
        $step++;
        $redirect = add_query_arg(array('page' => 'edd-upgrades', 'edd-upgrade' => 'upgrade_cr_post_meta', 'step' => $step), admin_url('index.php'));
        wp_safe_redirect($redirect);
        exit;
    } else {
        // No more items found, finish up
        update_option('eddcr_version', EDD_CONTENT_RESTRICTION_VER);
        delete_option('edd_doing_upgrade');
        wp_redirect(admin_url());
        exit;
    }
}
Esempio n. 2
0
/**
 * Upgrades all commission records to use a taxonomy for tracking the status of the commission
 *
 * @since 2.8
 * @return void
 */
function eddc_upgrade_commission_statuses()
{
    if (!current_user_can('manage_shop_settings')) {
        return;
    }
    define('EDDC_DOING_UPGRADES', true);
    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;
    $args = array('posts_per_page' => 20, 'paged' => $step, 'status' => 'any', 'order' => 'ASC', 'post_type' => 'edd_commission', 'fields' => 'ids');
    $commissions = get_posts($args);
    if ($commissions) {
        // Commissions found so upgrade them
        foreach ($commissions as $commission_id) {
            $status = get_post_meta($commission_id, '_commission_status', true);
            if ('paid' !== $status) {
                $status = 'unpaid';
            }
            eddc_set_commission_status($commission_id, $status);
        }
        $step++;
        $redirect = add_query_arg(array('page' => 'edd-upgrades', 'edd-upgrade' => 'upgrade_commission_statuses', 'step' => $step), admin_url('index.php'));
        wp_safe_redirect($redirect);
        exit;
    } else {
        // No more commissions found, finish up
        update_option('eddc_version', EDD_COMMISSIONS_VERSION);
        // No more commissions found, finish up
        wp_redirect(admin_url());
        exit;
    }
}
Esempio n. 3
0
/**
 * Upgrades vendor permissions
 *
 * @since 2.2
 * @return void
 */
function fes_22_upgrade_vendor_permissions()
{
    $fes_version = get_option('fes_db_version', '2.1');
    if (version_compare($fes_version, '2.2', '>=')) {
        return;
    }
    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;
    $offset = $step == 1 ? 0 : $step * 100;
    $users = new WP_User_Query(array('fields' => 'ID', 'number' => 100, 'offset' => $offset));
    $users = $users->results;
    if ($users && count($users) > 0) {
        foreach ($users as $user => $id) {
            if (user_can($id, 'fes_is_vendor') && !user_can($id, 'fes_is_admin') && !user_can($id, 'administrator') && !user_can($id, 'editor')) {
                $user = new WP_User($id);
                $user->add_role('frontend_vendor');
            }
        }
        // Keys found so upgrade them
        $step++;
        $redirect = add_query_arg(array('page' => 'fes-upgrades', 'edd_upgrade' => 'upgrade_vendor_permissions', 'step' => $step), admin_url('index.php'));
        wp_redirect($redirect);
        exit;
    } else {
        // No more keys found, update the DB version and finish up
        update_option('fes_db_version', fes_plugin_version);
        wp_redirect(admin_url('admin.php?page=fes-about'));
        exit;
    }
}
 /**
  * Set the export headers
  *
  * @access public
  * @since 2.3
  * @return void
  */
 public function headers()
 {
     ignore_user_abort(true);
     if (!edd_is_func_disabled('set_time_limit') && !ini_get('safe_mode')) {
         set_time_limit(0);
     }
     nocache_headers();
     header('Content-Type: text/csv; charset=utf-8');
     header('Content-Disposition: attachment; filename=edd-export-' . $this->export_type . '-' . $this->year . '-' . $this->month . '.csv');
     header("Expires: 0");
 }
 /**
  * Set the export headers
  *
  * @access public
  * @since 1.6
  * @return void
  */
 public function headers()
 {
     ignore_user_abort(true);
     if (!edd_is_func_disabled('set_time_limit') && !ini_get('safe_mode')) {
         set_time_limit(0);
     }
     $month = isset($_POST['month']) ? absint($_POST['month']) : date('n');
     $year = isset($_POST['year']) ? absint($_POST['year']) : date('Y');
     nocache_headers();
     header('Content-Type: text/csv; charset=utf-8');
     header('Content-Disposition: attachment; filename=' . apply_filters('edd_payments_export_filename', 'edd-export-' . $this->export_type . '-' . $month . '-' . $year) . '.csv');
     header("Expires: 0");
 }
 /**
  * Set the export headers
  *
  * @access public
  * @since 1.4.4
  * @return void
  */
 public function headers()
 {
     ignore_user_abort(true);
     if (!edd_is_func_disabled('set_time_limit') && !ini_get('safe_mode')) {
         set_time_limit(0);
     }
     $extra = '';
     if (!empty($_POST['edd_export_download'])) {
         $extra = sanitize_title(get_the_title(absint($_POST['edd_export_download']))) . '-';
     }
     nocache_headers();
     header('Content-Type: text/csv; charset=utf-8');
     header('Content-Disposition: attachment; filename=edd-export-' . $extra . $this->export_type . '-' . date('m-d-Y') . '.csv');
     header("Expires: 0");
 }
 /**
  * Deliver the file download
  *
  * @since  3.2.4
  * @return void
  */
 public function process_package_download()
 {
     if (isset($_GET['key']) && isset($_GET['id']) && isset($_GET['license']) && isset($_GET['expires'])) {
         $id = absint(urldecode($_GET['id']));
         $hash = urldecode($_GET['key']);
         $license = sanitize_text_field(urldecode($_GET['license']));
         $expires = is_numeric($_GET['expires']) ? $_GET['expires'] : urldecode(base64_decode($_GET['expires']));
         do_action('edd_sl_before_package_download', $id, $hash, $license, $expires);
         if (time() > $expires) {
             wp_die(__('Your download link has expired', 'edd_sl'), __('Error', 'edd_sl'), array('response' => 401));
         }
         if (empty($license)) {
             wp_die(__('No license key provided', 'edd_sl'), __('Error', 'edd_sl'), array('response' => 401));
         }
         if (!edd_software_licensing()->is_download_id_valid_for_license($id, $license)) {
             wp_die(__('Invalid license supplied', 'edd_sl'), __('Error', 'edd_sl'), array('response' => 401));
         }
         $requested_file = $this->get_download_package($id, $license, $hash, $expires);
         $file_extension = edd_get_file_extension($requested_file);
         $ctype = edd_get_file_ctype($file_extension);
         if (!edd_is_func_disabled('set_time_limit') && !ini_get('safe_mode')) {
             set_time_limit(0);
         }
         if (function_exists('get_magic_quotes_runtime') && get_magic_quotes_runtime()) {
             set_magic_quotes_runtime(0);
         }
         @session_write_close();
         if (function_exists('apache_setenv')) {
             @apache_setenv('no-gzip', 1);
         }
         @ini_set('zlib.output_compression', 'Off');
         nocache_headers();
         header("Robots: none");
         header("Content-Type: " . $ctype . "");
         header("Content-Description: File Transfer");
         header("Content-Disposition: attachment; filename=\"" . apply_filters('edd_requested_file_name', basename($requested_file)) . "\";");
         header("Content-Transfer-Encoding: binary");
         $method = edd_get_file_download_method();
         if ('x_sendfile' == $method && (!function_exists('apache_get_modules') || !in_array('mod_xsendfile', apache_get_modules()))) {
             // If X-Sendfile is selected but is not supported, fallback to Direct
             $method = 'direct';
         }
         $file_details = parse_url($requested_file);
         $schemes = array('http', 'https');
         // Direct URL schemes
         if ((!isset($file_details['scheme']) || !in_array($file_details['scheme'], $schemes)) && isset($file_details['path']) && file_exists($requested_file)) {
             /**
              * Download method is set to to Redirect in settings but an absolute path was provided
              * We need to switch to a direct download in order for the file to download properly
              */
             $method = 'direct';
         }
         switch ($method) {
             case 'redirect':
                 // Redirect straight to the file
                 header("Location: " . $requested_file);
                 break;
             case 'direct':
             default:
                 $direct = false;
                 if ((!isset($file_details['scheme']) || !in_array($file_details['scheme'], $schemes)) && isset($file_details['path']) && file_exists($requested_file)) {
                     /** This is an absolute path */
                     $direct = true;
                     $file_path = $requested_file;
                 } else {
                     if (defined('UPLOADS') && strpos($requested_file, UPLOADS) !== false) {
                         /**
                          * This is a local file given by URL so we need to figure out the path
                          * UPLOADS is always relative to ABSPATH
                          * site_url() is the URL to where WordPress is installed
                          */
                         $file_path = str_replace(site_url(), '', $requested_file);
                         $file_path = realpath(ABSPATH . $file_path);
                         $direct = true;
                     } else {
                         if (strpos($requested_file, WP_CONTENT_URL) !== false) {
                             /** This is a local file given by URL so we need to figure out the path */
                             $file_path = str_replace(WP_CONTENT_URL, WP_CONTENT_DIR, $requested_file);
                             $file_path = realpath($file_path);
                             $direct = true;
                         }
                     }
                 }
                 // Now deliver the file based on the kind of software the server is running / has enabled
                 if (function_exists('apache_get_modules') && in_array('mod_xsendfile', apache_get_modules())) {
                     header("X-Sendfile: {$file_path}");
                 } elseif (stristr(getenv('SERVER_SOFTWARE'), 'lighttpd')) {
                     header("X-LIGHTTPD-send-file: {$file_path}");
                 } elseif (stristr(getenv('SERVER_SOFTWARE'), 'nginx') || stristr(getenv('SERVER_SOFTWARE'), 'cherokee')) {
                     // We need a path relative to the domain
                     $file_path = str_ireplace($_SERVER['DOCUMENT_ROOT'], '', $file_path);
                     header("X-Accel-Redirect: /{$file_path}");
                 }
                 if ($direct) {
                     edd_deliver_download($file_path);
                 } else {
                     // The file supplied does not have a discoverable absolute path
                     header("Location: " . $requested_file);
                 }
                 break;
         }
         edd_die();
     } else {
         wp_die(__('You do not have permission to download this file', 'edd_sl'), __('Error', 'edd_sl'), array('response' => 401));
     }
     exit;
 }
Esempio n. 8
0
/**
 * Process add-on Downloads
 *
 * Handles the file download process for add-ons.
 *
 * @access      private
 * @since       1.1
 * @return      void
 */
function affwp_process_add_on_download()
{
    if (!isset($_GET['add_on'])) {
        return;
    }
    if (!is_user_logged_in()) {
        return;
    }
    $add_on = absint($_GET['add_on']);
    if ('download' != get_post_type($add_on)) {
        return;
    }
    $has_ultimate_license = in_array(3, affwp_get_users_price_ids());
    $has_professional_license = in_array(2, affwp_get_users_price_ids());
    if (!($has_ultimate_license || $has_professional_license)) {
        wp_die('You need either an Ultimate or Professional license to download this add-on', 'Error', array('response' => 403));
    }
    $user_info = array();
    $user_data = get_userdata(get_current_user_id());
    $user_info['email'] = $user_data->user_email;
    $user_info['id'] = $user_data->ID;
    $user_info['name'] = $user_data->display_name;
    edd_record_download_in_log($add_on, 0, $user_info, edd_get_ip(), 0, 0);
    $download_files = edd_get_download_files($add_on);
    $requested_file = $download_files[0]['file'];
    $file_extension = edd_get_file_extension($requested_file);
    $ctype = edd_get_file_ctype($file_extension);
    if (!edd_is_func_disabled('set_time_limit') && !ini_get('safe_mode')) {
        set_time_limit(0);
    }
    if (function_exists('get_magic_quotes_runtime') && get_magic_quotes_runtime()) {
        set_magic_quotes_runtime(0);
    }
    @session_write_close();
    if (function_exists('apache_setenv')) {
        @apache_setenv('no-gzip', 1);
    }
    @ini_set('zlib.output_compression', 'Off');
    nocache_headers();
    header("Robots: none");
    header("Content-Type: " . $ctype . "");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=\"" . basename($requested_file) . "\"");
    header("Content-Transfer-Encoding: binary");
    $method = edd_get_file_download_method();
    if ('x_sendfile' == $method && (!function_exists('apache_get_modules') || !in_array('mod_xsendfile', apache_get_modules()))) {
        // If X-Sendfile is selected but is not supported, fallback to Direct
        $method = 'direct';
    }
    switch ($method) {
        case 'redirect':
            // Redirect straight to the file
            header("Location: " . $requested_file);
            break;
        case 'direct':
        default:
            $direct = false;
            $file_details = parse_url($requested_file);
            $schemes = array('http', 'https');
            // Direct URL schemes
            if ((!isset($file_details['scheme']) || !in_array($file_details['scheme'], $schemes)) && isset($file_details['path']) && file_exists($requested_file)) {
                /** This is an absolute path */
                $direct = true;
                $file_path = $requested_file;
            } else {
                if (defined('UPLOADS') && strpos($requested_file, UPLOADS) !== false) {
                    /**
                     * This is a local file given by URL so we need to figure out the path
                     * UPLOADS is always relative to ABSPATH
                     * site_url() is the URL to where WordPress is installed
                     */
                    $file_path = str_replace(site_url(), '', $requested_file);
                    $file_path = realpath(ABSPATH . $file_path);
                    $direct = true;
                } else {
                    if (strpos($requested_file, WP_CONTENT_URL) !== false) {
                        /** This is a local file given by URL so we need to figure out the path */
                        $file_path = str_replace(WP_CONTENT_URL, WP_CONTENT_DIR, $requested_file);
                        $file_path = realpath($file_path);
                        $direct = true;
                    }
                }
            }
            // Now deliver the file based on the kind of software the server is running / has enabled
            if (function_exists('apache_get_modules') && in_array('mod_xsendfile', apache_get_modules())) {
                header("X-Sendfile: {$file_path}");
            } elseif (stristr(getenv('SERVER_SOFTWARE'), 'lighttpd')) {
                header("X-LIGHTTPD-send-file: {$file_path}");
            } elseif (stristr(getenv('SERVER_SOFTWARE'), 'nginx') || stristr(getenv('SERVER_SOFTWARE'), 'cherokee')) {
                // We need a path relative to the domain
                $file_path = str_ireplace($_SERVER['DOCUMENT_ROOT'], '', $file_path);
                header("X-Accel-Redirect: /{$file_path}");
            } else {
                if ($direct) {
                    edd_deliver_download($file_path);
                } else {
                    // The file supplied does not have a discoverable absolute path
                    header("Location: " . $requested_file);
                }
            }
            break;
    }
    edd_die();
    exit;
}
Esempio n. 9
0
/**
 * Process a settings export that generates a .json file of the shop settings
 *
 * @since 1.7
 * @return void
 */
function edd_process_settings_export()
{
    if (empty($_POST['edd_export_nonce'])) {
        return;
    }
    if (!wp_verify_nonce($_POST['edd_export_nonce'], 'edd_export_nonce')) {
        return;
    }
    if (!current_user_can('manage_shop_settings')) {
        return;
    }
    $settings = array();
    $settings['general'] = get_option('edd_general');
    $settings['gateways'] = get_option('edd_gateways');
    $settings['emails'] = get_option('edd_emails');
    $settings['styles'] = get_option('edd_styles');
    $settings['taxes'] = get_option('edd_taxes');
    $settings['extensions'] = get_option('edd_extensions');
    $settings['misc'] = get_option('edd_misc');
    ignore_user_abort(true);
    if (!edd_is_func_disabled('set_time_limit') && !ini_get('safe_mode')) {
        set_time_limit(0);
    }
    nocache_headers();
    header('Content-Type: application/json; charset=utf-8');
    header('Content-Disposition: attachment; filename=edd-settings-export-' . date('m-d-Y') . '.json');
    header("Expires: 0");
    echo json_encode($settings);
    exit;
}
/**
 * Export all downloads to CSV
 *
 * @access      private
 * @since       1.2
 * @return      void
 */
function edd_export_all_downloads_history()
{
    if (current_user_can('administrator')) {
        ignore_user_abort(true);
        if (!edd_is_func_disabled('set_time_limit') && !ini_get('safe_mode')) {
            set_time_limit(0);
        }
        $report_args = array('post_type' => 'download', 'post_status' => 'publish', 'posts_per_page' => -1, 'order' => 'post_date');
        $downloads = get_posts($report_args);
        if (!empty($downloads)) {
            header("Content-type: text/csv");
            $today = date_i18n("Y-m-d");
            header("Content-Disposition: attachment; filename=user_downloads_history-{$today}.csv");
            header("Pragma: no-cache");
            header("Expires: 0");
            echo '"' . __('Date', 'edd') . '",';
            echo '"' . __('Downloaded by', 'edd') . '",';
            echo '"' . __('IP Address', 'edd') . '",';
            echo '"' . __('Product', 'edd') . '",';
            echo '"' . __('File', 'edd') . '"';
            echo "\r\n";
            foreach ($downloads as $report) {
                $page = isset($_GET['paged']) ? intval($_GET['paged']) : 1;
                $download_log = new EDD_Logging();
                $file_downloads = $download_log->get_connected_logs(array('post_parent' => $report->ID, 'posts_per_page' => -1, 'log_type' => 'file_download', 'monthnum' => date('n'), 'year' => date('Y')));
                $files = edd_get_download_files($report->ID);
                if (is_array($file_downloads)) {
                    foreach ($file_downloads as $log) {
                        $user_info = get_post_meta($log->ID, '_edd_log_user_info', true);
                        $file_id = (int) get_post_meta($log->ID, '_edd_log_file_id', true);
                        $ip = get_post_meta($log->ID, '_edd_log_ip', true);
                        $user_id = isset($user_info['id']) ? $user_info['id'] : 0;
                        $user_data = get_userdata($user_id);
                        if ($user_data) {
                            $name = $user_data->display_name;
                        } else {
                            $name = $user_info['email'];
                        }
                        $file_id = (int) $file_id !== false ? $file_id : 0;
                        $file_name = isset($files[$file_id]['name']) ? $files[$file_id]['name'] : null;
                        echo '"' . $log->post_date . '",';
                        echo '"' . $name . '",';
                        echo '"' . $ip . '",';
                        echo '"' . html_entity_decode(get_the_title($report->ID)) . '",';
                        echo '"' . $file_name . '"';
                        echo "\r\n";
                    }
                    // endforeach
                }
            }
            exit;
        }
    } else {
        wp_die(__('Export not allowed for non-administrators.', 'edd'));
    }
}
/**
 * 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;
    }
}
/**
 * Process Download
 *
 * Handles the file download process.
 *
 * @access      private
 * @since       1.0
 * @return      void
 */
function edd_process_download()
{
    if (!isset($_GET['download_id']) && isset($_GET['download'])) {
        $_GET['download_id'] = $_GET['download'];
    }
    $args = apply_filters('edd_process_download_args', array('download' => isset($_GET['download_id']) ? (int) $_GET['download_id'] : '', 'email' => isset($_GET['email']) ? rawurldecode($_GET['email']) : '', 'expire' => isset($_GET['expire']) ? rawurldecode($_GET['expire']) : '', 'file_key' => isset($_GET['file']) ? (int) $_GET['file'] : '', 'price_id' => isset($_GET['price_id']) ? (int) $_GET['price_id'] : false, 'key' => isset($_GET['download_key']) ? $_GET['download_key'] : '', 'eddfile' => isset($_GET['eddfile']) ? $_GET['eddfile'] : '', 'ttl' => isset($_GET['ttl']) ? $_GET['ttl'] : '', 'token' => isset($_GET['token']) ? $_GET['token'] : ''));
    if (!empty($args['eddfile']) && !empty($args['ttl']) && !empty($args['token'])) {
        // Validate a signed URL that edd_process_signed_download_urlcontains a token
        $args = edd_process_signed_download_url($args);
        // Backfill some legacy super globals for backwards compatibility
        $_GET['download_id'] = $args['download'];
        $_GET['email'] = $args['email'];
        $_GET['expire'] = $args['expire'];
        $_GET['download_key'] = $args['key'];
        $_GET['price_id'] = $args['price_id'];
    } elseif (!empty($args['download']) && !empty($args['key']) && !empty($args['email']) && !empty($args['expire']) && isset($args['file_key'])) {
        // Validate a legacy URL without a token
        $args = edd_process_legacy_download_url($args);
    } else {
        return;
    }
    $args['has_access'] = apply_filters('edd_file_download_has_access', $args['has_access'], $args['payment'], $args);
    //$args['has_access'] = ( edd_logged_in_only() && is_user_logged_in() ) || !edd_logged_in_only() ? true : false;
    if ($args['payment'] && $args['has_access']) {
        do_action('edd_process_verified_download', $args['download'], $args['email'], $args['payment'], $args);
        // Determine the download method set in settings
        $method = edd_get_file_download_method();
        // Payment has been verified, setup the download
        $download_files = edd_get_download_files($args['download']);
        $attachment_id = !empty($download_files[$args['file_key']]['attachment_id']) ? absint($download_files[$args['file_key']]['attachment_id']) : false;
        /*
         * If we have an attachment ID stored, use get_attached_file() to retrieve absolute URL
         * If this fails or returns a relative path, we fail back to our own absolute URL detection
         */
        if ($attachment_id && 'attachment' == get_post_type($attachment_id)) {
            if ('redirect' == $method) {
                $attached_file = wp_get_attachment_url($attachment_id);
            } else {
                $attached_file = get_attached_file($attachment_id, false);
                // Confirm the file exists
                if (!file_exists($attached_file)) {
                    $attached_file = false;
                }
            }
            if ($attached_file) {
                $requested_file = $attached_file;
            }
        }
        // If we didn't find a file from the attachment, grab the given URL
        if (!isset($requested_file)) {
            $requested_file = isset($download_files[$args['file_key']]['file']) ? $download_files[$args['file_key']]['file'] : '';
        }
        // Allow the file to be altered before any headers are sent
        $requested_file = apply_filters('edd_requested_file', $requested_file, $download_files, $args['file_key']);
        if ('x_sendfile' == $method && (!function_exists('apache_get_modules') || !in_array('mod_xsendfile', apache_get_modules()))) {
            // If X-Sendfile is selected but is not supported, fallback to Direct
            $method = 'direct';
        }
        $file_details = parse_url($requested_file);
        $schemes = array('http', 'https');
        // Direct URL schemes
        if ((!isset($file_details['scheme']) || !in_array($file_details['scheme'], $schemes)) && isset($file_details['path']) && file_exists($requested_file)) {
            /**
             * Download method is seto to Redirect in settings but an absolute path was provided
             * We need to switch to a direct download in order for the file to download properly
             */
            $method = 'direct';
        }
        /**
         * Allow extensions to run actions prior to recording the file download log entry
         *
         * @since 2.6.14
         */
        do_action('edd_process_download_pre_record_log', $requested_file, $args, $method);
        // Record this file download in the log
        $user_info = array();
        $user_info['email'] = $args['email'];
        if (is_user_logged_in()) {
            $user_data = get_userdata(get_current_user_id());
            $user_info['id'] = get_current_user_id();
            $user_info['name'] = $user_data->display_name;
        }
        edd_record_download_in_log($args['download'], $args['file_key'], $user_info, edd_get_ip(), $args['payment'], $args['price_id']);
        $file_extension = edd_get_file_extension($requested_file);
        $ctype = edd_get_file_ctype($file_extension);
        if (!edd_is_func_disabled('set_time_limit') && !ini_get('safe_mode')) {
            @set_time_limit(0);
        }
        if (function_exists('get_magic_quotes_runtime') && get_magic_quotes_runtime() && version_compare(phpversion(), '5.4', '<')) {
            set_magic_quotes_runtime(0);
        }
        @session_write_close();
        if (function_exists('apache_setenv')) {
            @apache_setenv('no-gzip', 1);
        }
        @ini_set('zlib.output_compression', 'Off');
        do_action('edd_process_download_headers', $requested_file, $args['download'], $args['email'], $args['payment']);
        nocache_headers();
        header("Robots: none");
        header("Content-Type: " . $ctype . "");
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=\"" . apply_filters('edd_requested_file_name', basename($requested_file)) . "\"");
        header("Content-Transfer-Encoding: binary");
        // If the file isn't locally hosted, process the redirect
        if (filter_var($requested_file, FILTER_VALIDATE_URL) && !edd_is_local_file($requested_file)) {
            edd_deliver_download($requested_file, true);
            exit;
        }
        switch ($method) {
            case 'redirect':
                // Redirect straight to the file
                edd_deliver_download($requested_file, true);
                break;
            case 'direct':
            default:
                $direct = false;
                $file_path = $requested_file;
                if ((!isset($file_details['scheme']) || !in_array($file_details['scheme'], $schemes)) && isset($file_details['path']) && file_exists($requested_file)) {
                    /** This is an absolute path */
                    $direct = true;
                    $file_path = $requested_file;
                } else {
                    if (defined('UPLOADS') && strpos($requested_file, UPLOADS) !== false) {
                        /**
                         * This is a local file given by URL so we need to figure out the path
                         * UPLOADS is always relative to ABSPATH
                         * site_url() is the URL to where WordPress is installed
                         */
                        $file_path = str_replace(site_url(), '', $requested_file);
                        $file_path = realpath(ABSPATH . $file_path);
                        $direct = true;
                    } else {
                        if (strpos($requested_file, content_url()) !== false) {
                            /** This is a local file given by URL so we need to figure out the path */
                            $file_path = str_replace(content_url(), WP_CONTENT_DIR, $requested_file);
                            $file_path = realpath($file_path);
                            $direct = true;
                        } else {
                            if (strpos($requested_file, set_url_scheme(content_url(), 'https')) !== false) {
                                /** This is a local file given by an HTTPS URL so we need to figure out the path */
                                $file_path = str_replace(set_url_scheme(content_url(), 'https'), WP_CONTENT_DIR, $requested_file);
                                $file_path = realpath($file_path);
                                $direct = true;
                            }
                        }
                    }
                }
                // Set the file size header
                header("Content-Length: " . @filesize($file_path));
                // Now deliver the file based on the kind of software the server is running / has enabled
                if (stristr(getenv('SERVER_SOFTWARE'), 'lighttpd')) {
                    header("X-LIGHTTPD-send-file: {$file_path}");
                } elseif ($direct && (stristr(getenv('SERVER_SOFTWARE'), 'nginx') || stristr(getenv('SERVER_SOFTWARE'), 'cherokee'))) {
                    // We need a path relative to the domain
                    $file_path = str_ireplace(realpath($_SERVER['DOCUMENT_ROOT']), '', $file_path);
                    header("X-Accel-Redirect: /{$file_path}");
                }
                if ($direct) {
                    edd_deliver_download($file_path);
                } else {
                    // The file supplied does not have a discoverable absolute path
                    edd_deliver_download($requested_file, true);
                }
                break;
        }
        edd_die();
    } else {
        $error_message = __('You do not have permission to download this file', 'easy-digital-downloads');
        wp_die(apply_filters('edd_deny_download_message', $error_message, __('Purchase Verification Failed', 'easy-digital-downloads')), __('Error', 'easy-digital-downloads'), array('response' => 403));
    }
    exit;
}
/**
 * The free download process.
 * 
 * Modified from:
 * /includes/process-download.php -> edd_process_download()
 * Modifed parts:
 * Stripping the purchase validation process.
 *
 * @return void
 */
function vp_edd_fd_process_download()
{
    global $edd_options;
    $valid = true;
    $payment = -1;
    $download = isset($_GET['did']) ? (int) $_GET['did'] : '';
    $expire = isset($_GET['expire']) ? base64_decode(rawurldecode($_GET['expire'])) : '';
    $file_key = isset($_GET['file']) ? (int) $_GET['file'] : '';
    // if( $download === '' || $email === '' || $file_key === '' )
    if ($download === '' || $file_key === '') {
        return false;
    }
    // make sure user logged in
    $must_logged_in = isset($edd_options['vp_edd_fd_must_logged_in']) ? $edd_options['vp_edd_fd_must_logged_in'] : false;
    if ($must_logged_in) {
        if (!is_user_logged_in()) {
            $valid = false;
        }
    }
    // Make sure the link hasn't expired
    if (current_time('timestamp') > $expire) {
        wp_die(apply_filters('edd_download_link_expired_text', __('Sorry but your download link has expired.', 'edd')), __('Error', 'edd'));
    }
    // Check to see if the file download limit has been reached
    if (edd_is_file_at_download_limit($download, -1, $file_key)) {
        wp_die(apply_filters('edd_download_limit_reached_text', __('Sorry but you have hit your download limit for this file.', 'edd')), __('Error', 'edd'));
    }
    if ($valid) {
        // setup the download
        $download_files = edd_get_download_files($download);
        $requested_file = apply_filters('edd_requested_file', $download_files[$file_key]['file'], $download_files, $file_key);
        // gather user data
        $user_info = array();
        if ($must_logged_in) {
            global $user_ID;
            $user_data = get_userdata($user_ID);
            $user_info['email'] = $user_data->user_email;
            $user_info['id'] = $user_ID;
            $user_info['name'] = $user_data->display_name;
        } else {
            $user_info['email'] = 'anonymous';
            $user_info['id'] = 'anonymous';
        }
        edd_record_download_in_log($download, $file_key, $user_info, edd_get_ip(), $payment);
        $file_extension = edd_get_file_extension($requested_file);
        $ctype = edd_get_file_ctype($file_extension);
        if (!edd_is_func_disabled('set_time_limit') && !ini_get('safe_mode')) {
            set_time_limit(0);
        }
        if (function_exists('get_magic_quotes_runtime') && get_magic_quotes_runtime()) {
            set_magic_quotes_runtime(0);
        }
        @session_write_close();
        if (function_exists('apache_setenv')) {
            @apache_setenv('no-gzip', 1);
        }
        @ini_set('zlib.output_compression', 'Off');
        nocache_headers();
        header("Robots: none");
        header("Content-Type: " . $ctype . "");
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=\"" . apply_filters('edd_requested_file_name', basename($requested_file)) . "\";");
        header("Content-Transfer-Encoding: binary");
        $file_path = realpath($requested_file);
        if (strpos($requested_file, 'http://') === false && strpos($requested_file, 'https://') === false && strpos($requested_file, 'ftp://') === false && file_exists($file_path)) {
            /** This is an absolute path */
            edd_deliver_download($file_path);
        } else {
            if (strpos($requested_file, WP_CONTENT_URL) !== false) {
                /** This is a local file given by URL */
                $upload_dir = wp_upload_dir();
                $file_path = str_replace(WP_CONTENT_URL, WP_CONTENT_DIR, $requested_file);
                $file_path = realpath($file_path);
                if (file_exists($file_path)) {
                    edd_deliver_download($file_path);
                } else {
                    // Absolute path couldn't be discovered so send straight to the file URL
                    header("Location: " . $requested_file);
                }
            } else {
                // This is a remote file
                header("Location: " . $requested_file);
            }
        }
        exit;
    } else {
        wp_die(apply_filters('edd_deny_download_message', __('You do not have permission to download this file.', 'vp_edd_fd')), __('Error', 'edd'));
    }
    exit;
}
Esempio n. 14
0
/**
 * Process a settings export that generates a .json file of the shop settings
 *
 * @since       1.7
 * @return      void
 */
function edd_tools_import_export_process_export()
{
    if (empty($_POST['edd_export_nonce'])) {
        return;
    }
    if (!wp_verify_nonce($_POST['edd_export_nonce'], 'edd_export_nonce')) {
        return;
    }
    if (!current_user_can('manage_shop_settings')) {
        return;
    }
    $settings = array();
    $settings = get_option('edd_settings');
    ignore_user_abort(true);
    if (!edd_is_func_disabled('set_time_limit') && !ini_get('safe_mode')) {
        set_time_limit(0);
    }
    nocache_headers();
    header('Content-Type: application/json; charset=utf-8');
    header('Content-Disposition: attachment; filename=' . apply_filters('edd_settings_export_filename', 'edd-settings-export-' . date('m-d-Y')) . '.json');
    header("Expires: 0");
    echo json_encode($settings);
    exit;
}
Esempio n. 15
0
/**
 * Run the upgrade to generate licenses for past bundle purchases
 *
 * @since  3.2
 * @return void
 */
function edd_sl_v32_add_bundle_licenses()
{
    global $wpdb;
    if (!current_user_can('manage_shop_settings')) {
        wp_die(__('You do not have permission to do shop upgrades', 'edd'), __('Error', 'edd'), array('response' => 403));
    }
    ignore_user_abort(true);
    if (!edd_is_func_disabled('set_time_limit') && !ini_get('safe_mode')) {
        @set_time_limit(0);
    }
    $step = isset($_GET['step']) ? absint($_GET['step']) : 1;
    $number = 25;
    $offset = $step == 1 ? 0 : ($step - 1) * $number;
    // Get the upgrade type...if none provided, dismiss is used and no further action is taken
    $custom = isset($_GET['custom']) ? absint($_GET['custom']) : 0;
    if ($step < 2) {
        // User chose to not run any upgrades
        if (0 === $custom) {
            update_option('edd_sl_version', preg_replace('/[^0-9.].*/', '', EDD_SL_VERSION));
            edd_set_upgrade_complete('sl_add_bundle_licenses');
            delete_option('edd_doing_upgrade');
            wp_redirect(admin_url());
            exit;
        }
        // Check if we have any payments before moving on
        $sql = "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'edd_payment' LIMIT 1";
        $has_payments = $wpdb->get_col($sql);
        if (empty($has_payments)) {
            // We had no payments, just complete
            update_option('edd_sl_version', preg_replace('/[^0-9.].*/', '', EDD_SL_VERSION));
            edd_set_upgrade_complete('sl_add_bundle_licenses');
            delete_option('edd_doing_upgrade');
            wp_redirect(admin_url());
            exit;
        }
        // Check if we have any bundle products as well
        $sql = "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_edd_bundled_products' LIMIT 1";
        $has_bundles = $wpdb->get_col($sql);
        if (empty($has_bundles)) {
            // We had no bundles, just complete
            update_option('edd_sl_version', preg_replace('/[^0-9.].*/', '', EDD_SL_VERSION));
            edd_set_upgrade_complete('sl_add_bundle_licenses');
            delete_option('edd_doing_upgrade');
            wp_redirect(admin_url());
            exit;
        }
    }
    $sql = "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_edd_bundled_products'";
    $bundle_download_ids = $wpdb->get_col($sql);
    foreach ($bundle_download_ids as $key => $bundle_id) {
        $licenses_enabled = get_post_meta($bundle_id, '_edd_sl_enabled', false);
        if (empty($licenses_enabled)) {
            unset($bundle_download_ids[$key]);
        }
    }
    // If we ended up with no bundles that have licensing enabled, just exit as well
    if (empty($bundle_download_ids)) {
        update_option('edd_sl_version', preg_replace('/[^0-9.].*/', '', EDD_SL_VERSION));
        edd_set_upgrade_complete('sl_add_bundle_licenses');
        delete_option('edd_doing_upgrade');
        wp_redirect(admin_url());
        exit;
    }
    $total = isset($_GET['total']) ? absint($_GET['total']) : false;
    if (empty($total) || $total <= 1) {
        $args = array('number' => -1, 'download' => $bundle_download_ids);
        $all_payments = new EDD_Payments_Query($args);
        $all_payments = $all_payments->get_payments();
        $total = count($all_payments);
    }
    $payment_args = array('order' => 'ASC', 'orderby' => 'ID', 'number' => $number, 'page' => $step, 'download' => $bundle_download_ids);
    $payments = new EDD_Payments_Query($payment_args);
    $payments = $payments->get_payments();
    $bundle_contents = array();
    if (!empty($payments)) {
        foreach ($payments as $payment) {
            $cart_details = edd_get_payment_meta_downloads($payment->ID);
            foreach ($cart_details as $cart_index => $cart_item) {
                if (!in_array($cart_item['id'], $bundle_download_ids)) {
                    // Item is not a bundled product, move along
                    continue;
                }
                // See if there is a bundle license already
                $bundle_license = edd_software_licensing()->get_license_by_purchase($payment->ID, $cart_item['id']);
                // It not create the bundle license
                if (empty($bundle_license)) {
                    $bundle_license = edd_software_licensing()->generate_license($cart_item['id'], $payment->ID, 'default', $cart_item, $cart_index);
                    $bundle_license = edd_software_licensing()->get_license_by_purchase($payment->ID, $cart_item['id'], $cart_index);
                }
                // If we haven't retrieved the bundle contents yet, get them
                if (!isset($bundle_contents[$cart_item['id']])) {
                    $bundle_contents[$cart_item['id']] = edd_get_bundled_products($cart_item['id']);
                }
                // Get the products in the bundle
                $bundle_products = $bundle_contents[$cart_item['id']];
                // For every bundle in the download, get the license for this payment, and update it's post_parent
                foreach ($bundle_products as $license_download_id) {
                    $license = edd_software_licensing()->get_license_by_purchase($payment->ID, $license_download_id);
                    if (empty($license)) {
                        continue;
                    }
                    $update_args = array('ID' => $license->ID, 'post_parent' => $bundle_license->ID);
                    wp_update_post($update_args);
                }
            }
        }
        // More Payments found so upgrade them
        $step++;
        $redirect = add_query_arg(array('page' => 'edd-upgrades', 'edd-upgrade' => 'sl_add_bundle_licenses', 'step' => $step, 'number' => $number, 'total' => $total, 'custom' => $custom), admin_url('index.php'));
        wp_safe_redirect($redirect);
        exit;
    } else {
        // No more data to update. Downloads have been altered or dismissed
        update_option('edd_sl_version', preg_replace('/[^0-9.].*/', '', EDD_SL_VERSION));
        edd_set_upgrade_complete('sl_add_bundle_licenses');
        delete_option('edd_doing_upgrade');
        wp_redirect(admin_url());
        exit;
    }
}
/**
 * Converts old sale and file download logs to new logging system
 *
 * @since 1.3.1
 * @uses WP_Query
 * @uses EDD_Logging
 * @return void
 */
function edd_v131_upgrades()
{
    if (get_option('edd_logs_upgraded')) {
        return;
    }
    if (version_compare(get_option('edd_version'), '1.3', '>=')) {
        return;
    }
    ignore_user_abort(true);
    if (!edd_is_func_disabled('set_time_limit') && !ini_get('safe_mode')) {
        set_time_limit(0);
    }
    $args = array('post_type' => 'download', 'posts_per_page' => -1, 'post_status' => 'publish');
    $query = new WP_Query($args);
    $count = $query->post_count;
    $downloads = $query->get_posts();
    if ($downloads) {
        $edd_log = new EDD_Logging();
        $i = 0;
        foreach ($downloads as $download) {
            // Convert sale logs
            $sale_logs = edd_get_download_sales_log($download->ID, false);
            if ($sale_logs) {
                foreach ($sale_logs['sales'] as $sale) {
                    $log_data = array('post_parent' => $download->ID, 'post_date' => $sale['date'], 'log_type' => 'sale');
                    $log_meta = array('payment_id' => $sale['payment_id']);
                    $log = $edd_log->insert_log($log_data, $log_meta);
                }
            }
            // Convert file download logs
            $file_logs = edd_get_file_download_log($download->ID, false);
            if ($file_logs) {
                foreach ($file_logs['downloads'] as $log) {
                    $log_data = array('post_parent' => $download->ID, 'post_date' => $log['date'], 'log_type' => 'file_download');
                    $log_meta = array('user_info' => $log['user_info'], 'file_id' => $log['file_id'], 'ip' => $log['ip']);
                    $log = $edd_log->insert_log($log_data, $log_meta);
                }
            }
        }
    }
    add_option('edd_logs_upgraded', '1');
}
/**
 * Process Download
 *
 * Handles the file download process.
 *
 * @access      private
 * @since       1.0
 * @return      void
*/
function edd_process_download()
{
    $args = apply_filters('edd_process_download_args', array('download' => isset($_GET['download']) ? (int) $_GET['download'] : '', 'email' => isset($_GET['email']) ? rawurldecode($_GET['email']) : '', 'expire' => isset($_GET['expire']) ? base64_decode(rawurldecode($_GET['expire'])) : '', 'file_key' => isset($_GET['file']) ? (int) $_GET['file'] : '', 'key' => isset($_GET['download_key']) ? $_GET['download_key'] : ''));
    if ($args['download'] === '' || $args['email'] === '' || $args['file_key'] === '') {
        return false;
    }
    extract($args);
    $payment = edd_verify_download_link($download, $key, $email, $expire, $file_key);
    // Defaulting this to true for now because the method below doesn't work well
    $has_access = apply_filters('edd_file_download_has_access', true, $payment, $args);
    //$has_access = ( edd_logged_in_only() && is_user_logged_in() ) || !edd_logged_in_only() ? true : false;
    if ($payment && $has_access) {
        do_action('edd_process_verified_download', $download, $email);
        // payment has been verified, setup the download
        $download_files = edd_get_download_files($download);
        $requested_file = apply_filters('edd_requested_file', $download_files[$file_key]['file']);
        $user_info = array();
        $user_info['email'] = $email;
        if (is_user_logged_in()) {
            global $user_ID;
            $user_data = get_userdata($user_ID);
            $user_info['id'] = $user_ID;
            $user_info['name'] = $user_data->display_name;
        }
        edd_record_download_in_log($download, $file_key, $user_info, edd_get_ip(), $payment);
        $file_extension = edd_get_file_extension($requested_file);
        $ctype = edd_get_file_ctype($file_extension);
        if (!edd_is_func_disabled('set_time_limit') && !ini_get('safe_mode')) {
            set_time_limit(0);
        }
        if (function_exists('get_magic_quotes_runtime') && get_magic_quotes_runtime()) {
            set_magic_quotes_runtime(0);
        }
        @session_write_close();
        if (function_exists('apache_setenv')) {
            @apache_setenv('no-gzip', 1);
        }
        @ini_set('zlib.output_compression', 'Off');
        @ob_end_clean();
        if (ob_get_level()) {
            @ob_end_clean();
        }
        // Zip corruption fix
        nocache_headers();
        header("Robots: none");
        header("Content-Type: " . $ctype . "");
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=\"" . apply_filters('edd_requested_file_name', basename($requested_file)) . "\";");
        header("Content-Transfer-Encoding: binary");
        if (strpos($requested_file, 'http://') === false && strpos($requested_file, 'https://') === false && strpos($requested_file, 'ftp://') === false) {
            // this is an absolute path
            $requested_file = realpath($requested_file);
            if (file_exists($requested_file)) {
                if ($size = @filesize($requested_file)) {
                    header("Content-Length: " . $size);
                }
                @edd_readfile_chunked($requested_file);
            } else {
                wp_die(__('Sorry but this file does not exist.', 'edd'), __('Error', 'edd'));
            }
        } else {
            if (strpos($requested_file, WP_CONTENT_URL) !== false) {
                // This is a local file given by URL
                $upload_dir = wp_upload_dir();
                $requested_file = str_replace(WP_CONTENT_URL, WP_CONTENT_DIR, $requested_file);
                $requested_file = realpath($requested_file);
                if (file_exists($requested_file)) {
                    if ($size = @filesize($requested_file)) {
                        header("Content-Length: " . $size);
                    }
                    @edd_readfile_chunked($requested_file);
                } else {
                    wp_die(__('Sorry but this file does not exist.', 'edd'), __('Error', 'edd'));
                }
            } else {
                // This is a remote file
                header("Location: " . $requested_file);
            }
        }
        exit;
    } else {
        $error_message = __('You do not have permission to download this file', 'edd');
        wp_die(apply_filters('edd_deny_download_message', $error_message, __('Purchase Verification Failed', 'edd')));
    }
    exit;
}
/**
 * Upgrade the Usermeta API Key storage to swap keys/values for performance
 *
 * @since  2.4
 * @return void
 */
function edd_upgrade_user_api_keys()
{
    global $wpdb;
    if (!current_user_can('manage_shop_settings')) {
        wp_die(__('You do not have permission to do shop upgrades', 'edd'), __('Error', 'edd'), array('response' => 403));
    }
    ignore_user_abort(true);
    if (!edd_is_func_disabled('set_time_limit') && !ini_get('safe_mode')) {
        @set_time_limit(0);
    }
    $step = isset($_GET['step']) ? absint($_GET['step']) : 1;
    $number = 10;
    $offset = $step == 1 ? 0 : ($step - 1) * $number;
    if ($step < 2) {
        // Check if we have any users with API Keys before moving on
        $sql = "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = 'edd_user_public_key' LIMIT 1";
        $has_key = $wpdb->get_col($sql);
        if (empty($has_key)) {
            // We had no key, just complete
            update_option('edd_version', preg_replace('/[^0-9.].*/', '', EDD_VERSION));
            edd_set_upgrade_complete('upgrade_user_api_keys');
            delete_option('edd_doing_upgrade');
            wp_redirect(admin_url());
            exit;
        }
    }
    $total = isset($_GET['total']) ? absint($_GET['total']) : false;
    if (empty($total) || $total <= 1) {
        $total = $wpdb->get_var("SELECT count(user_id) FROM {$wpdb->usermeta} WHERE meta_key = 'edd_user_public_key'");
    }
    $keys_sql = $wpdb->prepare("SELECT user_id, meta_key, meta_value FROM {$wpdb->usermeta} WHERE meta_key = 'edd_user_public_key' OR meta_key = 'edd_user_secret_key' ORDER BY user_id ASC LIMIT %d,%d;", $offset, $number);
    $found_keys = $wpdb->get_results($keys_sql);
    if (!empty($found_keys)) {
        foreach ($found_keys as $key) {
            $user_id = $key->user_id;
            $meta_key = $key->meta_key;
            $meta_value = $key->meta_value;
            // Generate a new entry
            update_user_meta($user_id, $meta_value, $meta_key);
            // Delete the old one
            delete_user_meta($user_id, $meta_key);
        }
        // More Payments found so upgrade them
        $step++;
        $redirect = add_query_arg(array('page' => 'edd-upgrades', 'edd-upgrade' => 'upgrade_user_api_keys', 'step' => $step, 'number' => $number, 'total' => $total), admin_url('index.php'));
        wp_redirect($redirect);
        exit;
    } else {
        // No more customers found, finish up
        update_option('edd_version', preg_replace('/[^0-9.].*/', '', EDD_VERSION));
        edd_set_upgrade_complete('upgrade_user_api_keys');
        delete_option('edd_doing_upgrade');
        wp_redirect(admin_url());
        exit;
    }
}
/**
 * Upgrades for EDD v2.1 and the new customers database
 *
 * @since 2.1
 * @return void
 */
function edd_v21_upgrade_customers_db()
{
    global $wpdb;
    ignore_user_abort(true);
    if (!edd_is_func_disabled('set_time_limit') && !ini_get('safe_mode')) {
        @set_time_limit(0);
    }
    if (!get_option('edd_upgrade_customers_db_version')) {
        // Create the customers database on the first run
        @EDD()->customers->create_table();
    }
    $step = isset($_GET['step']) ? absint($_GET['step']) : 1;
    $number = 20;
    $offset = $step == 1 ? 0 : ($step - 1) * $number;
    $emails = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT meta_value FROM {$wpdb->postmeta} WHERE meta_key = '_edd_payment_user_email' LIMIT %d,%d;", $offset, $number));
    if ($emails) {
        foreach ($emails as $email) {
            if (EDD()->customers->exists($email)) {
                continue;
                // Allow the upgrade routine to be safely re-run in the case of failure
            }
            $args = array('user' => $email, 'order' => 'ASC', 'orderby' => 'ID', 'number' => -1, 'page' => $step);
            $payments = new EDD_Payments_Query($args);
            $payments = $payments->get_payments();
            if ($payments) {
                $total_value = 0.0;
                $total_count = 0;
                foreach ($payments as $payment) {
                    $status = get_post_status($payment->ID);
                    if ('revoked' == $status || 'publish' == $status) {
                        $total_value += $payment->total;
                        $total_count += 1;
                    }
                }
                $ids = wp_list_pluck($payments, 'ID');
                $user = get_user_by('email', $email);
                $args = array('email' => $email, 'user_id' => $user ? $user->ID : 0, 'name' => $user ? $user->display_name : '', 'purchase_count' => $total_count, 'purchase_value' => round($total_value, 2), 'payment_ids' => implode(',', array_map('absint', $ids)), 'date_created' => $payments[0]->date);
                $customer_id = EDD()->customers->add($args);
                foreach ($ids as $id) {
                    update_post_meta($id, '_edd_payment_customer_id', $customer_id);
                }
            }
        }
        // Customers found so upgrade them
        $step++;
        $redirect = add_query_arg(array('page' => 'edd-upgrades', 'edd-upgrade' => 'upgrade_customers_db', 'step' => $step), admin_url('index.php'));
        wp_redirect($redirect);
        exit;
    } else {
        // No more customers found, finish up
        update_option('edd_version', preg_replace('/[^0-9.].*/', '', EDD_VERSION));
        wp_redirect(admin_url());
        exit;
    }
}
 public function headers()
 {
     ignore_user_abort(true);
     if (!edd_is_func_disabled('set_time_limit') && !ini_get('safe_mode')) {
         set_time_limit(0);
     }
 }
 public function headers()
 {
     ignore_user_abort(true);
     if (!edd_is_func_disabled('set_time_limit') && !ini_get('safe_mode')) {
         set_time_limit(0);
     }
     nocache_headers();
     header("Location: " . admin_url('edit.php?post_type=download&page=edd-tools&tab=general'));
 }