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