]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Processor.php
Changed attachment handling to improve Mastodon compatibility
[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  * @brief ActivityPub Protocol class
21  */
22 class Processor
23 {
24         /**
25          * @brief Converts mentions from Pleroma into the Friendica format
26          *
27          * @param string $body
28          *
29          * @return converted body
30          */
31         private static function convertMentions($body)
32         {
33                 $URLSearchString = "^\[\]";
34                 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
35
36                 return $body;
37         }
38
39         /**
40          * @brief Constructs a string with tags for a given tag array
41          *
42          * @param array $tags
43          * @param boolean $sensitive
44          *
45          * @return string with tags
46          */
47         private static function constructTagList($tags, $sensitive)
48         {
49                 if (empty($tags)) {
50                         return '';
51                 }
52
53                 $tag_text = '';
54                 foreach ($tags as $tag) {
55                         if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
56                                 if (!empty($tag_text)) {
57                                         $tag_text .= ',';
58                                 }
59
60                                 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
61                         }
62                 }
63
64                 /// @todo add nsfw for $sensitive
65
66                 return $tag_text;
67         }
68
69         /**
70          * @brief 
71          *
72          * @param $attachments
73          * @param array $item
74          *
75          * @return item array
76          */
77         private static function constructAttachList($attachments, $item)
78         {
79                 if (empty($attachments)) {
80                         return $item;
81                 }
82
83                 foreach ($attachments as $attach) {
84                         $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
85                         if ($filetype == 'image') {
86                                 $item['body'] .= "\n[img]" . $attach['url'] . '[/img]';
87                         } else {
88                                 if (!empty($item["attach"])) {
89                                         $item["attach"] .= ',';
90                                 } else {
91                                         $item["attach"] = '';
92                                 }
93                                 if (!isset($attach['length'])) {
94                                         $attach['length'] = "0";
95                                 }
96                                 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
97                         }
98                 }
99
100                 return $item;
101         }
102
103         /**
104          * @brief 
105          *
106          * @param array $activity
107          * @param $body
108          */
109         public static function createItem($activity, $body)
110         {
111                 $item = [];
112                 $item['verb'] = ACTIVITY_POST;
113                 $item['parent-uri'] = $activity['reply-to-id'];
114
115                 if ($activity['reply-to-id'] == $activity['id']) {
116                         $item['gravity'] = GRAVITY_PARENT;
117                         $item['object-type'] = ACTIVITY_OBJ_NOTE;
118                 } else {
119                         $item['gravity'] = GRAVITY_COMMENT;
120                         $item['object-type'] = ACTIVITY_OBJ_COMMENT;
121                 }
122
123                 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
124                         logger('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
125                         self::fetchMissingActivity($activity['reply-to-id'], $activity);
126                 }
127
128                 self::postItem($activity, $item, $body);
129         }
130
131         /**
132          * @brief 
133          *
134          * @param array $activity
135          * @param $body
136          */
137         public static function likeItem($activity, $body)
138         {
139                 $item = [];
140                 $item['verb'] = ACTIVITY_LIKE;
141                 $item['parent-uri'] = $activity['object'];
142                 $item['gravity'] = GRAVITY_ACTIVITY;
143                 $item['object-type'] = ACTIVITY_OBJ_NOTE;
144
145                 self::postItem($activity, $item, $body);
146         }
147
148         /**
149          * @brief Delete items
150          *
151          * @param array $activity
152          * @param $body
153          */
154         public static function deleteItem($activity)
155         {
156                 $owner = Contact::getIdForURL($activity['owner']);
157                 $object = JsonLD::fetchElement($activity, 'object', 'id');
158                 logger('Deleting item ' . $object . ' from ' . $owner, LOGGER_DEBUG);
159                 Item::delete(['uri' => $object, 'owner-id' => $owner]);
160         }
161
162         /**
163          * @brief 
164          *
165          * @param array $activity
166          * @param $body
167          */
168         public static function dislikeItem($activity, $body)
169         {
170                 $item = [];
171                 $item['verb'] = ACTIVITY_DISLIKE;
172                 $item['parent-uri'] = $activity['object'];
173                 $item['gravity'] = GRAVITY_ACTIVITY;
174                 $item['object-type'] = ACTIVITY_OBJ_NOTE;
175
176                 self::postItem($activity, $item, $body);
177         }
178
179         /**
180          * @brief 
181          *
182          * @param array $activity
183          * @param array $item
184          * @param $body
185          */
186         private static function postItem($activity, $item, $body)
187         {
188                 /// @todo What to do with $activity['context']?
189
190                 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
191                         logger('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', LOGGER_DEBUG);
192                         return;
193                 }
194
195                 $item['network'] = Protocol::ACTIVITYPUB;
196                 $item['private'] = !in_array(0, $activity['receiver']);
197                 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
198                 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
199                 $item['uri'] = $activity['id'];
200                 $item['created'] = $activity['published'];
201                 $item['edited'] = $activity['updated'];
202                 $item['guid'] = $activity['diaspora:guid'];
203                 $item['title'] = HTML::toBBCode($activity['name']);
204                 $item['content-warning'] = HTML::toBBCode($activity['summary']);
205                 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
206                 $item['location'] = $activity['location'];
207                 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
208                 $item['app'] = $activity['service'];
209                 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
210
211                 $item = self::constructAttachList($activity['attachments'], $item);
212
213                 $source = JsonLD::fetchElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
214                 if (!empty($source)) {
215                         $item['body'] = $source;
216                 }
217
218                 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
219                 $item['source'] = $body;
220                 $item['conversation-href'] = $activity['context'];
221                 $item['conversation-uri'] = $activity['conversation'];
222
223                 foreach ($activity['receiver'] as $receiver) {
224                         $item['uid'] = $receiver;
225                         $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
226
227                         if (($receiver != 0) && empty($item['contact-id'])) {
228                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
229                         }
230
231                         $item_id = Item::insert($item);
232                         logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
233                 }
234         }
235
236         /**
237          * @brief 
238          *
239          * @param $url
240          * @param $child
241          */
242         private static function fetchMissingActivity($url, $child)
243         {
244                 if (Config::get('system', 'ostatus_full_threads')) {
245                         return;
246                 }
247
248                 $object = ActivityPub::fetchContent($url);
249                 if (empty($object)) {
250                         logger('Activity ' . $url . ' was not fetchable, aborting.');
251                         return;
252                 }
253
254                 $activity = [];
255                 $activity['@context'] = $object['@context'];
256                 unset($object['@context']);
257                 $activity['id'] = $object['id'];
258                 $activity['to'] = defaults($object, 'to', []);
259                 $activity['cc'] = defaults($object, 'cc', []);
260                 $activity['actor'] = $child['author'];
261                 $activity['object'] = $object;
262                 $activity['published'] = $object['published'];
263                 $activity['type'] = 'Create';
264
265                 ActivityPub\Receiver::processActivity($activity);
266                 logger('Activity ' . $url . ' had been fetched and processed.');
267         }
268
269         /**
270          * @brief perform a "follow" request
271          *
272          * @param array $activity
273          */
274         public static function followUser($activity)
275         {
276                 $actor = JsonLD::fetchElement($activity, 'object', 'id');
277                 $uid = User::getIdForURL($actor);
278                 if (empty($uid)) {
279                         return;
280                 }
281
282                 $owner = User::getOwnerDataById($uid);
283
284                 $cid = Contact::getIdForURL($activity['owner'], $uid);
285                 if (!empty($cid)) {
286                         $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
287                 } else {
288                         $contact = false;
289                 }
290
291                 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
292                         'author-link' => $activity['owner']];
293
294                 Contact::addRelationship($owner, $contact, $item);
295                 $cid = Contact::getIdForURL($activity['owner'], $uid);
296                 if (empty($cid)) {
297                         return;
298                 }
299
300                 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
301                 if ($contact['network'] != Protocol::ACTIVITYPUB) {
302                         Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
303                 }
304
305                 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
306                 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
307         }
308
309         /**
310          * @brief Update the given profile
311          *
312          * @param array $activity
313          */
314         public static function updatePerson($activity)
315         {
316                 if (empty($activity['object']['id'])) {
317                         return;
318                 }
319
320                 logger('Updating profile for ' . $activity['object']['id'], LOGGER_DEBUG);
321                 APContact::getByURL($activity['object']['id'], true);
322         }
323
324         /**
325          * @brief Delete the given profile
326          *
327          * @param array $activity
328          */
329         public static function deletePerson($activity)
330         {
331                 if (empty($activity['object']['id']) || empty($activity['object']['actor'])) {
332                         logger('Empty object id or actor.', LOGGER_DEBUG);
333                         return;
334                 }
335
336                 if ($activity['object']['id'] != $activity['object']['actor']) {
337                         logger('Object id does not match actor.', LOGGER_DEBUG);
338                         return;
339                 }
340
341                 $contacts = DBA::select('contact', ['id'], ['nurl' => normalise_link($activity['object']['id'])]);
342                 while ($contact = DBA::fetch($contacts)) {
343                         Contact::remove($contact["id"]);
344                 }
345                 DBA::close($contacts);
346
347                 logger('Deleted contact ' . $activity['object']['id'], LOGGER_DEBUG);
348         }
349
350         /**
351          * @brief Accept a follow request
352          *
353          * @param array $activity
354          */
355         public static function acceptFollowUser($activity)
356         {
357                 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
358                 $uid = User::getIdForURL($actor);
359                 if (empty($uid)) {
360                         return;
361                 }
362
363                 $owner = User::getOwnerDataById($uid);
364
365                 $cid = Contact::getIdForURL($activity['owner'], $uid);
366                 if (empty($cid)) {
367                         logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
368                         return;
369                 }
370
371                 $fields = ['pending' => false];
372
373                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
374                 if ($contact['rel'] == Contact::FOLLOWER) {
375                         $fields['rel'] = Contact::FRIEND;
376                 }
377
378                 $condition = ['id' => $cid];
379                 DBA::update('contact', $fields, $condition);
380                 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
381         }
382
383         /**
384          * @brief Reject a follow request
385          *
386          * @param array $activity
387          */
388         public static function rejectFollowUser($activity)
389         {
390                 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
391                 $uid = User::getIdForURL($actor);
392                 if (empty($uid)) {
393                         return;
394                 }
395
396                 $owner = User::getOwnerDataById($uid);
397
398                 $cid = Contact::getIdForURL($activity['owner'], $uid);
399                 if (empty($cid)) {
400                         logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
401                         return;
402                 }
403
404                 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
405                         Contact::remove($cid);
406                         logger('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', LOGGER_DEBUG);
407                 } else {
408                         logger('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', LOGGER_DEBUG);
409                 }
410         }
411
412         /**
413          * @brief Undo activity like "like" or "dislike"
414          *
415          * @param array $activity
416          */
417         public static function undoActivity($activity)
418         {
419                 $activity_url = JsonLD::fetchElement($activity, 'object', 'id');
420                 if (empty($activity_url)) {
421                         return;
422                 }
423
424                 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
425                 if (empty($actor)) {
426                         return;
427                 }
428
429                 $author_id = Contact::getIdForURL($actor);
430                 if (empty($author_id)) {
431                         return;
432                 }
433
434                 Item::delete(['uri' => $activity_url, 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
435         }
436
437         /**
438          * @brief Activity to remove a follower
439          *
440          * @param array $activity
441          */
442         public static function undoFollowUser($activity)
443         {
444                 $object = JsonLD::fetchElement($activity, 'object', 'object');
445                 $uid = User::getIdForURL($object);
446                 if (empty($uid)) {
447                         return;
448                 }
449
450                 $owner = User::getOwnerDataById($uid);
451
452                 $cid = Contact::getIdForURL($activity['owner'], $uid);
453                 if (empty($cid)) {
454                         logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
455                         return;
456                 }
457
458                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
459                 if (!DBA::isResult($contact)) {
460                         return;
461                 }
462
463                 Contact::removeFollower($owner, $contact);
464                 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
465         }
466 }