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