1<?php
2
3use dokuwiki\Extension\Plugin;
4use dokuwiki\plugin\struct\meta\Assignments;
5use dokuwiki\plugin\structpublish\meta\Constants;
6use dokuwiki\plugin\structpublish\meta\Revision;
7
8/**
9 * DokuWiki Plugin structpublish (Helper Component)
10 *
11 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
12 * @author  Anna Dabrowska <dokuwiki@cosmocode.de>
13 */
14class helper_plugin_structpublish_publish extends Plugin
15{
16    /** @var helper_plugin_structpublish_db  */
17    protected $dbHelper;
18
19    public function __construct()
20    {
21        $this->dbHelper = plugin_load('helper', 'structpublish_db');
22    }
23
24    /**
25     * Save publish data
26     *
27     * @param string $action
28     * @return Revision
29     * @throws Exception
30     */
31    public function saveRevision($action, $newversion = '')
32    {
33        global $ID;
34        global $INFO;
35
36        if (!$this->dbHelper->checkAccess($ID, [$action])) {
37            throw new \Exception('User may not ' . $action);
38        }
39
40        $revision = new Revision($ID, $INFO['currentrev']);
41
42        if ($action === Constants::ACTION_PUBLISH) {
43            $revision->setVersion($newversion);
44        }
45        $revision->setUser($_SERVER['REMOTE_USER']);
46        $revision->setStatus(Constants::transitionBy($action));
47        $revision->setTimestamp(time());
48        $revision->save();
49
50        if ($action === Constants::ACTION_PUBLISH) {
51            $this->updateSchemaData();
52        }
53
54        return $revision;
55    }
56
57    /**
58     * Set "published" status in all assigned schemas
59     *
60     * @return void
61     */
62    protected function updateSchemaData()
63    {
64        global $ID;
65        global $INFO;
66
67        $schemaAssignments = Assignments::getInstance();
68        $tables = $schemaAssignments->getPageAssignments($ID);
69
70        if (empty($tables)) {
71            return;
72        }
73
74        $sqlite = $this->dbHelper->getDB();
75
76        foreach ($tables as $table) {
77            // unpublish earlier revisions
78            $sqlite->query("UPDATE data_$table SET published = 0 WHERE pid = ?", [$ID]);
79            $sqlite->query("UPDATE multi_$table SET published = 0 WHERE pid = ?", [$ID]);
80
81            // publish the current revision
82            $sqlite->query(
83                "UPDATE data_$table SET published = 1 WHERE pid = ? AND rev = ?",
84                [$ID, $INFO['currentrev']]
85            );
86            $sqlite->query(
87                "UPDATE multi_$table SET published = 1 WHERE pid = ? AND rev = ?",
88                [$ID, $INFO['currentrev']]
89            );
90        }
91    }
92}
93