You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

490 lines
14 KiB

  1. <?php
  2. use dokuwiki\Extension\AuthPlugin;
  3. use dokuwiki\Logger;
  4. use dokuwiki\Utf8\Sort;
  5. /**
  6. * Plaintext authentication backend
  7. *
  8. * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
  9. * @author Andreas Gohr <andi@splitbrain.org>
  10. * @author Chris Smith <chris@jalakai.co.uk>
  11. * @author Jan Schumann <js@schumann-it.com>
  12. */
  13. class auth_plugin_authplain extends AuthPlugin
  14. {
  15. /** @var array user cache */
  16. protected $users;
  17. /** @var array filter pattern */
  18. protected $pattern = [];
  19. /** @var bool safe version of preg_split */
  20. protected $pregsplit_safe = false;
  21. /**
  22. * Constructor
  23. *
  24. * Carry out sanity checks to ensure the object is
  25. * able to operate. Set capabilities.
  26. *
  27. * @author Christopher Smith <chris@jalakai.co.uk>
  28. */
  29. public function __construct()
  30. {
  31. parent::__construct();
  32. global $config_cascade;
  33. if (!@is_readable($config_cascade['plainauth.users']['default'])) {
  34. $this->success = false;
  35. } else {
  36. if (@is_writable($config_cascade['plainauth.users']['default'])) {
  37. $this->cando['addUser'] = true;
  38. $this->cando['delUser'] = true;
  39. $this->cando['modLogin'] = true;
  40. $this->cando['modPass'] = true;
  41. $this->cando['modName'] = true;
  42. $this->cando['modMail'] = true;
  43. $this->cando['modGroups'] = true;
  44. }
  45. $this->cando['getUsers'] = true;
  46. $this->cando['getUserCount'] = true;
  47. $this->cando['getGroups'] = true;
  48. }
  49. }
  50. /**
  51. * Check user+password
  52. *
  53. * Checks if the given user exists and the given
  54. * plaintext password is correct
  55. *
  56. * @author Andreas Gohr <andi@splitbrain.org>
  57. * @param string $user
  58. * @param string $pass
  59. * @return bool
  60. */
  61. public function checkPass($user, $pass)
  62. {
  63. $userinfo = $this->getUserData($user);
  64. if ($userinfo === false) return false;
  65. return auth_verifyPassword($pass, $this->users[$user]['pass']);
  66. }
  67. /**
  68. * Return user info
  69. *
  70. * Returns info about the given user needs to contain
  71. * at least these fields:
  72. *
  73. * name string full name of the user
  74. * mail string email addres of the user
  75. * grps array list of groups the user is in
  76. *
  77. * @author Andreas Gohr <andi@splitbrain.org>
  78. * @param string $user
  79. * @param bool $requireGroups (optional) ignored by this plugin, grps info always supplied
  80. * @return array|false
  81. */
  82. public function getUserData($user, $requireGroups = true)
  83. {
  84. if ($this->users === null) $this->loadUserData();
  85. return $this->users[$user] ?? false;
  86. }
  87. /**
  88. * Creates a string suitable for saving as a line
  89. * in the file database
  90. * (delimiters escaped, etc.)
  91. *
  92. * @param string $user
  93. * @param string $pass
  94. * @param string $name
  95. * @param string $mail
  96. * @param array $grps list of groups the user is in
  97. * @return string
  98. */
  99. protected function createUserLine($user, $pass, $name, $mail, $grps)
  100. {
  101. $groups = implode(',', $grps);
  102. $userline = [$user, $pass, $name, $mail, $groups];
  103. $userline = str_replace('\\', '\\\\', $userline); // escape \ as \\
  104. $userline = str_replace(':', '\\:', $userline); // escape : as \:
  105. $userline = str_replace('#', '\\#', $userline); // escape # as \
  106. $userline = implode(':', $userline) . "\n";
  107. return $userline;
  108. }
  109. /**
  110. * Create a new User
  111. *
  112. * Returns false if the user already exists, null when an error
  113. * occurred and true if everything went well.
  114. *
  115. * The new user will be added to the default group by this
  116. * function if grps are not specified (default behaviour).
  117. *
  118. * @author Andreas Gohr <andi@splitbrain.org>
  119. * @author Chris Smith <chris@jalakai.co.uk>
  120. *
  121. * @param string $user
  122. * @param string $pwd
  123. * @param string $name
  124. * @param string $mail
  125. * @param array $grps
  126. * @return bool|null|string
  127. */
  128. public function createUser($user, $pwd, $name, $mail, $grps = null)
  129. {
  130. global $conf;
  131. global $config_cascade;
  132. // user mustn't already exist
  133. if ($this->getUserData($user) !== false) {
  134. msg($this->getLang('userexists'), -1);
  135. return false;
  136. }
  137. $pass = auth_cryptPassword($pwd);
  138. // set default group if no groups specified
  139. if (!is_array($grps)) $grps = [$conf['defaultgroup']];
  140. // prepare user line
  141. $userline = $this->createUserLine($user, $pass, $name, $mail, $grps);
  142. if (!io_saveFile($config_cascade['plainauth.users']['default'], $userline, true)) {
  143. msg($this->getLang('writefail'), -1);
  144. return null;
  145. }
  146. $this->users[$user] = [
  147. 'pass' => $pass,
  148. 'name' => $name,
  149. 'mail' => $mail,
  150. 'grps' => $grps
  151. ];
  152. return $pwd;
  153. }
  154. /**
  155. * Modify user data
  156. *
  157. * @author Chris Smith <chris@jalakai.co.uk>
  158. * @param string $user nick of the user to be changed
  159. * @param array $changes array of field/value pairs to be changed (password will be clear text)
  160. * @return bool
  161. */
  162. public function modifyUser($user, $changes)
  163. {
  164. global $ACT;
  165. global $config_cascade;
  166. // sanity checks, user must already exist and there must be something to change
  167. if (($userinfo = $this->getUserData($user)) === false) {
  168. msg($this->getLang('usernotexists'), -1);
  169. return false;
  170. }
  171. // don't modify protected users
  172. if (!empty($userinfo['protected'])) {
  173. msg(sprintf($this->getLang('protected'), hsc($user)), -1);
  174. return false;
  175. }
  176. if (!is_array($changes) || $changes === []) return true;
  177. // update userinfo with new data, remembering to encrypt any password
  178. $newuser = $user;
  179. foreach ($changes as $field => $value) {
  180. if ($field == 'user') {
  181. $newuser = $value;
  182. continue;
  183. }
  184. if ($field == 'pass') $value = auth_cryptPassword($value);
  185. $userinfo[$field] = $value;
  186. }
  187. $userline = $this->createUserLine(
  188. $newuser,
  189. $userinfo['pass'],
  190. $userinfo['name'],
  191. $userinfo['mail'],
  192. $userinfo['grps']
  193. );
  194. if (!io_replaceInFile($config_cascade['plainauth.users']['default'], '/^' . $user . ':/', $userline, true)) {
  195. msg('There was an error modifying your user data. You may need to register again.', -1);
  196. // FIXME, io functions should be fail-safe so existing data isn't lost
  197. $ACT = 'register';
  198. return false;
  199. }
  200. if (isset($this->users[$user])) unset($this->users[$user]);
  201. $this->users[$newuser] = $userinfo;
  202. return true;
  203. }
  204. /**
  205. * Remove one or more users from the list of registered users
  206. *
  207. * @author Christopher Smith <chris@jalakai.co.uk>
  208. * @param array $users array of users to be deleted
  209. * @return int the number of users deleted
  210. */
  211. public function deleteUsers($users)
  212. {
  213. global $config_cascade;
  214. if (!is_array($users) || $users === []) return 0;
  215. if ($this->users === null) $this->loadUserData();
  216. $deleted = [];
  217. foreach ($users as $user) {
  218. // don't delete protected users
  219. if (!empty($this->users[$user]['protected'])) {
  220. msg(sprintf($this->getLang('protected'), hsc($user)), -1);
  221. continue;
  222. }
  223. if (isset($this->users[$user])) $deleted[] = preg_quote($user, '/');
  224. }
  225. if ($deleted === []) return 0;
  226. $pattern = '/^(' . implode('|', $deleted) . '):/';
  227. if (!io_deleteFromFile($config_cascade['plainauth.users']['default'], $pattern, true)) {
  228. msg($this->getLang('writefail'), -1);
  229. return 0;
  230. }
  231. // reload the user list and count the difference
  232. $count = count($this->users);
  233. $this->loadUserData();
  234. $count -= count($this->users);
  235. return $count;
  236. }
  237. /**
  238. * Return a count of the number of user which meet $filter criteria
  239. *
  240. * @author Chris Smith <chris@jalakai.co.uk>
  241. *
  242. * @param array $filter
  243. * @return int
  244. */
  245. public function getUserCount($filter = [])
  246. {
  247. if ($this->users === null) $this->loadUserData();
  248. if ($filter === []) return count($this->users);
  249. $count = 0;
  250. $this->constructPattern($filter);
  251. foreach ($this->users as $user => $info) {
  252. $count += $this->filter($user, $info);
  253. }
  254. return $count;
  255. }
  256. /**
  257. * Bulk retrieval of user data
  258. *
  259. * @author Chris Smith <chris@jalakai.co.uk>
  260. *
  261. * @param int $start index of first user to be returned
  262. * @param int $limit max number of users to be returned
  263. * @param array $filter array of field/pattern pairs
  264. * @return array userinfo (refer getUserData for internal userinfo details)
  265. */
  266. public function retrieveUsers($start = 0, $limit = 0, $filter = [])
  267. {
  268. if ($this->users === null) $this->loadUserData();
  269. Sort::ksort($this->users);
  270. $i = 0;
  271. $count = 0;
  272. $out = [];
  273. $this->constructPattern($filter);
  274. foreach ($this->users as $user => $info) {
  275. if ($this->filter($user, $info)) {
  276. if ($i >= $start) {
  277. $out[$user] = $info;
  278. $count++;
  279. if (($limit > 0) && ($count >= $limit)) break;
  280. }
  281. $i++;
  282. }
  283. }
  284. return $out;
  285. }
  286. /**
  287. * Retrieves groups.
  288. * Loads complete user data into memory before searching for groups.
  289. *
  290. * @param int $start index of first group to be returned
  291. * @param int $limit max number of groups to be returned
  292. * @return array
  293. */
  294. public function retrieveGroups($start = 0, $limit = 0)
  295. {
  296. $groups = [];
  297. if ($this->users === null) $this->loadUserData();
  298. foreach ($this->users as $info) {
  299. $groups = array_merge($groups, array_diff($info['grps'], $groups));
  300. }
  301. Sort::ksort($groups);
  302. if ($limit > 0) {
  303. return array_splice($groups, $start, $limit);
  304. }
  305. return array_splice($groups, $start);
  306. }
  307. /**
  308. * Only valid pageid's (no namespaces) for usernames
  309. *
  310. * @param string $user
  311. * @return string
  312. */
  313. public function cleanUser($user)
  314. {
  315. global $conf;
  316. return cleanID(str_replace([':', '/', ';'], $conf['sepchar'], $user));
  317. }
  318. /**
  319. * Only valid pageid's (no namespaces) for groupnames
  320. *
  321. * @param string $group
  322. * @return string
  323. */
  324. public function cleanGroup($group)
  325. {
  326. global $conf;
  327. return cleanID(str_replace([':', '/', ';'], $conf['sepchar'], $group));
  328. }
  329. /**
  330. * Load all user data
  331. *
  332. * loads the user file into a datastructure
  333. *
  334. * @author Andreas Gohr <andi@splitbrain.org>
  335. */
  336. protected function loadUserData()
  337. {
  338. global $config_cascade;
  339. $this->users = $this->readUserFile($config_cascade['plainauth.users']['default']);
  340. // support protected users
  341. if (!empty($config_cascade['plainauth.users']['protected'])) {
  342. $protected = $this->readUserFile($config_cascade['plainauth.users']['protected']);
  343. foreach (array_keys($protected) as $key) {
  344. $protected[$key]['protected'] = true;
  345. }
  346. $this->users = array_merge($this->users, $protected);
  347. }
  348. }
  349. /**
  350. * Read user data from given file
  351. *
  352. * ignores non existing files
  353. *
  354. * @param string $file the file to load data from
  355. * @return array
  356. */
  357. protected function readUserFile($file)
  358. {
  359. $users = [];
  360. if (!file_exists($file)) return $users;
  361. $lines = file($file);
  362. foreach ($lines as $line) {
  363. $line = preg_replace('/(?<!\\\\)#.*$/', '', $line); //ignore comments (unless escaped)
  364. $line = trim($line);
  365. if (empty($line)) continue;
  366. $row = $this->splitUserData($line);
  367. $row = str_replace('\\:', ':', $row);
  368. $row = str_replace('\\\\', '\\', $row);
  369. $row = str_replace('\\#', '#', $row);
  370. $groups = array_values(array_filter(explode(",", $row[4])));
  371. $users[$row[0]]['pass'] = $row[1];
  372. $users[$row[0]]['name'] = urldecode($row[2]);
  373. $users[$row[0]]['mail'] = $row[3];
  374. $users[$row[0]]['grps'] = $groups;
  375. }
  376. return $users;
  377. }
  378. /**
  379. * Get the user line split into it's parts
  380. *
  381. * @param string $line
  382. * @return string[]
  383. */
  384. protected function splitUserData($line)
  385. {
  386. $data = preg_split('/(?<![^\\\\]\\\\)\:/', $line, 5); // allow for : escaped as \:
  387. if (count($data) < 5) {
  388. $data = array_pad($data, 5, '');
  389. Logger::error('User line with less than 5 fields. Possibly corruption in your user file', $data);
  390. }
  391. return $data;
  392. }
  393. /**
  394. * return true if $user + $info match $filter criteria, false otherwise
  395. *
  396. * @author Chris Smith <chris@jalakai.co.uk>
  397. *
  398. * @param string $user User login
  399. * @param array $info User's userinfo array
  400. * @return bool
  401. */
  402. protected function filter($user, $info)
  403. {
  404. foreach ($this->pattern as $item => $pattern) {
  405. if ($item == 'user') {
  406. if (!preg_match($pattern, $user)) return false;
  407. } elseif ($item == 'grps') {
  408. if (!count(preg_grep($pattern, $info['grps']))) return false;
  409. } elseif (!preg_match($pattern, $info[$item])) {
  410. return false;
  411. }
  412. }
  413. return true;
  414. }
  415. /**
  416. * construct a filter pattern
  417. *
  418. * @param array $filter
  419. */
  420. protected function constructPattern($filter)
  421. {
  422. $this->pattern = [];
  423. foreach ($filter as $item => $pattern) {
  424. $this->pattern[$item] = '/' . str_replace('/', '\/', $pattern) . '/i'; // allow regex characters
  425. }
  426. }
  427. }