]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Processor.php
Fix PHPDoc comments project-wide
[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 string 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 array 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          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
129          */
130         public static function updateItem($activity)
131         {
132                 $item = [];
133                 $item['changed'] = DateTimeFormat::utcNow();
134                 $item['edited'] = $activity['updated'];
135                 $item['title'] = HTML::toBBCode($activity['name']);
136                 $item['content-warning'] = HTML::toBBCode($activity['summary']);
137                 $content = self::replaceEmojis($activity['emojis'], HTML::toBBCode($activity['content']));
138                 $item['body'] = self::convertMentions($content);
139                 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
140
141                 Item::update($item, ['uri' => $activity['id']]);
142         }
143
144         /**
145          * Prepares data for a message
146          *
147          * @param array $activity Activity array
148          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
149          * @throws \ImagickException
150          */
151         public static function createItem($activity)
152         {
153                 $item = [];
154                 $item['verb'] = ACTIVITY_POST;
155                 $item['parent-uri'] = $activity['reply-to-id'];
156
157                 if ($activity['reply-to-id'] == $activity['id']) {
158                         $item['gravity'] = GRAVITY_PARENT;
159                         $item['object-type'] = ACTIVITY_OBJ_NOTE;
160                 } else {
161                         $item['gravity'] = GRAVITY_COMMENT;
162                         $item['object-type'] = ACTIVITY_OBJ_COMMENT;
163                 }
164
165                 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
166                         Logger::log('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
167                         self::fetchMissingActivity($activity['reply-to-id'], $activity);
168                 }
169
170                 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:comment', '');
171
172                 self::postItem($activity, $item);
173         }
174
175         /**
176          * Delete items
177          *
178          * @param array $activity
179          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
180          * @throws \ImagickException
181          */
182         public static function deleteItem($activity)
183         {
184                 $owner = Contact::getIdForURL($activity['actor']);
185
186                 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
187                 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
188         }
189
190         /**
191          * Prepare the item array for an activity
192          *
193          * @param array  $activity Activity array
194          * @param string $verb     Activity verb
195          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
196          * @throws \ImagickException
197          */
198         public static function createActivity($activity, $verb)
199         {
200                 $item = [];
201                 $item['verb'] = $verb;
202                 $item['parent-uri'] = $activity['object_id'];
203                 $item['gravity'] = GRAVITY_ACTIVITY;
204                 $item['object-type'] = ACTIVITY_OBJ_NOTE;
205
206                 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:like', '');
207
208                 self::postItem($activity, $item);
209         }
210
211         /**
212          * Create an event
213          *
214          * @param array $activity Activity array
215          * @param array $item
216          * @throws \Exception
217          */
218         public static function createEvent($activity, $item)
219         {
220                 $event['summary']  = HTML::toBBCode($activity['name']);
221                 $event['desc']     = HTML::toBBCode($activity['content']);
222                 $event['start']    = $activity['start-time'];
223                 $event['finish']   = $activity['end-time'];
224                 $event['nofinish'] = empty($event['finish']);
225                 $event['location'] = $activity['location'];
226                 $event['adjust']   = true;
227                 $event['cid']      = $item['contact-id'];
228                 $event['uid']      = $item['uid'];
229                 $event['uri']      = $item['uri'];
230                 $event['edited']   = $item['edited'];
231                 $event['private']  = $item['private'];
232                 $event['guid']     = $item['guid'];
233                 $event['plink']    = $item['plink'];
234
235                 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
236                 $ev = DBA::selectFirst('event', ['id'], $condition);
237                 if (DBA::isResult($ev)) {
238                         $event['id'] = $ev['id'];
239                 }
240
241                 $event_id = Event::store($event);
242                 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
243         }
244
245         /**
246          * Creates an item post
247          *
248          * @param array $activity Activity data
249          * @param array $item     item array
250          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
251          * @throws \ImagickException
252          */
253         private static function postItem($activity, $item)
254         {
255                 /// @todo What to do with $activity['context']?
256
257                 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
258                         Logger::log('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', Logger::DEBUG);
259                         return;
260                 }
261
262                 $item['network'] = Protocol::ACTIVITYPUB;
263                 $item['private'] = !in_array(0, $activity['receiver']);
264                 $item['author-link'] = $activity['author'];
265                 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
266
267                 if (empty($activity['thread-completion'])) {
268                         $item['owner-link'] = $activity['actor'];
269                         $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
270                 } else {
271                         Logger::log('Ignoring actor because of thread completion.', Logger::DEBUG);
272                         $item['owner-link'] = $item['author-link'];
273                         $item['owner-id'] = $item['author-id'];
274                 }
275
276                 $item['uri'] = $activity['id'];
277
278                 if (($item['parent-uri'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
279                         $item_private = !in_array(0, $activity['item_receiver']);
280                         $parent = Item::selectFirst(['private'], ['uri' => $item['parent-uri']]);
281                         if (!DBA::isResult($parent)) {
282                                 return;
283                         }
284                         if ($item_private && !$parent['private']) {
285                                 Logger::log('Item ' . $item['uri'] . ' is private but the parent ' . $item['parent-uri'] . ' is not. So we drop it.');
286                                 return;
287                         }
288                 }
289
290                 $item['created'] = $activity['published'];
291                 $item['edited'] = $activity['updated'];
292                 $item['guid'] = $activity['diaspora:guid'];
293                 $item['title'] = HTML::toBBCode($activity['name']);
294                 $item['content-warning'] = HTML::toBBCode($activity['summary']);
295                 $content = self::replaceEmojis($activity['emojis'], HTML::toBBCode($activity['content']));
296                 $item['body'] = self::convertMentions($content);
297
298                 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
299                         $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
300                 }
301
302                 $item['location'] = $activity['location'];
303
304                 if (!empty($item['latitude']) && !empty($item['longitude'])) {
305                         $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
306                 }
307
308                 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
309                 $item['app'] = $activity['generator'];
310                 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
311
312                 $item = self::constructAttachList($activity['attachments'], $item);
313
314                 if (!empty($activity['source'])) {
315                         $item['body'] = $activity['source'];
316                 }
317
318                 foreach ($activity['receiver'] as $receiver) {
319                         $item['uid'] = $receiver;
320                         $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
321
322                         if (($receiver != 0) && empty($item['contact-id'])) {
323                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
324                         }
325
326                         if ($activity['object_type'] == 'as:Event') {
327                                 self::createEvent($activity, $item);
328                         }
329
330                         $item_id = Item::insert($item);
331                         Logger::log('Storing for user ' . $item['uid'] . ': ' . $item_id);
332                 }
333         }
334
335         /**
336          * Fetches missing posts
337          *
338          * @param $url
339          * @param $child
340          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
341          */
342         private static function fetchMissingActivity($url, $child)
343         {
344                 if (Config::get('system', 'ostatus_full_threads')) {
345                         return;
346                 }
347
348                 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
349
350                 $object = ActivityPub::fetchContent($url, $uid);
351                 if (empty($object)) {
352                         Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
353                         return;
354                 }
355
356                 if (empty($object['id'])) {
357                         Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
358                         return;
359                 }
360
361                 $activity = [];
362                 $activity['@context'] = $object['@context'];
363                 unset($object['@context']);
364                 $activity['id'] = $object['id'];
365                 $activity['to'] = defaults($object, 'to', []);
366                 $activity['cc'] = defaults($object, 'cc', []);
367                 $activity['actor'] = $child['author'];
368                 $activity['object'] = $object;
369                 $activity['published'] = defaults($object, 'published', $child['published']);
370                 $activity['type'] = 'Create';
371
372                 $ldactivity = JsonLD::compact($activity);
373
374                 $ldactivity['thread-completion'] = true;
375
376                 ActivityPub\Receiver::processActivity($ldactivity);
377                 Logger::log('Activity ' . $url . ' had been fetched and processed.');
378         }
379
380         /**
381          * perform a "follow" request
382          *
383          * @param array $activity
384          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
385          * @throws \ImagickException
386          */
387         public static function followUser($activity)
388         {
389                 $uid = User::getIdForURL($activity['object_id']);
390                 if (empty($uid)) {
391                         return;
392                 }
393
394                 $owner = User::getOwnerDataById($uid);
395
396                 $cid = Contact::getIdForURL($activity['actor'], $uid);
397                 if (!empty($cid)) {
398                         self::switchContact($cid);
399                         DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
400                         $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
401                 } else {
402                         $contact = false;
403                 }
404
405                 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
406                         'author-link' => $activity['actor']];
407
408                 // Ensure that the contact has got the right network type
409                 self::switchContact($item['author-id']);
410
411                 Contact::addRelationship($owner, $contact, $item);
412                 $cid = Contact::getIdForURL($activity['actor'], $uid);
413                 if (empty($cid)) {
414                         return;
415                 }
416
417                 if (empty($contact)) {
418                         DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
419                 }
420
421                 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
422         }
423
424         /**
425          * Update the given profile
426          *
427          * @param array $activity
428          * @throws \Exception
429          */
430         public static function updatePerson($activity)
431         {
432                 if (empty($activity['object_id'])) {
433                         return;
434                 }
435
436                 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
437                 APContact::getByURL($activity['object_id'], true);
438         }
439
440         /**
441          * Delete the given profile
442          *
443          * @param array $activity
444          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
445          */
446         public static function deletePerson($activity)
447         {
448                 if (empty($activity['object_id']) || empty($activity['actor'])) {
449                         Logger::log('Empty object id or actor.', Logger::DEBUG);
450                         return;
451                 }
452
453                 if ($activity['object_id'] != $activity['actor']) {
454                         Logger::log('Object id does not match actor.', Logger::DEBUG);
455                         return;
456                 }
457
458                 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
459                 while ($contact = DBA::fetch($contacts)) {
460                         Contact::remove($contact['id']);
461                 }
462                 DBA::close($contacts);
463
464                 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
465         }
466
467         /**
468          * Accept a follow request
469          *
470          * @param array $activity
471          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
472          * @throws \ImagickException
473          */
474         public static function acceptFollowUser($activity)
475         {
476                 $uid = User::getIdForURL($activity['object_actor']);
477                 if (empty($uid)) {
478                         return;
479                 }
480
481                 $owner = User::getOwnerDataById($uid);
482
483                 $cid = Contact::getIdForURL($activity['actor'], $uid);
484                 if (empty($cid)) {
485                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
486                         return;
487                 }
488
489                 self::switchContact($cid);
490
491                 $fields = ['pending' => false];
492
493                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
494                 if ($contact['rel'] == Contact::FOLLOWER) {
495                         $fields['rel'] = Contact::FRIEND;
496                 }
497
498                 $condition = ['id' => $cid];
499                 DBA::update('contact', $fields, $condition);
500                 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
501         }
502
503         /**
504          * Reject a follow request
505          *
506          * @param array $activity
507          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
508          * @throws \ImagickException
509          */
510         public static function rejectFollowUser($activity)
511         {
512                 $uid = User::getIdForURL($activity['object_actor']);
513                 if (empty($uid)) {
514                         return;
515                 }
516
517                 $owner = User::getOwnerDataById($uid);
518
519                 $cid = Contact::getIdForURL($activity['actor'], $uid);
520                 if (empty($cid)) {
521                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
522                         return;
523                 }
524
525                 self::switchContact($cid);
526
527                 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
528                         Contact::remove($cid);
529                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
530                 } else {
531                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
532                 }
533         }
534
535         /**
536          * Undo activity like "like" or "dislike"
537          *
538          * @param array $activity
539          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
540          * @throws \ImagickException
541          */
542         public static function undoActivity($activity)
543         {
544                 if (empty($activity['object_id'])) {
545                         return;
546                 }
547
548                 if (empty($activity['object_actor'])) {
549                         return;
550                 }
551
552                 $author_id = Contact::getIdForURL($activity['object_actor']);
553                 if (empty($author_id)) {
554                         return;
555                 }
556
557                 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
558         }
559
560         /**
561          * Activity to remove a follower
562          *
563          * @param array $activity
564          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
565          * @throws \ImagickException
566          */
567         public static function undoFollowUser($activity)
568         {
569                 $uid = User::getIdForURL($activity['object_object']);
570                 if (empty($uid)) {
571                         return;
572                 }
573
574                 $owner = User::getOwnerDataById($uid);
575
576                 $cid = Contact::getIdForURL($activity['actor'], $uid);
577                 if (empty($cid)) {
578                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
579                         return;
580                 }
581
582                 self::switchContact($cid);
583
584                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
585                 if (!DBA::isResult($contact)) {
586                         return;
587                 }
588
589                 Contact::removeFollower($owner, $contact);
590                 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
591         }
592
593         /**
594          * Switches a contact to AP if needed
595          *
596          * @param integer $cid Contact ID
597          * @throws \Exception
598          */
599         private static function switchContact($cid)
600         {
601                 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
602                 if (!DBA::isResult($contact) || ($contact['network'] == Protocol::ACTIVITYPUB)) {
603                         return;
604                 }
605
606                 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
607                 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
608         }
609 }