1<?php
2
3use dokuwiki\ErrorHandler;
4use dokuwiki\Extension\Plugin;
5use dokuwiki\plugin\sqlite\SQLiteDB;
6
7/**
8 * DokuWiki Plugin watchcycle (Helper Component)
9 *
10 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
11 * @author  Szymon Olewniczak <dokuwiki@cosmocode.de>
12 * @author  Anna Dabrowska <dokuwiki@cosmocode.de>
13 */
14
15class helper_plugin_watchcycle_db extends Plugin
16{
17    /** @var SQLiteDB */
18    protected $sqlite;
19
20    public function __construct()
21    {
22        $this->init();
23    }
24
25    /**
26     * Initialize the database
27     *
28     * @throws Exception
29     */
30    protected function init()
31    {
32        $this->sqlite = new SQLiteDB('watchcycle', DOKU_PLUGIN . 'watchcycle/db/');
33
34        $helper = plugin_load('helper', 'watchcycle');
35        $this->sqlite->getPdo()->sqliteCreateFunction('DAYS_AGO', [$helper, 'daysAgo'], 1);
36    }
37
38    /**
39     * @param bool $throw throw an Exception when sqlite not available or fails to load
40     * @return SQLiteDB|null
41     * @throws Exception
42     */
43    public function getDB($throw = true)
44    {
45        return $this->sqlite;
46    }
47
48    /**
49     * @param array $headers
50     * @return array
51     */
52    public function getAll(array $headers = [])
53    {
54        global $INPUT;
55
56        $q = 'SELECT page, maintainer, cycle, DAYS_AGO(last_maintainer_rev) AS current, uptodate FROM watchcycle';
57        $where = [];
58        $q_args = [];
59        if ($INPUT->str('filter') != '') {
60            $where[] = 'page LIKE ?';
61            $q_args[] = '%' . $INPUT->str('filter') . '%';
62        }
63        if ($INPUT->has('outdated')) {
64            $where[] = 'uptodate=0';
65        }
66
67        if ($where !== []) {
68            $q .= ' WHERE ';
69            $q .= implode(' AND ', $where);
70        }
71
72        if ($INPUT->has('sortby') && in_array($INPUT->str('sortby'), $headers)) {
73            $q .= ' ORDER BY ' . $INPUT->str('sortby');
74            if ($INPUT->int('desc') == 1) {
75                $q .= ' DESC';
76            }
77        }
78
79        return $this->sqlite->queryAll($q, $q_args);
80    }
81}
82