<?php
/*
=====================================================
 DataLife Engine - by SoftNews Media Group
-----------------------------------------------------
 https://dle-news.ru/
-----------------------------------------------------
 Copyright (c) 2004-2025 SoftNews Media Group
=====================================================
 This code is protected by copyright
=====================================================
 File: downloads.php
-----------------------------------------------------
 Use: Top downloads page
=====================================================
*/

if( !defined('DATALIFEENGINE') ) {
	header( "HTTP/1.1 403 Forbidden" );
	header ( 'Location: ../../' );
	die( "Hacking attempt!" );
}

$allow_add_comment = false;
$allow_full_story = false;
$allow_comments = false;
$allow_userinfo = false;
$allow_active_news = true;
$config['allow_cache'] = false;

if( !isset($cstart) ) $cstart = 0;

// DLE uses cstart as page number in URL, convert to offset
if( $cstart ) {
	$cstart = $cstart - 1;
	$cstart = $cstart * $config['news_number'];
}

$cstart = intval($cstart);

$navigation_first_page = $config['http_home_url'] . "index.php?do=downloads";
$url_page = $navigation_first_page . "&cstart={cstart}";
$canonical = $navigation_first_page;

// Respect "no future" setting
$thisdate = date ( "Y-m-d H:i:s", time() );
if( $config['no_date'] AND !$config['news_future'] ) {
	$where_date = " AND p.date < '" . $thisdate . "'";
} else {
	$where_date = "";
}

$stop_list = "";
$allow_list = explode( ',', $user_group[$member_id['user_group']]['allow_cats'] );
$cat_join = "";

if( $allow_list[0] != "all" ) {
	if( $config['allow_multi_category'] ) {
		$cat_join = "INNER JOIN (SELECT DISTINCT(" . PREFIX . "_post_extras_cats.news_id) FROM " . PREFIX . "_post_extras_cats WHERE cat_id IN ('" . implode( "','", $allow_list ) . "')) c ON (p.id=c.news_id) ";
	} else {
		$stop_list = "category IN ('" . implode( "','", $allow_list ) . "') AND ";
	}
}

$not_allow_cats = explode( ',', $user_group[$member_id['user_group']]['not_allow_cats'] );

if( $not_allow_cats[0] != "" ) {
	if( $config['allow_multi_category'] ) {
		$stop_list = "p.id NOT IN ( SELECT DISTINCT(" . PREFIX . "_post_extras_cats.news_id) FROM " . PREFIX . "_post_extras_cats WHERE cat_id IN ('" . implode( "','", $not_allow_cats ) . "') ) AND ";
	} else {
		$stop_list = "category NOT IN ('" . implode( "','", $not_allow_cats ) . "') AND ";
	}
}

if( $user_group[$member_id['user_group']]['allow_short'] ) {
	$stop_list = "";
	$cat_join = "";
}

if( $config['user_in_news'] ) {
	$user_select = ", u.email, u.name, u.user_id, u.news_num, u.comm_num as user_comm_num, u.user_group, u.lastdate, u.reg_date, u.banned, u.allow_mail, u.info, u.signature, u.foto, u.fullname, u.land, u.favorites, u.pm_all, u.pm_unread, u.time_limit, u.xfields as user_xfields ";
	$user_join = "LEFT JOIN " . USERPREFIX . "_users u ON (e.user_id=u.user_id) ";
} else {
	$user_select = "";
	$user_join = "";
}

// 1) Get ordered IDs by total downloads; fallback to views if downloads are zero
// NOTE: downloads are counted per attached file via engine/download.php and stored in PREFIX_files.dcount
// Some tracks may have no attached files; those will have downloads=0 and will be ordered by views.
$sql_select_ids = "SELECT p.id, COALESCE(SUM(f.dcount), 0) AS downloads, MAX(e.news_read) AS views FROM " . PREFIX . "_post p "
	. "LEFT JOIN " . PREFIX . "_files f ON (f.news_id=p.id) "
	. "LEFT JOIN " . PREFIX . "_post_extras e ON (p.id=e.news_id) "
	. $cat_join
	. "WHERE " . $stop_list . "p.approve=1" . $where_date . " GROUP BY p.id "
	. "ORDER BY downloads DESC, views DESC, p.date DESC LIMIT " . $cstart . "," . $config['news_number'];

$sql_ids = $db->super_query($sql_select_ids, true);

if( is_array($sql_ids) AND count($sql_ids) ) {
	$temp_arr = array();
	foreach( $sql_ids as $value ) {
		$temp_arr[] = intval($value['id']);
	}

	$sql_select_ids = implode(',', $temp_arr);

	// 2) Count total items for pagination
	$sql_count = "SELECT COUNT(DISTINCT p.id) as count FROM " . PREFIX . "_post p "
		. "LEFT JOIN " . PREFIX . "_files f ON (f.news_id=p.id) "
		. "LEFT JOIN " . PREFIX . "_post_extras e ON (p.id=e.news_id) "
		. $cat_join
		. "WHERE " . $stop_list . "p.approve=1" . $where_date;

	// 3) Fetch posts in that order
	$sql_select = "SELECT p.id, p.autor, p.date, p.short_story, CHAR_LENGTH(p.full_story) as full_story, p.xfields, p.title, p.category, p.alt_name, p.comm_num, p.allow_comm, p.fixed, p.tags, e.news_read, e.allow_rate, e.rating, e.vote_num, e.votes, e.view_edit, e.editdate, e.editor, e.reason {$user_select}FROM "
		. PREFIX . "_post p LEFT JOIN " . PREFIX . "_post_extras e ON (p.id=e.news_id) {$user_join}"
		. "WHERE p.id IN ({$sql_select_ids}) ORDER BY FIND_IN_SET(p.id, '" . $sql_select_ids . "')";

	require (DLEPlugins::Check(ENGINE_DIR . '/modules/show.short.php'));

	if( $config['files_allow'] ) if( strpos( $tpl->result['content'], "[attachment=" ) !== false ) {
		$tpl->result['content'] = show_attach( $tpl->result['content'], $attachments );
	}

} else {
	$tpl->load_template('info.tpl');
	$tpl->set('{error}', 'No downloads found yet.');
	$tpl->set('{title}', 'Top downloads');
	$tpl->compile('content');
	$tpl->clear();
}
