1<?php
2/**
3 * DokuWiki Plugin watchcycle (Helper Component)
4 *
5 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
6 * @author  Szymon Olewniczak <dokuwiki@cosmocode.de>
7 */
8
9// must be run within Dokuwiki
10
11if (!defined('DOKU_INC')) {
12    die();
13}
14
15class helper_plugin_notification_db extends DokuWiki_Plugin
16{
17    /** @var helper_plugin_sqlite */
18    protected $sqlite;
19
20    /**
21     * helper_plugin_struct_db constructor.
22     */
23    public function __construct()
24    {
25        $this->init();
26    }
27
28    /**
29     * Initialize the database
30     *
31     * @throws Exception
32     */
33    protected function init()
34    {
35        /** @var helper_plugin_sqlite $sqlite */
36        $this->sqlite = plugin_load('helper', 'sqlite');
37        if (!$this->sqlite) {
38            if (defined('DOKU_UNITTEST')) {
39                throw new \Exception('Couldn\'t load sqlite.');
40            }
41            return;
42        }
43
44        if ($this->sqlite->getAdapter()->getName() != DOKU_EXT_PDO) {
45            if (defined('DOKU_UNITTEST')) {
46                throw new \Exception('Couldn\'t load PDO sqlite.');
47            }
48            $this->sqlite = null;
49            return;
50        }
51        $this->sqlite->getAdapter()->setUseNativeAlter(true);
52
53        // initialize the database connection
54        if (!$this->sqlite->init('notification', DOKU_PLUGIN . 'notification/db/')) {
55            if (defined('DOKU_UNITTEST')) {
56                throw new \Exception('Couldn\'t init sqlite.');
57            }
58            $this->sqlite = null;
59            return;
60        }
61    }
62
63    /**
64     * @return helper_plugin_sqlite|null
65     */
66    public function getDB()
67    {
68        global $conf;
69        $len = strlen($conf['metadir']);
70        if ($this->sqlite && $conf['metadir'] != substr($this->sqlite->getAdapter()->getDbFile(), 0, $len)) {
71            $this->init();
72        }
73        if (!$this->sqlite) {
74            msg($this->getLang('error sqlite missing'), -1);
75            return false;
76        }
77        return $this->sqlite;
78    }
79
80    /**
81     * Completely remove the database and reinitialize it
82     *
83     * You do not want to call this except for testing!
84     */
85    public function resetDB()
86    {
87        if (!$this->sqlite) {
88            return;
89        }
90        $file = $this->sqlite->getAdapter()->getDbFile();
91        if (!$file) {
92            return;
93        }
94        unlink($file);
95        clearstatcache(true, $file);
96        $this->init();
97    }
98}
99
100// vim:ts=4:sw=4:et:
101