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_watchcycle_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('watchcycle', DOKU_PLUGIN . 'watchcycle/db/')) {
55            if (defined('DOKU_UNITTEST')) {
56                throw new \Exception('Couldn\'t init sqlite.');
57            }
58            $this->sqlite = null;
59            return;
60        }
61
62        $helper = plugin_load('helper', 'watchcycle');
63        $this->sqlite->create_function('DAYS_AGO', [$helper, 'daysAgo'], 1);
64    }
65
66    /**
67     * @return helper_plugin_sqlite|null
68     */
69    public function getDB()
70    {
71        global $conf;
72        $len = strlen($conf['metadir']);
73        if ($this->sqlite && $conf['metadir'] != substr($this->sqlite->getAdapter()->getDbFile(), 0, $len)) {
74            $this->init();
75        }
76        if (!$this->sqlite) {
77            msg($this->getLang('error sqlite missing'), -1);
78            return false;
79        }
80        return $this->sqlite;
81    }
82
83    /**
84     * Completely remove the database and reinitialize it
85     *
86     * You do not want to call this except for testing!
87     */
88    public function resetDB()
89    {
90        if (!$this->sqlite) {
91            return;
92        }
93        $file = $this->sqlite->getAdapter()->getDbFile();
94        if (!$file) {
95            return;
96        }
97        unlink($file);
98        clearstatcache(true, $file);
99        $this->init();
100    }
101}
102
103// vim:ts=4:sw=4:et:
104