aboutsummaryrefslogtreecommitdiff
path: root/lib/pages.php
blob: 8524cf35fad0418cfeab489f845fc839ac6ada37 (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
<?php

class Page extends model {

    const DB_TABLE = 'pages';
    const DB_KEY = 'short_name';

    public string $title;
    public string $md;
    public string $html;
    public int $ts;
    public int $updateTs;
    public bool $visible;
    public string $shortName;

    function edit(array $fields) {
        $fields['update_ts'] = time();
        if ($fields['md'] != $this->md)
            $fields['html'] = markup::markdownToHtml($fields['md']);
        parent::edit($fields);
    }

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

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

    function getUrl(): string {
        return "/{$this->shortName}/";
    }

    function updateHtml(): void {
        $html = markup::markdownToHtml($this->md);
        $this->html = $html;
        DB()->query("UPDATE pages SET html=? WHERE short_name=?", $html, $this->shortName);
    }

}

class pages {

    static function add(array $data): ?int {
        $db = DB();
        $data['ts'] = time();
        $data['html'] = markup::markdownToHtml($data['md']);
        if (!$db->insert('pages', $data))
            return null;
        return $db->insertId();
    }

    static function delete(Page $page): void {
        DB()->query("DELETE FROM pages WHERE short_name=?", $page->shortName);
    }

    static function getByName(string $short_name): ?Page {
        $db = DB();
        $q = $db->query("SELECT * FROM pages WHERE short_name=?", $short_name);
        return $db->numRows($q) ? new Page($db->fetch($q)) : null;
    }

    /**
     * @return Page[]
     */
    static function getAll(): array {
        $db = DB();
        return array_map('Page::create_instance', $db->fetchAll($db->query("SELECT * FROM pages")));
    }

}