Activitypub_profile.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  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()
  48. public $modified; // timestamp() 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', 'description' => 'date this record was created'],
  64. 'modified' => ['type' => 'timestamp', 'not null' => true, '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 $profile): array
  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(): void
  141. {
  142. // Does any other protocol have this remote entity we're about to add ?
  143. Event::handle('StartTFNLookup', [$this->uri, get_class($this), &$profile_id]);
  144. if (!is_null($profile_id)) {
  145. // Yes! Avoid creating a new profile
  146. $this->profile_id = $profile_id;
  147. $this->created = $this->modified = common_sql_now();
  148. if ($this->insert() === false) {
  149. $this->query('ROLLBACK');
  150. throw new ServerException('Cannot save ActivityPub profile.');
  151. }
  152. // Update existing profile with received data
  153. $profile = Profile::getKV('id', $profile_id);
  154. self::update_local_profile($profile, $this);
  155. // Ask TFN to handle profile duplication
  156. Event::handle('EndTFNLookup', [get_class($this), $profile_id]);
  157. } else {
  158. // No, create both a new profile and remote profile
  159. $profile = new Profile();
  160. $profile->created = $this->created = $this->modified = common_sql_now();
  161. self::update_local_profile($profile, $this);
  162. $this->profile_id = $profile->insert();
  163. if ($this->profile_id === false) {
  164. $profile->query('ROLLBACK');
  165. throw new ServerException('Profile insertion failed.');
  166. }
  167. $ok = $this->insert();
  168. if ($ok === false) {
  169. $profile->query('ROLLBACK');
  170. $this->query('ROLLBACK');
  171. throw new ServerException('Cannot save ActivityPub profile.');
  172. }
  173. }
  174. }
  175. /**
  176. * Fetch the locally stored profile for this Activitypub_profile
  177. *
  178. * @return Profile
  179. * @throws NoProfileException if it was not found
  180. * @author Diogo Cordeiro <diogo@fc.up.pt>
  181. */
  182. public function local_profile(): Profile
  183. {
  184. $profile = Profile::getKV('id', $this->profile_id);
  185. if (!$profile instanceof Profile) {
  186. throw new NoProfileException($this->profile_id);
  187. }
  188. return $profile;
  189. }
  190. /**
  191. * Generates an Activitypub_profile from a Profile
  192. *
  193. * @param Profile $profile
  194. * @return Activitypub_profile
  195. * @throws Exception if no Activitypub_profile exists for given Profile
  196. * @author Diogo Cordeiro <diogo@fc.up.pt>
  197. */
  198. public static function from_profile(Profile $profile): Activitypub_profile
  199. {
  200. $profile_id = $profile->getID();
  201. $aprofile = self::getKV('profile_id', $profile_id);
  202. if (!$aprofile instanceof Activitypub_profile) {
  203. // No Activitypub_profile for this profile_id,
  204. if (!$profile->isLocal()) {
  205. // create one!
  206. $aprofile = self::create_from_local_profile($profile);
  207. } else {
  208. throw new Exception('No Activitypub_profile for Profile ID: ' . $profile_id . ', this is a local user.');
  209. }
  210. }
  211. // extend the ap_profile with some information we
  212. // don't store in the database
  213. $fields = [
  214. 'nickname' => 'nickname',
  215. 'fullname' => 'fullname',
  216. 'bio' => 'bio'
  217. ];
  218. foreach ($fields as $af => $pf) {
  219. $aprofile->$af = $profile->$pf;
  220. }
  221. return $aprofile;
  222. }
  223. /**
  224. * Travels an array of Profile and returns an array of Activitypub_profile
  225. *
  226. * @param array of Profile $profiles
  227. * @return array of Activitypub_profile
  228. */
  229. public static function from_profile_collection(array $profiles): array
  230. {
  231. $ap_profiles = [];
  232. foreach ($profiles as $profile) {
  233. try {
  234. $ap_profiles[] = self::from_profile($profile);
  235. } catch (Exception $e) {
  236. // Don't mind local profiles
  237. }
  238. }
  239. return $ap_profiles;
  240. }
  241. /**
  242. * Given an existent local profile creates an ActivityPub profile.
  243. * One must be careful not to give a user profile to this function
  244. * as only remote users have ActivityPub_profiles on local instance
  245. *
  246. * @param Profile $profile
  247. * @return Activitypub_profile
  248. * @throws HTTP_Request2_Exception
  249. * @throws Exception
  250. * @throws Exception
  251. * @author Diogo Cordeiro <diogo@fc.up.pt>
  252. */
  253. private static function create_from_local_profile(Profile $profile): Activitypub_profile
  254. {
  255. $aprofile = new Activitypub_profile();
  256. $url = $profile->getUri();
  257. $inboxes = Activitypub_explorer::get_actor_inboxes_uri($url);
  258. if ($inboxes === false) {
  259. throw new Exception('This is not an ActivityPub user thus AProfile is politely refusing to proceed.');
  260. }
  261. $aprofile->created = $aprofile->modified = common_sql_now();
  262. $aprofile->profile_id = $profile->getID();
  263. $aprofile->uri = $url;
  264. $aprofile->nickname = $profile->getNickname();
  265. $aprofile->fullname = $profile->getFullname();
  266. $aprofile->bio = substr($profile->getDescription(), 0, 1000);
  267. $aprofile->inboxuri = $inboxes["inbox"];
  268. $aprofile->sharedInboxuri = $inboxes["sharedInbox"];
  269. $aprofile->insert();
  270. return $aprofile;
  271. }
  272. /**
  273. * Returns sharedInbox if possible, inbox otherwise
  274. *
  275. * @return string Inbox URL
  276. * @author Diogo Cordeiro <diogo@fc.up.pt>
  277. */
  278. public function get_inbox(): string
  279. {
  280. if (is_null($this->sharedInboxuri)) {
  281. return $this->inboxuri;
  282. }
  283. return $this->sharedInboxuri;
  284. }
  285. /**
  286. * Getter for uri property
  287. *
  288. * @return string URI
  289. * @author Diogo Cordeiro <diogo@fc.up.pt>
  290. */
  291. public function getUri(): string
  292. {
  293. return $this->uri;
  294. }
  295. /**
  296. * Getter for url property
  297. *
  298. * @return string URL
  299. * @author Diogo Cordeiro <diogo@fc.up.pt>
  300. */
  301. public function getUrl(): string
  302. {
  303. return $this->getUri();
  304. }
  305. /**
  306. * Getter for id property
  307. *
  308. * @return int
  309. * @author Diogo Cordeiro <diogo@fc.up.pt>
  310. */
  311. public function getID(): int
  312. {
  313. return $this->profile_id;
  314. }
  315. /**
  316. * Ensures a valid Activitypub_profile when provided with a valid URI.
  317. *
  318. * @param string $url
  319. * @param bool $grab_online whether to try online grabbing, defaults to true
  320. * @return Activitypub_profile
  321. * @throws Exception if it isn't possible to return an Activitypub_profile
  322. * @author Diogo Cordeiro <diogo@fc.up.pt>
  323. */
  324. public static function fromUri(string $url, bool $grab_online = true): Activitypub_profile
  325. {
  326. try {
  327. return self::from_profile(Activitypub_explorer::get_profile_from_url($url, $grab_online));
  328. } catch (Exception $e) {
  329. throw new Exception('No valid ActivityPub profile found for given URI.');
  330. }
  331. }
  332. /**
  333. * Look up, and if necessary create, an Activitypub_profile for the remote
  334. * entity with the given WebFinger address.
  335. * This should never return null -- you will either get an object or
  336. * an exception will be thrown.
  337. *
  338. * @param string $addr WebFinger address
  339. * @return Activitypub_profile
  340. * @throws Exception on error conditions
  341. * @author Diogo Cordeiro <diogo@fc.up.pt>
  342. * @author GNU social
  343. */
  344. public static function ensure_webfinger(string $addr): Activitypub_profile
  345. {
  346. // Normalize $addr, i.e. add 'acct:' if missing
  347. $addr = Discovery::normalize($addr);
  348. // Try the cache
  349. $uri = self::cacheGet(sprintf('activitypub_profile:webfinger:%s', $addr));
  350. if ($uri !== false) {
  351. if (is_null($uri)) {
  352. // Negative cache entry
  353. // TRANS: Exception.
  354. throw new Exception(_m('Not a valid WebFinger address (via cache).'));
  355. }
  356. try {
  357. return self::fromUri($uri);
  358. } catch (Exception $e) {
  359. common_log(LOG_ERR, sprintf(__METHOD__ . ': WebFinger address cache inconsistent with database, did not find Activitypub_profile uri==%s', $uri));
  360. self::cacheSet(sprintf('activitypub_profile:webfinger:%s', $addr), false);
  361. }
  362. }
  363. // Now, try some discovery
  364. $disco = new Discovery();
  365. try {
  366. $xrd = $disco->lookup($addr);
  367. } catch (Exception $e) {
  368. // Save negative cache entry so we don't waste time looking it up again.
  369. // @todo FIXME: Distinguish temporary failures?
  370. self::cacheSet(sprintf('activitypub_profile:webfinger:%s', $addr), null);
  371. // TRANS: Exception.
  372. throw new Exception(_m('Not a valid WebFinger address.'));
  373. }
  374. $hints = array_merge(
  375. ['webfinger' => $addr],
  376. DiscoveryHints::fromXRD($xrd)
  377. );
  378. // If there's an Hcard, let's grab its info
  379. if (array_key_exists('hcard', $hints)) {
  380. if (!array_key_exists('profileurl', $hints) ||
  381. $hints['hcard'] != $hints['profileurl']) {
  382. $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
  383. $hints = array_merge($hcardHints, $hints);
  384. }
  385. }
  386. // If we got a profile page, try that!
  387. $profileUrl = null;
  388. if (array_key_exists('profileurl', $hints)) {
  389. $profileUrl = $hints['profileurl'];
  390. try {
  391. common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
  392. $aprofile = self::fromUri($hints['profileurl']);
  393. self::cacheSet(sprintf('activitypub_profile:webfinger:%s', $addr), $aprofile->getUri());
  394. return $aprofile;
  395. } catch (Exception $e) {
  396. common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
  397. // keep looking
  398. //
  399. // @todo FIXME: This means an error discovering from profile page
  400. // may give us a corrupt entry using the webfinger URI, which
  401. // will obscure the correct page-keyed profile later on.
  402. }
  403. }
  404. // XXX: try hcard
  405. // XXX: try FOAF
  406. // TRANS: Exception. %s is a WebFinger address.
  407. throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'), $addr));
  408. }
  409. /**
  410. * Update local profile with info from some AP profile
  411. *
  412. * @param Profile $profile
  413. * @param Activitypub_profile $aprofile
  414. * @return void
  415. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  416. * @author Diogo Cordeiro <diogo@fc.up.pt>
  417. */
  418. public static function update_local_profile(Profile $profile, Activitypub_profile $aprofile): void
  419. {
  420. $fields = [
  421. 'profileurl' => 'profileurl',
  422. 'nickname' => 'nickname',
  423. 'fullname' => 'fullname',
  424. 'bio' => 'bio'
  425. ];
  426. $orig = clone($profile);
  427. foreach ($fields as $af => $pf) {
  428. $profile->$pf = $aprofile->$af;
  429. }
  430. if ($profile->id) {
  431. common_debug('Updating local Profile:' . $profile->id . ' from remote ActivityPub profile');
  432. $profile->modified = common_sql_now();
  433. $profile->update($orig);
  434. }
  435. }
  436. /**
  437. * Update remote user profile in local instance
  438. *
  439. * @param Activitypub_profile $aprofile
  440. * @param array|false $res remote response, if array it updates, if false it deletes
  441. * @return Profile remote Profile object
  442. * @throws NoProfileException
  443. * @author Diogo Cordeiro <diogo@fc.up.pt>
  444. */
  445. public static function update_profile(Activitypub_profile $aprofile, $res): Profile
  446. {
  447. if ($res === false) {
  448. $profile = $aprofile->local_profile();
  449. $id = $profile->getID();
  450. $profile->delete();
  451. throw new NoProfileException($id, "410 Gone");
  452. }
  453. if (!is_array($res)) {
  454. throw new InvalidArgumentException('TypeError: Argument 2 passed to Activitypub_profile::update_profile() must be of the type array or bool(false).');
  455. }
  456. // ActivityPub Profile
  457. $aprofile->uri = $res['id'];
  458. $aprofile->nickname = $res['preferredUsername'];
  459. $aprofile->fullname = $res['name'] ?? null;
  460. $aprofile->bio = isset($res['summary']) ? substr(strip_tags($res['summary']), 0, 1000) : null;
  461. $aprofile->inboxuri = $res['inbox'];
  462. $aprofile->sharedInboxuri = $res['endpoints']['sharedInbox'] ?? $res['inbox'];
  463. $aprofile->profileurl = $res['url'] ?? $aprofile->uri;
  464. $aprofile->modified = common_sql_now();
  465. $profile = $aprofile->local_profile();
  466. // Profile
  467. self::update_local_profile($profile, $aprofile);
  468. $aprofile->update();
  469. // Public Key
  470. Activitypub_rsa::update_public_key($profile, $res['publicKey']['publicKeyPem']);
  471. // Avatar
  472. if (isset($res['icon']['url'])) {
  473. try {
  474. Activitypub_explorer::update_avatar($profile, $res['icon']['url']);
  475. } catch (Exception $e) {
  476. // Let the exception go, it isn't a serious issue
  477. common_debug('An error ocurred while grabbing remote avatar' . $e->getMessage());
  478. }
  479. }
  480. return $profile;
  481. }
  482. /**
  483. * Update remote user profile URI in local instance
  484. *
  485. * @param string $uri
  486. * @return void
  487. * @throws Exception (if the update fails)
  488. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  489. */
  490. public function updateUri(string $uri): void
  491. {
  492. $orig = clone($this);
  493. $this->uri = $uri;
  494. $this->updateWithKeys($orig);
  495. }
  496. /**
  497. * Getter for the number of subscribers of a
  498. * given local profile
  499. *
  500. * @param Profile $profile profile object
  501. * @return int number of subscribers
  502. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  503. */
  504. public static function subscriberCount(Profile $profile): int
  505. {
  506. $cnt = self::cacheGet(sprintf('activitypub_profile:subscriberCount:%d', $profile->id));
  507. if ($cnt !== false && is_int($cnt)) {
  508. return $cnt;
  509. }
  510. $user_table = common_database_tablename('user');
  511. $sub = new Subscription();
  512. $sub->subscribed = $profile->id;
  513. $sub->_join .= "\n" . <<<END
  514. INNER JOIN (
  515. SELECT id AS subscriber FROM {$user_table}
  516. UNION ALL
  517. SELECT profile_id FROM activitypub_profile
  518. ) AS t1 USING (subscriber)
  519. END;
  520. $sub->whereAdd('subscriber <> subscribed');
  521. $cnt = $sub->count('DISTINCT subscriber');
  522. self::cacheSet(sprintf('activitypub_profile:subscriberCount:%d', $profile->id), $cnt);
  523. return $cnt;
  524. }
  525. /**
  526. * Getter for the number of subscriptions of a
  527. * given local profile
  528. *
  529. * @param Profile $profile profile object
  530. * @return int number of subscriptions
  531. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  532. */
  533. public static function subscriptionCount(Profile $profile): int
  534. {
  535. $cnt = self::cacheGet(sprintf('activitypub_profile:subscriptionCount:%d', $profile->id));
  536. if ($cnt !== false && is_int($cnt)) {
  537. return $cnt;
  538. }
  539. $user_table = common_database_tablename('user');
  540. $sub = new Subscription();
  541. $sub->subscriber = $profile->id;
  542. $sub->_join .= "\n" . <<<END
  543. INNER JOIN (
  544. SELECT id AS subscribed FROM {$user_table}
  545. UNION ALL
  546. SELECT profile_id FROM activitypub_profile
  547. ) AS t1 USING (subscribed)
  548. END;
  549. $sub->whereAdd('subscriber <> subscribed');
  550. $cnt = $sub->count('DISTINCT subscribed');
  551. self::cacheSet(sprintf('activitypub_profile:subscriptionCount:%d', $profile->id), $cnt);
  552. return $cnt;
  553. }
  554. /**
  555. * Increment or decrement subscriber count
  556. *
  557. * @param Profile $profile
  558. * @param $adder
  559. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  560. */
  561. public static function updateSubscriberCount(Profile $profile, $adder): void
  562. {
  563. $cnt = self::cacheGet(sprintf('activitypub_profile:subscriberCount:%d', $profile->id));
  564. if ($cnt !== false && is_int($cnt)) {
  565. self::cacheSet(sprintf('activitypub_profile:subscriberCount:%d', $profile->id), $cnt + $adder);
  566. }
  567. }
  568. /**
  569. * Increment or decrement subscription count
  570. *
  571. * @param Profile $profile
  572. * @param $adder
  573. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  574. */
  575. public static function updateSubscriptionCount(Profile $profile, $adder): void
  576. {
  577. $cnt = self::cacheGet(sprintf('activitypub_profile:subscriptionCount:%d', $profile->id));
  578. if ($cnt !== false && is_int($cnt)) {
  579. self::cacheSet(sprintf('activitypub_profile:subscriptionCount:%d', $profile->id), $cnt + $adder);
  580. }
  581. }
  582. /**
  583. * Getter for the subscriber profiles of a
  584. * given local profile
  585. *
  586. * @param Profile $profile profile object
  587. * @param int $offset [optional] index of the starting row to fetch from
  588. * @param int|null $limit [optional] maximum number of rows allowed for fetching. If it is omitted,
  589. * then the sequence will have everything
  590. * from offset up until the end.
  591. * @return array subscriber profile objects
  592. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  593. */
  594. public static function getSubscribers(Profile $profile, int $offset = 0, ?int $limit = null): array
  595. {
  596. $cache = false;
  597. if ($offset + $limit <= Subscription::CACHE_WINDOW) {
  598. $subs = self::cacheGet(sprintf('activitypub_profile:subscriberCollection:%d', $profile->id));
  599. if ($subs !== false && is_array($subs)) {
  600. return array_slice($subs, $offset, $limit);
  601. }
  602. $cache = true;
  603. }
  604. $subs = Subscription::getSubscriberIDs($profile->id, $offset, $limit);
  605. $profiles = [];
  606. $users = User::multiGet('id', $subs);
  607. foreach ($users->fetchAll() as $user) {
  608. $profiles[$user->id] = $user->getProfile();
  609. }
  610. $ap_profiles = Activitypub_profile::multiGet('profile_id', $subs);
  611. foreach ($ap_profiles->fetchAll() as $ap) {
  612. $profiles[$ap->getID()] = $ap->local_profile();
  613. }
  614. if ($cache) {
  615. self::cacheSet(sprintf('activitypub_profile:subscriberCollection:%d', $profile->id), $profiles);
  616. }
  617. return $profiles;
  618. }
  619. /**
  620. * Getter for the subscribed profiles of a
  621. * given local profile
  622. *
  623. * @param Profile $profile profile object
  624. * @param int $offset index of the starting row to fetch from
  625. * @param int|null $limit maximum number of rows allowed for fetching
  626. * @return array subscribed profile objects
  627. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  628. */
  629. public static function getSubscribed(Profile $profile, int $offset = 0, ?int $limit = null): array
  630. {
  631. $cache = false;
  632. if ($offset + $limit <= Subscription::CACHE_WINDOW) {
  633. $subs = self::cacheGet(sprintf('activitypub_profile:subscribedCollection:%d', $profile->id));
  634. if (is_array($subs)) {
  635. return array_slice($subs, $offset, $limit);
  636. }
  637. $cache = true;
  638. }
  639. $subs = Subscription::getSubscribedIDs($profile->id, $offset, $limit);
  640. $profiles = [];
  641. $users = User::multiGet('id', $subs);
  642. foreach ($users->fetchAll() as $user) {
  643. $profiles[$user->id] = $user->getProfile();
  644. }
  645. $ap_profiles = Activitypub_profile::multiGet('profile_id', $subs);
  646. foreach ($ap_profiles->fetchAll() as $ap) {
  647. $profiles[$ap->getID()] = $ap->local_profile();
  648. }
  649. if ($cache) {
  650. self::cacheSet(sprintf('activitypub_profile:subscribedCollection:%d', $profile->id), $profiles);
  651. }
  652. return $profiles;
  653. }
  654. /**
  655. * Update cached values that are relevant to
  656. * the users involved in a subscription
  657. *
  658. * @param Profile $actor subscriber profile object
  659. * @param Profile $other subscribed profile object
  660. * @return void
  661. * @throws Exception
  662. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  663. */
  664. public static function subscribeCacheUpdate(Profile $actor, Profile $other): void
  665. {
  666. self::blow('activitypub_profile:subscribedCollection:%d', $actor->getID());
  667. self::blow('activitypub_profile:subscriberCollection:%d', $other->id);
  668. self::updateSubscriptionCount($actor, +1);
  669. self::updateSubscriberCount($other, +1);
  670. }
  671. /**
  672. * Update cached values that are relevant to
  673. * the users involved in an unsubscription
  674. *
  675. * @param Profile $actor subscriber profile object
  676. * @param Profile $other subscribed profile object
  677. * @return void
  678. * @throws Exception
  679. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  680. */
  681. public static function unsubscribeCacheUpdate(Profile $actor, Profile $other): void
  682. {
  683. self::blow('activitypub_profile:subscribedCollection:%d', $actor->getID());
  684. self::blow('activitypub_profile:subscriberCollection:%d', $other->id);
  685. self::updateSubscriptionCount($actor, -1);
  686. self::updateSubscriberCount($other, -1);
  687. }
  688. }