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