first commit
This commit is contained in:
commit
34e598ac1f
117
LICENSE
Normal file
117
LICENSE
Normal file
@ -0,0 +1,117 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and modification follow.
|
||||
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
one line to give the program's name and an idea of what it does. Copyright (C) yyyy name of author
|
||||
|
||||
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice
|
12
README.md
Normal file
12
README.md
Normal file
@ -0,0 +1,12 @@
|
||||
# deadjournal
|
||||
|
||||
Simple Web 2.0 blog engine
|
||||
|
||||
## How to deploy
|
||||
- Create a database in mysql/mariadb
|
||||
- Create tables using the file `sql/schema.sql`:
|
||||
```
|
||||
mysql -u other_user -p some_empty_database < sql/schema.sql
|
||||
```
|
||||
- Rename `config.example.php` to `config.php`
|
||||
- Specify the DB connection details in the config.php file
|
30
config.example.php
Executable file
30
config.example.php
Executable file
@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
define('DB_HOST', '127.0.0.1');
|
||||
define('DB_NAME', 'deadjournal');
|
||||
define('DB_USER', 'test_user');
|
||||
define('DB_PASS', 'password');
|
||||
|
||||
define('HOME_DIRECTORY', '/blog/'); // e.g. if https://bernd32.xyz/blog, then HOME_DIRECTORY is '/blog/'
|
||||
|
||||
session_name('my_blog_session');
|
||||
session_start();
|
||||
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 1);
|
||||
|
||||
date_default_timezone_set('Europe/Moscow');
|
||||
|
||||
define('HEADER_TEXT', 'Deadjournal');
|
||||
|
||||
define('FOOTER_TEXT', 'Powered by me.');
|
||||
|
||||
define('MAX_POSTS_PER_PAGE', 5);
|
||||
|
||||
// Можно указать как массив строк; подсети тоже в CIDR-формате, например '192.168.0.0/24'
|
||||
$ALLOWED_IPS = [
|
||||
'127.0.0.1',
|
||||
'192.168.1.100',
|
||||
];
|
||||
|
||||
define ('BLOG_TITLE', 'Deadjournal — there is no reason for you to be here');
|
206
controllers/AdminController.php
Executable file
206
controllers/AdminController.php
Executable file
@ -0,0 +1,206 @@
|
||||
<?php
|
||||
|
||||
namespace Controllers;
|
||||
|
||||
use Core\Controller;
|
||||
use Models\PostModel;
|
||||
use Models\TagModel;
|
||||
use function isAdmin;
|
||||
|
||||
class AdminController extends Controller
|
||||
{
|
||||
private $postModel;
|
||||
private $tagModel;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$this->postModel = new PostModel();
|
||||
$this->tagModel = new TagModel();
|
||||
}
|
||||
|
||||
// Control panel index page
|
||||
public function index()
|
||||
{
|
||||
if (!isAdmin()) {
|
||||
header('Location: ' . HOME_DIRECTORY . 'index.php?url=auth/login');
|
||||
exit;
|
||||
}
|
||||
|
||||
$postsPerPage = MAX_POSTS_PER_PAGE;
|
||||
if ($postsPerPage < 1) {
|
||||
$postsPerPage = 5; // fallback
|
||||
}
|
||||
|
||||
// Get the current page
|
||||
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
|
||||
if ($page < 1) {
|
||||
$page = 1;
|
||||
}
|
||||
|
||||
$totalPosts = $this->postModel->countAll();
|
||||
|
||||
$totalPages = ceil($totalPosts / $postsPerPage);
|
||||
if ($totalPages < 1) {
|
||||
$totalPages = 1;
|
||||
}
|
||||
|
||||
$offset = ($page - 1) * $postsPerPage;
|
||||
|
||||
$posts = $this->postModel->getPaginated($offset, $postsPerPage);
|
||||
|
||||
$this->view->render('admin/index.php', [
|
||||
'posts' => $posts,
|
||||
'totalPages' => $totalPages,
|
||||
'currentPage' => $page
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
// Creating new post
|
||||
// controllers/AdminController.php
|
||||
|
||||
public function create()
|
||||
{
|
||||
if (!isAdmin()) {
|
||||
die("Access denied");
|
||||
}
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
$title = $_POST['title'] ?? '';
|
||||
$content = $_POST['content'] ?? '';
|
||||
$tags = $_POST['tags'] ?? '';
|
||||
|
||||
// Date handling
|
||||
$created_at_input = $_POST['created_at'] ?? '';
|
||||
|
||||
// Если админ ничего не ввёл, мы передадим null => модель сама подставит текущую дату
|
||||
// Если ввёл, преобразуем к формату Y-m-d H:i:s
|
||||
$created_at = null;
|
||||
if (!empty($created_at_input)) {
|
||||
$created_at = date('Y-m-d H:i:s', strtotime($created_at_input));
|
||||
}
|
||||
|
||||
// TODO: move allowed tags to the config file
|
||||
$allowed_tags = '<b><i><u><strong><em><p><br><ul><ol><li><blockquote><code><pre><img><a>';
|
||||
$sanitizedContent = strip_tags($content, $allowed_tags);
|
||||
|
||||
// Creating a post
|
||||
$postId = $this->postModel->create($title, $sanitizedContent, $created_at);
|
||||
|
||||
// Handling tags
|
||||
$tagNames = array_map('trim', explode(',', $tags));
|
||||
foreach ($tagNames as $tagName) {
|
||||
if ($tagName !== '') {
|
||||
$tagId = $this->tagModel->createIfNotExists($tagName);
|
||||
$this->tagModel->addTagToPost($postId, $tagId);
|
||||
}
|
||||
}
|
||||
|
||||
header('Location: ' . HOME_DIRECTORY . 'index.php');
|
||||
exit;
|
||||
}
|
||||
|
||||
$this->view->render('admin/create.php', []);
|
||||
}
|
||||
|
||||
// Post editing
|
||||
public function edit($id)
|
||||
{
|
||||
if (!isAdmin()) {
|
||||
die("Access denied");
|
||||
}
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
$title = $_POST['title'] ?? '';
|
||||
$content = $_POST['content'] ?? '';
|
||||
$created_at_input = $_POST['created_at'] ?? '';
|
||||
$tags = $_POST['tags'] ?? '';
|
||||
|
||||
// Преобразуем или оставляем null
|
||||
$created_at = null;
|
||||
if (!empty($created_at_input)) {
|
||||
$created_at = date('Y-m-d H:i:s', strtotime($created_at_input));
|
||||
}
|
||||
|
||||
$contentWithPlaceholder = str_replace('<!--more-->', '[MORE_MARKER]', $content);
|
||||
$allowed_tags = '<b><i><u><strong><em><p><br><ul><ol><li><blockquote><code><pre><img><a>';
|
||||
$sanitizedContent = strip_tags($contentWithPlaceholder, $allowed_tags);
|
||||
$sanitizedContent = str_replace('[MORE_MARKER]', '<!--more-->', $sanitizedContent);
|
||||
|
||||
$this->postModel->update($id, $title, $sanitizedContent, $created_at);
|
||||
|
||||
$this->tagModel->removeAllTagsFromPost($id);
|
||||
|
||||
$tagNames = array_map('trim', explode(',', $tags));
|
||||
foreach ($tagNames as $tagName) {
|
||||
if (!empty($tagName)) {
|
||||
// если тег не пустой
|
||||
$tagId = $this->tagModel->createIfNotExists($tagName);
|
||||
$this->tagModel->addTagToPost($id, $tagId);
|
||||
}
|
||||
}
|
||||
|
||||
header('Location: ' . HOME_DIRECTORY . 'index.php');
|
||||
exit;
|
||||
}
|
||||
|
||||
$post = $this->postModel->getById($id);
|
||||
if (!$post) {
|
||||
die("Пост не найден");
|
||||
}
|
||||
|
||||
$this->view->render('admin/edit.php', ['post' => $post]);
|
||||
}
|
||||
|
||||
// Post deletion
|
||||
public function delete($id)
|
||||
{
|
||||
if (!isAdmin()) {
|
||||
die("Access denied");
|
||||
}
|
||||
|
||||
$this->postModel->delete($id);
|
||||
header('Location: ' . HOME_DIRECTORY . 'index.php?url=admin/index');
|
||||
exit;
|
||||
}
|
||||
|
||||
public function hide($id)
|
||||
{
|
||||
if (!isAdmin()) {
|
||||
die("Access denied");
|
||||
}
|
||||
|
||||
$this->postModel->hide($id);
|
||||
header('Location: ' . HOME_DIRECTORY . 'index.php?url=admin/index');
|
||||
exit;
|
||||
}
|
||||
|
||||
public function restore($id)
|
||||
{
|
||||
if (!isAdmin()) {
|
||||
die("Access denied");
|
||||
}
|
||||
|
||||
$this->postModel->restore($id);
|
||||
header('Location: ' . HOME_DIRECTORY . 'index.php?url=admin/hidden');
|
||||
exit;
|
||||
}
|
||||
|
||||
public function hidden()
|
||||
{
|
||||
if (!isAdmin()) {
|
||||
die("Access denied");
|
||||
}
|
||||
|
||||
// Fetch all hidden posts
|
||||
$posts = $this->postModel->getHidden();
|
||||
|
||||
// Render a special template, or reuse admin/index with a different set of posts
|
||||
$this->view->render('admin/hidden.php', [
|
||||
'posts' => $posts
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
}
|
46
controllers/AuthController.php
Executable file
46
controllers/AuthController.php
Executable file
@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace Controllers;
|
||||
|
||||
use Core\Controller;
|
||||
use Models\UserModel;
|
||||
|
||||
class AuthController extends Controller
|
||||
{
|
||||
private $userModel;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$this->userModel = new UserModel();
|
||||
}
|
||||
|
||||
public function login()
|
||||
{
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
$username = $_POST['username'] ?? '';
|
||||
$password = $_POST['password'] ?? '';
|
||||
|
||||
$user = $this->userModel->getByUsername($username);
|
||||
if ($user && password_verify($password, $user['password_hash'])) {
|
||||
$_SESSION['user_id'] = $user['id'];
|
||||
header('Location: ' . HOME_DIRECTORY . 'index.php?url=admin/index');
|
||||
exit;
|
||||
} else {
|
||||
$error = "Incorrect login or password";
|
||||
$this->view->render('admin/login.php', ['error' => $error]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
$this->view->render('admin/login.php');
|
||||
}
|
||||
|
||||
public function logout()
|
||||
{
|
||||
unset($_SESSION['user_id']);
|
||||
header('Location: ' . HOME_DIRECTORY . 'index.php');
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
105
controllers/PostController.php
Executable file
105
controllers/PostController.php
Executable file
@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace Controllers;
|
||||
|
||||
use Core\Controller;
|
||||
use Models\PostModel;
|
||||
use Models\TagModel;
|
||||
|
||||
class PostController extends Controller
|
||||
{
|
||||
private $postModel;
|
||||
private $tagModel;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
$this->postModel = new PostModel();
|
||||
$this->tagModel = new TagModel();
|
||||
}
|
||||
|
||||
public function index()
|
||||
{
|
||||
$postsPerPage = $postsPerPage = MAX_POSTS_PER_PAGE;
|
||||
if ($postsPerPage < 1) {
|
||||
$postsPerPage = 5; // fallback
|
||||
}
|
||||
|
||||
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
|
||||
if ($page < 1) {
|
||||
$page = 1;
|
||||
}
|
||||
|
||||
$totalPosts = $this->postModel->countAll();
|
||||
$totalPages = ceil($totalPosts / $postsPerPage);
|
||||
if ($totalPages < 1) {
|
||||
$totalPages = 1;
|
||||
}
|
||||
|
||||
$offset = ($page - 1) * $postsPerPage;
|
||||
|
||||
$posts = $this->postModel->getPaginated($offset, $postsPerPage);
|
||||
|
||||
foreach ($posts as &$post) {
|
||||
// getTagsByPostId() returns all tags for this post
|
||||
$post['tags'] = $this->tagModel->getTagsByPostId($post['id']);
|
||||
}
|
||||
|
||||
$this->view->render('post/list.php', [
|
||||
'posts' => $posts,
|
||||
'totalPages' => $totalPages,
|
||||
'currentPage' => $page
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
public function view($id)
|
||||
{
|
||||
// Просмотр конкретного поста
|
||||
$post = $this->postModel->getById($id);
|
||||
|
||||
if (!$post) {
|
||||
die("Пост не найден");
|
||||
}
|
||||
|
||||
$tags = $this->tagModel->getTagsByPostId($id);
|
||||
|
||||
$this->view->render('post/view.php', [
|
||||
'post' => $post,
|
||||
'tags' => $tags
|
||||
]);
|
||||
}
|
||||
|
||||
public function tag($tagName)
|
||||
{
|
||||
// Посты по тегу
|
||||
$posts = $this->tagModel->getPostsByTagName($tagName);
|
||||
|
||||
// Attach each post's tags
|
||||
foreach ($posts as &$post) {
|
||||
$post['tags'] = $this->tagModel->getTagsByPostId($post['id']);
|
||||
}
|
||||
|
||||
// Pass them to the list view
|
||||
$this->view->render('post/list.php', [
|
||||
'posts' => $posts,
|
||||
'tagName' => $tagName
|
||||
]);
|
||||
}
|
||||
|
||||
public function archive($yearMonth)
|
||||
{
|
||||
list($year, $month) = explode('-', $yearMonth);
|
||||
|
||||
$posts = $this->postModel->getByYearMonth($year, $month);
|
||||
|
||||
$monthName = date('F', mktime(0, 0, 0, (int)$month, 1, (int)$year));
|
||||
$archiveLabel = $monthName . ' ' . $year;
|
||||
|
||||
$this->view->render('post/list.php', [
|
||||
'posts' => $posts,
|
||||
'archiveLabel' => $archiveLabel
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
13
core/Controller.php
Executable file
13
core/Controller.php
Executable file
@ -0,0 +1,13 @@
|
||||
<?php
|
||||
namespace Core;
|
||||
|
||||
class Controller
|
||||
{
|
||||
protected $view;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->view = new View();
|
||||
}
|
||||
}
|
||||
|
33
core/Model.php
Executable file
33
core/Model.php
Executable file
@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace Core;
|
||||
|
||||
use PDO;
|
||||
use PDOException;
|
||||
|
||||
abstract class Model
|
||||
{
|
||||
protected $db;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->db = $this->getConnection();
|
||||
}
|
||||
|
||||
private function getConnection()
|
||||
{
|
||||
static $connection = null;
|
||||
|
||||
if ($connection === null) {
|
||||
$dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8';
|
||||
try {
|
||||
$connection = new PDO($dsn, DB_USER, DB_PASS);
|
||||
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
} catch (PDOException $e) {
|
||||
die('DB connection error: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
return $connection;
|
||||
}
|
||||
}
|
||||
|
21
core/View.php
Executable file
21
core/View.php
Executable file
@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace Core;
|
||||
|
||||
class View
|
||||
{
|
||||
public function render($template, $data = [], $layout = 'layout/main.php')
|
||||
{
|
||||
$content = $this->renderPartial($template, $data);
|
||||
include __DIR__ . '/../views/' . $layout;
|
||||
}
|
||||
|
||||
public function renderPartial($template, $data = [])
|
||||
{
|
||||
extract($data);
|
||||
ob_start();
|
||||
include __DIR__ . '/../views/' . $template;
|
||||
return ob_get_clean();
|
||||
}
|
||||
}
|
||||
|
76
core/helpers/functions.php
Executable file
76
core/helpers/functions.php
Executable file
@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
// Simple HTML screening
|
||||
function e($string)
|
||||
{
|
||||
return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
|
||||
}
|
||||
|
||||
function isAdmin()
|
||||
{
|
||||
if (!ipAllowed()) {
|
||||
return false;
|
||||
} else {
|
||||
return isset($_SESSION['user_id']);
|
||||
}
|
||||
}
|
||||
|
||||
function ipAllowed()
|
||||
{
|
||||
// If you declared $ALLOWED_IPS in config.php as global or static,
|
||||
// retrieve them with "global" or by including them from config
|
||||
global $ALLOWED_IPS;
|
||||
|
||||
$clientIp = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
|
||||
|
||||
foreach ($ALLOWED_IPS as $allowed) {
|
||||
if (isIpInRange($clientIp, $allowed)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isIpInRange($ip, $allowed)
|
||||
{
|
||||
// If the allowed is an IP with no slash, compare directly
|
||||
if (strpos($allowed, '/') === false) {
|
||||
return $ip === $allowed;
|
||||
} else {
|
||||
// It's a CIDR notation, e.g. 192.168.1.0/24
|
||||
list($subnet, $mask) = explode('/', $allowed);
|
||||
// Convert IPs to their numeric representation
|
||||
$ipLong = ip2long($ip);
|
||||
$subnetLong = ip2long($subnet);
|
||||
// mask => 24 means 255.255.255.0
|
||||
$mask = (int)$mask;
|
||||
$maskLong = ~((1 << (32 - $mask)) - 1);
|
||||
|
||||
return ($ipLong & $maskLong) === ($subnetLong & $maskLong);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Split content at <!--more--> marker.
|
||||
* Returns [ 'excerpt' => '...', 'hasMore' => bool ]
|
||||
*/
|
||||
function getExcerptWithMore(string $content): array
|
||||
{
|
||||
// Look for the marker
|
||||
$parts = explode('<!--more-->', $content, 2);
|
||||
|
||||
if (count($parts) === 2) {
|
||||
// We have an excerpt in $parts[0], and the remainder in $parts[1]
|
||||
return [
|
||||
'excerpt' => $parts[0],
|
||||
'hasMore' => true,
|
||||
];
|
||||
} else {
|
||||
// No marker found, so the entire post is $content
|
||||
return [
|
||||
'excerpt' => $content,
|
||||
'hasMore' => false,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
66
index.php
Executable file
66
index.php
Executable file
@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
require_once __DIR__ . '/config.php';
|
||||
|
||||
spl_autoload_register(function ($class) {
|
||||
$prefix = 'Core\\';
|
||||
$base_dir = __DIR__ . '/core/';
|
||||
if (strncmp($prefix, $class, strlen($prefix)) === 0) {
|
||||
$relative_class = substr($class, strlen($prefix));
|
||||
$file = $base_dir . $relative_class . '.php';
|
||||
if (file_exists($file)) {
|
||||
require $file;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
$prefix = 'Models\\';
|
||||
$base_dir = __DIR__ . '/models/';
|
||||
if (strncmp($prefix, $class, strlen($prefix)) === 0) {
|
||||
$relative_class = substr($class, strlen($prefix));
|
||||
$file = $base_dir . $relative_class . '.php';
|
||||
if (file_exists($file)) {
|
||||
require $file;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
$prefix = 'Controllers\\';
|
||||
$base_dir = __DIR__ . '/controllers/';
|
||||
if (strncmp($prefix, $class, strlen($prefix)) === 0) {
|
||||
$relative_class = substr($class, strlen($prefix));
|
||||
$file = $base_dir . $relative_class . '.php';
|
||||
if (file_exists($file)) {
|
||||
require $file;
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
require_once __DIR__ . '/core/helpers/functions.php';
|
||||
|
||||
// A simple router
|
||||
$url = $_GET['url'] ?? 'post/index';
|
||||
$urlParts = explode('/', $url);
|
||||
|
||||
$controllerName = ucfirst($urlParts[0]) . 'Controller';
|
||||
$actionName = $urlParts[1] ?? 'index';
|
||||
$param = $urlParts[2] ?? null;
|
||||
|
||||
$controllerClass = 'Controllers\\' . $controllerName;
|
||||
|
||||
if (!class_exists($controllerClass)) {
|
||||
die('Controller not found');
|
||||
}
|
||||
|
||||
$controllerObject = new $controllerClass();
|
||||
|
||||
if (!method_exists($controllerObject, $actionName)) {
|
||||
die('Action not found');
|
||||
}
|
||||
|
||||
if ($param) {
|
||||
$controllerObject->$actionName($param);
|
||||
} else {
|
||||
$controllerObject->$actionName();
|
||||
}
|
31
js/main.js
Normal file
31
js/main.js
Normal file
@ -0,0 +1,31 @@
|
||||
function addTag(tag) {
|
||||
const textarea = document.getElementById('postContent');
|
||||
if (textarea) {
|
||||
switch (tag) {
|
||||
case 'read_more':
|
||||
textarea.value += "\n<!--more-->\n";
|
||||
break;
|
||||
case 'img':
|
||||
textarea.value += "\n<img src=\"\" />\n";
|
||||
break;
|
||||
case 'list':
|
||||
textarea.value += "\n<ul>\n<li></li>\n</ul>\n";
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function wrapSelectedTextWithTag(tag) {
|
||||
const textarea = document.getElementById('postContent');
|
||||
const selectionStart = textarea.selectionStart;
|
||||
const selectionEnd = textarea.selectionEnd;
|
||||
const before = textarea.value.substring(0, selectionStart);
|
||||
const selectedText = textarea.value.substring(selectionStart, selectionEnd);
|
||||
const after = textarea.value.substring(selectionEnd);
|
||||
const newValue = before + `<${tag}>` + selectedText + `</${tag}>` + after;
|
||||
textarea.value = newValue;
|
||||
const newPos = selectionStart + tag.length + 2 + selectedText.length + tag.length + 3;
|
||||
textarea.focus();
|
||||
textarea.setSelectionRange(selectionStart, newPos);
|
||||
}
|
||||
|
163
models/PostModel.php
Executable file
163
models/PostModel.php
Executable file
@ -0,0 +1,163 @@
|
||||
<?php
|
||||
|
||||
namespace Models;
|
||||
|
||||
use Core\Model;
|
||||
use PDO;
|
||||
|
||||
class PostModel extends Model
|
||||
{
|
||||
public function getAll()
|
||||
{
|
||||
$sql = "SELECT * FROM posts
|
||||
WHERE hidden = 0
|
||||
ORDER BY created_at DESC";
|
||||
return $this->db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
|
||||
}
|
||||
|
||||
public function getById($id)
|
||||
{
|
||||
$stmt = $this->db->prepare("SELECT * FROM posts WHERE id = :id LIMIT 1");
|
||||
$stmt->execute(['id' => $id]);
|
||||
return $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
}
|
||||
|
||||
public function create($title, $content, $created_at = null)
|
||||
{
|
||||
if (!$created_at) {
|
||||
$created_at = date('Y-m-d H:i:s');
|
||||
}
|
||||
|
||||
$title = trim($title);
|
||||
$content = trim($content);
|
||||
|
||||
$stmt = $this->db->prepare("
|
||||
INSERT INTO posts (title, content, created_at)
|
||||
VALUES (:title, :content, :created_at)
|
||||
");
|
||||
$stmt->execute([
|
||||
'title' => $title,
|
||||
'content' => $content,
|
||||
'created_at' => $created_at
|
||||
]);
|
||||
return $this->db->lastInsertId();
|
||||
}
|
||||
|
||||
public function update($id, $title, $content, $created_at = null)
|
||||
{
|
||||
$title = trim($title);
|
||||
$content = trim($content);
|
||||
|
||||
if (!$created_at) {
|
||||
$stmt = $this->db->prepare("
|
||||
UPDATE posts
|
||||
SET title = :title, content = :content
|
||||
WHERE id = :id
|
||||
");
|
||||
return $stmt->execute([
|
||||
'id' => $id,
|
||||
'title' => $title,
|
||||
'content' => $content
|
||||
]);
|
||||
} else {
|
||||
// If date was specified
|
||||
$stmt = $this->db->prepare("
|
||||
UPDATE posts
|
||||
SET title = :title, content = :content, created_at = :created_at
|
||||
WHERE id = :id
|
||||
");
|
||||
return $stmt->execute([
|
||||
'id' => $id,
|
||||
'title' => $title,
|
||||
'content' => $content,
|
||||
'created_at' => $created_at
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function delete($id)
|
||||
{
|
||||
$stmt = $this->db->prepare("DELETE FROM posts WHERE id = :id");
|
||||
return $stmt->execute(['id' => $id]);
|
||||
}
|
||||
|
||||
public function hide($id)
|
||||
{
|
||||
$stmt = $this->db->prepare("
|
||||
UPDATE posts
|
||||
SET hidden = 1
|
||||
WHERE id = :id
|
||||
");
|
||||
return $stmt->execute(['id' => $id]);
|
||||
}
|
||||
|
||||
public function getHidden()
|
||||
{
|
||||
$sql = "SELECT * FROM posts
|
||||
WHERE hidden = 1
|
||||
ORDER BY created_at DESC";
|
||||
return $this->db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
|
||||
}
|
||||
|
||||
public function restore($id)
|
||||
{
|
||||
$stmt = $this->db->prepare("
|
||||
UPDATE posts
|
||||
SET hidden = 0
|
||||
WHERE id = :id
|
||||
");
|
||||
return $stmt->execute(['id' => $id]);
|
||||
}
|
||||
|
||||
public function countAll()
|
||||
{
|
||||
$stmt = $this->db->query("SELECT COUNT(*) as cnt FROM posts");
|
||||
return (int) $stmt->fetchColumn();
|
||||
}
|
||||
|
||||
public function getPaginated($offset, $limit)
|
||||
{
|
||||
$stmt = $this->db->prepare("
|
||||
SELECT * FROM posts
|
||||
WHERE hidden = 0
|
||||
ORDER BY created_at DESC
|
||||
LIMIT :offset, :limit
|
||||
");
|
||||
$stmt->bindValue(':offset', (int)$offset, \PDO::PARAM_INT);
|
||||
$stmt->bindValue(':limit', (int)$limit, \PDO::PARAM_INT);
|
||||
$stmt->execute();
|
||||
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
|
||||
}
|
||||
|
||||
public function getMonthlyArchives()
|
||||
{
|
||||
// This will return something like:
|
||||
// [ ['year_month' => '2024-11', 'year' => '2024', 'month' => '11', 'total' => '1'], ... ]
|
||||
$sql = "
|
||||
SELECT
|
||||
YEAR(created_at) AS `year`,
|
||||
MONTH(created_at) AS `month`,
|
||||
DATE_FORMAT(created_at, '%Y-%m') AS `year_month`,
|
||||
COUNT(*) AS `total`
|
||||
FROM posts
|
||||
GROUP BY YEAR(created_at), MONTH(created_at)
|
||||
ORDER BY YEAR(created_at) DESC, MONTH(created_at) DESC
|
||||
";
|
||||
$stmt = $this->db->query($sql);
|
||||
return $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
}
|
||||
|
||||
public function getByYearMonth($year, $month)
|
||||
{
|
||||
$stmt = $this->db->prepare("
|
||||
SELECT *
|
||||
FROM posts
|
||||
WHERE YEAR(created_at) = :year
|
||||
AND MONTH(created_at) = :month
|
||||
ORDER BY created_at DESC
|
||||
");
|
||||
$stmt->execute(['year' => $year, 'month' => $month]);
|
||||
return $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
}
|
||||
|
||||
}
|
84
models/TagModel.php
Executable file
84
models/TagModel.php
Executable file
@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace Models;
|
||||
|
||||
use Core\Model;
|
||||
use PDO;
|
||||
|
||||
class TagModel extends Model
|
||||
{
|
||||
public function createIfNotExists($tagName)
|
||||
{
|
||||
// Check if a tag exists
|
||||
$stmt = $this->db->prepare("SELECT id FROM tags WHERE name = :name LIMIT 1");
|
||||
$stmt->execute(['name' => $tagName]);
|
||||
$tag = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if ($tag) {
|
||||
return $tag['id'];
|
||||
}
|
||||
|
||||
// If not, then create
|
||||
$stmt = $this->db->prepare("INSERT INTO tags (name) VALUES (:name)");
|
||||
$stmt->execute(['name' => $tagName]);
|
||||
return $this->db->lastInsertId();
|
||||
}
|
||||
|
||||
public function addTagToPost($postId, $tagId)
|
||||
{
|
||||
$stmt = $this->db->prepare("INSERT IGNORE INTO post_tags (post_id, tag_id) VALUES (:post_id, :tag_id)");
|
||||
return $stmt->execute([
|
||||
'post_id' => $postId,
|
||||
'tag_id' => $tagId
|
||||
]);
|
||||
}
|
||||
|
||||
public function getTagsByPostId($postId)
|
||||
{
|
||||
$stmt = $this->db->prepare("
|
||||
SELECT t.* FROM tags t
|
||||
JOIN post_tags pt ON t.id = pt.tag_id
|
||||
WHERE pt.post_id = :post_id
|
||||
");
|
||||
$stmt->execute(['post_id' => $postId]);
|
||||
return $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
}
|
||||
|
||||
public function getPostsByTagName($tagName)
|
||||
{
|
||||
$stmt = $this->db->prepare("
|
||||
SELECT p.*
|
||||
FROM posts p
|
||||
JOIN post_tags pt ON p.id = pt.post_id
|
||||
JOIN tags t ON t.id = pt.tag_id
|
||||
WHERE t.name = :tagName
|
||||
ORDER BY p.created_at DESC
|
||||
");
|
||||
$stmt->execute(['tagName' => $tagName]);
|
||||
return $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
}
|
||||
|
||||
public function removeAllTagsFromPost($postId)
|
||||
{
|
||||
$stmt = $this->db->prepare("DELETE FROM post_tags WHERE post_id = :post_id");
|
||||
return $stmt->execute(['post_id' => $postId]);
|
||||
}
|
||||
|
||||
public function getAllTagsWithCounts()
|
||||
{
|
||||
$sql = "
|
||||
SELECT
|
||||
t.id,
|
||||
t.name,
|
||||
COUNT(pt.post_id) AS total
|
||||
FROM tags t
|
||||
LEFT JOIN post_tags pt ON t.id = pt.tag_id
|
||||
GROUP BY t.id, t.name
|
||||
HAVING COUNT(pt.post_id) != 0
|
||||
ORDER BY total DESC;
|
||||
";
|
||||
$stmt = $this->db->query($sql);
|
||||
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
|
||||
}
|
||||
}
|
||||
|
26
models/UserModel.php
Executable file
26
models/UserModel.php
Executable file
@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace Models;
|
||||
|
||||
use Core\Model;
|
||||
use PDO;
|
||||
|
||||
class UserModel extends Model
|
||||
{
|
||||
public function getByUsername($username)
|
||||
{
|
||||
$stmt = $this->db->prepare("SELECT * FROM users WHERE username = :username LIMIT 1");
|
||||
$stmt->execute(['username' => $username]);
|
||||
return $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
}
|
||||
|
||||
public function createUser($username, $password_hash)
|
||||
{
|
||||
$stmt = $this->db->prepare("INSERT INTO users (username, password_hash) VALUES (:username, :pass)");
|
||||
return $stmt->execute([
|
||||
'username' => $username,
|
||||
'pass' => $password_hash
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
35
sql/schema.sql
Executable file
35
sql/schema.sql
Executable file
@ -0,0 +1,35 @@
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
username VARCHAR(255) NOT NULL UNIQUE,
|
||||
password_hash VARCHAR(255) NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS posts (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
title VARCHAR(255) NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tags (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
name VARCHAR(50) NOT NULL UNIQUE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS post_tags (
|
||||
post_id INT NOT NULL,
|
||||
tag_id INT NOT NULL,
|
||||
PRIMARY KEY (post_id, tag_id),
|
||||
FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (tag_id) REFERENCES tags(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
setting_key VARCHAR(255) NOT NULL UNIQUE,
|
||||
setting_value TEXT
|
||||
);
|
||||
|
||||
INSERT IGNORE INTO settings (setting_key, setting_value)
|
||||
VALUES ('posts_per_page', '5'),
|
||||
('max_post_lines', '5');
|
31
views/admin/create.php
Executable file
31
views/admin/create.php
Executable file
@ -0,0 +1,31 @@
|
||||
<h2>Add New Post</h2>
|
||||
<form method="post" action="">
|
||||
<p>
|
||||
<label>Title:</label><br>
|
||||
<input type="text" name="title" required>
|
||||
</p>
|
||||
<p>
|
||||
<label>Content:</label><br>
|
||||
<textarea name="content" id="postContent" rows="10" cols="50"></textarea>
|
||||
<p>
|
||||
<button type="button" onclick="addTag('img')">img</button>
|
||||
<button type="button" onclick="addTag('list')">list</button>
|
||||
<button onclick="wrapSelectedTextWithTag('b')">b</button>
|
||||
<button onclick="wrapSelectedTextWithTag('i')">i</button>
|
||||
<button type="button" onclick="addTag('read_more')">read more</button>
|
||||
</p>
|
||||
</p>
|
||||
<p>
|
||||
<label>Publishing date:</label><br>
|
||||
<input type="datetime-local" name="created_at">
|
||||
</p>
|
||||
<p>
|
||||
<label>Tags (separate with commas):</label><br>
|
||||
<input type="text" name="tags">
|
||||
</p>
|
||||
<p>
|
||||
<button type="submit">Publish</button>
|
||||
</p>
|
||||
</form>
|
||||
|
||||
<script src="js/main.js?v=2"></script>
|
42
views/admin/edit.php
Executable file
42
views/admin/edit.php
Executable file
@ -0,0 +1,42 @@
|
||||
<?php
|
||||
use Models\TagModel;
|
||||
|
||||
// Fetch post's tags
|
||||
$tagModel = new TagModel();
|
||||
$postTags = $tagModel->getTagsByPostId($post['id']);
|
||||
// $postTags is an array, e.g.: [ ['id' => 1, 'name' => 'php'], ... ]
|
||||
|
||||
$tagsString = implode(', ', array_map(fn($t) => $t['name'], $postTags));
|
||||
?>
|
||||
|
||||
<h2>Edit post</h2>
|
||||
<form method="post" action="">
|
||||
<p>
|
||||
<label>Title:</label><br>
|
||||
<input type="text" name="title" value="<?= e($post['title']) ?>" required>
|
||||
</p>
|
||||
<p>
|
||||
<label>Post:</label><br>
|
||||
<textarea name="content" rows="10" cols="50"><?= e($post['content']) ?></textarea>
|
||||
</p>
|
||||
<p>
|
||||
<label>Tags (separated by comma):</label><br>
|
||||
<input type="text" name="tags" value="<?= e($tagsString) ?>">
|
||||
</p>
|
||||
<p>
|
||||
<label>Publishing date:</label><br>
|
||||
<?php
|
||||
$datetime_local_value = '';
|
||||
if (!empty($post['created_at'])) {
|
||||
// Делаем DateTime объект
|
||||
$dt = new DateTime($post['created_at']);
|
||||
// Преобразуем к Y-m-d\TH:i
|
||||
$datetime_local_value = $dt->format('Y-m-d\TH:i');
|
||||
}
|
||||
?>
|
||||
<input type="datetime-local" name="created_at" value="<?= e($datetime_local_value) ?>">
|
||||
</p>
|
||||
<p>
|
||||
<button type="submit">Update</button>
|
||||
</p>
|
||||
</form>
|
31
views/admin/hidden.php
Normal file
31
views/admin/hidden.php
Normal file
@ -0,0 +1,31 @@
|
||||
<h2>Hidden Posts</h2>
|
||||
<p><a href="/your_blog/index.php?url=admin/index">Back to Admin Panel</a></p>
|
||||
|
||||
<?php if (!empty($posts)): ?>
|
||||
<table border="1" cellpadding="5" cellspacing="0">
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Title</th>
|
||||
<th>Date</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
<?php foreach ($posts as $post): ?>
|
||||
<tr>
|
||||
<td><?= e($post['id']) ?></td>
|
||||
<td><?= e($post['title']) ?></td>
|
||||
<td><?= e($post['created_at']) ?></td>
|
||||
<td>
|
||||
<a href="/your_blog/index.php?url=admin/restore/<?= e($post['id']) ?>">
|
||||
Restore
|
||||
</a> |
|
||||
<a href="/your_blog/index.php?url=admin/delete/<?= e($post['id']) ?>"
|
||||
onclick="return confirm('Are you sure? This is permanent.')">
|
||||
Delete
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</table>
|
||||
<?php else: ?>
|
||||
<p>No hidden posts.</p>
|
||||
<?php endif; ?>
|
44
views/admin/index.php
Executable file
44
views/admin/index.php
Executable file
@ -0,0 +1,44 @@
|
||||
<h2>Control Panel</h2>
|
||||
<p><a href="<?= HOME_DIRECTORY ?>index.php?url=admin/create">New Post</a> </p>
|
||||
|
||||
<?php if (!empty($posts)): ?>
|
||||
<table border="1" cellpadding="5" cellspacing="0">
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Title</th>
|
||||
<th>Date</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
<?php foreach ($posts as $post): ?>
|
||||
<tr>
|
||||
<td><?= e($post['id']) ?></td>
|
||||
<td><?= e($post['title']) ?></td>
|
||||
<td><?= e($post['created_at']) ?></td>
|
||||
<td>
|
||||
<a href="<?= HOME_DIRECTORY ?>index.php?url=admin/edit/<?= e($post['id']) ?>">Edit</a> |
|
||||
<a href="<?= HOME_DIRECTORY ?>index.php?url=admin/delete/<?= e($post['id']) ?>"
|
||||
onclick="return confirm('Are you sure?')">
|
||||
Delete
|
||||
</a> |
|
||||
<a href="<?= HOME_DIRECTORY ?>index.php?url=admin/hide/<?= e($post['id']) ?>"> Hide </a>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</table>
|
||||
<?php if ($totalPages > 1): ?>
|
||||
<p>
|
||||
<?php for ($i = 1; $i <= $totalPages; $i++): ?>
|
||||
<?php if ($i == $currentPage): ?>
|
||||
<strong><?= $i ?></strong>
|
||||
<?php else: ?>
|
||||
<a href="?url=admin/index&page=<?= $i ?>"><?= $i ?></a>
|
||||
<?php endif; ?>
|
||||
<?php endfor; ?>
|
||||
</p>
|
||||
<?php endif; ?>
|
||||
<p><a href=?url=admin/hidden>Hidden posts</a></p>
|
||||
|
||||
<?php else: ?>
|
||||
<p>No new posts</p>
|
||||
<?php endif; ?>
|
||||
|
20
views/admin/login.php
Executable file
20
views/admin/login.php
Executable file
@ -0,0 +1,20 @@
|
||||
<h2>Abandon hope, all ye who enter here</h2>
|
||||
|
||||
<?php if (!empty($error)): ?>
|
||||
<p style="color:red;"><?= e($error) ?></p>
|
||||
<?php endif; ?>
|
||||
|
||||
<form method="post" action="">
|
||||
<p>
|
||||
<label>Login:</label><br>
|
||||
<input type="text" name="username" required>
|
||||
</p>
|
||||
<p>
|
||||
<label>Password:</label><br>
|
||||
<input type="password" name="password" required>
|
||||
</p>
|
||||
<p>
|
||||
<button type="submit">Enter</button>
|
||||
</p>
|
||||
</form>
|
||||
|
84
views/layout/main.php
Executable file
84
views/layout/main.php
Executable file
@ -0,0 +1,84 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title><?= BLOG_TITLE ?></title>
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
margin: 0 auto;
|
||||
width: 800px;
|
||||
background-color: #FFFFEE;
|
||||
color: #000;
|
||||
}
|
||||
header, footer {
|
||||
background-color: #EEAA88;
|
||||
padding: 10px;
|
||||
text-align: center;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
nav {
|
||||
margin-bottom: 10px;
|
||||
text-align: center;
|
||||
}
|
||||
.container {
|
||||
display: flex;
|
||||
}
|
||||
.content {
|
||||
flex: 1;
|
||||
}
|
||||
.post {
|
||||
border: 1px solid #ccc;
|
||||
padding: 10px;
|
||||
margin-bottom: 10px;
|
||||
background-color: #F0E0D6;
|
||||
}
|
||||
.post_info {
|
||||
text-align: end;
|
||||
font-style: italic;
|
||||
}
|
||||
.tags {
|
||||
font-size: 0.9em;
|
||||
color: #555;
|
||||
}
|
||||
code {
|
||||
background-color: #f4f4f4;
|
||||
display: block;
|
||||
padding: 5px;
|
||||
margin: 5px 0;
|
||||
font-family: Courier, monospace;
|
||||
}
|
||||
.widget-title {
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<header>
|
||||
<h1><?= HEADER_TEXT ?></h1>
|
||||
</header>
|
||||
|
||||
<nav>
|
||||
<a href="<?= HOME_DIRECTORY ?>index.php">Home</a> |
|
||||
<a href="<?= HOME_DIRECTORY ?>index.php?url=admin/index">Enter</a> |
|
||||
<a href="<?= HOME_DIRECTORY ?>index.php?url=auth/logout">Logout</a>
|
||||
</nav>
|
||||
|
||||
<div class="container">
|
||||
<div class="content">
|
||||
<?= $content ?>
|
||||
</div>
|
||||
<div class="sidebar">
|
||||
<?php
|
||||
echo $this->renderPartial('partials/archiveWidget.php');
|
||||
echo $this->renderPartial('partials/tagWidget.php');
|
||||
?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer>
|
||||
<?= FOOTER_TEXT ?>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
40
views/partials/archiveWidget.php
Executable file
40
views/partials/archiveWidget.php
Executable file
@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
use Models\PostModel;
|
||||
|
||||
// We can instantiate the PostModel here
|
||||
$postModel = new PostModel();
|
||||
$archives = $postModel->getMonthlyArchives();
|
||||
|
||||
// Basic styles or structure:
|
||||
echo '<div class="widget-archives">';
|
||||
echo '<h3 class="widget-title">Archives</h3>';
|
||||
|
||||
if (!empty($archives)) {
|
||||
echo '<ul>';
|
||||
foreach ($archives as $row) {
|
||||
$yearMonth = $row['year_month']; // e.g. "2024-11"
|
||||
$year = $row['year'];
|
||||
// Convert numeric month to a textual representation, e.g., November
|
||||
// Or you can keep it numeric if you prefer
|
||||
$monthNum = (int)$row['month']; // "11" => 11
|
||||
$monthLabel = date('F', mktime(0, 0, 0, $monthNum, 1, $year));
|
||||
$total = $row['total'];
|
||||
|
||||
// Build a link, e.g. /HOME_DIRECTORY/index.php?url=post/archive/2024-11
|
||||
// or /post/archive/2024-11 if you have a custom .htaccess
|
||||
$archiveUrl = HOME_DIRECTORY . 'index.php?url=post/archive/' . htmlspecialchars($yearMonth);
|
||||
|
||||
echo '<li>';
|
||||
echo '<a href="' . $archiveUrl . '">';
|
||||
// "November 2024 (2)"
|
||||
echo $monthLabel . ' ' . $year . ' </a>';
|
||||
echo '(' . $total . ')';
|
||||
echo '</li>';
|
||||
}
|
||||
echo '</ul>';
|
||||
} else {
|
||||
echo '<p>No archives yet.</p>';
|
||||
}
|
||||
|
||||
echo '</div>';
|
32
views/partials/tagWidget.php
Executable file
32
views/partials/tagWidget.php
Executable file
@ -0,0 +1,32 @@
|
||||
<?php
|
||||
use Models\TagModel;
|
||||
|
||||
// Instantiate the model
|
||||
$tagModel = new TagModel();
|
||||
// Get tags + their counts
|
||||
$allTags = $tagModel->getAllTagsWithCounts();
|
||||
|
||||
// Output the widget
|
||||
echo '<div class="widget-tags">';
|
||||
echo '<h3 class="widget-title">Tags</h3>';
|
||||
|
||||
if (!empty($allTags)) {
|
||||
echo '<ul>';
|
||||
foreach ($allTags as $tag) {
|
||||
$name = $tag['name'];
|
||||
$count = $tag['total'];
|
||||
|
||||
// Link to the posts that have this tag
|
||||
$url = HOME_DIRECTORY . 'index.php?url=post/tag/' . htmlspecialchars($name);
|
||||
|
||||
echo '<li>';
|
||||
echo '<a href="' . $url . '">';
|
||||
echo htmlspecialchars($name) . '</a> (' . $count . ')';
|
||||
echo '</li>';
|
||||
}
|
||||
echo '</ul>';
|
||||
} else {
|
||||
echo '<p>No tags found.</p>';
|
||||
}
|
||||
|
||||
echo '</div>';
|
85
views/post/list.php
Executable file
85
views/post/list.php
Executable file
@ -0,0 +1,85 @@
|
||||
|
||||
<?php if (isset($archiveLabel)): ?>
|
||||
<h2>Month: <?= e($archiveLabel) ?></h2>
|
||||
<?php else: ?>
|
||||
<h2>All posts</h2>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if (!empty($posts)): ?>
|
||||
|
||||
<?php foreach ($posts as $post): ?>
|
||||
<div class="post">
|
||||
<p class="post_info"><small><?= e($post['created_at']) ?></small></p>
|
||||
|
||||
<h3>
|
||||
<a href="<?= HOME_DIRECTORY ?>index.php?url=post/view/<?= e($post['id']) ?>">
|
||||
<?= e($post['title']) ?>
|
||||
</a>
|
||||
</h3>
|
||||
<?php if (isAdmin()): ?>
|
||||
<p>
|
||||
<a href="<?= HOME_DIRECTORY ?>index.php?url=admin/edit/<?= e($post['id']) ?>">
|
||||
Edit
|
||||
</a>
|
||||
</p>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php
|
||||
$result = getExcerptWithMore($post['content']);
|
||||
|
||||
?>
|
||||
<div>
|
||||
<?= nl2br($result['excerpt']) ?>
|
||||
</div>
|
||||
|
||||
<?php if (!empty($post['tags'])): ?>
|
||||
<p class="tags">
|
||||
Tags:
|
||||
<?php
|
||||
$separator = '';
|
||||
foreach ($post['tags'] as $tag) {
|
||||
// Print the separator (which is empty for the first tag, then becomes ", ")
|
||||
echo $separator;
|
||||
|
||||
$url = HOME_DIRECTORY . 'index.php?url=post/tag/' . e($tag['name']);
|
||||
$name = e($tag['name']);
|
||||
|
||||
// Output the link for this tag
|
||||
echo '<a href="' . $url . '">' . $name . '</a>';
|
||||
|
||||
// Now that we've printed one tag, change separator to ", "
|
||||
$separator = ', ';
|
||||
}
|
||||
?>
|
||||
</p>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if ($result['hasMore']): ?>
|
||||
<!-- If there's more, show a "Read more" link -->
|
||||
<p>
|
||||
<a href="<?= HOME_DIRECTORY ?>index.php?url=post/view/<?= e($post['id']) ?>">
|
||||
Read more...
|
||||
</a>
|
||||
</p>
|
||||
<?php endif; ?>
|
||||
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
|
||||
<!-- Pagination block -->
|
||||
<?php if (!empty($totalPages) && $totalPages > 1): ?>
|
||||
<p>
|
||||
<?php for ($i = 1; $i <= $totalPages; $i++): ?>
|
||||
<?php if ($i == $currentPage): ?>
|
||||
<strong><?= $i ?></strong>
|
||||
<?php else: ?>
|
||||
<a href="<?= HOME_DIRECTORY ?>index.php?url=post/index&page=<?= $i ?>"><?= $i ?></a>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php endfor; ?>
|
||||
</p>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php else: ?>
|
||||
<p>No posts</p>
|
||||
<?php endif; ?>
|
38
views/post/view.php
Executable file
38
views/post/view.php
Executable file
@ -0,0 +1,38 @@
|
||||
<div class="post">
|
||||
<h2><?= e($post['title']) ?></h2>
|
||||
<p><small>Published: <?= e($post['created_at']) ?></small></p>
|
||||
<div>
|
||||
|
||||
<?= nl2br($post['content']) ?> </div>
|
||||
|
||||
<?php if (!empty($tags)): ?>
|
||||
<p class="tags">
|
||||
Tags:
|
||||
<?php
|
||||
$separator = '';
|
||||
foreach ($tags as $tag) {
|
||||
// Print the separator (which is empty for the first tag, then becomes ", ")
|
||||
echo $separator;
|
||||
|
||||
$url = HOME_DIRECTORY . 'index.php?url=post/tag/' . e($tag['name']);
|
||||
$name = e($tag['name']);
|
||||
|
||||
// Output the link for this tag
|
||||
echo '<a href="' . $url . '">' . $name . '</a>';
|
||||
|
||||
// Now that we've printed one tag, change separator to ", "
|
||||
$separator = ', ';
|
||||
}
|
||||
?>
|
||||
</p>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if (isAdmin()): ?>
|
||||
<p>
|
||||
<a href="<?= HOME_DIRECTORY ?>index.php?url=admin/edit/<?= e($post['id']) ?>">
|
||||
Edit
|
||||
</a>
|
||||
</p>
|
||||
<?php endif; ?>
|
||||
|
||||
</div>
|
Loading…
Reference in New Issue
Block a user