AUserData.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2018 John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
  5. *
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Georg Ehrke <oc.list@georgehrke.com>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author John Molakvoæ <skjnldsv@protonmail.com>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author Vincent Petry <vincent@nextcloud.com>
  13. * @author Kate Döen <kate.doeen@nextcloud.com>
  14. *
  15. * @license GNU AGPL version 3 or any later version
  16. *
  17. * This program is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License as
  19. * published by the Free Software Foundation, either version 3 of the
  20. * License, or (at your option) any later version.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU Affero General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU Affero General Public License
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  29. *
  30. */
  31. namespace OCA\Provisioning_API\Controller;
  32. use OC\Group\Manager;
  33. use OC\User\Backend;
  34. use OC\User\NoUserException;
  35. use OC_Helper;
  36. use OCP\Accounts\IAccountManager;
  37. use OCP\Accounts\PropertyDoesNotExistException;
  38. use OCP\AppFramework\Http;
  39. use OCP\AppFramework\OCS\OCSException;
  40. use OCP\AppFramework\OCS\OCSNotFoundException;
  41. use OCP\AppFramework\OCSController;
  42. use OCP\Files\NotFoundException;
  43. use OCP\IConfig;
  44. use OCP\IGroupManager;
  45. use OCP\IRequest;
  46. use OCP\IUserManager;
  47. use OCP\IUserSession;
  48. use OCP\L10N\IFactory;
  49. use OCP\User\Backend\ISetDisplayNameBackend;
  50. use OCP\User\Backend\ISetPasswordBackend;
  51. abstract class AUserData extends OCSController {
  52. public const SCOPE_SUFFIX = 'Scope';
  53. public const USER_FIELD_DISPLAYNAME = 'display';
  54. public const USER_FIELD_LANGUAGE = 'language';
  55. public const USER_FIELD_LOCALE = 'locale';
  56. public const USER_FIELD_PASSWORD = 'password';
  57. public const USER_FIELD_QUOTA = 'quota';
  58. public const USER_FIELD_MANAGER = 'manager';
  59. public const USER_FIELD_NOTIFICATION_EMAIL = 'notify_email';
  60. /** @var IUserManager */
  61. protected $userManager;
  62. /** @var IConfig */
  63. protected $config;
  64. /** @var Manager */
  65. protected $groupManager;
  66. /** @var IUserSession */
  67. protected $userSession;
  68. /** @var IAccountManager */
  69. protected $accountManager;
  70. /** @var IFactory */
  71. protected $l10nFactory;
  72. public function __construct(string $appName,
  73. IRequest $request,
  74. IUserManager $userManager,
  75. IConfig $config,
  76. IGroupManager $groupManager,
  77. IUserSession $userSession,
  78. IAccountManager $accountManager,
  79. IFactory $l10nFactory) {
  80. parent::__construct($appName, $request);
  81. $this->userManager = $userManager;
  82. $this->config = $config;
  83. $this->groupManager = $groupManager;
  84. $this->userSession = $userSession;
  85. $this->accountManager = $accountManager;
  86. $this->l10nFactory = $l10nFactory;
  87. }
  88. /**
  89. * creates a array with all user data
  90. *
  91. * @param string $userId
  92. * @param bool $includeScopes
  93. * @return array
  94. * @throws NotFoundException
  95. * @throws OCSException
  96. * @throws OCSNotFoundException
  97. */
  98. protected function getUserData(string $userId, bool $includeScopes = false): array {
  99. $currentLoggedInUser = $this->userSession->getUser();
  100. assert($currentLoggedInUser !== null, 'No user logged in');
  101. $data = [];
  102. // Check if the target user exists
  103. $targetUserObject = $this->userManager->get($userId);
  104. if ($targetUserObject === null) {
  105. throw new OCSNotFoundException('User does not exist');
  106. }
  107. $isAdmin = $this->groupManager->isAdmin($currentLoggedInUser->getUID());
  108. if ($isAdmin
  109. || $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
  110. $data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true') === 'true';
  111. } else {
  112. // Check they are looking up themselves
  113. if ($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
  114. return $data;
  115. }
  116. }
  117. // Get groups data
  118. $userAccount = $this->accountManager->getAccount($targetUserObject);
  119. $groups = $this->groupManager->getUserGroups($targetUserObject);
  120. $gids = [];
  121. foreach ($groups as $group) {
  122. $gids[] = $group->getGID();
  123. }
  124. if ($isAdmin) {
  125. try {
  126. # might be thrown by LDAP due to handling of users disappears
  127. # from the external source (reasons unknown to us)
  128. # cf. https://github.com/nextcloud/server/issues/12991
  129. $data['storageLocation'] = $targetUserObject->getHome();
  130. } catch (NoUserException $e) {
  131. throw new OCSNotFoundException($e->getMessage(), $e);
  132. }
  133. }
  134. // Find the data
  135. $data['id'] = $targetUserObject->getUID();
  136. $data['lastLogin'] = $targetUserObject->getLastLogin() * 1000;
  137. $data['backend'] = $targetUserObject->getBackendClassName();
  138. $data['subadmin'] = $this->getUserSubAdminGroupsData($targetUserObject->getUID());
  139. $data[self::USER_FIELD_QUOTA] = $this->fillStorageInfo($targetUserObject->getUID());
  140. $managerUids = $targetUserObject->getManagerUids();
  141. $data[self::USER_FIELD_MANAGER] = empty($managerUids) ? '' : $managerUids[0];
  142. try {
  143. if ($includeScopes) {
  144. $data[IAccountManager::PROPERTY_AVATAR . self::SCOPE_SUFFIX] = $userAccount->getProperty(IAccountManager::PROPERTY_AVATAR)->getScope();
  145. }
  146. $data[IAccountManager::PROPERTY_EMAIL] = $targetUserObject->getSystemEMailAddress();
  147. if ($includeScopes) {
  148. $data[IAccountManager::PROPERTY_EMAIL . self::SCOPE_SUFFIX] = $userAccount->getProperty(IAccountManager::PROPERTY_EMAIL)->getScope();
  149. }
  150. $additionalEmails = $additionalEmailScopes = [];
  151. $emailCollection = $userAccount->getPropertyCollection(IAccountManager::COLLECTION_EMAIL);
  152. foreach ($emailCollection->getProperties() as $property) {
  153. $additionalEmails[] = $property->getValue();
  154. if ($includeScopes) {
  155. $additionalEmailScopes[] = $property->getScope();
  156. }
  157. }
  158. $data[IAccountManager::COLLECTION_EMAIL] = $additionalEmails;
  159. if ($includeScopes) {
  160. $data[IAccountManager::COLLECTION_EMAIL . self::SCOPE_SUFFIX] = $additionalEmailScopes;
  161. }
  162. $data[IAccountManager::PROPERTY_DISPLAYNAME] = $targetUserObject->getDisplayName();
  163. $data[IAccountManager::PROPERTY_DISPLAYNAME_LEGACY] = $data[IAccountManager::PROPERTY_DISPLAYNAME];
  164. if ($includeScopes) {
  165. $data[IAccountManager::PROPERTY_DISPLAYNAME . self::SCOPE_SUFFIX] = $userAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME)->getScope();
  166. }
  167. foreach ([
  168. IAccountManager::PROPERTY_PHONE,
  169. IAccountManager::PROPERTY_ADDRESS,
  170. IAccountManager::PROPERTY_WEBSITE,
  171. IAccountManager::PROPERTY_TWITTER,
  172. IAccountManager::PROPERTY_FEDIVERSE,
  173. IAccountManager::PROPERTY_ORGANISATION,
  174. IAccountManager::PROPERTY_ROLE,
  175. IAccountManager::PROPERTY_HEADLINE,
  176. IAccountManager::PROPERTY_BIOGRAPHY,
  177. IAccountManager::PROPERTY_PROFILE_ENABLED,
  178. ] as $propertyName) {
  179. $property = $userAccount->getProperty($propertyName);
  180. $data[$propertyName] = $property->getValue();
  181. if ($includeScopes) {
  182. $data[$propertyName . self::SCOPE_SUFFIX] = $property->getScope();
  183. }
  184. }
  185. } catch (PropertyDoesNotExistException $e) {
  186. // hard coded properties should exist
  187. throw new OCSException($e->getMessage(), Http::STATUS_INTERNAL_SERVER_ERROR, $e);
  188. }
  189. $data['groups'] = $gids;
  190. $data[self::USER_FIELD_LANGUAGE] = $this->l10nFactory->getUserLanguage($targetUserObject);
  191. $data[self::USER_FIELD_LOCALE] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'locale');
  192. $data[self::USER_FIELD_NOTIFICATION_EMAIL] = $targetUserObject->getPrimaryEMailAddress();
  193. $backend = $targetUserObject->getBackend();
  194. $data['backendCapabilities'] = [
  195. 'setDisplayName' => $backend instanceof ISetDisplayNameBackend || $backend->implementsActions(Backend::SET_DISPLAYNAME),
  196. 'setPassword' => $backend instanceof ISetPasswordBackend || $backend->implementsActions(Backend::SET_PASSWORD),
  197. ];
  198. return $data;
  199. }
  200. /**
  201. * Get the groups a user is a subadmin of
  202. *
  203. * @param string $userId
  204. * @return array
  205. * @throws OCSException
  206. */
  207. protected function getUserSubAdminGroupsData(string $userId): array {
  208. $user = $this->userManager->get($userId);
  209. // Check if the user exists
  210. if ($user === null) {
  211. throw new OCSNotFoundException('User does not exist');
  212. }
  213. // Get the subadmin groups
  214. $subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
  215. $groups = [];
  216. foreach ($subAdminGroups as $key => $group) {
  217. $groups[] = $group->getGID();
  218. }
  219. return $groups;
  220. }
  221. /**
  222. * @param string $userId
  223. * @return array
  224. * @throws OCSException
  225. */
  226. protected function fillStorageInfo(string $userId): array {
  227. try {
  228. \OC_Util::tearDownFS();
  229. \OC_Util::setupFS($userId);
  230. $storage = OC_Helper::getStorageInfo('/', null, true, false);
  231. $data = [
  232. 'free' => $storage['free'],
  233. 'used' => $storage['used'],
  234. 'total' => $storage['total'],
  235. 'relative' => $storage['relative'],
  236. self::USER_FIELD_QUOTA => $storage['quota'],
  237. ];
  238. } catch (NotFoundException $ex) {
  239. // User fs is not setup yet
  240. $user = $this->userManager->get($userId);
  241. if ($user === null) {
  242. throw new OCSException('User does not exist', 101);
  243. }
  244. $quota = $user->getQuota();
  245. if ($quota !== 'none') {
  246. $quota = OC_Helper::computerFileSize($quota);
  247. }
  248. $data = [
  249. self::USER_FIELD_QUOTA => $quota !== false ? $quota : 'none',
  250. 'used' => 0
  251. ];
  252. } catch (\Exception $e) {
  253. \OC::$server->get(\Psr\Log\LoggerInterface::class)->error(
  254. "Could not load storage info for {user}",
  255. [
  256. 'app' => 'provisioning_api',
  257. 'user' => $userId,
  258. 'exception' => $e,
  259. ]
  260. );
  261. /* In case the Exception left things in a bad state */
  262. \OC_Util::tearDownFS();
  263. return [];
  264. }
  265. return $data;
  266. }
  267. }