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