<?php

define('_IN_JOHNCMS', 1);
$headmod = 'library';
require_once('../incfiles/core.php');
require_once('inc.php');

$lng_lib = core::load_lng('library');
$textl = $lng['library'];

// Ограничиваем доступ к Библиотеке
$error = '';

if (!$set['mod_lib'] && $rights < 7) {
    $error = $lng_lib['library_closed'];
} elseif ($set['mod_lib'] == 1 && !$user_id) {
    $error = $lng['access_guest_forbidden'];
}

if ($error) {
    require_once('../incfiles/head.php');
    echo functions::display_error($error);
    require_once('../incfiles/end.php');
    exit;
}

// Заголовки библиотеки
if ($do) {
    switch ($do) {
        case 'dir':
            $tab = 'library_cats';
            break;

        default:
            $tab = 'library_texts';
    }

    $hdr = $id > 0 ? htmlentities(mb_substr(mysql_result(mysql_query("SELECT `name` FROM `" . $tab . "` WHERE `id`=" . $id . " LIMIT 1"), 0), 0, 30), ENT_QUOTES, 'UTF-8') : '';
    if ($hdr) {
        $textl = mb_strlen($hdr) > 30 ? $hdr . '...' : $hdr;
    }
}

require_once('../incfiles/head.php');

if (!$set['mod_lib']) {
    echo functions::display_error($lng_lib['library_closed']);
}

$array_includes = array(
    'addnew',
    'comments',
    'del',
    'download',
    'mkdir',
    'moder',
    'move',
    'new',
    'premod',
    'search',
    'top',
    'tags',
    'tagcloud',
    'lastcom'
);
$i = 0;

if (in_array($act, $array_includes)) {
    require_once('includes/' . $act . '.php');
} else {
    if (!$id) {
        echo '<div class="phdr"><b>' . $lng['library'] . '</b></div>';
        echo '<div class="topmenu"><a href="?act=search">' . $lng['search'] . '</a> | <a href="?act=tagcloud">' . $lng_lib['tagcloud'] . '</a></div>';

        echo '<div class="menu"><p>';
        if ($adm) {
            // Считаем число статей, ожидающих модерацию
            $res = mysql_result(mysql_query("SELECT COUNT(*) FROM `library_texts` WHERE `premod`=0"), 0);
            if ($res > 0) {
                echo '<div>' . $lng['on_moderation'] . ': <a href="?act=premod">' . $res . '</a></div>';
            }
        }
        $res = mysql_result(mysql_query("SELECT COUNT(*) FROM `library_texts` WHERE `time` > '" . (time() - 259200) . "' AND `premod`=1"), 0);
        if ($res) {
            echo '&raquo; <a href="?act=new">' . $lng_lib['new_articles'] . '</a> (' . $res . ')<br/>';
        }

        echo '&raquo; <a href="?act=lastcom">' . $lng_lib['last_comments'] . '</a><br/>' .
			'&raquo; <a href="?act=top&sort=read">TOP O\'qilganlar</a><br/>' .
            '&raquo; <a href="?act=top&sort=rating">TOP Ovoz olganlar</a><br/>' .
            '&raquo; <a href="?act=top&sort=comm">TOP Fikr bildirilganlar</a></p></div>';
        $sql = mysql_query("SELECT `id`, `name`, `dir`, `description` FROM `library_cats` WHERE `parent`=0 ORDER BY `pos` ASC");
        $total = mysql_result(mysql_query("SELECT COUNT(*) FROM `library_cats` WHERE `parent`=0"), 0);
        $y = 0;
        if ($total) {
            while ($row = mysql_fetch_assoc($sql)) {
                $y++;
echo '<div class="list' . (++$i % 2 ? 2 : 1) . '">&raquo; '
                    . '<a href="?do=dir&amp;id=' . $row['id'] . '">' . functions::checkout($row['name']) . '</a> <span class="count">'
                    . mysql_result(mysql_query("SELECT COUNT(*) FROM `" . ($row['dir'] ? 'library_cats' : 'library_texts') . "` WHERE " . ($row['dir'] ? '`parent`=' . $row['id'] : '`cat_id`=' . $row['id'])), 0) . '</span>';

                if (!empty($row['description'])) {
                    echo '<div style="font-size: x-small; padding-top: 2px"><span class="gray">' . functions::checkout($row['description']) . '</span></div>';
                }

                if ($adm) {
                    echo '<div class="sub">' . ($y != 1 ? '<a href="?act=move&amp;moveset=up&amp;posid=' . $y . '">' . $lng['up'] . '</a> | ' : $lng['up'] . ' | ') . ($y != $total ? '<a href="?act=move&amp;moveset=down&amp;posid=' . $y . '">' . $lng['down'] . '</a>' : $lng['down']) . ' | <a href="?act=moder&amp;type=dir&amp;id=' . $row['id'] . '">' . $lng['edit'] . '</a> | <a href="?act=del&amp;type=dir&amp;id=' . $row['id'] . '">' . $lng['delete'] . '</a></div>';
                }

                echo '</div>';
            }
        } else {
            echo '<div class="menu">' . $lng['list_empty'] . '</div>';
        }

        echo '<div class="phdr">' . $lng['total'] . ': ' . $total . '</div>';
        if ($adm) {
            echo '<div class="menu">&raquo; <a href="?act=mkdir&amp;id=0">' . $lng_lib['create_category'] . '</a></div>';
        }
    } else {
        $dir_nav = new Tree($id);
        $dir_nav->process_nav_panel();
        switch ($do) {
            case 'dir':
                // dir
                $actdir = mysql_fetch_assoc(mysql_query("SELECT `id`, `dir` FROM `library_cats` WHERE " . ($id !== null ? '`id`=' . $id : 1) . " LIMIT 1"));
                $actdir = $actdir['id'] > 0 ? $actdir['dir'] : redir404();
                echo '<div class="phdr">' . $dir_nav->print_nav_panel() . '</div>';

                if ($actdir) {
                    $total = mysql_result(mysql_query("SELECT COUNT(*) FROM `library_cats` WHERE " . ($id !== null ? '`parent`=' . $id : '`parent`=0')), 0);
                    $nav = ($total > $kmess) ? '<div class="topmenu">' . functions::display_pagination('?do=dir&amp;id=' . $id . '&amp;', $start, $total, $kmess) . '</div>' : '';
                    $y = 0;

                    if ($total) {
                        $sql = mysql_query("SELECT `id`, `name`, `dir`, `description` FROM `library_cats` WHERE " . ($id !== null ? '`parent`=' . $id : '`parent`=0') . ' ORDER BY `pos` ASC LIMIT ' . $start . ',' . $kmess);
                        echo $nav;

                        while ($row = mysql_fetch_assoc($sql)) {
                            $y++;
echo '<div class="list' . (++$i % 2 ? 2 : 1) . '">&raquo; '
                                . '<a href="?do=dir&amp;id=' . $row['id'] . '">' . functions::checkout($row['name']) . '</a> <span class="count">'
                                . mysql_result(mysql_query("SELECT COUNT(*) FROM `" . ($row['dir'] ? 'library_cats' : 'library_texts') . "` WHERE " . ($row['dir'] ? '`parent`=' . $row['id'] : '`cat_id`=' . $row['id'])), 0) . '</span>';
				
			                    if (!empty($row['description'])) {
                    echo '<div class="sub"><span class="gray">' . functions::checkout($row['description']) . '</span></div>';
                }
                            if ($adm) {
                                echo '<div class="sub">'
                                    . ($y != 1 ? '<a href="?do=dir&amp;id=' . $id . '&amp;act=move&amp;moveset=up&amp;posid=' . $y . '">' . $lng_lib['up']
                                        . '</a> | ' : '' . $lng_lib['up'] . ' | ')
                                    . ($y != $total
                                        ? '<a href="?do=dir&amp;id=' . $id . '&amp;act=move&amp;moveset=down&amp;posid=' . $y . '">' . $lng_lib['down'] . '</a>'
                                        : $lng_lib['down'])
                                    . ' | <a href="?act=moder&amp;type=dir&amp;id=' . $row['id'] . '">' . $lng['edit'] . '</a> | <a href="?act=del&amp;type=dir&amp;id=' . $row['id'] . '">' . $lng['delete'] . '</a></div>';
                            }
                            echo '</div>';
                        }
                    } else {
                        echo '<div class="menu"><p>' . $lng['list_empty'] . '</p></div>';
                    }

                    echo '<div class="phdr">' . $lng['total'] . ': ' . $total . '</div>';
                    echo $nav;

                    if ($adm) {
                        echo '<div class="menu">&raquo; <a href="?act=moder&amp;type=dir&amp;id=' . $id . '">' . $lng['edit'] . '</a><br/>'
                            . '&raquo; <a href="?act=del&amp;type=dir&amp;id=' . $id . '">' . $lng['delete'] . '</a><br/>'
                            . '&raquo; <a href="?act=mkdir&amp;id=' . $id . '">' . $lng_lib['create_category'] . '</a></div>';
                    }
                } else {
                    $total = mysql_result(mysql_query('SELECT COUNT(*) FROM `library_texts` WHERE `premod`=1 AND `cat_id`=' . $id), 0);
                    $page = $page >= ceil($total / $kmess) ? ceil($total / $kmess) : $page;
                    $start = $page == 1 ? 0 : ($page - 1) * $kmess;
                    $nav = ($total > $kmess) ? '<div class="topmenu">' . functions::display_pagination('?do=dir&amp;id=' . $id . '&amp;', $start, $total, $kmess) . '</div>' : '';

                    if ($total) {
                        $sql2 = mysql_query("SELECT `id`, `name`, `time`, `uploader`, `uploader_id`, `count_views`, `count_comments`, `comments`, `announce` FROM `library_texts` WHERE `premod`=1 AND `cat_id`=" . $id . " ORDER BY `id` DESC LIMIT " . $start . "," . $kmess);
                        echo $nav;

                        while ($row = mysql_fetch_assoc($sql2)) {
echo '<div class="menu">
<img src="/daviuz/news.png"><a href="index.php?id=' . $row['id'] . '">' . functions::checkout($row['name']) . '</a>
</div>';

                            // Описание к статье

$obj = new Hashtags($row['id']);
                            $rate = new Rating($row['id']);
                            $uploader = $row['uploader_id'] ? '<a href="' . core::$system_set['homeurl'] . '/users/profile.php?user=' . $row['uploader_id'] . '">' . functions::checkout($row['uploader']) . '</a>' : functions::checkout($row['uploader']);
                            echo '<table class="desc">'
                                . ($obj->get_all_stat_tags() ? '<tr><td class="caption">' . $lng_lib['tags'] . ':</td><td>' . $obj->get_all_stat_tags(1) . '</td></tr>' : '')
. '<tr><td class="caption"></td></tr>'
. '<tr><td class="caption"></td></tr>'
. '<tr><td class="caption"></td></tr></table></div>';
                        }
} else {
echo '<div class="menu">'.$lng['list_empty'] . '</div>';
                    }
                    echo '<div class="phdr">' . $lng['total'] . ': ' . $total . '</div>';
                    echo $nav;

                    if (($adm || (mysql_result(mysql_query("SELECT `user_add` FROM `library_cats` WHERE `id`=" . $id), 0) > 0)) && isset($id) && $user_id) {
                        echo '<div class="menu">&raquo; <a href="?act=addnew&amp;id=' . $id . '">' . $lng_lib['write_article'] . '</a>'
                            . ($adm ? ('<br/>&raquo; <a href="?act=moder&amp;type=dir&amp;id=' . $id . '">' . $lng['edit'] . '</a><br/>'
                                . '&raquo; <a href="?act=del&amp;type=dir&amp;id=' . $id . '">' . $lng['delete'] . '</a>') : '')
                            . '</div>';
                    }
                }

                break;

            default:
                $res = mysql_fetch_assoc(mysql_query("SELECT * FROM `library_texts` WHERE `id`=" . $id));
                if ($res['premod'] || $adm) {

                    // Счетчик прочтений
                    if (!isset($_SESSION['lib']) || isset($_SESSION['lib']) && $_SESSION['lib'] != $id) {
                        $_SESSION['lib'] = $id;
                        mysql_query('UPDATE `library_texts` SET  `count_views`=' . ($res['count_views'] ? ++$res['count_views'] : 1) . ' WHERE `id`=' . $id);
                    }

                    // Запрашиваем выбранную статью из базы
                    $symbols = core::$is_mobile ? 3000 : 7000;
                    $count_pages = ceil(mysql_result(mysql_query("SELECT CHAR_LENGTH(`text`) FROM `library_texts` WHERE `id`= '" . $id . "' LIMIT 1"), 0) / $symbols);
                    if ($count_pages) {

                        // Чтоб всегда последнюю страницу считал правильно
                        $page = $page >= $count_pages ? $count_pages : $page;
                        $text = mysql_result(mysql_query("SELECT SUBSTRING(`text`, " . ($page == 1 ? 1 : ($page - 1) * $symbols) . ", " . ($symbols + 100) . ") FROM `library_texts` WHERE `id`='" . $id . "'"), 0);
                        $tmp = mb_substr($text, $symbols, 100);
                    } else {
                        redir404();
                    }

                    $nav = $count_pages > 1 ? '<div class="topmenu">' . functions::display_pagination('index.php?id=' . $id . '&amp;', $page == 1 ? 0 : ($page - 1) * 1, $count_pages, 1) . '</div>' : '';
                    $catalog = mysql_fetch_assoc(mysql_query("SELECT `id`, `name` FROM `library_cats` WHERE `id` = " . $res['cat_id'] . " LIMIT 1"));
echo '<div class="phdr"><b><center >' . functions::checkout($res['name']) . '</center></b></div>';

                    // Верхняя постраничная навигация
                    if ($count_pages > 1) {
                        echo '<div class="topmenu"><p>' . functions::display_pagination('index.php?id=' . $id . '&amp;', $page == 1 ? 0 : ($page - 1) * 1, $count_pages, 1) . '</p></div>';
                    }

                    $text = functions::checkout(mb_substr($text, ($page == 1 ? 0 : min(position($text, PHP_EOL), position($text, ' '))), (($count_pages == 1 || $page == $count_pages) ? $symbols : $symbols + min(position($tmp, PHP_EOL), position($tmp, ' ')) - ($page == 1 ? 0 : min(position($text, PHP_EOL), position($text, ' '))))), 1, 1);
                    if ($set_user['smileys']) {
                        $text = functions::smileys($text, $rights ? 1 : 0);
                    }

                    echo '<div class="menu">';
                    if ($page == 1) {
                        // Заголовок статьи
$uploader = $res['uploader_id'] ? '<a href="' . core::$system_set['homeurl'] . '/users/profile.php?user=' .$res['uploader_id'] . '"> ' . functions::checkout($res['uploader']) . '</a>' : functions::checkout($res['uploader']);

echo '<b>Qo\'shdi: </b>' . $uploader . ' | <b>Ko\'rildi:</b> ' .$res['count_views'] . '<br/>';
echo '<b>Joylandi:</b> ' .functions::display_date($res['time']) . '<br/>';
                        // Картинка статьи
                        if (file_exists('../files/library/images/big/' . $id . '.png')) {
echo '<p><center><a href="../files/library/images/orig/' . $id . '.png"><img src="../files/library/images/big/' . $id . '.png" alt="screen" /></a></center></p><br/>';
}
} 
					
// Выводим текст статьи

echo $text . '</div>';
                    if ($page == 1) {
                        // Описание к статье



echo '<hr>';
}

echo '<tr><td class="caption"></td></tr>';

echo '</b>';



echo '<div class="menu"><!-- LikeBtn.com BEGIN --><span class="likebtn-wrapper" data-theme="facebook" data-lang="ru" data-identifier="item_1"></span><script>(function(d,e,s){if(d.getElementById("likebtn_wjs"))return;a=d.createElement(e);m=d.getElementsByTagName(e)[0];a.async=1;a.id="likebtn_wjs";a.src=s;m.parentNode.insertBefore(a, m)})(document,"script","//w.likebtn.com/js/w/widget.js");</script><!-- LikeBtn.com END --></div>';



echo '<div class="menu"><script src="//yastatic.net/es5-shims/0.0.2/es5-shims.min.js"></script>
<script src="//yastatic.net/share2/share.js"></script>
<div class="ya-share2" data-services="vkontakte,facebook,odnoklassniki,moimir,whatsapp,telegram"></div></div>';


                    if ($adm || mysql_result(mysql_query("SELECT `uploader_id` FROM `library_texts` WHERE `id` = " . $id), 0) == $user_id && $user_id) {
                        echo '<div class="menu">&raquo; <a href="?act=moder&amp;type=article&amp;id=' . $id . '">' . $lng['edit'] . '</a><br/>'
                            . '&raquo; <a href="?act=del&amp;type=article&amp;id=' . $id . '">' . $lng['delete'] . '</a></div>';
                    }
                } else {
                    redir404();
                }
        } // end switch
    } // end else !id
} // end else $act
require_once('../incfiles/end.php');