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