<?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: top100.php
-----------------------------------------------------
 Use: Top 100 tracks (all / year / month / week)
=====================================================
*/

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;

$period = isset($_GET['period']) ? (string)$_GET['period'] : 'all';
$period = strtolower(trim($period));
$period = preg_replace('/[^a-z]/', '', $period);

if( !in_array($period, array('all', 'year', 'month', 'week')) ) {
	$period = 'all';
}

$_TIME = isset($_TIME) ? $_TIME : time();

$where_period = '';
if( $period !== 'all' ) {
	$seconds = 0;
	switch ($period) {
		case 'week':
			$seconds = 7 * 86400;
			break;
		case 'month':
			$seconds = 30 * 86400;
			break;
		case 'year':
			$seconds = 365 * 86400;
			break;
	}
	$date_from = date('Y-m-d H:i:s', $_TIME - $seconds);
	$where_period = " AND p.date >= '{$date_from}'";
}

$navigation_first_page = $config['http_home_url'] . "index.php?do=top100";
if( $period !== 'all' ) {
	$navigation_first_page .= "&period=" . rawurlencode($period);
}

// Pagination URLs used by show.short.php
$url_page = $navigation_first_page . "&cstart={cstart}";
$canonical = $navigation_first_page;

// Per-page meta tags (avoid global defaults)
$period_labels = array(
	'all' => 'Tot timpul',
	'week' => 'Săptămână',
	'month' => 'Lună',
	'year' => 'An'
);

$page_title = 'Top 100';
if( $period !== 'all' AND isset($period_labels[$period]) ) {
	$page_title .= ' - ' . $period_labels[$period];
}

$metatags['title'] = $page_title . ' &raquo; ' . $metatags['title'];
$metatags['description'] = 'Top 100 most viewed posts (wallpapers, ringtones, video wallpapers), sorted by views. Filter by week, month, year, or all time.';
$metatags['keywords'] = 'top 100, most viewed, wallpapers, ringtones, video wallpapers, trending';

// Active period button styling (template: templates/zmusic/main.tpl)
if( isset($tpl) ) {
	$tpl->set('{top100_btn_all}', $period === 'all' ? 'btn-border' : 'btn-nobg');
	$tpl->set('{top100_btn_week}', $period === 'week' ? 'btn-border' : 'btn-nobg');
	$tpl->set('{top100_btn_month}', $period === 'month' ? 'btn-border' : 'btn-nobg');
	$tpl->set('{top100_btn_year}', $period === 'year' ? 'btn-border' : 'btn-nobg');
}

// 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' ) {
	$allow_list = array_map('intval', $allow_list);
	$allow_list = array_filter($allow_list);
	$allow_list = array_values($allow_list);

	if( $config['allow_multi_category'] ) {
		if( count($allow_list) ) {
			$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 {
			$allow_active_news = false;
		}
	} else {
		if( count($allow_list) ) {
			$stop_list = "category IN ('" . implode("','", $allow_list) . "') AND ";
		} else {
			$allow_active_news = false;
		}
	}
}

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

if( $not_allow_cats[0] != '' ) {
	$not_allow_cats = array_map('intval', $not_allow_cats);
	$not_allow_cats = array_filter($not_allow_cats);
	$not_allow_cats = array_values($not_allow_cats);

	if( $config['allow_multi_category'] ) {
		if( count($not_allow_cats) ) {
			$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 {
		if( count($not_allow_cats) ) {
			$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 = '';
}


$limit = 100;
$per_page = isset($config['news_number']) ? (int)$config['news_number'] : 0;
if( $per_page < 1 ) $per_page = 10;
if( $per_page > $limit ) $per_page = $limit;

// Convert DLE page number (?cstart=2,3,...) into SQL offset
if( isset($cstart) && $cstart ) {
	$cstart = (int)$cstart;
	if( $cstart < 1 ) $cstart = 1;
	if( $cstart > 9999999 ) $cstart = 9999999;
	$cstart = ($cstart - 1) * $per_page;
} else {
	$cstart = 0;
}

$offset = (int)$cstart;
if( $offset < 0 ) $offset = 0;

// Keep the list strictly within Top 100
if( $offset >= $limit ) {
	$allow_active_news = false;
}

$page_limit = $per_page;
if( $offset + $page_limit > $limit ) {
	$page_limit = $limit - $offset;
}

// Required by show.short.php for pagination/count logic.
// It will append $where_date itself.
// Cap the count to 100 so navigation does not exceed Top 100.
$sql_count = "SELECT LEAST(COUNT(*), {$limit}) as count FROM " . PREFIX . "_post p "
	. $cat_join
	. "WHERE " . $stop_list . "p.approve=1" . $where_period;

// 1) Ordered IDs by views (news_read) for the current page
$sql_select_ids = "SELECT p.id, COALESCE(e.news_read, 0) AS views FROM " . PREFIX . "_post p "
	. "LEFT JOIN " . PREFIX . "_post_extras e ON (p.id=e.news_id) "
	. $cat_join
	. "WHERE " . $stop_list . "p.approve=1" . $where_date . $where_period
	. " ORDER BY views DESC, p.date DESC LIMIT {$offset},{$page_limit}";

$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);

	$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 posts found yet.');
	$tpl->set('{title}', 'Top 100');
	$tpl->compile('content');
	$tpl->clear();
}
