<?php

/* DCMS Special
 * Дата последнего редактирования 10.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['edit']) && $_GET['edit'] == 'edit' && intval($_GET['id'])) {
    $public = $db->get_array($db->query("SELECT * FROM `public` WHERE `id` = '" . intval($_GET['id']) . "'"));

    $set['title'] = lang('Редактирование') . ' - ' . $public['name'] . '';
    require_once H . 'sys/inc/thead.php';

    if (isset($_POST['edit'])) {
        if (isset($_POST['name']) && preg_match('#^([A-zА-я \-]*)$#ui', $_POST['name'])) {
            $public['name'] = $_POST['name'];
            $db->query("UPDATE `public` SET `name` = '" . $db->safesql($public['name']) . "' WHERE `id` = '$public[id]' LIMIT 1");
        } else {
            $err[] = lang('Ошибка в поле название');
        }

        if (isset($_POST['post']) && utf8_strlen($_POST['post']) <= 10000) {
            $public['post'] = $_POST['post'];
            $db->query("UPDATE `public` SET `post` = '" . $db->safesql($public['post']) . "' WHERE `id` = '$user[id]' LIMIT 1");
        } else {
            $err[] = lang('Ошибка в поле описание');
        }

        if (isset($_POST['p']) && ($_POST['p'] == 1 || $_POST['p'] == 0)) {
            $public['p'] = intval($_POST['p']);
            $db->query("UPDATE `public` SET `p` = '" . $public['p'] . "' WHERE `id` = '" . $public['id'] . "' LIMIT 1");
        }

        if (isset($_POST['a']) && ($_POST['a'] == 1 || $_POST['a'] == 0)) {
            $public['a'] = intval($_POST['a']);
            $db->query("UPDATE `public` SET `a` = '" . $public['a'] . "' WHERE `id` = '" . $public['id'] . "' LIMIT 1");
        }


        if (isset($_POST['v']) && ($_POST['v'] == 1 || $_POST['v'] == 0)) {
            $public['v'] = intval($_POST['v']);
            $db->query("UPDATE `public` SET `v` = '" . $public['v'] . "' WHERE `id` = '" . $public['id'] . "' LIMIT 1");
        }


        if (isset($_POST['f']) && ($_POST['f'] == 1 || $_POST['f'] == 0)) {
            $public['f'] = intval($_POST['f']);
            $db->query("UPDATE `public` SET `f` = '" . $public['f'] . "' WHERE `id` = '" . $public['id'] . "' LIMIT 1");
        }

        if (!isset($err)) {
            msg('Изменения сохранены');
        }
    }

    aut();
    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='/public.php'>" . lang('Сообщества') . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo "<a href='index.php?id=$public[id]'>" . toOutput($public['name']) . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo lang('Управление сообществом');
    echo "</small></div><br />";

    if ($public['id_user'] == $user['id']) {
        echo "<form method='post' action='edit.php?id=" . $public['id'] . "&amp;edit=edit' class='list-group-item-null'>";

        echo lang('Название') . " <small style='color: grey'>(" . lang('можно сменить за 100 монет') . ")</small>:<br />";
        echo "<input class='form-control' type='text' name='name' value='" . toOutput($public['name'], false) . "' maxlength='128' />";

        $doc->Textarea('post', 'Описание', 10000, "" . toOutput($public['post'], false) . "");
        echo "<br />\n";

        echo "<b>" . lang('Настройка привилегий') . "</b><br />";
        echo lang('Выгрузка фотографий') . ":<br />";
        echo "<select class='form-control' name='p'>\n";
        echo "<option value='1'" . ($public['p'] == 1 ? " selected='selected'" : null) . ">" . lang('Только я') . "</option>\n";
        echo "<option value='0'" . ($public['p'] == 0 ? " selected='selected'" : null) . ">" . lang('Я и все подписчики') . "</option>\n";
        echo "</select>\n";

        echo lang('Выгрузка аудиозаписей') . ":<br />";
        echo "<select class='form-control' name='a'>\n";
        echo "<option value='1'" . ($public['a'] == 1 ? " selected='selected'" : null) . ">" . lang('Только я') . "</option>\n";
        echo "<option value='0'" . ($public['a'] == 0 ? " selected='selected'" : null) . ">" . lang('Я и все подписчики') . "</option>\n";
        echo "</select>\n";

        echo lang('Выгрузка видеозаписей') . ":<br />";
        echo "<select class='form-control' name='v'>\n";
        echo "<option value='1'" . ($public['v'] == 1 ? " selected='selected'" : null) . ">" . lang('Только я') . "</option>\n";
        echo "<option value='0'" . ($public['v'] == 0 ? " selected='selected'" : null) . ">" . lang('Я и все подписчики') . "</option>\n";
        echo "</select>\n";

        echo lang('Создавать темы в обсуждениях') . ":<br />";
        echo "<select class='form-control' name='f'>\n";
        echo "<option value='1'" . ($public['f'] == 1 ? " selected='selected'" : null) . ">" . lang('Только я') . "</option>\n";
        echo "<option value='0'" . ($public['f'] == 0 ? " selected='selected'" : null) . ">" . lang('Я и все подписчики') . "</option>\n";
        echo "</select><br />\n";

        $doc->Button('btn btn-success btn-sm', 'edit', 'save', 'Сохранить');
        echo "</form>";
    } else {
        echo "<div class='err'>" . lang('Это не Ваше сообщество') . "</div>";
    }
}

#Редактируем аватар сообщества
if (isset($_GET['foto']) && $_GET['foto'] == 'edit' && intval($_GET['id'])) {
    $public = $db->get_array($db->query("SELECT * FROM `public` WHERE `id` = '" . intval($_GET['id']) . "'"));

    $set['title'] = lang('Изменить аватар') . ' - ' . $public['name'] . '';
    require_once H . 'sys/inc/thead.php';

    if (isset($_FILES['file'])) {


        if (preg_match('#\.jpe?g$#i', $_FILES['file']['name']) && $imgc = @imagecreatefromjpeg($_FILES['file']['tmp_name'])) {
            if (imagesx($imgc) > 300 || imagesy($imgc) > 300) {
                $img_x = imagesx($imgc);
                $img_y = imagesy($imgc);
                if ($img_x == $img_y) {
                    $dstW = 300; // ширина
                    $dstH = 300; // высота 
                } elseif ($img_x > $img_y) {
                    $prop = $img_x / $img_y;
                    $dstW = 300;
                    $dstH = ceil($dstW / $prop);
                } else {
                    $prop = $img_y / $img_x;
                    $dstH = 300;
                    $dstW = ceil($dstH / $prop);
                }

                $screen = imagecreatetruecolor($dstW, $dstH);
                imagecopyresampled($screen, $imgc, 0, 0, 0, 0, $dstW, $dstH, $img_x, $img_y);
                imagedestroy($imgc);
                @chmod(H . "sys/public/ava/" . $public['id'] . ".jpg", 0777);
                @chmod(H . "sys/public/ava/" . $public['id'] . ".gif", 0777);
                @chmod(H . "sys/public/ava/" . $public['id'] . ".png", 0777);
                @unlink(H . "sys/public/ava/" . $public['id'] . ".jpg");
                @unlink(H . "sys/public/ava/" . $public['id'] . ".gif");
                @unlink(H . "sys/public/ava/" . $public['id'] . ".png");
                imagejpeg($screen, H . "sys/public/ava/" . $public['id'] . ".jpg", 100);
                @chmod(H . "sys/public/ava/" . $public['id'] . ".jpg", 0777);
                imagedestroy($screen);
            } else {
                copy($_FILES['file']['tmp_name'], H . "sys/public/ava/" . $public['id'] . ".jpg");
            }
            if (is_file(H . "sys/public/ava/" . $public['id'] . ".jpg")) {
                $db->query("INSERT INTO `public_foto` (`id_public`, `ras`, `foto`) values ('" . $public['id'] . "', 'jpg', '1')");
            } else {
                $db->query("UPDATE `public_foto` SET `foto` = '1' WHERE `id_public` = '" . $public['id'] . "'");
            }

            $_SESSION['message'] = lang('Аватар успешно обновлен');

            header("Location: edit.php?id=$public[id]&foto=edit");
            exit;
        } elseif (preg_match('#\.gif$#i', $_FILES['file']['name']) && $imgc = @imagecreatefromgif($_FILES['file']['tmp_name'])) {
            include_once 'sys/inc/gif_resize.php';
            $screen = gif_resize(fread(fopen($_FILES['file']['tmp_name'], "rb"), filesize($_FILES['file']['tmp_name'])), 110, 110);
            @chmod(H . "sys/public/ava/" . $public['id'] . ".jpg", 0777);
            @chmod(H . "sys/public/ava/" . $public['id'] . ".gif", 0777);
            @chmod(H . "sys/public/ava/" . $public['id'] . ".png", 0777);
            @unlink(H . "sys/public/ava/" . $public['id'] . ".jpg");
            @unlink(H . "sys/public/ava/" . $public['id'] . ".gif");
            @unlink(H . "sys/public/ava/" . $public['id'] . ".png");

            file_put_contents(H . "sys/public/ava/" . $public['id'] . ".gif", $screen);
            @chmod(H . "sys/public/ava/" . $public['id'] . ".gif", 0777);
            if (is_file(H . "sys/public/ava/" . $public['id'] . ".gif")) {
                $db->query("INSERT INTO `public_foto` (`id_public`, `ras`, `foto`) values ('" . $public['id'] . "', 'gif', '1')");
            } else {
                $db->query("UPDATE `public_foto` SET `foto` = '1' WHERE `id_public` = '" . $public['id'] . "'");
            }
            $_SESSION['message'] = lang('Аватар успешно обновлен');

            header("Location: edit.php?id=$public[id]&foto=edit");
            exit;
        } elseif (preg_match('#\.png$#i', $_FILES['file']['name']) && $imgc = @imagecreatefrompng($_FILES['file']['tmp_name'])) {
            if (imagesx($imgc) > 300 || imagesy($imgc) > 300) {
                $img_x = imagesx($imgc);
                $img_y = imagesy($imgc);
                if ($img_x == $img_y) {
                    $dstW = 300; // ширина
                    $dstH = 300; // высота 
                } elseif ($img_x > $img_y) {
                    $prop = $img_x / $img_y;
                    $dstW = 300;
                    $dstH = ceil($dstW / $prop);
                } else {
                    $prop = $img_y / $img_x;
                    $dstH = 300;
                    $dstW = ceil($dstH / $prop);
                }

                $screen = ImageCreate($dstW, $dstH);
                imagecopyresampled($screen, $imgc, 0, 0, 0, 0, $dstW, $dstH, $img_x, $img_y);
                imagedestroy($imgc);


                @chmod(H . "sys/public/ava/" . $public['id'] . ".jpg", 0777);
                @chmod(H . "sys/public/ava/" . $public['id'] . ".gif", 0777);
                @chmod(H . "sys/public/ava/" . $public['id'] . ".png", 0777);
                @unlink(H . "sys/public/ava/" . $public['id'] . ".jpg");
                @unlink(H . "sys/public/ava/" . $public['id'] . ".gif");
                @unlink(H . "sys/public/ava/" . $public['id'] . ".png");
                imagepng($screen, H . "sys/public/ava/" . $public['id'] . ".png");
                @chmod(H . "sys/public/ava/" . $public['id'] . ".png", 0777);
                imagedestroy($screen);
            } else {

                copy($_FILES['file']['tmp_name'], H . "sys/public/ava/" . $public['id'] . ".png");
            }
            if (is_file(H . "sys/public/ava/" . $public['id'] . ".png")) {
                $db->query("INSERT INTO `public_foto` (`id_public`, `ras`, `foto`) values ('" . $public['id'] . "', 'png', '1')");
            } else {
                $db->query("UPDATE `public_foto` SET `foto` = '1' WHERE `id_public` = '" . $public['id'] . "'");
            }
            $_SESSION['message'] = lang('Аватар успешно обновлен');

            header("Location: edit.php?id=$public[id]&foto=edit");
            exit;
        } else {
            $_SESSION['err'] = lang('Ошибка. Повторите попытку');
            header("Location: edit.php?id=$public[id]&foto=edit");
            exit;
        }
    }


    aut();
    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='/public.php'>" . lang('Сообщества') . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo "<a href='index.php?id=$public[id]'>" . toOutput($public['name']) . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo lang('Аватар сообщества');
    echo "</small></div><br />";

    $foto = $db->get_array($db->query("SELECT id,ras FROM `public_foto` WHERE `id_public` = '" . $public['id'] . "' AND `foto` = '1' LIMIT 1"));

    if (is_file(H . "sys/public/ava/" . $public['id'] . "." . $foto['ras'] . "")) {
        echo "<img src='/sys/public/ava/" . $public['id'] . "." . $foto['ras'] . "' width='223'/><br />";
    } else {
        echo "<img src='/sys/public/ava/no_foto.jpg' width='223'/><br />";
    }

    echo "<br /><form method='post' enctype='multipart/form-data' action=''>\n";
    echo lang('Выберите аватар') . "<br />";
    echo "<label class='custom-file'><input name='file' type='file' accept='image/*,image/gif,image/png,image/jpeg' class='custom-file-input'><span class='custom-file-control'></span></label><br /><br />";


    $doc->Button('btn btn-primary btn-sm', null, null, 'Загрузить');

    echo '</form>';
}

#Добавляем фото в сообщество
if (isset($_GET['foto']) && $_GET['foto'] == 'add' && intval($_GET['id'])) {
    $public = $db->get_array($db->query("SELECT * FROM `public` WHERE `id` = '" . intval($_GET['id']) . "'"));
    $no = $db->get_array($db->query("SELECT * FROM `public_coint` WHERE `id_public` = '" . $public['id'] . "' AND `id_user` = '" . $user['id'] . "'"), 0);

    $set['title'] = lang('Добавить фотографии') . ' - ' . $public['name'] . '';
    require_once H . 'sys/inc/thead.php';

    if (isset($user) && $user['id'] == $public['id_user'] && isset($_FILES['file'])) {
        if ($imgc = @imagecreatefromstring(file_get_contents($_FILES['file']['tmp_name']))) {
            $name = esc(stripcslashes(htmlspecialchars($_POST['name'])), 1);

            if ($name == null) {
                $name = esc(stripcslashes(htmlspecialchars(preg_replace('#\.[^\.]*$#i', NULL, $_FILES['file']['name']))));
            }

            $opis = esc(stripcslashes(htmlspecialchars($_POST['opis'])), 1);

            if (!preg_match("#^([A-zА-я0-9\-\_\ ])+$#ui", $name)) {
                $err = lang('В названии присутствуют запрещенные символы');
            }

            if (utf8_strlen($name) > 128) {
                $err = lang('Название слишком длинное');
            }
            $name = $db->safesql($name);

            if (utf8_strlen($opis) > 1024) {
                $err = lang('Описание слишком длинное');
            }
            $opis = $db->safesql($opis);
            $img_x = imagesx($imgc);
            $img_y = imagesy($imgc);

            if ($img_x > $set['max_upload_foto_x'] || $img_y > $set['max_upload_foto_y']) {
                $err = lang('Размер изображения превышает ограничения в') . ' ' . $set['max_upload_foto_x'] . '*' . $set['max_upload_foto_y'];
            }

            if (!isset($err)) {
                $db->query("INSERT INTO `public_foto` (`id_public`, `name`, `ras`, `foto`) values ('" . $public['id'] . "', '$name', 'jpg', '2')");
                $id_foto = $db->insert_id();
                $db->query("INSERT INTO `public_wall` (`id_public`, `link`, `ras`, `name`, `opis`, `id_pub`, `type`, `id_file`, `id_ank`) values('" . $public['id'] . "', '/sys/public/foto/600/$id_foto.jpg', 'jpg', '" . $name . "', '$opis', '" . $public['id'] . "', 'public_foto', '$id_foto', '" . $user['id'] . "')");
                $sss = $db->query("SELECT * FROM `public_coint` WHERE `id_public` = '" . $public['id'] . "' AND `i` = '1'");
                while ($podpiska = $db->get_array($sss)) {
                    $us_pub = $db->get_array($db->query("SELECT * FROM `user` WHERE `id` = '" . $podpiska['id_user'] . "' LIMIT 1"));
                    if ($us_pub['id'] != $public['id_user']) {
                        $db->query("INSERT INTO `public_wall` (`id_wall`, `link`, `ras`, `name`, `id_pub`, `type`, `id_file`) values('" . $us_pub['id'] . "', '/sys/public/foto/600/$id_foto.jpg', 'jpg', '[url=/modules/public/index.php?id=" . $public['id'] . "]" . $public['name'] . "[/url]', '" . $public['id'] . "', 'public_foto', '$id_foto')");
                    }
                }


                if ($img_x > 600 || $img_y > 600) {
                    if ($img_x == $img_y) {
                        $dstW = 600; // ширина
                        $dstH = 600; // высота 
                    } elseif ($img_x > $img_y) {
                        $prop = $img_x / $img_y;
                        $dstW = 600;
                        $dstH = ceil($dstW / $prop);
                    } else {
                        $prop = $img_y / $img_x;
                        $dstH = 600;
                        $dstW = ceil($dstH / $prop);
                    }

                    $screen = imagecreatetruecolor($dstW, $dstH);
                    imagecopyresampled($screen, $imgc, 0, 0, 0, 0, $dstW, $dstH, $img_x, $img_y);

                    $screen = img_copyright($screen); // наложение копирайта
                    imagejpeg($screen, H . "sys/public/foto/600/$id_foto.jpg", 90);
                    imagedestroy($screen);
                    $imgc = img_copyright($imgc); // наложение копирайта
                    imagejpeg($imgc, H . "sys/public/foto/foto/$id_foto.jpg", 90);
                    @chmod(H . "sys/public/foto/foto/$id_foto.jpg", 0777);
                } else {
                    $imgc = img_copyright($imgc); // наложение копирайта

                    imagejpeg($imgc, H . "sys/public/foto/600/$id_foto.jpg", 90);
                    imagejpeg($imgc, H . "sys/public/foto/foto/$id_foto.jpg", 90);
                    @chmod(H . "sys/public/foto/foto/$id_foto.jpg", 0777);
                }

                @chmod(H . "sys/public/foto/600/$id_foto.jpg", 0777);

                imagedestroy($imgc);

                msg("Фотография успешно добавлена");
            }
        } else {
            $err = lang('Выбранный Вами формат изображения не поддерживается');
        }
    }

    aut();
    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='/public.php'>" . lang('Сообщества') . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo "<a href='index.php?id=$public[id]'>" . toOutput($public['name']) . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo lang('Добавить фото');
    echo "</small></div><br />";


    if ($user['id'] == $no['id_user']) {
        if ($public['p'] == 0 || $user['id'] == $public['id_user']) {
            echo "<form enctype='multipart/form-data'' action='' method='post' class='list-group-item-null'>";

            $doc->Input('name', 'Название');
            $doc->Textarea('opis', 'Описание');
            $doc->File('file', 'Изображение');
            $doc->Button('btn btn-primary btn-sm', null, 'upload', 'Выгрузить');
            echo "</form>";
        } else {
            echo "<div class='list-group-item-null list-group-item-warning'>";
            echo lang('Вам запрещено выгружать фотографии');
            echo "</div>";
        }
    }

    $fotki = $db->super_query("SELECT COUNT(*) as count FROM `public_foto` WHERE `id_public` = '" . $public['id'] . "' AND `foto` = '2'");
    $fotki = $fotki['count'];
    echo "<div class='list-group-item-null list-group-item-grey'>";
    echo "<a href='foto.php?id=" . $public['id'] . "'>" . lang('Фотографии') . "</a><span class='count'>$fotki</span>";
    echo "</div>";

    $f = $db->query("SELECT id,ras FROM `public_foto` WHERE `id_public` = '" . $public['id'] . "' AND `foto` = '2'ORDER BY id DESC LIMIT 10");
    echo "<div class='list-group-item-null'>";
    while ($foto = $db->get_array($f)) {
        echo "<img src='/sys/public/foto/600/" . $foto['id'] . ".jpg' width='50' height='50'>";
    }
    echo "</div>";
}

#Редактируем запись
if (isset($_GET['wall']) && $_GET['wall'] == 'edit' && intval($_GET['id']) && intval($_GET['row'])) {
    $public = $db->get_array($db->query("SELECT * FROM `public` WHERE `id` = '" . intval($_GET['id']) . "'"));
    $row = $db->get_array($db->query("SELECT * FROM `public_wall` WHERE `id` = '" . intval($_GET['row']) . "'"));

    $set['title'] = lang('Редактирование') . ' - ' . $row['name'] . '';
    include_once H . 'sys/inc/thead.php';

    if (isset($_POST['edit'])) {
        if (isset($_POST['name']) && preg_match('#^([A-zА-я \-]*)$#ui', $_POST['name'])) {
            $row['name'] = $_POST['name'];
            $db->query("UPDATE `public_wall` SET `name` = '" . $db->safesql($row['name']) . "' WHERE `id` = '" . $row['id'] . "' LIMIT 1");
        }
        if (isset($_POST['opis']) && preg_match('#^([A-zА-я \-]*)$#ui', $_POST['opis'])) {
            $row['opis'] = $_POST['opis'];
            $db->query("UPDATE `public_wall` SET `opis` = '" . $db->safesql($row['opis']) . "' WHERE `id` = '" . $row['id'] . "' LIMIT 1");
        }
        $_SESSION['message'] = lang('Изменения сохранены');
        header("Location: index.php?id=" . $public['id'] . "");
        exit();
    }
    aut();
    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='/public.php'>" . lang('Сообщества') . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo "<a href='index.php?id=$public[id]'>" . toOutput($public['name']) . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo lang('Редактирование');
    echo "</small></div><br />";

    if (isset($user) && $user['id'] == $public['id_user']) {

        echo "<form method='post' action='edit.php?id=" . $public['id'] . "&amp;wall=edit&amp;row=" . $row['id'] . "' class='list-group-item-null'>";
        echo lang('Заголовок') . "<br />";
        echo "<input name='name' maxlength='128' required length='128' type='text' value='" . toOutput($row['name'], false) . "' class='form-control'>";

        if ($row['ras'] == 'jpg') {
            echo "<img src='" . $row['link'] . "' width='300' alt='Скрин...' /><br />\n";
        }
        if ($row['ras'] == 'jpeg') {
            echo "<img src='" . $row['link'] . "' width='300' alt='Скрин...' /><br />\n";
        }
        if ($row['ras'] == 'gif') {
            echo "<img src='" . $row['link'] . "' width='300' alt='Скрин...' /><br />\n";
        }
        if ($row['ras'] == 'png') {
            echo "<img src='" . $row['link'] . "' width='300' alt='Скрин...' /><br />\n";
        }
        if ($row['ras'] == 'mp3') {
            echo "<object type=application/x-shockwave-flash data=/sys/uppod.swf height=35 width=480>
    <param name=wmode VALUE=transparent />
    <param name=allowFullScreen value=true />
    <param name=allowScriptAccess value=always />
    <param name=movie value=/sys/uppod.swf />
    <param name=FlashVars value=way=" . $row['link'] . "&amp;swf=/sys/uppod.swf&amp;w=480&amp;h=35&amp;autoplay=0&amp;q=&amp;st=/sys/audio13.txt&amp;volume=40></object><br />";
        }
        if ($row['ras'] == 'mp4') {
            echo "<object type=application/x-shockwave-flash data=/sys/uppod.swf width=300 height=210>
<param name=bgcolor value=#ffffff />
<param name=allowFullScreen value=true />
<param name=allowScriptAccess value=always />
<param name=wmode value=transparent />
<param name=movie value=/sys/uppod.swf/>
<param name=flashvars value=file=" . $row['link'] . " />
</object>";
        }
        if ($row['ras'] == 'flv') {
            echo "<object type=application/x-shockwave-flash data=/sys/uppod.swf width=300 height=210>
<param name=bgcolor value=#ffffff />
<param name=allowFullScreen value=true />
<param name=allowScriptAccess value=always />
<param name=wmode value=transparent />
<param name=movie value=/sys/uppod.swf/>
<param name=flashvars value=file=" . $row['link'] . " />
</object>";
        }

        echo lang('Описание') . "<br />";
        echo "<textarea name='opis' class='form-control'>" . toOutput($row['opis'], false) . "</textarea><br />";

        $doc->Button('btn btn-primary btn-sm', 'edit', 'save', 'Сохранить');

        echo "</form>";
    } else {
        $msg = "Совершил попытку редактирования записи в сообществе [b]$public[name][/b]";
        $db->query("INSERT INTO `events` (`id_user`, `id_kont`, `msg`, `time`) values('$user[id]', '1', '" . $msg . "', '$time')");

        $_SESSION['message'] = lang('Администрация уведомлена');
        header("Location: index.php?id=$public[id]");
        exit;
    }
}

#Добавляем аудиозаписи
if (isset($_GET['audio']) && $_GET['audio'] == 'add' && intval($_GET['id'])) {
    $public = $db->get_array($db->query("SELECT * FROM `public` WHERE `id` = '" . intval($_GET['id']) . "'"));

    $set['title'] = lang('Добавить аудиозапись') . ' - ' . $public['name'] . '';
    require_once H . 'sys/inc/thead.php';

    if (isset($_POST['ok'])) {
        if (!isset($_FILES['file'])) {
            $err[] = lang('Ошибка при выгрузке файла');
        } elseif (!isset($_FILES['file']['tmp_name']) || filesize($_FILES['file']['tmp_name']) > $upload_max_filesize) {
            $err[] = lang('Размер файла превышает установленные ограничения');
        } else {

            $file = esc(stripcslashes(htmlspecialchars($_FILES['file']['name'])));
            $file = preg_replace('(\#|\?)', NULL, $file);
            $name = preg_replace('#\.[^\.]*$#', NULL, $file); // имя файла без расширения
            $ras = strtolower(preg_replace('#^.*\.#', NULL, $file));
            $type = $_FILES['file']['type'];
            $size = filesize($_FILES['file']['tmp_name']);
            $ras1 = 'mp3';
            $rasss = explode(';', $ras1);
            $ras_ok = false;
            for ($i = 0; $i < count($rasss); $i++) {
                if ($rasss[$i] != NULL && $ras == $rasss[$i]) {
                    $ras_ok = true;
                }
            }

            if (!$ras_ok) {
                $err = lang('Неверное расширение файла');
            }
        }

        if (!isset($err)) {
            $db->query("INSERT INTO `public_audio` (`id_public`, `name`, `ras`) VALUES ('" . $public['id'] . "', '$name', 'mp3' )");
            $id_file = $db->insert_id();
            $db->query("INSERT INTO `public_wall` (`id_public`, `link`, `ras`, `name`, `opis`, `id_ank`, `id_pub`, `type`, `id_file`) values('" . $public['id'] . "', '/sys/public/music/$id_file.mp3', 'mp3', '" . $name . "', 'Новая песня', '" . $user['id'] . "', '" . $public['id'] . "', 'public_audio', '$id_file')");
            $sss = $db->query("SELECT * FROM `public_coint` WHERE `id_public` = '" . $public['id'] . "' AND `i` = '1'");
            while ($podpiska = $db->get_array($sss)) {
                $us_pub = $db->get_array($db->query("SELECT * FROM `user` WHERE `id` = '" . $podpiska['id_user'] . "' LIMIT 1"));
                if ($us_pub['id'] != $public['id']) {
                    $db->query("INSERT INTO `public_wall` (`id_wall`, `link`, `ras`, `name`, `id_pub`, `type`, `id_file`) values('" . $us_pub['id'] . "', '/sys/public/music/$id_file.mp3', 'mp3', '[url=/modules/public/index.php?id=" . $public['id'] . "]" . $public['name'] . "[/url]', '" . $public['id'] . "', 'public_audio', '$id_file')");
                }
            }
            if (!@copy($_FILES['file']['tmp_name'], H . "sys/public/music/$id_file.mp3")) {
                $db->query("DELETE FROM `public_audio` WHERE `id` = '$id_file' LIMIT 1");
                $err[] = lang('Ошибка при выгрузке');
            }
        }

        if (!isset($err)) {
            $_SESSION['message'] = lang('Аудиозапись успешно добавлена');
            chmod(H . "sys/public/music/$id_file.mp3", 0666);
            header("Location: edit.php?id=" . $public['id'] . "&audio=add");
        }
    }

    aut();
    err();
    $no = $db->get_array($db->query("SELECT * FROM `public_coint` WHERE `id_public` = '" . $public['id'] . "' AND `id_user` = '" . $user['id'] . "'"), 0);

    #Навигация
    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='/public.php'>" . lang('Сообщества') . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo "<a href='index.php?id=$public[id]'>" . toOutput($public['name']) . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo "<a href='audio.php?id=$public[id]'>" . lang('Аудиозаписи') . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo lang('Новая аудиозапись');
    echo "</small></div><br />";

    if ($user['id'] == $no['id_user']) {
        if (isset($user) && $user['id'] == $public['id_user'] || $public['a'] == '0') {
            echo "<form class=\"list-group-item-null\" enctype=\"multipart/form-data\" action=\"edit.php?id=" . $public['id'] . "&audio=add\" method=\"post\">";

            $doc->File('file', 'Аудиозапись');
            $doc->Button('btn btn-primary btn-sm', 'ok', 'upload', 'Выгрузить');

            echo "</form>";
        } else {
            echo "<div class='list-group-item-null list-group-item-warning'>";
            echo lang('Вам запрещено добавлять аудиозаписи');
            echo "</div>";
        }
    }

    $q = $db->query("SELECT id,name FROM `public_audio` WHERE `id_public` = '" . $public['id'] . "' ORDER BY id DESC LIMIT 10");
    while ($music = $db->get_array($q)) {
        echo "<div class='list-group-item-null'>";
        echo "<i class='fa fa-music fa-fw'></i> " . toOutput($music['name']);
        echo "</div>";
        echo "<div class='hr'></div>";
    }
}

#Редактируем аудиозапись
if (isset($_GET['audio']) && $_GET['audio'] == 'audio' && intval($_GET['id']) && intval($_GET['row'])) {
    $public = $db->get_array($db->query("SELECT * FROM `public` WHERE `id` = '" . intval($_GET['id']) . "'"));
    $row = $db->get_array($db->query("SELECT * FROM `public_audio` WHERE `id` = '" . intval($_GET['row']) . "'"));

    $set['title'] = lang('Редактирование') . ' - ' . $row['name'] . '';
    require_once H . 'sys/inc/thead.php';

    if (isset($_POST['save'])) {
        if (!preg_match("#^([A-zА-я0-9\-\_\(\)\ ])+$#ui", $_POST['name'])) {
            $err[] = lang('В названии присутствуют запрещенные символы');
        } else {
            $row['name'] = $_POST['name'];
            $db->query("UPDATE `public_audio` SET `name` = '" . $db->safesql($row['name']) . "' WHERE `id` = '" . $row['id'] . "' LIMIT 1");
            $_SESSION['message'] = lang('Изменения сохранены');

            header("Location: edit.php?id=$public[id]&audio=audio&row=$row[id]");
            exit();
        }
    }
    aut();
    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='/public.php'>" . lang('Сообщества') . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo "<a href='index.php?id=$public[id]'>" . toOutput($public['name']) . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo lang('Редактировать аудиозапись');
    echo "</small></div><br />";

    if (isset($user) && $user['id'] == $public['id_user']) {
        echo "<form method='post' class='list-group-item-null' action='edit.php?id=$public[id]&amp;audio=audio&amp;row=$row[id]'>";
        $doc->Input('name', 'Название', 128, "" . toOutput($row['name']) . "");

        echo "<object type=application/x-shockwave-flash data=/sys/uppod.swf height=35 width=480>
    <param name=wmode VALUE=transparent />
    <param name=allowFullScreen value=true />
    <param name=allowScriptAccess value=always />
    <param name=movie value=/sys/uppod.swf />
    <param name=FlashVars value=way=/sys/public/music/" . $row['id'] . ".mp3&amp;swf=/sys/uppod.swf&amp;w=480&amp;h=35&amp;autoplay=0&amp;q=&amp;st=/sys/audio13.txt&amp;volume=40></object><br />";

        $doc->Button('btn btn-success btn-sm', 'save', 'save', 'Сохранить');
        echo "</form>";
    } else {
        echo "<div class='list-group-item-null list-group-item-danger'>";
        echo lang('Ошибка. Данные отправлены администрации');
        echo "</div>";
    }
}

#Редактируем видеозаписи
if (isset($_GET['video']) && $_GET['video'] == 'video' && intval($_GET['id']) && intval($_GET['row'])) {
    $public = $db->get_array($db->query("SELECT * FROM `public` WHERE `id` = '" . intval($_GET['id']) . "'"));
    $row = $db->get_array($db->query("SELECT * FROM `public_video` WHERE `id` = '" . intval($_GET['row']) . "'"));

    $set['title'] = lang('Редактирование') . ' - ' . $row['name'] . '';
    require_once H . 'sys/inc/thead.php';

    if (isset($_POST['edit'])) {
        if (!preg_match("#^([A-zА-я0-9\-\_\(\)\ ])+$#ui", $_POST['name'])) {
            $err[] = lang('В названии присутствуют запрещенные символы');
        } else {
            $row['name'] = $_POST['name'];
            $db->query("UPDATE `public_video` SET `name` = '" . $db->safesql($row['name']) . "' WHERE `id` = '" . $row['id'] . "' LIMIT 1");

            $_SESSION['message'] = lang('Изменения сохранены');
            header("Location: video.php?id=" . $public['id']);
            exit;
        }
    }
    aut();
    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='/public.php'>" . lang('Сообщества') . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo "<a href='index.php?id=$public[id]'>" . toOutput($public['name']) . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo lang('Редактировать видеозапись');
    echo "</small></div><br />";

    if (isset($user) && $user['id'] == $public['id_user']) {

        echo "<form method='post' class='list-group-item-null' action='edit.php?id=" . $public['id'] . "&amp;video=video&amp;row=" . $row['id'] . "'>";
        $doc->Input('name', 'Название', 128, "" . toOutput($row['name'], false) . "");
        echo "<br />";
        $doc->Button('btn btn-success btn-sm', 'edit', 'save', 'Сохранить');
        echo "</form>";
    } else {
        echo "<div class='list-group-item-null list-group-item-danger'>";
        echo lang('Ошибка. Данные отправлены администрации');
        echo "</div>";
    }
}

#Добавляем видеозапись
if (isset($_GET['video']) && $_GET['video'] == 'add' && intval($_GET['id'])) {
    $public = $db->get_array($db->query("SELECT * FROM `public` WHERE `id` = '" . intval($_GET['id']) . "'"));

    $set['title'] = lang('Добавить видеозапись') . ' - ' . $public['name'] . '';
    require_once H . 'sys/inc/thead.php';

    if (isset($_POST['save'])) {
        if (!isset($_FILES['file'])) {
            $err[] = lang('Ошибка при выгрузке файла');
        } elseif (!isset($_FILES['file']['tmp_name']) || filesize($_FILES['file']['tmp_name']) > 50971520) {
            $err[] = lang('Размер файла превышает установленные ограничения');
        } else {
            $file = esc(stripcslashes(htmlspecialchars($_FILES['file']['name'])));
            $file = preg_replace('(\#|\?)', NULL, $file);
            $name = preg_replace('#\.[^\.]*$#', NULL, $file); // имя файла без расширения
            $ras = strtolower(preg_replace('#^.*\.#', NULL, $file));
            $type = $_FILES['file']['type'];
            $size = filesize($_FILES['file']['tmp_name']);
            $rasss = explode(';', 'avi;mp4;3gp;flv');
            $ras_ok = false;
            for ($i = 0; $i < count($rasss); $i++) {
                if ($rasss[$i] != NULL && $ras == $rasss[$i]) {
                    $ras_ok = true;
                }
            }
            if (!$ras_ok) {
                $err = lang('Неверное расширение файла');
            }
        }

        if (!isset($err)) {
            $db->query("INSERT INTO `public_video` (`id_public`, `name`, `ras`, `time`) VALUES ('" . $public['id'] . "', '$name', '$ras', '$time')");
            $id_file = $db->insert_id();
            $db->query("INSERT INTO `public_wall` (`id_public`, `link`, `ras`, `name`, `opis`, `id_pub`, `id_ank`, `type`, `id_file`, `screen`) values('" . $public['id'] . "', '/sys/public/video/$ras/$id_file.$ras', '$ras', '" . $name . "', 'Новое видео', '" . $public['id'] . "', '" . $user['id'] . "', 'public_video', '$id_file', 'sys/public/screen/" . $id_file . ".jpg')");
            $sss = $db->query("SELECT * FROM `public_coint` WHERE `id_public` = '" . $public['id'] . "' AND `i` = '1'");
            while ($podpiska = $db->get_array($sss)) {
                $us_pub = $db->get_array($db->query("SELECT * FROM `user` WHERE `id` = '" . $podpiska['id_user'] . "' LIMIT 1"));
                if ($us_pub['id'] != $public['id']) {
                    $us_pub = $db->get_array($db->query("SELECT * FROM `user` WHERE `id` = '" . $podpiska['id_user'] . "' LIMIT 1"));
                    $db->query("INSERT INTO `public_wall` (`id_wall`, `link`, `ras`, `name`, `id_pub`, `type`, `id_file`) values('" . $us_pub['id'] . "', '/sys/public/video/$ras/$id_file.$ras', '$ras', '[url=/modules/public/index.php?id=" . $public['id'] . "]" . $public['name'] . "[/url]', '" . $public['id'] . "', 'public_video', '$id_file')");
                }
            }
            if (!@copy($_FILES['file']['tmp_name'], H . "sys/public/video/$ras/$id_file.$ras")) {
                $db->query("DELETE FROM `public_video` WHERE `id` = '$id_file' LIMIT 1");
                $err[] = lang('Ошибка при выгрузке');
            }
        }

        $media = @new ffmpeg_movie(H . "sys/public/video/$ras/$id_file.$ras");
        $length = intval($media->getDuration());
        $frame = intval($media->getFrameCount());
        $w = $media->GetFrameWidth();
        $h = $media->GetFrameHeight();
        $ff_frame = $media->getFrame(intval($frame / 2));
        if ($ff_frame) {
            $gd_image = $ff_frame->toGDImage();
            if ($gd_image) {
                $des_img = imagecreatetruecolor(130, 98);
                $s_img = $gd_image;
                imagecopyresampled($des_img, $s_img, 0, 0, 0, 0, 130, 98, $w, $h);
                imagejpeg($des_img, H . "sys/public/screen/$id_file.jpg");
                chmod(H . "sys/public/screen/$id_file.jpg", 0777);
                imagedestroy($des_img);
                imagedestroy($s_img);
            }
        }

        chmod(H . "sys/public/video/$ras/$id_file.$ras", 0777);
        $_SESSION['message'] = lang('Видеозапись успешно добавлена');

        header("Location: edit.php?id=" . $public['id'] . "&video=add");
        exit;
    }
    aut();
    err();

    $no = $db->get_array($db->query("SELECT * FROM `public_coint` WHERE `id_public` = '" . $public['id'] . "' AND `id_user` = '" . $user['id'] . "'"), 0);

    #Навигация
    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='/public.php'>" . lang('Сообщества') . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo "<a href='index.php?id=$public[id]'>" . toOutput($public['name']) . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo "<a href='video.php?id=$public[id]'>" . lang('Видеозаписи') . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo lang('Новая видеозапись');
    echo "</small></div><br />";

    if ($user['id'] == $no['id_user']) {
        if (isset($user) && $user['id'] == $public['id_user'] || $public['v'] == '0') {

            echo "<form class=\"list-group-item-null\" enctype=\"multipart/form-data\" action='edit.php?id=" . $public['id'] . "&amp;video=add' method=\"post\">\n";
            $doc->File('file', 'Видеозапись', 'video/*');
            $doc->Button('btn btn-primary btn-sm', 'save', 'upload', 'Загрузить');
            echo "</form>";
        } else {
            echo "<div class='list-group-item-null list-group-item-warning'>";
            echo lang('Вам запрещено добавлять видеозаписи');
            echo "</div>";
        }
    }

    $v = $db->query("SELECT * FROM `public_video` WHERE `id_public` = '" . $public['id'] . "' ORDER BY id DESC LIMIT 10");
    while ($video = $db->get_array($v)) {

        echo "<div class='list-group-item-null'>";
        echo "<i class='fa fa-youtube-play fa-fw'></i> " . toOutput($video['name']);
        echo "</div>";
        echo "<div class='hr'></div>";
    }
}

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