xref: /plugin/struct/helper/db.php (revision 299ca8cc642c152679238a0fa0ee3d839791f6b6)
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     * Initialize the database
21     *
22     * @throws Exception
23     */
24    protected function init()
25    {
26        $this->sqlite = new SQLiteDB('struct', DOKU_PLUGIN . 'struct/db/');
27
28        // register our JSON function with variable parameters
29        $this->sqlite->getPdo()->sqliteCreateFunction('STRUCT_JSON', [$this, 'STRUCT_JSON'], -1);
30
31        // this function is meant to be overwritten by plugins
32        $this->sqlite->getPdo()->sqliteCreateFunction('IS_PUBLISHER', [$this, 'IS_PUBLISHER'], -1);
33    }
34
35    /**
36     * @param bool $throw throw an Exception when sqlite not available
37     * @return SQLiteDB|null
38     */
39    public function getDB($throw = true)
40    {
41        if ($this->sqlite === null) {
42            try {
43                $this->init();
44            } catch (\Exception $exception) {
45                if (defined('DOKU_UNITTEST')) throw new \RuntimeException('Could not load SQLite', 0, $exception);
46                ErrorHandler::logException($exception);
47                if ($throw) throw new StructException('no sqlite');
48                return null;
49            }
50        }
51        return $this->sqlite;
52    }
53
54    /**
55     * Completely remove the database and reinitialize it
56     *
57     * You do not want to call this except for testing!
58     */
59    public function resetDB()
60    {
61        if (!$this->sqlite) return;
62        $file = $this->sqlite->getDbFile();
63        if (!$file) return;
64        unlink($file);
65        clearstatcache(true, $file);
66        $this->sqlite = null;
67    }
68
69    /**
70     * Encodes all given arguments into a JSON encoded array
71     *
72     * @param string ...
73     * @return string
74     */
75    public function STRUCT_JSON() // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps
76    {
77        $args = func_get_args();
78        return json_encode($args);
79    }
80
81    /**
82     * This dummy implementation can be overwritten by a plugin
83     *
84     * @return int
85     */
86    public function IS_PUBLISHER() // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps
87    {
88        return 1;
89    }
90}
91
92// vim:ts=4:sw=4:et:
93