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 transmitContactReject($target, $id, $uid)
235 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
237 $owner = User::getOwnerDataById($uid);
238 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
239 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
241 'actor' => $owner['url'],
242 'object' => ['id' => $id, 'type' => 'Follow',
243 'actor' => $profile['url'],
244 'object' => $owner['url']]];
246 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
247 return self::transmit($data, $profile['notify'], $uid);
250 public static function transmitContactUndo($target, $uid)
252 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
254 $id = System::baseUrl() . '/activity/' . System::createGUID();
256 $owner = User::getOwnerDataById($uid);
257 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
260 'actor' => $owner['url'],
261 'object' => ['id' => $id, 'type' => 'Follow',
262 'actor' => $owner['url'],
263 'object' => $profile['url']]];
265 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
266 return self::transmit($data, $profile['notify'], $uid);
270 * Fetches ActivityPub content from the given url
272 * @param string $url content url
275 public static function fetchContent($url)
277 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json']);
279 if (!$ret['success'] || empty($ret['body'])) {
283 return json_decode($ret['body'], true);
287 * Resolves the profile url from the address by using webfinger
289 * @param string $addr profile address (user@domain.tld)
292 private static function addrToUrl($addr)
294 $addr_parts = explode('@', $addr);
295 if (count($addr_parts) != 2) {
299 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
301 $ret = Network::curl($webfinger, false, $redirects, ['accept_content' => 'application/jrd+json,application/json']);
302 if (!$ret['success'] || empty($ret['body'])) {
306 $data = json_decode($ret['body'], true);
308 if (empty($data['links'])) {
312 foreach ($data['links'] as $link) {
313 if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
317 if (($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
318 return $link['href'];
325 public static function verifySignature($content, $http_headers)
327 $object = json_decode($content, true);
329 if (empty($object)) {
333 $actor = self::processElement($object, 'actor', 'id');
336 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
338 // First take every header
339 foreach ($http_headers as $k => $v) {
340 $field = str_replace('_', '-', strtolower($k));
341 $headers[$field] = $v;
344 // Now add every http header
345 foreach ($http_headers as $k => $v) {
346 if (strpos($k, 'HTTP_') === 0) {
347 $field = str_replace('_', '-', strtolower(substr($k, 5)));
348 $headers[$field] = $v;
352 $sig_block = ActivityPub::parseSigHeader($http_headers['HTTP_SIGNATURE']);
354 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
359 foreach ($sig_block['headers'] as $h) {
360 if (array_key_exists($h, $headers)) {
361 $signed_data .= $h . ': ' . $headers[$h] . "\n";
364 $signed_data = rtrim($signed_data, "\n");
366 if (empty($signed_data)) {
372 if ($sig_block['algorithm'] === 'rsa-sha256') {
373 $algorithm = 'sha256';
376 if ($sig_block['algorithm'] === 'rsa-sha512') {
377 $algorithm = 'sha512';
380 if (empty($algorithm)) {
384 $key = self::fetchKey($sig_block['keyId'], $actor);
390 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm)) {
394 // Check the digest if it was part of the signed data
395 if (in_array('digest', $sig_block['headers'])) {
396 $digest = explode('=', $headers['digest'], 2);
397 if ($digest[0] === 'SHA-256') {
400 if ($digest[0] === 'SHA-512') {
404 /// @todo add all hashes from the rfc
406 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
411 // Check the content-length if it was part of the signed data
412 if (in_array('content-length', $sig_block['headers'])) {
413 if (strlen($content) != $headers['content-length']) {
422 private static function fetchKey($id, $actor)
424 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
426 $profile = Probe::uri($url, Protocol::ACTIVITYPUB);
427 if (!empty($profile)) {
428 return $profile['pubkey'];
429 } elseif ($url != $actor) {
430 $profile = Probe::uri($actor, Protocol::ACTIVITYPUB);
431 if (!empty($profile)) {
432 return $profile['pubkey'];
442 * @param string $header
443 * @return array associate array with
444 * - \e string \b keyID
445 * - \e string \b algorithm
446 * - \e array \b headers
447 * - \e string \b signature
449 private static function parseSigHeader($header)
454 if (preg_match('/keyId="(.*?)"/ism',$header,$matches)) {
455 $ret['keyId'] = $matches[1];
458 if (preg_match('/algorithm="(.*?)"/ism',$header,$matches)) {
459 $ret['algorithm'] = $matches[1];
462 if (preg_match('/headers="(.*?)"/ism',$header,$matches)) {
463 $ret['headers'] = explode(' ', $matches[1]);
466 if (preg_match('/signature="(.*?)"/ism',$header,$matches)) {
467 $ret['signature'] = base64_decode(preg_replace('/\s+/','',$matches[1]));
474 * Fetches a profile from the given url
476 * @param string $url profile url
479 public static function fetchProfile($url)
481 if (empty(parse_url($url, PHP_URL_SCHEME))) {
482 $url = self::addrToUrl($url);
488 $data = self::fetchContent($url);
490 if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
494 $profile = ['network' => Protocol::ACTIVITYPUB];
495 $profile['nick'] = $data['preferredUsername'];
496 $profile['name'] = defaults($data, 'name', $profile['nick']);
497 $profile['guid'] = defaults($data, 'uuid', null);
498 $profile['url'] = $data['id'];
500 $parts = parse_url($profile['url']);
501 unset($parts['scheme']);
502 unset($parts['path']);
503 $profile['addr'] = $profile['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
504 $profile['alias'] = self::processElement($data, 'url', 'href');
505 $profile['photo'] = self::processElement($data, 'icon', 'url');
506 // $profile['community']
507 // $profile['keywords']
508 // $profile['location']
509 $profile['about'] = defaults($data, 'summary', '');
510 $profile['batch'] = self::processElement($data, 'endpoints', 'sharedInbox');
511 $profile['notify'] = $data['inbox'];
512 $profile['poll'] = $data['outbox'];
513 $profile['pubkey'] = self::processElement($data, 'publicKey', 'publicKeyPem');
515 // Check if the address is resolvable
516 if (self::addrToUrl($profile['addr']) == $profile['url']) {
517 $parts = parse_url($profile['url']);
518 unset($parts['path']);
519 $profile['baseurl'] = Network::unparseURL($parts);
521 unset($profile['addr']);
524 if ($profile['url'] == $profile['alias']) {
525 unset($profile['alias']);
528 // Remove all "null" fields
529 foreach ($profile as $field => $content) {
530 if (is_null($content)) {
531 unset($profile[$field]);
537 unset($data['type']);
538 unset($data['manuallyApprovesFollowers']);
541 unset($data['@context']);
543 unset($data['attachment']);
544 unset($data['image']);
545 unset($data['nomadicLocations']);
546 unset($data['signature']);
547 unset($data['following']);
548 unset($data['followers']);
549 unset($data['featured']);
550 unset($data['movedTo']);
551 unset($data['liked']);
552 unset($data['sharedInbox']); // Misskey
553 unset($data['isCat']); // Misskey
554 unset($data['kroeg:blocks']); // Kroeg
555 unset($data['updated']); // Kroeg
560 public static function processInbox($body, $header, $uid)
562 logger('Incoming message for user ' . $uid, LOGGER_DEBUG);
564 if (!self::verifySignature($body, $header)) {
565 logger('Invalid signature, message will be discarded.', LOGGER_DEBUG);
569 $activity = json_decode($body, true);
571 if (!is_array($activity)) {
572 logger('Invalid body.', LOGGER_DEBUG);
576 self::processActivity($activity, $body, $uid);
579 public static function fetchOutbox($url)
581 $data = self::fetchContent($url);
586 if (!empty($data['orderedItems'])) {
587 $items = $data['orderedItems'];
588 } elseif (!empty($data['first']['orderedItems'])) {
589 $items = $data['first']['orderedItems'];
590 } elseif (!empty($data['first'])) {
591 self::fetchOutbox($data['first']);
597 foreach ($items as $activity) {
598 self::processActivity($activity);
602 function processActivity($activity, $body = '', $uid = null)
604 if (empty($activity['type'])) {
605 logger('Empty type', LOGGER_DEBUG);
609 if (empty($activity['object'])) {
610 logger('Empty object', LOGGER_DEBUG);
614 if (empty($activity['actor'])) {
615 logger('Empty actor', LOGGER_DEBUG);
620 $actor = self::processElement($activity, 'actor', 'id');
622 logger('Empty actor - 2', LOGGER_DEBUG);
626 if (is_string($activity['object'])) {
627 $object_url = $activity['object'];
628 } elseif (!empty($activity['object']['id'])) {
629 $object_url = $activity['object']['id'];
631 logger('No object found', LOGGER_DEBUG);
635 // ----------------------------------
638 unset($activity['@context']);
639 unset($activity['id']);
642 unset($activity['title']);
643 unset($activity['atomUri']);
644 unset($activity['context_id']);
645 unset($activity['statusnetConversationId']);
648 unset($activity['context']);
649 unset($activity['location']);
650 unset($activity['signature']);
652 // Fetch all receivers from to, cc, bto and bcc
653 $receivers = self::getReceivers($activity);
655 // When it is a delivery to a personal inbox we add that user to the receivers
657 $owner = User::getOwnerDataById($uid);
658 $additional = [$owner['url'] => $uid];
659 $receivers = array_merge($receivers, $additional);
662 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
664 logger('Processing activity: ' . $activity['type'], LOGGER_DEBUG);
666 // Fetch the content only on activities where this matters
667 if (in_array($activity['type'], ['Create', 'Update', 'Announce'])) {
668 $item = self::fetchObject($object_url, $activity['object']);
670 logger("Object data couldn't be processed", LOGGER_DEBUG);
674 if (in_array($activity['type'], ['Accept'])) {
675 $item['object'] = self::processElement($activity, 'object', 'actor', 'type', 'Follow');
676 } elseif (in_array($activity['type'], ['Undo'])) {
677 $item['object'] = self::processElement($activity, 'object', 'object', 'type', 'Follow');
679 $item['object'] = $object_url;
681 $item['id'] = $activity['id'];
682 $item['receiver'] = [];
683 $item['type'] = $activity['type'];
686 $item = self::addActivityFields($item, $activity);
688 $item['owner'] = $actor;
690 $item['receiver'] = array_merge($item['receiver'], $receivers);
692 switch ($activity['type']) {
696 self::createItem($item, $body);
700 self::likeItem($item, $body);
710 self::followUser($item);
714 self::acceptFollowUser($item);
718 self::undoFollowUser($item);
722 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
727 private static function getReceivers($activity)
731 $elements = ['to', 'cc', 'bto', 'bcc'];
732 foreach ($elements as $element) {
733 if (empty($activity[$element])) {
737 // The receiver can be an arror or a string
738 if (is_string($activity[$element])) {
739 $activity[$element] = [$activity[$element]];
742 foreach ($activity[$element] as $receiver) {
743 if ($receiver == self::PUBLIC) {
744 $receivers[$receiver] = 0;
747 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
748 $contact = DBA::selectFirst('contact', ['uid'], $condition);
749 if (!DBA::isResult($contact)) {
752 $receivers[$receiver] = $contact['uid'];
758 private static function addActivityFields($item, $activity)
760 if (!empty($activity['published']) && empty($item['published'])) {
761 $item['published'] = $activity['published'];
764 if (!empty($activity['updated']) && empty($item['updated'])) {
765 $item['updated'] = $activity['updated'];
768 if (!empty($activity['inReplyTo']) && empty($item['parent-uri'])) {
769 $item['parent-uri'] = self::processElement($activity, 'inReplyTo', 'id');
772 if (!empty($activity['instrument'])) {
773 $item['service'] = self::processElement($activity, 'instrument', 'name', 'type', 'Service');
778 private static function fetchObject($object_url, $object = [])
780 $data = self::fetchContent($object_url);
784 logger('Empty content', LOGGER_DEBUG);
786 } elseif (is_string($data)) {
787 logger('No object array provided.', LOGGER_DEBUG);
788 $item = Item::selectFirst([], ['uri' => $data]);
789 if (!DBA::isResult($item)) {
790 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
793 logger('Using already stored item', LOGGER_DEBUG);
794 $data = self::createNote($item);
796 logger('Using provided object', LOGGER_DEBUG);
800 if (empty($data['type'])) {
801 logger('Empty type', LOGGER_DEBUG);
804 $type = $data['type'];
805 logger('Type ' . $type, LOGGER_DEBUG);
808 if (in_array($type, ['Note', 'Article', 'Video'])) {
809 $common = self::processCommonData($data);
814 return array_merge($common, self::processNote($data));
816 return array_merge($common, self::processArticle($data));
818 return array_merge($common, self::processVideo($data));
821 if (empty($data['object'])) {
824 return self::fetchObject($data['object']);
831 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
836 private static function processCommonData(&$object)
838 if (empty($object['id']) || empty($object['attributedTo'])) {
843 $item['type'] = $object['type'];
844 $item['uri'] = $object['id'];
846 if (!empty($object['inReplyTo'])) {
847 $item['reply-to-uri'] = self::processElement($object, 'inReplyTo', 'id');
849 $item['reply-to-uri'] = $item['uri'];
852 $item['published'] = defaults($object, 'published', null);
853 $item['updated'] = defaults($object, 'updated', $item['published']);
855 if (empty($item['published']) && !empty($item['updated'])) {
856 $item['published'] = $item['updated'];
859 $item['uuid'] = defaults($object, 'uuid', null);
860 $item['owner'] = $item['author'] = self::processElement($object, 'attributedTo', 'id');
861 $item['context'] = defaults($object, 'context', null);
862 $item['conversation'] = defaults($object, 'conversation', null);
863 $item['sensitive'] = defaults($object, 'sensitive', null);
864 $item['name'] = defaults($object, 'title', null);
865 $item['name'] = defaults($object, 'name', $item['name']);
866 $item['summary'] = defaults($object, 'summary', null);
867 $item['content'] = defaults($object, 'content', null);
868 $item['source'] = defaults($object, 'source', null);
869 $item['location'] = self::processElement($object, 'location', 'name', 'type', 'Place');
870 $item['attachments'] = defaults($object, 'attachment', null);
871 $item['tags'] = defaults($object, 'tag', null);
872 $item['service'] = self::processElement($object, 'instrument', 'name', 'type', 'Service');
873 $item['alternate-url'] = self::processElement($object, 'url', 'href');
874 $item['receiver'] = self::getReceivers($object);
878 unset($object['source']);
881 unset($object['@context']);
882 unset($object['type']);
883 unset($object['actor']);
884 unset($object['signature']);
885 unset($object['mediaType']);
886 unset($object['duration']);
887 unset($object['replies']);
888 unset($object['icon']);
891 audience, preview, endTime, startTime, generator, image
896 private static function processNote($object)
902 unset($object['emoji']);
903 unset($object['atomUri']);
904 unset($object['inReplyToAtomUri']);
907 unset($object['contentMap']);
908 unset($object['announcement_count']);
909 unset($object['announcements']);
910 unset($object['context_id']);
911 unset($object['likes']);
912 unset($object['like_count']);
913 unset($object['inReplyToStatusId']);
914 unset($object['shares']);
915 unset($object['quoteUrl']);
916 unset($object['statusnetConversationId']);
921 private static function processArticle($object)
928 private static function processVideo($object)
933 unset($object['category']);
934 unset($object['licence']);
935 unset($object['language']);
936 unset($object['commentsEnabled']);
939 unset($object['views']);
940 unset($object['waitTranscoding']);
941 unset($object['state']);
942 unset($object['support']);
943 unset($object['subtitleLanguage']);
944 unset($object['likes']);
945 unset($object['dislikes']);
946 unset($object['shares']);
947 unset($object['comments']);
952 private static function processElement($array, $element, $key, $type = null, $type_value = null)
958 if (empty($array[$element])) {
962 if (is_string($array[$element])) {
963 return $array[$element];
966 if (is_null($type_value)) {
967 if (!empty($array[$element][$key])) {
968 return $array[$element][$key];
971 if (!empty($array[$element][0][$key])) {
972 return $array[$element][0][$key];
978 if (!empty($array[$element][$key]) && !empty($array[$element][$type]) && ($array[$element][$type] == $type_value)) {
979 return $array[$element][$key];
982 /// @todo Add array search
987 private static function convertMentions($body)
989 $URLSearchString = "^\[\]";
990 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
995 private static function constructTagList($tags, $sensitive)
1002 foreach ($tags as $tag) {
1003 if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1004 if (!empty($tag_text)) {
1008 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1012 /// @todo add nsfw for $sensitive
1017 private static function constructAttachList($attachments, $item)
1019 if (empty($attachments)) {
1023 foreach ($attachments as $attach) {
1024 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1025 if ($filetype == 'image') {
1026 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1028 if (!empty($item["attach"])) {
1029 $item["attach"] .= ',';
1031 $item["attach"] = '';
1033 if (!isset($attach['length'])) {
1034 $attach['length'] = "0";
1036 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1043 private static function createItem($activity, $body)
1046 $item['verb'] = ACTIVITY_POST;
1047 $item['parent-uri'] = $activity['reply-to-uri'];
1049 if ($activity['reply-to-uri'] == $activity['uri']) {
1050 $item['gravity'] = GRAVITY_PARENT;
1051 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1053 $item['gravity'] = GRAVITY_COMMENT;
1054 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1057 self::postItem($activity, $item, $body);
1060 private static function likeItem($activity, $body)
1063 $item['verb'] = ACTIVITY_LIKE;
1064 $item['parent-uri'] = $activity['object'];
1065 $item['gravity'] = GRAVITY_ACTIVITY;
1066 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1068 self::postItem($activity, $item, $body);
1071 private static function postItem($activity, $item, $body)
1073 /// @todo What to do with $activity['context']?
1075 $item['network'] = Protocol::ACTIVITYPUB;
1076 $item['private'] = !in_array(0, $activity['receiver']);
1077 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1078 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1079 $item['uri'] = $activity['uri'];
1080 $item['created'] = $activity['published'];
1081 $item['edited'] = $activity['updated'];
1082 $item['guid'] = $activity['uuid'];
1083 $item['title'] = HTML::toBBCode($activity['name']);
1084 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1085 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1086 $item['location'] = $activity['location'];
1087 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1088 $item['app'] = $activity['service'];
1089 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1091 $item = self::constructAttachList($activity['attachments'], $item);
1093 $source = self::processElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1094 if (!empty($source)) {
1095 $item['body'] = $source;
1098 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1099 $item['source'] = $body;
1100 $item['conversation-uri'] = $activity['conversation'];
1102 foreach ($activity['receiver'] as $receiver) {
1103 $item['uid'] = $receiver;
1104 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1106 if (($receiver != 0) && empty($item['contact-id'])) {
1107 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1110 $item_id = Item::insert($item);
1111 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1112 if (!empty($item_id) && ($item['uid'] == 0)) {
1113 Item::distribute($item_id);
1118 private static function followUser($activity)
1120 if (empty($activity['receiver'][$activity['object']])) {
1124 $uid = $activity['receiver'][$activity['object']];
1125 $owner = User::getOwnerDataById($uid);
1127 $cid = Contact::getIdForURL($activity['owner'], $uid);
1129 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1134 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1135 'author-link' => $activity['owner']];
1137 Contact::addRelationship($owner, $contact, $item);
1138 $cid = Contact::getIdForURL($activity['owner'], $uid);
1143 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1144 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1145 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1148 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1149 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1152 private static function acceptFollowUser($activity)
1154 if (empty($activity['receiver'][$activity['object']])) {
1158 $uid = $activity['receiver'][$activity['object']];
1159 $owner = User::getOwnerDataById($uid);
1161 $cid = Contact::getIdForURL($activity['owner'], $uid);
1163 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1167 $fields = ['pending' => false];
1169 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1170 if ($contact['rel'] == Contact::FOLLOWER) {
1171 $fields['rel'] = Contact::FRIEND;
1174 $condition = ['id' => $cid];
1175 DBA::update('contact', $fields, $condition);
1176 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1179 private static function undoFollowUser($activity)
1181 if (empty($activity['receiver'][$activity['object']])) {
1185 $uid = $activity['receiver'][$activity['object']];
1186 $owner = User::getOwnerDataById($uid);
1188 $cid = Contact::getIdForURL($activity['owner'], $uid);
1190 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1194 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1195 if (!DBA::isResult($contact)) {
1199 Contact::removeFollower($owner, $contact);
1200 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);