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