]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Processor.php
Merge pull request #5906 from annando/ap-switch
[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                 $item['location'] = $activity['location'];
215
216                 if (!empty($item['latitude']) && !empty($item['longitude'])) {
217                         $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
218                 }
219
220                 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
221                 $item['app'] = $activity['generator'];
222                 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
223                 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:comment', '');
224
225                 $item = self::constructAttachList($activity['attachments'], $item);
226
227                 if (!empty($activity['source'])) {
228                         $item['body'] = $activity['source'];
229                 }
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                         self::switchContact($cid);
298                         $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
299                 } else {
300                         $contact = false;
301                 }
302
303                 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
304                         'author-link' => $activity['actor']];
305
306                 // Ensure that the contact has got the right network type
307                 self::switchContact($item['author-id']);
308
309                 Contact::addRelationship($owner, $contact, $item);
310                 $cid = Contact::getIdForURL($activity['actor'], $uid);
311                 if (empty($cid)) {
312                         return;
313                 }
314
315                 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
316                 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
317         }
318
319         /**
320          * Update the given profile
321          *
322          * @param array $activity
323          */
324         public static function updatePerson($activity)
325         {
326                 if (empty($activity['object_id'])) {
327                         return;
328                 }
329
330                 logger('Updating profile for ' . $activity['object_id'], LOGGER_DEBUG);
331                 APContact::getByURL($activity['object_id'], true);
332         }
333
334         /**
335          * Delete the given profile
336          *
337          * @param array $activity
338          */
339         public static function deletePerson($activity)
340         {
341                 if (empty($activity['object_id']) || empty($activity['actor'])) {
342                         logger('Empty object id or actor.', LOGGER_DEBUG);
343                         return;
344                 }
345
346                 if ($activity['object_id'] != $activity['actor']) {
347                         logger('Object id does not match actor.', LOGGER_DEBUG);
348                         return;
349                 }
350
351                 $contacts = DBA::select('contact', ['id'], ['nurl' => normalise_link($activity['object_id'])]);
352                 while ($contact = DBA::fetch($contacts)) {
353                         Contact::remove($contact['id']);
354                 }
355                 DBA::close($contacts);
356
357                 logger('Deleted contact ' . $activity['object_id'], LOGGER_DEBUG);
358         }
359
360         /**
361          * Accept a follow request
362          *
363          * @param array $activity
364          */
365         public static function acceptFollowUser($activity)
366         {
367                 $uid = User::getIdForURL($activity['object_actor']);
368                 if (empty($uid)) {
369                         return;
370                 }
371
372                 $owner = User::getOwnerDataById($uid);
373
374                 $cid = Contact::getIdForURL($activity['actor'], $uid);
375                 if (empty($cid)) {
376                         logger('No contact found for ' . $activity['actor'], LOGGER_DEBUG);
377                         return;
378                 }
379
380                 self::switchContact($cid);
381
382                 $fields = ['pending' => false];
383
384                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
385                 if ($contact['rel'] == Contact::FOLLOWER) {
386                         $fields['rel'] = Contact::FRIEND;
387                 }
388
389                 $condition = ['id' => $cid];
390                 DBA::update('contact', $fields, $condition);
391                 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
392         }
393
394         /**
395          * Reject a follow request
396          *
397          * @param array $activity
398          */
399         public static function rejectFollowUser($activity)
400         {
401                 $uid = User::getIdForURL($activity['object_actor']);
402                 if (empty($uid)) {
403                         return;
404                 }
405
406                 $owner = User::getOwnerDataById($uid);
407
408                 $cid = Contact::getIdForURL($activity['actor'], $uid);
409                 if (empty($cid)) {
410                         logger('No contact found for ' . $activity['actor'], LOGGER_DEBUG);
411                         return;
412                 }
413
414                 self::switchContact($cid);
415
416                 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
417                         Contact::remove($cid);
418                         logger('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', LOGGER_DEBUG);
419                 } else {
420                         logger('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', LOGGER_DEBUG);
421                 }
422         }
423
424         /**
425          * Undo activity like "like" or "dislike"
426          *
427          * @param array $activity
428          */
429         public static function undoActivity($activity)
430         {
431                 if (empty($activity['object_id'])) {
432                         return;
433                 }
434
435                 if (empty($activity['object_actor'])) {
436                         return;
437                 }
438
439                 $author_id = Contact::getIdForURL($activity['object_actor']);
440                 if (empty($author_id)) {
441                         return;
442                 }
443
444                 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
445         }
446
447         /**
448          * Activity to remove a follower
449          *
450          * @param array $activity
451          */
452         public static function undoFollowUser($activity)
453         {
454                 $uid = User::getIdForURL($activity['object_object']);
455                 if (empty($uid)) {
456                         return;
457                 }
458
459                 $owner = User::getOwnerDataById($uid);
460
461                 $cid = Contact::getIdForURL($activity['actor'], $uid);
462                 if (empty($cid)) {
463                         logger('No contact found for ' . $activity['actor'], LOGGER_DEBUG);
464                         return;
465                 }
466
467                 self::switchContact($cid);
468
469                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
470                 if (!DBA::isResult($contact)) {
471                         return;
472                 }
473
474                 Contact::removeFollower($owner, $contact);
475                 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
476         }
477
478         /**
479          * Switches a contact to AP if needed
480          *
481          * @param integer $cid Contact ID
482          */
483         private static function switchContact($cid)
484         {
485                 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
486                 if (!DBA::isResult($contact) || ($contact['network'] == Protocol::ACTIVITYPUB)) {
487                         return;
488                 }
489
490                 logger('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
491                 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
492         }
493 }