diff options
Diffstat (limited to 'lib/tags.php')
-rw-r--r-- | lib/tags.php | 87 |
1 files changed, 87 insertions, 0 deletions
diff --git a/lib/tags.php b/lib/tags.php new file mode 100644 index 0000000..ecc9e5a --- /dev/null +++ b/lib/tags.php @@ -0,0 +1,87 @@ +<?php + +class Tag extends model implements Stringable { + + const DB_TABLE = 'tags'; + + public int $id; + public string $tag; + public int $postsCount; + public int $visiblePostsCount; + + function getUrl(): string { + return '/'.$this->tag.'/'; + } + + function getPostsCount(bool $is_admin): int { + return $is_admin ? $this->postsCount : $this->visiblePostsCount; + } + + function __toString(): string { + return $this->tag; + } + +} + +class tags { + + static function getAll(bool $include_hidden = false): array { + $db = DB(); + $field = $include_hidden ? 'posts_count' : 'visible_posts_count'; + $q = $db->query("SELECT * FROM tags WHERE $field > 0 ORDER BY $field DESC, tag"); + return array_map('Tag::create_instance', $db->fetchAll($q)); + } + + static function get(string $tag): ?Tag { + $db = DB(); + $q = $db->query("SELECT * FROM tags WHERE tag=?", $tag); + return $db->numRows($q) ? new Tag($db->fetch($q)) : null; + } + + static function recountTagPosts(int $tag_id): void { + $db = DB(); + $count = $db->result($db->query("SELECT COUNT(*) FROM posts_tags WHERE tag_id=?", $tag_id)); + $vis_count = $db->result($db->query("SELECT COUNT(*) FROM posts_tags + LEFT JOIN posts ON posts.id=posts_tags.post_id + WHERE posts_tags.tag_id=? AND posts.visible=1", $tag_id)); + $db->query("UPDATE tags SET posts_count=?, visible_posts_count=? WHERE id=?", + $count, $vis_count, $tag_id); + } + + static function splitString(string $tags): array { + $tags = trim($tags); + if ($tags == '') + return []; + $tags = preg_split('/,\s+/', $tags); + $tags = array_filter($tags, static function($tag) { return trim($tag) != ''; }); + $tags = array_map('trim', $tags); + $tags = array_map('mb_strtolower', $tags); + + return $tags; + } + + static function getTags(array $tags): array { + $found_tags = []; + $map = []; + + $db = DB(); + $q = $db->query("SELECT id, tag FROM tags + WHERE tag IN ('".implode("','", array_map(fn($tag) => $db->escape($tag), $tags))."')"); + + while ($row = $db->fetch($q)) { + $found_tags[] = $row['tag']; + $map[$row['tag']] = (int)$row['id']; + } + + $notfound_tags = array_diff($tags, $found_tags); + if (!empty($notfound_tags)) { + foreach ($notfound_tags as $tag) { + $db->insert('tags', ['tag' => $tag]); + $map[$tag] = $db->insertId(); + } + } + + return $map; + } + +}
\ No newline at end of file |