]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Receiver.php
Merge pull request #10093 from urbalazs/copyright-2021
[friendica.git] / src / Protocol / ActivityPub / Receiver.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Protocol\ActivityPub;
23
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Database\DBA;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Model\Contact;
31 use Friendica\Model\APContact;
32 use Friendica\Model\Item;
33 use Friendica\Model\Post;
34 use Friendica\Model\User;
35 use Friendica\Protocol\Activity;
36 use Friendica\Protocol\ActivityPub;
37 use Friendica\Util\HTTPSignature;
38 use Friendica\Util\JsonLD;
39 use Friendica\Util\LDSignature;
40 use Friendica\Util\Strings;
41
42 /**
43  * ActivityPub Receiver Protocol class
44  *
45  * To-Do:
46  * @todo Undo Announce
47  *
48  * Check what this is meant to do:
49  * - Add
50  * - Block
51  * - Flag
52  * - Remove
53  * - Undo Block
54  */
55 class Receiver
56 {
57         const PUBLIC_COLLECTION = 'as:Public';
58         const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
59         const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event', 'as:Audio'];
60         const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
61
62         const TARGET_UNKNOWN = 0;
63         const TARGET_TO = 1;
64         const TARGET_CC = 2;
65         const TARGET_BTO = 3;
66         const TARGET_BCC = 4;
67         const TARGET_FOLLOWER = 5;
68         const TARGET_ANSWER = 6;
69         const TARGET_GLOBAL = 7;
70
71         /**
72          * Checks if the web request is done for the AP protocol
73          *
74          * @return bool is it AP?
75          */
76         public static function isRequest()
77         {
78                 return stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') ||
79                         stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/ld+json');
80         }
81
82         /**
83          * Checks incoming message from the inbox
84          *
85          * @param         $body
86          * @param         $header
87          * @param integer $uid User ID
88          * @throws \Exception
89          */
90         public static function processInbox($body, $header, $uid)
91         {
92                 $activity = json_decode($body, true);
93                 if (empty($activity)) {
94                         Logger::warning('Invalid body.');
95                         return;
96                 }
97
98                 $ldactivity = JsonLD::compact($activity);
99
100                 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id');
101
102                 $apcontact = APContact::getByURL($actor);
103                 if (empty($apcontact)) {
104                         Logger::notice('Unable to retrieve AP contact for actor - message is discarded', ['actor' => $actor]);
105                         return;
106                 } elseif ($apcontact['type'] == 'Application' && $apcontact['nick'] == 'relay') {
107                         self::processRelayPost($ldactivity, $actor);
108                         return;
109                 } else {
110                         APContact::unmarkForArchival($apcontact);
111                 }
112
113                 $http_signer = HTTPSignature::getSigner($body, $header);
114                 if (empty($http_signer)) {
115                         Logger::warning('Invalid HTTP signature, message will be discarded.');
116                         return;
117                 } else {
118                         Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
119                 }
120
121                 $signer = [$http_signer];
122
123                 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
124
125                 if (LDSignature::isSigned($activity)) {
126                         $ld_signer = LDSignature::getSigner($activity);
127                         if (empty($ld_signer)) {
128                                 Logger::log('Invalid JSON-LD signature from ' . $actor, Logger::DEBUG);
129                         } elseif ($ld_signer != $http_signer) {
130                                 $signer[] = $ld_signer;
131                         }
132                         if (!empty($ld_signer && ($actor == $http_signer))) {
133                                 Logger::log('The HTTP and the JSON-LD signature belong to ' . $ld_signer, Logger::DEBUG);
134                                 $trust_source = true;
135                         } elseif (!empty($ld_signer)) {
136                                 Logger::log('JSON-LD signature is signed by ' . $ld_signer, Logger::DEBUG);
137                                 $trust_source = true;
138                         } elseif ($actor == $http_signer) {
139                                 Logger::log('Bad JSON-LD signature, but HTTP signer fits the actor.', Logger::DEBUG);
140                                 $trust_source = true;
141                         } else {
142                                 Logger::log('Invalid JSON-LD signature and the HTTP signer is different.', Logger::DEBUG);
143                                 $trust_source = false;
144                         }
145                 } elseif ($actor == $http_signer) {
146                         Logger::log('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', Logger::DEBUG);
147                         $trust_source = true;
148                 } else {
149                         Logger::log('No JSON-LD signature, different actor.', Logger::DEBUG);
150                         $trust_source = false;
151                 }
152
153                 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer);
154         }
155
156         /**
157          * Process incoming posts from relays
158          *
159          * @param array  $activity
160          * @param string $actor
161          * @return void
162          */
163         private static function processRelayPost(array $activity, string $actor)
164         {
165                 $type = JsonLD::fetchElement($activity, '@type');
166                 if (!$type) {
167                         Logger::info('Empty type', ['activity' => $activity]);
168                         return;
169                 }
170
171                 if ($type != 'as:Announce') {
172                         Logger::info('Not an announcement', ['activity' => $activity]);
173                         return;
174                 }
175
176                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
177                 if (empty($object_id)) {
178                         Logger::info('No object id found', ['activity' => $activity]);
179                         return;
180                 }
181
182                 $contact = Contact::getByURL($actor);
183                 if (empty($contact)) {
184                         Logger::info('Relay contact not found', ['actor' => $actor]);
185                         return;
186                 }
187
188                 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
189                         Logger::notice('Relay is no sharer', ['actor' => $actor]);
190                         return;
191                 }
192
193                 Logger::info('Got relayed message id', ['id' => $object_id]);
194
195                 $item_id = Item::searchByLink($object_id);
196                 if ($item_id) {
197                         Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id]);
198                         return;
199                 }
200
201                 $id = Processor::fetchMissingActivity($object_id, [], $actor);
202                 if (empty($id)) {
203                         Logger::notice('Relayed message had not been fetched', ['id' => $object_id]);
204                         return;
205                 }
206
207                 $item_id = Item::searchByLink($object_id);
208                 if ($item_id) {
209                         Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id]);
210                 } else {
211                         Logger::notice('Relayed message had not been stored', ['id' => $object_id]);
212                 }
213         }
214
215         /**
216          * Fetches the object type for a given object id
217          *
218          * @param array   $activity
219          * @param string  $object_id Object ID of the the provided object
220          * @param integer $uid       User ID
221          *
222          * @return string with object type
223          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
224          * @throws \ImagickException
225          */
226         private static function fetchObjectType($activity, $object_id, $uid = 0)
227         {
228                 if (!empty($activity['as:object'])) {
229                         $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
230                         if (!empty($object_type)) {
231                                 return $object_type;
232                         }
233                 }
234
235                 if (Post::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
236                         // We just assume "note" since it doesn't make a difference for the further processing
237                         return 'as:Note';
238                 }
239
240                 $profile = APContact::getByURL($object_id);
241                 if (!empty($profile['type'])) {
242                         APContact::unmarkForArchival($profile);
243                         return 'as:' . $profile['type'];
244                 }
245
246                 $data = ActivityPub::fetchContent($object_id, $uid);
247                 if (!empty($data)) {
248                         $object = JsonLD::compact($data);
249                         $type = JsonLD::fetchElement($object, '@type');
250                         if (!empty($type)) {
251                                 return $type;
252                         }
253                 }
254
255                 return null;
256         }
257
258         /**
259          * Prepare the object array
260          *
261          * @param array   $activity     Array with activity data
262          * @param integer $uid          User ID
263          * @param boolean $push         Message had been pushed to our system
264          * @param boolean $trust_source Do we trust the source?
265          *
266          * @return array with object data
267          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
268          * @throws \ImagickException
269          */
270         public static function prepareObjectData($activity, $uid, $push, &$trust_source)
271         {
272                 $id = JsonLD::fetchElement($activity, '@id');
273                 if (!empty($id) && !$trust_source) {
274                         $fetched_activity = ActivityPub::fetchContent($id, $uid ?? 0);
275                         if (!empty($fetched_activity)) {
276                                 $object = JsonLD::compact($fetched_activity);
277                                 $fetched_id = JsonLD::fetchElement($object, '@id');
278                                 if ($fetched_id == $id) {
279                                         Logger::info('Activity had been fetched successfully', ['id' => $id]);
280                                         $trust_source = true;
281                                         $activity = $object;
282                                 } else {
283                                         Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
284                                 }
285                         } else {
286                                 Logger::info('Activity could not been fetched', ['id' => $id]);
287                         }
288                 }
289
290                 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
291                 if (empty($actor)) {
292                         Logger::info('Empty actor', ['activity' => $activity]);
293                         return [];
294                 }
295
296                 $type = JsonLD::fetchElement($activity, '@type');
297
298                 // Fetch all receivers from to, cc, bto and bcc
299                 $receiverdata = self::getReceivers($activity, $actor);
300                 $receivers = $reception_types = [];
301                 foreach ($receiverdata as $key => $data) {
302                         $receivers[$key] = $data['uid'];
303                         $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
304                 }
305
306                 // When it is a delivery to a personal inbox we add that user to the receivers
307                 if (!empty($uid)) {
308                         $additional = [$uid => $uid];
309                         $receivers = array_replace($receivers, $additional);
310                         if (empty($activity['thread-completion']) && (empty($reception_types[$uid]) || in_array($reception_types[$uid], [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL]))) {
311                                 $reception_types[$uid] = self::TARGET_BCC;
312                         }
313                 } else {
314                         // We possibly need some user to fetch private content,
315                         // so we fetch the first out ot the list.
316                         $uid = self::getFirstUserFromReceivers($receivers);
317                 }
318
319                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
320                 if (empty($object_id)) {
321                         Logger::log('No object found', Logger::DEBUG);
322                         return [];
323                 }
324
325                 if (!is_string($object_id)) {
326                         Logger::info('Invalid object id', ['object' => $object_id]);
327                         return [];
328                 }
329
330                 $object_type = self::fetchObjectType($activity, $object_id, $uid);
331
332                 // Fetch the content only on activities where this matters
333                 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
334                         // Always fetch on "Announce"
335                         $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $uid);
336                         if (empty($object_data)) {
337                                 Logger::log("Object data couldn't be processed", Logger::DEBUG);
338                                 return [];
339                         }
340
341                         $object_data['object_id'] = $object_id;
342
343                         if ($type == 'as:Announce') {
344                                 $object_data['push'] = false;
345                         } else {
346                                 $object_data['push'] = $push;
347                         }
348
349                         // Test if it is an answer to a mail
350                         if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
351                                 $object_data['directmessage'] = true;
352                         } else {
353                                 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
354                         }
355                 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
356                         // Create a mostly empty array out of the activity data (instead of the object).
357                         // This way we later don't have to check for the existence of ech individual array element.
358                         $object_data = self::processObject($activity);
359                         $object_data['name'] = $type;
360                         $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
361                         $object_data['object_id'] = $object_id;
362                         $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
363                         $object_data['push'] = $push;
364                 } elseif (in_array($type, ['as:Add'])) {
365                         $object_data = [];
366                         $object_data['id'] = JsonLD::fetchElement($activity, '@id');
367                         $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
368                         $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
369                         $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
370                         $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
371                         $object_data['push'] = $push;
372                 } else {
373                         $object_data = [];
374                         $object_data['id'] = JsonLD::fetchElement($activity, '@id');
375                         $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
376                         $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
377                         $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
378                         $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
379                         $object_data['push'] = $push;
380
381                         // An Undo is done on the object of an object, so we need that type as well
382                         if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
383                                 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
384                         }
385                 }
386
387                 $object_data = self::addActivityFields($object_data, $activity);
388
389                 if (empty($object_data['object_type'])) {
390                         $object_data['object_type'] = $object_type;
391                 }
392
393                 $object_data['type'] = $type;
394                 $object_data['actor'] = $actor;
395                 $object_data['item_receiver'] = $receivers;
396                 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
397                 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
398
399                 $author = $object_data['author'] ?? $actor;
400                 if (!empty($author) && !empty($object_data['id'])) {
401                         $author_host = parse_url($author, PHP_URL_HOST);
402                         $id_host = parse_url($object_data['id'], PHP_URL_HOST);
403                         if ($author_host == $id_host) {
404                                 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
405                         } else {
406                                 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
407                                 $trust_source = false;
408                         }
409                 }
410
411                 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
412
413                 return $object_data;
414         }
415
416         /**
417          * Fetches the first user id from the receiver array
418          *
419          * @param array $receivers Array with receivers
420          * @return integer user id;
421          */
422         public static function getFirstUserFromReceivers($receivers)
423         {
424                 foreach ($receivers as $receiver) {
425                         if (!empty($receiver)) {
426                                 return $receiver;
427                         }
428                 }
429                 return 0;
430         }
431
432         /**
433          * Processes the activity object
434          *
435          * @param array   $activity     Array with activity data
436          * @param string  $body
437          * @param integer $uid          User ID
438          * @param boolean $trust_source Do we trust the source?
439          * @param boolean $push         Message had been pushed to our system
440          * @throws \Exception
441          */
442         public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
443         {
444                 $type = JsonLD::fetchElement($activity, '@type');
445                 if (!$type) {
446                         Logger::info('Empty type', ['activity' => $activity]);
447                         return;
448                 }
449
450                 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
451                         Logger::info('Empty object', ['activity' => $activity]);
452                         return;
453                 }
454
455                 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
456                 if (empty($actor)) {
457                         Logger::info('Empty actor', ['activity' => $activity]);
458                         return;
459                 }
460
461                 if (is_array($activity['as:object'])) {
462                         $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
463                 } else {
464                         $attributed_to = '';
465                 }
466
467                 // Test the provided signatures against the actor and "attributedTo"
468                 if ($trust_source) {
469                         if (!empty($attributed_to) && !empty($actor)) {
470                                 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
471                         } else {
472                                 $trust_source = in_array($actor, $signer);
473                         }
474                 }
475
476                 // $trust_source is called by reference and is set to true if the content was retrieved successfully
477                 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
478                 if (empty($object_data)) {
479                         Logger::info('No object data found', ['activity' => $activity]);
480                         return;
481                 }
482
483                 if (!$trust_source) {
484                         Logger::info('Activity trust could not be achieved.',  ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
485                         return;
486                 }
487
488                 if (!empty($body) && empty($object_data['raw'])) {
489                         $object_data['raw'] = $body;
490                 }
491
492                 // Internal flag for thread completion. See Processor.php
493                 if (!empty($activity['thread-completion'])) {
494                         $object_data['thread-completion'] = $activity['thread-completion'];
495                 }
496
497                 // Internal flag for posts that arrived via relay
498                 if (!empty($activity['from-relay'])) {
499                         $object_data['from-relay'] = $activity['from-relay'];
500                 }
501                 
502                 switch ($type) {
503                         case 'as:Create':
504                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
505                                         $item = ActivityPub\Processor::createItem($object_data);
506                                         ActivityPub\Processor::postItem($object_data, $item);
507                                 }
508                                 break;
509
510                         case 'as:Add':
511                                 if ($object_data['object_type'] == 'as:tag') {
512                                         ActivityPub\Processor::addTag($object_data);
513                                 }
514                                 break;
515
516                         case 'as:Announce':
517                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
518                                         $object_data['thread-completion'] = Contact::getIdForURL($actor);
519
520                                         $item = ActivityPub\Processor::createItem($object_data);
521                                         if (empty($item)) {
522                                                 return;
523                                         }
524
525                                         $item['post-type'] = Item::PT_ANNOUNCEMENT;
526                                         ActivityPub\Processor::postItem($object_data, $item);
527
528                                         $announce_object_data = self::processObject($activity);
529                                         $announce_object_data['name'] = $type;
530                                         $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
531                                         $announce_object_data['object_id'] = $object_data['object_id'];
532                                         $announce_object_data['object_type'] = $object_data['object_type'];
533                                         $announce_object_data['push'] = $push;
534
535                                         if (!empty($body)) {
536                                                 $announce_object_data['raw'] = $body;
537                                         }
538
539                                         ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
540                                 }
541                                 break;
542
543                         case 'as:Like':
544                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
545                                         ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
546                                 }
547                                 break;
548
549                         case 'as:Dislike':
550                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
551                                         ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
552                                 }
553                                 break;
554
555                         case 'as:TentativeAccept':
556                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
557                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
558                                 }
559                                 break;
560
561                         case 'as:Update':
562                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
563                                         ActivityPub\Processor::updateItem($object_data);
564                                 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
565                                         ActivityPub\Processor::updatePerson($object_data);
566                                 }
567                                 break;
568
569                         case 'as:Delete':
570                                 if ($object_data['object_type'] == 'as:Tombstone') {
571                                         ActivityPub\Processor::deleteItem($object_data);
572                                 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
573                                         ActivityPub\Processor::deletePerson($object_data);
574                                 }
575                                 break;
576
577                         case 'as:Follow':
578                                 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
579                                         ActivityPub\Processor::followUser($object_data);
580                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
581                                         $object_data['reply-to-id'] = $object_data['object_id'];
582                                         ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
583                                 }
584                                 break;
585
586                         case 'as:Accept':
587                                 if ($object_data['object_type'] == 'as:Follow') {
588                                         ActivityPub\Processor::acceptFollowUser($object_data);
589                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
590                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
591                                 }
592                                 break;
593
594                         case 'as:Reject':
595                                 if ($object_data['object_type'] == 'as:Follow') {
596                                         ActivityPub\Processor::rejectFollowUser($object_data);
597                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
598                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
599                                 }
600                                 break;
601
602                         case 'as:Undo':
603                                 if (($object_data['object_type'] == 'as:Follow') &&
604                                         in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
605                                         ActivityPub\Processor::undoFollowUser($object_data);
606                                 } elseif (($object_data['object_type'] == 'as:Accept') &&
607                                         in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
608                                         ActivityPub\Processor::rejectFollowUser($object_data);
609                                 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
610                                         in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
611                                         ActivityPub\Processor::undoActivity($object_data);
612                                 }
613                                 break;
614
615                         default:
616                                 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
617                                 break;
618                 }
619         }
620
621         /**
622          * Fetch the receiver list from an activity array
623          *
624          * @param array   $activity
625          * @param string  $actor
626          * @param array   $tags
627          * @param boolean $fetch_unlisted 
628          *
629          * @return array with receivers (user id)
630          * @throws \Exception
631          */
632         private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
633         {
634                 $reply = $receivers = [];
635
636                 // When it is an answer, we inherite the receivers from the parent
637                 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
638                 if (!empty($replyto)) {
639                         $reply = [$replyto];
640
641                         // Fix possibly wrong item URI (could be an answer to a plink uri)
642                         $fixedReplyTo = Item::getURIByLink($replyto);
643                         if (!empty($fixedReplyTo)) {
644                                 $reply[] = $fixedReplyTo;
645                         }
646                 }
647
648                 // Fetch all posts that refer to the object id
649                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
650                 if (!empty($object_id)) {
651                         $reply[] = $object_id;
652                 }
653
654                 if (!empty($reply)) {
655                         $parents = Post::select(['uid'], ['uri' => $reply]);
656                         while ($parent = Post::fetch($parents)) {
657                                 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
658                         }
659                         DBA::close($parents);
660                 }
661
662                 if (!empty($actor)) {
663                         $profile = APContact::getByURL($actor);
664                         $followers = $profile['followers'] ?? '';
665
666                         Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
667                 } else {
668                         Logger::info('Empty actor', ['activity' => $activity]);
669                         $followers = '';
670                 }
671
672                 // We have to prevent false follower assumptions upon thread completions
673                 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
674
675                 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
676                         $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
677                         if (empty($receiver_list)) {
678                                 continue;
679                         }
680
681                         foreach ($receiver_list as $receiver) {
682                                 if ($receiver == self::PUBLIC_COLLECTION) {
683                                         $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
684                                 }
685
686                                 // Add receiver "-1" for unlisted posts 
687                                 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
688                                         $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
689                                 }
690
691                                 // Fetch the receivers for the public and the followers collection
692                                 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
693                                         $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target);
694                                         continue;
695                                 }
696
697                                 // Fetching all directly addressed receivers
698                                 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
699                                 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
700                                 if (!DBA::isResult($contact)) {
701                                         continue;
702                                 }
703
704                                 // Check if the potential receiver is following the actor
705                                 // Exception: The receiver is targetted via "to" or this is a comment
706                                 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
707                                         $networks = Protocol::FEDERATED;
708                                         $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
709                                                 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
710
711                                         // Forum posts are only accepted from forum contacts
712                                         if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
713                                                 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
714                                         }
715
716                                         if (!DBA::exists('contact', $condition)) {
717                                                 continue;
718                                         }
719                                 }
720
721                                 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
722                                 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
723                                         switch ($element) {
724                                                 case 'as:to':
725                                                         $type = self::TARGET_TO;
726                                                         break;
727                                                 case 'as:cc':
728                                                         $type = self::TARGET_CC;
729                                                         break;
730                                                 case 'as:bto':
731                                                         $type = self::TARGET_BTO;
732                                                         break;
733                                                 case 'as:bcc':
734                                                         $type = self::TARGET_BCC;
735                                                         break;
736                                         }
737
738                                         $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
739                                 }
740                         }
741                 }
742
743                 self::switchContacts($receivers, $actor);
744
745                 return $receivers;
746         }
747
748         /**
749          * Fetch the receiver list of a given actor
750          *
751          * @param string  $actor
752          * @param array   $tags
753          * @param array   $receivers
754          * @param integer $target_type
755          *
756          * @return array with receivers (user id)
757          * @throws \Exception
758          */
759         private static function getReceiverForActor($actor, $tags, $receivers, $target_type)
760         {
761                 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
762                         'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
763
764                 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
765                 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
766                 while ($contact = DBA::fetch($contacts)) {
767                         if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
768                                 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
769                         }
770                 }
771                 DBA::close($contacts);
772
773                 // The queries are split because of performance issues
774                 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
775                 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
776                 while ($contact = DBA::fetch($contacts)) {
777                         if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
778                                 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
779                         }
780                 }
781                 DBA::close($contacts);
782                 return $receivers;
783         }
784
785         /**
786          * Tests if the contact is a valid receiver for this actor
787          *
788          * @param array  $contact
789          * @param string $actor
790          * @param array  $tags
791          *
792          * @return bool with receivers (user id)
793          * @throws \Exception
794          */
795         private static function isValidReceiverForActor($contact, $tags)
796         {
797                 // Are we following the contact? Then this is a valid receiver
798                 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
799                         return true;
800                 }
801
802                 // When the possible receiver isn't a community, then it is no valid receiver
803                 $owner = User::getOwnerDataById($contact['uid']);
804                 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
805                         return false;
806                 }
807
808                 // Is the community account tagged?
809                 foreach ($tags as $tag) {
810                         if ($tag['type'] != 'Mention') {
811                                 continue;
812                         }
813
814                         if (Strings::compareLink($tag['href'], $owner['url'])) {
815                                 return true;
816                         }
817                 }
818
819                 return false;
820         }
821
822         /**
823          * Switches existing contacts to ActivityPub
824          *
825          * @param integer $cid Contact ID
826          * @param integer $uid User ID
827          * @param string  $url Profile URL
828          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
829          * @throws \ImagickException
830          */
831         public static function switchContact($cid, $uid, $url)
832         {
833                 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
834                         Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
835                         return;
836                 }
837
838                 if (Contact::updateFromProbe($cid)) {
839                         Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
840                 }
841
842                 // Send a new follow request to be sure that the connection still exists
843                 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
844                         Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
845                         ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
846                 }
847         }
848
849         /**
850          *
851          *
852          * @param $receivers
853          * @param $actor
854          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
855          * @throws \ImagickException
856          */
857         private static function switchContacts($receivers, $actor)
858         {
859                 if (empty($actor)) {
860                         return;
861                 }
862
863                 foreach ($receivers as $receiver) {
864                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
865                         if (DBA::isResult($contact)) {
866                                 self::switchContact($contact['id'], $receiver['uid'], $actor);
867                         }
868
869                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
870                         if (DBA::isResult($contact)) {
871                                 self::switchContact($contact['id'], $receiver['uid'], $actor);
872                         }
873                 }
874         }
875
876         /**
877          *
878          *
879          * @param       $object_data
880          * @param array $activity
881          *
882          * @return mixed
883          */
884         private static function addActivityFields($object_data, $activity)
885         {
886                 if (!empty($activity['published']) && empty($object_data['published'])) {
887                         $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
888                 }
889
890                 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
891                         $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
892                 }
893
894                 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
895                 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
896
897                 if (!empty($object_data['object_id'])) {
898                         // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
899                         $objectId = Item::getURIByLink($object_data['object_id']);
900                         if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
901                                 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
902                                 $object_data['object_id'] = $objectId;
903                         }
904                 }
905
906                 return $object_data;
907         }
908
909         /**
910          * Fetches the object data from external ressources if needed
911          *
912          * @param string  $object_id    Object ID of the the provided object
913          * @param array   $object       The provided object array
914          * @param boolean $trust_source Do we trust the provided object?
915          * @param integer $uid          User ID for the signature that we use to fetch data
916          *
917          * @return array|false with trusted and valid object data
918          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
919          * @throws \ImagickException
920          */
921         private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
922         {
923                 // By fetching the type we check if the object is complete.
924                 $type = JsonLD::fetchElement($object, '@type');
925
926                 if (!$trust_source || empty($type)) {
927                         $data = ActivityPub::fetchContent($object_id, $uid);
928                         if (!empty($data)) {
929                                 $object = JsonLD::compact($data);
930                                 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
931                         } else {
932                                 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
933
934                                 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
935                                 if (!DBA::isResult($item)) {
936                                         Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
937                                         return false;
938                                 }
939                                 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
940                                 $data = ActivityPub\Transmitter::createNote($item);
941                                 $object = JsonLD::compact($data);
942                         }
943
944                         $id = JsonLD::fetchElement($object, '@id');
945                         if (empty($id)) {
946                                 Logger::info('Empty id');
947                                 return false;
948                         }
949         
950                         if ($id != $object_id) {
951                                 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
952                                 return false;
953                         }
954                 } else {
955                         Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
956                 }
957
958                 $type = JsonLD::fetchElement($object, '@type');
959                 if (empty($type)) {
960                         Logger::info('Empty type');
961                         return false;
962                 }
963
964                 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
965                 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
966                         $object_data = self::processObject($object);
967
968                         if (!empty($data)) {
969                                 $object_data['raw'] = json_encode($data);
970                         }
971                         return $object_data;
972                 }
973
974                 if ($type == 'as:Announce') {
975                         $object_id = JsonLD::fetchElement($object, 'object', '@id');
976                         if (empty($object_id) || !is_string($object_id)) {
977                                 return false;
978                         }
979                         return self::fetchObject($object_id, [], false, $uid);
980                 }
981
982                 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
983                 return false;
984         }
985
986         /**
987          * Converts the language element (Used by Peertube)
988          *
989          * @param array $languages
990          * @return array Languages
991          */
992         public static function processLanguages(array $languages)
993         {
994                 if (empty($languages)) {
995                         return [];
996                 }
997
998                 $language_list = [];
999
1000                 foreach ($languages as $language) {
1001                         if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1002                                 $language_list[$language['_:identifier']] = $language['as:name'];
1003                         }
1004                 }
1005                 return $language_list;
1006         }
1007
1008         /**
1009          * Convert tags from JSON-LD format into a simplified format
1010          *
1011          * @param array $tags Tags in JSON-LD format
1012          *
1013          * @return array with tags in a simplified format
1014          */
1015         public static function processTags(array $tags)
1016         {
1017                 $taglist = [];
1018
1019                 foreach ($tags as $tag) {
1020                         if (empty($tag)) {
1021                                 continue;
1022                         }
1023
1024                         $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1025                                 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1026                                 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1027
1028                         if (empty($element['type'])) {
1029                                 continue;
1030                         }
1031
1032                         if (empty($element['href'])) {
1033                                 $element['href'] = $element['name'];
1034                         }
1035
1036                         $taglist[] = $element;
1037                 }
1038                 return $taglist;
1039         }
1040
1041         /**
1042          * Convert emojis from JSON-LD format into a simplified format
1043          *
1044          * @param array $emojis
1045          * @return array with emojis in a simplified format
1046          */
1047         private static function processEmojis(array $emojis)
1048         {
1049                 $emojilist = [];
1050
1051                 foreach ($emojis as $emoji) {
1052                         if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1053                                 continue;
1054                         }
1055
1056                         $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1057                         $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1058                                 'href' => $url];
1059
1060                         $emojilist[] = $element;
1061                 }
1062
1063                 return $emojilist;
1064         }
1065
1066         /**
1067          * Convert attachments from JSON-LD format into a simplified format
1068          *
1069          * @param array $attachments Attachments in JSON-LD format
1070          *
1071          * @return array Attachments in a simplified format
1072          */
1073         private static function processAttachments(array $attachments)
1074         {
1075                 $attachlist = [];
1076
1077                 // Removes empty values
1078                 $attachments = array_filter($attachments);
1079
1080                 foreach ($attachments as $attachment) {
1081                         switch (JsonLD::fetchElement($attachment, '@type')) {
1082                                 case 'as:Page':
1083                                         $pageUrl = null;
1084                                         $pageImage = null;
1085
1086                                         $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1087                                         foreach ($urls as $url) {
1088                                                 // Single scalar URL case
1089                                                 if (is_string($url)) {
1090                                                         $pageUrl = $url;
1091                                                         continue;
1092                                                 }
1093
1094                                                 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1095                                                 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1096                                                 if (Strings::startsWith($mediaType, 'image')) {
1097                                                         $pageImage = $href;
1098                                                 } else {
1099                                                         $pageUrl = $href;
1100                                                 }
1101                                         }
1102
1103                                         $attachlist[] = [
1104                                                 'type'  => 'link',
1105                                                 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1106                                                 'desc'  => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1107                                                 'url'   => $pageUrl,
1108                                                 'image' => $pageImage,
1109                                         ];
1110                                         break;
1111                                 case 'as:Link':
1112                                         $attachlist[] = [
1113                                                 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1114                                                 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1115                                                 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1116                                                 'url' => JsonLD::fetchElement($attachment, 'as:href', '@id')
1117                                         ];
1118                                         break;
1119                                 case 'as:Image':
1120                                         $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1121                                         $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1122                                         $imagePreviewUrl = null;
1123                                         // Multiple URLs?
1124                                         if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1125                                                 $imageVariants = [];
1126                                                 $previewVariants = [];
1127                                                 foreach ($urls as $url) {
1128                                                         // Scalar URL, no discrimination possible
1129                                                         if (is_string($url)) {
1130                                                                 $imageFullUrl = $url;
1131                                                                 continue;
1132                                                         }
1133
1134                                                         // Not sure what to do with a different Link media type than the base Image, we skip
1135                                                         if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1136                                                                 continue;
1137                                                         }
1138
1139                                                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1140
1141                                                         // Default URL choice if no discriminating width is provided
1142                                                         $imageFullUrl = $href ?? $imageFullUrl;
1143
1144                                                         $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1145
1146                                                         if ($href && $width) {
1147                                                                 $imageVariants[$width] = $href;
1148                                                                 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1149                                                                 $previewVariants[abs(632 - $width)] = $href;
1150                                                         }
1151                                                 }
1152
1153                                                 if ($imageVariants) {
1154                                                         // Taking the maximum size image
1155                                                         ksort($imageVariants);
1156                                                         $imageFullUrl = array_pop($imageVariants);
1157
1158                                                         // Taking the minimum number distance to the target distance
1159                                                         ksort($previewVariants);
1160                                                         $imagePreviewUrl = array_shift($previewVariants);
1161                                                 }
1162
1163                                                 unset($imageVariants);
1164                                                 unset($previewVariants);
1165                                         }
1166
1167                                         $attachlist[] = [
1168                                                 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1169                                                 'mediaType' => $mediaType,
1170                                                 'name'  => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1171                                                 'url'   => $imageFullUrl,
1172                                                 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1173                                         ];
1174                                         break;
1175                                 default:
1176                                         $attachlist[] = [
1177                                                 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1178                                                 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1179                                                 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1180                                                 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')
1181                                         ];
1182                         }
1183                 }
1184
1185                 return $attachlist;
1186         }
1187
1188         /**
1189          * Fetch the original source or content with the "language" Markdown or HTML
1190          *
1191          * @param array $object
1192          * @param array $object_data
1193          *
1194          * @return array
1195          * @throws \Exception
1196          */
1197         private static function getSource($object, $object_data)
1198         {
1199                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1200                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1201                 if (!empty($object_data['source'])) {
1202                         return $object_data;
1203                 }
1204
1205                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1206                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1207                 if (!empty($object_data['source'])) {
1208                         $object_data['source'] = Markdown::toBBCode($object_data['source']);
1209                         return $object_data;
1210                 }
1211
1212                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1213                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1214                 if (!empty($object_data['source'])) {
1215                         $object_data['source'] = HTML::toBBCode($object_data['source']);
1216                         return $object_data;
1217                 }
1218
1219                 return $object_data;
1220         }
1221
1222         /**
1223          * Check if the "as:url" element is an array with multiple links
1224          * This is the case with audio and video posts.
1225          * Then the links are added as attachments
1226          *
1227          * @param array $object      The raw object
1228          * @param array $object_data The parsed object data for later processing
1229          * @return array the object data
1230          */
1231         private static function processAttachmentUrls(array $object, array $object_data) {
1232                 // Check if this is some url with multiple links
1233                 if (empty($object['as:url'])) {
1234                         return $object_data;
1235                 }
1236                 
1237                 $urls = $object['as:url'];
1238                 $keys = array_keys($urls);
1239                 if (!is_numeric(array_pop($keys))) {
1240                         return $object_data;
1241                 }
1242
1243                 $attachments = [];
1244
1245                 foreach ($urls as $url) {
1246                         if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1247                                 continue;
1248                         }
1249
1250                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1251                         if (empty($href)) {
1252                                 continue;
1253                         }
1254
1255                         $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1256                         if (empty($mediatype)) {
1257                                 continue;
1258                         }
1259
1260                         if ($mediatype == 'text/html') {
1261                                 $object_data['alternate-url'] = $href;
1262                         }
1263
1264                         $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1265
1266                         if ($filetype == 'audio') {
1267                                 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => null, 'size' => null];
1268                         } elseif ($filetype == 'video') {
1269                                 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1270                                 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1271
1272                                 // We save bandwidth by using a moderate height (alt least 480 pixel height)
1273                                 // Peertube normally uses these heights: 240, 360, 480, 720, 1080
1274                                 if (!empty($attachments[$filetype]['height']) &&
1275                                         ($height > $attachments[$filetype]['height']) && ($attachments[$filetype]['height'] >= 480)) {
1276                                         continue;
1277                                 }
1278
1279                                 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size];
1280                         } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1281                                 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1282
1283                                 // For Torrent links we always store the highest resolution
1284                                 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1285                                         continue;
1286                                 }
1287
1288                                 $attachments[$mediatype] = ['type' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null];
1289                         }
1290                 }
1291
1292                 foreach ($attachments as $type => $attachment) {
1293                         $object_data['attachments'][] = ['type' => $type,
1294                                 'mediaType' => $attachment['type'],
1295                                 'height' => $attachment['height'],
1296                                 'size' => $attachment['size'],
1297                                 'name' => '',
1298                                 'url' => $attachment['url']];
1299                 }
1300                 return $object_data;
1301         }
1302
1303         /**
1304          * Fetches data from the object part of an activity
1305          *
1306          * @param array $object
1307          *
1308          * @return array
1309          * @throws \Exception
1310          */
1311         private static function processObject($object)
1312         {
1313                 if (!JsonLD::fetchElement($object, '@id')) {
1314                         return false;
1315                 }
1316
1317                 $object_data = [];
1318                 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1319                 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1320                 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1321
1322                 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1323                 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1324                         $object_data['reply-to-id'] = $object_data['id'];
1325                 } else {
1326                         // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1327                         $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1328                         if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1329                                 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1330                                 $object_data['reply-to-id'] = $replyToId;
1331                         }
1332                 }
1333
1334                 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1335                 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1336
1337                 if (empty($object_data['updated'])) {
1338                         $object_data['updated'] = $object_data['published'];
1339                 }
1340
1341                 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1342                         $object_data['published'] = $object_data['updated'];
1343                 }
1344
1345                 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1346                 if (empty($actor)) {
1347                         $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1348                 }
1349
1350                 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1351                 $location = JsonLD::fetchElement($location, 'location', '@value');
1352                 if ($location) {
1353                         // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1354                         // down to HTML and then finally format to plaintext.
1355                         $location = Markdown::convert($location);
1356                         $location = BBCode::convert($location);
1357                         $location = HTML::toPlaintext($location);
1358                 }
1359
1360                 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1361                 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1362                 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1363                 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1364                 $object_data['actor'] = $object_data['author'] = $actor;
1365                 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1366                 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1367                 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1368                 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1369                 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1370                 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1371                 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1372                 $object_data = self::getSource($object, $object_data);
1373                 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1374                 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1375                 $object_data['location'] = $location;
1376                 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1377                 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1378                 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1379                 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1380                 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1381                 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1382                 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1383                 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1384                 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1385                 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1386                 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1387
1388                 // Special treatment for Hubzilla links
1389                 if (is_array($object_data['alternate-url'])) {
1390                         $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1391
1392                         if (!is_string($object_data['alternate-url'])) {
1393                                 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1394                         }
1395                 }
1396
1397                 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1398                         $object_data = self::processAttachmentUrls($object, $object_data);
1399                 }
1400
1401                 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1402                 $receivers = $reception_types = [];
1403                 foreach ($receiverdata as $key => $data) {
1404                         $receivers[$key] = $data['uid'];
1405                         $reception_types[$data['uid']] = $data['type'] ?? 0;
1406                 }
1407
1408                 $object_data['receiver'] = $receivers;
1409                 $object_data['reception_type'] = $reception_types;
1410
1411                 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1412                 unset($object_data['receiver'][-1]);
1413                 unset($object_data['reception_type'][-1]);
1414
1415                 // Common object data:
1416
1417                 // Unhandled
1418                 // @context, type, actor, signature, mediaType, duration, replies, icon
1419
1420                 // Also missing: (Defined in the standard, but currently unused)
1421                 // audience, preview, endTime, startTime, image
1422
1423                 // Data in Notes:
1424
1425                 // Unhandled
1426                 // contentMap, announcement_count, announcements, context_id, likes, like_count
1427                 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1428
1429                 // Data in video:
1430
1431                 // To-Do?
1432                 // category, licence, language, commentsEnabled
1433
1434                 // Unhandled
1435                 // views, waitTranscoding, state, support, subtitleLanguage
1436                 // likes, dislikes, shares, comments
1437
1438                 return $object_data;
1439         }
1440 }