]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Processor.php
819892cb66edb49d958dcdb3d84753a37a10ea70
[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'] = JsonLD::fetchElement($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');
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'] = JsonLD::fetchElement($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                 $ldactivity = JsonLD::compact($activity);
265                 ActivityPub\Receiver::processActivity($activity, $ldactivity);
266                 logger('Activity ' . $url . ' had been fetched and processed.');
267         }
268
269         /**
270          * perform a "follow" request
271          *
272          * @param array $activity
273          */
274         public static function followUser($activity)
275         {
276                 $actor = JsonLD::fetchElement($activity, 'object');
277                 $uid = User::getIdForURL($actor);
278                 if (empty($uid)) {
279                         return;
280                 }
281
282                 $owner = User::getOwnerDataById($uid);
283
284                 $cid = Contact::getIdForURL($activity['owner'], $uid);
285                 if (!empty($cid)) {
286                         $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
287                 } else {
288                         $contact = false;
289                 }
290
291                 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
292                         'author-link' => $activity['owner']];
293
294                 Contact::addRelationship($owner, $contact, $item);
295                 $cid = Contact::getIdForURL($activity['owner'], $uid);
296                 if (empty($cid)) {
297                         return;
298                 }
299
300                 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
301                 if ($contact['network'] != Protocol::ACTIVITYPUB) {
302                         Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
303                 }
304
305                 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
306                 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
307         }
308
309         /**
310          * Update the given profile
311          *
312          * @param array $activity
313          */
314         public static function updatePerson($activity)
315         {
316                 $actor = JsonLD::fetchElement($activity, 'object');
317                 if ($actor) {
318                         return;
319                 }
320
321                 logger('Updating profile for ' . $actor, LOGGER_DEBUG);
322                 APContact::getByURL($actor, true);
323         }
324
325         /**
326          * Delete the given profile
327          *
328          * @param array $activity
329          */
330         public static function deletePerson($activity)
331         {
332                 $id = JsonLD::fetchElement($activity, 'object');
333                 $actor = JsonLD::fetchElement($activity, 'object', 'as:actor');
334
335                 if (empty($id) || empty($actor)) {
336                         logger('Empty object id or actor.', LOGGER_DEBUG);
337                         return;
338                 }
339
340                 if ($id != $actor) {
341                         logger('Object id does not match actor.', LOGGER_DEBUG);
342                         return;
343                 }
344
345                 $contacts = DBA::select('contact', ['id'], ['nurl' => normalise_link($id)]);
346                 while ($contact = DBA::fetch($contacts)) {
347                         Contact::remove($contact['id']);
348                 }
349                 DBA::close($contacts);
350
351                 logger('Deleted contact ' . $id, LOGGER_DEBUG);
352         }
353
354         /**
355          * Accept a follow request
356          *
357          * @param array $activity
358          */
359         public static function acceptFollowUser($activity)
360         {
361                 $actor = JsonLD::fetchElement($activity, 'object', 'as:actor');
362                 $uid = User::getIdForURL($actor);
363                 if (empty($uid)) {
364                         return;
365                 }
366
367                 $owner = User::getOwnerDataById($uid);
368
369                 $cid = Contact::getIdForURL($activity['owner'], $uid);
370                 if (empty($cid)) {
371                         logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
372                         return;
373                 }
374
375                 $fields = ['pending' => false];
376
377                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
378                 if ($contact['rel'] == Contact::FOLLOWER) {
379                         $fields['rel'] = Contact::FRIEND;
380                 }
381
382                 $condition = ['id' => $cid];
383                 DBA::update('contact', $fields, $condition);
384                 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
385         }
386
387         /**
388          * Reject a follow request
389          *
390          * @param array $activity
391          */
392         public static function rejectFollowUser($activity)
393         {
394                 $actor = JsonLD::fetchElement($activity, 'object', 'as:actor');
395                 $uid = User::getIdForURL($actor);
396                 if (empty($uid)) {
397                         return;
398                 }
399
400                 $owner = User::getOwnerDataById($uid);
401
402                 $cid = Contact::getIdForURL($activity['owner'], $uid);
403                 if (empty($cid)) {
404                         logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
405                         return;
406                 }
407
408                 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
409                         Contact::remove($cid);
410                         logger('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', LOGGER_DEBUG);
411                 } else {
412                         logger('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', LOGGER_DEBUG);
413                 }
414         }
415
416         /**
417          * Undo activity like "like" or "dislike"
418          *
419          * @param array $activity
420          */
421         public static function undoActivity($activity)
422         {
423                 $activity_url = JsonLD::fetchElement($activity, 'object');
424                 if (empty($activity_url)) {
425                         return;
426                 }
427
428                 $actor = JsonLD::fetchElement($activity, 'object', 'as:actor');
429                 if (empty($actor)) {
430                         return;
431                 }
432
433                 $author_id = Contact::getIdForURL($actor);
434                 if (empty($author_id)) {
435                         return;
436                 }
437
438                 Item::delete(['uri' => $activity_url, 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
439         }
440
441         /**
442          * Activity to remove a follower
443          *
444          * @param array $activity
445          */
446         public static function undoFollowUser($activity)
447         {
448                 $object = JsonLD::fetchElement($activity, 'object', 'as:object');
449                 $uid = User::getIdForURL($object);
450                 if (empty($uid)) {
451                         return;
452                 }
453
454                 $owner = User::getOwnerDataById($uid);
455
456                 $cid = Contact::getIdForURL($activity['owner'], $uid);
457                 if (empty($cid)) {
458                         logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
459                         return;
460                 }
461
462                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
463                 if (!DBA::isResult($contact)) {
464                         return;
465                 }
466
467                 Contact::removeFollower($owner, $contact);
468                 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
469         }
470 }