3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Core\Logger;
27 use Friendica\Core\Protocol;
28 use Friendica\Database\DBA;
30 use Friendica\Model\APContact;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Conversation;
33 use Friendica\Model\Event;
34 use Friendica\Model\Item;
35 use Friendica\Model\ItemURI;
36 use Friendica\Model\Mail;
37 use Friendica\Model\Tag;
38 use Friendica\Model\Term;
39 use Friendica\Model\User;
40 use Friendica\Protocol\Activity;
41 use Friendica\Protocol\ActivityPub;
42 use Friendica\Util\DateTimeFormat;
43 use Friendica\Util\JsonLD;
44 use Friendica\Util\Strings;
47 * ActivityPub Processor Protocol class
52 * Converts mentions from Pleroma into the Friendica format
56 * @return string converted body
58 private static function convertMentions($body)
60 $URLSearchString = "^\[\]";
61 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
67 * Replaces emojis in the body
69 * @param array $emojis
72 * @return string with replaced emojis
74 private static function replaceEmojis($body, array $emojis)
76 foreach ($emojis as $emoji) {
77 $replace = '[class=emoji mastodon][img=' . $emoji['href'] . ']' . $emoji['name'] . '[/img][/class]';
78 $body = str_replace($emoji['name'], $replace, $body);
84 * Constructs a string with tags for a given tag array
87 * @param boolean $sensitive
88 * @return string with tags
90 private static function constructTagString(array $tags = null, $sensitive = false)
97 foreach ($tags as $tag) {
98 if (in_array($tag['type'] ?? '', ['Mention', 'Hashtag'])) {
99 if (!empty($tag_text)) {
103 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
107 /// @todo add nsfw for $sensitive
113 * Add attachment data to the item array
115 * @param array $activity
118 * @return array array
120 private static function constructAttachList($activity, $item)
122 if (empty($activity['attachments'])) {
126 foreach ($activity['attachments'] as $attach) {
127 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
128 if ($filetype == 'image') {
129 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
133 if (empty($attach['name'])) {
134 $item['body'] .= "\n[img]" . $attach['url'] . '[/img]';
136 $item['body'] .= "\n[img=" . $attach['url'] . ']' . $attach['name'] . '[/img]';
138 } elseif ($filetype == 'audio') {
139 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
143 $item['body'] .= "\n[audio]" . $attach['url'] . '[/audio]';
144 } elseif ($filetype == 'video') {
145 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
149 $item['body'] .= "\n[video]" . $attach['url'] . '[/video]';
151 if (!empty($item["attach"])) {
152 $item["attach"] .= ',';
154 $item["attach"] = '';
156 if (!isset($attach['length'])) {
157 $attach['length'] = "0";
159 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.($attach['name'] ?? '') .'"[/attach]';
169 * @param array $activity Activity array
170 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
172 public static function updateItem($activity)
174 $item = Item::selectFirst(['uri', 'uri-id', 'thr-parent', 'gravity'], ['uri' => $activity['id']]);
175 if (!DBA::isResult($item)) {
176 Logger::warning('Unknown item', ['uri' => $activity['id']]);
180 $item['changed'] = DateTimeFormat::utcNow();
181 $item['edited'] = DateTimeFormat::utc($activity['updated']);
183 $item = self::processContent($activity, $item);
188 Item::update($item, ['uri' => $activity['id']]);
192 * Prepares data for a message
194 * @param array $activity Activity array
195 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
196 * @throws \ImagickException
198 public static function createItem($activity)
201 $item['verb'] = Activity::POST;
202 $item['thr-parent'] = $activity['reply-to-id'];
204 if ($activity['reply-to-id'] == $activity['id']) {
205 $item['gravity'] = GRAVITY_PARENT;
206 $item['object-type'] = Activity\ObjectType::NOTE;
208 $item['gravity'] = GRAVITY_COMMENT;
209 $item['object-type'] = Activity\ObjectType::COMMENT;
211 // Ensure that the comment reaches all receivers of the referring post
212 $activity['receiver'] = self::addReceivers($activity);
215 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
216 Logger::notice('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id']]);
217 self::fetchMissingActivity($activity['reply-to-id'], $activity);
220 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
222 self::postItem($activity, $item);
228 * @param array $activity
229 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
230 * @throws \ImagickException
232 public static function deleteItem($activity)
234 $owner = Contact::getIdForURL($activity['actor']);
236 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
237 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
241 * Prepare the item array for an activity
243 * @param array $activity Activity array
244 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
245 * @throws \ImagickException
247 public static function addTag($activity)
249 if (empty($activity['object_content']) || empty($activity['object_id'])) {
253 foreach ($activity['receiver'] as $receiver) {
254 $item = Item::selectFirst(['id', 'uri-id', 'tag', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
255 if (!DBA::isResult($item)) {
256 // We don't fetch missing content for this purpose
260 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
261 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
265 Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
268 // - Check if "blocktag" is set
269 // - Check if actor is a contact
271 if (!stristr($item['tag'], trim($activity['object_content']))) {
272 $tag = $item['tag'] . (strlen($item['tag']) ? ',' : '') . '#[url=' . $activity['object_id'] . ']'. $activity['object_content'] . '[/url]';
273 Item::update(['tag' => $tag], ['id' => $item['id']]);
274 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
280 * Add users to the receiver list of the given public activity.
281 * This is used to ensure that the activity will be stored in every thread.
283 * @param array $activity Activity array
284 * @return array Modified receiver list
286 private static function addReceivers(array $activity)
288 if (!in_array(0, $activity['receiver'])) {
289 // Private activities will not be modified
290 return $activity['receiver'];
293 // Add all owners of the referring item to the receivers
294 $original = $receivers = $activity['receiver'];
295 $items = Item::select(['uid'], ['uri' => $activity['object_id']]);
296 while ($item = DBA::fetch($items)) {
297 $receivers['uid:' . $item['uid']] = $item['uid'];
301 if (count($original) != count($receivers)) {
302 Logger::info('Improved data', ['id' => $activity['id'], 'object' => $activity['object_id'], 'original' => $original, 'improved' => $receivers]);
309 * Prepare the item array for an activity
311 * @param array $activity Activity array
312 * @param string $verb Activity verb
313 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
314 * @throws \ImagickException
316 public static function createActivity($activity, $verb)
319 $item['verb'] = $verb;
320 $item['thr-parent'] = $activity['object_id'];
321 $item['gravity'] = GRAVITY_ACTIVITY;
322 $item['object-type'] = Activity\ObjectType::NOTE;
324 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
326 $activity['receiver'] = self::addReceivers($activity);
328 self::postItem($activity, $item);
334 * @param array $activity Activity array
338 public static function createEvent($activity, $item)
340 $event['summary'] = HTML::toBBCode($activity['name']);
341 $event['desc'] = HTML::toBBCode($activity['content']);
342 $event['start'] = $activity['start-time'];
343 $event['finish'] = $activity['end-time'];
344 $event['nofinish'] = empty($event['finish']);
345 $event['location'] = $activity['location'];
346 $event['adjust'] = true;
347 $event['cid'] = $item['contact-id'];
348 $event['uid'] = $item['uid'];
349 $event['uri'] = $item['uri'];
350 $event['edited'] = $item['edited'];
351 $event['private'] = $item['private'];
352 $event['guid'] = $item['guid'];
353 $event['plink'] = $item['plink'];
355 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
356 $ev = DBA::selectFirst('event', ['id'], $condition);
357 if (DBA::isResult($ev)) {
358 $event['id'] = $ev['id'];
361 $event_id = Event::store($event);
362 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
366 * Process the content
368 * @param array $activity Activity array
370 * @return array|bool Returns the item array or false if there was an unexpected occurrence
373 private static function processContent($activity, $item)
375 $item['title'] = HTML::toBBCode($activity['name']);
377 if (!empty($activity['source'])) {
378 $item['body'] = $activity['source'];
380 $content = HTML::toBBCode($activity['content']);
382 if (!empty($activity['emojis'])) {
383 $content = self::replaceEmojis($content, $activity['emojis']);
386 $content = self::convertMentions($content);
388 if (empty($activity['directmessage']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
389 $item_private = !in_array(0, $activity['item_receiver']);
390 $parent = Item::selectFirst(['id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
391 if (!DBA::isResult($parent)) {
392 Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
395 if ($item_private && ($parent['private'] == Item::PRIVATE)) {
396 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
400 $potential_implicit_mentions = self::getImplicitMentionList($parent);
401 $content = self::removeImplicitMentionsFromBody($content, $potential_implicit_mentions);
402 $activity['tags'] = self::convertImplicitMentionsInTags($activity['tags'], $potential_implicit_mentions);
404 $item['content-warning'] = HTML::toBBCode($activity['summary']);
405 $item['body'] = $content;
408 $item['tag'] = self::constructTagString($activity['tags'], $activity['sensitive']);
410 self::storeFromBody($item);
411 self::storeTags($item['uri-id'], $activity['tags']);
413 $item['location'] = $activity['location'];
415 if (!empty($item['latitude']) && !empty($item['longitude'])) {
416 $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
419 $item['app'] = $activity['generator'];
424 private static function storeFromBody($item)
426 // Make sure to delete all existing tags (can happen when called via the update functionality)
427 DBA::delete('post-tag', ['uri-id' => $uriid]);
429 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
433 * Generate a GUID out of an URL
435 * @param string $url message URL
436 * @return string with GUID
438 private static function getGUIDByURL(string $url)
440 $parsed = parse_url($url);
442 $host_hash = hash('crc32', $parsed['host']);
444 unset($parsed["scheme"]);
445 unset($parsed["host"]);
447 $path = implode("/", $parsed);
449 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
453 * Creates an item post
455 * @param array $activity Activity data
456 * @param array $item item array
457 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
458 * @throws \ImagickException
460 private static function postItem($activity, $item)
462 /// @todo What to do with $activity['context']?
463 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['thr-parent']])) {
464 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
468 $item['network'] = Protocol::ACTIVITYPUB;
469 $item['author-link'] = $activity['author'];
470 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
471 $item['owner-link'] = $activity['actor'];
472 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
474 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
475 $item['private'] = Item::UNLISTED;
476 } elseif (in_array(0, $activity['receiver'])) {
477 $item['private'] = Item::PUBLIC;
479 $item['private'] = Item::PRIVATE;
482 if (!empty($activity['raw'])) {
483 $item['source'] = $activity['raw'];
484 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
485 $item['conversation-href'] = $activity['context'] ?? '';
486 $item['conversation-uri'] = $activity['conversation'] ?? '';
488 if (isset($activity['push'])) {
489 $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
495 if (!empty($activity['thread-completion'])) {
496 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
497 $item['causer-link'] = $item['owner-link'];
498 $item['causer-id'] = $item['owner-id'];
500 Logger::info('Ignoring actor because of thread completion.', ['actor' => $item['owner-link']]);
501 $item['owner-link'] = $item['author-link'];
502 $item['owner-id'] = $item['author-id'];
504 $actor = APContact::getByURL($item['owner-link'], false);
505 $isForum = ($actor['type'] == 'Group');
508 $item['uri'] = $activity['id'];
510 $item['created'] = DateTimeFormat::utc($activity['published']);
511 $item['edited'] = DateTimeFormat::utc($activity['updated']);
512 $item['guid'] = $activity['diaspora:guid'] ?: $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
514 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
516 $item = self::processContent($activity, $item);
521 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
523 $item = self::constructAttachList($activity, $item);
527 foreach ($activity['receiver'] as $receiver) {
528 if ($receiver == -1) {
532 $item['uid'] = $receiver;
535 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver, true);
537 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
540 if (($receiver != 0) && empty($item['contact-id'])) {
541 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
544 if (!empty($activity['directmessage'])) {
545 self::postMail($activity, $item);
549 if (DI::pConfig()->get($receiver, 'system', 'accept_only_sharer', false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
550 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
552 if ($skip && (($activity['type'] == 'as:Announce') || $isForum)) {
553 $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
557 Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
561 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
564 if (($item['gravity'] != GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
565 self::createEvent($activity, $item);
568 $item_id = Item::insert($item);
570 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
572 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
575 if ($item['uid'] == 0) {
580 // Store send a follow request for every reshare - but only when the item had been stored
581 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
582 $author = APContact::getByURL($item['owner-link'], false);
583 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
584 if ($author['type'] != 'Group') {
585 Logger::log('Send follow request for ' . $item['uri'] . ' (' . $stored . ') to ' . $item['author-link'], Logger::DEBUG);
586 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
592 * Store tags and mentions into the tag table
594 * @param integer $uriid
597 private static function storeTags(int $uriid, array $tags = null)
599 foreach ($tags as $tag) {
600 if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
604 $hash = substr($tag['name'], 0, 1);
606 if ($tag['type'] == 'Mention') {
607 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
608 Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
609 Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
610 $tag['name'] = substr($tag['name'], 1);
612 $type = Tag::IMPLICIT_MENTION;
614 if (!empty($tag['href'])) {
615 $apcontact = APContact::getByURL($tag['href']);
616 if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
617 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
620 } elseif ($tag['type'] == 'Hashtag') {
621 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
622 $tag['name'] = substr($tag['name'], 1);
624 $type = Tag::HASHTAG;
627 if (empty($tag['name'])) {
631 Tag::store($uriid, $type, $tag['name'], $tag['href']);
636 * Creates an mail post
638 * @param array $activity Activity data
639 * @param array $item item array
640 * @return int|bool New mail table row id or false on error
641 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
643 private static function postMail($activity, $item)
645 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
646 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
650 Logger::info('Direct Message', $item);
653 $msg['uid'] = $item['uid'];
655 $msg['contact-id'] = $item['contact-id'];
657 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
658 $msg['from-name'] = $contact['name'];
659 $msg['from-url'] = $contact['url'];
660 $msg['from-photo'] = $contact['photo'];
662 $msg['uri'] = $item['uri'];
663 $msg['created'] = $item['created'];
665 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
666 if (DBA::isResult($parent)) {
667 $msg['parent-uri'] = $parent['parent-uri'];
668 $msg['title'] = $parent['title'];
670 $msg['parent-uri'] = $item['thr-parent'];
672 if (!empty($item['title'])) {
673 $msg['title'] = $item['title'];
674 } elseif (!empty($item['content-warning'])) {
675 $msg['title'] = $item['content-warning'];
677 // Trying to generate a title out of the body
678 $title = $item['body'];
680 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
681 $title = $matches[3];
684 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, 2, true), 0));
686 if (strlen($title) > 20) {
687 $title = substr($title, 0, 20) . '...';
690 $msg['title'] = $title;
693 $msg['body'] = $item['body'];
695 return Mail::insert($msg);
699 * Fetches missing posts
701 * @param string $url message URL
702 * @param array $child activity array with the child of this message
703 * @return string fetched message URL
704 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
706 public static function fetchMissingActivity($url, $child = [])
708 if (!empty($child['receiver'])) {
709 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
714 $object = ActivityPub::fetchContent($url, $uid);
715 if (empty($object)) {
716 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
720 if (empty($object['id'])) {
721 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
725 if (!empty($child['author'])) {
726 $actor = $child['author'];
727 } elseif (!empty($object['actor'])) {
728 $actor = $object['actor'];
729 } elseif (!empty($object['attributedTo'])) {
730 $actor = $object['attributedTo'];
736 if (!empty($object['published'])) {
737 $published = $object['published'];
738 } elseif (!empty($child['published'])) {
739 $published = $child['published'];
741 $published = DateTimeFormat::utcNow();
745 $activity['@context'] = $object['@context'];
746 unset($object['@context']);
747 $activity['id'] = $object['id'];
748 $activity['to'] = $object['to'] ?? [];
749 $activity['cc'] = $object['cc'] ?? [];
750 $activity['actor'] = $actor;
751 $activity['object'] = $object;
752 $activity['published'] = $published;
753 $activity['type'] = 'Create';
755 $ldactivity = JsonLD::compact($activity);
757 $ldactivity['thread-completion'] = true;
759 ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity));
761 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'object' => $activity['id']]);
763 return $activity['id'];
767 * perform a "follow" request
769 * @param array $activity
770 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
771 * @throws \ImagickException
773 public static function followUser($activity)
775 $uid = User::getIdForURL($activity['object_id']);
780 $owner = User::getOwnerDataById($uid);
782 $cid = Contact::getIdForURL($activity['actor'], $uid);
784 self::switchContact($cid);
785 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
786 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
791 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
792 'author-link' => $activity['actor']];
794 $note = Strings::escapeTags(trim($activity['content'] ?? ''));
796 // Ensure that the contact has got the right network type
797 self::switchContact($item['author-id']);
799 $result = Contact::addRelationship($owner, $contact, $item, false, $note);
800 if ($result === true) {
801 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $item['author-id'], $owner['uid']);
804 $cid = Contact::getIdForURL($activity['actor'], $uid);
809 if (empty($contact)) {
810 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
813 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
817 * Update the given profile
819 * @param array $activity
822 public static function updatePerson($activity)
824 if (empty($activity['object_id'])) {
828 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
829 Contact::updateFromProbeByURL($activity['object_id'], true);
833 * Delete the given profile
835 * @param array $activity
836 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
838 public static function deletePerson($activity)
840 if (empty($activity['object_id']) || empty($activity['actor'])) {
841 Logger::log('Empty object id or actor.', Logger::DEBUG);
845 if ($activity['object_id'] != $activity['actor']) {
846 Logger::log('Object id does not match actor.', Logger::DEBUG);
850 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
851 while ($contact = DBA::fetch($contacts)) {
852 Contact::remove($contact['id']);
854 DBA::close($contacts);
856 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
860 * Accept a follow request
862 * @param array $activity
863 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
864 * @throws \ImagickException
866 public static function acceptFollowUser($activity)
868 $uid = User::getIdForURL($activity['object_actor']);
873 $cid = Contact::getIdForURL($activity['actor'], $uid);
875 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
879 self::switchContact($cid);
881 $fields = ['pending' => false];
883 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
884 if ($contact['rel'] == Contact::FOLLOWER) {
885 $fields['rel'] = Contact::FRIEND;
888 $condition = ['id' => $cid];
889 DBA::update('contact', $fields, $condition);
890 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
894 * Reject a follow request
896 * @param array $activity
897 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
898 * @throws \ImagickException
900 public static function rejectFollowUser($activity)
902 $uid = User::getIdForURL($activity['object_actor']);
907 $cid = Contact::getIdForURL($activity['actor'], $uid);
909 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
913 self::switchContact($cid);
915 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
916 Contact::remove($cid);
917 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
919 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
924 * Undo activity like "like" or "dislike"
926 * @param array $activity
927 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
928 * @throws \ImagickException
930 public static function undoActivity($activity)
932 if (empty($activity['object_id'])) {
936 if (empty($activity['object_actor'])) {
940 $author_id = Contact::getIdForURL($activity['object_actor']);
941 if (empty($author_id)) {
945 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
949 * Activity to remove a follower
951 * @param array $activity
952 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
953 * @throws \ImagickException
955 public static function undoFollowUser($activity)
957 $uid = User::getIdForURL($activity['object_object']);
962 $owner = User::getOwnerDataById($uid);
964 $cid = Contact::getIdForURL($activity['actor'], $uid);
966 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
970 self::switchContact($cid);
972 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
973 if (!DBA::isResult($contact)) {
977 Contact::removeFollower($owner, $contact);
978 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
982 * Switches a contact to AP if needed
984 * @param integer $cid Contact ID
987 private static function switchContact($cid)
989 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
990 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
994 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
995 Contact::updateFromProbe($cid);
999 * Collects implicit mentions like:
1000 * - the author of the parent item
1001 * - all the mentioned conversants in the parent item
1003 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
1005 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1007 private static function getImplicitMentionList(array $parent)
1009 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1013 $parent_terms = Term::tagArrayFromItemId($parent['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
1015 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
1017 $implicit_mentions = [];
1018 if (empty($parent_author)) {
1019 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
1021 $implicit_mentions[] = $parent_author['url'];
1022 $implicit_mentions[] = $parent_author['nurl'];
1023 $implicit_mentions[] = $parent_author['alias'];
1026 if (!empty($parent['alias'])) {
1027 $implicit_mentions[] = $parent['alias'];
1030 foreach ($parent_terms as $term) {
1031 $contact = Contact::getDetailsByURL($term['url'], 0);
1032 if (!empty($contact)) {
1033 $implicit_mentions[] = $contact['url'];
1034 $implicit_mentions[] = $contact['nurl'];
1035 $implicit_mentions[] = $contact['alias'];
1039 return $implicit_mentions;
1043 * Strips from the body prepended implicit mentions
1045 * @param string $body
1046 * @param array $potential_mentions
1049 private static function removeImplicitMentionsFromBody($body, array $potential_mentions)
1051 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1055 $kept_mentions = [];
1057 // Extract one prepended mention at a time from the body
1058 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
1059 if (!in_array($matches[2], $potential_mentions)) {
1060 $kept_mentions[] = $matches[1];
1063 $body = $matches[3];
1066 // Re-appending the kept mentions to the body after extraction
1067 $kept_mentions[] = $body;
1069 return implode('', $kept_mentions);
1072 private static function convertImplicitMentionsInTags($activity_tags, array $potential_mentions)
1074 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1075 return $activity_tags;
1078 foreach ($activity_tags as $index => $tag) {
1079 if (in_array($tag['href'], $potential_mentions)) {
1080 $activity_tags[$index]['name'] = preg_replace(
1081 '/' . preg_quote(Term::TAG_CHARACTER[Term::MENTION], '/') . '/',
1082 Term::TAG_CHARACTER[Term::IMPLICIT_MENTION],
1083 $activity_tags[$index]['name'],
1089 return $activity_tags;