UsersController.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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\Accounts\AccountManager;
  32. use OC\AppFramework\Http;
  33. use OC\ForbiddenException;
  34. use OC\User\User;
  35. use OCP\App\IAppManager;
  36. use OCP\AppFramework\Controller;
  37. use OCP\AppFramework\Http\DataResponse;
  38. use OCP\AppFramework\Http\TemplateResponse;
  39. use OCP\IConfig;
  40. use OCP\IGroupManager;
  41. use OCP\IL10N;
  42. use OCP\ILogger;
  43. use OCP\IRequest;
  44. use OCP\IURLGenerator;
  45. use OCP\IUser;
  46. use OCP\IUserManager;
  47. use OCP\IUserSession;
  48. use OCP\Mail\IMailer;
  49. use OCP\IAvatarManager;
  50. use Punic\Exception;
  51. /**
  52. * @package OC\Settings\Controller
  53. */
  54. class UsersController extends Controller {
  55. /** @var IL10N */
  56. private $l10n;
  57. /** @var IUserSession */
  58. private $userSession;
  59. /** @var bool */
  60. private $isAdmin;
  61. /** @var IUserManager */
  62. private $userManager;
  63. /** @var IGroupManager */
  64. private $groupManager;
  65. /** @var IConfig */
  66. private $config;
  67. /** @var ILogger */
  68. private $log;
  69. /** @var \OC_Defaults */
  70. private $defaults;
  71. /** @var IMailer */
  72. private $mailer;
  73. /** @var string */
  74. private $fromMailAddress;
  75. /** @var IURLGenerator */
  76. private $urlGenerator;
  77. /** @var bool contains the state of the encryption app */
  78. private $isEncryptionAppEnabled;
  79. /** @var bool contains the state of the admin recovery setting */
  80. private $isRestoreEnabled = false;
  81. /** @var IAvatarManager */
  82. private $avatarManager;
  83. /** @var AccountManager */
  84. private $accountManager;
  85. /**
  86. * @param string $appName
  87. * @param IRequest $request
  88. * @param IUserManager $userManager
  89. * @param IGroupManager $groupManager
  90. * @param IUserSession $userSession
  91. * @param IConfig $config
  92. * @param bool $isAdmin
  93. * @param IL10N $l10n
  94. * @param ILogger $log
  95. * @param \OC_Defaults $defaults
  96. * @param IMailer $mailer
  97. * @param string $fromMailAddress
  98. * @param IURLGenerator $urlGenerator
  99. * @param IAppManager $appManager
  100. * @param IAvatarManager $avatarManager
  101. * @param AccountManager $accountManager
  102. */
  103. public function __construct($appName,
  104. IRequest $request,
  105. IUserManager $userManager,
  106. IGroupManager $groupManager,
  107. IUserSession $userSession,
  108. IConfig $config,
  109. $isAdmin,
  110. IL10N $l10n,
  111. ILogger $log,
  112. \OC_Defaults $defaults,
  113. IMailer $mailer,
  114. $fromMailAddress,
  115. IURLGenerator $urlGenerator,
  116. IAppManager $appManager,
  117. IAvatarManager $avatarManager,
  118. AccountManager $accountManager
  119. ) {
  120. parent::__construct($appName, $request);
  121. $this->userManager = $userManager;
  122. $this->groupManager = $groupManager;
  123. $this->userSession = $userSession;
  124. $this->config = $config;
  125. $this->isAdmin = $isAdmin;
  126. $this->l10n = $l10n;
  127. $this->log = $log;
  128. $this->defaults = $defaults;
  129. $this->mailer = $mailer;
  130. $this->fromMailAddress = $fromMailAddress;
  131. $this->urlGenerator = $urlGenerator;
  132. $this->avatarManager = $avatarManager;
  133. $this->accountManager = $accountManager;
  134. // check for encryption state - TODO see formatUserForIndex
  135. $this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
  136. if($this->isEncryptionAppEnabled) {
  137. // putting this directly in empty is possible in PHP 5.5+
  138. $result = $config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
  139. $this->isRestoreEnabled = !empty($result);
  140. }
  141. }
  142. /**
  143. * @param IUser $user
  144. * @param array $userGroups
  145. * @return array
  146. */
  147. private function formatUserForIndex(IUser $user, array $userGroups = null) {
  148. // TODO: eliminate this encryption specific code below and somehow
  149. // hook in additional user info from other apps
  150. // recovery isn't possible if admin or user has it disabled and encryption
  151. // is enabled - so we eliminate the else paths in the conditional tree
  152. // below
  153. $restorePossible = false;
  154. if ($this->isEncryptionAppEnabled) {
  155. if ($this->isRestoreEnabled) {
  156. // check for the users recovery setting
  157. $recoveryMode = $this->config->getUserValue($user->getUID(), 'encryption', 'recoveryEnabled', '0');
  158. // method call inside empty is possible with PHP 5.5+
  159. $recoveryModeEnabled = !empty($recoveryMode);
  160. if ($recoveryModeEnabled) {
  161. // user also has recovery mode enabled
  162. $restorePossible = true;
  163. }
  164. }
  165. } else {
  166. // recovery is possible if encryption is disabled (plain files are
  167. // available)
  168. $restorePossible = true;
  169. }
  170. $subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
  171. foreach($subAdminGroups as $key => $subAdminGroup) {
  172. $subAdminGroups[$key] = $subAdminGroup->getGID();
  173. }
  174. $displayName = $user->getEMailAddress();
  175. if (is_null($displayName)) {
  176. $displayName = '';
  177. }
  178. $avatarAvailable = false;
  179. if ($this->config->getSystemValue('enable_avatars', true) === true) {
  180. try {
  181. $avatarAvailable = $this->avatarManager->getAvatar($user->getUID())->exists();
  182. } catch (\Exception $e) {
  183. //No avatar yet
  184. }
  185. }
  186. return [
  187. 'name' => $user->getUID(),
  188. 'displayname' => $user->getDisplayName(),
  189. 'groups' => (empty($userGroups)) ? $this->groupManager->getUserGroupIds($user) : $userGroups,
  190. 'subadmin' => $subAdminGroups,
  191. 'quota' => $user->getQuota(),
  192. 'storageLocation' => $user->getHome(),
  193. 'lastLogin' => $user->getLastLogin() * 1000,
  194. 'backend' => $user->getBackendClassName(),
  195. 'email' => $displayName,
  196. 'isRestoreDisabled' => !$restorePossible,
  197. 'isAvatarAvailable' => $avatarAvailable,
  198. ];
  199. }
  200. /**
  201. * @param array $userIDs Array with schema [$uid => $displayName]
  202. * @return IUser[]
  203. */
  204. private function getUsersForUID(array $userIDs) {
  205. $users = [];
  206. foreach ($userIDs as $uid => $displayName) {
  207. $users[$uid] = $this->userManager->get($uid);
  208. }
  209. return $users;
  210. }
  211. /**
  212. * @NoAdminRequired
  213. *
  214. * @param int $offset
  215. * @param int $limit
  216. * @param string $gid GID to filter for
  217. * @param string $pattern Pattern to search for in the username
  218. * @param string $backend Backend to filter for (class-name)
  219. * @return DataResponse
  220. *
  221. * TODO: Tidy up and write unit tests - code is mainly static method calls
  222. */
  223. public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
  224. // FIXME: The JS sends the group '_everyone' instead of no GID for the "all users" group.
  225. if($gid === '_everyone') {
  226. $gid = '';
  227. }
  228. // Remove backends
  229. if(!empty($backend)) {
  230. $activeBackends = $this->userManager->getBackends();
  231. $this->userManager->clearBackends();
  232. foreach($activeBackends as $singleActiveBackend) {
  233. if($backend === get_class($singleActiveBackend)) {
  234. $this->userManager->registerBackend($singleActiveBackend);
  235. break;
  236. }
  237. }
  238. }
  239. $users = [];
  240. if ($this->isAdmin) {
  241. if($gid !== '') {
  242. $batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
  243. } else {
  244. $batch = $this->userManager->search($pattern, $limit, $offset);
  245. }
  246. foreach ($batch as $user) {
  247. $users[] = $this->formatUserForIndex($user);
  248. }
  249. } else {
  250. $subAdminOfGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
  251. // New class returns IGroup[] so convert back
  252. $gids = [];
  253. foreach ($subAdminOfGroups as $group) {
  254. $gids[] = $group->getGID();
  255. }
  256. $subAdminOfGroups = $gids;
  257. // Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
  258. if($gid !== '' && !in_array($gid, $subAdminOfGroups)) {
  259. $gid = '';
  260. }
  261. // Batch all groups the user is subadmin of when a group is specified
  262. $batch = [];
  263. if($gid === '') {
  264. foreach($subAdminOfGroups as $group) {
  265. $groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
  266. foreach($groupUsers as $uid => $displayName) {
  267. $batch[$uid] = $displayName;
  268. }
  269. }
  270. } else {
  271. $batch = $this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset);
  272. }
  273. $batch = $this->getUsersForUID($batch);
  274. foreach ($batch as $user) {
  275. // Only add the groups, this user is a subadmin of
  276. $userGroups = array_values(array_intersect(
  277. $this->groupManager->getUserGroupIds($user),
  278. $subAdminOfGroups
  279. ));
  280. $users[] = $this->formatUserForIndex($user, $userGroups);
  281. }
  282. }
  283. return new DataResponse($users);
  284. }
  285. /**
  286. * @NoAdminRequired
  287. * @PasswordConfirmationRequired
  288. *
  289. * @param string $username
  290. * @param string $password
  291. * @param array $groups
  292. * @param string $email
  293. * @return DataResponse
  294. */
  295. public function create($username, $password, array $groups=array(), $email='') {
  296. if($email !== '' && !$this->mailer->validateMailAddress($email)) {
  297. return new DataResponse(
  298. array(
  299. 'message' => (string)$this->l10n->t('Invalid mail address')
  300. ),
  301. Http::STATUS_UNPROCESSABLE_ENTITY
  302. );
  303. }
  304. $currentUser = $this->userSession->getUser();
  305. if (!$this->isAdmin) {
  306. if (!empty($groups)) {
  307. foreach ($groups as $key => $group) {
  308. $groupObject = $this->groupManager->get($group);
  309. if($groupObject === null) {
  310. unset($groups[$key]);
  311. continue;
  312. }
  313. if (!$this->groupManager->getSubAdmin()->isSubAdminofGroup($currentUser, $groupObject)) {
  314. unset($groups[$key]);
  315. }
  316. }
  317. }
  318. if (empty($groups)) {
  319. $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($currentUser);
  320. // New class returns IGroup[] so convert back
  321. $gids = [];
  322. foreach ($groups as $group) {
  323. $gids[] = $group->getGID();
  324. }
  325. $groups = $gids;
  326. }
  327. }
  328. if ($this->userManager->userExists($username)) {
  329. return new DataResponse(
  330. array(
  331. 'message' => (string)$this->l10n->t('A user with that name already exists.')
  332. ),
  333. Http::STATUS_CONFLICT
  334. );
  335. }
  336. try {
  337. $user = $this->userManager->createUser($username, $password);
  338. } catch (\Exception $exception) {
  339. $message = $exception->getMessage();
  340. if (!$message) {
  341. $message = $this->l10n->t('Unable to create user.');
  342. }
  343. return new DataResponse(
  344. array(
  345. 'message' => (string) $message,
  346. ),
  347. Http::STATUS_FORBIDDEN
  348. );
  349. }
  350. if($user instanceof User) {
  351. if($groups !== null) {
  352. foreach($groups as $groupName) {
  353. $group = $this->groupManager->get($groupName);
  354. if(empty($group)) {
  355. $group = $this->groupManager->createGroup($groupName);
  356. }
  357. $group->addUser($user);
  358. }
  359. }
  360. /**
  361. * Send new user mail only if a mail is set
  362. */
  363. if($email !== '') {
  364. $user->setEMailAddress($email);
  365. // data for the mail template
  366. $mailData = array(
  367. 'username' => $username,
  368. 'url' => $this->urlGenerator->getAbsoluteURL('/')
  369. );
  370. $mail = new TemplateResponse('settings', 'email.new_user', $mailData, 'blank');
  371. $mailContent = $mail->render();
  372. $mail = new TemplateResponse('settings', 'email.new_user_plain_text', $mailData, 'blank');
  373. $plainTextMailContent = $mail->render();
  374. $subject = $this->l10n->t('Your %s account was created', [$this->defaults->getName()]);
  375. try {
  376. $message = $this->mailer->createMessage();
  377. $message->setTo([$email => $username]);
  378. $message->setSubject($subject);
  379. $message->setHtmlBody($mailContent);
  380. $message->setPlainBody($plainTextMailContent);
  381. $message->setFrom([$this->fromMailAddress => $this->defaults->getName()]);
  382. $this->mailer->send($message);
  383. } catch(\Exception $e) {
  384. $this->log->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
  385. }
  386. }
  387. // fetch users groups
  388. $userGroups = $this->groupManager->getUserGroupIds($user);
  389. return new DataResponse(
  390. $this->formatUserForIndex($user, $userGroups),
  391. Http::STATUS_CREATED
  392. );
  393. }
  394. return new DataResponse(
  395. array(
  396. 'message' => (string)$this->l10n->t('Unable to create user.')
  397. ),
  398. Http::STATUS_FORBIDDEN
  399. );
  400. }
  401. /**
  402. * @NoAdminRequired
  403. * @PasswordConfirmationRequired
  404. *
  405. * @param string $id
  406. * @return DataResponse
  407. */
  408. public function destroy($id) {
  409. $userId = $this->userSession->getUser()->getUID();
  410. $user = $this->userManager->get($id);
  411. if($userId === $id) {
  412. return new DataResponse(
  413. array(
  414. 'status' => 'error',
  415. 'data' => array(
  416. 'message' => (string)$this->l10n->t('Unable to delete user.')
  417. )
  418. ),
  419. Http::STATUS_FORBIDDEN
  420. );
  421. }
  422. if(!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
  423. return new DataResponse(
  424. array(
  425. 'status' => 'error',
  426. 'data' => array(
  427. 'message' => (string)$this->l10n->t('Authentication error')
  428. )
  429. ),
  430. Http::STATUS_FORBIDDEN
  431. );
  432. }
  433. if($user) {
  434. if($user->delete()) {
  435. return new DataResponse(
  436. array(
  437. 'status' => 'success',
  438. 'data' => array(
  439. 'username' => $id
  440. )
  441. ),
  442. Http::STATUS_NO_CONTENT
  443. );
  444. }
  445. }
  446. return new DataResponse(
  447. array(
  448. 'status' => 'error',
  449. 'data' => array(
  450. 'message' => (string)$this->l10n->t('Unable to delete user.')
  451. )
  452. ),
  453. Http::STATUS_FORBIDDEN
  454. );
  455. }
  456. /**
  457. * @NoAdminRequired
  458. * @NoSubadminRequired
  459. * @PasswordConfirmationRequired
  460. *
  461. * @param string $avatarScope
  462. * @param string $displayname
  463. * @param string $displaynameScope
  464. * @param string $phone
  465. * @param string $phoneScope
  466. * @param string $email
  467. * @param string $emailScope
  468. * @param string $website
  469. * @param string $websiteScope
  470. * @param string $address
  471. * @param string $addressScope
  472. * @param string $twitter
  473. * @param string $twitterScope
  474. * @return DataResponse
  475. */
  476. public function setUserSettings($avatarScope,
  477. $displayname,
  478. $displaynameScope,
  479. $phone,
  480. $phoneScope,
  481. $email,
  482. $emailScope,
  483. $website,
  484. $websiteScope,
  485. $address,
  486. $addressScope,
  487. $twitter,
  488. $twitterScope
  489. ) {
  490. if(!empty($email) && !$this->mailer->validateMailAddress($email)) {
  491. return new DataResponse(
  492. array(
  493. 'status' => 'error',
  494. 'data' => array(
  495. 'message' => (string)$this->l10n->t('Invalid mail address')
  496. )
  497. ),
  498. Http::STATUS_UNPROCESSABLE_ENTITY
  499. );
  500. }
  501. $data = [
  502. AccountManager::PROPERTY_AVATAR => ['scope' => $avatarScope],
  503. AccountManager::PROPERTY_DISPLAYNAME => ['value' => $displayname, 'scope' => $displaynameScope],
  504. AccountManager::PROPERTY_EMAIL=> ['value' => $email, 'scope' => $emailScope],
  505. AccountManager::PROPERTY_WEBSITE => ['value' => $website, 'scope' => $websiteScope],
  506. AccountManager::PROPERTY_ADDRESS => ['value' => $address, 'scope' => $addressScope],
  507. AccountManager::PROPERTY_PHONE => ['value' => $phone, 'scope' => $phoneScope],
  508. AccountManager::PROPERTY_TWITTER => ['value' => $twitter, 'scope' => $twitterScope]
  509. ];
  510. $user = $this->userSession->getUser();
  511. try {
  512. $this->saveUserSettings($user, $data);
  513. return new DataResponse(
  514. array(
  515. 'status' => 'success',
  516. 'data' => array(
  517. 'userId' => $user->getUID(),
  518. 'avatarScope' => $avatarScope,
  519. 'displayname' => $displayname,
  520. 'displaynameScope' => $displaynameScope,
  521. 'email' => $email,
  522. 'emailScope' => $emailScope,
  523. 'website' => $website,
  524. 'websiteScope' => $websiteScope,
  525. 'address' => $address,
  526. 'addressScope' => $addressScope,
  527. 'message' => (string)$this->l10n->t('Settings saved')
  528. )
  529. ),
  530. Http::STATUS_OK
  531. );
  532. } catch (ForbiddenException $e) {
  533. return new DataResponse([
  534. 'status' => 'error',
  535. 'data' => [
  536. 'message' => $e->getMessage()
  537. ],
  538. ]);
  539. }
  540. }
  541. /**
  542. * update account manager with new user data
  543. *
  544. * @param IUser $user
  545. * @param array $data
  546. * @throws ForbiddenException
  547. */
  548. protected function saveUserSettings(IUser $user, $data) {
  549. // keep the user back-end up-to-date with the latest display name and email
  550. // address
  551. $oldDisplayName = $user->getDisplayName();
  552. if (isset($data[AccountManager::PROPERTY_DISPLAYNAME]['value'])
  553. && $oldDisplayName !== $data[AccountManager::PROPERTY_DISPLAYNAME]['value']
  554. ) {
  555. $result = $user->setDisplayName($data[AccountManager::PROPERTY_DISPLAYNAME]['value']);
  556. if ($result === false) {
  557. throw new ForbiddenException($this->l10n->t('Unable to change full name'));
  558. }
  559. }
  560. $oldEmailAddress = $user->getEMailAddress();
  561. if (isset($data[AccountManager::PROPERTY_EMAIL]['value'])
  562. && $oldEmailAddress !== $data[AccountManager::PROPERTY_EMAIL]['value']
  563. ) {
  564. // this is the only permission a backend provides and is also used
  565. // for the permission of setting a email address
  566. if (!$user->canChangeDisplayName()) {
  567. throw new ForbiddenException($this->l10n->t('Unable to change email address'));
  568. }
  569. $user->setEMailAddress($data[AccountManager::PROPERTY_EMAIL]['value']);
  570. }
  571. $this->accountManager->updateUser($user, $data);
  572. }
  573. /**
  574. * Count all unique users visible for the current admin/subadmin.
  575. *
  576. * @NoAdminRequired
  577. *
  578. * @return DataResponse
  579. */
  580. public function stats() {
  581. $userCount = 0;
  582. if ($this->isAdmin) {
  583. $countByBackend = $this->userManager->countUsers();
  584. if (!empty($countByBackend)) {
  585. foreach ($countByBackend as $count) {
  586. $userCount += $count;
  587. }
  588. }
  589. } else {
  590. $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
  591. $uniqueUsers = [];
  592. foreach ($groups as $group) {
  593. foreach($group->getUsers() as $uid => $displayName) {
  594. $uniqueUsers[$uid] = true;
  595. }
  596. }
  597. $userCount = count($uniqueUsers);
  598. }
  599. return new DataResponse(
  600. [
  601. 'totalUsers' => $userCount
  602. ]
  603. );
  604. }
  605. /**
  606. * Set the displayName of a user
  607. *
  608. * @NoAdminRequired
  609. * @NoSubadminRequired
  610. * @PasswordConfirmationRequired
  611. * @todo merge into saveUserSettings
  612. *
  613. * @param string $username
  614. * @param string $displayName
  615. * @return DataResponse
  616. */
  617. public function setDisplayName($username, $displayName) {
  618. $currentUser = $this->userSession->getUser();
  619. $user = $this->userManager->get($username);
  620. if ($user === null ||
  621. !$user->canChangeDisplayName() ||
  622. (
  623. !$this->groupManager->isAdmin($currentUser->getUID()) &&
  624. !$this->groupManager->getSubAdmin()->isUserAccessible($currentUser, $user) &&
  625. $currentUser->getUID() !== $username
  626. )
  627. ) {
  628. return new DataResponse([
  629. 'status' => 'error',
  630. 'data' => [
  631. 'message' => $this->l10n->t('Authentication error'),
  632. ],
  633. ]);
  634. }
  635. $userData = $this->accountManager->getUser($user);
  636. $userData[AccountManager::PROPERTY_DISPLAYNAME]['value'] = $displayName;
  637. try {
  638. $this->saveUserSettings($user, $userData);
  639. return new DataResponse([
  640. 'status' => 'success',
  641. 'data' => [
  642. 'message' => $this->l10n->t('Your full name has been changed.'),
  643. 'username' => $username,
  644. 'displayName' => $displayName,
  645. ],
  646. ]);
  647. } catch (ForbiddenException $e) {
  648. return new DataResponse([
  649. 'status' => 'error',
  650. 'data' => [
  651. 'message' => $e->getMessage(),
  652. 'displayName' => $user->getDisplayName(),
  653. ],
  654. ]);
  655. }
  656. }
  657. /**
  658. * Set the mail address of a user
  659. *
  660. * @NoAdminRequired
  661. * @NoSubadminRequired
  662. * @PasswordConfirmationRequired
  663. *
  664. * @param string $id
  665. * @param string $mailAddress
  666. * @return DataResponse
  667. */
  668. public function setEMailAddress($id, $mailAddress) {
  669. $user = $this->userManager->get($id);
  670. if (!$this->isAdmin
  671. && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)
  672. ) {
  673. return new DataResponse(
  674. array(
  675. 'status' => 'error',
  676. 'data' => array(
  677. 'message' => (string)$this->l10n->t('Forbidden')
  678. )
  679. ),
  680. Http::STATUS_FORBIDDEN
  681. );
  682. }
  683. if($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
  684. return new DataResponse(
  685. array(
  686. 'status' => 'error',
  687. 'data' => array(
  688. 'message' => (string)$this->l10n->t('Invalid mail address')
  689. )
  690. ),
  691. Http::STATUS_UNPROCESSABLE_ENTITY
  692. );
  693. }
  694. if (!$user) {
  695. return new DataResponse(
  696. array(
  697. 'status' => 'error',
  698. 'data' => array(
  699. 'message' => (string)$this->l10n->t('Invalid user')
  700. )
  701. ),
  702. Http::STATUS_UNPROCESSABLE_ENTITY
  703. );
  704. }
  705. // this is the only permission a backend provides and is also used
  706. // for the permission of setting a email address
  707. if (!$user->canChangeDisplayName()) {
  708. return new DataResponse(
  709. array(
  710. 'status' => 'error',
  711. 'data' => array(
  712. 'message' => (string)$this->l10n->t('Unable to change mail address')
  713. )
  714. ),
  715. Http::STATUS_FORBIDDEN
  716. );
  717. }
  718. $userData = $this->accountManager->getUser($user);
  719. $userData[AccountManager::PROPERTY_EMAIL]['value'] = $mailAddress;
  720. try {
  721. $this->saveUserSettings($user, $userData);
  722. return new DataResponse(
  723. array(
  724. 'status' => 'success',
  725. 'data' => array(
  726. 'username' => $id,
  727. 'mailAddress' => $mailAddress,
  728. 'message' => (string)$this->l10n->t('Email saved')
  729. )
  730. ),
  731. Http::STATUS_OK
  732. );
  733. } catch (ForbiddenException $e) {
  734. return new DataResponse([
  735. 'status' => 'error',
  736. 'data' => [
  737. 'message' => $e->getMessage()
  738. ],
  739. ]);
  740. }
  741. }
  742. }