1
0

CloudIdManager.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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 (str_starts_with($line, "CLOUD;")) {
  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->urlGenerator->getAbsoluteURL('/'), '/');
  155. }
  156. // note that for remote id's we don't strip the protocol for the remote we use to construct the CloudId
  157. // this way if a user has an explicit non-https cloud id this will be preserved
  158. // we do still use the version without protocol for looking up the display name
  159. $remote = $this->removeProtocolFromUrl($remote, true);
  160. $remote = $this->fixRemoteURL($remote);
  161. $host = $this->removeProtocolFromUrl($remote);
  162. $key = $user . '@' . ($isLocal ? 'local' : $host);
  163. $cached = $this->cache[$key] ?? $this->memCache->get($key);
  164. if ($cached) {
  165. $this->cache[$key] = $cached; // put items from memcache into local cache
  166. return new CloudId($cached['id'], $cached['user'], $cached['remote'], $cached['displayName']);
  167. }
  168. if ($isLocal) {
  169. $localUser = $this->userManager->get($user);
  170. $displayName = $localUser ? $localUser->getDisplayName() : '';
  171. } else {
  172. $displayName = $this->getDisplayNameFromContact($user . '@' . $host);
  173. }
  174. $id = $user . '@' . $remote;
  175. $data = [
  176. 'id' => $id,
  177. 'user' => $user,
  178. 'remote' => $remote,
  179. 'displayName' => $displayName,
  180. ];
  181. $this->cache[$key] = $data;
  182. $this->memCache->set($key, $data, 15 * 60);
  183. return new CloudId($id, $user, $remote, $displayName);
  184. }
  185. /**
  186. * @param string $url
  187. * @return string
  188. */
  189. public function removeProtocolFromUrl(string $url, bool $httpsOnly = false): string {
  190. if (str_starts_with($url, 'https://')) {
  191. return substr($url, 8);
  192. }
  193. if (!$httpsOnly && str_starts_with($url, 'http://')) {
  194. return substr($url, 7);
  195. }
  196. return $url;
  197. }
  198. /**
  199. * Strips away a potential file names and trailing slashes:
  200. * - http://localhost
  201. * - http://localhost/
  202. * - http://localhost/index.php
  203. * - http://localhost/index.php/s/{shareToken}
  204. *
  205. * all return: http://localhost
  206. *
  207. * @param string $remote
  208. * @return string
  209. */
  210. protected function fixRemoteURL(string $remote): string {
  211. $remote = str_replace('\\', '/', $remote);
  212. if ($fileNamePosition = strpos($remote, '/index.php')) {
  213. $remote = substr($remote, 0, $fileNamePosition);
  214. }
  215. $remote = rtrim($remote, '/');
  216. return $remote;
  217. }
  218. /**
  219. * @param string $cloudId
  220. * @return bool
  221. */
  222. public function isValidCloudId(string $cloudId): bool {
  223. return str_contains($cloudId, '@');
  224. }
  225. }