]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Processor.php
Merge pull request #6183 from MrPetovan/bug/6135-hide-follower-only-birthdays
[friendica.git] / src / Protocol / ActivityPub / Processor.php
1 <?php
2 /**
3  * @file src/Protocol/ActivityPub/Processor.php
4  */
5 namespace Friendica\Protocol\ActivityPub;
6
7 use Friendica\Database\DBA;
8 use Friendica\Content\Text\HTML;
9 use Friendica\Core\Config;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Protocol;
12 use Friendica\Model\Conversation;
13 use Friendica\Model\Contact;
14 use Friendica\Model\APContact;
15 use Friendica\Model\Item;
16 use Friendica\Model\Event;
17 use Friendica\Model\User;
18 use Friendica\Protocol\ActivityPub;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\JsonLD;
21 use Friendica\Util\Strings;
22
23 /**
24  * ActivityPub Processor Protocol class
25  */
26 class Processor
27 {
28         /**
29          * Converts mentions from Pleroma into the Friendica format
30          *
31          * @param string $body
32          *
33          * @return converted body
34          */
35         private static function convertMentions($body)
36         {
37                 $URLSearchString = "^\[\]";
38                 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
39
40                 return $body;
41         }
42
43         /**
44          * Replaces emojis in the body
45          *
46          * @param array $emojis
47          * @param string $body
48          *
49          * @return string with replaced emojis
50          */
51         public static function replaceEmojis($emojis, $body)
52         {
53                 foreach ($emojis as $emoji) {
54                         $replace = '[class=emoji mastodon][img=' . $emoji['href'] . ']' . $emoji['name'] . '[/img][/class]';
55                         $body = str_replace($emoji['name'], $replace, $body);
56                 }
57                 return $body;
58         }
59
60         /**
61          * Constructs a string with tags for a given tag array
62          *
63          * @param array $tags
64          * @param boolean $sensitive
65          *
66          * @return string with tags
67          */
68         private static function constructTagList($tags, $sensitive)
69         {
70                 if (empty($tags)) {
71                         return '';
72                 }
73
74                 $tag_text = '';
75                 foreach ($tags as $tag) {
76                         if (in_array(defaults($tag, 'type', ''), ['Mention', 'Hashtag'])) {
77                                 if (!empty($tag_text)) {
78                                         $tag_text .= ',';
79                                 }
80
81                                 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
82                         }
83                 }
84
85                 /// @todo add nsfw for $sensitive
86
87                 return $tag_text;
88         }
89
90         /**
91          * Add attachment data to the item array
92          *
93          * @param array $attachments
94          * @param array $item
95          *
96          * @return item array
97          */
98         private static function constructAttachList($attachments, $item)
99         {
100                 if (empty($attachments)) {
101                         return $item;
102                 }
103
104                 foreach ($attachments as $attach) {
105                         $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
106                         if ($filetype == 'image') {
107                                 $item['body'] .= "\n[img]" . $attach['url'] . '[/img]';
108                         } else {
109                                 if (!empty($item["attach"])) {
110                                         $item["attach"] .= ',';
111                                 } else {
112                                         $item["attach"] = '';
113                                 }
114                                 if (!isset($attach['length'])) {
115                                         $attach['length'] = "0";
116                                 }
117                                 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
118                         }
119                 }
120
121                 return $item;
122         }
123
124         /**
125          * Updates a message
126          *
127          * @param array  $activity Activity array
128          */
129         public static function updateItem($activity)
130         {
131                 $item = [];
132                 $item['changed'] = DateTimeFormat::utcNow();
133                 $item['edited'] = $activity['updated'];
134                 $item['title'] = HTML::toBBCode($activity['name']);
135                 $item['content-warning'] = HTML::toBBCode($activity['summary']);
136                 $content = self::replaceEmojis($activity['emojis'], HTML::toBBCode($activity['content']));
137                 $item['body'] = self::convertMentions($content);
138                 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
139
140                 Item::update($item, ['uri' => $activity['id']]);
141         }
142
143         /**
144          * Prepares data for a message
145          *
146          * @param array  $activity Activity array
147          */
148         public static function createItem($activity)
149         {
150                 $item = [];
151                 $item['verb'] = ACTIVITY_POST;
152                 $item['parent-uri'] = $activity['reply-to-id'];
153
154                 if ($activity['reply-to-id'] == $activity['id']) {
155                         $item['gravity'] = GRAVITY_PARENT;
156                         $item['object-type'] = ACTIVITY_OBJ_NOTE;
157                 } else {
158                         $item['gravity'] = GRAVITY_COMMENT;
159                         $item['object-type'] = ACTIVITY_OBJ_COMMENT;
160                 }
161
162                 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
163                         Logger::log('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
164                         self::fetchMissingActivity($activity['reply-to-id'], $activity);
165                 }
166
167                 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:comment', '');
168
169                 self::postItem($activity, $item);
170         }
171
172         /**
173          * Delete items
174          *
175          * @param array $activity
176          */
177         public static function deleteItem($activity)
178         {
179                 $owner = Contact::getIdForURL($activity['actor']);
180
181                 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
182                 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
183         }
184
185         /**
186          * Prepare the item array for an activity
187          *
188          * @param array  $activity Activity array
189          * @param string $verb     Activity verb
190          */
191         public static function createActivity($activity, $verb)
192         {
193                 $item = [];
194                 $item['verb'] = $verb;
195                 $item['parent-uri'] = $activity['object_id'];
196                 $item['gravity'] = GRAVITY_ACTIVITY;
197                 $item['object-type'] = ACTIVITY_OBJ_NOTE;
198
199                 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:like', '');
200
201                 self::postItem($activity, $item);
202         }
203
204         /**
205          * Create an event
206          *
207          * @param array $activity Activity array
208          * @param array $item
209          */
210         public static function createEvent($activity, $item)
211         {
212                 $event['summary'] = $activity['name'];
213                 $event['desc'] = $activity['content'];
214                 $event['start'] = $activity['start-time'];
215                 $event['finish'] = $activity['end-time'];
216                 $event['nofinish'] = empty($event['finish']);
217                 $event['location'] = $activity['location'];
218                 $event['adjust'] = true;
219                 $event['cid'] = $item['contact-id'];
220                 $event['uid'] = $item['uid'];
221                 $event['uri'] = $item['uri'];
222                 $event['edited'] = $item['edited'];
223                 $event['private'] = $item['private'];
224                 $event['guid'] = $item['guid'];
225                 $event['plink'] = $item['plink'];
226
227                 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
228                 $ev = DBA::selectFirst('event', ['id'], $condition);
229                 if (DBA::isResult($ev)) {
230                         $event['id'] = $ev['id'];
231                 }
232
233                 $event_id = Event::store($event);
234                 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
235         }
236
237         /**
238          * Creates an item post
239          *
240          * @param array  $activity Activity data
241          * @param array  $item     item array
242          */
243         private static function postItem($activity, $item)
244         {
245                 /// @todo What to do with $activity['context']?
246
247                 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
248                         Logger::log('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', Logger::DEBUG);
249                         return;
250                 }
251
252                 $item['network'] = Protocol::ACTIVITYPUB;
253                 $item['private'] = !in_array(0, $activity['receiver']);
254                 $item['author-link'] = $activity['author'];
255                 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
256
257                 if (empty($activity['thread-completion'])) {
258                         $item['owner-link'] = $activity['actor'];
259                         $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
260                 } else {
261                         Logger::log('Ignoring actor because of thread completion.', Logger::DEBUG);
262                         $item['owner-link'] = $item['author-link'];
263                         $item['owner-id'] = $item['author-id'];
264                 }
265
266                 $item['uri'] = $activity['id'];
267                 $item['created'] = $activity['published'];
268                 $item['edited'] = $activity['updated'];
269                 $item['guid'] = $activity['diaspora:guid'];
270                 $item['title'] = HTML::toBBCode($activity['name']);
271                 $item['content-warning'] = HTML::toBBCode($activity['summary']);
272                 $content = self::replaceEmojis($activity['emojis'], HTML::toBBCode($activity['content']));
273                 $item['body'] = self::convertMentions($content);
274
275                 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
276                         $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
277                 }
278
279                 $item['location'] = $activity['location'];
280
281                 if (!empty($item['latitude']) && !empty($item['longitude'])) {
282                         $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
283                 }
284
285                 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
286                 $item['app'] = $activity['generator'];
287                 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
288
289                 $item = self::constructAttachList($activity['attachments'], $item);
290
291                 if (!empty($activity['source'])) {
292                         $item['body'] = $activity['source'];
293                 }
294
295                 foreach ($activity['receiver'] as $receiver) {
296                         $item['uid'] = $receiver;
297                         $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
298
299                         if (($receiver != 0) && empty($item['contact-id'])) {
300                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
301                         }
302
303                         if ($activity['object_type'] == 'as:Event') {
304                                 self::createEvent($activity, $item);
305                         }
306
307                         $item_id = Item::insert($item);
308                         Logger::log('Storing for user ' . $item['uid'] . ': ' . $item_id);
309                 }
310         }
311
312         /**
313          * Fetches missing posts
314          *
315          * @param $url
316          * @param $child
317          */
318         private static function fetchMissingActivity($url, $child)
319         {
320                 if (Config::get('system', 'ostatus_full_threads')) {
321                         return;
322                 }
323
324                 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
325
326                 $object = ActivityPub::fetchContent($url, $uid);
327                 if (empty($object)) {
328                         Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
329                         return;
330                 }
331
332                 $activity = [];
333                 $activity['@context'] = $object['@context'];
334                 unset($object['@context']);
335                 $activity['id'] = $object['id'];
336                 $activity['to'] = defaults($object, 'to', []);
337                 $activity['cc'] = defaults($object, 'cc', []);
338                 $activity['actor'] = $child['author'];
339                 $activity['object'] = $object;
340                 $activity['published'] = defaults($object, 'published', $child['published']);
341                 $activity['type'] = 'Create';
342
343                 $ldactivity = JsonLD::compact($activity);
344
345                 $ldactivity['thread-completion'] = true;
346
347                 ActivityPub\Receiver::processActivity($ldactivity);
348                 Logger::log('Activity ' . $url . ' had been fetched and processed.');
349         }
350
351         /**
352          * perform a "follow" request
353          *
354          * @param array $activity
355          */
356         public static function followUser($activity)
357         {
358                 $uid = User::getIdForURL($activity['object_id']);
359                 if (empty($uid)) {
360                         return;
361                 }
362
363                 $owner = User::getOwnerDataById($uid);
364
365                 $cid = Contact::getIdForURL($activity['actor'], $uid);
366                 if (!empty($cid)) {
367                         self::switchContact($cid);
368                         $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
369                 } else {
370                         $contact = false;
371                 }
372
373                 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
374                         'author-link' => $activity['actor']];
375
376                 // Ensure that the contact has got the right network type
377                 self::switchContact($item['author-id']);
378
379                 Contact::addRelationship($owner, $contact, $item);
380                 $cid = Contact::getIdForURL($activity['actor'], $uid);
381                 if (empty($cid)) {
382                         return;
383                 }
384
385                 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
386                 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
387         }
388
389         /**
390          * Update the given profile
391          *
392          * @param array $activity
393          */
394         public static function updatePerson($activity)
395         {
396                 if (empty($activity['object_id'])) {
397                         return;
398                 }
399
400                 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
401                 APContact::getByURL($activity['object_id'], true);
402         }
403
404         /**
405          * Delete the given profile
406          *
407          * @param array $activity
408          */
409         public static function deletePerson($activity)
410         {
411                 if (empty($activity['object_id']) || empty($activity['actor'])) {
412                         Logger::log('Empty object id or actor.', Logger::DEBUG);
413                         return;
414                 }
415
416                 if ($activity['object_id'] != $activity['actor']) {
417                         Logger::log('Object id does not match actor.', Logger::DEBUG);
418                         return;
419                 }
420
421                 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
422                 while ($contact = DBA::fetch($contacts)) {
423                         Contact::remove($contact['id']);
424                 }
425                 DBA::close($contacts);
426
427                 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
428         }
429
430         /**
431          * Accept a follow request
432          *
433          * @param array $activity
434          */
435         public static function acceptFollowUser($activity)
436         {
437                 $uid = User::getIdForURL($activity['object_actor']);
438                 if (empty($uid)) {
439                         return;
440                 }
441
442                 $owner = User::getOwnerDataById($uid);
443
444                 $cid = Contact::getIdForURL($activity['actor'], $uid);
445                 if (empty($cid)) {
446                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
447                         return;
448                 }
449
450                 self::switchContact($cid);
451
452                 $fields = ['pending' => false];
453
454                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
455                 if ($contact['rel'] == Contact::FOLLOWER) {
456                         $fields['rel'] = Contact::FRIEND;
457                 }
458
459                 $condition = ['id' => $cid];
460                 DBA::update('contact', $fields, $condition);
461                 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
462         }
463
464         /**
465          * Reject a follow request
466          *
467          * @param array $activity
468          */
469         public static function rejectFollowUser($activity)
470         {
471                 $uid = User::getIdForURL($activity['object_actor']);
472                 if (empty($uid)) {
473                         return;
474                 }
475
476                 $owner = User::getOwnerDataById($uid);
477
478                 $cid = Contact::getIdForURL($activity['actor'], $uid);
479                 if (empty($cid)) {
480                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
481                         return;
482                 }
483
484                 self::switchContact($cid);
485
486                 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
487                         Contact::remove($cid);
488                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
489                 } else {
490                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
491                 }
492         }
493
494         /**
495          * Undo activity like "like" or "dislike"
496          *
497          * @param array $activity
498          */
499         public static function undoActivity($activity)
500         {
501                 if (empty($activity['object_id'])) {
502                         return;
503                 }
504
505                 if (empty($activity['object_actor'])) {
506                         return;
507                 }
508
509                 $author_id = Contact::getIdForURL($activity['object_actor']);
510                 if (empty($author_id)) {
511                         return;
512                 }
513
514                 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
515         }
516
517         /**
518          * Activity to remove a follower
519          *
520          * @param array $activity
521          */
522         public static function undoFollowUser($activity)
523         {
524                 $uid = User::getIdForURL($activity['object_object']);
525                 if (empty($uid)) {
526                         return;
527                 }
528
529                 $owner = User::getOwnerDataById($uid);
530
531                 $cid = Contact::getIdForURL($activity['actor'], $uid);
532                 if (empty($cid)) {
533                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
534                         return;
535                 }
536
537                 self::switchContact($cid);
538
539                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
540                 if (!DBA::isResult($contact)) {
541                         return;
542                 }
543
544                 Contact::removeFollower($owner, $contact);
545                 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
546         }
547
548         /**
549          * Switches a contact to AP if needed
550          *
551          * @param integer $cid Contact ID
552          */
553         private static function switchContact($cid)
554         {
555                 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
556                 if (!DBA::isResult($contact) || ($contact['network'] == Protocol::ACTIVITYPUB)) {
557                         return;
558                 }
559
560                 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
561                 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
562         }
563 }