<?php

/*
 * @name        JMY CMS
 * @link        https://jmy.su/
 * @copyright   Copyright (C) 2012-2025 JMY LTD
 * @license     LICENSE.txt (see attached file)
 * @version     VERSION.txt (see attached file)
 * @author      Komarov Ivan
 * @edited      Orlov Alexsey
 */

if (!defined('ACCESS')) {
    header('Location: /');
    exit;
}
loadConfig('content');
loadLang('content');
global $db, $config, $content, $core, $url, $user, $headTag, $content_conf, $cache, $lang;
switch ($url[1] ?? null) {
    default:
        if (eregStrt('.htm', mjsEnd($url))) {
            view(mjsEnd($url));
        } else {
            main(isset($url[1]) && $url[1] != 'page' ? $url[1] : false);
        }
        break;

    case 'cat':
        $id = $url[2] ?? false;
        main($id);
        break;
    case 'date':
        main('date');
        break;

    case 'edit':
        if ($core->auth->isAdmin) {
            location(ADMIN . '/module/content/edit/' . $url[2]);
        } elseif ($core->auth->isModer) {
            $id = isset($url[2]) ? intval($url[2]) : 0;
            news_add($id);
        }
        break;
    case 'delete':
        if ($core->auth->isAdmin) location(ADMIN . '/module/content/delete/' . $url[2]);
        break;
//////////\\\Закладки пользователей\\\///////////////////
    case 'add_bookmarks':
        $id = isset($url[2]) ? intval($url[2]) : 0;
        bookmarksSubscribe($id, 'content', 1);
        header("refresh: 5; url='" . $_SERVER['HTTP_REFERER'] . "'");
        break;
    case 'del_bookmarks':
        $id = isset($url[2]) ? intval($url[2]) : 0;
        bookmarksSubscribe($id, 'content', 0);
        header("refresh: 5; url='" . $_SERVER['HTTP_REFERER'] . "'");
        break;
//////////\\\Закладки пользователей\\\///////////////////
}

function main($cat = null, $show = ''): void
{
    global $db, $core, $tags, $config, $user, $content_conf, $url, $headTag, $cache, $lang;
    $where = 'active = 1';
    $userInfo = '';
    $avatar = '';
    $miniImg = array();
    if (!$cat) {
        $set_title = $lang['static'];
        $where .= '';
        $pLink = '';
        $core->tpl->uniqTag = 'main';
    } elseif ($cat == 'tag') {
        $blockCL = true;
        $set_title = $lang['static'] . ',' . $lang['tag'] . ',' . $url[2];
        $core->tpl->title($lang['tag'] . ': ' . $url[2]);
        $where .= 'AND tags regexp \'[[:<:]](' . $db->safesql($url[2]) . ')[[:>:]]\'';
        $pLink = '/tags/' . $url[2];
        $core->tpl->uniqTag = 'cat';
    } elseif ($cat == 'date') {
        $blockCL = true;
        $date_new = $url[2];
        if (!empty($date_new)) {
            $date_arr = explode('-', $date_new);
            $set_title = $lang['static'] . ',' . $date_new;
            $core->tpl->title($lang['date'] . ': ' . $date_new);
            $where .= isset($date_arr[2]) ? 'AND `date` BETWEEN ' . mktime(0, 0, 0, $date_arr[1], $date_arr[2], $date_arr[0]) . ' AND ' . mktime(0, 0, 0, $date_arr[1], $date_arr[2] + 1, $date_arr[0]) : 'AND `date` BETWEEN ' . mktime(0, 0, 0, $date_arr[1], 1, $date_arr[0]) . ' AND ' . mktime(0, 0, 0, $date_arr[1] + 1, 1, $date_arr[0]);
            $pLink = '/date/' . $date_new;
            $core->tpl->uniqTag = 'main';
        } else {
            location('news');
        }
    } else {
        $cat = mjsEnd($url);
        $altname = filter($cat, 'a');
        $cat_query = $altname == 'cats' ? $core->select_data('categories', false, false, 'id as cid, name, fulltitle, description, keywords') : $core->select_data('categories', 'altname ="' . $db->safesql($altname) . '"', false, 'id as cid, name, fulltitle, description, keywords');
        if ($db->numRows($cat_query) == 0) location();
        $cat_info = $db->getRow($cat_query);
        $cat_cid = $cat_info['cid'] ?? false;
        $cat_fulltitle = $cat_info['fulltitle'] ?? '';
        $cat_name = $cat_info['name'] ?? '';
        $cat_keywords = $cat_info['keywords'] ?? '';
        $cat_description = $cat_info['description'] ?? '';
        $set_title = !empty($cat_fulltitle) ? $cat_fulltitle : $cat_name;
        if (!empty($cat_keywords)) $core->tpl->keywords = $cat_keywords;
        if (!empty($cat_description)) $core->tpl->description = $cat_description;
        $core->tpl->uniqTag = 'cat';
        $core->tpl->feed_link = 'cat/' . $cat_cid;
        $where .= "AND cat like '%," . $cat_cid . ",%'";
        $cat_ids = getcache('categories');
        $cat_pod = false;
        foreach ($cat_ids as $cid => $val) {
            foreach ($val as $pid => $name) {
                if ($pid == $cat_cid) $cat_pod .= ',' . $cid;
            }
        }
        $pLink = '/' . $core->getCat('content', $cat_cid, 'development');
    }
    $core->header_title($set_title);
    $where .= 'AND c.date <="' . time() . '"';
    if (!INDEX) {
        $core->getCat('content', $cat_cid ?? '', 'breadcrumb', 1);
//$core->getCatList(isset($cat_info['cid']) ? $cat_info['cid'] : '', 'content', 3);
    }
    $query = $core->select_data('content', $where, 'c.date DESC LIMIT ' . $core->site_limit_page($content_conf, $content_conf['num']), 'c.*, l.*', 'as c LEFT JOIN ' . DB_PREFIX . '_langs as l on(l.postId=c.id and l.module="content")');
    if ($db->numRows($query) > 0) {
        while ($content = $db->getRow($query)) {
            if (isset($content['author'])) $userInfo = $core->row_data('users', 'nick ="' . $content['author'] . '"');
            if (isset($userInfo['nick'])) $avatar = $content['author'] == $userInfo['nick'] && $userInfo['id'] != $content['id'] ? avatar($userInfo['id']) : $config['url'] . '/' . $user['noAvatar'];
            $cat = $content['cat'] !== ',0,' ? $core->getCat('content', $content['cat'], 'short', 3) : '';
            $link = $content['cat'] !== ',0,' ? 'content/' . $core->getCat('content', $content['cat'], 'development') . '/' : 'content/';
            $altname = $content['translate'];
            $content_link = $content['cat'] !== ',0,' ? 'content/' . $core->getCat('content', $content['cat'], 'development') . '/' : 'content/';
            $short = $core->bbDecode($content['short'], $content['id']);
            $core->tpl->loadFile('content/content-main');
            $core->tpl->setVar('ID', $content['id']);
            $core->tpl->setVar('TITLE', $content['title']);
            $core->tpl->setVar('TEXT', $core->bbDecode(str($content['short'], 500), $content['id']));
            $core->tpl->setVar('SHORT', '<div id="short-' . $content['id'] . '">' . $core->bbDecode(str($content['short'], 500), $content['id']) . '</div>');
            $core->tpl->setVar('FULL', '<div id="full-' . $content['id'] . '">' . $core->bbDecode($content['short'], $content['id']) . '</div>');
            $core->tpl->setVar('ICON', isset($catInfo['icon']) ? $core->getCatImg($pLink, $catInfo['icon'], $catInfo['title']) : '');
            $core->tpl->setVar('AUTHOR_AVATAR', $avatar);
            $core->tpl->setVar('AUTHOR', '<a href="profile/' . $content['author'] . '" title="' . $lang['page'] . ': ' . $content['author'] . '">' . $content['author'] . '</a>');
            $core->tpl->setVar('ALTNAME', $content['translate']);
            $core->tpl->setVar('KEYWORDS', $content['keywords']);
            $core->tpl->setVar('COMMENTS', formatCounter($content['comments']));
            $core->tpl->setVar('VIEWS', formatCounter($content['views']));
            $core->tpl->setVar('DATE', formatDate($content['date']));
            $core->tpl->setVar('BOOKMARKS', BookmarksInit($content['id'], 'content', $content['title']));
            $core->tpl->setVar('PREVIEW', $content['preview'] ? $content['preview'] : '');
            $core->tpl->setVar('CATEGORY', $cat);
            $core->tpl->sources = preg_replace_callback("#\\[bookmarks\\](.*?)\\[/bookmarks\\]#is", function ($matches) use ($content_conf) {
                if ($content_conf['bookmarks']) return $matches[1];
            }, $core->tpl->sources);
            $core->tpl->sources = preg_replace_callback("#\\{%SHORT:(.*?)%\\}#is",
                function ($match) use ($short) {
                    return short($match[1], processText($short));
                }, $core->tpl->sources);
            $core->tpl->sources = preg_replace_callback("#\\[mini_img\\](.*?)\\[/mini_img\\]#is", function ($matches) use ($miniImg) {
                if (!empty($miniImg[0])) return $matches[1];
            }, $core->tpl->sources);
            $core->tpl->sources = preg_replace_callback("#\\[category\\](.*?)\\[/category\\]#is", function ($matches) use ($cat) {
                if ($cat) return $matches[1];
            }, $core->tpl->sources);
            $core->tpl->sources = preg_replace_callback("#\\[preview\\](.*?)\\[/preview\\]#is", function ($matches) use ($content) {
                if ($content['preview']) return $matches[1];
            }, $core->tpl->sources);
            $core->tpl->sources = preg_replace_callback("#\\[more\\](.*?)\\[/more\\]#is",
                function ($match) use ($link, $altname) {
                    return format_link($match[1], $link . $altname . '.html');
                }, $core->tpl->sources);
            $core->tpl->end();
        }
        list($all) = $core->fetch_data('content', $where, 'count(c.id)', 'as c LEFT JOIN ' . DB_PREFIX . '_langs as l on(l.postId=c.id and l.module="content")');
        $core->tpl->pages(init_page(), $content_conf['num'], $all, 'content' . $pLink . '/{page}');
    } else {
        $core->tpl->info($lang['static_empty']);
    }
}

function view($tran = false)
{
    global $db, $core, $config, $files_conf, $cache, $content_conf, $url, $cache, $lang;
    $where = 'translate';
    $translate = $tran ? str_replace(array('.html', '.htm'), array('', ''), empty($tran) ? $url[2] : filter($tran, 'a')) : str_replace(array('.html', '.htm'), array('', ''), $url[2]);
    if (is_numeric(empty($tran) ? $url[2] : $tran)) $where = 'id';
    $query = $core->select_data('content', 'c.active=1 AND c.' . $where . '="' . $db->safesql($translate) . '" AND l.lang ="' . $core->InitLang() . '"', false, 'c.*, l.*', 'as c LEFT JOIN ' . DB_PREFIX . '_langs as l on(l.postId=c.id and l.module="content")');
    if ($db->numRows($query) == 0) location();
    $tagFormated = '';
    if ($db->numRows($query) > 0) {
        while ($content = $db->getRow($query)) {
            !empty($content['translate']) ? $core->tpl->altname = $content['translate'] : location('404.php');
            $core->tpl->uniqTag[] = 'view';
            $core->tpl->uniqTag[] = 'view-' . $content['id'];
            $core->tpl->uniqTag[] = $content['translate'];
            if (!empty($content['keywords'])) $core->tpl->keywords = $content['keywords'];
            if (!empty($content['description'])) $core->tpl->description = $content['description'];
            $ptitle = !empty($content['fulltitle']) ? $content['fulltitle'] : $content['title'];
            set_title(array($ptitle));
            $theme = !empty($content['theme']) ? $content['theme'] . '/' : '';
            if ($content['comments'] < 0) $core->upd_data('content', 'comments = 0', 'id ="' . $content['id'] . '"');
            $core->upd_data('content', 'views = views+1', 'id ="' . $content['id'] . '"');
            $cat = $content['cat'] !== ',0,' ? $core->getCat('content', $content['cat'], 'short', 3) : '';
            $cat_one = $content['cat'] !== ',0,' ? $core->getCat('content', $content['cat'], 'development', 1) : 'index';
            $url_link = isset($url[2]) ? $url[0] . '/' . $url[1] . '/' . $content['translate'] . '.html' : $url[0] . '/' . $content['translate'] . '.html';
            $actual_link = isset($url[1]) ? filter($_REQUEST['url']) : '';
            $link = $content['cat'] !== ',0,' ? 'content/' . $core->getCat('content', $content['cat'], 'development') : 'content/';
            $u_link = $url[0] . '/' . $content['translate'] . '.html' ? $url[0] . '/' . $content['translate'] . '.html' : $link . '/' . $content['translate'] . '.html';
            $filelist = glob("*.'" . $files_conf['attachFormats'] . "'");
            $flinks = $filelist ? str_replace(array($config['url'] . '/files/content/' . $content['id'] . '/' . $filelist), array($filelist), $content['short']) : $content['short'];
            $urls = !strpos($content['short'], $config['url']) ? '' : $config['url'];
            if (!strpos($content['short'], $lang['attach_download'])) {
                $atlang = $lang['attach_version_download'];
            } elseif (!strpos($content['short'], $lang['attach_version_download'])) {
                $atlang = $lang['attach_version_download'];
            } elseif (!strpos($content['short'], $lang['download'])) {
                $atlang = $lang['download'];
            } else {
                $atlang = '';
            }
            $urls = !strpos($content['short'], $config['url']) ? '' : $config['url'];
            if ($files_conf['download_file'] == 'enable_all') {
                $fulls = str_replace(array('', ''), array('', ''), $content['short']);
            } elseif ($files_conf['download_file'] == "enable_reg") {
                $fulls = str_replace(array($urls . '/files/content/' . $content['id'] . '/' . $flinks, $atlang), array('', '<a href="' . $config['url'] . '/profile/register" title="' . $lang['attach_derror'] . '">' . $atlang . '</a>'), $content['short']);
            } else {
                $fulls = str_replace(array($urls . '/files/content/' . $content['id'] . '/' . $flinks, $atlang), array('', ''), $content['short']);
            }
            $core->tpl->loadFile('content/' . $theme . 'content-view');
            $core->tpl->setVar('ID', $content['id']);
            $core->tpl->setVar('TITLE', $content['title']);
            $core->tpl->setVar('SHORT', '<div id="short-' . $content['id'] . '">' . $core->bbDecode(str($content['short'], 500), $content['id']) . '</div>');
            $core->tpl->setVar('FULL', '<div id="full-' . $content['id'] . '">' . $core->bbDecode($fulls, $content['id']) . '</div>');
            $core->tpl->setVar('ALTNAME', $content['translate']);
            $core->tpl->setVar('AUTHOR', '<a href="profile/' . $content['author'] . '" title="' . $lang['page'] . ': ' . $content['author'] . '">' . $content['author'] . '</a>');
            $core->tpl->setVar('KEYWORDS', $content['keywords']);
            $core->tpl->setVar('COMMENTS', formatCounter($content['comments']));
            $core->tpl->setVar('VIEWS', formatCounter($content['views']));
            $core->tpl->setVar('DATE', formatDate($content['date']));
            $core->tpl->setVar('BOOKMARKS', BookmarksInit($content['id'], 'content', $content['title']));
            $core->tpl->setVar('PREVIEW', $content['preview']);
            $core->tpl->setVar('CATEGORY', $cat);
            $core->tpl->setVar('EDIT', ($core->auth->isModer || $core->auth->isAdmin) ? '<a href="content/edit/' . $content['id'] . '">' . $lang['menu_full'] . '</a>' : '');
            $core->tpl->setVar('DEL_CONTENT', isset($core->auth->user_info['nick']) && ($content['author'] == $core->auth->user_info['nick'] || $core->auth->isModer || $core->auth->isAdmin) ? '<a href="content/delete/' . $content['id'] . '" onclick="return confirm(\'' . $lang['posts_sure_delete'] . '\');">' . $lang['delete'] . '</a>' : '');
            $array_replace = array(
                "#\\[editmenu\\](.*?)\\[/editmenu\\]#is" => ((isset($core->auth->user_info['nick']) && ($content['author'] == $core->auth->user_info['nick'] || $core->auth->isModer || $core->auth->isAdmin)) ? "\${1}" : ''),
                "#\\[edit\\](.*?)\\[/edit\\]#is" => ((isset($core->auth->user_info['nick']) && ($content['author'] == $core->auth->user_info['nick'] || $core->auth->isModer || $core->auth->isAdmin)) ? "\${1}" : ''),
                "#\\[del_content\\](.*?)\\[/del_content\\]#is" => ((isset($core->auth->user_info['nick']) && ($content['author'] == $core->auth->user_info['nick'] || $core->auth->isModer || $core->auth->isAdmin)) ? "\${1}" : ''),
                "#\\[img:([0-9]*?)\\]#is" => (!empty($miniImg[0]) ? '<img src="' . $miniImg[0] . '" border="0" width="\\1">' : ''),
            );
            $core->tpl->sources = preg_replace(array_keys($array_replace), array_values($array_replace), $core->tpl->sources);
            $core->tpl->sources = preg_replace_callback("#\\[bookmarks\\](.*?)\\[/bookmarks\\]#is", function ($matches) use ($content_conf) {
                if ($content_conf['bookmarks']) return $matches[1];
            }, $core->tpl->sources);
            $core->tpl->sources = preg_replace_callback("#\\[category\\](.*?)\\[/category\\]#is", function ($matches) use ($cat) {
                if ($cat) return $matches[1];
            }, $core->tpl->sources);
            $core->tpl->sources = preg_replace_callback("#\\[preview\\](.*?)\\[/preview\\]#is", function ($matches) use ($content) {
                if ($content['preview']) return $matches[1];
            }, $core->tpl->sources);
            $related_cache = $cache->do_get('related_' . $content['id']);
            if (empty($related_cache) && $content_conf['related_content'] > 0) {
                $body_text = $content['title'] . strip_tags(stripslashes("" . (!empty($content['full']) ? $content['full'] : $content['short'])));
                if (!empty($body_text)) {
                    $where = 'WHERE MATCH (`title`, `short`, `full`) AGAINST ("+(' . $db->safesql($body_text) . ')" IN BOOLEAN MODE) AND c.id !="' . $content['id'] . '" AND c.active = 1';
                    $order = 'c.date DESC';
                    $rel_query = $core->select_data('content', $where, $order . ' LIMIT ' . $content_conf['related_content'], 'c.*, l.*', 'AS c LEFT JOIN ' . DB_PREFIX . '_langs as l on(l.postId=c.id and l.module="content")');
                    $related_cache = '';
                    if ($db->numRows($rel_query) > 0) {
                        while ($related = $db->getRow($rel_query)) {
                            $related_cache .= related_images('content', $content_conf, $related);
                        }
                    }
                    $cache->do_put('related_' . $content['id'], $related_cache, 3600);
                }
            }
            $core->tpl->setVar('RELATED', $related_cache);
            $array_replace["#\\[related\\](.*?)\\[/related\\]#is"] = (!empty($related_cache) ? '\\1' : '');
            $core->tpl->sources = preg_replace(array_keys($array_replace), array_values($array_replace), $core->tpl->sources);
            $core->tpl->end();
            ComplaintInit($content['id']);
            if ($content_conf['allowComm'] == 1) show_comments('content', $content['id'], $content_conf['comments_num']);
            errorLocation($cat_one, $url_link, $actual_link);
        }
    } else {
        error_news();
    }
}