summaryrefslogtreecommitdiff
path: root/model/Post.php
blob: 6f3f1abacac3e154fe94670994f50aa4140493ee (plain)
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
<?php

class Post extends Model {

    const DB_TABLE = 'posts';

    public int $id;
    public string $title;
    public string $md;
    public string $html;
    public string $tocHtml;
    public string $text;
    public int $ts;
    public int $updateTs;
    public bool $visible;
    public bool $toc;
    public string $shortName;

    public function edit(array $data) {
        $cur_ts = time();
        if (!$this->visible && $data['visible'])
            $data['ts'] = $cur_ts;

        $data['update_ts'] = $cur_ts;

        if ($data['md'] != $this->md) {
            $data['html'] = markup::markdownToHtml($data['md']);
            $data['text'] = markup::htmlToText($data['html']);
        }

        if ((isset($data['toc']) && $data['toc']) || $this->toc) {
            $data['toc_html'] = markup::toc($data['md']);
        }

        parent::edit($data);
        $this->updateImagePreviews();
    }

    public function updateHtml() {
        $html = markup::markdownToHtml($this->md);
        $this->html = $html;

        getDb()->query("UPDATE posts SET html=? WHERE id=?", $html, $this->id);
    }

    public function updateText() {
        $html = markup::markdownToHtml($this->md);
        $text = markup::htmlToText($html);
        $this->text = $text;

        getDb()->query("UPDATE posts SET text=? WHERE id=?", $text, $this->id);
    }

    public function getDescriptionPreview(int $len): string {
        if (mb_strlen($this->text) >= $len)
            return mb_substr($this->text, 0, $len-3).'...';
        return $this->text;
    }

    public function getFirstImage(): ?Upload {
        if (!preg_match('/\{image:([\w]{8})/', $this->md, $match))
            return null;
        return uploads::getByRandomId($match[1]);
    }

    public function getUrl(): string {
        return $this->shortName != '' ? "/{$this->shortName}/" : "/{$this->id}/";
    }

    public function getDate(): string {
        return date('j M', $this->ts);
    }

    public function getYear(): int {
        return (int)date('Y', $this->ts);
    }

    public function getFullDate(): string {
        return date('j F Y', $this->ts);
    }

    public function getUpdateDate(): string {
        return date('j M', $this->updateTs);
    }

    public function getFullUpdateDate(): string {
        return date('j F Y', $this->updateTs);
    }

    public function getHtml(bool $is_retina, string $theme): string {
        $html = $this->html;
        $html = markup::htmlImagesFix($html, $is_retina, $theme);
        return $html;
    }

    public function getToc(): ?string {
        return $this->toc ? $this->tocHtml : null;
    }

    public function isUpdated(): bool {
        return $this->updateTs && $this->updateTs != $this->ts;
    }

    /**
     * @return Tag[]
     */
    public function getTags(): array {
        $db = getDb();
        $q = $db->query("SELECT tags.* FROM posts_tags
            LEFT JOIN tags ON tags.id=posts_tags.tag_id
            WHERE posts_tags.post_id=?
            ORDER BY posts_tags.tag_id", $this->id);
        return array_map('Tag::create_instance', $db->fetchAll($q));
    }

    /**
     * @return int[]
     */
    public function getTagIds(): array {
        $ids = [];
        $db = getDb();
        $q = $db->query("SELECT tag_id FROM posts_tags WHERE post_id=? ORDER BY tag_id", $this->id);
        while ($row = $db->fetch($q)) {
            $ids[] = (int)$row['tag_id'];
        }
        return $ids;
    }

    public function setTagIds(array $new_tag_ids) {
        $cur_tag_ids = $this->getTagIds();
        $add_tag_ids = array_diff($new_tag_ids, $cur_tag_ids);
        $rm_tag_ids = array_diff($cur_tag_ids, $new_tag_ids);

        $db = getDb();
        if (!empty($add_tag_ids)) {
            $rows = [];
            foreach ($add_tag_ids as $id)
                $rows[] = ['post_id' => $this->id, 'tag_id' => $id];
            $db->multipleInsert('posts_tags', $rows);
        }

        if (!empty($rm_tag_ids))
            $db->query("DELETE FROM posts_tags WHERE post_id=? AND tag_id IN(".implode(',', $rm_tag_ids).")", $this->id);

        $upd_tag_ids = array_merge($new_tag_ids, $rm_tag_ids);
        $upd_tag_ids = array_unique($upd_tag_ids);
        foreach ($upd_tag_ids as $id)
            posts::recountPostsWithTag($id);
    }

    /**
     * @param bool $update Whether to overwrite preview if already exists
     * @return int
     */
    public function updateImagePreviews(bool $update = false): int {
        $images = [];
        if (!preg_match_all('/\{image:([\w]{8}),(.*?)}/', $this->md, $matches))
            return 0;

        for ($i = 0; $i < count($matches[0]); $i++) {
            $id = $matches[1][$i];
            $w = $h = null;
            $opts = explode(',', $matches[2][$i]);
            foreach ($opts as $opt) {
                if (strpos($opt, '=') !== false) {
                    list($k, $v) = explode('=', $opt);
                    if ($k == 'w')
                        $w = (int)$v;
                    else if ($k == 'h')
                        $h = (int)$v;
                }
            }
            $images[$id][] = [$w, $h];
        }

        if (empty($images))
            return 0;

        $images_affected = 0;
        $uploads = uploads::getUploadsByRandomId(array_keys($images), true);
        foreach ($uploads as $u) {
            foreach ($images[$u->randomId] as $s) {
                list($w, $h) = $s;
                list($w, $h) = $u->getImagePreviewSize($w, $h);
                if ($u->createImagePreview($w, $h, $update, $u->imageMayHaveAlphaChannel()))
                    $images_affected++;
            }
        }

        return $images_affected;
    }

}