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 = join(',', $cols);
33        $vals = array_merge($this->getSingleNoninputValues(), $this->singleValues);
34        $rid = $this->getRid() ?: "(SELECT (COALESCE(MAX(rid), 0 ) + 1) FROM $this->stable)";
35
36        return "REPLACE INTO $this->stable (rid, $cols)
37                      VALUES ($rid," . trim(str_repeat('?,', count($vals)), ',') . ');';
38    }
39
40    /** @inheritDoc */
41    protected function getMultiSql()
42    {
43        return '';
44    }
45
46    /** @inheritDoc */
47    protected function getSingleNoninputCols()
48    {
49        return ['pid', 'rev', 'latest', 'published'];
50    }
51
52    /** @inheritDoc */
53    protected function getSingleNoninputValues()
54    {
55        return [$this->pid, AccessTable::DEFAULT_REV, AccessTable::DEFAULT_LATEST, $this->published];
56    }
57
58    /**
59     * @inheritdoc
60     * @return int|bool
61     */
62    protected function getLastRevisionTimestamp()
63    {
64        $table = 'data_structpublish';
65        $where = "WHERE pid = ?";
66        $opts = [$this->pid];
67        if ($this->ts) {
68            $where .= " AND REV > 0 AND rev <= ?";
69            $opts[] = $this->ts;
70        }
71
72        /** @noinspection SqlResolve */
73        $sql = "SELECT rev FROM $table $where ORDER BY rev DESC LIMIT 1";
74        $ret = $this->sqlite->queryValue($sql, $opts);
75
76        // make sure we don't cast empty result to 0 (serial data has rev = 0)
77        if ($ret !== false) {
78            $ret = (int) $ret;
79        }
80        return $ret;
81    }
82
83    /**
84     * Remove latest status from previous publish data
85     * for the current page id
86     */
87    protected function beforeSave()
88    {
89        /** @noinspection SqlResolve */
90        return $this->sqlite->query(
91            "UPDATE $this->stable SET latest = 0 WHERE latest = 1 AND pid = ?",
92            [$this->pid]
93        );
94    }
95}
96