xref: /plugin/struct/helper/db.php (revision 8a68af5ad36c4285cf2928aa21be93b85b2d1894)
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 or fails to load
37     * @return SQLiteDB|null
38     * @throws Exception
39     */
40    public function getDB($throw = true)
41    {
42        if ($this->sqlite === null) {
43            if (!class_exists(SQLiteDB::class)) {
44                if ($throw || defined('DOKU_UNITTEST')) throw new StructException('no sqlite');
45                return null;
46            }
47
48            try {
49                $this->init();
50            } catch (\Exception $exception) {
51                ErrorHandler::logException($exception);
52                if ($throw) throw $exception;
53                return null;
54            }
55        }
56        return $this->sqlite;
57    }
58
59    /**
60     * Completely remove the database and reinitialize it
61     *
62     * You do not want to call this except for testing!
63     */
64    public function resetDB()
65    {
66        if (!$this->sqlite) return;
67        $file = $this->sqlite->getDbFile();
68        if (!$file) return;
69        unlink($file);
70        clearstatcache(true, $file);
71        $this->sqlite = null;
72    }
73
74    /**
75     * Encodes all given arguments into a JSON encoded array
76     *
77     * @param string ...
78     * @return string
79     */
80    public function STRUCT_JSON() // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps
81    {
82        $args = func_get_args();
83        return json_encode($args);
84    }
85
86    /**
87     * This dummy implementation can be overwritten by a plugin
88     *
89     * @return int
90     */
91    public function IS_PUBLISHER() // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps
92    {
93        return 1;
94    }
95}
96
97// vim:ts=4:sw=4:et:
98