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_ireadit_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('ireadit', DOKU_PLUGIN . 'ireadit/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     * @param bool $throw throw an Exception when sqlite not available?
65     * @return helper_plugin_sqlite|null
66     * @throws Exception
67     */
68    public function getDB($throw=true)
69    {
70        global $conf;
71        $len = strlen($conf['metadir']);
72        if ($this->sqlite && $conf['metadir'] != substr($this->sqlite->getAdapter()->getDbFile(), 0, $len)) {
73            $this->init();
74        }
75        if(!$this->sqlite && $throw) {
76            throw new \Exception('The ireadit plugin requires the sqlite plugin. Please install and enable it.');
77        }
78        return $this->sqlite;
79    }
80
81    /**
82     * Completely remove the database and reinitialize it
83     *
84     * You do not want to call this except for testing!
85     */
86    public function resetDB()
87    {
88        if (!$this->sqlite) {
89            return;
90        }
91        $file = $this->sqlite->getAdapter()->getDbFile();
92        if (!$file) {
93            return;
94        }
95        unlink($file);
96        clearstatcache(true, $file);
97        $this->init();
98    }
99}
100
101// vim:ts=4:sw=4:et:
102