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