3 * @file src/Protocol/ActivityPub.php
5 namespace Friendica\Protocol;
7 use Friendica\Database\DBA;
8 use Friendica\Core\System;
9 use Friendica\BaseObject;
10 use Friendica\Util\Network;
11 use Friendica\Util\HTTPSignature;
12 use Friendica\Core\Protocol;
13 use Friendica\Model\Conversation;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Item;
16 use Friendica\Model\User;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Crypto;
19 use Friendica\Content\Text\BBCode;
20 use Friendica\Content\Text\HTML;
21 use Friendica\Network\Probe;
24 * @brief ActivityPub Protocol class
25 * The ActivityPub Protocol is a message exchange protocol defined by the W3C.
26 * https://www.w3.org/TR/activitypub/
27 * https://www.w3.org/TR/activitystreams-core/
28 * https://www.w3.org/TR/activitystreams-vocabulary/
30 * https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/
31 * https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
33 * Digest: https://tools.ietf.org/html/rfc5843
34 * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
36 * Part of the code for HTTP signing is taken from the Osada project.
42 * - Activities: Dislike, Update, Delete
43 * - Object Types: Person, Tombstome
46 * - Activities: Like, Dislike, Update, Delete
47 * - Object Tyoes: Article, Announce, Person, Tombstone
50 * - Message distribution
51 * - Endpoints: Outbox, Object, Follower, Following
55 const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
57 public static function transmit($data, $target, $uid)
59 $owner = User::getOwnerDataById($uid);
65 $content = json_encode($data);
67 $host = parse_url($target, PHP_URL_HOST);
68 $path = parse_url($target, PHP_URL_PATH);
71 $headers = ['Host: ' . $host, 'Date: ' . $date];
73 $signed_data = "(request-target): post " . $path . "\nhost: " . $host . "\ndate: " . $date;
75 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
77 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",headers="(request-target) host date",signature="' . $signature . '"';
78 $headers[] = 'Content-Type: application/activity+json';
80 Network::post($target, $content, $headers);
81 $return_code = BaseObject::getApp()->get_curl_code();
83 logger('Transmit to ' . $target . ' returned ' . $return_code);
87 * Return the ActivityPub profile of the given user
89 * @param integer $uid User ID
92 public static function profile($uid)
94 $accounttype = ['Person', 'Organization', 'Service', 'Group', 'Application'];
96 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
97 'account_removed' => false, 'verified' => true];
98 $fields = ['guid', 'nickname', 'pubkey', 'account-type'];
99 $user = DBA::selectFirst('user', $fields, $condition);
100 if (!DBA::isResult($user)) {
104 $fields = ['locality', 'region', 'country-name'];
105 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
106 if (!DBA::isResult($profile)) {
110 $fields = ['name', 'url', 'location', 'about', 'avatar'];
111 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
112 if (!DBA::isResult($contact)) {
116 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
117 ['uuid' => 'http://schema.org/identifier', 'sensitive' => 'as:sensitive',
118 'vcard' => 'http://www.w3.org/2006/vcard/ns#']]];
120 $data['id'] = $contact['url'];
121 $data['uuid'] = $user['guid'];
122 $data['type'] = $accounttype[$user['account-type']];
123 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
124 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
125 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
126 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
127 $data['preferredUsername'] = $user['nickname'];
128 $data['name'] = $contact['name'];
129 $data['vcard:hasAddress'] = ['@type' => 'Home', 'vcard:country-name' => $profile['country-name'],
130 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
131 $data['summary'] = $contact['about'];
132 $data['url'] = $contact['url'];
133 $data['manuallyApprovesFollowers'] = false;
134 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
135 'owner' => $contact['url'],
136 'publicKeyPem' => $user['pubkey']];
137 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
138 $data['icon'] = ['type' => 'Image',
139 'url' => $contact['avatar']];
141 // tags: https://kitty.town/@inmysocks/100656097926961126.json
145 public static function createActivityFromItem($item_id)
147 $item = Item::selectFirst([], ['id' => $item_id]);
149 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
150 ['Emoji' => 'toot:Emoji', 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
151 'conversation' => 'ostatus:conversation', 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri',
152 'ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
153 'toot' => 'http://joinmastodon.org/ns#']]];
155 $data['type'] = 'Create';
156 $data['id'] = $item['uri'];
157 $data['actor'] = $item['author-link'];
158 $data['to'] = 'https://www.w3.org/ns/activitystreams#Public';
159 $data['object'] = self::createNote($item);
163 public static function createNote($item)
166 $data['type'] = 'Note';
167 $data['id'] = $item['uri'];
169 if ($item['uri'] != $item['thr-parent']) {
170 $data['inReplyTo'] = $item['thr-parent'];
173 $conversation = DBA::selectFirst('conversation', ['conversation-uri'], ['item-uri' => $item['parent-uri']]);
174 if (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
175 $conversation_uri = $conversation['conversation-uri'];
177 $conversation_uri = $item['parent-uri'];
180 $data['context'] = $data['conversation'] = $conversation_uri;
181 $data['actor'] = $item['author-link'];
183 if (!$item['private']) {
184 $data['to'][] = 'https://www.w3.org/ns/activitystreams#Public';
186 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
187 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
188 $data['attributedTo'] = $item['author-link'];
189 $data['name'] = BBCode::convert($item['title'], false, 7);
190 $data['content'] = BBCode::convert($item['body'], false, 7);
191 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
192 //$data['summary'] = ''; // Ignore by now
193 //$data['sensitive'] = false; // - Query NSFW
194 //$data['emoji'] = []; // Ignore by now
195 //$data['tag'] = []; /// @ToDo
196 //$data['attachment'] = []; // @ToDo
200 public static function transmitActivity($activity, $target, $uid)
202 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
204 $owner = User::getOwnerDataById($uid);
206 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
207 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
209 'actor' => $owner['url'],
210 'object' => $profile['url']];
212 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
213 return self::transmit($data, $profile['notify'], $uid);
216 public static function transmitContactAccept($target, $id, $uid)
218 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
220 $owner = User::getOwnerDataById($uid);
221 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
222 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
224 'actor' => $owner['url'],
225 'object' => ['id' => $id, 'type' => 'Follow',
226 'actor' => $profile['url'],
227 'object' => $owner['url']]];
229 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
230 return self::transmit($data, $profile['notify'], $uid);
233 public static function transmitContactUndo($target, $id, $uid)
235 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
238 $id = System::baseUrl() . '/activity/' . System::createGUID();
241 $owner = User::getOwnerDataById($uid);
242 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
243 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
245 'actor' => $owner['url'],
246 'object' => ['id' => $id, 'type' => 'Follow',
247 'actor' => $owner['url'],
248 'object' => $profile['url']]];
250 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
251 return self::transmit($data, $profile['notify'], $uid);
255 * Fetches ActivityPub content from the given url
257 * @param string $url content url
260 public static function fetchContent($url)
262 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json']);
264 if (!$ret['success'] || empty($ret['body'])) {
268 return json_decode($ret['body'], true);
272 * Resolves the profile url from the address by using webfinger
274 * @param string $addr profile address (user@domain.tld)
277 private static function addrToUrl($addr)
279 $addr_parts = explode('@', $addr);
280 if (count($addr_parts) != 2) {
284 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
286 $ret = Network::curl($webfinger, false, $redirects, ['accept_content' => 'application/jrd+json,application/json']);
287 if (!$ret['success'] || empty($ret['body'])) {
291 $data = json_decode($ret['body'], true);
293 if (empty($data['links'])) {
297 foreach ($data['links'] as $link) {
298 if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
302 if (($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
303 return $link['href'];
310 public static function verifySignature($content, $http_headers)
312 $object = json_decode($content, true);
314 if (empty($object)) {
318 $actor = self::processElement($object, 'actor', 'id');
321 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
323 // First take every header
324 foreach ($http_headers as $k => $v) {
325 $field = str_replace('_', '-', strtolower($k));
326 $headers[$field] = $v;
329 // Now add every http header
330 foreach ($http_headers as $k => $v) {
331 if (strpos($k, 'HTTP_') === 0) {
332 $field = str_replace('_', '-', strtolower(substr($k, 5)));
333 $headers[$field] = $v;
337 $sig_block = ActivityPub::parseSigHeader($http_headers['HTTP_SIGNATURE']);
339 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
344 foreach ($sig_block['headers'] as $h) {
345 if (array_key_exists($h, $headers)) {
346 $signed_data .= $h . ': ' . $headers[$h] . "\n";
349 $signed_data = rtrim($signed_data, "\n");
351 if (empty($signed_data)) {
357 if ($sig_block['algorithm'] === 'rsa-sha256') {
358 $algorithm = 'sha256';
361 if ($sig_block['algorithm'] === 'rsa-sha512') {
362 $algorithm = 'sha512';
365 if (empty($algorithm)) {
369 $key = self::fetchKey($sig_block['keyId'], $actor);
375 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm)) {
379 // Check the digest if it was part of the signed data
380 if (in_array('digest', $sig_block['headers'])) {
381 $digest = explode('=', $headers['digest'], 2);
382 if ($digest[0] === 'SHA-256') {
385 if ($digest[0] === 'SHA-512') {
389 /// @todo add all hashes from the rfc
391 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
396 // Check the content-length if it was part of the signed data
397 if (in_array('content-length', $sig_block['headers'])) {
398 if (strlen($content) != $headers['content-length']) {
407 private static function fetchKey($id, $actor)
409 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
411 $profile = Probe::uri($url, Protocol::ACTIVITYPUB);
412 if (!empty($profile)) {
413 return $profile['pubkey'];
414 } elseif ($url != $actor) {
415 $profile = Probe::uri($actor, Protocol::ACTIVITYPUB);
416 if (!empty($profile)) {
417 return $profile['pubkey'];
427 * @param string $header
428 * @return array associate array with
429 * - \e string \b keyID
430 * - \e string \b algorithm
431 * - \e array \b headers
432 * - \e string \b signature
434 private static function parseSigHeader($header)
439 if (preg_match('/keyId="(.*?)"/ism',$header,$matches)) {
440 $ret['keyId'] = $matches[1];
443 if (preg_match('/algorithm="(.*?)"/ism',$header,$matches)) {
444 $ret['algorithm'] = $matches[1];
447 if (preg_match('/headers="(.*?)"/ism',$header,$matches)) {
448 $ret['headers'] = explode(' ', $matches[1]);
451 if (preg_match('/signature="(.*?)"/ism',$header,$matches)) {
452 $ret['signature'] = base64_decode(preg_replace('/\s+/','',$matches[1]));
459 * Fetches a profile from the given url
461 * @param string $url profile url
464 public static function fetchProfile($url)
466 if (empty(parse_url($url, PHP_URL_SCHEME))) {
467 $url = self::addrToUrl($url);
473 $data = self::fetchContent($url);
475 if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
479 $profile = ['network' => Protocol::ACTIVITYPUB];
480 $profile['nick'] = $data['preferredUsername'];
481 $profile['name'] = defaults($data, 'name', $profile['nick']);
482 $profile['guid'] = defaults($data, 'uuid', null);
483 $profile['url'] = $data['id'];
485 $parts = parse_url($profile['url']);
486 unset($parts['scheme']);
487 unset($parts['path']);
488 $profile['addr'] = $profile['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
489 $profile['alias'] = self::processElement($data, 'url', 'href');
490 $profile['photo'] = self::processElement($data, 'icon', 'url');
491 // $profile['community']
492 // $profile['keywords']
493 // $profile['location']
494 $profile['about'] = defaults($data, 'summary', '');
495 $profile['batch'] = self::processElement($data, 'endpoints', 'sharedInbox');
496 $profile['notify'] = $data['inbox'];
497 $profile['poll'] = $data['outbox'];
498 $profile['pubkey'] = self::processElement($data, 'publicKey', 'publicKeyPem');
500 // Check if the address is resolvable
501 if (self::addrToUrl($profile['addr']) == $profile['url']) {
502 $parts = parse_url($profile['url']);
503 unset($parts['path']);
504 $profile['baseurl'] = Network::unparseURL($parts);
506 unset($profile['addr']);
509 if ($profile['url'] == $profile['alias']) {
510 unset($profile['alias']);
513 // Remove all "null" fields
514 foreach ($profile as $field => $content) {
515 if (is_null($content)) {
516 unset($profile[$field]);
522 unset($data['type']);
523 unset($data['manuallyApprovesFollowers']);
526 unset($data['@context']);
528 unset($data['attachment']);
529 unset($data['image']);
530 unset($data['nomadicLocations']);
531 unset($data['signature']);
532 unset($data['following']);
533 unset($data['followers']);
534 unset($data['featured']);
535 unset($data['movedTo']);
536 unset($data['liked']);
537 unset($data['sharedInbox']); // Misskey
538 unset($data['isCat']); // Misskey
539 unset($data['kroeg:blocks']); // Kroeg
540 unset($data['updated']); // Kroeg
545 public static function processInbox($body, $header, $uid)
547 logger('Incoming message for user ' . $uid, LOGGER_DEBUG);
549 if (!self::verifySignature($body, $header)) {
550 logger('Invalid signature, message will be discarded.', LOGGER_DEBUG);
554 $activity = json_decode($body, true);
556 if (!is_array($activity)) {
557 logger('Invalid body.', LOGGER_DEBUG);
561 self::processActivity($activity, $body, $uid);
564 public static function fetchOutbox($url)
566 $data = self::fetchContent($url);
571 if (!empty($data['orderedItems'])) {
572 $items = $data['orderedItems'];
573 } elseif (!empty($data['first']['orderedItems'])) {
574 $items = $data['first']['orderedItems'];
575 } elseif (!empty($data['first'])) {
576 self::fetchOutbox($data['first']);
582 foreach ($items as $activity) {
583 self::processActivity($activity);
587 function processActivity($activity, $body = '', $uid = null)
589 if (empty($activity['type'])) {
590 logger('Empty type', LOGGER_DEBUG);
594 if (empty($activity['object'])) {
595 logger('Empty object', LOGGER_DEBUG);
599 if (empty($activity['actor'])) {
600 logger('Empty actor', LOGGER_DEBUG);
605 $actor = self::processElement($activity, 'actor', 'id');
607 logger('Empty actor - 2', LOGGER_DEBUG);
611 if (is_string($activity['object'])) {
612 $object_url = $activity['object'];
613 } elseif (!empty($activity['object']['id'])) {
614 $object_url = $activity['object']['id'];
616 logger('No object found', LOGGER_DEBUG);
620 // ----------------------------------
623 unset($activity['@context']);
624 unset($activity['id']);
627 unset($activity['title']);
628 unset($activity['atomUri']);
629 unset($activity['context_id']);
630 unset($activity['statusnetConversationId']);
633 unset($activity['context']);
634 unset($activity['location']);
635 unset($activity['signature']);
637 // Fetch all receivers from to, cc, bto and bcc
638 $receivers = self::getReceivers($activity);
640 // When it is a delivery to a personal inbox we add that user to the receivers
642 $owner = User::getOwnerDataById($uid);
643 $additional = [$owner['url'] => $uid];
644 $receivers = array_merge($receivers, $additional);
647 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
649 logger('Processing activity: ' . $activity['type'], LOGGER_DEBUG);
651 // Fetch the content only on activities where this matters
652 if (in_array($activity['type'], ['Create', 'Update', 'Announce'])) {
653 $item = self::fetchObject($object_url, $activity['object']);
655 logger("Object data couldn't be processed", LOGGER_DEBUG);
659 if (in_array($activity['type'], ['Accept'])) {
660 $item['object'] = self::processElement($activity, 'object', 'actor', 'type', 'Follow');
661 } elseif (in_array($activity['type'], ['Undo'])) {
662 $item['object'] = self::processElement($activity, 'object', 'object', 'type', 'Follow');
664 $item['object'] = $object_url;
666 $item['id'] = $activity['id'];
667 $item['receiver'] = [];
668 $item['type'] = $activity['type'];
671 $item = self::addActivityFields($item, $activity);
673 $item['owner'] = $actor;
675 $item['receiver'] = array_merge($item['receiver'], $receivers);
677 switch ($activity['type']) {
681 self::createItem($item, $body);
685 self::likeItem($item, $body);
695 self::followUser($item);
699 self::acceptFollowUser($item);
703 self::undoFollowUser($item);
707 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
712 private static function getReceivers($activity)
716 $elements = ['to', 'cc', 'bto', 'bcc'];
717 foreach ($elements as $element) {
718 if (empty($activity[$element])) {
722 // The receiver can be an arror or a string
723 if (is_string($activity[$element])) {
724 $activity[$element] = [$activity[$element]];
727 foreach ($activity[$element] as $receiver) {
728 if ($receiver == self::PUBLIC) {
729 $receivers[$receiver] = 0;
732 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
733 $contact = DBA::selectFirst('contact', ['uid'], $condition);
734 if (!DBA::isResult($contact)) {
737 $receivers[$receiver] = $contact['uid'];
743 private static function addActivityFields($item, $activity)
745 if (!empty($activity['published']) && empty($item['published'])) {
746 $item['published'] = $activity['published'];
749 if (!empty($activity['updated']) && empty($item['updated'])) {
750 $item['updated'] = $activity['updated'];
753 if (!empty($activity['inReplyTo']) && empty($item['parent-uri'])) {
754 $item['parent-uri'] = self::processElement($activity, 'inReplyTo', 'id');
757 if (!empty($activity['instrument'])) {
758 $item['service'] = self::processElement($activity, 'instrument', 'name', 'type', 'Service');
763 private static function fetchObject($object_url, $object = [])
765 $data = self::fetchContent($object_url);
769 logger('Empty content', LOGGER_DEBUG);
771 } elseif (is_string($data)) {
772 logger('No object array provided.', LOGGER_DEBUG);
773 $item = Item::selectFirst([], ['uri' => $data]);
774 if (!DBA::isResult($item)) {
775 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
778 logger('Using already stored item', LOGGER_DEBUG);
779 $data = self::createNote($item);
781 logger('Using provided object', LOGGER_DEBUG);
785 if (empty($data['type'])) {
786 logger('Empty type', LOGGER_DEBUG);
789 $type = $data['type'];
790 logger('Type ' . $type, LOGGER_DEBUG);
793 if (in_array($type, ['Note', 'Article', 'Video'])) {
794 $common = self::processCommonData($data);
799 return array_merge($common, self::processNote($data));
801 return array_merge($common, self::processArticle($data));
803 return array_merge($common, self::processVideo($data));
806 if (empty($data['object'])) {
809 return self::fetchObject($data['object']);
816 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
821 private static function processCommonData(&$object)
823 if (empty($object['id']) || empty($object['attributedTo'])) {
828 $item['type'] = $object['type'];
829 $item['uri'] = $object['id'];
831 if (!empty($object['inReplyTo'])) {
832 $item['reply-to-uri'] = self::processElement($object, 'inReplyTo', 'id');
834 $item['reply-to-uri'] = $item['uri'];
837 $item['published'] = defaults($object, 'published', null);
838 $item['updated'] = defaults($object, 'updated', $item['published']);
840 if (empty($item['published']) && !empty($item['updated'])) {
841 $item['published'] = $item['updated'];
844 $item['uuid'] = defaults($object, 'uuid', null);
845 $item['owner'] = $item['author'] = self::processElement($object, 'attributedTo', 'id');
846 $item['context'] = defaults($object, 'context', null);
847 $item['conversation'] = defaults($object, 'conversation', null);
848 $item['sensitive'] = defaults($object, 'sensitive', null);
849 $item['name'] = defaults($object, 'title', null);
850 $item['name'] = defaults($object, 'name', $item['name']);
851 $item['summary'] = defaults($object, 'summary', null);
852 $item['content'] = defaults($object, 'content', null);
853 $item['source'] = defaults($object, 'source', null);
854 $item['location'] = self::processElement($object, 'location', 'name', 'type', 'Place');
855 $item['attachments'] = defaults($object, 'attachment', null);
856 $item['tags'] = defaults($object, 'tag', null);
857 $item['service'] = self::processElement($object, 'instrument', 'name', 'type', 'Service');
858 $item['alternate-url'] = self::processElement($object, 'url', 'href');
859 $item['receiver'] = self::getReceivers($object);
863 unset($object['source']);
866 unset($object['@context']);
867 unset($object['type']);
868 unset($object['actor']);
869 unset($object['signature']);
870 unset($object['mediaType']);
871 unset($object['duration']);
872 unset($object['replies']);
873 unset($object['icon']);
876 audience, preview, endTime, startTime, generator, image
881 private static function processNote($object)
887 unset($object['emoji']);
888 unset($object['atomUri']);
889 unset($object['inReplyToAtomUri']);
892 unset($object['contentMap']);
893 unset($object['announcement_count']);
894 unset($object['announcements']);
895 unset($object['context_id']);
896 unset($object['likes']);
897 unset($object['like_count']);
898 unset($object['inReplyToStatusId']);
899 unset($object['shares']);
900 unset($object['quoteUrl']);
901 unset($object['statusnetConversationId']);
906 private static function processArticle($object)
913 private static function processVideo($object)
918 unset($object['category']);
919 unset($object['licence']);
920 unset($object['language']);
921 unset($object['commentsEnabled']);
924 unset($object['views']);
925 unset($object['waitTranscoding']);
926 unset($object['state']);
927 unset($object['support']);
928 unset($object['subtitleLanguage']);
929 unset($object['likes']);
930 unset($object['dislikes']);
931 unset($object['shares']);
932 unset($object['comments']);
937 private static function processElement($array, $element, $key, $type = null, $type_value = null)
943 if (empty($array[$element])) {
947 if (is_string($array[$element])) {
948 return $array[$element];
951 if (is_null($type_value)) {
952 if (!empty($array[$element][$key])) {
953 return $array[$element][$key];
956 if (!empty($array[$element][0][$key])) {
957 return $array[$element][0][$key];
963 if (!empty($array[$element][$key]) && !empty($array[$element][$type]) && ($array[$element][$type] == $type_value)) {
964 return $array[$element][$key];
967 /// @todo Add array search
972 private static function convertMentions($body)
974 $URLSearchString = "^\[\]";
975 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
980 private static function constructTagList($tags, $sensitive)
987 foreach ($tags as $tag) {
988 if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
989 if (!empty($tag_text)) {
993 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
997 /// @todo add nsfw for $sensitive
1002 private static function constructAttachList($attachments, $item)
1004 if (empty($attachments)) {
1008 foreach ($attachments as $attach) {
1009 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1010 if ($filetype == 'image') {
1011 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1013 if (!empty($item["attach"])) {
1014 $item["attach"] .= ',';
1016 $item["attach"] = '';
1018 if (!isset($attach['length'])) {
1019 $attach['length'] = "0";
1021 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1028 private static function createItem($activity, $body)
1031 $item['verb'] = ACTIVITY_POST;
1032 $item['parent-uri'] = $activity['reply-to-uri'];
1034 if ($activity['reply-to-uri'] == $activity['uri']) {
1035 $item['gravity'] = GRAVITY_PARENT;
1036 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1038 $item['gravity'] = GRAVITY_COMMENT;
1039 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1042 self::postItem($activity, $item, $body);
1045 private static function likeItem($activity, $body)
1048 $item['verb'] = ACTIVITY_LIKE;
1049 $item['parent-uri'] = $activity['object'];
1050 $item['gravity'] = GRAVITY_ACTIVITY;
1051 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1053 self::postItem($activity, $item, $body);
1056 private static function postItem($activity, $item, $body)
1058 /// @todo What to do with $activity['context']?
1060 $item['network'] = Protocol::ACTIVITYPUB;
1061 $item['private'] = !in_array(0, $activity['receiver']);
1062 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1063 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1064 $item['uri'] = $activity['uri'];
1065 $item['created'] = $activity['published'];
1066 $item['edited'] = $activity['updated'];
1067 $item['guid'] = $activity['uuid'];
1068 $item['title'] = HTML::toBBCode($activity['name']);
1069 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1070 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1071 $item['location'] = $activity['location'];
1072 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1073 $item['app'] = $activity['service'];
1074 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1076 $item = self::constructAttachList($activity['attachments'], $item);
1078 $source = self::processElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1079 if (!empty($source)) {
1080 $item['body'] = $source;
1083 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1084 $item['source'] = $body;
1085 $item['conversation-uri'] = $activity['conversation'];
1087 foreach ($activity['receiver'] as $receiver) {
1088 $item['uid'] = $receiver;
1089 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1091 if (($receiver != 0) && empty($item['contact-id'])) {
1092 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1095 $item_id = Item::insert($item);
1096 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1097 if (!empty($item_id) && ($item['uid'] == 0)) {
1098 Item::distribute($item_id);
1103 private static function followUser($activity)
1105 if (empty($activity['receiver'][$activity['object']])) {
1109 $uid = $activity['receiver'][$activity['object']];
1110 $owner = User::getOwnerDataById($uid);
1112 $cid = Contact::getIdForURL($activity['owner'], $uid);
1114 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1119 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1120 'author-link' => $activity['owner']];
1122 Contact::addRelationship($owner, $contact, $item);
1123 $cid = Contact::getIdForURL($activity['owner'], $uid);
1128 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1129 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1130 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1133 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1134 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1137 private static function acceptFollowUser($activity)
1139 if (empty($activity['receiver'][$activity['object']])) {
1143 $uid = $activity['receiver'][$activity['object']];
1144 $owner = User::getOwnerDataById($uid);
1146 $cid = Contact::getIdForURL($activity['owner'], $uid);
1148 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1152 $fields = ['pending' => false];
1153 $condition = ['id' => $cid, 'pending' => true];
1154 DBA::update('comtact', $fields, $condition);
1155 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1158 private static function undoFollowUser($activity)
1160 if (empty($activity['receiver'][$activity['object']])) {
1164 $uid = $activity['receiver'][$activity['object']];
1165 $owner = User::getOwnerDataById($uid);
1167 $cid = Contact::getIdForURL($activity['owner'], $uid);
1169 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1173 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1174 if (!DBA::isResult($contact)) {
1178 Contact::removeFollower($owner, $contact);
1179 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);