manager.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Joas Schilling <coding@schilljs.com>
  7. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Michael U <mdusher@users.noreply.github.com>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Robin Appelman <robin@icewind.nl>
  12. * @author Robin McCorkell <robin@mccorkell.me.uk>
  13. * @author Thomas Müller <thomas.mueller@tmit.eu>
  14. * @author Vincent Chan <plus.vincchan@gmail.com>
  15. * @author Volkan Gezer <volkangezer@gmail.com>
  16. *
  17. * @license AGPL-3.0
  18. *
  19. * This code is free software: you can redistribute it and/or modify
  20. * it under the terms of the GNU Affero General Public License, version 3,
  21. * as published by the Free Software Foundation.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU Affero General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU Affero General Public License, version 3,
  29. * along with this program. If not, see <http://www.gnu.org/licenses/>
  30. *
  31. */
  32. namespace OC\User;
  33. use OC\Hooks\PublicEmitter;
  34. use OCP\IUserBackend;
  35. use OCP\IUserManager;
  36. use OCP\IConfig;
  37. /**
  38. * Class Manager
  39. *
  40. * Hooks available in scope \OC\User:
  41. * - preSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
  42. * - postSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
  43. * - preDelete(\OC\User\User $user)
  44. * - postDelete(\OC\User\User $user)
  45. * - preCreateUser(string $uid, string $password)
  46. * - postCreateUser(\OC\User\User $user, string $password)
  47. * - change(\OC\User\User $user)
  48. *
  49. * @package OC\User
  50. */
  51. class Manager extends PublicEmitter implements IUserManager {
  52. /**
  53. * @var \OCP\UserInterface[] $backends
  54. */
  55. private $backends = array();
  56. /**
  57. * @var \OC\User\User[] $cachedUsers
  58. */
  59. private $cachedUsers = array();
  60. /**
  61. * @var \OCP\IConfig $config
  62. */
  63. private $config;
  64. /**
  65. * @param \OCP\IConfig $config
  66. */
  67. public function __construct(IConfig $config = null) {
  68. $this->config = $config;
  69. $cachedUsers = &$this->cachedUsers;
  70. $this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) {
  71. /** @var \OC\User\User $user */
  72. unset($cachedUsers[$user->getUID()]);
  73. });
  74. $this->listen('\OC\User', 'postLogin', function ($user) {
  75. /** @var \OC\User\User $user */
  76. $user->updateLastLoginTimestamp();
  77. });
  78. $this->listen('\OC\User', 'postRememberedLogin', function ($user) {
  79. /** @var \OC\User\User $user */
  80. $user->updateLastLoginTimestamp();
  81. });
  82. }
  83. /**
  84. * Get the active backends
  85. * @return \OCP\UserInterface[]
  86. */
  87. public function getBackends() {
  88. return $this->backends;
  89. }
  90. /**
  91. * register a user backend
  92. *
  93. * @param \OCP\UserInterface $backend
  94. */
  95. public function registerBackend($backend) {
  96. $this->backends[] = $backend;
  97. }
  98. /**
  99. * remove a user backend
  100. *
  101. * @param \OCP\UserInterface $backend
  102. */
  103. public function removeBackend($backend) {
  104. $this->cachedUsers = array();
  105. if (($i = array_search($backend, $this->backends)) !== false) {
  106. unset($this->backends[$i]);
  107. }
  108. }
  109. /**
  110. * remove all user backends
  111. */
  112. public function clearBackends() {
  113. $this->cachedUsers = array();
  114. $this->backends = array();
  115. }
  116. /**
  117. * get a user by user id
  118. *
  119. * @param string $uid
  120. * @return \OC\User\User|null Either the user or null if the specified user does not exist
  121. */
  122. public function get($uid) {
  123. if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends
  124. return $this->cachedUsers[$uid];
  125. }
  126. foreach ($this->backends as $backend) {
  127. if ($backend->userExists($uid)) {
  128. return $this->getUserObject($uid, $backend);
  129. }
  130. }
  131. return null;
  132. }
  133. /**
  134. * get or construct the user object
  135. *
  136. * @param string $uid
  137. * @param \OCP\UserInterface $backend
  138. * @param bool $cacheUser If false the newly created user object will not be cached
  139. * @return \OC\User\User
  140. */
  141. protected function getUserObject($uid, $backend, $cacheUser = true) {
  142. if (isset($this->cachedUsers[$uid])) {
  143. return $this->cachedUsers[$uid];
  144. }
  145. if (method_exists($backend, 'loginName2UserName')) {
  146. $loginName = $backend->loginName2UserName($uid);
  147. if ($loginName !== false) {
  148. $uid = $loginName;
  149. }
  150. if (isset($this->cachedUsers[$uid])) {
  151. return $this->cachedUsers[$uid];
  152. }
  153. }
  154. $user = new User($uid, $backend, $this, $this->config);
  155. if ($cacheUser) {
  156. $this->cachedUsers[$uid] = $user;
  157. }
  158. return $user;
  159. }
  160. /**
  161. * check if a user exists
  162. *
  163. * @param string $uid
  164. * @return bool
  165. */
  166. public function userExists($uid) {
  167. $user = $this->get($uid);
  168. return ($user !== null);
  169. }
  170. /**
  171. * Check if the password is valid for the user
  172. *
  173. * @param string $loginName
  174. * @param string $password
  175. * @return mixed the User object on success, false otherwise
  176. */
  177. public function checkPassword($loginName, $password) {
  178. $loginName = str_replace("\0", '', $loginName);
  179. $password = str_replace("\0", '', $password);
  180. foreach ($this->backends as $backend) {
  181. if ($backend->implementsActions(\OC_User_Backend::CHECK_PASSWORD)) {
  182. $uid = $backend->checkPassword($loginName, $password);
  183. if ($uid !== false) {
  184. return $this->getUserObject($uid, $backend);
  185. }
  186. }
  187. }
  188. \OC::$server->getLogger()->warning('Login failed: \''. $loginName .'\' (Remote IP: \''. \OC::$server->getRequest()->getRemoteAddress(). '\')', ['app' => 'core']);
  189. return false;
  190. }
  191. /**
  192. * search by user id
  193. *
  194. * @param string $pattern
  195. * @param int $limit
  196. * @param int $offset
  197. * @return \OC\User\User[]
  198. */
  199. public function search($pattern, $limit = null, $offset = null) {
  200. $users = array();
  201. foreach ($this->backends as $backend) {
  202. $backendUsers = $backend->getUsers($pattern, $limit, $offset);
  203. if (is_array($backendUsers)) {
  204. foreach ($backendUsers as $uid) {
  205. $users[$uid] = $this->getUserObject($uid, $backend);
  206. }
  207. }
  208. }
  209. uasort($users, function ($a, $b) {
  210. /**
  211. * @var \OC\User\User $a
  212. * @var \OC\User\User $b
  213. */
  214. return strcmp($a->getUID(), $b->getUID());
  215. });
  216. return $users;
  217. }
  218. /**
  219. * search by displayName
  220. *
  221. * @param string $pattern
  222. * @param int $limit
  223. * @param int $offset
  224. * @return \OC\User\User[]
  225. */
  226. public function searchDisplayName($pattern, $limit = null, $offset = null) {
  227. $users = array();
  228. foreach ($this->backends as $backend) {
  229. $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
  230. if (is_array($backendUsers)) {
  231. foreach ($backendUsers as $uid => $displayName) {
  232. $users[] = $this->getUserObject($uid, $backend);
  233. }
  234. }
  235. }
  236. usort($users, function ($a, $b) {
  237. /**
  238. * @var \OC\User\User $a
  239. * @var \OC\User\User $b
  240. */
  241. return strcmp($a->getDisplayName(), $b->getDisplayName());
  242. });
  243. return $users;
  244. }
  245. /**
  246. * @param string $uid
  247. * @param string $password
  248. * @throws \Exception
  249. * @return bool|\OC\User\User the created user or false
  250. */
  251. public function createUser($uid, $password) {
  252. $l = \OC::$server->getL10N('lib');
  253. // Check the name for bad characters
  254. // Allowed are: "a-z", "A-Z", "0-9" and "_.@-'"
  255. if (preg_match('/[^a-zA-Z0-9 _\.@\-\']/', $uid)) {
  256. throw new \Exception($l->t('Only the following characters are allowed in a username:'
  257. . ' "a-z", "A-Z", "0-9", and "_.@-\'"'));
  258. }
  259. // No empty username
  260. if (trim($uid) == '') {
  261. throw new \Exception($l->t('A valid username must be provided'));
  262. }
  263. // No whitespace at the beginning or at the end
  264. if (strlen(trim($uid, "\t\n\r\0\x0B\xe2\x80\x8b")) !== strlen(trim($uid))) {
  265. throw new \Exception($l->t('Username contains whitespace at the beginning or at the end'));
  266. }
  267. // No empty password
  268. if (trim($password) == '') {
  269. throw new \Exception($l->t('A valid password must be provided'));
  270. }
  271. // Check if user already exists
  272. if ($this->userExists($uid)) {
  273. throw new \Exception($l->t('The username is already being used'));
  274. }
  275. $this->emit('\OC\User', 'preCreateUser', array($uid, $password));
  276. foreach ($this->backends as $backend) {
  277. if ($backend->implementsActions(\OC_User_Backend::CREATE_USER)) {
  278. $backend->createUser($uid, $password);
  279. $user = $this->getUserObject($uid, $backend);
  280. $this->emit('\OC\User', 'postCreateUser', array($user, $password));
  281. return $user;
  282. }
  283. }
  284. return false;
  285. }
  286. /**
  287. * returns how many users per backend exist (if supported by backend)
  288. *
  289. * @return array an array of backend class as key and count number as value
  290. */
  291. public function countUsers() {
  292. $userCountStatistics = array();
  293. foreach ($this->backends as $backend) {
  294. if ($backend->implementsActions(\OC_User_Backend::COUNT_USERS)) {
  295. $backendUsers = $backend->countUsers();
  296. if($backendUsers !== false) {
  297. if($backend instanceof IUserBackend) {
  298. $name = $backend->getBackendName();
  299. } else {
  300. $name = get_class($backend);
  301. }
  302. if(isset($userCountStatistics[$name])) {
  303. $userCountStatistics[$name] += $backendUsers;
  304. } else {
  305. $userCountStatistics[$name] = $backendUsers;
  306. }
  307. }
  308. }
  309. }
  310. return $userCountStatistics;
  311. }
  312. /**
  313. * The callback is executed for each user on each backend.
  314. * If the callback returns false no further users will be retrieved.
  315. *
  316. * @param \Closure $callback
  317. * @param string $search
  318. * @since 9.0.0
  319. */
  320. public function callForAllUsers(\Closure $callback, $search = '') {
  321. foreach($this->getBackends() as $backend) {
  322. $limit = 500;
  323. $offset = 0;
  324. do {
  325. $users = $backend->getUsers($search, $limit, $offset);
  326. foreach ($users as $uid) {
  327. if (!$backend->userExists($uid)) {
  328. continue;
  329. }
  330. $user = $this->getUserObject($uid, $backend, false);
  331. $return = $callback($user);
  332. if ($return === false) {
  333. break;
  334. }
  335. }
  336. $offset += $limit;
  337. } while (count($users) >= $limit);
  338. }
  339. }
  340. }