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