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\Mail;
36 use Friendica\Model\Term;
37 use Friendica\Model\User;
38 use Friendica\Protocol\Activity;
39 use Friendica\Protocol\ActivityPub;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\JsonLD;
42 use Friendica\Util\Strings;
45 * ActivityPub Processor Protocol class
50 * Converts mentions from Pleroma into the Friendica format
54 * @return string converted body
56 private static function convertMentions($body)
58 $URLSearchString = "^\[\]";
59 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
65 * Replaces emojis in the body
67 * @param array $emojis
70 * @return string with replaced emojis
72 private static function replaceEmojis($body, array $emojis)
74 foreach ($emojis as $emoji) {
75 $replace = '[class=emoji mastodon][img=' . $emoji['href'] . ']' . $emoji['name'] . '[/img][/class]';
76 $body = str_replace($emoji['name'], $replace, $body);
82 * Constructs a string with tags for a given tag array
85 * @param boolean $sensitive
86 * @return string with tags
88 private static function constructTagString(array $tags = null, $sensitive = false)
95 foreach ($tags as $tag) {
96 if (in_array($tag['type'] ?? '', ['Mention', 'Hashtag'])) {
97 if (!empty($tag_text)) {
101 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
105 /// @todo add nsfw for $sensitive
111 * Add attachment data to the item array
113 * @param array $activity
116 * @return array array
118 private static function constructAttachList($activity, $item)
120 if (empty($activity['attachments'])) {
124 foreach ($activity['attachments'] as $attach) {
125 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
126 if ($filetype == 'image') {
127 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
131 if (empty($attach['name'])) {
132 $item['body'] .= "\n[img]" . $attach['url'] . '[/img]';
134 $item['body'] .= "\n[img=" . $attach['url'] . ']' . $attach['name'] . '[/img]';
137 if (!empty($item["attach"])) {
138 $item["attach"] .= ',';
140 $item["attach"] = '';
142 if (!isset($attach['length'])) {
143 $attach['length'] = "0";
145 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.($attach['name'] ?? '') .'"[/attach]';
155 * @param array $activity Activity array
156 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
158 public static function updateItem($activity)
160 $item = Item::selectFirst(['uri', 'thr-parent', 'gravity'], ['uri' => $activity['id']]);
161 if (!DBA::isResult($item)) {
162 Logger::warning('Unknown item', ['uri' => $activity['id']]);
166 $item['changed'] = DateTimeFormat::utcNow();
167 $item['edited'] = DateTimeFormat::utc($activity['updated']);
169 $item = self::processContent($activity, $item);
174 Item::update($item, ['uri' => $activity['id']]);
178 * Prepares data for a message
180 * @param array $activity Activity array
181 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
182 * @throws \ImagickException
184 public static function createItem($activity)
187 $item['verb'] = Activity::POST;
188 $item['thr-parent'] = $activity['reply-to-id'];
190 if ($activity['reply-to-id'] == $activity['id']) {
191 $item['gravity'] = GRAVITY_PARENT;
192 $item['object-type'] = Activity\ObjectType::NOTE;
194 $item['gravity'] = GRAVITY_COMMENT;
195 $item['object-type'] = Activity\ObjectType::COMMENT;
197 // Ensure that the comment reaches all receivers of the referring post
198 $activity['receiver'] = self::addReceivers($activity);
201 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
202 Logger::notice('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id']]);
203 self::fetchMissingActivity($activity['reply-to-id'], $activity);
206 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
208 self::postItem($activity, $item);
214 * @param array $activity
215 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
216 * @throws \ImagickException
218 public static function deleteItem($activity)
220 $owner = Contact::getIdForURL($activity['actor']);
222 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
223 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
227 * Prepare the item array for an activity
229 * @param array $activity Activity array
230 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
231 * @throws \ImagickException
233 public static function addTag($activity)
235 if (empty($activity['object_content']) || empty($activity['object_id'])) {
239 foreach ($activity['receiver'] as $receiver) {
240 $item = Item::selectFirst(['id', 'tag', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
241 if (!DBA::isResult($item)) {
242 // We don't fetch missing content for this purpose
246 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
247 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
252 // - Check if "blocktag" is set
253 // - Check if actor is a contact
255 if (!stristr($item['tag'], trim($activity['object_content']))) {
256 $tag = $item['tag'] . (strlen($item['tag']) ? ',' : '') . '#[url=' . $activity['object_id'] . ']'. $activity['object_content'] . '[/url]';
257 Item::update(['tag' => $tag], ['id' => $item['id']]);
258 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
264 * Add users to the receiver list of the given public activity.
265 * This is used to ensure that the activity will be stored in every thread.
267 * @param array $activity Activity array
268 * @return array Modified receiver list
270 private static function addReceivers(array $activity)
272 if (!in_array(0, $activity['receiver'])) {
273 // Private activities will not be modified
274 return $activity['receiver'];
277 // Add all owners of the referring item to the receivers
278 $original = $receivers = $activity['receiver'];
279 $items = Item::select(['uid'], ['uri' => $activity['object_id']]);
280 while ($item = DBA::fetch($items)) {
281 $receivers['uid:' . $item['uid']] = $item['uid'];
285 if (count($original) != count($receivers)) {
286 Logger::info('Improved data', ['id' => $activity['id'], 'object' => $activity['object_id'], 'original' => $original, 'improved' => $receivers]);
293 * Prepare the item array for an activity
295 * @param array $activity Activity array
296 * @param string $verb Activity verb
297 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
298 * @throws \ImagickException
300 public static function createActivity($activity, $verb)
303 $item['verb'] = $verb;
304 $item['thr-parent'] = $activity['object_id'];
305 $item['gravity'] = GRAVITY_ACTIVITY;
306 $item['object-type'] = Activity\ObjectType::NOTE;
308 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
310 $activity['receiver'] = self::addReceivers($activity);
312 self::postItem($activity, $item);
318 * @param array $activity Activity array
322 public static function createEvent($activity, $item)
324 $event['summary'] = HTML::toBBCode($activity['name']);
325 $event['desc'] = HTML::toBBCode($activity['content']);
326 $event['start'] = $activity['start-time'];
327 $event['finish'] = $activity['end-time'];
328 $event['nofinish'] = empty($event['finish']);
329 $event['location'] = $activity['location'];
330 $event['adjust'] = true;
331 $event['cid'] = $item['contact-id'];
332 $event['uid'] = $item['uid'];
333 $event['uri'] = $item['uri'];
334 $event['edited'] = $item['edited'];
335 $event['private'] = $item['private'];
336 $event['guid'] = $item['guid'];
337 $event['plink'] = $item['plink'];
339 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
340 $ev = DBA::selectFirst('event', ['id'], $condition);
341 if (DBA::isResult($ev)) {
342 $event['id'] = $ev['id'];
345 $event_id = Event::store($event);
346 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
350 * Process the content
352 * @param array $activity Activity array
354 * @return array|bool Returns the item array or false if there was an unexpected occurrence
357 private static function processContent($activity, $item)
359 $item['title'] = HTML::toBBCode($activity['name']);
361 if (!empty($activity['source'])) {
362 $item['body'] = $activity['source'];
364 $content = HTML::toBBCode($activity['content']);
366 if (!empty($activity['emojis'])) {
367 $content = self::replaceEmojis($content, $activity['emojis']);
370 $content = self::convertMentions($content);
372 if (empty($activity['directmessage']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
373 $item_private = !in_array(0, $activity['item_receiver']);
374 $parent = Item::selectFirst(['id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
375 if (!DBA::isResult($parent)) {
376 Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
379 if ($item_private && ($parent['private'] == Item::PRIVATE)) {
380 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
384 $potential_implicit_mentions = self::getImplicitMentionList($parent);
385 $content = self::removeImplicitMentionsFromBody($content, $potential_implicit_mentions);
386 $activity['tags'] = self::convertImplicitMentionsInTags($activity['tags'], $potential_implicit_mentions);
388 $item['content-warning'] = HTML::toBBCode($activity['summary']);
389 $item['body'] = $content;
391 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
392 $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
396 $item['tag'] = self::constructTagString($activity['tags'], $activity['sensitive']);
398 $item['location'] = $activity['location'];
400 if (!empty($item['latitude']) && !empty($item['longitude'])) {
401 $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
404 $item['app'] = $activity['generator'];
410 * Generate a GUID out of an URL
412 * @param string $url message URL
413 * @return string with GUID
415 private static function getGUIDByURL(string $url)
417 $parsed = parse_url($url);
419 $host_hash = hash('crc32', $parsed['host']);
421 unset($parsed["scheme"]);
422 unset($parsed["host"]);
424 $path = implode("/", $parsed);
426 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
430 * Creates an item post
432 * @param array $activity Activity data
433 * @param array $item item array
434 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
435 * @throws \ImagickException
437 private static function postItem($activity, $item)
439 /// @todo What to do with $activity['context']?
440 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['thr-parent']])) {
441 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
445 $item['network'] = Protocol::ACTIVITYPUB;
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);
451 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
452 $item['private'] = Item::UNLISTED;
453 } elseif (in_array(0, $activity['receiver'])) {
454 $item['private'] = Item::PUBLIC;
456 $item['private'] = Item::PRIVATE;
459 if (!empty($activity['raw'])) {
460 $item['source'] = $activity['raw'];
461 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
462 $item['conversation-href'] = $activity['context'] ?? '';
463 $item['conversation-uri'] = $activity['conversation'] ?? '';
465 if (isset($activity['push'])) {
466 $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
472 if (!empty($activity['thread-completion'])) {
473 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
474 $item['causer-link'] = $item['owner-link'];
475 $item['causer-id'] = $item['owner-id'];
477 Logger::info('Ignoring actor because of thread completion.', ['actor' => $item['owner-link']]);
478 $item['owner-link'] = $item['author-link'];
479 $item['owner-id'] = $item['author-id'];
481 $actor = APContact::getByURL($item['owner-link'], false);
482 $isForum = ($actor['type'] == 'Group');
485 $item['uri'] = $activity['id'];
487 $item['created'] = DateTimeFormat::utc($activity['published']);
488 $item['edited'] = DateTimeFormat::utc($activity['updated']);
489 $item['guid'] = $activity['diaspora:guid'] ?: self::getGUIDByURL($item['uri']);
491 $item = self::processContent($activity, $item);
496 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
498 $item = self::constructAttachList($activity, $item);
502 foreach ($activity['receiver'] as $receiver) {
503 if ($receiver == -1) {
507 $item['uid'] = $receiver;
510 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver, true);
512 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
515 if (($receiver != 0) && empty($item['contact-id'])) {
516 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
519 if (!empty($activity['directmessage'])) {
520 self::postMail($activity, $item);
524 if (DI::pConfig()->get($receiver, 'system', 'accept_only_sharer', false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
525 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
527 if ($skip && (($activity['type'] == 'as:Announce') || $isForum)) {
528 $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
532 Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
536 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
539 if ($activity['object_type'] == 'as:Event') {
540 self::createEvent($activity, $item);
543 $item_id = Item::insert($item);
545 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
547 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
550 if ($item['uid'] == 0) {
555 // Store send a follow request for every reshare - but only when the item had been stored
556 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
557 $author = APContact::getByURL($item['owner-link'], false);
558 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
559 if ($author['type'] != 'Group') {
560 Logger::log('Send follow request for ' . $item['uri'] . ' (' . $stored . ') to ' . $item['author-link'], Logger::DEBUG);
561 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
567 * Creates an mail post
569 * @param array $activity Activity data
570 * @param array $item item array
571 * @return int|bool New mail table row id or false on error
572 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
574 private static function postMail($activity, $item)
576 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
577 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
581 Logger::info('Direct Message', $item);
584 $msg['uid'] = $item['uid'];
586 $msg['contact-id'] = $item['contact-id'];
588 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
589 $msg['from-name'] = $contact['name'];
590 $msg['from-url'] = $contact['url'];
591 $msg['from-photo'] = $contact['photo'];
593 $msg['uri'] = $item['uri'];
594 $msg['created'] = $item['created'];
596 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
597 if (DBA::isResult($parent)) {
598 $msg['parent-uri'] = $parent['parent-uri'];
599 $msg['title'] = $parent['title'];
601 $msg['parent-uri'] = $item['thr-parent'];
603 if (!empty($item['title'])) {
604 $msg['title'] = $item['title'];
605 } elseif (!empty($item['content-warning'])) {
606 $msg['title'] = $item['content-warning'];
608 // Trying to generate a title out of the body
609 $title = $item['body'];
611 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
612 $title = $matches[3];
615 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, 2, true), 0));
617 if (strlen($title) > 20) {
618 $title = substr($title, 0, 20) . '...';
621 $msg['title'] = $title;
624 $msg['body'] = $item['body'];
626 return Mail::insert($msg);
630 * Fetches missing posts
632 * @param string $url message URL
633 * @param array $child activity array with the child of this message
634 * @return string fetched message URL
635 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
637 public static function fetchMissingActivity($url, $child = [])
639 if (!empty($child['receiver'])) {
640 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
645 $object = ActivityPub::fetchContent($url, $uid);
646 if (empty($object)) {
647 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
651 if (empty($object['id'])) {
652 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
656 if (!empty($child['author'])) {
657 $actor = $child['author'];
658 } elseif (!empty($object['actor'])) {
659 $actor = $object['actor'];
660 } elseif (!empty($object['attributedTo'])) {
661 $actor = $object['attributedTo'];
667 if (!empty($object['published'])) {
668 $published = $object['published'];
669 } elseif (!empty($child['published'])) {
670 $published = $child['published'];
672 $published = DateTimeFormat::utcNow();
676 $activity['@context'] = $object['@context'];
677 unset($object['@context']);
678 $activity['id'] = $object['id'];
679 $activity['to'] = $object['to'] ?? [];
680 $activity['cc'] = $object['cc'] ?? [];
681 $activity['actor'] = $actor;
682 $activity['object'] = $object;
683 $activity['published'] = $published;
684 $activity['type'] = 'Create';
686 $ldactivity = JsonLD::compact($activity);
688 $ldactivity['thread-completion'] = true;
690 ActivityPub\Receiver::processActivity($ldactivity);
691 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'object' => $activity['id']]);
693 return $activity['id'];
697 * perform a "follow" request
699 * @param array $activity
700 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
701 * @throws \ImagickException
703 public static function followUser($activity)
705 $uid = User::getIdForURL($activity['object_id']);
710 $owner = User::getOwnerDataById($uid);
712 $cid = Contact::getIdForURL($activity['actor'], $uid);
714 self::switchContact($cid);
715 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
716 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
721 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
722 'author-link' => $activity['actor']];
724 $note = Strings::escapeTags(trim($activity['content'] ?? ''));
726 // Ensure that the contact has got the right network type
727 self::switchContact($item['author-id']);
729 $result = Contact::addRelationship($owner, $contact, $item, false, $note);
730 if ($result === true) {
731 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $item['author-id'], $owner['uid']);
734 $cid = Contact::getIdForURL($activity['actor'], $uid);
739 if (empty($contact)) {
740 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
743 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
747 * Update the given profile
749 * @param array $activity
752 public static function updatePerson($activity)
754 if (empty($activity['object_id'])) {
758 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
759 Contact::updateFromProbeByURL($activity['object_id'], true);
763 * Delete the given profile
765 * @param array $activity
766 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
768 public static function deletePerson($activity)
770 if (empty($activity['object_id']) || empty($activity['actor'])) {
771 Logger::log('Empty object id or actor.', Logger::DEBUG);
775 if ($activity['object_id'] != $activity['actor']) {
776 Logger::log('Object id does not match actor.', Logger::DEBUG);
780 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
781 while ($contact = DBA::fetch($contacts)) {
782 Contact::remove($contact['id']);
784 DBA::close($contacts);
786 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
790 * Accept a follow request
792 * @param array $activity
793 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
794 * @throws \ImagickException
796 public static function acceptFollowUser($activity)
798 $uid = User::getIdForURL($activity['object_actor']);
803 $cid = Contact::getIdForURL($activity['actor'], $uid);
805 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
809 self::switchContact($cid);
811 $fields = ['pending' => false];
813 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
814 if ($contact['rel'] == Contact::FOLLOWER) {
815 $fields['rel'] = Contact::FRIEND;
818 $condition = ['id' => $cid];
819 DBA::update('contact', $fields, $condition);
820 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
824 * Reject a follow request
826 * @param array $activity
827 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
828 * @throws \ImagickException
830 public static function rejectFollowUser($activity)
832 $uid = User::getIdForURL($activity['object_actor']);
837 $cid = Contact::getIdForURL($activity['actor'], $uid);
839 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
843 self::switchContact($cid);
845 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
846 Contact::remove($cid);
847 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
849 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
854 * Undo activity like "like" or "dislike"
856 * @param array $activity
857 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
858 * @throws \ImagickException
860 public static function undoActivity($activity)
862 if (empty($activity['object_id'])) {
866 if (empty($activity['object_actor'])) {
870 $author_id = Contact::getIdForURL($activity['object_actor']);
871 if (empty($author_id)) {
875 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
879 * Activity to remove a follower
881 * @param array $activity
882 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
883 * @throws \ImagickException
885 public static function undoFollowUser($activity)
887 $uid = User::getIdForURL($activity['object_object']);
892 $owner = User::getOwnerDataById($uid);
894 $cid = Contact::getIdForURL($activity['actor'], $uid);
896 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
900 self::switchContact($cid);
902 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
903 if (!DBA::isResult($contact)) {
907 Contact::removeFollower($owner, $contact);
908 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
912 * Switches a contact to AP if needed
914 * @param integer $cid Contact ID
917 private static function switchContact($cid)
919 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
920 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
924 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
925 Contact::updateFromProbe($cid);
929 * Collects implicit mentions like:
930 * - the author of the parent item
931 * - all the mentioned conversants in the parent item
933 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
935 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
937 private static function getImplicitMentionList(array $parent)
939 if (DI::config()->get('system', 'disable_implicit_mentions')) {
943 $parent_terms = Term::tagArrayFromItemId($parent['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
945 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
947 $implicit_mentions = [];
948 if (empty($parent_author)) {
949 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
951 $implicit_mentions[] = $parent_author['url'];
952 $implicit_mentions[] = $parent_author['nurl'];
953 $implicit_mentions[] = $parent_author['alias'];
956 if (!empty($parent['alias'])) {
957 $implicit_mentions[] = $parent['alias'];
960 foreach ($parent_terms as $term) {
961 $contact = Contact::getDetailsByURL($term['url'], 0);
962 if (!empty($contact)) {
963 $implicit_mentions[] = $contact['url'];
964 $implicit_mentions[] = $contact['nurl'];
965 $implicit_mentions[] = $contact['alias'];
969 return $implicit_mentions;
973 * Strips from the body prepended implicit mentions
975 * @param string $body
976 * @param array $potential_mentions
979 private static function removeImplicitMentionsFromBody($body, array $potential_mentions)
981 if (DI::config()->get('system', 'disable_implicit_mentions')) {
987 // Extract one prepended mention at a time from the body
988 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
989 if (!in_array($matches[2], $potential_mentions)) {
990 $kept_mentions[] = $matches[1];
996 // Re-appending the kept mentions to the body after extraction
997 $kept_mentions[] = $body;
999 return implode('', $kept_mentions);
1002 private static function convertImplicitMentionsInTags($activity_tags, array $potential_mentions)
1004 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1005 return $activity_tags;
1008 foreach ($activity_tags as $index => $tag) {
1009 if (in_array($tag['href'], $potential_mentions)) {
1010 $activity_tags[$index]['name'] = preg_replace(
1011 '/' . preg_quote(Term::TAG_CHARACTER[Term::MENTION], '/') . '/',
1012 Term::TAG_CHARACTER[Term::IMPLICIT_MENTION],
1013 $activity_tags[$index]['name'],
1019 return $activity_tags;