1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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;
}
}
|