1<?php
2
3namespace dokuwiki\plugin\structpublish\meta;
4
5use dokuwiki\plugin\struct\meta\AccessTable;
6use dokuwiki\plugin\struct\meta\AccessTableSerial;
7
8/**
9 * Class AccessTableStructpublish
10 *
11 * Load and save publish data
12 *
13 * @package dokuwiki\plugin\struct\meta
14 */
15class AccessTableStructpublish extends AccessTableSerial
16{
17    protected $published = 0;
18
19    /**
20     * @param 0|1|bool $published
21     * @return void
22     */
23    public function setPublished($published)
24    {
25        $this->published = (int) $published;
26    }
27
28    /** @inheritDoc */
29    protected function getSingleSql()
30    {
31        $cols = array_merge($this->getSingleNoninputCols(), $this->singleCols);
32        $cols = implode(',', $cols);
33
34        $vals = array_merge($this->getSingleNoninputValues(), $this->singleValues);
35        $rid = $this->getRid() ?: "(SELECT (COALESCE(MAX(rid), 0 ) + 1) FROM $this->stable)";
36
37        return "REPLACE INTO $this->stable (rid, $cols)
38                      VALUES ($rid," . trim(str_repeat('?,', count($vals)), ',') . ');';
39    }
40
41    /** @inheritDoc */
42    protected function getMultiSql()
43    {
44        return '';
45    }
46
47    /** @inheritDoc */
48    protected function getSingleNoninputCols()
49    {
50        return ['pid', 'rev', 'latest', 'published'];
51    }
52
53    /** @inheritDoc */
54    protected function getSingleNoninputValues()
55    {
56        return [$this->pid, AccessTable::DEFAULT_REV, AccessTable::DEFAULT_LATEST, $this->published];
57    }
58
59    /**
60     * @inheritdoc
61     * @return int|bool
62     */
63    protected function getLastRevisionTimestamp()
64    {
65        $table = 'data_structpublish';
66        $where = "WHERE pid = ?";
67        $opts = [$this->pid];
68        if ($this->ts) {
69            $where .= " AND REV > 0 AND rev <= ?";
70            $opts[] = $this->ts;
71        }
72
73        /** @noinspection SqlResolve */
74        $sql = "SELECT rev FROM $table $where ORDER BY rev DESC LIMIT 1";
75        $ret = $this->sqlite->queryValue($sql, $opts);
76
77        // make sure we don't cast empty result to 0 (serial data has rev = 0)
78        if ($ret !== false) {
79            $ret = (int) $ret;
80        }
81        return $ret;
82    }
83
84    /**
85     * Remove latest status from previous publish data
86     * for the current page id
87     */
88    protected function beforeSave()
89    {
90        /** @noinspection SqlResolve */
91        return $this->sqlite->query(
92            "UPDATE $this->stable SET latest = 0 WHERE latest = 1 AND pid = ?",
93            [$this->pid]
94        );
95    }
96}
97