<?php

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

if (!isset($db) || !is_object($db)) {
    return;
}

$charset = isset($config['charset']) && $config['charset'] ? strtoupper((string)$config['charset']) : 'UTF-8';
if ($charset === 'UTF8') {
    $charset = 'UTF-8';
}

$limit = isset($limit) ? (int)$limit : 10;
if ($limit < 1) {
    $limit = 10;
}
if ($limit > 50) {
    $limit = 50;
}

$exclude = isset($exclude) ? (string)$exclude : '';
$exclude = array_filter(array_map('trim', explode(',', $exclude)));
$excludeMap = $exclude ? array_fill_keys($exclude, true) : [];

$only = isset($only) ? (string)$only : '';
$only = array_filter(array_map('trim', explode(',', $only)));
$onlyMap = $only ? array_fill_keys($only, true) : [];

$showRules = isset($show_rules) ? (int)$show_rules : 1;

$rows = $db->super_query(
    "SELECT id, name, descr, password, grouplevel, sitemap FROM " . PREFIX . "_static ORDER BY sitemap DESC, id ASC",
    true
);

if (!is_array($rows) || !$rows) {
    return;
}

$count = 0;

foreach ($rows as $row) {
    if (!isset($row['name']) || $row['name'] === '') {
        continue;
    }

    $name = (string)$row['name'];

    if ($name === 'dle-rules-page') {
        if (!$showRules) {
            continue;
        }
    }

    if (isset($excludeMap[$name])) {
        continue;
    }

    if ($onlyMap && !isset($onlyMap[$name])) {
        continue;
    }

    if (!empty($row['password']) && $member_id['user_group'] != 1) {
        continue;
    }

    $grouplevel = isset($row['grouplevel']) ? (string)$row['grouplevel'] : 'all';
    if ($grouplevel !== 'all') {
        $groups = array_filter(array_map('intval', explode(',', $grouplevel)));
        if ($groups && !in_array((int)$member_id['user_group'], $groups, true)) {
            continue;
        }
    }

    $label = isset($row['descr']) ? trim(strip_tags((string)$row['descr'])) : '';
    if ($label === '') {
        $label = $name;
    }

    $label = htmlspecialchars($label, ENT_QUOTES, $charset);

    if ($name === 'dle-rules-page') {
        $href = $config['http_home_url'] . 'index.php?do=rules';
    } else {
        $href = $config['http_home_url'] . 'index.php?do=static&page=' . rawurlencode($name);
    }

    $href = htmlspecialchars($href, ENT_QUOTES, $charset);

    echo '<li><a href="' . $href . '">' . $label . '</a></li>';

    $count++;
    if ($count >= $limit) {
        break;
    }
}
