CloudIdManager.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. if (!empty($user) && !empty($remote)) {
  116. return new CloudId($id, $user, $remote, $this->getDisplayNameFromContact($id));
  117. }
  118. }
  119. throw new \InvalidArgumentException('Invalid cloud id');
  120. }
  121. protected function getDisplayNameFromContact(string $cloudId): ?string {
  122. $addressBookEntries = $this->contactsManager->search($cloudId, ['CLOUD'], [
  123. 'limit' => 1,
  124. 'enumeration' => false,
  125. 'fullmatch' => false,
  126. 'strict_search' => true,
  127. ]);
  128. foreach ($addressBookEntries as $entry) {
  129. if (isset($entry['CLOUD'])) {
  130. foreach ($entry['CLOUD'] as $cloudID) {
  131. if ($cloudID === $cloudId) {
  132. // Warning, if user decides to make his full name local only,
  133. // no FN is found on federated servers
  134. if (isset($entry['FN'])) {
  135. return $entry['FN'];
  136. } else {
  137. return $cloudID;
  138. }
  139. }
  140. }
  141. }
  142. }
  143. return null;
  144. }
  145. /**
  146. * @param string $user
  147. * @param string|null $remote
  148. * @return CloudId
  149. */
  150. public function getCloudId(string $user, ?string $remote): ICloudId {
  151. $isLocal = $remote === null;
  152. if ($isLocal) {
  153. $remote = rtrim($this->removeProtocolFromUrl($this->urlGenerator->getAbsoluteURL('/')), '/');
  154. $fixedRemote = $this->fixRemoteURL($remote);
  155. $host = $fixedRemote;
  156. } else {
  157. // note that for remote id's we don't strip the protocol for the remote we use to construct the CloudId
  158. // this way if a user has an explicit non-https cloud id this will be preserved
  159. // we do still use the version without protocol for looking up the display name
  160. $fixedRemote = $this->fixRemoteURL($remote);
  161. $host = $this->removeProtocolFromUrl($fixedRemote);
  162. }
  163. $key = $user . '@' . ($isLocal ? 'local' : $host);
  164. $cached = $this->cache[$key] ?? $this->memCache->get($key);
  165. if ($cached) {
  166. $this->cache[$key] = $cached; // put items from memcache into local cache
  167. return new CloudId($cached['id'], $cached['user'], $cached['remote'], $cached['displayName']);
  168. }
  169. if ($isLocal) {
  170. $localUser = $this->userManager->get($user);
  171. $displayName = $localUser ? $localUser->getDisplayName() : '';
  172. } else {
  173. $displayName = $this->getDisplayNameFromContact($user . '@' . $host);
  174. }
  175. $id = $user . '@' . $remote;
  176. $data = [
  177. 'id' => $id,
  178. 'user' => $user,
  179. 'remote' => $fixedRemote,
  180. 'displayName' => $displayName,
  181. ];
  182. $this->cache[$key] = $data;
  183. $this->memCache->set($key, $data, 15 * 60);
  184. return new CloudId($id, $user, $fixedRemote, $displayName);
  185. }
  186. /**
  187. * @param string $url
  188. * @return string
  189. */
  190. private function removeProtocolFromUrl($url) {
  191. if (strpos($url, 'https://') === 0) {
  192. return substr($url, strlen('https://'));
  193. } elseif (strpos($url, 'http://') === 0) {
  194. return substr($url, strlen('http://'));
  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 strpos($cloudId, '@') !== false;
  224. }
  225. }