CloudIdManager.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2017, Robin Appelman <robin@icewind.nl>
  5. *
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Guillaume Virlet <github@virlet.org>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Robin Appelman <robin@icewind.nl>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. *
  13. * @license GNU AGPL version 3 or any later version
  14. *
  15. * This program is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License as
  17. * published by the Free Software Foundation, either version 3 of the
  18. * License, or (at your option) any later version.
  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
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  27. *
  28. */
  29. namespace OC\Federation;
  30. use OCA\DAV\Events\CardUpdatedEvent;
  31. use OCP\Contacts\IManager;
  32. use OCP\EventDispatcher\Event;
  33. use OCP\EventDispatcher\IEventDispatcher;
  34. use OCP\Federation\ICloudId;
  35. use OCP\Federation\ICloudIdManager;
  36. use OCP\ICache;
  37. use OCP\ICacheFactory;
  38. use OCP\IURLGenerator;
  39. use OCP\IUserManager;
  40. use OCP\User\Events\UserChangedEvent;
  41. class CloudIdManager implements ICloudIdManager {
  42. /** @var IManager */
  43. private $contactsManager;
  44. /** @var IURLGenerator */
  45. private $urlGenerator;
  46. /** @var IUserManager */
  47. private $userManager;
  48. private ICache $memCache;
  49. /** @var array[] */
  50. private array $cache = [];
  51. public function __construct(
  52. IManager $contactsManager,
  53. IURLGenerator $urlGenerator,
  54. IUserManager $userManager,
  55. ICacheFactory $cacheFactory,
  56. IEventDispatcher $eventDispatcher
  57. ) {
  58. $this->contactsManager = $contactsManager;
  59. $this->urlGenerator = $urlGenerator;
  60. $this->userManager = $userManager;
  61. $this->memCache = $cacheFactory->createDistributed('cloud_id_');
  62. $eventDispatcher->addListener(UserChangedEvent::class, [$this, 'handleUserEvent']);
  63. $eventDispatcher->addListener(CardUpdatedEvent::class, [$this, 'handleCardEvent']);
  64. }
  65. public function handleUserEvent(Event $event): void {
  66. if ($event instanceof UserChangedEvent && $event->getFeature() === 'displayName') {
  67. $userId = $event->getUser()->getUID();
  68. $key = $userId . '@local';
  69. unset($this->cache[$key]);
  70. $this->memCache->remove($key);
  71. }
  72. }
  73. public function handleCardEvent(Event $event): void {
  74. if ($event instanceof CardUpdatedEvent) {
  75. $data = $event->getCardData()['carddata'];
  76. foreach (explode("\r\n", $data) as $line) {
  77. if (strpos($line, "CLOUD;") === 0) {
  78. $parts = explode(':', $line, 2);
  79. if (isset($parts[1])) {
  80. $key = $parts[1];
  81. unset($this->cache[$key]);
  82. $this->memCache->remove($key);
  83. }
  84. }
  85. }
  86. }
  87. }
  88. /**
  89. * @param string $cloudId
  90. * @return ICloudId
  91. * @throws \InvalidArgumentException
  92. */
  93. public function resolveCloudId(string $cloudId): ICloudId {
  94. // TODO magic here to get the url and user instead of just splitting on @
  95. if (!$this->isValidCloudId($cloudId)) {
  96. throw new \InvalidArgumentException('Invalid cloud id');
  97. }
  98. // Find the first character that is not allowed in user names
  99. $id = $this->fixRemoteURL($cloudId);
  100. $posSlash = strpos($id, '/');
  101. $posColon = strpos($id, ':');
  102. if ($posSlash === false && $posColon === false) {
  103. $invalidPos = \strlen($id);
  104. } elseif ($posSlash === false) {
  105. $invalidPos = $posColon;
  106. } elseif ($posColon === false) {
  107. $invalidPos = $posSlash;
  108. } else {
  109. $invalidPos = min($posSlash, $posColon);
  110. }
  111. $lastValidAtPos = strrpos($id, '@', $invalidPos - strlen($id));
  112. if ($lastValidAtPos !== false) {
  113. $user = substr($id, 0, $lastValidAtPos);
  114. $remote = substr($id, $lastValidAtPos + 1);
  115. $this->userManager->validateUserId($user);
  116. if (!empty($user) && !empty($remote)) {
  117. return new CloudId($id, $user, $remote, $this->getDisplayNameFromContact($id));
  118. }
  119. }
  120. throw new \InvalidArgumentException('Invalid cloud id');
  121. }
  122. protected function getDisplayNameFromContact(string $cloudId): ?string {
  123. $addressBookEntries = $this->contactsManager->search($cloudId, ['CLOUD'], [
  124. 'limit' => 1,
  125. 'enumeration' => false,
  126. 'fullmatch' => false,
  127. 'strict_search' => true,
  128. ]);
  129. foreach ($addressBookEntries as $entry) {
  130. if (isset($entry['CLOUD'])) {
  131. foreach ($entry['CLOUD'] as $cloudID) {
  132. if ($cloudID === $cloudId) {
  133. // Warning, if user decides to make his full name local only,
  134. // no FN is found on federated servers
  135. if (isset($entry['FN'])) {
  136. return $entry['FN'];
  137. } else {
  138. return $cloudID;
  139. }
  140. }
  141. }
  142. }
  143. }
  144. return null;
  145. }
  146. /**
  147. * @param string $user
  148. * @param string|null $remote
  149. * @return CloudId
  150. */
  151. public function getCloudId(string $user, ?string $remote): ICloudId {
  152. $isLocal = $remote === null;
  153. if ($isLocal) {
  154. $remote = rtrim($this->removeProtocolFromUrl($this->urlGenerator->getAbsoluteURL('/')), '/');
  155. $fixedRemote = $this->fixRemoteURL($remote);
  156. $host = $fixedRemote;
  157. } else {
  158. // note that for remote id's we don't strip the protocol for the remote we use to construct the CloudId
  159. // this way if a user has an explicit non-https cloud id this will be preserved
  160. // we do still use the version without protocol for looking up the display name
  161. $fixedRemote = $this->fixRemoteURL($remote);
  162. $host = $this->removeProtocolFromUrl($fixedRemote);
  163. }
  164. $key = $user . '@' . ($isLocal ? 'local' : $host);
  165. $cached = $this->cache[$key] ?? $this->memCache->get($key);
  166. if ($cached) {
  167. $this->cache[$key] = $cached; // put items from memcache into local cache
  168. return new CloudId($cached['id'], $cached['user'], $cached['remote'], $cached['displayName']);
  169. }
  170. if ($isLocal) {
  171. $localUser = $this->userManager->get($user);
  172. $displayName = $localUser ? $localUser->getDisplayName() : '';
  173. } else {
  174. $displayName = $this->getDisplayNameFromContact($user . '@' . $host);
  175. }
  176. $id = $user . '@' . $remote;
  177. $data = [
  178. 'id' => $id,
  179. 'user' => $user,
  180. 'remote' => $fixedRemote,
  181. 'displayName' => $displayName,
  182. ];
  183. $this->cache[$key] = $data;
  184. $this->memCache->set($key, $data, 15 * 60);
  185. return new CloudId($id, $user, $fixedRemote, $displayName);
  186. }
  187. /**
  188. * @param string $url
  189. * @return string
  190. */
  191. public function removeProtocolFromUrl(string $url): string {
  192. if (str_starts_with($url, 'https://')) {
  193. return substr($url, 8);
  194. }
  195. if (str_starts_with($url, 'http://')) {
  196. return substr($url, 7);
  197. }
  198. return $url;
  199. }
  200. /**
  201. * Strips away a potential file names and trailing slashes:
  202. * - http://localhost
  203. * - http://localhost/
  204. * - http://localhost/index.php
  205. * - http://localhost/index.php/s/{shareToken}
  206. *
  207. * all return: http://localhost
  208. *
  209. * @param string $remote
  210. * @return string
  211. */
  212. protected function fixRemoteURL(string $remote): string {
  213. $remote = str_replace('\\', '/', $remote);
  214. if ($fileNamePosition = strpos($remote, '/index.php')) {
  215. $remote = substr($remote, 0, $fileNamePosition);
  216. }
  217. $remote = rtrim($remote, '/');
  218. return $remote;
  219. }
  220. /**
  221. * @param string $cloudId
  222. * @return bool
  223. */
  224. public function isValidCloudId(string $cloudId): bool {
  225. return strpos($cloudId, '@') !== false;
  226. }
  227. }