UsersController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Clark Tomlinson <fallen013@gmail.com>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Robin Appelman <robin@icewind.nl>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. * @author Vincent Petry <pvince81@owncloud.com>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OC\Settings\Controller;
  31. use OC\AppFramework\Http;
  32. use OC\User\User;
  33. use OCP\App\IAppManager;
  34. use OCP\AppFramework\Controller;
  35. use OCP\AppFramework\Http\DataResponse;
  36. use OCP\AppFramework\Http\TemplateResponse;
  37. use OCP\IConfig;
  38. use OCP\IGroupManager;
  39. use OCP\IL10N;
  40. use OCP\ILogger;
  41. use OCP\IRequest;
  42. use OCP\IURLGenerator;
  43. use OCP\IUser;
  44. use OCP\IUserManager;
  45. use OCP\IUserSession;
  46. use OCP\Mail\IMailer;
  47. use OCP\IAvatarManager;
  48. /**
  49. * @package OC\Settings\Controller
  50. */
  51. class UsersController extends Controller {
  52. /** @var IL10N */
  53. private $l10n;
  54. /** @var IUserSession */
  55. private $userSession;
  56. /** @var bool */
  57. private $isAdmin;
  58. /** @var IUserManager */
  59. private $userManager;
  60. /** @var IGroupManager */
  61. private $groupManager;
  62. /** @var IConfig */
  63. private $config;
  64. /** @var ILogger */
  65. private $log;
  66. /** @var \OC_Defaults */
  67. private $defaults;
  68. /** @var IMailer */
  69. private $mailer;
  70. /** @var string */
  71. private $fromMailAddress;
  72. /** @var IURLGenerator */
  73. private $urlGenerator;
  74. /** @var bool contains the state of the encryption app */
  75. private $isEncryptionAppEnabled;
  76. /** @var bool contains the state of the admin recovery setting */
  77. private $isRestoreEnabled = false;
  78. /** @var IAvatarManager */
  79. private $avatarManager;
  80. /**
  81. * @param string $appName
  82. * @param IRequest $request
  83. * @param IUserManager $userManager
  84. * @param IGroupManager $groupManager
  85. * @param IUserSession $userSession
  86. * @param IConfig $config
  87. * @param bool $isAdmin
  88. * @param IL10N $l10n
  89. * @param ILogger $log
  90. * @param \OC_Defaults $defaults
  91. * @param IMailer $mailer
  92. * @param string $fromMailAddress
  93. * @param IURLGenerator $urlGenerator
  94. * @param IAppManager $appManager
  95. * @param IAvatarManager $avatarManager
  96. */
  97. public function __construct($appName,
  98. IRequest $request,
  99. IUserManager $userManager,
  100. IGroupManager $groupManager,
  101. IUserSession $userSession,
  102. IConfig $config,
  103. $isAdmin,
  104. IL10N $l10n,
  105. ILogger $log,
  106. \OC_Defaults $defaults,
  107. IMailer $mailer,
  108. $fromMailAddress,
  109. IURLGenerator $urlGenerator,
  110. IAppManager $appManager,
  111. IAvatarManager $avatarManager) {
  112. parent::__construct($appName, $request);
  113. $this->userManager = $userManager;
  114. $this->groupManager = $groupManager;
  115. $this->userSession = $userSession;
  116. $this->config = $config;
  117. $this->isAdmin = $isAdmin;
  118. $this->l10n = $l10n;
  119. $this->log = $log;
  120. $this->defaults = $defaults;
  121. $this->mailer = $mailer;
  122. $this->fromMailAddress = $fromMailAddress;
  123. $this->urlGenerator = $urlGenerator;
  124. $this->avatarManager = $avatarManager;
  125. // check for encryption state - TODO see formatUserForIndex
  126. $this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
  127. if($this->isEncryptionAppEnabled) {
  128. // putting this directly in empty is possible in PHP 5.5+
  129. $result = $config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
  130. $this->isRestoreEnabled = !empty($result);
  131. }
  132. }
  133. /**
  134. * @param IUser $user
  135. * @param array $userGroups
  136. * @return array
  137. */
  138. private function formatUserForIndex(IUser $user, array $userGroups = null) {
  139. // TODO: eliminate this encryption specific code below and somehow
  140. // hook in additional user info from other apps
  141. // recovery isn't possible if admin or user has it disabled and encryption
  142. // is enabled - so we eliminate the else paths in the conditional tree
  143. // below
  144. $restorePossible = false;
  145. if ($this->isEncryptionAppEnabled) {
  146. if ($this->isRestoreEnabled) {
  147. // check for the users recovery setting
  148. $recoveryMode = $this->config->getUserValue($user->getUID(), 'encryption', 'recoveryEnabled', '0');
  149. // method call inside empty is possible with PHP 5.5+
  150. $recoveryModeEnabled = !empty($recoveryMode);
  151. if ($recoveryModeEnabled) {
  152. // user also has recovery mode enabled
  153. $restorePossible = true;
  154. }
  155. }
  156. } else {
  157. // recovery is possible if encryption is disabled (plain files are
  158. // available)
  159. $restorePossible = true;
  160. }
  161. $subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
  162. foreach($subAdminGroups as $key => $subAdminGroup) {
  163. $subAdminGroups[$key] = $subAdminGroup->getGID();
  164. }
  165. $displayName = $user->getEMailAddress();
  166. if (is_null($displayName)) {
  167. $displayName = '';
  168. }
  169. $avatarAvailable = false;
  170. if ($this->config->getSystemValue('enable_avatars', true) === true) {
  171. try {
  172. $avatarAvailable = $this->avatarManager->getAvatar($user->getUID())->exists();
  173. } catch (\Exception $e) {
  174. //No avatar yet
  175. }
  176. }
  177. return [
  178. 'name' => $user->getUID(),
  179. 'displayname' => $user->getDisplayName(),
  180. 'groups' => (empty($userGroups)) ? $this->groupManager->getUserGroupIds($user) : $userGroups,
  181. 'subadmin' => $subAdminGroups,
  182. 'quota' => $user->getQuota(),
  183. 'storageLocation' => $user->getHome(),
  184. 'lastLogin' => $user->getLastLogin() * 1000,
  185. 'backend' => $user->getBackendClassName(),
  186. 'email' => $displayName,
  187. 'isRestoreDisabled' => !$restorePossible,
  188. 'isAvatarAvailable' => $avatarAvailable,
  189. ];
  190. }
  191. /**
  192. * @param array $userIDs Array with schema [$uid => $displayName]
  193. * @return IUser[]
  194. */
  195. private function getUsersForUID(array $userIDs) {
  196. $users = [];
  197. foreach ($userIDs as $uid => $displayName) {
  198. $users[$uid] = $this->userManager->get($uid);
  199. }
  200. return $users;
  201. }
  202. /**
  203. * @NoAdminRequired
  204. *
  205. * @param int $offset
  206. * @param int $limit
  207. * @param string $gid GID to filter for
  208. * @param string $pattern Pattern to search for in the username
  209. * @param string $backend Backend to filter for (class-name)
  210. * @return DataResponse
  211. *
  212. * TODO: Tidy up and write unit tests - code is mainly static method calls
  213. */
  214. public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
  215. // FIXME: The JS sends the group '_everyone' instead of no GID for the "all users" group.
  216. if($gid === '_everyone') {
  217. $gid = '';
  218. }
  219. // Remove backends
  220. if(!empty($backend)) {
  221. $activeBackends = $this->userManager->getBackends();
  222. $this->userManager->clearBackends();
  223. foreach($activeBackends as $singleActiveBackend) {
  224. if($backend === get_class($singleActiveBackend)) {
  225. $this->userManager->registerBackend($singleActiveBackend);
  226. break;
  227. }
  228. }
  229. }
  230. $users = [];
  231. if ($this->isAdmin) {
  232. if($gid !== '') {
  233. $batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
  234. } else {
  235. $batch = $this->userManager->search($pattern, $limit, $offset);
  236. }
  237. foreach ($batch as $user) {
  238. $users[] = $this->formatUserForIndex($user);
  239. }
  240. } else {
  241. $subAdminOfGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
  242. // New class returns IGroup[] so convert back
  243. $gids = [];
  244. foreach ($subAdminOfGroups as $group) {
  245. $gids[] = $group->getGID();
  246. }
  247. $subAdminOfGroups = $gids;
  248. // Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
  249. if($gid !== '' && !in_array($gid, $subAdminOfGroups)) {
  250. $gid = '';
  251. }
  252. // Batch all groups the user is subadmin of when a group is specified
  253. $batch = [];
  254. if($gid === '') {
  255. foreach($subAdminOfGroups as $group) {
  256. $groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
  257. foreach($groupUsers as $uid => $displayName) {
  258. $batch[$uid] = $displayName;
  259. }
  260. }
  261. } else {
  262. $batch = $this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset);
  263. }
  264. $batch = $this->getUsersForUID($batch);
  265. foreach ($batch as $user) {
  266. // Only add the groups, this user is a subadmin of
  267. $userGroups = array_values(array_intersect(
  268. $this->groupManager->getUserGroupIds($user),
  269. $subAdminOfGroups
  270. ));
  271. $users[] = $this->formatUserForIndex($user, $userGroups);
  272. }
  273. }
  274. return new DataResponse($users);
  275. }
  276. /**
  277. * @NoAdminRequired
  278. *
  279. * @param string $username
  280. * @param string $password
  281. * @param array $groups
  282. * @param string $email
  283. * @return DataResponse
  284. */
  285. public function create($username, $password, array $groups=array(), $email='') {
  286. if($email !== '' && !$this->mailer->validateMailAddress($email)) {
  287. return new DataResponse(
  288. array(
  289. 'message' => (string)$this->l10n->t('Invalid mail address')
  290. ),
  291. Http::STATUS_UNPROCESSABLE_ENTITY
  292. );
  293. }
  294. $currentUser = $this->userSession->getUser();
  295. if (!$this->isAdmin) {
  296. if (!empty($groups)) {
  297. foreach ($groups as $key => $group) {
  298. $groupObject = $this->groupManager->get($group);
  299. if($groupObject === null) {
  300. unset($groups[$key]);
  301. continue;
  302. }
  303. if (!$this->groupManager->getSubAdmin()->isSubAdminofGroup($currentUser, $groupObject)) {
  304. unset($groups[$key]);
  305. }
  306. }
  307. }
  308. if (empty($groups)) {
  309. $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($currentUser);
  310. // New class returns IGroup[] so convert back
  311. $gids = [];
  312. foreach ($groups as $group) {
  313. $gids[] = $group->getGID();
  314. }
  315. $groups = $gids;
  316. }
  317. }
  318. if ($this->userManager->userExists($username)) {
  319. return new DataResponse(
  320. array(
  321. 'message' => (string)$this->l10n->t('A user with that name already exists.')
  322. ),
  323. Http::STATUS_CONFLICT
  324. );
  325. }
  326. try {
  327. $user = $this->userManager->createUser($username, $password);
  328. } catch (\Exception $exception) {
  329. $message = $exception->getMessage();
  330. if (!$message) {
  331. $message = $this->l10n->t('Unable to create user.');
  332. }
  333. return new DataResponse(
  334. array(
  335. 'message' => (string) $message,
  336. ),
  337. Http::STATUS_FORBIDDEN
  338. );
  339. }
  340. if($user instanceof User) {
  341. if($groups !== null) {
  342. foreach($groups as $groupName) {
  343. $group = $this->groupManager->get($groupName);
  344. if(empty($group)) {
  345. $group = $this->groupManager->createGroup($groupName);
  346. }
  347. $group->addUser($user);
  348. }
  349. }
  350. /**
  351. * Send new user mail only if a mail is set
  352. */
  353. if($email !== '') {
  354. $user->setEMailAddress($email);
  355. // data for the mail template
  356. $mailData = array(
  357. 'username' => $username,
  358. 'url' => $this->urlGenerator->getAbsoluteURL('/')
  359. );
  360. $mail = new TemplateResponse('settings', 'email.new_user', $mailData, 'blank');
  361. $mailContent = $mail->render();
  362. $mail = new TemplateResponse('settings', 'email.new_user_plain_text', $mailData, 'blank');
  363. $plainTextMailContent = $mail->render();
  364. $subject = $this->l10n->t('Your %s account was created', [$this->defaults->getName()]);
  365. try {
  366. $message = $this->mailer->createMessage();
  367. $message->setTo([$email => $username]);
  368. $message->setSubject($subject);
  369. $message->setHtmlBody($mailContent);
  370. $message->setPlainBody($plainTextMailContent);
  371. $message->setFrom([$this->fromMailAddress => $this->defaults->getName()]);
  372. $this->mailer->send($message);
  373. } catch(\Exception $e) {
  374. $this->log->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
  375. }
  376. }
  377. // fetch users groups
  378. $userGroups = $this->groupManager->getUserGroupIds($user);
  379. return new DataResponse(
  380. $this->formatUserForIndex($user, $userGroups),
  381. Http::STATUS_CREATED
  382. );
  383. }
  384. return new DataResponse(
  385. array(
  386. 'message' => (string)$this->l10n->t('Unable to create user.')
  387. ),
  388. Http::STATUS_FORBIDDEN
  389. );
  390. }
  391. /**
  392. * @NoAdminRequired
  393. *
  394. * @param string $id
  395. * @return DataResponse
  396. */
  397. public function destroy($id) {
  398. $userId = $this->userSession->getUser()->getUID();
  399. $user = $this->userManager->get($id);
  400. if($userId === $id) {
  401. return new DataResponse(
  402. array(
  403. 'status' => 'error',
  404. 'data' => array(
  405. 'message' => (string)$this->l10n->t('Unable to delete user.')
  406. )
  407. ),
  408. Http::STATUS_FORBIDDEN
  409. );
  410. }
  411. if(!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
  412. return new DataResponse(
  413. array(
  414. 'status' => 'error',
  415. 'data' => array(
  416. 'message' => (string)$this->l10n->t('Authentication error')
  417. )
  418. ),
  419. Http::STATUS_FORBIDDEN
  420. );
  421. }
  422. if($user) {
  423. if($user->delete()) {
  424. return new DataResponse(
  425. array(
  426. 'status' => 'success',
  427. 'data' => array(
  428. 'username' => $id
  429. )
  430. ),
  431. Http::STATUS_NO_CONTENT
  432. );
  433. }
  434. }
  435. return new DataResponse(
  436. array(
  437. 'status' => 'error',
  438. 'data' => array(
  439. 'message' => (string)$this->l10n->t('Unable to delete user.')
  440. )
  441. ),
  442. Http::STATUS_FORBIDDEN
  443. );
  444. }
  445. /**
  446. * Set the mail address of a user
  447. *
  448. * @NoAdminRequired
  449. * @NoSubadminRequired
  450. *
  451. * @param string $id
  452. * @param string $mailAddress
  453. * @return DataResponse
  454. */
  455. public function setMailAddress($id, $mailAddress) {
  456. $userId = $this->userSession->getUser()->getUID();
  457. $user = $this->userManager->get($id);
  458. if($userId !== $id
  459. && !$this->isAdmin
  460. && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
  461. return new DataResponse(
  462. array(
  463. 'status' => 'error',
  464. 'data' => array(
  465. 'message' => (string)$this->l10n->t('Forbidden')
  466. )
  467. ),
  468. Http::STATUS_FORBIDDEN
  469. );
  470. }
  471. if($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
  472. return new DataResponse(
  473. array(
  474. 'status' => 'error',
  475. 'data' => array(
  476. 'message' => (string)$this->l10n->t('Invalid mail address')
  477. )
  478. ),
  479. Http::STATUS_UNPROCESSABLE_ENTITY
  480. );
  481. }
  482. if(!$user){
  483. return new DataResponse(
  484. array(
  485. 'status' => 'error',
  486. 'data' => array(
  487. 'message' => (string)$this->l10n->t('Invalid user')
  488. )
  489. ),
  490. Http::STATUS_UNPROCESSABLE_ENTITY
  491. );
  492. }
  493. // this is the only permission a backend provides and is also used
  494. // for the permission of setting a email address
  495. if(!$user->canChangeDisplayName()){
  496. return new DataResponse(
  497. array(
  498. 'status' => 'error',
  499. 'data' => array(
  500. 'message' => (string)$this->l10n->t('Unable to change mail address')
  501. )
  502. ),
  503. Http::STATUS_FORBIDDEN
  504. );
  505. }
  506. // delete user value if email address is empty
  507. $user->setEMailAddress($mailAddress);
  508. return new DataResponse(
  509. array(
  510. 'status' => 'success',
  511. 'data' => array(
  512. 'username' => $id,
  513. 'mailAddress' => $mailAddress,
  514. 'message' => (string)$this->l10n->t('Email saved')
  515. )
  516. ),
  517. Http::STATUS_OK
  518. );
  519. }
  520. /**
  521. * Count all unique users visible for the current admin/subadmin.
  522. *
  523. * @NoAdminRequired
  524. *
  525. * @return DataResponse
  526. */
  527. public function stats() {
  528. $userCount = 0;
  529. if ($this->isAdmin) {
  530. $countByBackend = $this->userManager->countUsers();
  531. if (!empty($countByBackend)) {
  532. foreach ($countByBackend as $count) {
  533. $userCount += $count;
  534. }
  535. }
  536. } else {
  537. $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
  538. $uniqueUsers = [];
  539. foreach ($groups as $group) {
  540. foreach($group->getUsers() as $uid => $displayName) {
  541. $uniqueUsers[$uid] = true;
  542. }
  543. }
  544. $userCount = count($uniqueUsers);
  545. }
  546. return new DataResponse(
  547. [
  548. 'totalUsers' => $userCount
  549. ]
  550. );
  551. }
  552. /**
  553. * Set the displayName of a user
  554. *
  555. * @NoAdminRequired
  556. * @NoSubadminRequired
  557. *
  558. * @param string $username
  559. * @param string $displayName
  560. * @return DataResponse
  561. */
  562. public function setDisplayName($username, $displayName) {
  563. $currentUser = $this->userSession->getUser();
  564. if ($username === null) {
  565. $username = $currentUser->getUID();
  566. }
  567. $user = $this->userManager->get($username);
  568. if ($user === null ||
  569. !$user->canChangeDisplayName() ||
  570. (
  571. !$this->groupManager->isAdmin($currentUser->getUID()) &&
  572. !$this->groupManager->getSubAdmin()->isUserAccessible($currentUser, $user) &&
  573. $currentUser !== $user)
  574. ) {
  575. return new DataResponse([
  576. 'status' => 'error',
  577. 'data' => [
  578. 'message' => $this->l10n->t('Authentication error'),
  579. ],
  580. ]);
  581. }
  582. if ($user->setDisplayName($displayName)) {
  583. return new DataResponse([
  584. 'status' => 'success',
  585. 'data' => [
  586. 'message' => $this->l10n->t('Your full name has been changed.'),
  587. 'username' => $username,
  588. 'displayName' => $displayName,
  589. ],
  590. ]);
  591. } else {
  592. return new DataResponse([
  593. 'status' => 'error',
  594. 'data' => [
  595. 'message' => $this->l10n->t('Unable to change full name'),
  596. 'displayName' => $user->getDisplayName(),
  597. ],
  598. ]);
  599. }
  600. }
  601. }