<?php

/* DCMS Special
 * Дата последнего редактирования 09.10.2016
 * Модифицировал densnet
 */

foreach (array('start', 'compress', 'sess', 'settings', 'db_connect', 'ipua', 'fnc', 'user') as $inc) {
    require_once "../../sys/inc/$inc.php";
}

if (isset($_GET['d'])) {
    $name = esc(urldecode($_GET['d']));
    $q = $db->super_query("SELECT COUNT(*) as count FROM diary WHERE name = '$name' LIMIT 1");
    if ($q['count'] != 0) {
        $diary = $db->get_row($db->query("SELECT * FROM `diary` WHERE `name`='$name' LIMIT 1"));
        $us = get_user($diary['id_user']);
        $set['title'] = '' . $diary['name'] . ' - ' . lang('Блог') . ' ' . $us['nick'] . ''; // заголовок страницы

        if ($diary['tags'] != NULL) {
            $set['meta_keywords'] = '' . $diary['tags'] . '';
        }
        $set['meta_description'] = '' . cut_text($diary['msg']) . '';

        require_once H . 'sys/inc/thead.php';

        aut();

        if (isset($_POST['save']) && isset($user)) {
            if (isset($_POST['msg']) && ($user['id'] == $us['id'] || $user['level'] > 2 && $user['level'] > $us['level'])) {
                $msg = esc(stripcslashes(htmlspecialchars($_POST['msg'])));

                if (utf8_strlen($msg) < 10) {
                    $err[] = lang('Слишком короткое содержание');
                }
                if (utf8_strlen($msg) > 10000) {
                    $err[] = lang('Слишком длинное содержание');
                }

                $mat = antimat($msg);

                if ($mat) {
                    $err[] = lang('В содержании обнаружен мат') . ': ' . $mat;
                }

                $msg = $db->safesql($msg);

                if (!isset($err)) {
                    $diary['msg'] = esc(stripcslashes(htmlspecialchars($_POST['msg'])));

                    $db->query("UPDATE `diary` SET `msg`='$msg' WHERE `id`='$diary[id]' LIMIT 1");
                    $_SESSION['message'] = lang('Изменения сохранены');

                    header("Location: /modules/diary/$diary[name]/");
                    exit();
                }
            } elseif (isset($_POST['tags']) && ($user['id'] == $us['id'] || $user['level'] > 2 && $user['level'] > $us['level'])) {
                $tags = esc(stripcslashes(htmlspecialchars($_POST['tags'])));

                if (utf8_strlen($tags) < 2) {
                    $err[] = lang('Слишком короткие теги');
                }
                if (utf8_strlen($tags) > 256) {
                    $err[] = lang('Слишком длинные теги');
                }

                $mat = antimat($tags);

                if ($mat) {
                    $err[] = lang('В тегах обнаружен мат') . ': ' . $mat;
                }

                $tags = $db->safesql($tags);

                if (!isset($err)) {
                    $diary['tags'] = $tags;
                    $db->query("UPDATE `diary` SET `tags`='$diary[tags]' WHERE `id`='$diary[id]' LIMIT 1");
                    $_SESSION['message'] = lang('Изменения сохранены');

                    header("Location: /modules/diary/$diary[name]/");
                    exit();
                }
            } elseif (isset($_POST['cat']) && $user['level'] > 2 && ($user['id'] == $us['id'] || $user['level'] > $us['level'])) {
                $q = $db->super_query("SELECT COUNT(*) as count FROM diary_cat WHERE id = '" . intval($_POST['cat']) . "' LIMIT 1");
                if ($q['count'] != 0) {
                    $diary['id_cat'] = intval($_POST['cat']);
                    $db->query("UPDATE `diary` SET `id_cat`='" . intval($_POST['cat']) . "' WHERE `id`='$diary[id]' LIMIT 1");
                    $_SESSION['message'] = lang('Изменения сохранены');

                    header("Location: /modules/diary/$diary[name]/");
                    exit();
                } else {
                    $err[] = lang('Ошибка категории');
                }
            } elseif (isset($_POST['name']) && $user['level'] > 2 && ($user['id'] == $us['id'] || $user['level'] > $us['level'])) {
                $name = $_POST['name'];

                if (utf8_strlen($name) < 3) {
                    $err[] = lang('Слишком короткое название');
                }
                if (utf8_strlen($name) > 100) {
                    $err[] = lang('Слишком длинное название');
                }

                $mat = antimat($name);

                if ($mat) {
                    $err[] = lang('В названии обнаружен мат') . ': ' . $mat;
                }
                $name = $db->safesql($name);

                $q = $db->super_query("SELECT COUNT(*) as count FROM diary WHERE name = '$name' LIMIT 1");
                if ($q['count'] != 0) {
                    $err[] = lang('Блог с таким названием уже существует');
                }

                if (!isset($err)) {
                    $diary['name'] = $name;
                    $db->query("UPDATE `diary` SET `name`='$diary[name]' WHERE `id`='$diary[id]' LIMIT 1");
                    $_SESSION['message'] = lang('Изменения сохранены');

                    header("Location: /modules/diary/$diary[name]/");
                    exit();
                }
            } elseif (isset($_POST['readers']) && ($_POST['readers'] == 0 || $_POST['readers'] == 1 || $_POST['readers'] == 2) && ($user['id'] == $us['id'] || $user['level'] > 2 && $user['level'] > $us['level'])) {
                $readers = intval($_POST['readers']);
                $diary['readers'] = $readers;
                $db->query("UPDATE `diary` SET `readers`='$diary[readers]' WHERE `id`='$diary[id]' LIMIT 1");
                $_SESSION['message'] = lang('Изменения сохранены');

                header("Location: /modules/diary/$diary[name]/");
                exit();
            }
        }

        $q = $db->super_query("SELECT COUNT(*) as count FROM friends WHERE (`user` = '$user[id]' AND `friends` = '$us[id]') OR (`user` = '$us[id]' AND `friends` = '$user[id]')");
        if (isset($user) && $us['id'] != $user['id'] && ($user['level'] > $us['level'] || ($diary['readers'] == 0 || $diary['readers'] == 1) || $diary['readers'] == 2 && $q['count'] != 0)) {
            $q = $db->super_query("SELECT COUNT(*) as count FROM diary_rating WHERE `id_diary` = '$diary[id]' AND `id_user`='$user[id]' LIMIT 1");
            if ($q['count'] == 0 && isset($_GET['plus']) && ($_GET['plus'] == 1 || $_GET['plus'] == 2 || $_GET['plus'] == 3 || $_GET['plus'] == 4 || $_GET['plus'] == 5)) {
                $plus = intval($_GET['plus']);
                $db->query("INSERT INTO `diary_rating` (`id_diary`, `id_user`, `rating`) values ('$diary[id]', '$user[id]', '$plus')");
                $rat = $db->super_query("SELECT SUM(`rating`) as rating FROM `diary_rating` WHERE `id_diary` = '$diary[id]'");
                $diary['rating'] = $rat['rating'];
                $db->query("UPDATE `diary` SET `rating`='$diary[rating]' WHERE `id`='$diary[id]' LIMIT 1");
                $db->query("INSERT INTO `notification` (`id_user`, `id_kont`, `msg`, `time`) values('$user[id]', '$us[id]', '$SexOst отзыв +$plus к Блогу [url=/modules/diary/$diary[name]/]$diary[name][/url]', '$time')");
                $_SESSION['message'] = lang('Голос засчитан. Спасибо');

                header("Location: /modules/diary/$diary[name]/");
                exit();
            }
        }
        $cat = $db->get_row($db->query("SELECT * FROM `diary_cat` WHERE `id`='$diary[id_cat]' LIMIT 1"));
        err();

        #Навигация
        echo "<div class='list-group-item-null list-group-item-grey'><small>";
        echo "<a href='/' class='hint--right' data-hint='" . lang('На главную') . "'><i class='fa fa-home fa-lg'></i></a> <i class='fa fa-angle-right fa-fw'></i> ";
        echo "<a href='/modules/diary/'>" . lang('Блоги') . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
        echo "<a href='/modules/diary/?r=$cat[id]'>" . cutStr($cat['name'], 30) . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
        echo cutStr($diary['name'], 30);
        echo "</small></div><br />";

        if (isset($user) && $user['level'] > 2 && ($user['id'] == $us['id'] || $user['level'] > $us['level'])) {
            if (isset($_GET['delete'])) {
                echo '<div class="list-group-item-null list-group-item-info">';
                echo lang('Вы уверены, что хотите удалить Блог') . '?<br />';
                echo '<a class="btn btn-success btn-sm" href="/modules/diary/?r=' . $diary['id_cat'] . '&del=' . $diary['id'] . '">Да</a> <a class="btn btn-secondary btn-sm" href="/modules/diary/' . $diary['name'] . '/" title="Нет, отменить удаление">Нет</a></div>';
            }
        }

        if (isset($_GET['edit']) && $_GET['edit'] == 'name' && isset($user) && $user['level'] > 2 && ($user['id'] == $us['id'] || $user['level'] > $us['level'])) {
            echo "<form method='post' class='list-group-item-null list-group-item-grey' name='message' action='/modules/diary/$diary[name]/'>";
            echo lang('Название') . "<br />";
            echo "<input name='name' maxlength='100' required type='text' value='$diary[name]' class='form-control'>";
            echo "<br />";
            $doc->Button('btn btn-success btn-sm', 'save', 'save', 'Сохранить');
            $doc->Link('btn btn-secondary btn-sm', "/modules/diary/$diary[name]/", null, 'Отмена');
            echo "</form>";
        } else {
            echo "<div class='list-group-item-null list-group-item-grey'><span style='float: right;'>";
            if (isset($user) && $user['level'] > 2 && ($user['id'] == $us['id'] || $user['level'] > $us['level'])) {
                echo "<a href='?edit=name' class='hint--left' data-hint='" . lang('Редактировать название') . "'><i class='fa fa-edit fa-fw'></i></a>";
            }
            if (isset($user) && ($user['id'] == $us['id'] || $user['level'] > 2 && $user['level'] > $us['level'])) {
                echo "<a href='?delete' class='hint--left' data-hint='" . lang('Удалить блог') . "'><i class='fa fa-trash-o fa-fw'></i></a>";
            }
            echo "</span>";
            echo "<i class='fa fa-book fa-fw'></i> " . toOutput($diary['name']) . "<br />";
            echo "</div>";
        }

        $q = $db->super_query("SELECT COUNT(*) as count FROM diary_images WHERE id_diary = '$diary[id]' AND `position`='up' LIMIT 1");
        if ($q['count'] > 0) {
            echo '<div class="list-group-item-null">';
            $q = $db->query("SELECT * FROM `diary_images` WHERE `id_diary`='$diary[id]' AND `position`='up' ORDER BY `id` ASC");
            while ($image = $db->get_row($q)) {
                echo '<a href="/modules/diary/images/' . $image['id'] . '.' . $image['ras'] . '" title="Скачать оригинал">';
                if (IS_WEB) {
                    echo '<img src="/modules/diary/images/640/' . $image['id'] . '.' . $image['ras'] . '" style="width: 500px;" alt=""/></a> ';
                } else {
                    echo '<img src="/modules/diary/images/128/' . $image['id'] . '.' . $image['ras'] . '" alt=""/></a> ';
                }
            }
            echo'</div>';
        }
        if (isset($_GET['edit']) && $_GET['edit'] == 'msg' && isset($user) && ($user['id'] == $us['id'] || $user['level'] > 2 && $user['level'] > $us['level'])) {
            echo "<form method='post' class='list-group-item-null' name='message' action='/modules/diary/$diary[name]/'>";
            echo lang('Содержание') . "<br />";
            echo "<textarea name='msg' maxlength='10024' required class='form-control'>" . $diary['msg'] . "</textarea>";

            echo '<br/>';
            $doc->Button('btn btn-success btn-sm', 'save', 'save', 'Сохранить');
            $doc->Link('btn btn-secondary btn-sm', "/modules/diary/$diary[name]/", null, 'Отмена');
            echo '</form>';
        } else {
            echo '<div class="list-group-item-null">';
            echo toOutput($diary['msg']) . ' ';
            if (isset($user) && ($user['id'] == $us['id'] || $user['level'] > 2 && $user['level'] > $us['level'])) {
                echo "<a href='?edit=msg' style='float: right;' class='hint--left' data-hint='" . lang('Редактировать содержание') . "'><i class='fa fa-edit fa-fw'></i></a>";
            }
            echo '</div>';
        }

        $q = $db->super_query("SELECT COUNT(*) as count FROM diary_images WHERE id_diary = '$diary[id]' AND `position`='down' LIMIT 1");
        if ($q['count'] > 0) {
            echo '<div class="list-group-item-null">';
            $q2 = $db->query("SELECT * FROM `diary_images` WHERE `id_diary`='$diary[id]' AND `position`='down' ORDER BY `id` ASC");
            while ($image2 = $db->get_row($q2)) {
                echo '<a href="/modules/diary/images/' . $image2['id'] . '.' . $image2['ras'] . '" title="Скачать оригинал">';
                if (IS_WEB) {
                    echo '<img src="/modules/diary/images/640/' . $image2['id'] . '.' . $image2['ras'] . '" style="width: 500px;" alt=""/></a> ';
                } else {
                    echo '<img src="/modules/diary/images/128/' . $image2['id'] . '.' . $image2['ras'] . '" alt=""/></a> ';
                }
            }
            echo '</div>';
        }

        echo "<div class='list-group-item-null list-group-item-grey'>";
        echo "<small style='color: grey;float: right;'>" . date::times($diary['time']) . "</small>";
        echo user($us['id']);
        echo "<br />";

        if (isset($_GET['edit']) && $_GET['edit'] == 'cat' && isset($user) && $user['level'] > 2 && ($user['id'] == $us['id'] || $user['level'] > $us['level'])) {
            echo "<form method='post' class='list-group-item-null list-group-item-grey' action='/modules/diary/$diary[name]/'>";
            echo "<select name='cat' class='form-control'>";
            $c = $db->query("SELECT * FROM `diary_cat` ORDER BY `name` ASC");
            while ($cats = $db->get_row($c)) {
                echo'<option value="' . $cats['id'] . '"' . ($diary['id_cat'] == $cats['id'] ? ' selected="selected"' : null) . '>' . $cats['name'] . '</option>';
            }
            echo '</select><br/>';

            $doc->Button('btn btn-success btn-sm', 'save', 'save', 'Сохранить');
            $doc->Link('btn btn-secondary btn-sm', "/modules/diary/$diary[name]/", null, 'Отмена');
            echo '</form>';
        } else {
            echo "<i class='fa fa-folder fa-fw'></i> " . lang('Категория') . ": <a href='/modules/diary/index.php?r=$cat[id]'>$cat[name]</a> ";
            if (isset($user) && $user['level'] > 2 && ($user['id'] == $us['id'] || $user['level'] > $us['level'])) {
                echo "<a href='?edit=cat' class='hint--top' data-hint='" . lang('Редактировать категорию') . "'><i class='fa fa-edit fa-fw'></i></a>";
            }
        }
        echo '<br/>';

        if (isset($_GET['edit']) && $_GET['edit'] == 'tags' && isset($user) && ($user['id'] == $us['id'] || $user['level'] > 2 && $user['level'] > $us['level'])) {
            echo "<form method='post' class='list-group-item-null list-group-item-grey' name='message' action='/modules/diary/$diary[name]/'>";

            $doc->Input('tags', 'Метки', 128, "$diary[tags]");
            echo "<br />";
            $doc->Button('btn btn-success btn-sm', 'save', 'save', 'Сохранить');
            $doc->Link('btn btn-secondary btn-sm', "/modules/diary/$diary[name]/", null, 'Отмена');
            echo '</form>';
        } else {
            echo "<i class='fa fa-tags fa-fw'></i> " . lang('Метки') . ": ";
            if ($diary['tags'] != NULL) {
                $tagss = explode(',', $diary['tags']);
                for ($i = 0; $i < count($tagss); $i++) {
                    echo "<a href='/modules/diary/tags.php?tag=$tagss[$i]' class='hint--top' data-hint='Искать метку $tagss[$i]'>$tagss[$i]</a>, ";
                }
            } else {
                echo lang('нет меток');
            }
            if (isset($user) && ($user['id'] == $us['id'] || $user['level'] > 2 && $user['level'] > $us['level'])) {
                echo " <a href='?edit=tags' class='hint--top' data-hint='" . lang('Редактировать метки') . "'><i class='fa fa-edit fa-fw'></i></a>";
            }
        }

        if (isset($user) && ($user['id'] == $us['id'] || $user['level'] > 2 && $user['level'] > $us['level'])) {
            echo "<br /><a href='/modules/diary/images.php?id=$diary[id]'><i class='fa fa-image fa-fw'></i> " . lang('Управление изображениями') . "</a>";
        }
        echo '</div>';

        $q = $db->super_query("SELECT COUNT(*) as count FROM `friends` WHERE (`user` = '$user[id]' AND `friends` = '$us[id]') OR (`user` = '$us[id]' AND `friends` = '$user[id]')");

        if (isset($user) && $us['id'] == $user['id'] || isset($user) && $user['level'] > $us['level'] || ($diary['readers'] == 0 || $diary['readers'] == 1) || isset($user) && $diary['readers'] == 2 && $q['count'] != 0) {
            if (isset($user) && $user['id'] != $us['id'] || !isset($user)) {
                $db->query("UPDATE `diary` SET `viewings`='" . ($diary['viewings'] + 1) . "' WHERE `id`='$diary[id]' LIMIT 1");
            }

            $q = $db->super_query("SELECT COUNT(*) as count FROM `diary_rating` WHERE `id_diary` = '$diary[id]' AND `id_user`='$user[id]' LIMIT 1");

            if (isset($user) && $user['id'] != $us['id'] && $q['count'] == 0) {
                echo '<div class="list-group-item-null list-group-item-info"><center>';
                echo '<a href="/modules/diary/' . $diary['name'] . '/?plus=1" class="btn btn-secondary btn-sm" title="Повысить рейтинг Блога на 1">+1</a> ';
                echo '<a href="/modules/diary/' . $diary['name'] . '/?plus=2" class="btn btn-secondary btn-sm" title="Повысить рейтинг Блога на 2">+2</a> ';
                echo '<a href="/modules/diary/' . $diary['name'] . '/?plus=3" class="btn btn-secondary btn-sm" title="Повысить рейтинг Блога на 3">+3</a> ';
                echo '<a href="/modules/diary/' . $diary['name'] . '/?plus=4" class="btn btn-secondary btn-sm" title="Повысить рейтинг Блога на 4">+4</a> ';
                echo '<a href="/modules/diary/' . $diary['name'] . '/?plus=5" class="btn btn-secondary btn-sm" title="Повысить рейтинг Блога на 5">+5</a>';
                echo '</center></div>';
            }
        } else {
            echo '<div class="list-group-item-null list-group-item-warning">';
            echo '<i class="fa fa-users fa-fw"> <b>' . lang('Блог пользователя могут читать только друзья') . '</b>';
            echo '</div>';
        }

        echo '<div class="list-group-item-null">';
        echo "<i class='fa fa-eye fa-fw'></i> " . lang('Просмотров') . ": $diary[viewings] | ";
        echo "<i class='fa fa-star fa-fw'></i> " . lang('Рейтинг') . ": $diary[rating]<br />";

        if (isset($_GET['edit']) && $_GET['edit'] == 'readers' && isset($user) && ($user['id'] == $us['id'] || $user['level'] > 2 && $user['level'] > $us['level'])) {
            echo '<form method="post" class="list-group-item-null" action="/modules/diary/' . $diary['name'] . '/">';
            echo '<select name="readers" class="form-control">';
            echo '<option value="0"' . ($diary['readers'] == 0 ? ' selected="selected"' : null) . '>' . lang('Читают и комментируют все') . '</option>';
            echo '<option value="1"' . ($diary['readers'] == 1 ? ' selected="selected"' : null) . '>' . lang('Читают все, комментируют друзья') . '</option>';
            echo '<option value="2"' . ($diary['readers'] == 2 ? ' selected="selected"' : null) . '>' . lang('Читают и комментируют друзья') . '</option>';
            echo '</select><br/>';
            $doc->Button('btn btn-success btn-sm', 'save', 'save', 'Сохранить');
            $doc->Link('btn btn-secondary btn-sm', "/modules/diary/$diary[name]/", null, 'Отмена');
            echo '</form>';
        } else {
            echo lang('Читают') . ': ';
            if ($diary['readers'] == 0 || $diary['readers'] == 1) {
                echo '<b>' . lang('Все') . '</b>';
            } else {
                echo '<b>' . lang('Друзья') . '</b>';
            }
            echo' | ';
            echo lang('Комментируют') . ': ';
            if ($diary['readers'] == 0) {
                echo '<b>' . lang('Все') . '</b>';
            } else {
                echo '<b>' . lang('Друзья') . '</b>';
            }
            if (isset($user) && ($user['id'] == $us['id'] || $user['level'] > 2 && $user['level'] > $us['level'])) {
                echo " <a href='?edit=readers' class='hint--top' data-hint='" . lang('Редактировать приватность') . "'><i class='fa fa-edit fa-fw'></i></a>";
            }
            echo'<br/>';
        }
        echo '</div>';

        $q = $db->super_query("SELECT COUNT(*) as count FROM `diary_komm` WHERE `id_diary` = '$diary[id]'");
        $count_komm = $q['count'];

        echo "<a class='list-group-item-null list-group-item-grey' href='/modules/diary/komm.php?id=$diary[id]'><i class='fa fa-comments fa-fw'></i> " . lang('Комментарии') . " <span class='label label-default'>$count_komm</span></a>";
    } else {
        header("Location:index.php");
    }
} else {
    header("Location:index.php");
}
require_once H . 'sys/inc/tfoot.php';
