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\Event;
33 use Friendica\Model\Item;
34 use Friendica\Model\Mail;
35 use Friendica\Model\Term;
36 use Friendica\Model\User;
37 use Friendica\Protocol\Activity;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Util\DateTimeFormat;
40 use Friendica\Util\JsonLD;
41 use Friendica\Util\Strings;
44 * ActivityPub Processor Protocol class
49 * Converts mentions from Pleroma into the Friendica format
53 * @return string converted body
55 private static function convertMentions($body)
57 $URLSearchString = "^\[\]";
58 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
64 * Replaces emojis in the body
66 * @param array $emojis
69 * @return string with replaced emojis
71 private static function replaceEmojis($body, array $emojis)
73 foreach ($emojis as $emoji) {
74 $replace = '[class=emoji mastodon][img=' . $emoji['href'] . ']' . $emoji['name'] . '[/img][/class]';
75 $body = str_replace($emoji['name'], $replace, $body);
81 * Constructs a string with tags for a given tag array
84 * @param boolean $sensitive
85 * @return string with tags
87 private static function constructTagString(array $tags = null, $sensitive = false)
94 foreach ($tags as $tag) {
95 if (in_array($tag['type'] ?? '', ['Mention', 'Hashtag'])) {
96 if (!empty($tag_text)) {
100 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
104 /// @todo add nsfw for $sensitive
110 * Add attachment data to the item array
112 * @param array $activity
115 * @return array array
117 private static function constructAttachList($activity, $item)
119 if (empty($activity['attachments'])) {
123 foreach ($activity['attachments'] as $attach) {
124 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
125 if ($filetype == 'image') {
126 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
130 if (empty($attach['name'])) {
131 $item['body'] .= "\n[img]" . $attach['url'] . '[/img]';
133 $item['body'] .= "\n[img=" . $attach['url'] . ']' . $attach['name'] . '[/img]';
136 if (!empty($item["attach"])) {
137 $item["attach"] .= ',';
139 $item["attach"] = '';
141 if (!isset($attach['length'])) {
142 $attach['length'] = "0";
144 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.($attach['name'] ?? '') .'"[/attach]';
154 * @param array $activity Activity array
155 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
157 public static function updateItem($activity)
159 $item = Item::selectFirst(['uri', 'thr-parent', 'gravity'], ['uri' => $activity['id']]);
160 if (!DBA::isResult($item)) {
161 Logger::warning('Unknown item', ['uri' => $activity['id']]);
165 $item['changed'] = DateTimeFormat::utcNow();
166 $item['edited'] = DateTimeFormat::utc($activity['updated']);
168 $item = self::processContent($activity, $item);
173 Item::update($item, ['uri' => $activity['id']]);
177 * Prepares data for a message
179 * @param array $activity Activity array
180 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
181 * @throws \ImagickException
183 public static function createItem($activity)
186 $item['verb'] = Activity::POST;
187 $item['thr-parent'] = $activity['reply-to-id'];
189 if ($activity['reply-to-id'] == $activity['id']) {
190 $item['gravity'] = GRAVITY_PARENT;
191 $item['object-type'] = Activity\ObjectType::NOTE;
193 $item['gravity'] = GRAVITY_COMMENT;
194 $item['object-type'] = Activity\ObjectType::COMMENT;
196 // Ensure that the comment reaches all receivers of the referring post
197 $activity['receiver'] = self::addReceivers($activity);
200 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
201 Logger::notice('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id']]);
202 self::fetchMissingActivity($activity['reply-to-id'], $activity);
205 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
207 self::postItem($activity, $item);
213 * @param array $activity
214 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
215 * @throws \ImagickException
217 public static function deleteItem($activity)
219 $owner = Contact::getIdForURL($activity['actor']);
221 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
222 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
226 * Prepare the item array for an activity
228 * @param array $activity Activity array
229 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
230 * @throws \ImagickException
232 public static function addTag($activity)
234 if (empty($activity['object_content']) || empty($activity['object_id'])) {
238 foreach ($activity['receiver'] as $receiver) {
239 $item = Item::selectFirst(['id', 'tag', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
240 if (!DBA::isResult($item)) {
241 // We don't fetch missing content for this purpose
245 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
246 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
251 // - Check if "blocktag" is set
252 // - Check if actor is a contact
254 if (!stristr($item['tag'], trim($activity['object_content']))) {
255 $tag = $item['tag'] . (strlen($item['tag']) ? ',' : '') . '#[url=' . $activity['object_id'] . ']'. $activity['object_content'] . '[/url]';
256 Item::update(['tag' => $tag], ['id' => $item['id']]);
257 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
263 * Add users to the receiver list of the given public activity.
264 * This is used to ensure that the activity will be stored in every thread.
266 * @param array $activity Activity array
267 * @return array Modified receiver list
269 private static function addReceivers(array $activity)
271 if (!in_array(0, $activity['receiver'])) {
272 // Private activities will not be modified
273 return $activity['receiver'];
276 // Add all owners of the referring item to the receivers
277 $original = $receivers = $activity['receiver'];
278 $items = Item::select(['uid'], ['uri' => $activity['object_id']]);
279 while ($item = DBA::fetch($items)) {
280 $receivers['uid:' . $item['uid']] = $item['uid'];
284 if (count($original) != count($receivers)) {
285 Logger::info('Improved data', ['id' => $activity['id'], 'object' => $activity['object_id'], 'original' => $original, 'improved' => $receivers]);
292 * Prepare the item array for an activity
294 * @param array $activity Activity array
295 * @param string $verb Activity verb
296 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
297 * @throws \ImagickException
299 public static function createActivity($activity, $verb)
302 $item['verb'] = $verb;
303 $item['thr-parent'] = $activity['object_id'];
304 $item['gravity'] = GRAVITY_ACTIVITY;
305 $item['object-type'] = Activity\ObjectType::NOTE;
307 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
309 $activity['receiver'] = self::addReceivers($activity);
311 self::postItem($activity, $item);
317 * @param array $activity Activity array
321 public static function createEvent($activity, $item)
323 $event['summary'] = HTML::toBBCode($activity['name']);
324 $event['desc'] = HTML::toBBCode($activity['content']);
325 $event['start'] = $activity['start-time'];
326 $event['finish'] = $activity['end-time'];
327 $event['nofinish'] = empty($event['finish']);
328 $event['location'] = $activity['location'];
329 $event['adjust'] = true;
330 $event['cid'] = $item['contact-id'];
331 $event['uid'] = $item['uid'];
332 $event['uri'] = $item['uri'];
333 $event['edited'] = $item['edited'];
334 $event['private'] = $item['private'];
335 $event['guid'] = $item['guid'];
336 $event['plink'] = $item['plink'];
338 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
339 $ev = DBA::selectFirst('event', ['id'], $condition);
340 if (DBA::isResult($ev)) {
341 $event['id'] = $ev['id'];
344 $event_id = Event::store($event);
345 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
349 * Process the content
351 * @param array $activity Activity array
353 * @return array|bool Returns the item array or false if there was an unexpected occurrence
356 private static function processContent($activity, $item)
358 $item['title'] = HTML::toBBCode($activity['name']);
360 if (!empty($activity['source'])) {
361 $item['body'] = $activity['source'];
363 $content = HTML::toBBCode($activity['content']);
365 if (!empty($activity['emojis'])) {
366 $content = self::replaceEmojis($content, $activity['emojis']);
369 $content = self::convertMentions($content);
371 if (empty($activity['directmessage']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
372 $item_private = !in_array(0, $activity['item_receiver']);
373 $parent = Item::selectFirst(['id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
374 if (!DBA::isResult($parent)) {
375 Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
378 if ($item_private && !$parent['private']) {
379 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
383 $potential_implicit_mentions = self::getImplicitMentionList($parent);
384 $content = self::removeImplicitMentionsFromBody($content, $potential_implicit_mentions);
385 $activity['tags'] = self::convertImplicitMentionsInTags($activity['tags'], $potential_implicit_mentions);
387 $item['content-warning'] = HTML::toBBCode($activity['summary']);
388 $item['body'] = $content;
390 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
391 $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
395 $item['tag'] = self::constructTagString($activity['tags'], $activity['sensitive']);
397 $item['location'] = $activity['location'];
399 if (!empty($item['latitude']) && !empty($item['longitude'])) {
400 $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
403 $item['app'] = $activity['generator'];
409 * Generate a GUID out of an URL
411 * @param string $url message URL
412 * @return string with GUID
414 private static function getGUIDByURL(string $url)
416 $parsed = parse_url($url);
418 $host_hash = hash('crc32', $parsed['host']);
420 unset($parsed["scheme"]);
421 unset($parsed["host"]);
423 $path = implode("/", $parsed);
425 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
429 * Creates an item post
431 * @param array $activity Activity data
432 * @param array $item item array
433 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
434 * @throws \ImagickException
436 private static function postItem($activity, $item)
438 /// @todo What to do with $activity['context']?
439 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['thr-parent']])) {
440 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
444 $item['network'] = Protocol::ACTIVITYPUB;
445 $item['private'] = !in_array(0, $activity['receiver']);
446 $item['author-link'] = $activity['author'];
447 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
448 $item['owner-link'] = $activity['actor'];
449 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
453 if (!empty($activity['thread-completion'])) {
454 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
455 $item['causer-link'] = $item['owner-link'];
456 $item['causer-id'] = $item['owner-id'];
458 Logger::info('Ignoring actor because of thread completion.', ['actor' => $item['owner-link']]);
459 $item['owner-link'] = $item['author-link'];
460 $item['owner-id'] = $item['author-id'];
462 $actor = APContact::getByURL($item['owner-link'], false);
463 $isForum = ($actor['type'] == 'Group');
466 $item['uri'] = $activity['id'];
468 $item['created'] = DateTimeFormat::utc($activity['published']);
469 $item['edited'] = DateTimeFormat::utc($activity['updated']);
470 $item['guid'] = $activity['diaspora:guid'] ?: self::getGUIDByURL($item['uri']);
472 $item = self::processContent($activity, $item);
477 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
479 $item = self::constructAttachList($activity, $item);
483 foreach ($activity['receiver'] as $receiver) {
484 $item['uid'] = $receiver;
487 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver, true);
489 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
492 if (($receiver != 0) && empty($item['contact-id'])) {
493 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
496 if (!empty($activity['directmessage'])) {
497 self::postMail($activity, $item);
501 if (DI::pConfig()->get($receiver, 'system', 'accept_only_sharer', false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
502 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
504 if ($skip && (($activity['type'] == 'as:Announce') || $isForum)) {
505 $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
509 Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
513 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
516 if ($activity['object_type'] == 'as:Event') {
517 self::createEvent($activity, $item);
520 $item_id = Item::insert($item);
522 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
524 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
527 if ($item['uid'] == 0) {
532 // Store send a follow request for every reshare - but only when the item had been stored
533 if ($stored && !$item['private'] && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
534 $author = APContact::getByURL($item['owner-link'], false);
535 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
536 if ($author['type'] != 'Group') {
537 Logger::log('Send follow request for ' . $item['uri'] . ' (' . $stored . ') to ' . $item['author-link'], Logger::DEBUG);
538 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
544 * Creates an mail post
546 * @param array $activity Activity data
547 * @param array $item item array
548 * @return int|bool New mail table row id or false on error
549 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
551 private static function postMail($activity, $item)
553 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
554 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
558 Logger::info('Direct Message', $item);
561 $msg['uid'] = $item['uid'];
563 $msg['contact-id'] = $item['contact-id'];
565 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
566 $msg['from-name'] = $contact['name'];
567 $msg['from-url'] = $contact['url'];
568 $msg['from-photo'] = $contact['photo'];
570 $msg['uri'] = $item['uri'];
571 $msg['created'] = $item['created'];
573 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
574 if (DBA::isResult($parent)) {
575 $msg['parent-uri'] = $parent['parent-uri'];
576 $msg['title'] = $parent['title'];
578 $msg['parent-uri'] = $item['thr-parent'];
580 if (!empty($item['title'])) {
581 $msg['title'] = $item['title'];
582 } elseif (!empty($item['content-warning'])) {
583 $msg['title'] = $item['content-warning'];
585 // Trying to generate a title out of the body
586 $title = $item['body'];
588 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
589 $title = $matches[3];
592 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, 2, true), 0));
594 if (strlen($title) > 20) {
595 $title = substr($title, 0, 20) . '...';
598 $msg['title'] = $title;
601 $msg['body'] = $item['body'];
603 return Mail::insert($msg);
607 * Fetches missing posts
609 * @param string $url message URL
610 * @param array $child activity array with the child of this message
611 * @return string fetched message URL
612 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
614 public static function fetchMissingActivity($url, $child = [])
616 if (!empty($child['receiver'])) {
617 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
622 $object = ActivityPub::fetchContent($url, $uid);
623 if (empty($object)) {
624 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
628 if (empty($object['id'])) {
629 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
633 if (!empty($child['author'])) {
634 $actor = $child['author'];
635 } elseif (!empty($object['actor'])) {
636 $actor = $object['actor'];
637 } elseif (!empty($object['attributedTo'])) {
638 $actor = $object['attributedTo'];
644 if (!empty($object['published'])) {
645 $published = $object['published'];
646 } elseif (!empty($child['published'])) {
647 $published = $child['published'];
649 $published = DateTimeFormat::utcNow();
653 $activity['@context'] = $object['@context'];
654 unset($object['@context']);
655 $activity['id'] = $object['id'];
656 $activity['to'] = $object['to'] ?? [];
657 $activity['cc'] = $object['cc'] ?? [];
658 $activity['actor'] = $actor;
659 $activity['object'] = $object;
660 $activity['published'] = $published;
661 $activity['type'] = 'Create';
663 $ldactivity = JsonLD::compact($activity);
665 $ldactivity['thread-completion'] = true;
667 ActivityPub\Receiver::processActivity($ldactivity);
668 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'object' => $activity['id']]);
670 return $activity['id'];
674 * perform a "follow" request
676 * @param array $activity
677 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
678 * @throws \ImagickException
680 public static function followUser($activity)
682 $uid = User::getIdForURL($activity['object_id']);
687 $owner = User::getOwnerDataById($uid);
689 $cid = Contact::getIdForURL($activity['actor'], $uid);
691 self::switchContact($cid);
692 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
693 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
698 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
699 'author-link' => $activity['actor']];
701 $note = Strings::escapeTags(trim($activity['content'] ?? ''));
703 // Ensure that the contact has got the right network type
704 self::switchContact($item['author-id']);
706 $result = Contact::addRelationship($owner, $contact, $item, false, $note);
707 if ($result === true) {
708 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $item['author-id'], $owner['uid']);
711 $cid = Contact::getIdForURL($activity['actor'], $uid);
716 if (empty($contact)) {
717 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
720 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
724 * Update the given profile
726 * @param array $activity
729 public static function updatePerson($activity)
731 if (empty($activity['object_id'])) {
735 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
736 Contact::updateFromProbeByURL($activity['object_id'], true);
740 * Delete the given profile
742 * @param array $activity
743 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
745 public static function deletePerson($activity)
747 if (empty($activity['object_id']) || empty($activity['actor'])) {
748 Logger::log('Empty object id or actor.', Logger::DEBUG);
752 if ($activity['object_id'] != $activity['actor']) {
753 Logger::log('Object id does not match actor.', Logger::DEBUG);
757 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
758 while ($contact = DBA::fetch($contacts)) {
759 Contact::remove($contact['id']);
761 DBA::close($contacts);
763 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
767 * Accept a follow request
769 * @param array $activity
770 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
771 * @throws \ImagickException
773 public static function acceptFollowUser($activity)
775 $uid = User::getIdForURL($activity['object_actor']);
780 $cid = Contact::getIdForURL($activity['actor'], $uid);
782 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
786 self::switchContact($cid);
788 $fields = ['pending' => false];
790 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
791 if ($contact['rel'] == Contact::FOLLOWER) {
792 $fields['rel'] = Contact::FRIEND;
795 $condition = ['id' => $cid];
796 DBA::update('contact', $fields, $condition);
797 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
801 * Reject a follow request
803 * @param array $activity
804 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
805 * @throws \ImagickException
807 public static function rejectFollowUser($activity)
809 $uid = User::getIdForURL($activity['object_actor']);
814 $cid = Contact::getIdForURL($activity['actor'], $uid);
816 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
820 self::switchContact($cid);
822 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
823 Contact::remove($cid);
824 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
826 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
831 * Undo activity like "like" or "dislike"
833 * @param array $activity
834 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
835 * @throws \ImagickException
837 public static function undoActivity($activity)
839 if (empty($activity['object_id'])) {
843 if (empty($activity['object_actor'])) {
847 $author_id = Contact::getIdForURL($activity['object_actor']);
848 if (empty($author_id)) {
852 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
856 * Activity to remove a follower
858 * @param array $activity
859 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
860 * @throws \ImagickException
862 public static function undoFollowUser($activity)
864 $uid = User::getIdForURL($activity['object_object']);
869 $owner = User::getOwnerDataById($uid);
871 $cid = Contact::getIdForURL($activity['actor'], $uid);
873 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
877 self::switchContact($cid);
879 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
880 if (!DBA::isResult($contact)) {
884 Contact::removeFollower($owner, $contact);
885 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
889 * Switches a contact to AP if needed
891 * @param integer $cid Contact ID
894 private static function switchContact($cid)
896 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
897 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
901 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
902 Contact::updateFromProbe($cid);
906 * Collects implicit mentions like:
907 * - the author of the parent item
908 * - all the mentioned conversants in the parent item
910 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
912 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
914 private static function getImplicitMentionList(array $parent)
916 if (DI::config()->get('system', 'disable_implicit_mentions')) {
920 $parent_terms = Term::tagArrayFromItemId($parent['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
922 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
924 $implicit_mentions = [];
925 if (empty($parent_author)) {
926 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
928 $implicit_mentions[] = $parent_author['url'];
929 $implicit_mentions[] = $parent_author['nurl'];
930 $implicit_mentions[] = $parent_author['alias'];
933 if (!empty($parent['alias'])) {
934 $implicit_mentions[] = $parent['alias'];
937 foreach ($parent_terms as $term) {
938 $contact = Contact::getDetailsByURL($term['url'], 0);
939 if (!empty($contact)) {
940 $implicit_mentions[] = $contact['url'];
941 $implicit_mentions[] = $contact['nurl'];
942 $implicit_mentions[] = $contact['alias'];
946 return $implicit_mentions;
950 * Strips from the body prepended implicit mentions
952 * @param string $body
953 * @param array $potential_mentions
956 private static function removeImplicitMentionsFromBody($body, array $potential_mentions)
958 if (DI::config()->get('system', 'disable_implicit_mentions')) {
964 // Extract one prepended mention at a time from the body
965 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
966 if (!in_array($matches[2], $potential_mentions)) {
967 $kept_mentions[] = $matches[1];
973 // Re-appending the kept mentions to the body after extraction
974 $kept_mentions[] = $body;
976 return implode('', $kept_mentions);
979 private static function convertImplicitMentionsInTags($activity_tags, array $potential_mentions)
981 if (DI::config()->get('system', 'disable_implicit_mentions')) {
982 return $activity_tags;
985 foreach ($activity_tags as $index => $tag) {
986 if (in_array($tag['href'], $potential_mentions)) {
987 $activity_tags[$index]['name'] = preg_replace(
988 '/' . preg_quote(Term::TAG_CHARACTER[Term::MENTION], '/') . '/',
989 Term::TAG_CHARACTER[Term::IMPLICIT_MENTION],
990 $activity_tags[$index]['name'],
996 return $activity_tags;