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