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);
451 if (!empty($activity['raw']) && isset($activity['protocol'])) {
452 $item['source'] = $activity['raw'];
453 $item['protocol'] = $activity['protocol'];
458 if (!empty($activity['thread-completion'])) {
459 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
460 $item['causer-link'] = $item['owner-link'];
461 $item['causer-id'] = $item['owner-id'];
463 Logger::info('Ignoring actor because of thread completion.', ['actor' => $item['owner-link']]);
464 $item['owner-link'] = $item['author-link'];
465 $item['owner-id'] = $item['author-id'];
467 $actor = APContact::getByURL($item['owner-link'], false);
468 $isForum = ($actor['type'] == 'Group');
471 $item['uri'] = $activity['id'];
473 $item['created'] = DateTimeFormat::utc($activity['published']);
474 $item['edited'] = DateTimeFormat::utc($activity['updated']);
475 $item['guid'] = $activity['diaspora:guid'] ?: self::getGUIDByURL($item['uri']);
477 $item = self::processContent($activity, $item);
482 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
484 $item = self::constructAttachList($activity, $item);
488 foreach ($activity['receiver'] as $receiver) {
489 $item['uid'] = $receiver;
492 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver, true);
494 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
497 if (($receiver != 0) && empty($item['contact-id'])) {
498 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
501 if (!empty($activity['directmessage'])) {
502 self::postMail($activity, $item);
506 if (DI::pConfig()->get($receiver, 'system', 'accept_only_sharer', false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
507 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
509 if ($skip && (($activity['type'] == 'as:Announce') || $isForum)) {
510 $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
514 Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
518 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
521 if ($activity['object_type'] == 'as:Event') {
522 self::createEvent($activity, $item);
525 $item_id = Item::insert($item);
527 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
529 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
532 if ($item['uid'] == 0) {
537 // Store send a follow request for every reshare - but only when the item had been stored
538 if ($stored && !$item['private'] && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
539 $author = APContact::getByURL($item['owner-link'], false);
540 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
541 if ($author['type'] != 'Group') {
542 Logger::log('Send follow request for ' . $item['uri'] . ' (' . $stored . ') to ' . $item['author-link'], Logger::DEBUG);
543 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
549 * Creates an mail post
551 * @param array $activity Activity data
552 * @param array $item item array
553 * @return int|bool New mail table row id or false on error
554 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
556 private static function postMail($activity, $item)
558 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
559 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
563 Logger::info('Direct Message', $item);
566 $msg['uid'] = $item['uid'];
568 $msg['contact-id'] = $item['contact-id'];
570 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
571 $msg['from-name'] = $contact['name'];
572 $msg['from-url'] = $contact['url'];
573 $msg['from-photo'] = $contact['photo'];
575 $msg['uri'] = $item['uri'];
576 $msg['created'] = $item['created'];
578 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
579 if (DBA::isResult($parent)) {
580 $msg['parent-uri'] = $parent['parent-uri'];
581 $msg['title'] = $parent['title'];
583 $msg['parent-uri'] = $item['thr-parent'];
585 if (!empty($item['title'])) {
586 $msg['title'] = $item['title'];
587 } elseif (!empty($item['content-warning'])) {
588 $msg['title'] = $item['content-warning'];
590 // Trying to generate a title out of the body
591 $title = $item['body'];
593 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
594 $title = $matches[3];
597 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, 2, true), 0));
599 if (strlen($title) > 20) {
600 $title = substr($title, 0, 20) . '...';
603 $msg['title'] = $title;
606 $msg['body'] = $item['body'];
608 return Mail::insert($msg);
612 * Fetches missing posts
614 * @param string $url message URL
615 * @param array $child activity array with the child of this message
616 * @return string fetched message URL
617 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
619 public static function fetchMissingActivity($url, $child = [])
621 if (!empty($child['receiver'])) {
622 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
627 $object = ActivityPub::fetchContent($url, $uid);
628 if (empty($object)) {
629 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
633 if (empty($object['id'])) {
634 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
638 if (!empty($child['author'])) {
639 $actor = $child['author'];
640 } elseif (!empty($object['actor'])) {
641 $actor = $object['actor'];
642 } elseif (!empty($object['attributedTo'])) {
643 $actor = $object['attributedTo'];
649 if (!empty($object['published'])) {
650 $published = $object['published'];
651 } elseif (!empty($child['published'])) {
652 $published = $child['published'];
654 $published = DateTimeFormat::utcNow();
658 $activity['@context'] = $object['@context'];
659 unset($object['@context']);
660 $activity['id'] = $object['id'];
661 $activity['to'] = $object['to'] ?? [];
662 $activity['cc'] = $object['cc'] ?? [];
663 $activity['actor'] = $actor;
664 $activity['object'] = $object;
665 $activity['published'] = $published;
666 $activity['type'] = 'Create';
668 $ldactivity = JsonLD::compact($activity);
670 $ldactivity['thread-completion'] = true;
672 ActivityPub\Receiver::processActivity($ldactivity);
673 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'object' => $activity['id']]);
675 return $activity['id'];
679 * perform a "follow" request
681 * @param array $activity
682 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
683 * @throws \ImagickException
685 public static function followUser($activity)
687 $uid = User::getIdForURL($activity['object_id']);
692 $owner = User::getOwnerDataById($uid);
694 $cid = Contact::getIdForURL($activity['actor'], $uid);
696 self::switchContact($cid);
697 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
698 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
703 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
704 'author-link' => $activity['actor']];
706 $note = Strings::escapeTags(trim($activity['content'] ?? ''));
708 // Ensure that the contact has got the right network type
709 self::switchContact($item['author-id']);
711 $result = Contact::addRelationship($owner, $contact, $item, false, $note);
712 if ($result === true) {
713 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $item['author-id'], $owner['uid']);
716 $cid = Contact::getIdForURL($activity['actor'], $uid);
721 if (empty($contact)) {
722 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
725 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
729 * Update the given profile
731 * @param array $activity
734 public static function updatePerson($activity)
736 if (empty($activity['object_id'])) {
740 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
741 Contact::updateFromProbeByURL($activity['object_id'], true);
745 * Delete the given profile
747 * @param array $activity
748 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
750 public static function deletePerson($activity)
752 if (empty($activity['object_id']) || empty($activity['actor'])) {
753 Logger::log('Empty object id or actor.', Logger::DEBUG);
757 if ($activity['object_id'] != $activity['actor']) {
758 Logger::log('Object id does not match actor.', Logger::DEBUG);
762 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
763 while ($contact = DBA::fetch($contacts)) {
764 Contact::remove($contact['id']);
766 DBA::close($contacts);
768 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
772 * Accept a follow request
774 * @param array $activity
775 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
776 * @throws \ImagickException
778 public static function acceptFollowUser($activity)
780 $uid = User::getIdForURL($activity['object_actor']);
785 $cid = Contact::getIdForURL($activity['actor'], $uid);
787 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
791 self::switchContact($cid);
793 $fields = ['pending' => false];
795 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
796 if ($contact['rel'] == Contact::FOLLOWER) {
797 $fields['rel'] = Contact::FRIEND;
800 $condition = ['id' => $cid];
801 DBA::update('contact', $fields, $condition);
802 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
806 * Reject a follow request
808 * @param array $activity
809 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
810 * @throws \ImagickException
812 public static function rejectFollowUser($activity)
814 $uid = User::getIdForURL($activity['object_actor']);
819 $cid = Contact::getIdForURL($activity['actor'], $uid);
821 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
825 self::switchContact($cid);
827 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
828 Contact::remove($cid);
829 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
831 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
836 * Undo activity like "like" or "dislike"
838 * @param array $activity
839 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
840 * @throws \ImagickException
842 public static function undoActivity($activity)
844 if (empty($activity['object_id'])) {
848 if (empty($activity['object_actor'])) {
852 $author_id = Contact::getIdForURL($activity['object_actor']);
853 if (empty($author_id)) {
857 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
861 * Activity to remove a follower
863 * @param array $activity
864 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
865 * @throws \ImagickException
867 public static function undoFollowUser($activity)
869 $uid = User::getIdForURL($activity['object_object']);
874 $owner = User::getOwnerDataById($uid);
876 $cid = Contact::getIdForURL($activity['actor'], $uid);
878 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
882 self::switchContact($cid);
884 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
885 if (!DBA::isResult($contact)) {
889 Contact::removeFollower($owner, $contact);
890 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
894 * Switches a contact to AP if needed
896 * @param integer $cid Contact ID
899 private static function switchContact($cid)
901 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
902 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
906 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
907 Contact::updateFromProbe($cid);
911 * Collects implicit mentions like:
912 * - the author of the parent item
913 * - all the mentioned conversants in the parent item
915 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
917 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
919 private static function getImplicitMentionList(array $parent)
921 if (DI::config()->get('system', 'disable_implicit_mentions')) {
925 $parent_terms = Term::tagArrayFromItemId($parent['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
927 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
929 $implicit_mentions = [];
930 if (empty($parent_author)) {
931 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
933 $implicit_mentions[] = $parent_author['url'];
934 $implicit_mentions[] = $parent_author['nurl'];
935 $implicit_mentions[] = $parent_author['alias'];
938 if (!empty($parent['alias'])) {
939 $implicit_mentions[] = $parent['alias'];
942 foreach ($parent_terms as $term) {
943 $contact = Contact::getDetailsByURL($term['url'], 0);
944 if (!empty($contact)) {
945 $implicit_mentions[] = $contact['url'];
946 $implicit_mentions[] = $contact['nurl'];
947 $implicit_mentions[] = $contact['alias'];
951 return $implicit_mentions;
955 * Strips from the body prepended implicit mentions
957 * @param string $body
958 * @param array $potential_mentions
961 private static function removeImplicitMentionsFromBody($body, array $potential_mentions)
963 if (DI::config()->get('system', 'disable_implicit_mentions')) {
969 // Extract one prepended mention at a time from the body
970 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
971 if (!in_array($matches[2], $potential_mentions)) {
972 $kept_mentions[] = $matches[1];
978 // Re-appending the kept mentions to the body after extraction
979 $kept_mentions[] = $body;
981 return implode('', $kept_mentions);
984 private static function convertImplicitMentionsInTags($activity_tags, array $potential_mentions)
986 if (DI::config()->get('system', 'disable_implicit_mentions')) {
987 return $activity_tags;
990 foreach ($activity_tags as $index => $tag) {
991 if (in_array($tag['href'], $potential_mentions)) {
992 $activity_tags[$index]['name'] = preg_replace(
993 '/' . preg_quote(Term::TAG_CHARACTER[Term::MENTION], '/') . '/',
994 Term::TAG_CHARACTER[Term::IMPLICIT_MENTION],
995 $activity_tags[$index]['name'],
1001 return $activity_tags;