xref: /plugin/authwordpress/auth.php (revision c66ceb5422c39cc313ed9c143515b46aef48f3da)
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        // check if new type of hash
139        if (str_starts_with($data['pass'], '$wp')) {
140            $password_to_verify = base64_encode(hash_hmac('sha384', $pass, 'wp-sha384', true));
141            $check = password_verify($password_to_verify, substr($data['pass'], 3));
142        } else {
143            $hasher = new PasswordHash(8, true);
144            // Add slashes to match WordPress behavior
145            $check = $hasher->CheckPassword(addslashes($pass), $data['pass']);
146        }
147        $this->logDebug("Password " . ($check ? 'OK' : 'Invalid'));
148
149        return $check;
150    }
151
152    /**
153     * Bulk retrieval of user data.
154     *
155     * @param   int   $start index of first user to be returned
156     * @param   int   $limit max number of users to be returned
157     * @param   array $filter array of field/pattern pairs
158     *
159     * @return  array userinfo (refer getUserData for internal userinfo details)
160     */
161    public function retrieveUsers($start = 0, $limit = 0, $filter = array())
162    {
163        msg($this->getLang('user_list_use_wordpress'));
164
165        $this->cacheAllUsers();
166
167        // Apply filter and pagination
168        $this->setFilter($filter);
169        $list = array();
170        $count = $i = 0;
171        foreach ($this->users as $user => $info) {
172            if ($this->applyFilter($user, $info)) {
173                if ($i >= $start) {
174                    $list[$user] = $info;
175                    $count++;
176                    if ($limit > 0 && $count >= $limit) {
177                        break;
178                    }
179                }
180                $i++;
181            }
182        }
183
184        return $list;
185    }
186
187    /**
188     * Return a count of the number of user which meet $filter criteria.
189     *
190     * @param array $filter
191     *
192     * @return int
193     */
194    public function getUserCount($filter = array())
195    {
196        $this->cacheAllUsers();
197
198        if (empty($filter)) {
199            $count = count($this->users);
200        } else {
201            $this->setFilter($filter);
202            $count = 0;
203            foreach ($this->users as $user => $info) {
204                $count += (int)$this->applyFilter($user, $info);
205            }
206        }
207        return $count;
208    }
209
210
211    /**
212     * Returns info about the given user.
213     *
214     * @param string $user the user name
215     * @param bool   $requireGroups defaults to true
216     *
217     * @return array|false containing user data or false in case of error
218     */
219    public function getUserData($user, $requireGroups = true)
220    {
221        if (isset($this->users[$user])) {
222            return $this->users[$user];
223        }
224
225        $sql = $this->sql_wp_user_data
226            . 'WHERE user_login = :user';
227
228        $stmt = $this->db->prepare($sql);
229        $stmt->bindParam(':user', $user);
230        $this->logDebug("Retrieving data for user '$user'\n$sql");
231
232        if (!$stmt->execute()) {
233            // Query execution failed
234            $err = $stmt->errorInfo();
235            $this->logDebug("Error $err[1]: $err[2]");
236            return false;
237        }
238
239        $user = $stmt->fetch(PDO::FETCH_ASSOC);
240        if ($user === false) {
241            // Unknown user
242            $this->logDebug("Unknown user");
243            return false;
244        }
245
246        return $this->cacheUser($user);
247    }
248
249
250    /**
251     * Connect to Wordpress database.
252     *
253     * Initializes $db property as PDO object.
254     *
255     * @return void
256     */
257    protected function connectWordpressDb(): void
258    {
259        if ($this->db) {
260            // Already connected
261            return;
262        }
263
264        // Build connection string
265        $dsn = array(
266            'host=' . $this->getConf('hostname'),
267            'dbname=' . $this->getConf('database'),
268            'charset=UTF8',
269        );
270        $port = $this->getConf('port');
271        if ($port) {
272            $dsn[] = 'port=' . $port;
273        }
274        $dsn = 'mysql:' . implode(';', $dsn);
275
276        $this->db = new PDO($dsn, $this->getConf('username'), $this->getConf('password'));
277    }
278
279    /**
280     * Cache User Data.
281     *
282     * Convert a Wordpress DB User row to DokuWiki user info array
283     * and stores it in the users cache.
284     *
285     * @param  array $row Raw Wordpress user table row
286     *
287     * @return array user data
288     */
289    protected function cacheUser(array $row): array
290    {
291        global $conf;
292
293        $login = $row['user_login'];
294
295        // If the user is already cached, just return it
296        if (isset($this->users[$login])) {
297            return $this->users[$login];
298        }
299
300        // Group membership - add DokuWiki's default group
301        $groups = array_keys(unserialize($row['grps']));
302        if ($this->getConf('usedefaultgroup')) {
303            $groups[] = $conf['defaultgroup'];
304        }
305
306        $info = array(
307            'user' => $login,
308            'name' => $row['display_name'],
309            'pass' => $row['user_pass'],
310            'mail' => $row['user_email'],
311            'grps' => $groups,
312        );
313
314        $this->users[$login] = $info;
315        return $info;
316    }
317
318    /**
319     * Loads all Wordpress users into the cache.
320     *
321     * @return void
322     */
323    protected function cacheAllUsers()
324    {
325        if ($this->usersCached) {
326            return;
327        }
328
329        $stmt = $this->db->prepare($this->sql_wp_user_data);
330        $stmt->execute();
331
332        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $user) {
333            $this->cacheUser($user);
334        }
335
336        $this->usersCached = true;
337    }
338
339    /**
340     * Build filter patterns from given criteria.
341     *
342     * @param array $filter
343     *
344     * @return void
345     */
346    protected function setFilter(array $filter): void
347    {
348        $this->filter = array();
349        foreach ($filter as $field => $value) {
350            // Build PCRE pattern, utf8 + case insensitive
351            $this->filter[$field] = '/' . str_replace('/', '\/', $value) . '/ui';
352        }
353    }
354
355    /**
356     * Return true if given user matches filter pattern, false otherwise.
357     *
358     * @param string $user login
359     * @param array  $info User data
360     *
361     * @return bool
362     */
363    protected function applyFilter(string $user, array $info): bool
364    {
365        foreach ($this->filter as $elem => $pattern) {
366            if ($elem == 'grps') {
367                if (!preg_grep($pattern, $info['grps'])) {
368                    return false;
369                }
370            } else {
371                if (!preg_match($pattern, $info[$elem])) {
372                    return false;
373                }
374            }
375        }
376        return true;
377    }
378
379    /**
380     * Add message to debug log.
381     *
382     * @param string $msg
383     *
384     * @return void
385     */
386    protected function logDebug(string $msg): void
387    {
388        global $updateVersion;
389        if ($updateVersion >= 52) {
390            Logger::debug($msg);
391        } else {
392            dbglog($msg);
393        }
394    }
395}
396
397// vim:ts=4:sw=4:noet:
398