Activitypub_profile.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * ActivityPub implementation for GNU social
  18. *
  19. * @package GNUsocial
  20. * @author Diogo Cordeiro <diogo@fc.up.pt>
  21. * @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
  22. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  23. * @link http://www.gnu.org/software/social/
  24. */
  25. defined('GNUSOCIAL') || die();
  26. /**
  27. * ActivityPub Profile
  28. *
  29. * @category Plugin
  30. * @package GNUsocial
  31. * @author Diogo Cordeiro <diogo@fc.up.pt>
  32. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  33. */
  34. class Activitypub_profile extends Managed_DataObject
  35. {
  36. public $__table = 'activitypub_profile';
  37. public $uri; // text() not_null
  38. public $profile_id; // int(4) primary_key not_null
  39. public $inboxuri; // text() not_null
  40. public $sharedInboxuri; // text()
  41. public $nickname; // varchar(64) multiple_key not_null
  42. public $fullname; // text()
  43. public $profileurl; // text()
  44. public $homepage; // text()
  45. public $bio; // text() multiple_key
  46. public $location; // text()
  47. public $created; // datetime() not_null default_CURRENT_TIMESTAMP
  48. public $modified; // datetime() not_null default_CURRENT_TIMESTAMP
  49. /**
  50. * Return table definition for Schema setup and DB_DataObject usage.
  51. *
  52. * @return array array of column definitions
  53. * @author Diogo Cordeiro <diogo@fc.up.pt>
  54. */
  55. public static function schemaDef()
  56. {
  57. return [
  58. 'fields' => [
  59. 'uri' => ['type' => 'text', 'not null' => true],
  60. 'profile_id' => ['type' => 'int', 'not null' => true],
  61. 'inboxuri' => ['type' => 'text', 'not null' => true],
  62. 'sharedInboxuri' => ['type' => 'text'],
  63. 'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'],
  64. 'modified' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'],
  65. ],
  66. 'primary key' => ['profile_id'],
  67. 'foreign keys' => [
  68. 'activitypub_profile_profile_id_fkey' => ['profile', ['profile_id' => 'id']],
  69. ],
  70. ];
  71. }
  72. /**
  73. * Generates a pretty profile from a Profile object
  74. *
  75. * @param Profile $profile
  76. * @return array array to be used in a response
  77. * @throws InvalidUrlException
  78. * @throws ServerException
  79. * @throws Exception
  80. * @author Diogo Cordeiro <diogo@fc.up.pt>
  81. */
  82. public static function profile_to_array($profile)
  83. {
  84. $uri = $profile->getUri();
  85. $id = $profile->getID();
  86. $rsa = new Activitypub_rsa();
  87. $public_key = $rsa->ensure_public_key($profile);
  88. unset($rsa);
  89. $res = [
  90. '@context' => [
  91. 'https://www.w3.org/ns/activitystreams',
  92. 'https://w3id.org/security/v1',
  93. [
  94. 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers'
  95. ]
  96. ],
  97. 'id' => $uri,
  98. 'type' => 'Person',
  99. 'following' => common_local_url('apActorFollowing', ['id' => $id]),
  100. 'followers' => common_local_url('apActorFollowers', ['id' => $id]),
  101. 'liked' => common_local_url('apActorLiked', ['id' => $id]),
  102. 'inbox' => common_local_url('apInbox', ['id' => $id]),
  103. 'outbox' => common_local_url('apActorOutbox', ['id' => $id]),
  104. 'preferredUsername' => $profile->getNickname(),
  105. 'name' => $profile->getBestName(),
  106. 'summary' => ($desc = $profile->getDescription()) == null ? "" : $desc,
  107. 'url' => $profile->getUrl(),
  108. 'manuallyApprovesFollowers' => false,
  109. 'publicKey' => [
  110. 'id' => $uri . "#public-key",
  111. 'owner' => $uri,
  112. 'publicKeyPem' => $public_key
  113. ],
  114. 'tag' => [],
  115. 'attachment' => [],
  116. 'icon' => [
  117. 'type' => 'Image',
  118. 'mediaType' => 'image/png',
  119. 'height' => AVATAR_PROFILE_SIZE,
  120. 'width' => AVATAR_PROFILE_SIZE,
  121. 'url' => $profile->avatarUrl(AVATAR_PROFILE_SIZE)
  122. ]
  123. ];
  124. if ($profile->isLocal()) {
  125. $res['endpoints']['sharedInbox'] = common_local_url('apInbox');
  126. } else {
  127. $aprofile = new Activitypub_profile();
  128. $aprofile = $aprofile->from_profile($profile);
  129. $res['endpoints']['sharedInbox'] = $aprofile->sharedInboxuri;
  130. }
  131. return $res;
  132. }
  133. /**
  134. * Insert the current object variables into the database
  135. *
  136. * @throws ServerException
  137. * @author Diogo Cordeiro <diogo@fc.up.pt>
  138. * @access public
  139. */
  140. public function do_insert()
  141. {
  142. // Does any other protocol have this remote entity we're about to add ?
  143. if (!Event::handle('StartTFNLookup', [$this->uri, get_class($this), &$profile_id])) {
  144. // Yes! Avoid creating a new profile
  145. $this->profile_id = $profile_id;
  146. $this->created = $this->modified = common_sql_now();
  147. if ($this->insert() === false) {
  148. $this->query('ROLLBACK');
  149. throw new ServerException('Cannot save ActivityPub profile.');
  150. }
  151. // Update existing profile with received data
  152. $profile = Profile::getKV('id', $profile_id);
  153. self::update_local_profile($profile, $this);
  154. // Ask TFN to handle profile duplication
  155. Event::handle('EndTFNLookup', [get_class($this), $profile_id]);
  156. } else {
  157. // No, create both a new profile and remote profile
  158. $profile = new Profile();
  159. $profile->created = $this->created = $this->modified = common_sql_now();
  160. self::update_local_profile($profile, $this);
  161. $this->profile_id = $profile->insert();
  162. if ($this->profile_id === false) {
  163. $profile->query('ROLLBACK');
  164. throw new ServerException('Profile insertion failed.');
  165. }
  166. $ok = $this->insert();
  167. if ($ok === false) {
  168. $profile->query('ROLLBACK');
  169. $this->query('ROLLBACK');
  170. throw new ServerException('Cannot save ActivityPub profile.');
  171. }
  172. }
  173. }
  174. /**
  175. * Fetch the locally stored profile for this Activitypub_profile
  176. *
  177. * @return get_called_class
  178. * @throws NoProfileException if it was not found
  179. * @author Diogo Cordeiro <diogo@fc.up.pt>
  180. */
  181. public function local_profile()
  182. {
  183. $profile = Profile::getKV('id', $this->profile_id);
  184. if (!$profile instanceof Profile) {
  185. throw new NoProfileException($this->profile_id);
  186. }
  187. return $profile;
  188. }
  189. /**
  190. * Generates an Activitypub_profile from a Profile
  191. *
  192. * @param Profile $profile
  193. * @return Activitypub_profile
  194. * @throws Exception if no Activitypub_profile exists for given Profile
  195. * @author Diogo Cordeiro <diogo@fc.up.pt>
  196. */
  197. public static function from_profile(Profile $profile): Activitypub_profile
  198. {
  199. $profile_id = $profile->getID();
  200. $aprofile = self::getKV('profile_id', $profile_id);
  201. if (!$aprofile instanceof Activitypub_profile) {
  202. // No Activitypub_profile for this profile_id,
  203. if (!$profile->isLocal()) {
  204. // create one!
  205. $aprofile = self::create_from_local_profile($profile);
  206. } else {
  207. throw new Exception('No Activitypub_profile for Profile ID: ' . $profile_id . ', this is a local user.');
  208. }
  209. }
  210. // extend the ap_profile with some information we
  211. // don't store in the database
  212. $fields = [
  213. 'nickname' => 'nickname',
  214. 'fullname' => 'fullname',
  215. 'bio' => 'bio'
  216. ];
  217. foreach ($fields as $af => $pf) {
  218. $aprofile->$af = $profile->$pf;
  219. }
  220. return $aprofile;
  221. }
  222. public static function from_profile_collection(array $profiles): array
  223. {
  224. $ap_profiles = [];
  225. foreach ($profiles as $profile) {
  226. try {
  227. $ap_profiles[] = self::from_profile($profile);
  228. } catch (Exception $e) {
  229. // Don't mind local profiles
  230. }
  231. }
  232. return $ap_profiles;
  233. }
  234. /**
  235. * Given an existent local profile creates an ActivityPub profile.
  236. * One must be careful not to give a user profile to this function
  237. * as only remote users have ActivityPub_profiles on local instance
  238. *
  239. * @param Profile $profile
  240. * @return Activitypub_profile
  241. * @throws HTTP_Request2_Exception
  242. * @throws Exception
  243. * @throws Exception
  244. * @author Diogo Cordeiro <diogo@fc.up.pt>
  245. */
  246. private static function create_from_local_profile(Profile $profile)
  247. {
  248. $aprofile = new Activitypub_profile();
  249. $url = $profile->getUri();
  250. $inboxes = Activitypub_explorer::get_actor_inboxes_uri($url);
  251. if ($inboxes == null) {
  252. throw new Exception('This is not an ActivityPub user thus AProfile is politely refusing to proceed.');
  253. }
  254. $aprofile->created = $aprofile->modified = common_sql_now();
  255. $aprofile = new Activitypub_profile;
  256. $aprofile->profile_id = $profile->getID();
  257. $aprofile->uri = $url;
  258. $aprofile->nickname = $profile->getNickname();
  259. $aprofile->fullname = $profile->getFullname();
  260. $aprofile->bio = substr($profile->getDescription(), 0, 1000);
  261. $aprofile->inboxuri = $inboxes["inbox"];
  262. $aprofile->sharedInboxuri = $inboxes["sharedInbox"];
  263. $aprofile->insert();
  264. return $aprofile;
  265. }
  266. /**
  267. * Returns sharedInbox if possible, inbox otherwise
  268. *
  269. * @return string Inbox URL
  270. * @author Diogo Cordeiro <diogo@fc.up.pt>
  271. */
  272. public function get_inbox()
  273. {
  274. if (is_null($this->sharedInboxuri)) {
  275. return $this->inboxuri;
  276. }
  277. return $this->sharedInboxuri;
  278. }
  279. /**
  280. * Getter for uri property
  281. *
  282. * @return string URI
  283. * @author Diogo Cordeiro <diogo@fc.up.pt>
  284. */
  285. public function getUri()
  286. {
  287. return $this->uri;
  288. }
  289. /**
  290. * Getter for url property
  291. *
  292. * @return string URL
  293. * @author Diogo Cordeiro <diogo@fc.up.pt>
  294. */
  295. public function getUrl()
  296. {
  297. return $this->getUri();
  298. }
  299. /**
  300. * Getter for id property
  301. *
  302. * @return int
  303. * @author Diogo Cordeiro <diogo@fc.up.pt>
  304. */
  305. public function getID()
  306. {
  307. return $this->profile_id;
  308. }
  309. /**
  310. * Ensures a valid Activitypub_profile when provided with a valid URI.
  311. *
  312. * @param string $url
  313. * @param bool $grab_online whether to try online grabbing, defaults to true
  314. * @return Activitypub_profile
  315. * @throws Exception if it isn't possible to return an Activitypub_profile
  316. * @author Diogo Cordeiro <diogo@fc.up.pt>
  317. */
  318. public static function fromUri($url, $grab_online = true)
  319. {
  320. try {
  321. return self::from_profile(Activitypub_explorer::get_profile_from_url($url, $grab_online));
  322. } catch (Exception $e) {
  323. throw new Exception('No valid ActivityPub profile found for given URI.');
  324. }
  325. }
  326. /**
  327. * Look up, and if necessary create, an Activitypub_profile for the remote
  328. * entity with the given WebFinger address.
  329. * This should never return null -- you will either get an object or
  330. * an exception will be thrown.
  331. *
  332. * @param string $addr WebFinger address
  333. * @return Activitypub_profile
  334. * @throws Exception on error conditions
  335. * @author Diogo Cordeiro <diogo@fc.up.pt>
  336. * @author GNU social
  337. */
  338. public static function ensure_webfinger($addr)
  339. {
  340. // Normalize $addr, i.e. add 'acct:' if missing
  341. $addr = Discovery::normalize($addr);
  342. // Try the cache
  343. $uri = self::cacheGet(sprintf('activitypub_profile:webfinger:%s', $addr));
  344. if ($uri !== false) {
  345. if (is_null($uri)) {
  346. // Negative cache entry
  347. // TRANS: Exception.
  348. throw new Exception(_m('Not a valid WebFinger address (via cache).'));
  349. }
  350. try {
  351. return self::fromUri($uri);
  352. } catch (Exception $e) {
  353. common_log(LOG_ERR, sprintf(__METHOD__ . ': WebFinger address cache inconsistent with database, did not find Activitypub_profile uri==%s', $uri));
  354. self::cacheSet(sprintf('activitypub_profile:webfinger:%s', $addr), false);
  355. }
  356. }
  357. // Now, try some discovery
  358. $disco = new Discovery();
  359. try {
  360. $xrd = $disco->lookup($addr);
  361. } catch (Exception $e) {
  362. // Save negative cache entry so we don't waste time looking it up again.
  363. // @todo FIXME: Distinguish temporary failures?
  364. self::cacheSet(sprintf('activitypub_profile:webfinger:%s', $addr), null);
  365. // TRANS: Exception.
  366. throw new Exception(_m('Not a valid WebFinger address.'));
  367. }
  368. $hints = array_merge(
  369. ['webfinger' => $addr],
  370. DiscoveryHints::fromXRD($xrd)
  371. );
  372. // If there's an Hcard, let's grab its info
  373. if (array_key_exists('hcard', $hints)) {
  374. if (!array_key_exists('profileurl', $hints) ||
  375. $hints['hcard'] != $hints['profileurl']) {
  376. $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
  377. $hints = array_merge($hcardHints, $hints);
  378. }
  379. }
  380. // If we got a profile page, try that!
  381. $profileUrl = null;
  382. if (array_key_exists('profileurl', $hints)) {
  383. $profileUrl = $hints['profileurl'];
  384. try {
  385. common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
  386. $aprofile = self::fromUri($hints['profileurl']);
  387. self::cacheSet(sprintf('activitypub_profile:webfinger:%s', $addr), $aprofile->getUri());
  388. return $aprofile;
  389. } catch (Exception $e) {
  390. common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
  391. // keep looking
  392. //
  393. // @todo FIXME: This means an error discovering from profile page
  394. // may give us a corrupt entry using the webfinger URI, which
  395. // will obscure the correct page-keyed profile later on.
  396. }
  397. }
  398. // XXX: try hcard
  399. // XXX: try FOAF
  400. // TRANS: Exception. %s is a WebFinger address.
  401. throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'), $addr));
  402. }
  403. /**
  404. * Update local profile with info from some AP profile
  405. *
  406. * @param Profile $profile
  407. * @param Activitypub_profile $aprofile
  408. * @return void
  409. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  410. * @author Diogo Cordeiro <diogo@fc.up.pt>
  411. */
  412. public static function update_local_profile(Profile $profile, Activitypub_profile $aprofile): void
  413. {
  414. $fields = [
  415. 'profileurl' => 'profileurl',
  416. 'nickname' => 'nickname',
  417. 'fullname' => 'fullname',
  418. 'bio' => 'bio'
  419. ];
  420. $orig = clone($profile);
  421. foreach ($fields as $af => $pf) {
  422. $profile->$pf = $aprofile->$af;
  423. }
  424. if ($profile->id) {
  425. common_debug('Updating local Profile:' . $profile->id . ' from remote ActivityPub profile');
  426. $profile->modified = common_sql_now();
  427. $profile->update($orig);
  428. }
  429. }
  430. /**
  431. * Update remote user profile in local instance
  432. * Depends on do_update
  433. *
  434. * @param Activitypub_profile $aprofile
  435. * @param array $res remote response
  436. * @return Profile remote Profile object
  437. * @throws NoProfileException
  438. * @author Diogo Cordeiro <diogo@fc.up.pt>
  439. */
  440. public static function update_profile($aprofile, $res)
  441. {
  442. // ActivityPub Profile
  443. $aprofile->uri = $res['id'];
  444. $aprofile->nickname = $res['preferredUsername'];
  445. $aprofile->fullname = $res['name'] ?? null;
  446. $aprofile->bio = isset($res['summary']) ? substr(strip_tags($res['summary']), 0, 1000) : null;
  447. $aprofile->inboxuri = $res['inbox'];
  448. $aprofile->sharedInboxuri = $res['endpoints']['sharedInbox'] ?? $res['inbox'];
  449. $aprofile->profileurl = $res['url'] ?? $aprofile->uri;
  450. $aprofile->modified = common_sql_now();
  451. $profile = $aprofile->local_profile();
  452. // Profile
  453. self::update_local_profile($profile, $aprofile);
  454. $aprofile->update();
  455. // Public Key
  456. Activitypub_rsa::update_public_key($profile, $res['publicKey']['publicKeyPem']);
  457. // Avatar
  458. if (isset($res['icon']['url'])) {
  459. try {
  460. Activitypub_explorer::update_avatar($profile, $res['icon']['url']);
  461. } catch (Exception $e) {
  462. // Let the exception go, it isn't a serious issue
  463. common_debug('An error ocurred while grabbing remote avatar' . $e->getMessage());
  464. }
  465. }
  466. return $profile;
  467. }
  468. /**
  469. * Update remote user profile URI in local instance
  470. *
  471. * @param string $uri
  472. * @return void
  473. * @throws Exception (if the update fails)
  474. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  475. */
  476. public function updateUri(string $uri)
  477. {
  478. $orig = clone($this);
  479. $this->uri = $uri;
  480. $this->updateWithKeys($orig);
  481. }
  482. /**
  483. * Getter for the number of subscribers of a
  484. * given local profile
  485. *
  486. * @param Profile $profile profile object
  487. * @return int number of subscribers
  488. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  489. */
  490. public static function subscriberCount(Profile $profile): int
  491. {
  492. $cnt = self::cacheGet(sprintf('activitypub_profile:subscriberCount:%d', $profile->id));
  493. if ($cnt !== false && is_int($cnt)) {
  494. return $cnt;
  495. }
  496. $sub = new Subscription();
  497. $sub->subscribed = $profile->id;
  498. $sub->whereAdd('subscriber != subscribed');
  499. $sub->whereAdd('subscriber IN (SELECT id FROM user UNION SELECT profile_id FROM activitypub_profile)');
  500. $cnt = $sub->count('distinct subscriber');
  501. self::cacheSet(sprintf('activitypub_profile:subscriberCount:%d', $profile->id), $cnt);
  502. return $cnt;
  503. }
  504. /**
  505. * Getter for the number of subscriptions of a
  506. * given local profile
  507. *
  508. * @param Profile $profile profile object
  509. * @return int number of subscriptions
  510. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  511. */
  512. public static function subscriptionCount(Profile $profile): int
  513. {
  514. $cnt = self::cacheGet(sprintf('activitypub_profile:subscriptionCount:%d', $profile->id));
  515. if ($cnt !== false && is_int($cnt)) {
  516. return $cnt;
  517. }
  518. $sub = new Subscription();
  519. $sub->subscriber = $profile->id;
  520. $sub->whereAdd('subscriber != subscribed');
  521. $sub->whereAdd('subscribed IN (SELECT id FROM user UNION SELECT profile_id FROM activitypub_profile)');
  522. $cnt = $sub->count('distinct subscribed');
  523. self::cacheSet(sprintf('activitypub_profile:subscriptionCount:%d', $profile->id), $cnt);
  524. return $cnt;
  525. }
  526. public static function updateSubscriberCount(Profile $profile, $adder)
  527. {
  528. $cnt = self::cacheGet(sprintf('activitypub_profile:subscriberCount:%d', $profile->id));
  529. if ($cnt !== false && is_int($cnt)) {
  530. self::cacheSet(sprintf('activitypub_profile:subscriberCount:%d', $profile->id), $cnt + $adder);
  531. }
  532. }
  533. public static function updateSubscriptionCount(Profile $profile, $adder)
  534. {
  535. $cnt = self::cacheGet(sprintf('activitypub_profile:subscriptionCount:%d', $profile->id));
  536. if ($cnt !== false && is_int($cnt)) {
  537. self::cacheSet(sprintf('activitypub_profile:subscriptionCount:%d', $profile->id), $cnt + $adder);
  538. }
  539. }
  540. /**
  541. * Getter for the subscriber profiles of a
  542. * given local profile
  543. *
  544. * @param Profile $profile profile object
  545. * @param int $offset index of the starting row to fetch from
  546. * @param int $limit maximum number of rows allowed for fetching
  547. * @return array subscriber profile objects
  548. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  549. */
  550. public static function getSubscribers(Profile $profile, $offset = 0, $limit = null): array
  551. {
  552. $cache = false;
  553. if ($offset + $limit <= Subscription::CACHE_WINDOW) {
  554. $subs = self::cacheGet(sprintf('activitypub_profile:subscriberCollection:%d', $profile->id));
  555. if ($subs !== false && is_array($subs)) {
  556. return array_slice($subs, $offset, $limit);
  557. }
  558. $cache = true;
  559. }
  560. $subs = Subscription::getSubscriberIDs($profile->id, $offset, $limit);
  561. $profiles = [];
  562. $users = User::multiGet('id', $subs);
  563. foreach ($users->fetchAll() as $user) {
  564. $profiles[$user->id] = $user->getProfile();
  565. }
  566. $ap_profiles = Activitypub_profile::multiGet('profile_id', $subs);
  567. foreach ($ap_profiles->fetchAll() as $ap) {
  568. $profiles[$ap->getID()] = $ap->local_profile();
  569. }
  570. if ($cache) {
  571. self::cacheSet(sprintf('activitypub_profile:subscriberCollection:%d', $profile->id), $profiles);
  572. }
  573. return $profiles;
  574. }
  575. /**
  576. * Getter for the subscribed profiles of a
  577. * given local profile
  578. *
  579. * @param Profile $profile profile object
  580. * @param int $offset index of the starting row to fetch from
  581. * @param int $limit maximum number of rows allowed for fetching
  582. * @return array subscribed profile objects
  583. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  584. */
  585. public static function getSubscribed(Profile $profile, $offset = 0, $limit = null): array
  586. {
  587. $cache = false;
  588. if ($offset + $limit <= Subscription::CACHE_WINDOW) {
  589. $subs = self::cacheGet(sprintf('activitypub_profile:subscribedCollection:%d', $profile->id));
  590. if (is_array($subs)) {
  591. return array_slice($subs, $offset, $limit);
  592. }
  593. $cache = true;
  594. }
  595. $subs = Subscription::getSubscribedIDs($profile->id, $offset, $limit);
  596. try {
  597. $profiles = [];
  598. $users = User::multiGet('id', $subs);
  599. foreach ($users->fetchAll() as $user) {
  600. $profiles[$user->id] = $user->getProfile();
  601. }
  602. $ap_profiles = Activitypub_profile::multiGet('profile_id', $subs);
  603. foreach ($ap_profiles->fetchAll() as $ap) {
  604. $profiles[$ap->getID()] = $ap->local_profile();
  605. }
  606. } catch (NoResultException $e) {
  607. return $e->obj;
  608. }
  609. if ($cache) {
  610. self::cacheSet(sprintf('activitypub_profile:subscribedCollection:%d', $profile->id), $profiles);
  611. }
  612. return $profiles;
  613. }
  614. /**
  615. * Update cached values that are relevant to
  616. * the users involved in a subscription
  617. *
  618. * @param Profile $actor subscriber profile object
  619. * @param Profile $other subscribed profile object
  620. * @return void
  621. * @throws Exception
  622. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  623. */
  624. public static function subscribeCacheUpdate(Profile $actor, Profile $other)
  625. {
  626. self::blow('activitypub_profile:subscribedCollection:%d', $actor->getID());
  627. self::blow('activitypub_profile:subscriberCollection:%d', $other->id);
  628. self::updateSubscriptionCount($actor, +1);
  629. self::updateSubscriberCount($other, +1);
  630. }
  631. /**
  632. * Update cached values that are relevant to
  633. * the users involved in an unsubscription
  634. *
  635. * @param Profile $actor subscriber profile object
  636. * @param Profile $other subscribed profile object
  637. * @return void
  638. * @throws Exception
  639. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  640. */
  641. public static function unsubscribeCacheUpdate(Profile $actor, Profile $other)
  642. {
  643. self::blow('activitypub_profile:subscribedCollection:%d', $actor->getID());
  644. self::blow('activitypub_profile:subscriberCollection:%d', $other->id);
  645. self::updateSubscriptionCount($actor, -1);
  646. self::updateSubscriberCount($other, -1);
  647. }
  648. }