UpdateGroups.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. foreach (array_diff($knownUsers, $actualUsers) as $removedUser) {
  145. $userObject = $this->userManager->get($removedUser);
  146. if ($userObject instanceof IUser) {
  147. $this->dispatcher->dispatchTyped(new UserRemovedEvent($groupObject, $userObject));
  148. }
  149. $this->logger->info(
  150. 'bgJ "updateGroups" – {user} removed from {group}',
  151. [
  152. 'app' => 'user_ldap',
  153. 'user' => $removedUser,
  154. 'group' => $group
  155. ]
  156. );
  157. $hasChanged = true;
  158. }
  159. foreach (array_diff($actualUsers, $knownUsers) as $addedUser) {
  160. $userObject = $this->userManager->get($addedUser);
  161. if ($userObject instanceof IUser) {
  162. $this->dispatcher->dispatchTyped(new UserAddedEvent($groupObject, $userObject));
  163. }
  164. $this->logger->info(
  165. 'bgJ "updateGroups" – {user} added to {group}',
  166. [
  167. 'app' => 'user_ldap',
  168. 'user' => $addedUser,
  169. 'group' => $group
  170. ]
  171. );
  172. $hasChanged = true;
  173. }
  174. if ($hasChanged) {
  175. $qb->setParameters([
  176. 'members' => serialize($actualUsers),
  177. 'groupId' => $group
  178. ]);
  179. $qb->executeStatement();
  180. }
  181. }
  182. $this->logger->debug(
  183. 'bgJ "updateGroups" – FINISHED dealing with known Groups.',
  184. ['app' => 'user_ldap']
  185. );
  186. }
  187. /**
  188. * @param string[] $createdGroups
  189. * @throws Exception
  190. */
  191. private function handleCreatedGroups(array $createdGroups): void {
  192. $this->logger->debug(
  193. 'bgJ "updateGroups" – dealing with created Groups.',
  194. ['app' => 'user_ldap']
  195. );
  196. $query = $this->dbc->getQueryBuilder();
  197. $query->insert('ldap_group_members')
  198. ->setValue('owncloudname', $query->createParameter('owncloudname'))
  199. ->setValue('owncloudusers', $query->createParameter('owncloudusers'));
  200. foreach ($createdGroups as $createdGroup) {
  201. $this->logger->info(
  202. 'bgJ "updateGroups" – new group "' . $createdGroup . '" found.',
  203. ['app' => 'user_ldap']
  204. );
  205. $users = serialize($this->groupBackend->usersInGroup($createdGroup));
  206. $query->setParameter('owncloudname', $createdGroup)
  207. ->setParameter('owncloudusers', $users);
  208. $query->executeStatement();
  209. }
  210. $this->logger->debug(
  211. 'bgJ "updateGroups" – FINISHED dealing with created Groups.',
  212. ['app' => 'user_ldap']
  213. );
  214. }
  215. /**
  216. * @param string[] $removedGroups
  217. * @throws Exception
  218. */
  219. private function handleRemovedGroups(array $removedGroups): void {
  220. $this->logger->debug(
  221. 'bgJ "updateGroups" – dealing with removed groups.',
  222. ['app' => 'user_ldap']
  223. );
  224. $query = $this->dbc->getQueryBuilder();
  225. $query->delete('ldap_group_members')
  226. ->where($query->expr()->in('owncloudname', $query->createParameter('owncloudnames')));
  227. foreach (array_chunk($removedGroups, 1000) as $removedGroupsChunk) {
  228. $this->logger->info(
  229. 'bgJ "updateGroups" – groups {removedGroups} were removed.',
  230. [
  231. 'app' => 'user_ldap',
  232. 'removedGroups' => $removedGroupsChunk
  233. ]
  234. );
  235. $query->setParameter('owncloudnames', $removedGroupsChunk, IQueryBuilder::PARAM_STR_ARRAY);
  236. $query->executeStatement();
  237. }
  238. $this->logger->debug(
  239. 'bgJ "updateGroups" – FINISHED dealing with removed groups.',
  240. ['app' => 'user_ldap']
  241. );
  242. }
  243. }