]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Processor.php
Switch to parsing compacted JSON data
[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\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          * 
71          *
72          * @param $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          * 
105          *
106          * @param array $activity
107          * @param $body
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          * 
133          *
134          * @param array $activity
135          * @param $body
136          */
137         public static function likeItem($activity, $body)
138         {
139                 $item = [];
140                 $item['verb'] = ACTIVITY_LIKE;
141                 $item['parent-uri'] = $activity['object'];
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          * @param $body
153          */
154         public static function deleteItem($activity)
155         {
156                 $owner = Contact::getIdForURL($activity['owner']);
157                 $object = JsonLD::fetchElement($activity, 'object', 'id');
158                 logger('Deleting item ' . $object . ' from ' . $owner, LOGGER_DEBUG);
159                 Item::delete(['uri' => $object, 'owner-id' => $owner]);
160         }
161
162         /**
163          * 
164          *
165          * @param array $activity
166          * @param $body
167          */
168         public static function dislikeItem($activity, $body)
169         {
170                 $item = [];
171                 $item['verb'] = ACTIVITY_DISLIKE;
172                 $item['parent-uri'] = $activity['object'];
173                 $item['gravity'] = GRAVITY_ACTIVITY;
174                 $item['object-type'] = ACTIVITY_OBJ_NOTE;
175
176                 self::postItem($activity, $item, $body);
177         }
178
179         /**
180          * 
181          *
182          * @param array $activity
183          * @param array $item
184          * @param $body
185          */
186         private static function postItem($activity, $item, $body)
187         {
188                 /// @todo What to do with $activity['context']?
189
190                 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
191                         logger('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', LOGGER_DEBUG);
192                         return;
193                 }
194
195                 $item['network'] = Protocol::ACTIVITYPUB;
196                 $item['private'] = !in_array(0, $activity['receiver']);
197                 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
198                 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
199                 $item['uri'] = $activity['id'];
200                 $item['created'] = $activity['published'];
201                 $item['edited'] = $activity['updated'];
202                 $item['guid'] = $activity['diaspora:guid'];
203                 $item['title'] = HTML::toBBCode($activity['name']);
204                 $item['content-warning'] = HTML::toBBCode($activity['summary']);
205                 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
206                 $item['location'] = $activity['location'];
207                 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
208                 $item['app'] = $activity['service'];
209                 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
210
211                 $item = self::constructAttachList($activity['attachments'], $item);
212
213                 if (!empty($activity['source'])) {
214                         $item['body'] = $activity['source'];
215                 }
216
217                 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
218                 $item['source'] = $body;
219                 $item['conversation-href'] = $activity['context'];
220                 $item['conversation-uri'] = $activity['conversation'];
221
222                 foreach ($activity['receiver'] as $receiver) {
223                         $item['uid'] = $receiver;
224                         $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
225
226                         if (($receiver != 0) && empty($item['contact-id'])) {
227                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
228                         }
229
230                         $item_id = Item::insert($item);
231                         logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
232                 }
233         }
234
235         /**
236          * 
237          *
238          * @param $url
239          * @param $child
240          */
241         private static function fetchMissingActivity($url, $child)
242         {
243                 if (Config::get('system', 'ostatus_full_threads')) {
244                         return;
245                 }
246
247                 $object = ActivityPub::fetchContent($url);
248                 if (empty($object)) {
249                         logger('Activity ' . $url . ' was not fetchable, aborting.');
250                         return;
251                 }
252
253                 $activity = [];
254                 $activity['@context'] = $object['@context'];
255                 unset($object['@context']);
256                 $activity['id'] = $object['id'];
257                 $activity['to'] = defaults($object, 'to', []);
258                 $activity['cc'] = defaults($object, 'cc', []);
259                 $activity['actor'] = $child['author'];
260                 $activity['object'] = $object;
261                 $activity['published'] = $object['published'];
262                 $activity['type'] = 'Create';
263
264                 ActivityPub\Receiver::processActivity($activity);
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                 $actor = JsonLD::fetchElement($activity, 'object', 'id');
276                 $uid = User::getIdForURL($actor);
277                 if (empty($uid)) {
278                         return;
279                 }
280
281                 $owner = User::getOwnerDataById($uid);
282
283                 $cid = Contact::getIdForURL($activity['owner'], $uid);
284                 if (!empty($cid)) {
285                         $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
286                 } else {
287                         $contact = false;
288                 }
289
290                 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
291                         'author-link' => $activity['owner']];
292
293                 Contact::addRelationship($owner, $contact, $item);
294                 $cid = Contact::getIdForURL($activity['owner'], $uid);
295                 if (empty($cid)) {
296                         return;
297                 }
298
299                 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
300                 if ($contact['network'] != Protocol::ACTIVITYPUB) {
301                         Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
302                 }
303
304                 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
305                 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
306         }
307
308         /**
309          * Update the given profile
310          *
311          * @param array $activity
312          */
313         public static function updatePerson($activity)
314         {
315                 if (empty($activity['object']['id'])) {
316                         return;
317                 }
318
319                 logger('Updating profile for ' . $activity['object']['id'], LOGGER_DEBUG);
320                 APContact::getByURL($activity['object']['id'], true);
321         }
322
323         /**
324          * Delete the given profile
325          *
326          * @param array $activity
327          */
328         public static function deletePerson($activity)
329         {
330                 if (empty($activity['object']['id']) || empty($activity['object']['actor'])) {
331                         logger('Empty object id or actor.', LOGGER_DEBUG);
332                         return;
333                 }
334
335                 if ($activity['object']['id'] != $activity['object']['actor']) {
336                         logger('Object id does not match actor.', LOGGER_DEBUG);
337                         return;
338                 }
339
340                 $contacts = DBA::select('contact', ['id'], ['nurl' => normalise_link($activity['object']['id'])]);
341                 while ($contact = DBA::fetch($contacts)) {
342                         Contact::remove($contact["id"]);
343                 }
344                 DBA::close($contacts);
345
346                 logger('Deleted contact ' . $activity['object']['id'], LOGGER_DEBUG);
347         }
348
349         /**
350          * Accept a follow request
351          *
352          * @param array $activity
353          */
354         public static function acceptFollowUser($activity)
355         {
356                 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
357                 $uid = User::getIdForURL($actor);
358                 if (empty($uid)) {
359                         return;
360                 }
361
362                 $owner = User::getOwnerDataById($uid);
363
364                 $cid = Contact::getIdForURL($activity['owner'], $uid);
365                 if (empty($cid)) {
366                         logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
367                         return;
368                 }
369
370                 $fields = ['pending' => false];
371
372                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
373                 if ($contact['rel'] == Contact::FOLLOWER) {
374                         $fields['rel'] = Contact::FRIEND;
375                 }
376
377                 $condition = ['id' => $cid];
378                 DBA::update('contact', $fields, $condition);
379                 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
380         }
381
382         /**
383          * Reject a follow request
384          *
385          * @param array $activity
386          */
387         public static function rejectFollowUser($activity)
388         {
389                 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
390                 $uid = User::getIdForURL($actor);
391                 if (empty($uid)) {
392                         return;
393                 }
394
395                 $owner = User::getOwnerDataById($uid);
396
397                 $cid = Contact::getIdForURL($activity['owner'], $uid);
398                 if (empty($cid)) {
399                         logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
400                         return;
401                 }
402
403                 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
404                         Contact::remove($cid);
405                         logger('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', LOGGER_DEBUG);
406                 } else {
407                         logger('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', LOGGER_DEBUG);
408                 }
409         }
410
411         /**
412          * Undo activity like "like" or "dislike"
413          *
414          * @param array $activity
415          */
416         public static function undoActivity($activity)
417         {
418                 $activity_url = JsonLD::fetchElement($activity, 'object', 'id');
419                 if (empty($activity_url)) {
420                         return;
421                 }
422
423                 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
424                 if (empty($actor)) {
425                         return;
426                 }
427
428                 $author_id = Contact::getIdForURL($actor);
429                 if (empty($author_id)) {
430                         return;
431                 }
432
433                 Item::delete(['uri' => $activity_url, 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
434         }
435
436         /**
437          * Activity to remove a follower
438          *
439          * @param array $activity
440          */
441         public static function undoFollowUser($activity)
442         {
443                 $object = JsonLD::fetchElement($activity, 'object', 'object');
444                 $uid = User::getIdForURL($object);
445                 if (empty($uid)) {
446                         return;
447                 }
448
449                 $owner = User::getOwnerDataById($uid);
450
451                 $cid = Contact::getIdForURL($activity['owner'], $uid);
452                 if (empty($cid)) {
453                         logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
454                         return;
455                 }
456
457                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
458                 if (!DBA::isResult($contact)) {
459                         return;
460                 }
461
462                 Contact::removeFollower($owner, $contact);
463                 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
464         }
465 }