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

$lng_lib = core::load_lng('library');
$textl = Kutubxona;

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

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

?>

    <!-- style table image -->
    <style type="text/css">
        .avatar {
            display: table-cell;
            vertical-align: top;
        }

        .avatar img {
            height: 32px;
            margin-right: 5px;
            margin-bottom: 5px;
            width: 32px;
        }

        .righttable {
            display: table-cell;
            vertical-align: top;
            width: 100%;
        }
    </style>
    <!-- end style -->

<?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"><strong>' . $lng['library'] . '</strong></div>';

        echo '<div class="gmenu"><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 functions::image('new.png', array('width' => 16, 'height' => 16)) . '<a href="?act=new">' . $lng_lib['new_articles'] . '</a> (' . $res . ')<br/>';
        }

echo functions::image('rate.gif', array('width' => 16, 'height' => 16)) . '<a href="?act=top"> Top maqolalar</a><br/>' .
functions::image('talk.gif', array('width' => 16, 'height' => 16)) . '<a href="?act=lastcom">Oxirgi fikrlar</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) . '">'
                    . '<a href="?do=dir&amp;id=' . $row['id'] . '">' . functions::checkout($row['name']) . '</a> ('
                    . mysql_result(mysql_query("SELECT COUNT(*) FROM `" . ($row['dir'] ? 'library_cats' : 'library_texts') . "` WHERE " . ($row['dir'] ? '`parent`=' . $row['id'] : '`cat_id`=' . $row['id'])), 0) . ')';

                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> | Udalit yo\'q</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="rmenu"><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"><center>' . $dir_nav->print_nav_panel() . '</center></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) . '">'
                                . '<a href="?do=dir&amp;id=' . $row['id'] . '">' . functions::checkout($row['name']) . '</a>('
                                . mysql_result(mysql_query("SELECT COUNT(*) FROM `" . ($row['dir'] ? 'library_cats' : 'library_texts') . "` WHERE " . ($row['dir'] ? '`parent`=' . $row['id'] : '`cat_id`=' . $row['id'])), 0) . ' '
                                . ($row['dir'] ? ' кат.' : ' ст.') . ')'
                                . '<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> | Udalit yo`q qilish</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"><a href="?act=moder&amp;type=dir&amp;id=' . $id . '">' . $lng['edit'] . '</a><br/>'
. 'Udalit yo`q xD.<br/>'
                            . '<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="menu"><center>' . functions::display_pagination('?do=dir&amp;id=' . $id . '&amp;', $start, $total, $kmess) . '</center></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 '<div class="menu">';
                        while ($row = mysql_fetch_assoc($sql2)) {

echo '<a href="index.php?id=' . $row['id'] . '"><img src="/ico/forum.png"> ' . functions::checkout($row['name']) . '</a><hr>';
                        }
                    } else {
                        echo '<div class="menu">' . $lng['list_empty'] . '</div>';
                    }

echo '</div></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"><a href="?act=addnew&amp;id=' . $id . '">' . $lng_lib['write_article'] . '</a>'
                            . ($adm ? ('<br/><a href="?act=moder&amp;type=dir&amp;id=' . $id . '">' . $lng['edit'] . '</a><br/>'
. '<a href="/">Udalit yo`qatish</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="menu"><center>' . functions::display_pagination('index.php?id=' . $id . '&amp;', $page == 1 ? 0 : ($page - 1) * 1, $count_pages, 1) . '</center></div>' : '';
                    $catalog = mysql_fetch_assoc(mysql_query("SELECT `id`, `name` FROM `library_cats` WHERE `id` = " . $res['cat_id'] . " LIMIT 1"));
echo ' <div class="menu"><a href="/"><img src="/ico/home.png"></a> &raquo; <a href="/library/i.php">Yoqimli kutubxona</a> &raquo; <a href="?do=dir&amp;id=' . $catalog['id'] . '">' . functions::checkout($catalog['name']) . '</a></div>';
                    // Верхняя постраничная навигация
                    if ($count_pages > 1) {
                    }

                        echo '</div>';
                        // Заголовок статьи
                        echo '<div class="phdr"><center>' . functions::checkout($res['name']) . '</center></div>';
echo '<div class="menu">';
// reklama
echo '<center>';
if (!empty($cms_ads[3])) {
echo $cms_ads[3];
}
echo '</center>';
if ($page == 1) {
                        // Описание к статье
                        $obj = new Hashtags($res['id']);
                        $rate = new Rating($res['id']);
                        $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']);
                    }

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

                    if ($page == 1) {
                        // Картинка статьи
                        if (file_exists('../files/library/images/big/' . $id . '.png')) {
                            $img_style = 'width: 50%; max-width: 240px; height: auto; float: left; clear: both; margin: 10px';
echo '<center><img src="../files/library/images/big/' . $id . '.png" width="300" height="200" style="background: #ffffff; padding: 3px;border: 1px solid #CCCCE5;border-radius: 2px;" alt="."></center><br>';}
echo '<center><b>Joylandi:</b> <font color="red"> ' . functions::display_date($res['time']) . '</font></center></center><hr>';
}
                    // Выводим текст статьи
                    echo $text .
                        '</div>' .
'</div>';

                    echo $nav;

echo '<div class="menu"> <div class="sub" align="center"><!-- LikeBtn.com BEGIN -->
<span class="likebtn-wrapper" data-theme="custom" data-icon_l_c="#ffffff" data-icon_l_c_v="#ffffff" data-icon_d_c="#ffffff" data-icon_d_c_v="#ffffff" data-label_c="#ffffff" data-label_c_v="#ffffff" data-counter_l_c="#ffffff" data-counter_d_c="#ffffff" data-bg_c="#9f3089" data-bg_c_v="#9f3089" data-brdr_c="#db54f3" data-i18n_like="Yoqdi" data-identifier="nwEnt2362" data-show_dislike_label="true" data-share_enabled="false" data-share_size="small" data-loader_show="true"   data-i18n_dislike="Yoqmadi" data-i18n_after_like="Yoqdi" data-i18n_after_dislike="Yoqmadi" data-i18n_like_tooltip="Menga bu yoqdi" data-i18n_dislike_tooltip="Menga bu yoqmadi" data-i18n_unlike_tooltip="Menga endi yoqmaydi" data-i18n_undislike_tooltip="Rad etish"></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>
<hr><center><b> Do\'stlaringizga ulashing</center> </b><div class="it-share-93f60bacb3f5ffd3f41380e5a80d44fc horizontal center"></div><script type="text/javascript" async charset="utf-8" src="//share.itraffic.su/share.js?buttons=tg,wa,vi,ok,fb,vk,bm&size=normal&theme=1&align=center&direction=horizontal&add=0&key=93f60bacb3f5ffd3f41380e5a80d44fc"></script><hr>
<center>Ko\'rildi: <b>' . $res['count_views'] . '</b> | Joyladi: ' . $uploader . '</center>
</div>';

include ('includes/comments.php');
//Tasodifiy Maqola For 6xx library
echo '<div class="phdr"><center>Tasodifiy maqolalar</center></div>';
echo '<div class="menu">';
$tasodifiy = mysql_query ("SELECT * FROM `library_texts` WHERE `premod` = '1' ORDER BY RAND() LIMIT 5");
while ($tasodif = mysql_fetch_array($tasodifiy)) {
echo '<a href="../library/index.php?id='.$tasodif['id'].'"><img src="/ico/link.png" alt="link"/> '.$tasodif['name'].'</a><hr>';
}
echo '</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"><a href="?act=moder&amp;type=article&amp;id=' . $id . '">' . $lng['edit'] . '</a><br/>'
                            . '<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');