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