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_addressbook_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     * Modified for addressbook plugin by Gero Gothe
30     *
31     * Initialize the database
32     *
33     * @throws Exception
34     */
35    protected function init()
36    {
37        /** @var helper_plugin_sqlite $sqlite */
38        $this->sqlite = plugin_load('helper', 'sqlite');
39        if (!$this->sqlite) {
40            if (defined('DOKU_UNITTEST')) {
41                throw new \Exception('Couldn\'t load sqlite.');
42            }
43            return;
44        }
45
46        if ($this->sqlite->getAdapter()->getName() != DOKU_EXT_PDO) {
47            if (defined('DOKU_UNITTEST')) {
48                throw new \Exception('Couldn\'t load PDO sqlite.');
49            }
50            $this->sqlite = null;
51            return;
52        }
53        $this->sqlite->getAdapter()->setUseNativeAlter(true);
54
55        // initialize the database connection
56        if (!$this->sqlite->init('addressbook', DOKU_PLUGIN . 'addressbook/db/')) { # Changed plugin name
57            if (defined('DOKU_UNITTEST')) {
58                throw new \Exception('Couldn\'t init sqlite.');
59            }
60            $this->sqlite = null;
61            return;
62        }
63    }
64
65    /**
66     * @param bool $throw throw an Exception when sqlite not available?
67     * @return helper_plugin_sqlite|null
68     * @throws Exception
69     */
70    public function getDB($throw=true)
71    {
72        global $conf;
73        $len = strlen($conf['metadir']);
74        if ($this->sqlite && $conf['metadir'] != substr($this->sqlite->getAdapter()->getDbFile(), 0, $len)) {
75            $this->init();
76        }
77        if(!$this->sqlite && $throw) {
78            throw new \Exception('The addressbook plugin requires the sqlite plugin. Please install and enable it.');
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