xref: /plugin/dbquery/helper.php (revision 2e564e06806b572fcd4150c4267799087a935085)
1<?php
2
3/**
4 * DokuWiki Plugin dbquery (Helper Component)
5 *
6 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
7 * @author  Andreas Gohr <dokuwiki@cosmocode.de>
8 */
9class helper_plugin_dbquery extends dokuwiki\Extension\Plugin
10{
11
12    /**
13     * @param string $name Page name of the query
14     * @throws \Exception
15     */
16    public function loadQueryFromPage($name)
17    {
18
19        $name = cleanID($name);
20        $id = $this->getConf('namespace') . ':' . $name;
21        if (!page_exists($id)) throw new \Exception("No query named '$name' found");
22
23        $doc = p_cached_output(wikiFN($id), 'dbquery');
24        // FIXME handle additional stuff later
25
26        return trim($doc);
27    }
28
29    /**
30     * Opens a database connection, executes the query and returns the result
31     *
32     * @param string $query
33     * @param string[] $params
34     * @return array
35     * @throws \PDOException
36     * @todo should we keep the DB connection around for subsequent queries?
37     * @todo should we allow SELECT queries only for additional security?
38     */
39    public function executeQuery($query, $params)
40    {
41        $pdo = new PDO($this->getConf('dsn'), $this->getConf('user'), $this->getConf('pass'));
42        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
43
44        $sth = $pdo->prepare($query);
45        $sth->execute($params);
46        $data = $sth->fetchAll(PDO::FETCH_ASSOC);
47        $sth->closeCursor();
48
49        return $data;
50    }
51}
52