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