<?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;
}
global $db, $config, $core, $tags, $news_conf, $email_conf, $url, $headTag, $cache, $lang;
ConfigMod('news');
loadLang('news');
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 'addPost':
        news_add();
        break;
    case 'savePost':
        if ($core->auth->isUser && $core->auth->group_info['addPost'] == 1) {
            $title = isset($_POST['title']) ? filter($_POST['title']) : '';
            $langTitle = isset($_POST['langtitle']) ? filter($_POST['langtitle']) : array();
            $langTitle[$config['lang']] = $title;
            $source = isset($_POST['source']) ? filter($_POST['source']) : '';
            $short = isset($_POST['short']) ? filter($_POST['short']) : '';
            $full = isset($_POST['full']) ? filter($_POST['full']) : '';
            $status = isset($_POST['status']) ? intval($_POST['status']) : '';
            $xfield = isset($_POST['xfield']) ? filter($_POST['xfield']) : '';
            $xfieldT = isset($_POST['xfieldT']) ? filter($_POST['xfieldT']) : '';
            $translit = translit($title);
            $fileds = '';
            $qTr = $core->select_data('news', 'altname ="' . $db->safesql($translit) . '"');
            if ($db->numRows($qTr) > 0) $translit = $translit . gencode(3);
            $category = isset($_POST['category']) ? array_unique($_POST['category']) : '0';
            $edit_id = isset($_POST['edit_id']) ? intval($_POST['edit_id']) : '';
            if (is_array($category)) {
                if (array_search(0, $category)) unset($category[array_serach(0, $category)]);
                $firstCat = $category[0];
                unset($category[0]);
                $deleteCat = array_search($firstCat, $category);
                unset($category[$deleteCat]);
                $category[0] = $firstCat;
                ksort($category);
                $cats = '';
                foreach ($category as $cid) {
                    $cats .= intval($cid) . ",";
                }
            } else {
                $cats = $category . ',';
            }
            $cats = ',' . $cats;
            $fieldsSer = '';
            if (!empty($xfield)) {
                foreach ($xfield as $xId => $xContent) {
                    if (!empty($xContent) && $xId > 0 && !empty($xfieldT[$xId])) {
                        $xContent = processText(filter($xContent, 'html'));
                        $xId = intval($xId);
                        $xfieldT[$xId] = processText(filter($xfieldT[$xId], 'title'));
                        $fileds[$xId] = array($xfieldT[$xId], $xContent);
                    }
                }
                $fieldsSer = serialize($fileds);
            }
            set_title(array($lang['news']));
            if (!empty($edit_id) && ($core->auth->isModer || $core->auth->isAdmin)) {
                $update = $core->upd_data('news', 'author ="' . $core->auth->user_info['nick'] . '", cat ="' . $cats . '", source ="' . $source . '", altname ="' . $translit . '", fields ="' . $fieldsSer . '", active ="' . $status . '" ', 'id ="' . $edit_id . '"');
                $news = $core->row_data('news', 'id ="' . $edit_id . '"');
                $short = fileInit('news', $news['id'], 'content', parseBB(processText(filter($_POST['short'], 'html')), $news['id']), 'user_temp' . $core->auth->user_id);
                $full = fileInit('news', $news['id'], 'content', parseBB(processText(filter($_POST['full'], 'html')), $news['id']), 'user_temp' . $core->auth->user_id);
                $core->upd_data('langs', 'title ="' . $db->safesql(processText($title)) . '", short ="' . $db->safesql($short) . '", full ="' . $db->safesql($full) . '"', 'postId ="' . $edit_id . '" AND module ="news" AND lang ="' . $config['lang'] . '"');
                fileInit('news', $news['id'], 'dir', '', 'user_temp' . $core->auth->user_id);
                $core->tpl->info($lang['news_updates'] . (($core->auth->user_info['group'] == $news_conf['noModer']) ? '' : $lang['news_success_moder']));
                $access = $core->row_data('users', 'nick ="' . $db->safesql($news['author']) . '"');
                delcache('userInfo_' . $access['id']);
                header("refresh: 5; url=" . $config['url'] . "");
            } elseif (!empty($title) && !empty($short) && empty($edit_id)) {
                $insert = $core->ins_data('news', 'id,author,date,tags,cat,altname,source,preview,keywords,description,allow_comments,allow_rating,allow_index,score,votes,views,comments,fields,groups,fixed,active,users_delete,users_del_data,fulltitle', 'NULL,"' . $core->auth->user_info['nick'] . '","' . time() . '","","' . $cats . '","' . $db->safesql($translit) . '","' . $source . '","","","",0,0,0,0,0,0,0,"' . $fieldsSer . '","",0,"' . (($core->auth->user_info['group'] == $news_conf['noModer']) ? 1 : 2) . '","",0,""');
                $news = $core->row_data('news', 'altname ="' . $db->safesql($translit) . '"');
                $short = fileInit('news', $news['id'], 'content', parseBB(processText(filter($_POST['short'], 'html')), $news['id']), 'user_temp' . $core->auth->user_id);
                $full = fileInit('news', $news['id'], 'content', parseBB(processText(filter($_POST['full'], 'html')), $news['id']), 'user_temp' . $core->auth->user_id);
                fileInit('news', $news['id'], 'dir', '', 'user_temp' . $core->auth->user_id);
                $core->ins_data('langs', '_id,postId,module,title,fulltitle,short,full,lang', 'NULL,"' . $news['id'] . '","news","' . $db->safesql(processText($title)) . '","","' . $db->safesql($short) . '","' . $db->safesql($full) . '","' . $config['lang'] . '"');
                $core->tpl->info($lang['news_success'] . (($core->auth->user_info['group'] == $news_conf['noModer']) ? '' : $lang['news_success_moder']));
                $access = $core->row_data('users', 'nick ="' . $db->safesql($news['author']) . '"');
                delcache('userInfo_' . $access['id']);
                header("refresh: 5; url=" . $config['url'] . "");
                require_once ROOT . '/etc/email.config.php';
                if ($email_conf['new_news'] == 1) {
                    $query = $core->select_data('email', false, 'id ASC');
                    $category = $core->row_data('categories', false, false, 'name');
                    $email = ($config['support_mail']);
                    while ($result = $db->getRow($query)) {
                        if (!empty($email)) {
                            $message = $result['new_news_text'] > 0 ? str_replace(array('&lt;', '&gt;', '{%username%}', '{%date%}', '{%title%}', '{%category%}', '{%url%}'), array('<', '>', $news['author'], formatDate(time(), true), $title, $category['name'], $config['url']), $result['new_news_text']) : str_replace(array('\p', '\n', '\r', '<br>', '<br/>', '&nbsp;', '{%username%}', '{%date%}', '{%title%}', '{%category%}', '{%url%}'), array('""', '""', '""', '\n', '\n', '\n', $news['author'], formatDate(time(), true), $title, $category['name'], $config['url']), $result['new_news_text']);
                            mailSMTP($email, $result['new_news_text'], $lang['mail_news'], $message);
                        } else {
                            $core->tpl->info($lang['sendfalse'] . '   <strong><a href="javascript:history.go(-1)"><b>' . $lang['go_back'] . '</b></a></strong>');
                        }
                    }
                }
            } else {
                $core->tpl->info($lang['error_form']);
            }
        }
        break;
    case 'cat':
        $id = $url[2] ?? false;
        main($id);
        break;
    case 'date':
        main('date');
        break;
    case 'user_news':
        main(false, 'user_news');
        break;
    case 'best_news':
        main(false, 'best_news');
        break;
    case 'view':
        view();
        break;
    case 'edit':
        if ($core->auth->isAdmin) {
            location(ADMIN . '/module/news/edit/' . $url[2]);
        } elseif ($core->auth->isModer) {
            $id = isset($url[2]) ? intval($url[2]) : 0;
            news_add($id);
        }
        break;
    case 'editshort':
        $id = isset($url[2]) ? intval($url[2]) : 0;
        news_add($id);
        break;
    case 'delete':
        if ($core->auth->isAdmin) location(ADMIN . '/module/news/delete/' . $url[2]);
        break;
//Удаление новостей пользователем (без удаления из базы)//
    case 'del_news':
        $id = isset($url[2]) ? intval($url[2]) : 0;
        $users_delete = $lang['posts_autor_deleted'] . $core->auth->user_info['nick'];
        if (!empty($id)) {
            $rows = $core->row_data('news', 'id ="' . $id . '"');
            $active = $rows['active'] == 1 ? 3 : 0;
            $core->upd_data('news', 'active ="' . $active . '",users_delete ="' . $db->safesql(processText($users_delete)) . '",users_del_data ="' . time() . '"', 'id ="' . $id . '"');
            header('Location: /');
        } else {
            $core->tpl->info($lang['posts_active_error']);
        }
        break;
//////////\\\Закладки пользователей\\\///////////////////
    case 'bookmarks':
        global $db, $core, $url, $news_conf, $lang;
        set_title(array($lang['user_bookmarks']));
        $where = 'uid ="' . $core->auth->user_id . '"';
        $query = $core->select_data('bookmarks', $where, 'id DESC LIMIT ' . $core->site_limit_page($news_conf, $news_conf['numbookmarks']));
        if ($news_conf['bookmarks'] == 1) {
            if ($db->numRows($query) > 0) {
                while ($rows = $db->getRow($query)) {
                    if ($rows['uid'] == $core->auth->user_id && $news_conf['bookmarks'] == 1) {
                        if (mb_strlen($rows['title'], 'utf-8') > 80)
                            $rows['title'] = mb_substr($rows['title'], 0, 80, 'utf-8') . '..';
                        $title = $rows['title'];
                        $id = $rows['id'];
                        $nid = $rows['nid'];
                        $url = $rows['url'];
                        $date = formatDate($rows['date'], true);
                        $folder = strripos($url, 'news/') === false ? 'content' : 'news';
                        $delete = '<a href="' . $folder . '/del_bookmarks/' . $rows['id'] . '">' . $lang['delete'] . '</a>';
                        $news = $core->row_data('news', 'id="' . $nid . '"', false, false, 'as n LEFT JOIN ' . DB_PREFIX . '_langs as c on(c.postId=n.id and c.module="news")');
                        $cid = str_replace(array('/' . $core->auth->user_id), array(''), $rows['nid']);
                        $content = $core->row_data('content', 'id="' . $cid . '"', false, false, 'as c LEFT JOIN ' . DB_PREFIX . '_langs as l on(l.postId=c.id and l.module="content")');
                        $mod_id = strripos($url, 'news/') === false ? $content['id'] : $news['id'];
                        $patch = !$news_conf['related_news_img_thumbs'] ? 'files/' . $folder . '/' . $mod_id . '/' : 'files/thumbs/files/' . $folder . '/' . $mod_id . '/';
                        $dir = news_image($patch);
                        $dbz = strripos($url, 'news/') === false ? $content : $news;
                        $altname = ($folder == 'news') ? 'altname' : 'translate';
                        $rel_link = $dbz['cat'] !== ',0,' ? $folder . '/' . $core->getCat($folder, $dbz['cat'], 'development') . '/' . $dbz[$altname] . '.html' : $folder . '/';
                        $images = array();
                        $all_files = !empty($dir) ? scandir($dir) : null;
                        for ($i = 0; $i < count($all_files); $i++) {
                            if (!str_contains($all_files[$i], ".png") and !str_contains($all_files[$i], ".jpg") and
                                !str_contains($all_files[$i], ".gif")
                            ) continue;
                            $images[] = $all_files[$i];
                        }
                        $img_random = (!empty($images) ? $images[rand(0, sizeof($images) - 1)] : '');
                        $img_src = $dir . $img_random;
                        $img_src = (!empty($dir) && filesize($img_src) > 0) ? $img_src : '/media/cats/no_image.png';
                        $count = (is_array($img_src)) ? count($img_src) : 0;
                        if ($count) {
                            $width = '';
                            $height = '';
                            $type = '';
                            $attr = '';
                        } else {
                            list($width, $height, $type, $attr) = getimagesize(ROOT . $img_src);
                        }
                        if ($news_conf['bookmarks_news_img_height'] && $news_conf['bookmarks_news_img_widtht']) {
                            $style = 'style="width:' . $news_conf['bookmarks_news_img_widtht'] . 'px; height:' . $news_conf['bookmarks_news_img_height'] . 'px;"';
                        } elseif ($news_conf['bookmarks_news_img_height'] == 0 && $news_conf['bookmarks_news_img_widtht']) {
                            $style = 'style="width:' . $news_conf['bookmarks_news_img_widtht'] . 'px; height:' . $height . 'px;"';
                        } elseif ($news_conf['bookmarks_news_img_height'] && $news_conf['bookmarks_news_img_widtht'] == 0) {
                            $style = 'style="width:' . $width . 'px; height:' . $news_conf['bookmarks_news_img_height'] . 'px;"';
                        } else {
                            $style = 'style="width:' . $width . 'px; height:' . $height . 'px;"';
                        }
                        if (!$dir) @mkdir(ROOT . $patch, 0777);
                        set_title(array($lang['bookmarks']));
                        $core->tpl->loadFile('bookmarks');
                        $core->tpl->setVar('TITLE', $title);
                        $core->tpl->setVar('IMG', '<div class="post-media"><a href="' . $rel_link . '"><img src="' . $img_src . '"  ' . $style . ' alt=""></a></div>');
                        $core->tpl->setVar('ID', $id);
                        $core->tpl->setVar('URL_IMG', $img_src);
                        $core->tpl->setVar('NID', $nid);
                        $core->tpl->setVar('URL', $rel_link);
                        $core->tpl->setVar('DATE', $date);
                        $core->tpl->setVar('DELETE', $delete);
                        $core->tpl->end();
                    }
                }
            } else {
                $core->tpl->info($lang['no_bookmarks']);
                header("refresh: 15; url=/news/");
            }
        } else {
            $core->tpl->info($lang['off_bookmarks']);
        }
        break;
    //////////\\\Закладки пользователей\\\///////////////////
    case 'add_bookmarks':
        $id = isset($url[2]) ? intval($url[2]) : 0;
        bookmarksSubscribe($id, 'news', 1);
        header("refresh: 5; url='" . $_SERVER['HTTP_REFERER'] . "'");
        break;
    case 'del_bookmarks':
        $id = isset($url[2]) ? intval($url[2]) : 0;
        bookmarksSubscribe($id, 'news', 0);
        header("refresh: 5; url='" . $_SERVER['HTTP_REFERER'] . "'");
        break;
//////////\\\Закладки пользователей\\\///////////////////
    case 'user_comments':
        global $core, $user, $lang;
        set_title(array($lang['user_comments']));
        $query = $core->select_data('comments', 'uid ="' . $core->auth->user_info['id'] . '"');
        if ($db->numRows($query) > 0) {
            while ($comment = $db->getRow($query)) {
                if (!$comment['editdate']) {
                    $olddate = formatDate($comment['date'], true);
                    $date = formatDate($comment['date'], true);
                    $tdate = '';
                } else {
                    $date = formatDate($comment['date'], true);
                    $ndate = formatDate($comment['editdate'], true);
                    $tdate = "";
                    if (!empty($user['commentEditText'])) {
                        $arrayReplace = array('{user}' => $core->auth->user_info['nick'], '{date}' => $ndate);
                        $edate = "\n\n" . str_replace(array_keys($arrayReplace), array_values($arrayReplace), $user['commentEditText']) . "";
                        $tdate = "<span title=\"" . $edate . "\">" . $lang['v_edit'] . "</span>";
                    }
                }
                $active = $core->auth->isModer || $core->auth->isAdmin ? 'AND `active` >=0' : 'AND `active` = 1';
                $news = $core->row_data('news', 'id ="' . $comment['post_id'] . $active . '"', false, 'n.*, c.*', ' as n LEFT JOIN ' . DB_PREFIX . '_langs as c on(c.postId=n.id and c.module="news")');
                $status = $news['id'] && $news['active'] == 2 ? $lang['comment_moderate'] : ($news['id'] ? $lang['comment_active'] : $lang['comment_deleted']);
                $url_link = $news['id'] && $news['active'] == 2 ? 'news/edit/' . $news['id'] : ($news['id'] ? ($comment['module'] == 'profile' ? 'view/' . $comment['post_id'] : _nLink($comment['module'], $comment['post_id'])) : '');
                $core->tpl->loadFile('comments/comments.user');
                $core->tpl->setVar('TITLE', _nTitle($comment['module'], $comment['post_id']));
                $core->tpl->setVar('NICK', ($comment['uid'] != 0) ? $core->auth->user_info['nick'] : '');
                $core->tpl->setVar('AVATAR', ($comment['uid'] != 0) ? avatar($comment['uid']) : '');
                $core->tpl->setVar('BODY', '<div id="comment_' . $comment['id'] . '">' . $core->bbDecode(stripslashes($comment['text'])) . '</div>');
                $core->tpl->setVar('COM_STATUS', $status);
                $core->tpl->setVar('URL_COMMENTS', $url_link);
                $core->tpl->setVar('DATE', $date . $tdate);
                $core->tpl->end();
            }
        } else {
            $core->tpl->loadFile('comments/comments.user');
            $core->tpl->setVar('NICK', '');
            $core->tpl->setVar('AVATAR', '');
            $core->tpl->setVar('BODY', $core->tpl->info($lang['no_lastcomments']));
            $core->tpl->setVar('URL_COMMENTS', '');
            $core->tpl->setVar('DATE', '');
            $core->tpl->end();
        }
        break;
    case 'tags':
        if (isset($url[2])) {
            main('tag');
        } else {
            $core->header_title($lang['news'], $lang['tags']);
            $tag_query = $core->select_data('tags', false, false, 'tag');
            while ($tag = $db->getRow($tag_query)) {
                $tags[] = $tag['tag'];
            }
            $tag_cloud = new TagsCloud;
            $tags_list = $tag_cloud->get_cloud($tags);
            $tagscloud = '';
            $core->tpl->title($lang['total_tags'] . ': ' . count($tags_list));
            $core->tpl->open();
            $core->tpl->loadFile('tagscloud');
            if ($db->numRows($tag_query) > 0) {
                foreach ($tags_list as $tag) {
                    $tagscloud .= $tag;
                }
            } else {
                $tagscloud = $lang['tags_absents'];
            }
            $core->tpl->setVar('TAGSCLOUD', $tagscloud);
            $core->tpl->end();
            $core->tpl->close();
        }
        break;
}
function main($cat = null, $show = '')
{
    global $db, $core, $tags, $news_conf, $url, $headTag, $lang;
    $where = 'active = 1';
    $order = 'fixed DESC';
    $link = '';
    if ($show == 'user_news') {
        $set_title = $lang['user_news'];
        $where .= 'AND author ="' . $core->auth->user_info['nick'] . '"';
        $order .= ', date DESC';
        $show_link = ($url[1] == 'user_news') ? '/user_news' : '';
    } elseif ($show == 'best_news') {
        $set_title = $lang['best_news'];
        $where .= '';
        $order .= ', views DESC';
        $show_link = ($url[1] == 'best_news') ? '/best_news' : '';
    } else {
        $set_title = $lang['news'];
        $where .= '';
        $order .= ', date DESC';
        $show_link = '';
    }
    if (!$cat) {
        $set_title = $set_title;
        $where .= 'AND n.allow_index !=0';
        $link = '';
        $core->tpl->uniqTag = 'main';
    } elseif ($cat == 'tag') {
        $blockCL = true;
        $set_title = $lang['news'] . ',' . $lang['tag'] . ',' . $url[2];
        $core->tpl->title($lang['tag'] . ': ' . $url[2]);
        $where .= 'AND tags regexp \'[[:<:]](' . $db->safesql($url[2]) . ')[[:>:]]\'';
        $link = '/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['news'] . ',' . $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]);
            $link = '/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;
            }
        }
        $link = '/' . $core->getCat('news', $cat_cid, 'development');
    }
    $exceNews = array('user_news', 'best_news');
    $link = (isset($url[1]) && $url[1] == $exceNews) ? $show_link : $link;
    $core->header_title($set_title);
    $where .= 'AND n.date <="' . time() . '"';
    $query = $core->select_data('news', $where, $order . " LIMIT " . $core->site_limit_page($news_conf, $news_conf['num']), 'n.*, c.*', 'as n LEFT JOIN ' . DB_PREFIX . '_langs as c on(c.postId=n.id and c.module="news")');
    if ($db->numRows($query) > 0) {
        while ($news = $db->getRow($query)) {
            $tag_list = explode(', ', $news['tags']);
            $tag_count = 0;
            $tags = false;
            foreach ($tag_list as $tag) {
                $tag_count++;
                if ($tag_count < ($news_conf['tags_num'] + 1)) $tags .= '<a href="news/tags/' . $tag . '" title="' . $tag . '">' . ($headTag == $tag ? '<strong>' . $tag . '</strong>' : $tag) . '</a>, ';
            }
            if ($news['comments'] < 0) $core->upd_data('news', 'comments = 0', 'id ="' . $news['id'] . '"');
            $catInfo = $news['cat'] !== ',0,' ? $core->catInfo('news', $news['cat']) : '';
            $cat = $news['cat'] !== ',0,' ? $core->getCat('news', $news['cat'], 'short', 3) : '';
            $news_link = $news['cat'] !== ',0,' ? 'news/' . $core->getCat('news', $news['cat'], 'development') . '/' : 'news/';
            $cat_one = $news['cat'] !== ',0,' ? $core->getCat('news', $news['cat'], 'altname', 1) : 'index';
            $short = $core->bbDecode($news['short'], $news['id']);
            $core->tpl->loadFile('news/news-' . (is_array($core->tpl->uniqTag) ? $core->tpl->uniqTag[0] : (empty($core->tpl->uniqTag) ? 'main' : $core->tpl->uniqTag)));
            include(loadTag('news'));
            $core->tpl->end();
            unset($tags);
        }
        list($all) = $core->fetch_data('news', $where, 'count(n.id)', 'as n LEFT JOIN ' . DB_PREFIX . '_langs as c on(c.postId=n.id and c.module="news")');
        $core->tpl->pages(init_page(), $news_conf['num'], $all, 'news' . $link . '/{page}');
    } else {
        error_news();
    }
}

function view($tran = false)
{
    global $db, $core, $tags, $news_conf, $url, $cache, $lang;
    $where = 'altname';
    $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('news', 'n.active=1 AND n.' . $where . '="' . $db->safesql($translate) . '" AND l.lang ="' . $core->InitLang() . '"', false, 'n.*, l.*, c.id as cid, c.name, c.altname as alturl, c.icon as catIcon', 'AS n LEFT JOIN ' . DB_PREFIX . '_categories AS c ON (n.cat=c.id) LEFT JOIN ' . DB_PREFIX . '_langs as l on(l.postId=n.id and l.module="news")');
    if ($db->numRows($query) == 0) location();
    $tagFormated = '';
    if ($db->numRows($query) > 0) {
        while ($news = $db->getRow($query)) {
            $textFull = $news['full'];
            $pageContent = init_page('break');
            $pageBreaks = explode('[pagebreak]', $textFull);
            if (!isset($pageBreaks[$pageContent - 1])) $pageContent = 1;
            $pagesBr = count($pageBreaks);
            $breakNav = '';
            $textFull = $pageBreaks[$pageContent - 1];
            $textShort = $news['short'];
            if ($news['comments'] < 0) $core->upd_data('news', 'comments = 0', 'id ="' . $news['id'] . '"');
            $core->upd_data('news', 'views = views+1', $where . '="' . $db->safesql($translate) . '"');
            $tag_list = explode(',', $news['tags']);
            $tag_count = 0;
            $tags = false;
            $core->tpl->altname = !empty($news['altname']) ? $news['altname'] : location('404.php');
            if (!empty($news['keywords'])) $core->tpl->keywords = $news['keywords'];
            if (!empty($news['description'])) $core->tpl->description = $news['description'];
            foreach ($tag_list as $tag) {
                $tag_count++;
                $tag = trim($tag);
                if ($tag_count < ($news_conf['tags_num'] + 1)) $tags .= '<a href="news/tags/' . urlencode($tag) . '" title="' . $tag . '">' . $tag . '</a>, ';
            }
            if ($news_conf['tagIll']) {
                $tagFormat = '';
                foreach ($tag_list as $ttag) {
                    $ttag = trim($ttag);
                    $tagFormat .= "'" . $ttag . "' => '" . str_replace('{tag}', $ttag, $news_conf['illFormat']) . "',";
                }
                eval('$tagFormated = array(' . $tagFormat . ');');
                $textFull = str_ireplace(array_keys($tagFormated), array_values($tagFormated), $textFull);
                $textShort = str_ireplace(array_keys($tagFormated), array_values($tagFormated), $textShort);
            }
            $cat_id = str_replace(',', '', $news['cat']);
            $cat_for = $core->row_data('categories', 'id ="' . $cat_id . '"');
            $core->tpl->uniqTag = 'view';
            $ptitle = !empty($news['fulltitle']) ? $news['fulltitle'] : $news['title'];
            set_title(array($news['name'], $ptitle));
            $catInfo = $news['cat'] !== ',0,' ? $core->catInfo('news', $news['cat']) : '';
            $cat = $news['cat'] !== ',0,' ? $core->getCat('news', $news['cat'], 'short', 3) : '';
            $news_link = $news['cat'] !== ',0,' ? 'news/' . $core->getCat('news', $news['cat'], 'development') . '/' : 'news/';
            $cat_one = $news['cat'] !== ',0,' ? $core->getCat('news', $news['cat'], 'altname', 1) : 'index';
            $url_link = isset($url[2]) ? $url[0] . '/' . $url[1] . '/' . $news['altname'] . '.html' : $url[0] . '/' . $news['altname'] . '.html';
            $actual_link = isset($url[1]) ? filter($_REQUEST['url']) : '';
            $error_link = strripos($actual_link, $news['altname'] . '.html');
            if (!empty($catInfo)) $actual_link <> $url_link && ($news_link . $news['altname'] . '.html') <> $url_link || $actual_link <> $url_link && ($news_link . $news['altname'] . '.html') <> $actual_link ? location('404.php') : ($error_link == false ? location('404.php') : '');
            $short = $core->bbDecode($textShort, $news['id']);
            $miniImg = _getCustomImg($short);
            if ($pagesBr > 1 && $pageBreaks[1] !== '') {
                if (isset($pageBreaks[$pageContent - 2])) $breakNav .= "<a href=\"" . $news_link . 'break/' . ($pageContent - 1) . '/' . $news['altname'] . ".html\" title=\"" . $lang['back'] . "\">" . $lang['previous_page'] . "</a>";
                if (isset($pageBreaks[$pageContent - 2]) && isset($pageBreaks[$pageContent])) $breakNav .= ' | ';
                if (isset($pageBreaks[$pageContent])) $breakNav .= "<a href=\"" . $news_link . 'break/' . ($pageContent + 1) . '/' . $news['altname'] . ".html\" title=\"" . $lang['next_page'] . "\">" . $lang['next_page'] . "</a>";
            }
            $core->tpl->loadFile('news/news-' . (is_array($core->tpl->uniqTag) ? $core->tpl->uniqTag[0] : (empty($core->tpl->uniqTag) ? 'main' : $core->tpl->uniqTag)));
            include(loadTag('news'));
            $core->tpl->end();
            ComplaintInit($news['id']);
            $news['allow_comments'] ? show_comments('news', $news['id'], $news_conf['comments_num']) : $core->tpl->info($lang['news_comments_off']);
            errorLocation($cat_one, $url_link, $actual_link);
        }
    } else {
        error_news();
    }
}

function news_add($nid = null)
{
    global $core, $db, $config, $news_conf, $user, $url, $lang;
    if (($core->auth->isUser && $core->auth->group_info['addPost'] == 1) || ($core->auth->isModer || $core->auth->isAdmin)) {
        if (isset($nid)) {
            $bb = new bb;
            $news = $core->row_data('news', 'id ="' . $nid . '"');
            $id = $news['id'];
            $row = $core->row_data('langs', 'PostId ="' . $id . '" AND module="news"');
            $etitle = $row['title'];
            $author = $news['author'];
            $date = gmdate('d.m.Y H:i', $news['date']);
            $tags = $news['tags'];
            $source = $news['source'];
            $groups = $news['groups'];
            $altname = $news['altname'];
            $fields = int_Serialize('uns', $news['fields']);
            $active = ($news['active'] == 2 ? 0 : $news['active']);
            $cat = $news['cat'];
            $cat_array = explode(',', $cat);
            $catttt = explode(',', $cat);
            $edit = true;
            $grroups = explode(',', $groups);
            $firstCat = $catttt[1];
            $file_module = 'news';
            $file_t = '';
            $deleteKey = array_search($firstCat, $catttt);
            unset($catttt[$deleteKey]);
            $langMassiv = $core->getLangList(true);
            $query = $core->select_data('langs', 'postId ="' . $id . '" AND module="news"');
            while ($langs = $db->getRow($query)) {
                $title[$langs['lang']] = prepareTitle($langs['title']);
                $short[$langs['lang']] = stripslashes($core->bbDecode(parseBB($langs['short'])));
                $full[$langs['lang']] = stripslashes($core->bbDecode(parseBB($langs['full'])));
            }
            $admhead = $lang['edit_news'];
            $action = $admhead;
            $dosave = $lang['update'];
        } else {
            $id = false;
            $short = false;
            $full = false;
            $etitle = false;
            $author = $core->auth->user_info['nick'];
            $date = false;
            $tags = false;
            $source = false;
            $cat = false;
            $altname = false;
            $keywords = false;
            $description = false;
            $fields = false;
            $fix = '';
            $active = 2;
            $edit = false;
            $catttt = array();
            $grroups = array();
            $firstCat = '';
            $file_module = 'user';
            $file_t = 'news';
            $admhead = $lang['add_news'];
            $action = $admhead;
            $dosave = $lang['add'];
        }
        set_title(array($lang['news'], $admhead));
        $query = $core->select_data('news', 'active = 2');
        if (($db->numRows($query) > $news_conf['preModer']) && (!isset($nid)) && ($core->auth->user_info['group'] != $news_conf['noModer'])) {
            $core->tpl->info($lang['news_add_info_0']);
        } else {
            if (!isset($nid) && ($core->auth->user_info['group'] != $news_conf['noModer'])) $core->tpl->info($lang['news_add_info_1']);
            $cat_one = '';
            $cat_more = '';
            $cats_arr = $core->aCatList('news');
            if (!empty($cats_arr)) {
                foreach ($cats_arr as $cid => $name) {
                    $selected = ($cid == $firstCat) ? "selected" : "";
                    $cat_one .= '<option value="' . $cid . '" ' . $selected . '>' . $name . '</option>';
                }
                foreach ($cats_arr as $cid => $name) {
                    if ($catttt) $selected = in_array($cid, $catttt) ? "selected" : "";
                    $cat_more .= '<option value="' . $cid . '" ' . $selected . ' id="cat_' . $cid . '">' . $name . '</option>';
                }
                $selected = ($cid == $firstCat) ? "selected" : "";
            }
            $status = '<option value="0" ' . ($active == 0 ? "selected" : "") . '>' . $lang['not_actively'] . '</option>
<option value="1" ' . ($active == 1 ? "selected" : "") . '>' . $lang['actively'] . '</option>
<option value="2" ' . ($active == 2 ? "selected" : "") . '>' . $lang['on_moderation'] . '</option>';
            $path = '';
            /*
             *  if ($url[1] == 'addPost' || $url[1] == 'editshort') {
                 $path == ROOT . 'files/news/' . $id;
                 if (!file_exists($path) && GetDirectorySize($path) == 0 && $author == $core->auth->user_info['nick']) {
                     initDir('news', 'users_' . $core->auth->user_info['id'], $id);
                 } else {
                     initDir('news', $id);
                 }
             }
            */
            initDir('news', 'users_' . $core->auth->user_info['id'], $id);

            $bbShort = bb_area('short', (isset($short[$config['lang']]) ? $short[$config['lang']] : ''), 5, 'textarea', 'onchange = "caa(this);"', true, true);
            $bbFull = bb_area('full', (isset($full[$config['lang']]) ? $full[$config['lang']] : ''), 5, 'textarea', 'onchange = "caa(this);"', true, false);
            $core->tpl->loadFile('news/news-add');
            preg_match("#\\[xfield_tpl\\](.*?)\\[/xfield_tpl\\]#si", $core->tpl->sources, $matchEmpty);
            if (isset($matchEmpty[1])) {
                $xfiled_tpl = $matchEmpty[1];
                $fields = int_Serialize('uns', $core->auth->user_info['fields']);
//$core->tpl->sources = preg_replace(array("#\\[\\](.*?)\\[/xfield_tpl\\]#si","#\\[list\\](.*?)\\[/list\\]#si"), array(($xfiled_tpl == 0 ? '\\1' : ''), $matchEmpty), $core->tpl->sources);
                $xfileds = '';
                $queryF = $core->select_data('xfields', 'module = "news" and to_user = 1');
                if ($db->numRows($queryF) > 0) {
                    while ($xfield = $db->getRow($queryF)) {
                        if ($xfield['type'] == 6) {
                            $xfieldChange = ' <div class="form-control" >
   <input id = "xfield[' . $xfield['id'] . ']" name = "xfield[' . $xfield['id'] . ']" type = "radio" ' . ($xfield['content'] == 0 ? 'checked' : '') . ' value = "0" >
   <label for="xfield[' . $xfield['id'] . ']" class="padding inputTitle" > ' . $lang['no'] . ' </label >
   <input id = "xfield[' . $xfield['id'] . ']" name = "xfield[' . $xfield['id'] . ']" type = "radio" ' . ($xfield['content'] == 1 ? 'checked' : '') . ' value = "1" >
   <label for="xfield[' . $xfield['id'] . ']" class="padding inputTitle" > ' . $lang['yes'] . ' </label >
</div>';
                        } elseif ($xfield['type'] == 5) {
                            $xfieldChange = ' < input id = "xfield[' . $xfield['id'] . ']" name = "xfield[' . $xfield['id'] . ']" ' . ($xfield['content'] ? 'checked' : '') . ' type = "checkbox"  value = "' . (!empty($fields[$xfield['id']][1]) ? $fields[$xfield['id']][1] : $xfield['content']) . '" > ';
                        } elseif ($xfield['type'] == 4) {
                            $xfieldChange = ' < textarea class="form-control" name = "xfield[' . $xfield['id'] . ']" > ' . (!empty($fields[$xfield['id']][1]) ? $fields[$xfield['id']][1] : $xfield['content']) . ' </textarea > ';
                        } elseif ($xfield['type'] == 3) {
                            $dxfield = array_map('trim', explode("\n", $xfield['content']));
                            $xfieldChange = ' < select class="form-control" name = "xfield[' . $xfield['id'] . ']" > ';
                            foreach ($dxfield as $xfiled_content) {
                                $xfieldChange .= '<option value = "' . $xfiled_content . '" ' . (isset($fields[$xfield['id']][1]) && $fields[$xfield['id']][1] == $xfiled_content ? 'selected' : '') . ' > ' . $xfiled_content . '</option > ';
                            }
                            $xfieldChange .= '</select > ';
                        } elseif ($xfield['type'] == 2) {
                            $xfieldChange = ' < textarea class="form-control" name = "xfield[' . $xfield['id'] . ']" > ' . (!empty($fields[$xfield['id']][1]) ? $fields[$xfield['id']][1] : ($id ? '' : $xfield['content'])) . ' </textarea > ';
                        } else {
                            $xfieldChange = '<input type = "text" class="form-control" name = "xfield[' . $xfield['id'] . ']" value = "' . (!empty($fields[$xfield['id']][1]) ? $fields[$xfield['id']][1] : ($id ? '' : $xfield['content'])) . '" > ';
                        }
                        $xfileds .= preg_replace(array('@{%XTITLE%}@', '@{%XBODY:\[(.*?)\] %}@is'), array($xfield['title'], str_replace('{addition}', stripslashes('\\1'), '<input type = "hidden" name = "xfieldT[' . $xfield['id'] . ']" value = "' . $xfield['title'] . '" > ' . $xfieldChange)), $xfiled_tpl);
                    }
                    $yesField = true;
                    $core->tpl->setVar('XFIELDS', $xfileds);
                }
            }
            $core->tpl->sources = preg_replace(array("#\\[fields\\](.*?)\\[/fields\\]#si", "#\\[xfield_tpl\\](.*?)\\[/xfield_tpl\\]#si"), array((isset($yesField) ? '\\1' : ''), ''), $core->tpl->sources);
            $core->tpl->setVar('BB_SHORT', $bbShort);
            $core->tpl->setVar('TITLE', $etitle);
            $core->tpl->setVar('BB_FULL', $bbFull);
            $core->tpl->setVar('ACTION', $action);
            $core->tpl->sources = preg_replace_callback("#\\[fileupload\\](.*?)\\[/fileupload\\]#is", function ($matches) use ($core, $news_conf) {
                if ($core->auth->user_info['loadAttach'] && $news_conf['fileEditor'] == 1) return $matches[1];
            }, $core->tpl->sources);

            $core->tpl->setVar('CATS_ONE', $cat_one);
            $core->tpl->setVar('CATS_MORE', $cat_more);
            $core->tpl->sources = preg_replace_callback("#\\[status\\](.*?)\\[/status\\]#is", function ($matches) {
                if (isset($nid)) return $matches[1];
            }, $core->tpl->sources);
            $core->tpl->setVar('STATUS', $status);
            $core->tpl->setVar('DO_IT', $dosave);
            $core->tpl->setVar('tags', $tags);
            $core->tpl->setVar('source', $source);
            $core->tpl->setVar('ID', $nid);
            $core->tpl->end();
        }
    } else {
        $info_text = isset($nid) && ($core->auth->isUser && $core->auth->group_info['addPost'] == 1) ? 'news_add_error_1' : 'news_add_error_0';
        $core->tpl->info($lang[$info_text]);
    }
    if (isset($core->auth->user_info['nick'])) {
        $access = $core->row_data('users', 'nick = "' . $db->safesql($core->auth->user_info['nick']) . '"');
        delcache('userInfo_' . $access['id']);
    }
}

function delete($id)
{
    global $core;
    $news = $core->row_data('news', 'id = "' . $id . '"');
    $core->del_data('langs', 'postId = "' . $news['id'] . '" AND module = "news"');
    full_rmdir(ROOT . initDC('news', '', '', $news['id']));
    $core->del_data('news', 'id = "' . $id . '"');
    $core->upd_data('users', 'user_news = user_news - 1', 'nick = "' . $news['author'] . '"');
    workTags($id, $news['tags'], 'delete');
    deleteComments('news', $id);
    $dirs = (ROOT . initDC('user', 'commments', $core->auth->user_info['id'], $news['id']));
    !$dirs ? '' : full_rmdir(ROOT . initDC('user', 'commments', $core->auth->user_info['id'], $news['id']));
}