UpdateGroups.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Lukas Reschke <lukas@statuscode.ch>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Robin Appelman <robin@icewind.nl>
  12. * @author Robin McCorkell <robin@mccorkell.me.uk>
  13. *
  14. * @license AGPL-3.0
  15. *
  16. * This code is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License, version 3,
  18. * as published by the Free Software Foundation.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License, version 3,
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>
  27. *
  28. */
  29. namespace OCA\User_LDAP\Jobs;
  30. use OCP\AppFramework\Utility\ITimeFactory;
  31. use OCP\BackgroundJob\TimedJob;
  32. use OCA\User_LDAP\Group_Proxy;
  33. use OCP\DB\Exception;
  34. use OCP\DB\QueryBuilder\IQueryBuilder;
  35. use OCP\EventDispatcher\IEventDispatcher;
  36. use OCP\Group\Events\UserAddedEvent;
  37. use OCP\Group\Events\UserRemovedEvent;
  38. use OCP\IConfig;
  39. use OCP\IDBConnection;
  40. use OCP\IGroupManager;
  41. use OCP\IUser;
  42. use OCP\IUserManager;
  43. use Psr\Log\LoggerInterface;
  44. class UpdateGroups extends TimedJob {
  45. /** @var ?array<string, array{owncloudusers: string, owncloudname: string}> */
  46. private ?array $groupsFromDB = null;
  47. private Group_Proxy $groupBackend;
  48. private IEventDispatcher $dispatcher;
  49. private IGroupManager $groupManager;
  50. private IUserManager $userManager;
  51. private LoggerInterface $logger;
  52. private IDBConnection $dbc;
  53. public function __construct(
  54. Group_Proxy $groupBackend,
  55. IEventDispatcher $dispatcher,
  56. IGroupManager $groupManager,
  57. IUserManager $userManager,
  58. LoggerInterface $logger,
  59. IDBConnection $dbc,
  60. IConfig $config,
  61. ITimeFactory $timeFactory
  62. ) {
  63. parent::__construct($timeFactory);
  64. $this->interval = (int)$config->getAppValue('user_ldap', 'bgjRefreshInterval', '3600');
  65. $this->groupBackend = $groupBackend;
  66. $this->dispatcher = $dispatcher;
  67. $this->groupManager = $groupManager;
  68. $this->userManager = $userManager;
  69. $this->logger = $logger;
  70. $this->dbc = $dbc;
  71. }
  72. /**
  73. * @param mixed $argument
  74. * @throws Exception
  75. */
  76. public function run($argument): void {
  77. $this->updateGroups();
  78. }
  79. /**
  80. * @throws Exception
  81. */
  82. public function updateGroups(): void {
  83. $this->logger->debug(
  84. 'Run background job "updateGroups"',
  85. ['app' => 'user_ldap']
  86. );
  87. /** @var string[] $knownGroups */
  88. $knownGroups = array_keys($this->getKnownGroups());
  89. $actualGroups = $this->groupBackend->getGroups();
  90. if (empty($actualGroups) && empty($knownGroups)) {
  91. $this->logger->info(
  92. 'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
  93. ['app' => 'user_ldap']
  94. );
  95. return;
  96. }
  97. $this->handleKnownGroups(array_intersect($actualGroups, $knownGroups));
  98. $this->handleCreatedGroups(array_diff($actualGroups, $knownGroups));
  99. $this->handleRemovedGroups(array_diff($knownGroups, $actualGroups));
  100. $this->logger->debug(
  101. 'bgJ "updateGroups" – Finished.',
  102. ['app' => 'user_ldap']
  103. );
  104. }
  105. /**
  106. * @return array<string, array{owncloudusers: string, owncloudname: string}>
  107. * @throws Exception
  108. */
  109. private function getKnownGroups(): array {
  110. if (is_array($this->groupsFromDB)) {
  111. return $this->groupsFromDB;
  112. }
  113. $qb = $this->dbc->getQueryBuilder();
  114. $qb->select(['owncloudname', 'owncloudusers'])
  115. ->from('ldap_group_members');
  116. $qResult = $qb->executeQuery();
  117. $result = $qResult->fetchAll();
  118. $qResult->closeCursor();
  119. $this->groupsFromDB = [];
  120. foreach ($result as $dataset) {
  121. $this->groupsFromDB[$dataset['owncloudname']] = $dataset;
  122. }
  123. return $this->groupsFromDB;
  124. }
  125. /**
  126. * @param string[] $groups
  127. * @throws Exception
  128. */
  129. private function handleKnownGroups(array $groups): void {
  130. $this->logger->debug(
  131. 'bgJ "updateGroups" – Dealing with known Groups.',
  132. ['app' => 'user_ldap']
  133. );
  134. $qb = $this->dbc->getQueryBuilder();
  135. $qb->update('ldap_group_members')
  136. ->set('owncloudusers', $qb->createParameter('members'))
  137. ->where($qb->expr()->eq('owncloudname', $qb->createParameter('groupId')));
  138. $groupsFromDB = $this->getKnownGroups();
  139. foreach ($groups as $group) {
  140. $knownUsers = unserialize($groupsFromDB[$group]['owncloudusers']);
  141. $actualUsers = $this->groupBackend->usersInGroup($group);
  142. $hasChanged = false;
  143. $groupObject = $this->groupManager->get($group);
  144. if ($groupObject === null) {
  145. /* We are not expecting the group to not be found since it was returned by $this->groupBackend->getGroups() */
  146. $this->logger->error(
  147. 'bgJ "updateGroups" – Failed to get group {group} for update',
  148. [
  149. 'app' => 'user_ldap',
  150. 'group' => $group
  151. ]
  152. );
  153. continue;
  154. }
  155. foreach (array_diff($knownUsers, $actualUsers) as $removedUser) {
  156. $userObject = $this->userManager->get($removedUser);
  157. if ($userObject instanceof IUser) {
  158. $this->dispatcher->dispatchTyped(new UserRemovedEvent($groupObject, $userObject));
  159. }
  160. $this->logger->info(
  161. 'bgJ "updateGroups" – {user} removed from {group}',
  162. [
  163. 'app' => 'user_ldap',
  164. 'user' => $removedUser,
  165. 'group' => $group
  166. ]
  167. );
  168. $hasChanged = true;
  169. }
  170. foreach (array_diff($actualUsers, $knownUsers) as $addedUser) {
  171. $userObject = $this->userManager->get($addedUser);
  172. if ($userObject instanceof IUser) {
  173. $this->dispatcher->dispatchTyped(new UserAddedEvent($groupObject, $userObject));
  174. }
  175. $this->logger->info(
  176. 'bgJ "updateGroups" – {user} added to {group}',
  177. [
  178. 'app' => 'user_ldap',
  179. 'user' => $addedUser,
  180. 'group' => $group
  181. ]
  182. );
  183. $hasChanged = true;
  184. }
  185. if ($hasChanged) {
  186. $qb->setParameters([
  187. 'members' => serialize($actualUsers),
  188. 'groupId' => $group
  189. ]);
  190. $qb->executeStatement();
  191. }
  192. }
  193. $this->logger->debug(
  194. 'bgJ "updateGroups" – FINISHED dealing with known Groups.',
  195. ['app' => 'user_ldap']
  196. );
  197. }
  198. /**
  199. * @param string[] $createdGroups
  200. * @throws Exception
  201. */
  202. private function handleCreatedGroups(array $createdGroups): void {
  203. $this->logger->debug(
  204. 'bgJ "updateGroups" – dealing with created Groups.',
  205. ['app' => 'user_ldap']
  206. );
  207. $query = $this->dbc->getQueryBuilder();
  208. $query->insert('ldap_group_members')
  209. ->setValue('owncloudname', $query->createParameter('owncloudname'))
  210. ->setValue('owncloudusers', $query->createParameter('owncloudusers'));
  211. foreach ($createdGroups as $createdGroup) {
  212. $this->logger->info(
  213. 'bgJ "updateGroups" – new group "' . $createdGroup . '" found.',
  214. ['app' => 'user_ldap']
  215. );
  216. $users = serialize($this->groupBackend->usersInGroup($createdGroup));
  217. $query->setParameter('owncloudname', $createdGroup)
  218. ->setParameter('owncloudusers', $users);
  219. $query->executeStatement();
  220. }
  221. $this->logger->debug(
  222. 'bgJ "updateGroups" – FINISHED dealing with created Groups.',
  223. ['app' => 'user_ldap']
  224. );
  225. }
  226. /**
  227. * @param string[] $removedGroups
  228. * @throws Exception
  229. */
  230. private function handleRemovedGroups(array $removedGroups): void {
  231. $this->logger->debug(
  232. 'bgJ "updateGroups" – dealing with removed groups.',
  233. ['app' => 'user_ldap']
  234. );
  235. $query = $this->dbc->getQueryBuilder();
  236. $query->delete('ldap_group_members')
  237. ->where($query->expr()->in('owncloudname', $query->createParameter('owncloudnames')));
  238. foreach (array_chunk($removedGroups, 1000) as $removedGroupsChunk) {
  239. $this->logger->info(
  240. 'bgJ "updateGroups" – groups {removedGroups} were removed.',
  241. [
  242. 'app' => 'user_ldap',
  243. 'removedGroups' => $removedGroupsChunk
  244. ]
  245. );
  246. $query->setParameter('owncloudnames', $removedGroupsChunk, IQueryBuilder::PARAM_STR_ARRAY);
  247. $query->executeStatement();
  248. }
  249. $this->logger->debug(
  250. 'bgJ "updateGroups" – FINISHED dealing with removed groups.',
  251. ['app' => 'user_ldap']
  252. );
  253. }
  254. }