diff --git a/config.dist.php b/config.dist.php index e29c7a3..b4be3ae 100644 --- a/config.dist.php +++ b/config.dist.php @@ -11,6 +11,7 @@ return [ */ "general" => [ "language" => "en", + "timezone" => "UTC", "assets_url" => "/plugi-core/dist", "uploads_url" => "/uploads", ], diff --git a/extensions/plugi-ext-blog/README.md b/extensions/plugi-ext-blog/README.md index 47a9438..1b4d4b2 100644 --- a/extensions/plugi-ext-blog/README.md +++ b/extensions/plugi-ext-blog/README.md @@ -8,9 +8,11 @@ The blog extension provides Website Manager post and category management plus tw 2. Open Website Manager and apply the pending database definition update. Existing installations need this update to create or update the extension-owned post and category tables, including the optional featured-image field. 3. Add categories if useful, then create posts as drafts or publish them from the Blog section. +Set `general.timezone` in the root `config.php` to the site's IANA timezone (for example, `Europe/Berlin`); it defaults to `UTC` and controls blog publication input and display. Publication dates are stored as site-local `DATETIME` values, so existing installations should configure the timezone that matches their existing post dates. + ## Create the public pages -1. Create a regular Plugi page with the route `/blog` and add the **Published Posts** block. It lists published posts newest first; drafts are never shown. +1. Create a regular Plugi page with the route `/blog` and add the **Published Posts** block. It lists published posts newest first; drafts are never shown. Public search matches titles, slugs, and excerpts (at least three characters), not full post bodies. 2. Create another regular page with the route `/blog/{slug}` and add the **Blog Post** block. The core router supplies the named `slug` parameter to the block. 3. Apply the site’s normal page layout and theme to both pages. Their presentation remains controlled by the page builder and theme. diff --git a/extensions/plugi-ext-blog/admin/Classes/PostsRepository.php b/extensions/plugi-ext-blog/admin/Classes/PostsRepository.php index a600ae5..bc64e15 100644 --- a/extensions/plugi-ext-blog/admin/Classes/PostsRepository.php +++ b/extensions/plugi-ext-blog/admin/Classes/PostsRepository.php @@ -3,12 +3,14 @@ namespace Plugi\Extensions\Blog; use DateTimeImmutable; +use DateTimeZone; use InvalidArgumentException; use Plugi\Repositories\BaseRepository; class PostsRepository extends BaseRepository { public const POSTS_PER_PAGE = 10; + public const MIN_PUBLIC_SEARCH_LENGTH = 3; protected $table = 'ext__blog_posts'; @@ -32,17 +34,6 @@ class PostsRepository extends BaseRepository return $this->db->select("SELECT * FROM {$this->table} ORDER BY updated_at DESC, id DESC", []); } - public function getPublishedForListing(): array - { - $categoriesTable = $_ENV['DATABASE_PREFIX'] . 'ext__blog_categories'; - $uploadsTable = $_ENV['DATABASE_PREFIX'] . 'uploads'; - $posts = $this->db->select( - "SELECT posts.*, categories.name AS category_name, featured_image.public_id AS featured_image_public_id, featured_image.original_file AS featured_image_original_file, featured_image.alt_text AS featured_image_alt_text FROM {$this->table} posts LEFT JOIN {$categoriesTable} categories ON categories.id = posts.category_id LEFT JOIN {$uploadsTable} featured_image ON featured_image.public_id = posts.featured_image_id AND LOWER(featured_image.mime_type) LIKE 'image/%' WHERE posts.status = ? ORDER BY posts.published_at DESC, posts.id DESC", - ['published'] - ); - return array_map(fn(array $post): array => $this->resolveFeaturedImage($post), $posts); - } - public function getPageForAdmin(string $search, int $page): array { return $this->getPostPage($search, $page, false); @@ -55,6 +46,11 @@ class PostsRepository extends BaseRepository private function getPostPage(string $search, int $page, bool $publishedOnly): array { + $search = trim($search); + if ($publishedOnly && $search !== '' && mb_strlen($search) < self::MIN_PUBLIC_SEARCH_LENGTH) { + return ['posts' => [], 'total' => 0]; + } + $categoriesTable = $_ENV['DATABASE_PREFIX'] . 'ext__blog_categories'; $uploadsTable = $_ENV['DATABASE_PREFIX'] . 'uploads'; $from = $publishedOnly @@ -68,9 +64,14 @@ class PostsRepository extends BaseRepository $parameters[] = 'published'; } if (trim($search) !== '') { - $filters[] = '(posts.title LIKE ? ESCAPE \'!\' OR posts.slug LIKE ? ESCAPE \'!\' OR posts.excerpt LIKE ? ESCAPE \'!\' OR posts.body LIKE ? ESCAPE \'!\')'; + $filters[] = $publishedOnly + ? '(posts.title LIKE ? ESCAPE \'!\' OR posts.slug LIKE ? ESCAPE \'!\' OR posts.excerpt LIKE ? ESCAPE \'!\')' + : '(posts.title LIKE ? ESCAPE \'!\' OR posts.slug LIKE ? ESCAPE \'!\' OR posts.excerpt LIKE ? ESCAPE \'!\' OR posts.body LIKE ? ESCAPE \'!\')'; $pattern = '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], trim($search)) . '%'; - array_push($parameters, $pattern, $pattern, $pattern, $pattern); + array_push($parameters, $pattern, $pattern, $pattern); + if (!$publishedOnly) { + $parameters[] = $pattern; + } } $where = $filters === [] ? '' : ' WHERE ' . implode(' AND ', $filters); @@ -194,8 +195,9 @@ class PostsRepository extends BaseRepository private function validatedPublicationDate(mixed $value, string $status): ?string { + $timezone = new DateTimeZone((string) (phpb_config('general.timezone') ?: 'UTC')); if ($value === null || $value === '') { - return $status === 'published' ? date('Y-m-d H:i:s') : null; + return $status === 'published' ? (new DateTimeImmutable('now', $timezone))->format('Y-m-d H:i:s') : null; } if (!is_string($value)) { throw new InvalidArgumentException('Enter a valid publication date.'); @@ -203,12 +205,12 @@ class PostsRepository extends BaseRepository $value = trim($value); $format = str_contains($value, 'T') ? 'Y-m-d\\TH:i' : 'Y-m-d H:i:s'; - $date = DateTimeImmutable::createFromFormat('!' . $format, $value); + $date = DateTimeImmutable::createFromFormat('!' . $format, $value, $timezone); $errors = DateTimeImmutable::getLastErrors(); if ($date === false || ($errors !== false && ($errors['warning_count'] > 0 || $errors['error_count'] > 0)) || $date->format($format) !== $value) { throw new InvalidArgumentException('Enter a valid publication date.'); } - if ($date > new DateTimeImmutable()) { + if ($date > new DateTimeImmutable('now', $timezone)) { throw new InvalidArgumentException('Publication dates cannot be in the future.'); } diff --git a/extensions/plugi-ext-blog/admin/Views/EditPost.php b/extensions/plugi-ext-blog/admin/Views/EditPost.php index 65d033b..5d5ac41 100644 --- a/extensions/plugi-ext-blog/admin/Views/EditPost.php +++ b/extensions/plugi-ext-blog/admin/Views/EditPost.php @@ -5,6 +5,7 @@ use Plugi\Extensions\Blog\PostsRepository; use Plugi\Repositories\UploadRepository; $postsRepository = new PostsRepository(); +$timezone = new \DateTimeZone((string) (phpb_config('general.timezone') ?: 'UTC')); $post = [ 'title' => '', 'slug' => '', @@ -19,7 +20,7 @@ if (isset($_GET['id']) && ctype_digit((string) $_GET['id'])) { $post = $postsRepository->findWithId($_GET['id']) ?? $post; } $isEditing = isset($post['id']); -$publishedAt = $post['published_at'] ? date('Y-m-d\TH:i', strtotime($post['published_at'])) : ''; +$publishedAt = $post['published_at'] ? (new \DateTimeImmutable($post['published_at'], $timezone))->format('Y-m-d\TH:i') : ''; $categories = (new CategoriesRepository())->getAllForAdmin(); $imageUploads = array_values(array_filter((new UploadRepository())->getAll(), static fn($file): bool => is_string($file->mime_type ?? null) && str_starts_with(strtolower($file->mime_type), 'image/'))); ?> @@ -147,7 +148,7 @@ $imageUploads = array_values(array_filter((new UploadRepository())->getAll(), st
-

Leave blank to use the current time when publishing. Future dates are not supported.

+

Times use the site timezone (getName()) ?>). Leave blank to use the current time when publishing. Future dates are not supported.

diff --git a/extensions/plugi-ext-blog/admin/Views/ListPosts.php b/extensions/plugi-ext-blog/admin/Views/ListPosts.php index 8eb12dc..fac6beb 100644 --- a/extensions/plugi-ext-blog/admin/Views/ListPosts.php +++ b/extensions/plugi-ext-blog/admin/Views/ListPosts.php @@ -73,7 +73,7 @@ foreach ($categories as $category) { Title Category Status - Published + Published (site time) Actions diff --git a/extensions/plugi-ext-blog/blocks/post-detail/view.php b/extensions/plugi-ext-blog/blocks/post-detail/view.php index 50c365f..450e771 100644 --- a/extensions/plugi-ext-blog/blocks/post-detail/view.php +++ b/extensions/plugi-ext-blog/blocks/post-detail/view.php @@ -1,6 +1,7 @@ findPublishedBySlug($slug) : null; @@ -20,9 +21,9 @@ $post = is_string($slug) && $slug !== '' - - - + + + diff --git a/extensions/plugi-ext-blog/blocks/post-list/view.php b/extensions/plugi-ext-blog/blocks/post-list/view.php index de8a85c..7498be4 100644 --- a/extensions/plugi-ext-blog/blocks/post-list/view.php +++ b/extensions/plugi-ext-blog/blocks/post-list/view.php @@ -1,12 +1,14 @@ ['min_range' => 1]]) : false; $page = $page === false ? 1 : $page; $listingPath = isset($_SERVER['SERVER_NAME'], $_SERVER['REQUEST_URI']) ? phpb_full_url(phpb_current_relative_url(true)) : '/'; $pageResult = $postsRepository->getPageForListing($search, $page); +$searchTooShort = $search !== '' && mb_strlen($search) < \Plugi\Extensions\Blog\PostsRepository::MIN_PUBLIC_SEARCH_LENGTH; $totalPages = max(1, (int) ceil($pageResult['total'] / \Plugi\Extensions\Blog\PostsRepository::POSTS_PER_PAGE)); if ($page > $totalPages) { $page = $totalPages; @@ -17,13 +19,15 @@ $searchParameters = $search === '' ? [] : ['q' => $search];
- + +
Enter at least characters to search.
+
@@ -43,9 +47,9 @@ $searchParameters = $search === '' ? [] : ['q' => $search]; - - - + + + diff --git a/extensions/plugi-ext-blog/tests/BlogRepositoriesTest.php b/extensions/plugi-ext-blog/tests/BlogRepositoriesTest.php index b708f68..ee8efde 100644 --- a/extensions/plugi-ext-blog/tests/BlogRepositoriesTest.php +++ b/extensions/plugi-ext-blog/tests/BlogRepositoriesTest.php @@ -141,6 +141,9 @@ function renderBlogEditor(int $postId): string } $_ENV['DATABASE_PREFIX'] = 'test_'; +$siteTimezone = 'Pacific/Kiritimati'; +date_default_timezone_set('Pacific/Pago_Pago'); +$phpb_config = ['website_manager' => ['url' => '/website-manager'], 'general' => ['uploads_url' => '/uploads', 'timezone' => $siteTimezone]]; $phpb_db = new BlogTestDatabase(); $phpb_db->createSchema(); assertBlog(isset($phpb_db->getDBDefinition()['ext__blog_posts'], $phpb_db->getDBDefinition()['ext__blog_categories']), 'The blog tables should be included in the core database definition.'); @@ -183,6 +186,8 @@ $post = $posts->create([ ]); assertBlog(is_array($post) && $post['status'] === 'published', 'A valid published post should be created.'); assertBlog($post['published_at'] !== null, 'Publishing without a date should set the current publication timestamp.'); +$storedPublication = \DateTimeImmutable::createFromFormat('!Y-m-d H:i:s', $post['published_at'], new \DateTimeZone($siteTimezone)); +assertBlog($storedPublication !== false && abs($storedPublication->getTimestamp() - time()) < 60, 'The automatic publication timestamp should use the configured site timezone.'); assertBlog($post['featured_image_id'] === 'blog-cover-1', 'A valid image upload reference should be persisted on the post.'); expectBlogValidation(fn() => $posts->create([ 'title' => 'Missing featured image', 'slug' => 'missing-featured-image', 'excerpt' => '', 'body' => 'Body', 'featured_image_id' => 'missing-upload', 'category_id' => '', 'status' => 'draft', 'published_at' => '', @@ -200,7 +205,7 @@ $olderPost = $posts->create([ 'status' => 'published', 'published_at' => '2020-01-01T00:00', ]); -$pastPublication = date('Y-m-d\\TH:i', time() - 3600); +$pastPublication = (new \DateTimeImmutable('now', new \DateTimeZone($siteTimezone)))->modify('-1 hour')->format('Y-m-d\\TH:i'); $datedPost = $posts->create([ 'title' => 'Dated draft', 'slug' => 'dated-draft', @@ -220,13 +225,9 @@ $secondPost = $posts->create([ 'published_at' => '', ]); $_ENV['BASE_URL'] = 'https://blog.example'; -$phpb_config = ['website_manager' => ['url' => '/website-manager'], 'general' => ['uploads_url' => '/uploads']]; -$publishedPosts = $posts->getPublishedForListing(); -assertBlog(count($publishedPosts) === 2, 'The public listing should exclude drafts.'); -assertBlog($publishedPosts[0]['slug'] === $post['slug'] && $publishedPosts[0]['category_name'] === 'News', 'Published posts should be newest first and include their category name.'); -assertBlog($publishedPosts[1]['slug'] === $olderPost['slug'], 'Older published posts should follow newer posts.'); $editorHtml = renderBlogEditor((int) $post['id']); +assertBlog(str_contains($editorHtml, 'site timezone (Pacific/Kiritimati)'), 'The editor should identify the timezone used for publication dates.'); assertBlog(str_contains($editorHtml, '