<?php

if (!defined('ABSPATH')) {
    die('Error!');
}
do_action("wpdm_onstart_download", $package);
global $current_user, $dfiles;
$speed = 1024;
//in KB - default 1 MB
$speed = apply_filters('wpdm_download_speed', $speed);
get_currentuserinfo();
if (wpdm_is_download_limit_exceed($package['ID'])) {
    wp_die(__('Download Limit Exceeded', 'wpdmpro'));
}
$files = \WPDM\Package::getFiles($package['ID']);
$fileCount = count($files);
$log = new WPDM_Stats();
$oid = isset($_GET['oid']) ? esc_attr($_GET['oid']) : '';
$indsc = 1;
$indsc = isset($_GET['ind']) && get_option('__wpdm_ind_stats') == 0 ? 0 : 1;
if ($indsc && !isset($_GET['nostat'])) {
    $log->NewStat($package['ID'], $current_user->ID, $oid);
}
if ($fileCount == 0) {
    if (isset($package['sourceurl']) && $package['sourceurl'] != '') {
        if (!isset($package['url_protect']) || $package['url_protect'] == 0 && strpos($package['sourceurl'], '://')) {
            header('location: ' . $package['sourceurl']);
            die;
        }
        $r_filename = basename($package['sourceurl']);
        $r_filename = explode("?", $r_filename);
$order_fields = array('__wpdm_download_count', '__wpdm_view_count', '__wpdm_package_size_b');
if (!in_array("__wpdm_" . $order_field, $order_fields)) {
    $query_params['orderby'] = $order_field;
    $query_params['order'] = $order;
} else {
    $query_params['orderby'] = 'meta_value_num';
    $query_params['meta_key'] = "__wpdm_" . $order_field;
    $query_params['order'] = $order;
}
$q = new WP_Query($query_params);
$total_files = $q->found_posts;
while ($q->have_posts()) {
    $q->the_post();
    $ext = "_blank";
    $data = wpdm_custom_data(get_the_ID());
    $data['files'] = \WPDM\Package::getFiles(get_the_ID());
    if (isset($data['files']) && count($data['files']) > 0) {
        $tfiles = $data['files'];
        $tfile = array_shift($tfiles);
        $tmpvar = explode(".", $tfile);
        $ext = count($tmpvar) > 1 ? end($tmpvar) : $ext;
    } else {
        $data['files'] = array();
    }
    $ext = isset($data['icon']) && $data['icon'] != '' ? $data['icon'] : $ext . ".png";
    $cats = wp_get_post_terms(get_the_ID(), 'wpdmcategory');
    $fcats = array();
    foreach ($cats as $cat) {
        $fcats[] = "<a class='sbyc' href='{$cfurl}{$cat->slug}'>{$cat->name}</a>";
    }
    $cats = @implode(", ", $fcats);