xref: /plugin/struct/helper/db.php (revision 91c655b4cc7207c34fe7560ef21514d22e892fe8)
1<?php
2
3/**
4 * DokuWiki Plugin struct (Helper Component)
5 *
6 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
7 * @author  Andreas Gohr, Michael Große <dokuwiki@cosmocode.de>
8 */
9
10use dokuwiki\ErrorHandler;
11use dokuwiki\plugin\sqlite\SQLiteDB;
12use dokuwiki\plugin\struct\meta\StructException;
13
14class helper_plugin_struct_db extends DokuWiki_Plugin
15{
16    /** @var SQLiteDB */
17    protected $sqlite;
18
19    /**
20     * @param bool $throw throw an Exception when sqlite not available
21     * @return SQLiteDB|null
22     */
23    public function getDB($throw = true)
24    {
25        if ($this->sqlite === null) {
26            try {
27                $this->sqlite = new SQLiteDB('struct', DOKU_PLUGIN . 'struct/db/');
28            } catch (\Exception $exception) {
29                if (defined('DOKU_UNITTEST')) throw new \RuntimeException('Could not load SQLite', 0, $exception);
30                ErrorHandler::logException($exception);
31                if ($throw) throw new StructException('no sqlite');
32                return null;
33            }
34
35            // register our JSON function with variable parameters
36            $this->sqlite->getPdo()->sqliteCreateFunction('STRUCT_JSON', [$this, 'STRUCT_JSON'], -1);
37
38            // this function is meant to be overwritten by plugins
39            $this->sqlite->getPdo()->sqliteCreateFunction('IS_PUBLISHER', [$this, 'IS_PUBLISHER'], -1);
40        }
41        return $this->sqlite;
42    }
43
44    /**
45     * Completely remove the database and reinitialize it
46     *
47     * You do not want to call this except for testing!
48     */
49    public function resetDB()
50    {
51        if (!$this->sqlite) return;
52        $file = $this->sqlite->getDbFile();
53        if (!$file) return;
54        unlink($file);
55        clearstatcache(true, $file);
56        $this->sqlite = null;
57    }
58
59    /**
60     * Encodes all given arguments into a JSON encoded array
61     *
62     * @param string ...
63     * @return string
64     */
65    public function STRUCT_JSON() // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps
66    {
67        $args = func_get_args();
68        return json_encode($args);
69    }
70
71    /**
72     * This dummy implementation can be overwritten by a plugin
73     *
74     * @return int
75     */
76    public function IS_PUBLISHER() // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps
77    {
78        return 1;
79    }
80}
81
82// vim:ts=4:sw=4:et:
83