1<?php
2
3/**
4 * DokuWiki Plugin authwordpress (Auth Component)
5 *
6 * Provides authentication against a WordPress MySQL database backend
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; version 2 of the License
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * See the COPYING file in your DokuWiki folder for details
18 *
19 * @author     Damien Regad <dregad@mantisbt.org>
20 * @copyright  2015 Damien Regad
21 * @license    GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
22 * @version    1.1
23 * @link       https://github.com/dregad/dokuwiki-authwordpress
24 *
25 * @noinspection PhpComposerExtensionStubsInspection
26 *               PhpUnused
27 *               PhpMissingReturnTypeInspection
28 */
29
30// must be run within Dokuwiki
31if (!defined('DOKU_INC')) {
32    die();
33}
34
35use dokuwiki\Logger;
36
37/**
38 * WordPress password hashing framework
39 */
40require_once('class-phpass.php');
41
42/**
43 * Authentication class
44 */
45// @codingStandardsIgnoreLine
46class auth_plugin_authwordpress extends DokuWiki_Auth_Plugin
47{
48    /**
49     * SQL statement to retrieve User data from WordPress DB
50     * (including group memberships)
51     * '%prefix%' will be replaced by the actual prefix (from plugin config)
52     * @var string $sql_wp_user_data
53     */
54    protected $sql_wp_user_data = "SELECT
55            id, user_login, user_pass, user_email, display_name,
56            meta_value AS grps
57        FROM %prefix%users u
58        JOIN %prefix%usermeta m ON u.id = m.user_id AND meta_key = '%prefix%capabilities'";
59
60    /**
61     * Wordpress database connection
62     * @var PDO $db
63     */
64    protected $db;
65
66    /**
67     * Users cache
68     * @var array $users
69     */
70    protected $users;
71
72    /**
73     * True if all users have been loaded in the cache
74     * @see $users
75     * @var bool $usersCached
76     */
77    protected $usersCached = false;
78
79    /**
80     * Filter pattern
81     * @var array $filter
82     */
83    protected $filter;
84
85    /**
86     * Constructor.
87     */
88    public function __construct()
89    {
90        parent::__construct();
91
92        // Plugin capabilities
93        $this->cando['getUsers'] = true;
94        $this->cando['getUserCount'] = true;
95
96        // Try to establish a connection to the WordPress DB
97        // abort in case of failure
98        try {
99            $this->connectWordpressDb();
100        } catch (Exception $e) {
101            msg(sprintf($this->getLang('error_connect_failed'), $e->getMessage()));
102            $this->success = false;
103            return;
104        }
105
106        // Initialize SQL query with configured prefix
107        $this->sql_wp_user_data = str_replace(
108            '%prefix%',
109            $this->getConf('prefix'),
110            $this->sql_wp_user_data
111        );
112
113        $this->success = true;
114    }
115
116
117    /**
118     * Check user+password.
119     *
120     * Note that WordPress adds slashes to the password before generating the hash
121     * {@see https://developer.wordpress.org/reference/functions/wp_magic_quotes/},
122     * so we need to do the same otherwise password containing `\`, `'` or `"` will
123     * never match ({@see https://github.com/dregad/dokuwiki-plugin-authwordpress/issues/23)}.
124     *
125     * @param   string $user the user name
126     * @param   string $pass the clear text password
127     *
128     * @return  bool
129     *
130     * @uses PasswordHash::CheckPassword WordPress password hasher
131     */
132    public function checkPass($user, $pass)
133    {
134        $data = $this->getUserData($user);
135        if ($data === false) {
136            return false;
137        }
138
139        $hasher = new PasswordHash(8, true);
140
141        // Add slashes to match WordPress behavior
142        $check = $hasher->CheckPassword(addslashes($pass), $data['pass']);
143        $this->logDebug("Password " . ($check ? 'OK' : 'Invalid'));
144
145        return $check;
146    }
147
148    /**
149     * Bulk retrieval of user data.
150     *
151     * @param   int   $start index of first user to be returned
152     * @param   int   $limit max number of users to be returned
153     * @param   array $filter array of field/pattern pairs
154     *
155     * @return  array userinfo (refer getUserData for internal userinfo details)
156     */
157    public function retrieveUsers($start = 0, $limit = 0, $filter = array())
158    {
159        msg($this->getLang('user_list_use_wordpress'));
160
161        $this->cacheAllUsers();
162
163        // Apply filter and pagination
164        $this->setFilter($filter);
165        $list = array();
166        $count = $i = 0;
167        foreach ($this->users as $user => $info) {
168            if ($this->applyFilter($user, $info)) {
169                if ($i >= $start) {
170                    $list[$user] = $info;
171                    $count++;
172                    if ($limit > 0 && $count >= $limit) {
173                        break;
174                    }
175                }
176                $i++;
177            }
178        }
179
180        return $list;
181    }
182
183    /**
184     * Return a count of the number of user which meet $filter criteria.
185     *
186     * @param array $filter
187     *
188     * @return int
189     */
190    public function getUserCount($filter = array())
191    {
192        $this->cacheAllUsers();
193
194        if (empty($filter)) {
195            $count = count($this->users);
196        } else {
197            $this->setFilter($filter);
198            $count = 0;
199            foreach ($this->users as $user => $info) {
200                $count += (int)$this->applyFilter($user, $info);
201            }
202        }
203        return $count;
204    }
205
206
207    /**
208     * Returns info about the given user.
209     *
210     * @param string $user the user name
211     * @param bool   $requireGroups defaults to true
212     *
213     * @return array|false containing user data or false in case of error
214     */
215    public function getUserData($user, $requireGroups = true)
216    {
217        if (isset($this->users[$user])) {
218            return $this->users[$user];
219        }
220
221        $sql = $this->sql_wp_user_data
222            . 'WHERE user_login = :user';
223
224        $stmt = $this->db->prepare($sql);
225        $stmt->bindParam(':user', $user);
226        $this->logDebug("Retrieving data for user '$user'\n$sql");
227
228        if (!$stmt->execute()) {
229            // Query execution failed
230            $err = $stmt->errorInfo();
231            $this->logDebug("Error $err[1]: $err[2]");
232            return false;
233        }
234
235        $user = $stmt->fetch(PDO::FETCH_ASSOC);
236        if ($user === false) {
237            // Unknown user
238            $this->logDebug("Unknown user");
239            return false;
240        }
241
242        return $this->cacheUser($user);
243    }
244
245
246    /**
247     * Connect to Wordpress database.
248     *
249     * Initializes $db property as PDO object.
250     *
251     * @return void
252     */
253    protected function connectWordpressDb(): void
254    {
255        if ($this->db) {
256            // Already connected
257            return;
258        }
259
260        // Build connection string
261        $dsn = array(
262            'host=' . $this->getConf('hostname'),
263            'dbname=' . $this->getConf('database'),
264            'charset=UTF8',
265        );
266        $port = $this->getConf('port');
267        if ($port) {
268            $dsn[] = 'port=' . $port;
269        }
270        $dsn = 'mysql:' . implode(';', $dsn);
271
272        $this->db = new PDO($dsn, $this->getConf('username'), $this->getConf('password'));
273    }
274
275    /**
276     * Cache User Data.
277     *
278     * Convert a Wordpress DB User row to DokuWiki user info array
279     * and stores it in the users cache.
280     *
281     * @param  array $row Raw Wordpress user table row
282     *
283     * @return array user data
284     */
285    protected function cacheUser(array $row): array
286    {
287        global $conf;
288
289        $login = $row['user_login'];
290
291        // If the user is already cached, just return it
292        if (isset($this->users[$login])) {
293            return $this->users[$login];
294        }
295
296        // Group membership - add DokuWiki's default group
297        $groups = array_keys(unserialize($row['grps']));
298        if ($this->getConf('usedefaultgroup')) {
299            $groups[] = $conf['defaultgroup'];
300        }
301
302        $info = array(
303            'user' => $login,
304            'name' => $row['display_name'],
305            'pass' => $row['user_pass'],
306            'mail' => $row['user_email'],
307            'grps' => $groups,
308        );
309
310        $this->users[$login] = $info;
311        return $info;
312    }
313
314    /**
315     * Loads all Wordpress users into the cache.
316     *
317     * @return void
318     */
319    protected function cacheAllUsers()
320    {
321        if ($this->usersCached) {
322            return;
323        }
324
325        $stmt = $this->db->prepare($this->sql_wp_user_data);
326        $stmt->execute();
327
328        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $user) {
329            $this->cacheUser($user);
330        }
331
332        $this->usersCached = true;
333    }
334
335    /**
336     * Build filter patterns from given criteria.
337     *
338     * @param array $filter
339     *
340     * @return void
341     */
342    protected function setFilter(array $filter): void
343    {
344        $this->filter = array();
345        foreach ($filter as $field => $value) {
346            // Build PCRE pattern, utf8 + case insensitive
347            $this->filter[$field] = '/' . str_replace('/', '\/', $value) . '/ui';
348        }
349    }
350
351    /**
352     * Return true if given user matches filter pattern, false otherwise.
353     *
354     * @param string $user login
355     * @param array  $info User data
356     *
357     * @return bool
358     */
359    protected function applyFilter(string $user, array $info): bool
360    {
361        foreach ($this->filter as $elem => $pattern) {
362            if ($elem == 'grps') {
363                if (!preg_grep($pattern, $info['grps'])) {
364                    return false;
365                }
366            } else {
367                if (!preg_match($pattern, $info[$elem])) {
368                    return false;
369                }
370            }
371        }
372        return true;
373    }
374
375    /**
376     * Add message to debug log.
377     *
378     * @param string $msg
379     *
380     * @return void
381     */
382    protected function logDebug(string $msg): void
383    {
384        global $updateVersion;
385        if ($updateVersion >= 52) {
386            Logger::debug($msg);
387        } else {
388            dbglog($msg);
389        }
390    }
391}
392
393// vim:ts=4:sw=4:noet:
394