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