Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1810 lines
50 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. <?php
  2. /**
  3. * @file src/Protocol/ActivityPub.php
  4. */
  5. namespace Friendica\Protocol;
  6. use Friendica\Database\DBA;
  7. use Friendica\Core\System;
  8. use Friendica\BaseObject;
  9. use Friendica\Util\Network;
  10. use Friendica\Util\HTTPSignature;
  11. use Friendica\Core\Protocol;
  12. use Friendica\Model\Conversation;
  13. use Friendica\Model\Contact;
  14. use Friendica\Model\APContact;
  15. use Friendica\Model\Item;
  16. use Friendica\Model\Profile;
  17. use Friendica\Model\Term;
  18. use Friendica\Model\User;
  19. use Friendica\Util\DateTimeFormat;
  20. use Friendica\Util\Crypto;
  21. use Friendica\Content\Text\BBCode;
  22. use Friendica\Content\Text\HTML;
  23. use Friendica\Util\JsonLD;
  24. use Friendica\Util\LDSignature;
  25. use Friendica\Core\Config;
  26. /**
  27. * @brief ActivityPub Protocol class
  28. * The ActivityPub Protocol is a message exchange protocol defined by the W3C.
  29. * https://www.w3.org/TR/activitypub/
  30. * https://www.w3.org/TR/activitystreams-core/
  31. * https://www.w3.org/TR/activitystreams-vocabulary/
  32. *
  33. * https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/
  34. * https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
  35. *
  36. * Digest: https://tools.ietf.org/html/rfc5843
  37. * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
  38. *
  39. * Mastodon implementation of supported activities:
  40. * https://github.com/tootsuite/mastodon/blob/master/app/lib/activitypub/activity.rb#L26
  41. *
  42. * To-do:
  43. *
  44. * Receiver:
  45. * - Update Note
  46. * - Delete Note
  47. * - Delete Person
  48. * - Undo Announce
  49. * - Reject Follow
  50. * - Undo Accept
  51. * - Undo Follow
  52. * - Add
  53. * - Create Image
  54. * - Create Video
  55. * - Event
  56. * - Remove
  57. * - Block
  58. * - Flag
  59. *
  60. * Transmitter:
  61. * - Announce
  62. * - Undo Announce
  63. * - Update Person
  64. * - Reject Follow
  65. * - Event
  66. *
  67. * General:
  68. * - Attachments
  69. * - nsfw (sensitive)
  70. * - Queueing unsucessful deliveries
  71. * - Polling the outboxes for missing content?
  72. * - Possibly using the LD-JSON parser
  73. */
  74. class ActivityPub
  75. {
  76. const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
  77. const CONTEXT = ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
  78. ['vcard' => 'http://www.w3.org/2006/vcard/ns#',
  79. 'diaspora' => 'https://diasporafoundation.org/ns/',
  80. 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers',
  81. 'sensitive' => 'as:sensitive', 'Hashtag' => 'as:Hashtag']];
  82. /**
  83. * @brief Checks if the web request is done for the AP protocol
  84. *
  85. * @return is it AP?
  86. */
  87. public static function isRequest()
  88. {
  89. return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
  90. stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
  91. }
  92. /**
  93. * @brief collects the lost of followers of the given owner
  94. *
  95. * @param array $owner Owner array
  96. * @param integer $page Page number
  97. *
  98. * @return array of owners
  99. */
  100. public static function getFollowers($owner, $page = null)
  101. {
  102. $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
  103. 'self' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
  104. $count = DBA::count('contact', $condition);
  105. $data = ['@context' => self::CONTEXT];
  106. $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
  107. $data['type'] = 'OrderedCollection';
  108. $data['totalItems'] = $count;
  109. // When we hide our friends we will only show the pure number but don't allow more.
  110. $profile = Profile::getProfileForUser($owner['uid']);
  111. if (!empty($profile['hide-friends'])) {
  112. return $data;
  113. }
  114. if (empty($page)) {
  115. $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
  116. } else {
  117. $list = [];
  118. $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
  119. while ($contact = DBA::fetch($contacts)) {
  120. $list[] = $contact['url'];
  121. }
  122. if (!empty($list)) {
  123. $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
  124. }
  125. $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
  126. $data['orderedItems'] = $list;
  127. }
  128. return $data;
  129. }
  130. /**
  131. * @brief Create list of following contacts
  132. *
  133. * @param array $owner Owner array
  134. * @param integer $page Page numbe
  135. *
  136. * @return array of following contacts
  137. */
  138. public static function getFollowing($owner, $page = null)
  139. {
  140. $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
  141. 'self' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
  142. $count = DBA::count('contact', $condition);
  143. $data = ['@context' => self::CONTEXT];
  144. $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
  145. $data['type'] = 'OrderedCollection';
  146. $data['totalItems'] = $count;
  147. // When we hide our friends we will only show the pure number but don't allow more.
  148. $profile = Profile::getProfileForUser($owner['uid']);
  149. if (!empty($profile['hide-friends'])) {
  150. return $data;
  151. }
  152. if (empty($page)) {
  153. $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
  154. } else {
  155. $list = [];
  156. $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
  157. while ($contact = DBA::fetch($contacts)) {
  158. $list[] = $contact['url'];
  159. }
  160. if (!empty($list)) {
  161. $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
  162. }
  163. $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
  164. $data['orderedItems'] = $list;
  165. }
  166. return $data;
  167. }
  168. /**
  169. * @brief Public posts for the given owner
  170. *
  171. * @param array $owner Owner array
  172. * @param integer $page Page numbe
  173. *
  174. * @return array of posts
  175. */
  176. public static function getOutbox($owner, $page = null)
  177. {
  178. $public_contact = Contact::getIdForURL($owner['url'], 0, true);
  179. $condition = ['uid' => $owner['uid'], 'contact-id' => $owner['id'], 'author-id' => $public_contact,
  180. 'wall' => true, 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
  181. 'deleted' => false, 'visible' => true];
  182. $count = DBA::count('item', $condition);
  183. $data = ['@context' => self::CONTEXT];
  184. $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
  185. $data['type'] = 'OrderedCollection';
  186. $data['totalItems'] = $count;
  187. if (empty($page)) {
  188. $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
  189. } else {
  190. $list = [];
  191. $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
  192. $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
  193. while ($item = Item::fetch($items)) {
  194. $object = self::createObjectFromItemID($item['id']);
  195. unset($object['@context']);
  196. $list[] = $object;
  197. }
  198. if (!empty($list)) {
  199. $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
  200. }
  201. $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
  202. $data['orderedItems'] = $list;
  203. }
  204. return $data;
  205. }
  206. /**
  207. * Return the ActivityPub profile of the given user
  208. *
  209. * @param integer $uid User ID
  210. * @return profile array
  211. */
  212. public static function profile($uid)
  213. {
  214. $accounttype = ['Person', 'Organization', 'Service', 'Group', 'Application'];
  215. $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
  216. 'account_removed' => false, 'verified' => true];
  217. $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
  218. $user = DBA::selectFirst('user', $fields, $condition);
  219. if (!DBA::isResult($user)) {
  220. return [];
  221. }
  222. $fields = ['locality', 'region', 'country-name'];
  223. $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
  224. if (!DBA::isResult($profile)) {
  225. return [];
  226. }
  227. $fields = ['name', 'url', 'location', 'about', 'avatar'];
  228. $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
  229. if (!DBA::isResult($contact)) {
  230. return [];
  231. }
  232. $data = ['@context' => self::CONTEXT];
  233. $data['id'] = $contact['url'];
  234. $data['diaspora:guid'] = $user['guid'];
  235. $data['type'] = $accounttype[$user['account-type']];
  236. $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
  237. $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
  238. $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
  239. $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
  240. $data['preferredUsername'] = $user['nickname'];
  241. $data['name'] = $contact['name'];
  242. $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
  243. 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
  244. $data['summary'] = $contact['about'];
  245. $data['url'] = $contact['url'];
  246. $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
  247. $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
  248. 'owner' => $contact['url'],
  249. 'publicKeyPem' => $user['pubkey']];
  250. $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
  251. $data['icon'] = ['type' => 'Image',
  252. 'url' => $contact['avatar']];
  253. // tags: https://kitty.town/@inmysocks/100656097926961126.json
  254. return $data;
  255. }
  256. /**
  257. * @brief Returns an array with permissions of a given item array
  258. *
  259. * @param array $item
  260. *
  261. * @return array with permissions
  262. */
  263. private static function fetchPermissionBlockFromConversation($item)
  264. {
  265. if (empty($item['thr-parent'])) {
  266. return [];
  267. }
  268. $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
  269. $conversation = DBA::selectFirst('conversation', ['source'], $condition);
  270. if (!DBA::isResult($conversation)) {
  271. return [];
  272. }
  273. $activity = json_decode($conversation['source'], true);
  274. $actor = JsonLD::fetchElement($activity, 'actor', 'id');
  275. $profile = APContact::getProfileByURL($actor);
  276. $item_profile = APContact::getProfileByURL($item['author-link']);
  277. $exclude[] = $item['author-link'];
  278. if ($item['gravity'] == GRAVITY_PARENT) {
  279. $exclude[] = $item['owner-link'];
  280. }
  281. $permissions['to'][] = $actor;
  282. $elements = ['to', 'cc', 'bto', 'bcc'];
  283. foreach ($elements as $element) {
  284. if (empty($activity[$element])) {
  285. continue;
  286. }
  287. if (is_string($activity[$element])) {
  288. $activity[$element] = [$activity[$element]];
  289. }
  290. foreach ($activity[$element] as $receiver) {
  291. if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
  292. $receiver = $item_profile['followers'];
  293. }
  294. if (!in_array($receiver, $exclude)) {
  295. $permissions[$element][] = $receiver;
  296. }
  297. }
  298. }
  299. return $permissions;
  300. }
  301. /**
  302. * @brief Creates an array of permissions from an item thread
  303. *
  304. * @param array $item
  305. *
  306. * @return permission array
  307. */
  308. public static function createPermissionBlockForItem($item)
  309. {
  310. $data = ['to' => [], 'cc' => []];
  311. $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
  312. $actor_profile = APContact::getProfileByURL($item['author-link']);
  313. $terms = Term::tagArrayFromItemId($item['id']);
  314. $contacts[$item['author-link']] = $item['author-link'];
  315. if (!$item['private']) {
  316. $data['to'][] = self::PUBLIC;
  317. if (!empty($actor_profile['followers'])) {
  318. $data['cc'][] = $actor_profile['followers'];
  319. }
  320. foreach ($terms as $term) {
  321. if ($term['type'] != TERM_MENTION) {
  322. continue;
  323. }
  324. $profile = APContact::getProfileByURL($term['url'], false);
  325. if (!empty($profile) && empty($contacts[$profile['url']])) {
  326. $data['cc'][] = $profile['url'];
  327. $contacts[$profile['url']] = $profile['url'];
  328. }
  329. }
  330. } else {
  331. $receiver_list = Item::enumeratePermissions($item);
  332. $mentioned = [];
  333. foreach ($terms as $term) {
  334. if ($term['type'] != TERM_MENTION) {
  335. continue;
  336. }
  337. $cid = Contact::getIdForURL($term['url'], $item['uid']);
  338. if (!empty($cid) && in_array($cid, $receiver_list)) {
  339. $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
  340. $data['to'][] = $contact['url'];
  341. $contacts[$contact['url']] = $contact['url'];
  342. }
  343. }
  344. foreach ($receiver_list as $receiver) {
  345. $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
  346. if (empty($contacts[$contact['url']])) {
  347. $data['cc'][] = $contact['url'];
  348. $contacts[$contact['url']] = $contact['url'];
  349. }
  350. }
  351. }
  352. $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity'], ['parent' => $item['parent']]);
  353. while ($parent = Item::fetch($parents)) {
  354. // Don't include data from future posts
  355. if ($parent['id'] >= $item['id']) {
  356. continue;
  357. }
  358. $profile = APContact::getProfileByURL($parent['author-link'], false);
  359. if (!empty($profile) && empty($contacts[$profile['url']])) {
  360. $data['cc'][] = $profile['url'];
  361. $contacts[$profile['url']] = $profile['url'];
  362. }
  363. if ($item['gravity'] != GRAVITY_PARENT) {
  364. continue;
  365. }
  366. $profile = APContact::getProfileByURL($parent['owner-link'], false);
  367. if (!empty($profile) && empty($contacts[$profile['url']])) {
  368. $data['cc'][] = $profile['url'];
  369. $contacts[$profile['url']] = $profile['url'];
  370. }
  371. }
  372. DBA::close($parents);
  373. if (empty($data['to'])) {
  374. $data['to'] = $data['cc'];
  375. $data['cc'] = [];
  376. }
  377. return $data;
  378. }
  379. /**
  380. * @brief Fetches an array of inboxes for the given item and user
  381. *
  382. * @param array $item
  383. * @param integer $uid User ID
  384. *
  385. * @return array with inboxes
  386. */
  387. public static function fetchTargetInboxes($item, $uid)
  388. {
  389. $permissions = self::createPermissionBlockForItem($item);
  390. if (empty($permissions)) {
  391. return [];
  392. }
  393. $inboxes = [];
  394. if ($item['gravity'] == GRAVITY_ACTIVITY) {
  395. $item_profile = APContact::getProfileByURL($item['author-link']);
  396. } else {
  397. $item_profile = APContact::getProfileByURL($item['owner-link']);
  398. }
  399. $elements = ['to', 'cc', 'bto', 'bcc'];
  400. foreach ($elements as $element) {
  401. if (empty($permissions[$element])) {
  402. continue;
  403. }
  404. foreach ($permissions[$element] as $receiver) {
  405. if ($receiver == $item_profile['followers']) {
  406. $contacts = DBA::select('contact', ['notify', 'batch'], ['uid' => $uid,
  407. 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB,
  408. 'archive' => false, 'pending' => false]);
  409. while ($contact = DBA::fetch($contacts)) {
  410. $contact = defaults($contact, 'batch', $contact['notify']);
  411. $inboxes[$contact] = $contact;
  412. }
  413. DBA::close($contacts);
  414. } else {
  415. $profile = APContact::getProfileByURL($receiver);
  416. if (!empty($profile)) {
  417. $target = defaults($profile, 'sharedinbox', $profile['inbox']);
  418. $inboxes[$target] = $target;
  419. }
  420. }
  421. }
  422. }
  423. return $inboxes;
  424. }
  425. /**
  426. * @brief Returns the activity type of a given item
  427. *
  428. * @param array $item
  429. *
  430. * @return activity type
  431. */
  432. public static function getTypeOfItem($item)
  433. {
  434. if ($item['verb'] == ACTIVITY_POST) {
  435. if ($item['created'] == $item['edited']) {
  436. $type = 'Create';
  437. } else {
  438. $type = 'Update';
  439. }
  440. } elseif ($item['verb'] == ACTIVITY_LIKE) {
  441. $type = 'Like';
  442. } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
  443. $type = 'Dislike';
  444. } elseif ($item['verb'] == ACTIVITY_ATTEND) {
  445. $type = 'Accept';
  446. } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
  447. $type = 'Reject';
  448. } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
  449. $type = 'TentativeAccept';
  450. } else {
  451. $type = '';
  452. }
  453. return $type;
  454. }
  455. /**
  456. * @brief Creates an activity array for a given item id
  457. *
  458. * @param integer $item_id
  459. * @param boolean $object_mode Is the activity item is used inside another object?
  460. *
  461. * @return array of activity
  462. */
  463. public static function createActivityFromItem($item_id, $object_mode = false)
  464. {
  465. $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
  466. if (!DBA::isResult($item)) {
  467. return false;
  468. }
  469. $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
  470. $conversation = DBA::selectFirst('conversation', ['source'], $condition);
  471. if (DBA::isResult($conversation)) {
  472. $data = json_decode($conversation['source']);
  473. if (!empty($data)) {
  474. return $data;
  475. }
  476. }
  477. $type = self::getTypeOfItem($item);
  478. if (!$object_mode) {
  479. $data = ['@context' => self::CONTEXT];
  480. if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
  481. $type = 'Undo';
  482. } elseif ($item['deleted']) {
  483. $type = 'Delete';
  484. }
  485. } else {
  486. $data = [];
  487. }
  488. $data['id'] = $item['uri'] . '#' . $type;
  489. $data['type'] = $type;
  490. $data['actor'] = $item['author-link'];
  491. $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
  492. if ($item["created"] != $item["edited"]) {
  493. $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
  494. }
  495. $data['context'] = self::fetchContextURLForItem($item);
  496. $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
  497. if (in_array($data['type'], ['Create', 'Update', 'Announce', 'Delete'])) {
  498. $data['object'] = self::createNote($item);
  499. } elseif ($data['type'] == 'Undo') {
  500. $data['object'] = self::createActivityFromItem($item_id, true);
  501. } else {
  502. $data['object'] = $item['thr-parent'];
  503. }
  504. $owner = User::getOwnerDataById($item['uid']);
  505. if (!$object_mode) {
  506. return LDSignature::sign($data, $owner);
  507. } else {
  508. return $data;
  509. }
  510. }
  511. /**
  512. * @brief Creates an object array for a given item id
  513. *
  514. * @param integer $item_id
  515. *
  516. * @return object array
  517. */
  518. public static function createObjectFromItemID($item_id)
  519. {
  520. $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
  521. if (!DBA::isResult($item)) {
  522. return false;
  523. }
  524. $data = ['@context' => self::CONTEXT];
  525. $data = array_merge($data, self::createNote($item));
  526. return $data;
  527. }
  528. /**
  529. * @brief Returns a tag array for a given item array
  530. *
  531. * @param array $item
  532. *
  533. * @return array of tags
  534. */
  535. private static function createTagList($item)
  536. {
  537. $tags = [];
  538. $terms = Term::tagArrayFromItemId($item['id']);
  539. foreach ($terms as $term) {
  540. if ($term['type'] == TERM_MENTION) {
  541. $contact = Contact::getDetailsByURL($term['url']);
  542. if (!empty($contact['addr'])) {
  543. $mention = '@' . $contact['addr'];
  544. } else {
  545. $mention = '@' . $term['url'];
  546. }
  547. $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
  548. }
  549. }
  550. return $tags;
  551. }
  552. /**
  553. * @brief Fetches the "context" value for a givem item array from the "conversation" table
  554. *
  555. * @param array $item
  556. *
  557. * @return string with context url
  558. */
  559. private static function fetchContextURLForItem($item)
  560. {
  561. $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
  562. if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
  563. $context_uri = $conversation['conversation-href'];
  564. } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
  565. $context_uri = $conversation['conversation-uri'];
  566. } else {
  567. $context_uri = str_replace('/object/', '/context/', $item['parent-uri']);
  568. }
  569. return $context_uri;
  570. }
  571. /**
  572. * @brief Creates a note/article object array
  573. *
  574. * @param array $item
  575. *
  576. * @return object array
  577. */
  578. private static function createNote($item)
  579. {
  580. if (!empty($item['title'])) {
  581. $type = 'Article';
  582. } else {
  583. $type = 'Note';
  584. }
  585. if ($item['deleted']) {
  586. $type = 'Tombstone';
  587. }
  588. $data = [];
  589. $data['id'] = $item['uri'];
  590. $data['type'] = $type;
  591. if ($item['deleted']) {
  592. return $data;
  593. }
  594. $data['summary'] = null; // Ignore by now
  595. if ($item['uri'] != $item['thr-parent']) {
  596. $data['inReplyTo'] = $item['thr-parent'];
  597. } else {
  598. $data['inReplyTo'] = null;
  599. }
  600. $data['diaspora:guid'] = $item['guid'];
  601. $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
  602. if ($item["created"] != $item["edited"]) {
  603. $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
  604. }
  605. $data['url'] = $item['plink'];
  606. $data['attributedTo'] = $item['author-link'];
  607. $data['actor'] = $item['author-link'];
  608. $data['sensitive'] = false; // - Query NSFW
  609. $data['context'] = self::fetchContextURLForItem($item);
  610. if (!empty($item['title'])) {
  611. $data['name'] = BBCode::convert($item['title'], false, 7);
  612. }
  613. $data['content'] = BBCode::convert($item['body'], false, 7);
  614. $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
  615. if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
  616. $data['diaspora:comment'] = $item['signed_text'];
  617. }
  618. $data['attachment'] = []; // @ToDo
  619. $data['tag'] = self::createTagList($item);
  620. $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
  621. return $data;
  622. }
  623. /**
  624. * @brief Transmits a given activity to a target
  625. *
  626. * @param array $activity
  627. * @param string $target Target profile
  628. * @param integer $uid User ID
  629. */
  630. public static function transmitActivity($activity, $target, $uid)
  631. {
  632. $profile = APContact::getProfileByURL($target);
  633. $owner = User::getOwnerDataById($uid);
  634. $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
  635. 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
  636. 'type' => $activity,
  637. 'actor' => $owner['url'],
  638. 'object' => $profile['url'],
  639. 'to' => $profile['url']];
  640. logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
  641. $signed = LDSignature::sign($data, $owner);
  642. HTTPSignature::transmit($signed, $profile['inbox'], $uid);
  643. }
  644. /**
  645. * @brief Transmit a message that the contact request had been accepted
  646. *
  647. * @param string $target Target profile
  648. * @param $id
  649. * @param integer $uid User ID
  650. */
  651. public static function transmitContactAccept($target, $id, $uid)
  652. {
  653. $profile = APContact::getProfileByURL($target);
  654. $owner = User::getOwnerDataById($uid);
  655. $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
  656. 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
  657. 'type' => 'Accept',
  658. 'actor' => $owner['url'],
  659. 'object' => ['id' => $id, 'type' => 'Follow',
  660. 'actor' => $profile['url'],
  661. 'object' => $owner['url']],
  662. 'to' => $profile['url']];
  663. logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
  664. $signed = LDSignature::sign($data, $owner);
  665. HTTPSignature::transmit($signed, $profile['inbox'], $uid);
  666. }
  667. /**
  668. * @brief
  669. *
  670. * @param string $target Target profile
  671. * @param $id
  672. * @param integer $uid User ID
  673. */
  674. public static function transmitContactReject($target, $id, $uid)
  675. {
  676. $profile = APContact::getProfileByURL($target);
  677. $owner = User::getOwnerDataById($uid);
  678. $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
  679. 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
  680. 'type' => 'Reject',
  681. 'actor' => $owner['url'],
  682. 'object' => ['id' => $id, 'type' => 'Follow',
  683. 'actor' => $profile['url'],
  684. 'object' => $owner['url']],
  685. 'to' => $profile['url']];
  686. logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
  687. $signed = LDSignature::sign($data, $owner);
  688. HTTPSignature::transmit($signed, $profile['inbox'], $uid);
  689. }
  690. /**
  691. * @brief
  692. *
  693. * @param string $target Target profile
  694. * @param integer $uid User ID
  695. */
  696. public static function transmitContactUndo($target, $uid)
  697. {
  698. $profile = APContact::getProfileByURL($target);
  699. $id = System::baseUrl() . '/activity/' . System::createGUID();
  700. $owner = User::getOwnerDataById($uid);
  701. $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
  702. 'id' => $id,
  703. 'type' => 'Undo',
  704. 'actor' => $owner['url'],
  705. 'object' => ['id' => $id, 'type' => 'Follow',
  706. 'actor' => $owner['url'],
  707. 'object' => $profile['url']],
  708. 'to' => $profile['url']];
  709. logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
  710. $signed = LDSignature::sign($data, $owner);
  711. HTTPSignature::transmit($signed, $profile['inbox'], $uid);
  712. }
  713. /**
  714. * Fetches ActivityPub content from the given url
  715. *
  716. * @param string $url content url
  717. * @return array
  718. */
  719. public static function fetchContent($url)
  720. {
  721. $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json, application/ld+json']);
  722. if (!$ret['success'] || empty($ret['body'])) {
  723. return;
  724. }
  725. return json_decode($ret['body'], true);
  726. }
  727. /**
  728. * Fetches a profile from the given url into an array that is compatible to Probe::uri
  729. *
  730. * @param string $url profile url
  731. * @return array
  732. */
  733. public static function probeProfile($url)
  734. {
  735. $apcontact = APContact::getProfileByURL($url, true);
  736. if (empty($apcontact)) {
  737. return false;
  738. }
  739. $profile = ['network' => Protocol::ACTIVITYPUB];
  740. $profile['nick'] = $apcontact['nick'];
  741. $profile['name'] = $apcontact['name'];
  742. $profile['guid'] = $apcontact['uuid'];
  743. $profile['url'] = $apcontact['url'];
  744. $profile['addr'] = $apcontact['addr'];
  745. $profile['alias'] = $apcontact['alias'];
  746. $profile['photo'] = $apcontact['photo'];
  747. // $profile['community']
  748. // $profile['keywords']
  749. // $profile['location']
  750. $profile['about'] = $apcontact['about'];
  751. $profile['batch'] = $apcontact['sharedinbox'];
  752. $profile['notify'] = $apcontact['inbox'];
  753. $profile['poll'] = $apcontact['outbox'];
  754. $profile['pubkey'] = $apcontact['pubkey'];
  755. $profile['baseurl'] = $apcontact['baseurl'];
  756. // Remove all "null" fields
  757. foreach ($profile as $field => $content) {
  758. if (is_null($content)) {
  759. unset($profile[$field]);
  760. }
  761. }
  762. return $profile;
  763. }
  764. /**
  765. * @brief
  766. *
  767. * @param $body
  768. * @param $header
  769. * @param integer $uid User ID
  770. */
  771. public static function processInbox($body, $header, $uid)
  772. {
  773. $http_signer = HTTPSignature::getSigner($body, $header);
  774. if (empty($http_signer)) {
  775. logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
  776. return;
  777. } else {
  778. logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
  779. }
  780. $activity = json_decode($body, true);
  781. $actor = JsonLD::fetchElement($activity, 'actor', 'id');
  782. logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
  783. if (empty($activity)) {
  784. logger('Invalid body.', LOGGER_DEBUG);
  785. return;
  786. }
  787. if (LDSignature::isSigned($activity)) {
  788. $ld_signer = LDSignature::getSigner($activity);
  789. if (empty($ld_signer)) {
  790. logger('Invalid JSON-LD signature from ' . $actor, LOGGER_DEBUG);
  791. }
  792. if (!empty($ld_signer && ($actor == $http_signer))) {
  793. logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
  794. $trust_source = true;
  795. } elseif (!empty($ld_signer)) {
  796. logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
  797. $trust_source = true;
  798. } elseif ($actor == $http_signer) {
  799. logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
  800. $trust_source = true;
  801. } else {
  802. logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
  803. $trust_source = false;
  804. }
  805. } elseif ($actor == $http_signer) {
  806. logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
  807. $trust_source = true;
  808. } else {
  809. logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
  810. $trust_source = false;
  811. }
  812. self::processActivity($activity, $body, $uid, $trust_source);
  813. }
  814. /**
  815. * @brief
  816. *
  817. * @param $url
  818. * @param integer $uid User ID
  819. */
  820. public static function fetchOutbox($url, $uid)
  821. {
  822. $data = self::fetchContent($url);
  823. if (empty($data)) {
  824. return;
  825. }
  826. if (!empty($data['orderedItems'])) {
  827. $items = $data['orderedItems'];
  828. } elseif (!empty($data['first']['orderedItems'])) {
  829. $items = $data['first']['orderedItems'];
  830. } elseif (!empty($data['first'])) {
  831. self::fetchOutbox($data['first'], $uid);
  832. return;
  833. } else {
  834. $items = [];
  835. }
  836. foreach ($items as $activity) {
  837. self::processActivity($activity, '', $uid, true);
  838. }
  839. }
  840. /**
  841. * @brief
  842. *
  843. * @param array $activity
  844. * @param integer $uid User ID
  845. * @param $trust_source
  846. *
  847. * @return
  848. */
  849. private static function prepareObjectData($activity, $uid, &$trust_source)
  850. {
  851. $actor = JsonLD::fetchElement($activity, 'actor', 'id');
  852. if (empty($actor)) {
  853. logger('Empty actor', LOGGER_DEBUG);
  854. return [];
  855. }
  856. // Fetch all receivers from to, cc, bto and bcc
  857. $receivers = self::getReceivers($activity, $actor);
  858. // When it is a delivery to a personal inbox we add that user to the receivers
  859. if (!empty($uid)) {
  860. $owner = User::getOwnerDataById($uid);
  861. $additional = ['uid:' . $uid => $uid];
  862. $receivers = array_merge($receivers, $additional);
  863. }
  864. logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
  865. $object_id = JsonLD::fetchElement($activity, 'object', 'id');
  866. if (empty($object_id)) {
  867. logger('No object found', LOGGER_DEBUG);
  868. return [];
  869. }
  870. // Fetch the content only on activities where this matters
  871. if (in_array($activity['type'], ['Create', 'Announce'])) {
  872. $object_data = self::fetchObject($object_id, $activity['object'], $trust_source);
  873. if (empty($object_data)) {
  874. logger("Object data couldn't be processed", LOGGER_DEBUG);
  875. return [];
  876. }
  877. // We had been able to retrieve the object data - so we can trust the source
  878. $trust_source = true;
  879. } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
  880. // Create a mostly empty array out of the activity data (instead of the object).
  881. // This way we later don't have to check for the existence of ech individual array element.
  882. $object_data = self::processObject($activity);
  883. $object_data['name'] = $activity['type'];
  884. $object_data['author'] = $activity['actor'];
  885. $object_data['object'] = $object_id;
  886. $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
  887. } else {
  888. $object_data = [];
  889. $object_data['id'] = $activity['id'];
  890. $object_data['object'] = $activity['object'];
  891. $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
  892. }
  893. $object_data = self::addActivityFields($object_data, $activity);
  894. $object_data['type'] = $activity['type'];
  895. $object_data['owner'] = $actor;
  896. $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
  897. logger('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], LOGGER_DEBUG);
  898. return $object_data;
  899. }
  900. /**
  901. * @brief
  902. *
  903. * @param array $activity
  904. * @param $body
  905. * @param integer $uid User ID
  906. * @param $trust_source
  907. */
  908. private static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
  909. {
  910. if (empty($activity['type'])) {
  911. logger('Empty type', LOGGER_DEBUG);
  912. return;
  913. }
  914. if (empty($activity['object'])) {
  915. logger('Empty object', LOGGER_DEBUG);
  916. return;
  917. }
  918. if (empty($activity['actor'])) {
  919. logger('Empty actor', LOGGER_DEBUG);
  920. return;
  921. }
  922. // $trust_source is called by reference and is set to true if the content was retrieved successfully
  923. $object_data = self::prepareObjectData($activity, $uid, $trust_source);
  924. if (empty($object_data)) {
  925. logger('No object data found', LOGGER_DEBUG);
  926. return;
  927. }
  928. if (!$trust_source) {
  929. logger('No trust for activity type "' . $activity['type'] . '", so we quit now.', LOGGER_DEBUG);
  930. }
  931. switch ($activity['type']) {
  932. case 'Create':
  933. case 'Announce':
  934. self::createItem($object_data, $body);
  935. break;
  936. case 'Like':
  937. self::likeItem($object_data, $body);
  938. break;
  939. case 'Dislike':
  940. self::dislikeItem($object_data, $body);
  941. break;
  942. case 'Update':
  943. if (in_array($object_data['object_type'], ['Person', 'Organization', 'Service', 'Group', 'Application'])) {
  944. self::updatePerson($object_data, $body);
  945. }
  946. break;
  947. case 'Delete':
  948. break;
  949. case 'Follow':
  950. self::followUser($object_data);
  951. break;
  952. case 'Accept':
  953. if ($object_data['object_type'] == 'Follow') {
  954. self::acceptFollowUser($object_data);
  955. }
  956. break;
  957. case 'Undo':
  958. if ($object_data['object_type'] == 'Follow') {
  959. self::undoFollowUser($object_data);
  960. } elseif (in_array($object_data['object_type'], ['Like', 'Dislike', 'Accept', 'Reject', 'TentativeAccept'])) {
  961. self::undoActivity($object_data);
  962. }
  963. break;
  964. default:
  965. logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
  966. break;
  967. }
  968. }
  969. /**
  970. * @brief
  971. *
  972. * @param array $activity
  973. * @param $actor
  974. *
  975. * @return
  976. */
  977. private static function getReceivers($activity, $actor)
  978. {
  979. $receivers = [];
  980. // When it is an answer, we inherite the receivers from the parent
  981. $replyto = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
  982. if (!empty($replyto)) {
  983. $parents = Item::select(['uid'], ['uri' => $replyto]);
  984. while ($parent = Item::fetch($parents)) {
  985. $receivers['uid:' . $parent['uid']] = $parent['uid'];
  986. }
  987. }
  988. if (!empty($actor)) {
  989. $profile = APContact::getProfileByURL($actor);
  990. $followers = defaults($profile, 'followers', '');
  991. logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
  992. } else {
  993. logger('Empty actor', LOGGER_DEBUG);
  994. $followers = '';
  995. }
  996. $elements = ['to', 'cc', 'bto', 'bcc'];
  997. foreach ($elements as $element) {
  998. if (empty($activity[$element])) {
  999. continue;
  1000. }
  1001. // The receiver can be an arror or a string
  1002. if (is_string($activity[$element])) {
  1003. $activity[$element] = [$activity[$element]];
  1004. }
  1005. foreach ($activity[$element] as $receiver) {
  1006. if ($receiver == self::PUBLIC) {
  1007. $receivers['uid:0'] = 0;
  1008. }
  1009. if (($receiver == self::PUBLIC) && !empty($actor)) {
  1010. // This will most likely catch all OStatus connections to Mastodon
  1011. $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
  1012. , 'archive' => false, 'pending' => false];
  1013. $contacts = DBA::select('contact', ['uid'], $condition);
  1014. while ($contact = DBA::fetch($contacts)) {
  1015. if ($contact['uid'] != 0) {
  1016. $receivers['uid:' . $contact['uid']] = $contact['uid'];
  1017. }
  1018. }
  1019. DBA::close($contacts);
  1020. }
  1021. if (in_array($receiver, [$followers, self::PUBLIC]) && !empty($actor)) {
  1022. $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
  1023. 'network' => Protocol::ACTIVITYPUB, 'archive' => false, 'pending' => false];
  1024. $contacts = DBA::select('contact', ['uid'], $condition);
  1025. while ($contact = DBA::fetch($contacts)) {
  1026. if ($contact['uid'] != 0) {
  1027. $receivers['uid:' . $contact['uid']] = $contact['uid'];
  1028. }
  1029. }
  1030. DBA::close($contacts);
  1031. continue;
  1032. }
  1033. $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
  1034. $contact = DBA::selectFirst('contact', ['uid'], $condition);
  1035. if (!DBA::isResult($contact)) {
  1036. continue;
  1037. }
  1038. $receivers['uid:' . $contact['uid']] = $contact['uid'];
  1039. }
  1040. }
  1041. self::switchContacts($receivers, $actor);
  1042. return $receivers;
  1043. }
  1044. /**
  1045. * @brief
  1046. *
  1047. * @param $cid
  1048. * @param integer $uid User ID
  1049. * @param $url
  1050. */
  1051. private static function switchContact($cid, $uid, $url)
  1052. {
  1053. $profile = ActivityPub::probeProfile($url);
  1054. if (empty($profile)) {
  1055. return;
  1056. }
  1057. logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' from OStatus to ActivityPub');
  1058. $photo = $profile['photo'];
  1059. unset($profile['photo']);
  1060. unset($profile['baseurl']);
  1061. $profile['nurl'] = normalise_link($profile['url']);
  1062. DBA::update('contact', $profile, ['id' => $cid]);
  1063. Contact::updateAvatar($photo, $uid, $cid);
  1064. }
  1065. /**
  1066. * @brief
  1067. *
  1068. * @param $receivers
  1069. * @param $actor
  1070. */
  1071. private static function switchContacts($receivers, $actor)
  1072. {
  1073. if (empty($actor)) {
  1074. return;
  1075. }
  1076. foreach ($receivers as $receiver) {
  1077. $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
  1078. if (DBA::isResult($contact)) {
  1079. self::switchContact($contact['id'], $receiver, $actor);
  1080. }
  1081. $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
  1082. if (DBA::isResult($contact)) {
  1083. self::switchContact($contact['id'], $receiver, $actor);
  1084. }
  1085. }
  1086. }
  1087. /**
  1088. * @brief
  1089. *
  1090. * @param $object_data
  1091. * @param array $activity
  1092. *
  1093. * @return
  1094. */
  1095. private static function addActivityFields($object_data, $activity)
  1096. {
  1097. if (!empty($activity['published']) && empty($object_data['published'])) {
  1098. $object_data['published'] = $activity['published'];
  1099. }
  1100. if (!empty($activity['updated']) && empty($object_data['updated'])) {
  1101. $object_data['updated'] = $activity['updated'];
  1102. }
  1103. if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
  1104. $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
  1105. }
  1106. if (!empty($activity['instrument'])) {
  1107. $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
  1108. }
  1109. return $object_data;
  1110. }
  1111. /**
  1112. * @brief
  1113. *
  1114. * @param $object_id
  1115. * @param $object
  1116. * @param $trust_source
  1117. *
  1118. * @return
  1119. */
  1120. private static function fetchObject($object_id, $object = [], $trust_source = false)
  1121. {
  1122. if (!$trust_source || is_string($object)) {
  1123. $data = self::fetchContent($object_id);
  1124. if (empty($data)) {
  1125. logger('Empty content for ' . $object_id . ', check if content is available locally.', LOGGER_DEBUG);
  1126. $data = $object_id;
  1127. } else {
  1128. logger('Fetched content for ' . $object_id, LOGGER_DEBUG);
  1129. }
  1130. } else {
  1131. logger('Using original object for url ' . $object_id, LOGGER_DEBUG);
  1132. $data = $object;
  1133. }
  1134. if (is_string($data)) {
  1135. $item = Item::selectFirst([], ['uri' => $data]);
  1136. if (!DBA::isResult($item)) {
  1137. logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
  1138. return false;
  1139. }
  1140. logger('Using already stored item for url ' . $object_id, LOGGER_DEBUG);
  1141. $data = self::createNote($item);
  1142. }
  1143. if (empty($data['type'])) {
  1144. logger('Empty type', LOGGER_DEBUG);
  1145. return false;
  1146. }
  1147. switch ($data['type']) {
  1148. case 'Note':
  1149. case 'Article':
  1150. case 'Video':
  1151. return self::processObject($data);
  1152. case 'Announce':
  1153. if (empty($data['object'])) {
  1154. return false;
  1155. }
  1156. return self::fetchObject($data['object']);
  1157. case 'Person':
  1158. case 'Tombstone':
  1159. break;
  1160. default:
  1161. logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
  1162. break;
  1163. }
  1164. }
  1165. /**
  1166. * @brief
  1167. *
  1168. * @param $object
  1169. *
  1170. * @return
  1171. */
  1172. private static function processObject(&$object)
  1173. {
  1174. if (empty($object['id'])) {
  1175. return false;
  1176. }
  1177. $object_data = [];
  1178. $object_data['object_type'] = $object['type'];
  1179. $object_data['id'] = $object['id'];
  1180. if (!empty($object['inReplyTo'])) {
  1181. $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'inReplyTo', 'id');
  1182. } else {
  1183. $object_data['reply-to-id'] = $object_data['id'];
  1184. }
  1185. $object_data['published'] = defaults($object, 'published', null);
  1186. $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
  1187. if (empty($object_data['published']) && !empty($object_data['updated'])) {
  1188. $object_data['published'] = $object_data['updated'];
  1189. }
  1190. $actor = JsonLD::fetchElement($object, 'attributedTo', 'id');
  1191. if (empty($actor)) {
  1192. $actor = defaults($object, 'actor', null);
  1193. }
  1194. $object_data['diaspora:guid'] = defaults($object, 'diaspora:guid', null);
  1195. $object_data['owner'] = $object_data['author'] = $actor;
  1196. $object_data['context'] = defaults($object, 'context', null);
  1197. $object_data['conversation'] = defaults($object, 'conversation', null);
  1198. $object_data['sensitive'] = defaults($object, 'sensitive', null);
  1199. $object_data['name'] = defaults($object, 'title', null);
  1200. $object_data['name'] = defaults($object, 'name', $object_data['name']);
  1201. $object_data['summary'] = defaults($object, 'summary', null);
  1202. $object_data['content'] = defaults($object, 'content', null);
  1203. $object_data['source'] = defaults($object, 'source', null);
  1204. $object_data['location'] = JsonLD::fetchElement($object, 'location', 'name', 'type', 'Place');
  1205. $object_data['attachments'] = defaults($object, 'attachment', null);
  1206. $object_data['tags'] = defaults($object, 'tag', null);
  1207. $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service');
  1208. $object_data['alternate-url'] = JsonLD::fetchElement($object, 'url', 'href');
  1209. $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
  1210. // Common object data:
  1211. // Unhandled
  1212. // @context, type, actor, signature, mediaType, duration, replies, icon
  1213. // Also missing: (Defined in the standard, but currently unused)
  1214. // audience, preview, endTime, startTime, generator, image
  1215. // Data in Notes:
  1216. // Unhandled
  1217. // contentMap, announcement_count, announcements, context_id, likes, like_count
  1218. // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
  1219. // Data in video:
  1220. // To-Do?
  1221. // category, licence, language, commentsEnabled
  1222. // Unhandled
  1223. // views, waitTranscoding, state, support, subtitleLanguage
  1224. // likes, dislikes, shares, comments
  1225. return $object_data;
  1226. }
  1227. /**
  1228. * @brief Converts mentions from Pleroma into the Friendica format
  1229. *
  1230. * @param string $body
  1231. *
  1232. * @return converted body
  1233. */
  1234. private static function convertMentions($body)
  1235. {
  1236. $URLSearchString = "^\[\]";
  1237. $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
  1238. return $body;
  1239. }
  1240. /**
  1241. * @brief Constructs a string with tags for a given tag array
  1242. *
  1243. * @param array $tags
  1244. * @param boolean $sensitive
  1245. *
  1246. * @return string with tags
  1247. */
  1248. private static function constructTagList($tags, $sensitive)
  1249. {
  1250. if (empty($tags)) {
  1251. return '';
  1252. }
  1253. $tag_text = '';
  1254. foreach ($tags as $tag) {
  1255. if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
  1256. if (!empty($tag_text)) {
  1257. $tag_text .= ',';
  1258. }
  1259. $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
  1260. }
  1261. }
  1262. /// @todo add nsfw for $sensitive
  1263. return $tag_text;
  1264. }
  1265. /**
  1266. * @brief
  1267. *
  1268. * @param $attachments
  1269. * @param array $item
  1270. *
  1271. * @return item array
  1272. */
  1273. private static function constructAttachList($attachments, $item)
  1274. {
  1275. if (empty($attachments)) {
  1276. return $item;
  1277. }
  1278. foreach ($attachments as $attach) {
  1279. $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
  1280. if ($filetype == 'image') {
  1281. $item['body'] .= "\n[img]".$attach['url'].'[/img]';
  1282. } else {
  1283. if (!empty($item["attach"])) {
  1284. $item["attach"] .= ',';
  1285. } else {
  1286. $item["attach"] = '';
  1287. }
  1288. if (!isset($attach['length'])) {
  1289. $attach['length'] = "0";
  1290. }
  1291. $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
  1292. }
  1293. }
  1294. return $item;
  1295. }
  1296. /**
  1297. * @brief
  1298. *
  1299. * @param array $activity
  1300. * @param $body
  1301. */
  1302. private static function createItem($activity, $body)
  1303. {
  1304. $item = [];
  1305. $item['verb'] = ACTIVITY_POST;
  1306. $item['parent-uri'] = $activity['reply-to-id'];
  1307. if ($activity['reply-to-id'] == $activity['id']) {
  1308. $item['gravity'] = GRAVITY_PARENT;
  1309. $item['object-type'] = ACTIVITY_OBJ_NOTE;
  1310. } else {
  1311. $item['gravity'] = GRAVITY_COMMENT;
  1312. $item['object-type'] = ACTIVITY_OBJ_COMMENT;
  1313. }
  1314. if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
  1315. logger('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
  1316. self::fetchMissingActivity($activity['reply-to-id'], $activity);
  1317. }
  1318. self::postItem($activity, $item, $body);
  1319. }
  1320. /**
  1321. * @brief
  1322. *
  1323. * @param array $activity
  1324. * @param $body
  1325. */
  1326. private static function likeItem($activity, $body)
  1327. {
  1328. $item = [];
  1329. $item['verb'] = ACTIVITY_LIKE;
  1330. $item['parent-uri'] = $activity['object'];
  1331. $item['gravity'] = GRAVITY_ACTIVITY;
  1332. $item['object-type'] = ACTIVITY_OBJ_NOTE;
  1333. self::postItem($activity, $item, $body);
  1334. }
  1335. /**
  1336. * @brief
  1337. *
  1338. * @param array $activity
  1339. * @param $body
  1340. */
  1341. private static function dislikeItem($activity, $body)
  1342. {
  1343. $item = [];
  1344. $item['verb'] = ACTIVITY_DISLIKE;
  1345. $item['parent-uri'] = $activity['object'];
  1346. $item['gravity'] = GRAVITY_ACTIVITY;
  1347. $item['object-type'] = ACTIVITY_OBJ_NOTE;
  1348. self::postItem($activity, $item, $body);
  1349. }
  1350. /**
  1351. * @brief
  1352. *
  1353. * @param array $activity
  1354. * @param array $item
  1355. * @param $body
  1356. */
  1357. private static function postItem($activity, $item, $body)
  1358. {
  1359. /// @todo What to do with $activity['context']?
  1360. if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
  1361. logger('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', LOGGER_DEBUG);
  1362. return;
  1363. }
  1364. $item['network'] = Protocol::ACTIVITYPUB;
  1365. $item['private'] = !in_array(0, $activity['receiver']);
  1366. $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
  1367. $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
  1368. $item['uri'] = $activity['id'];
  1369. $item['created'] = $activity['published'];
  1370. $item['edited'] = $activity['updated'];
  1371. $item['guid'] = $activity['diaspora:guid'];
  1372. $item['title'] = HTML::toBBCode($activity['name']);
  1373. $item['content-warning'] = HTML::toBBCode($activity['summary']);
  1374. $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
  1375. $item['location'] = $activity['location'];
  1376. $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
  1377. $item['app'] = $activity['service'];
  1378. $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
  1379. $item = self::constructAttachList($activity['attachments'], $item);
  1380. $source = JsonLD::fetchElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
  1381. if (!empty($source)) {
  1382. $item['body'] = $source;
  1383. }
  1384. $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
  1385. $item['source'] = $body;
  1386. $item['conversation-href'] = $activity['context'];
  1387. $item['conversation-uri'] = $activity['conversation'];
  1388. foreach ($activity['receiver'] as $receiver) {
  1389. $item['uid'] = $receiver;
  1390. $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
  1391. if (($receiver != 0) && empty($item['contact-id'])) {
  1392. $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
  1393. }
  1394. $item_id = Item::insert($item);
  1395. logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
  1396. }
  1397. }
  1398. /**
  1399. * @brief
  1400. *
  1401. * @param $url
  1402. * @param $child
  1403. */
  1404. private static function fetchMissingActivity($url, $child)
  1405. {
  1406. if (Config::get('system', 'ostatus_full_threads')) {
  1407. return;
  1408. }
  1409. $object = ActivityPub::fetchContent($url);
  1410. if (empty($object)) {
  1411. logger('Activity ' . $url . ' was not fetchable, aborting.');
  1412. return;
  1413. }
  1414. $activity = [];
  1415. $activity['@context'] = $object['@context'];
  1416. unset($object['@context']);
  1417. $activity['id'] = $object['id'];
  1418. $activity['to'] = defaults($object, 'to', []);
  1419. $activity['cc'] = defaults($object, 'cc', []);
  1420. $activity['actor'] = $child['author'];
  1421. $activity['object'] = $object;
  1422. $activity['published'] = $object['published'];
  1423. $activity['type'] = 'Create';
  1424. self::processActivity($activity);
  1425. logger('Activity ' . $url . ' had been fetched and processed.');
  1426. }
  1427. /**
  1428. * @brief perform a "follow" request
  1429. *
  1430. * @param array $activity
  1431. */
  1432. private static function followUser($activity)
  1433. {
  1434. $actor = JsonLD::fetchElement($activity, 'object', 'id');
  1435. $uid = User::getIdForURL($actor);
  1436. if (empty($uid)) {
  1437. return;
  1438. }
  1439. $owner = User::getOwnerDataById($uid);
  1440. $cid = Contact::getIdForURL($activity['owner'], $uid);
  1441. if (!empty($cid)) {
  1442. $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
  1443. } else {
  1444. $contact = false;
  1445. }
  1446. $item = ['author-id' => Contact::getIdForURL($activity['owner']),
  1447. 'author-link' => $activity['owner']];
  1448. Contact::addRelationship($owner, $contact, $item);
  1449. $cid = Contact::getIdForURL($activity['owner'], $uid);
  1450. if (empty($cid)) {
  1451. return;
  1452. }
  1453. $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
  1454. if ($contact['network'] != Protocol::ACTIVITYPUB) {
  1455. Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
  1456. }
  1457. DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
  1458. logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
  1459. }
  1460. /**
  1461. * @brief Update the given profile
  1462. *
  1463. * @param array $activity
  1464. */
  1465. private static function updatePerson($activity)
  1466. {
  1467. if (empty($activity['object']['id'])) {
  1468. return;
  1469. }
  1470. logger('Updating profile for ' . $activity['object']['id'], LOGGER_DEBUG);
  1471. APContact::getProfileByURL($activity['object']['id'], true);
  1472. }
  1473. /**
  1474. * @brief Accept a follow request
  1475. *
  1476. * @param array $activity
  1477. */
  1478. private static function acceptFollowUser($activity)
  1479. {
  1480. $actor = JsonLD::fetchElement($activity, 'object', 'actor');
  1481. $uid = User::getIdForURL($actor);
  1482. if (empty($uid)) {
  1483. return;
  1484. }
  1485. $owner = User::getOwnerDataById($uid);
  1486. $cid = Contact::getIdForURL($activity['owner'], $uid);
  1487. if (empty($cid)) {
  1488. logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
  1489. return;
  1490. }
  1491. $fields = ['pending' => false];
  1492. $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
  1493. if ($contact['rel'] == Contact::FOLLOWER) {
  1494. $fields['rel'] = Contact::FRIEND;
  1495. }
  1496. $condition = ['id' => $cid];
  1497. DBA::update('contact', $fields, $condition);
  1498. logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
  1499. }
  1500. /**
  1501. * @brief Undo activity like "like" or "dislike"
  1502. *
  1503. * @param array $activity
  1504. */
  1505. private static function undoActivity($activity)
  1506. {
  1507. $activity_url = JsonLD::fetchElement($activity, 'object', 'id');
  1508. if (empty($activity_url)) {
  1509. return;
  1510. }
  1511. $actor = JsonLD::fetchElement($activity, 'object', 'actor');
  1512. if (empty($actor)) {
  1513. return;
  1514. }
  1515. $author_id = Contact::getIdForURL($actor);
  1516. if (empty($author_id)) {
  1517. return;
  1518. }
  1519. Item::delete(['uri' => $activity_url, 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
  1520. }
  1521. /**
  1522. * @brief Activity to remove a follower
  1523. *
  1524. * @param array $activity
  1525. */
  1526. private static function undoFollowUser($activity)
  1527. {
  1528. $object = JsonLD::fetchElement($activity, 'object', 'object');
  1529. $uid = User::getIdForURL($object);
  1530. if (empty($uid)) {
  1531. return;
  1532. }
  1533. $owner = User::getOwnerDataById($uid);
  1534. $cid = Contact::getIdForURL($activity['owner'], $uid);
  1535. if (empty($cid)) {
  1536. logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
  1537. return;
  1538. }
  1539. $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
  1540. if (!DBA::isResult($contact)) {
  1541. return;
  1542. }
  1543. Contact::removeFollower($owner, $contact);
  1544. logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
  1545. }
  1546. }