/**
 * Verifies a download purchase using a purchase key and email.
 *
 * @deprecated Please avoid usage of this function in favor of the tokenized urls with edd_validate_url_token()
 * introduced in EDD 2.3
 *
 * @since 1.0
 *
 * @param int    $download_id
 * @param string $key
 * @param string $email
 * @param string $expire
 * @param int    $file_key
 *
 * @return bool True if payment and link was verified, false otherwise
 */
function edd_verify_download_link($download_id = 0, $key = '', $email = '', $expire = '', $file_key = 0)
{
    $meta_query = array('relation' => 'AND', array('key' => '_edd_payment_purchase_key', 'value' => $key), array('key' => '_edd_payment_user_email', 'value' => $email));
    $accepted_stati = apply_filters('edd_allowed_download_stati', array('publish', 'complete'));
    $payments = get_posts(array('meta_query' => $meta_query, 'post_type' => 'edd_payment', 'post_status' => $accepted_stati));
    if ($payments) {
        foreach ($payments as $payment) {
            $cart_details = edd_get_payment_meta_cart_details($payment->ID, true);
            if (!empty($cart_details)) {
                foreach ($cart_details as $cart_key => $cart_item) {
                    if ($cart_item['id'] != $download_id) {
                        continue;
                    }
                    $price_options = isset($cart_item['item_number']['options']) ? $cart_item['item_number']['options'] : false;
                    $price_id = isset($price_options['price_id']) ? $price_options['price_id'] : false;
                    $file_condition = edd_get_file_price_condition($cart_item['id'], $file_key);
                    // Check to see if the file download limit has been reached
                    if (edd_is_file_at_download_limit($cart_item['id'], $payment->ID, $file_key, $price_id)) {
                        wp_die(apply_filters('edd_download_limit_reached_text', __('Sorry but you have hit your download limit for this file.', 'edd')), __('Error', 'edd'), array('response' => 403));
                    }
                    // If this download has variable prices, we have to confirm that this file was included in their purchase
                    if (!empty($price_options) && $file_condition != 'all' && edd_has_variable_prices($cart_item['id'])) {
                        if ($file_condition == $price_options['price_id']) {
                            return $payment->ID;
                        }
                    }
                    // Make sure the link hasn't expired
                    if (base64_encode(base64_decode($expire, true)) === $expire) {
                        $expire = base64_decode($expire);
                        // If it is a base64 string, decode it. Old expiration dates were in base64
                    }
                    if (current_time('timestamp') > $expire) {
                        wp_die(apply_filters('edd_download_link_expired_text', __('Sorry but your download link has expired.', 'edd')), __('Error', 'edd'), array('response' => 403));
                    }
                    return $payment->ID;
                    // Payment has been verified and link is still valid
                }
            }
        }
    } else {
        wp_die(__('No payments matching your request were found.', 'edd'), __('Error', 'edd'), array('response' => 403));
    }
    // Payment not verified
    return false;
}
/**
 * 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;
}
/**
 * Used to process a signed URL for processing downloads
 *
 * @since  2.3
 * @param  array $args Arguments provided to download a file
 * @return array       Same arguments, with the status of verification added
 */
function edd_process_signed_download_url($args)
{
    $parts = parse_url(add_query_arg(array()));
    wp_parse_str($parts['query'], $query_args);
    $url = add_query_arg($query_args, site_url());
    $valid_token = edd_validate_url_token($url);
    // Bail if the token isn't valid.
    // The request should pass through EDD, or custom handling can be enabled with the action.
    if (!$valid_token) {
        $args['payment'] = false;
        $args['has_access'] = false;
        return $args;
    }
    $order_parts = explode(':', rawurldecode($_GET['eddfile']));
    // Check to make sure not at download limit
    if (edd_is_file_at_download_limit($order_parts[1], $order_parts[0], $order_parts[2], $order_parts[3])) {
        wp_die(apply_filters('edd_download_limit_reached_text', __('Sorry but you have hit your download limit for this file.', 'easy-digital-downloads')), __('Error', 'easy-digital-downloads'), array('response' => 403));
    }
    $args['expire'] = $_GET['ttl'];
    $args['download'] = $order_parts[1];
    $args['payment'] = $order_parts[0];
    $args['file_key'] = $order_parts[2];
    $args['price_id'] = $order_parts[3];
    $args['email'] = get_post_meta($order_parts[0], '_edd_payment_user_email', true);
    $args['key'] = get_post_meta($order_parts[0], '_edd_payment_purchase_key', true);
    $payment = new EDD_Payment($args['payment']);
    $args['has_access'] = 'publish' === $payment->status ? true : false;
    return $args;
}
/**
 * Verify Download Link
 *
 * Verifies a download purchase using a purchase key and email.
 *
 * @access      public
 * @since       1.0
 * @return      boolean
*/
function edd_verify_download_link($download_id, $key, $email, $expire, $file_key)
{
    $meta_query = array('relation' => 'AND', array('key' => '_edd_payment_purchase_key', 'value' => $key), array('key' => '_edd_payment_user_email', 'value' => $email));
    $payments = get_posts(array('meta_query' => $meta_query, 'post_type' => 'edd_payment'));
    if ($payments) {
        foreach ($payments as $payment) {
            $payment_meta = get_post_meta($payment->ID, '_edd_payment_meta', true);
            $downloads = maybe_unserialize($payment_meta['downloads']);
            $cart_details = unserialize($payment_meta['cart_details']);
            if ($payment->post_status != 'publish' && $payment->post_status != 'complete') {
                return false;
            }
            if ($downloads) {
                foreach ($downloads as $key => $download) {
                    $id = isset($payment_meta['cart_details']) ? $download['id'] : $download;
                    $price_options = $cart_details[$key]['item_number']['options'];
                    $file_condition = edd_get_file_price_condition($id, $file_key);
                    $variable_prices_enabled = get_post_meta($id, '_variable_pricing', true);
                    // if this download has variable prices, we have to confirm that this file was included in their purchase
                    if (!empty($price_options) && $file_condition != 'all' && $variable_prices_enabled) {
                        if ($file_condition !== $price_options['price_id']) {
                            return false;
                        }
                    }
                    if ($id == $download_id) {
                        // check to see if the file download limit has been reached
                        if (edd_is_file_at_download_limit($id, $payment->ID, $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'));
                        }
                        // make sure the link hasn't expired
                        if (time() < $expire) {
                            return $payment->ID;
                            // payment has been verified and link is still valid
                        }
                        return false;
                        // payment verified, but link is no longer valid
                    }
                }
            }
        }
    }
    // payment not verified
    return false;
}