]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub.php
85d21d7cbaf5a28ccb35480ffb7a2ef9a55551c4
[friendica.git] / src / Protocol / ActivityPub.php
1 <?php
2 /**
3  * @file src/Protocol/ActivityPub.php
4  */
5 namespace Friendica\Protocol;
6
7 use Friendica\Database\DBA;
8 use Friendica\Core\System;
9 use Friendica\BaseObject;
10 use Friendica\Util\Network;
11 use Friendica\Util\HTTPSignature;
12 use Friendica\Core\Protocol;
13 use Friendica\Model\Conversation;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Item;
16 use Friendica\Model\User;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Crypto;
19 use Friendica\Content\Text\BBCode;
20 use Friendica\Content\Text\HTML;
21 use Friendica\Network\Probe;
22
23 /**
24  * @brief ActivityPub Protocol class
25  * The ActivityPub Protocol is a message exchange protocol defined by the W3C.
26  * https://www.w3.org/TR/activitypub/
27  * https://www.w3.org/TR/activitystreams-core/
28  * https://www.w3.org/TR/activitystreams-vocabulary/
29  *
30  * https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/
31  * https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
32  *
33  * Digest: https://tools.ietf.org/html/rfc5843
34  * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
35  *
36  * Part of the code for HTTP signing is taken from the Osada project.
37  * https://framagit.org/macgirvin/osada
38  *
39  * To-do:
40  *
41  * Receiver:
42  * - Activities: Dislike, Update, Delete
43  * - Object Types: Person, Tombstome
44  *
45  * Transmitter:
46  * - Activities: Like, Dislike, Update, Delete
47  * - Object Tyoes: Article, Announce, Person, Tombstone
48  *
49  * General:
50  * - Message distribution
51  * - Endpoints: Outbox, Object, Follower, Following
52  * - General cleanup
53  */
54 class ActivityPub
55 {
56         const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
57
58         public static function transmit($data, $target, $uid)
59         {
60                 $owner = User::getOwnerDataById($uid);
61
62                 if (!$owner) {
63                         return;
64                 }
65
66                 $content = json_encode($data);
67
68                 $host = parse_url($target, PHP_URL_HOST);
69                 $path = parse_url($target, PHP_URL_PATH);
70                 $date = date('r');
71
72                 $headers = ['Host: ' . $host, 'Date: ' . $date];
73
74                 $signed_data = "(request-target): post " . $path . "\nhost: " . $host . "\ndate: " . $date;
75
76                 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
77
78                 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",headers="(request-target) host date",signature="' . $signature . '"';
79                 $headers[] = 'Content-Type: application/activity+json';
80
81                 Network::post($target, $content, $headers);
82                 $return_code = BaseObject::getApp()->get_curl_code();
83
84                 logger('Transmit to ' . $target . ' returned ' . $return_code);
85         }
86
87         /**
88          * Return the ActivityPub profile of the given user
89          *
90          * @param integer $uid User ID
91          * @return array
92          */
93         public static function profile($uid)
94         {
95                 $accounttype = ['Person', 'Organization', 'Service', 'Group', 'Application'];
96
97                 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
98                         'account_removed' => false, 'verified' => true];
99                 $fields = ['guid', 'nickname', 'pubkey', 'account-type'];
100                 $user = DBA::selectFirst('user', $fields, $condition);
101                 if (!DBA::isResult($user)) {
102                         return [];
103                 }
104
105                 $fields = ['locality', 'region', 'country-name'];
106                 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
107                 if (!DBA::isResult($profile)) {
108                         return [];
109                 }
110
111                 $fields = ['name', 'url', 'location', 'about', 'avatar'];
112                 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
113                 if (!DBA::isResult($contact)) {
114                         return [];
115                 }
116
117                 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
118                         ['uuid' => 'http://schema.org/identifier', 'sensitive' => 'as:sensitive',
119                         'vcard' => 'http://www.w3.org/2006/vcard/ns#']]];
120
121                 $data['id'] = $contact['url'];
122                 $data['uuid'] = $user['guid'];
123                 $data['type'] = $accounttype[$user['account-type']];
124                 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
125                 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
126                 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
127                 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
128                 $data['preferredUsername'] = $user['nickname'];
129                 $data['name'] = $contact['name'];
130                 $data['vcard:hasAddress'] = ['@type' => 'Home', 'vcard:country-name' => $profile['country-name'],
131                         'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
132                 $data['summary'] = $contact['about'];
133                 $data['url'] = $contact['url'];
134                 $data['manuallyApprovesFollowers'] = false;
135                 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
136                         'owner' => $contact['url'],
137                         'publicKeyPem' => $user['pubkey']];
138                 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
139                 $data['icon'] = ['type' => 'Image',
140                         'url' => $contact['avatar']];
141
142                 // tags: https://kitty.town/@inmysocks/100656097926961126.json
143                 return $data;
144         }
145
146         public static function createActivityFromItem($item_id)
147         {
148                 $item = Item::selectFirst([], ['id' => $item_id]);
149
150                 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
151                         ['Emoji' => 'toot:Emoji', 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
152                         'conversation' => 'ostatus:conversation', 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri',
153                         'ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
154                         'toot' => 'http://joinmastodon.org/ns#']]];
155
156                 $data['type'] = 'Create';
157                 $data['id'] = $item['uri'];
158                 $data['actor'] = $item['author-link'];
159                 $data['to'] = 'https://www.w3.org/ns/activitystreams#Public';
160                 $data['object'] = self::createNote($item);
161                 return $data;
162         }
163
164         public static function createNote($item)
165         {
166                 $data = [];
167                 $data['type'] = 'Note';
168                 $data['id'] = $item['uri'];
169
170                 if ($item['uri'] != $item['thr-parent']) {
171                         $data['inReplyTo'] = $item['thr-parent'];
172                 }
173
174                 $conversation = DBA::selectFirst('conversation', ['conversation-uri'], ['item-uri' => $item['parent-uri']]);
175                 if (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
176                         $conversation_uri = $conversation['conversation-uri'];
177                 } else {
178                         $conversation_uri = $item['parent-uri'];
179                 }
180
181                 $data['context'] = $data['conversation'] = $conversation_uri;
182                 $data['actor'] = $item['author-link'];
183                 $data['to'] = [];
184                 if (!$item['private']) {
185                         $data['to'][] = 'https://www.w3.org/ns/activitystreams#Public';
186                 }
187                 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
188                 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
189                 $data['attributedTo'] = $item['author-link'];
190                 $data['name'] = BBCode::convert($item['title'], false, 7);
191                 $data['content'] = BBCode::convert($item['body'], false, 7);
192                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
193                 //$data['summary'] = ''; // Ignore by now
194                 //$data['sensitive'] = false; // - Query NSFW
195                 //$data['emoji'] = []; // Ignore by now
196                 //$data['tag'] = []; /// @ToDo
197                 //$data['attachment'] = []; // @ToDo
198                 return $data;
199         }
200
201         public static function transmitActivity($activity, $target, $uid)
202         {
203                 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
204
205                 $owner = User::getOwnerDataById($uid);
206
207                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
208                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
209                         'type' => $activity,
210                         'actor' => $owner['url'],
211                         'object' => $profile['url']];
212
213                 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
214                 return self::transmit($data,  $profile['notify'], $uid);
215         }
216
217         public static function transmitContactAccept($target, $id, $uid)
218         {
219                 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
220
221                 $owner = User::getOwnerDataById($uid);
222                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
223                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
224                         'type' => 'Accept',
225                         'actor' => $owner['url'],
226                         'object' => ['id' => $id, 'type' => 'Follow',
227                                 'actor' => $profile['url'],
228                                 'object' => $owner['url']]];
229
230                 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
231                 return self::transmit($data,  $profile['notify'], $uid);
232         }
233
234         public static function transmitContactReject($target, $id, $uid)
235         {
236                 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
237
238                 $owner = User::getOwnerDataById($uid);
239                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
240                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
241                         'type' => 'Reject',
242                         'actor' => $owner['url'],
243                         'object' => ['id' => $id, 'type' => 'Follow',
244                                 'actor' => $profile['url'],
245                                 'object' => $owner['url']]];
246
247                 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
248                 return self::transmit($data,  $profile['notify'], $uid);
249         }
250
251         public static function transmitContactUndo($target, $uid)
252         {
253                 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
254
255                 $id = System::baseUrl() . '/activity/' . System::createGUID();
256
257                 $owner = User::getOwnerDataById($uid);
258                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
259                         'id' => $id,
260                         'type' => 'Undo',
261                         'actor' => $owner['url'],
262                         'object' => ['id' => $id, 'type' => 'Follow',
263                                 'actor' => $owner['url'],
264                                 'object' => $profile['url']]];
265
266                 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
267                 return self::transmit($data,  $profile['notify'], $uid);
268         }
269
270         /**
271          * Fetches ActivityPub content from the given url
272          *
273          * @param string $url content url
274          * @return array
275          */
276         public static function fetchContent($url)
277         {
278                 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json']);
279
280                 if (!$ret['success'] || empty($ret['body'])) {
281                         return;
282                 }
283
284                 return json_decode($ret['body'], true);
285         }
286
287         /**
288          * Resolves the profile url from the address by using webfinger
289          *
290          * @param string $addr profile address (user@domain.tld)
291          * @return string url
292          */
293         private static function addrToUrl($addr)
294         {
295                 $addr_parts = explode('@', $addr);
296                 if (count($addr_parts) != 2) {
297                         return false;
298                 }
299
300                 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
301
302                 $ret = Network::curl($webfinger, false, $redirects, ['accept_content' => 'application/jrd+json,application/json']);
303                 if (!$ret['success'] || empty($ret['body'])) {
304                         return false;
305                 }
306
307                 $data = json_decode($ret['body'], true);
308
309                 if (empty($data['links'])) {
310                         return false;
311                 }
312
313                 foreach ($data['links'] as $link) {
314                         if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
315                                 continue;
316                         }
317
318                         if (($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
319                                 return $link['href'];
320                         }
321                 }
322
323                 return false;
324         }
325
326         public static function verifySignature($content, $http_headers)
327         {
328                 $object = json_decode($content, true);
329
330                 if (empty($object)) {
331                         return false;
332                 }
333
334                 $actor = self::processElement($object, 'actor', 'id');
335
336                 $headers = [];
337                 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
338
339                 // First take every header
340                 foreach ($http_headers as $k => $v) {
341                         $field = str_replace('_', '-', strtolower($k));
342                         $headers[$field] = $v;
343                 }
344
345                 // Now add every http header
346                 foreach ($http_headers as $k => $v) {
347                         if (strpos($k, 'HTTP_') === 0) {
348                                 $field = str_replace('_', '-', strtolower(substr($k, 5)));
349                                 $headers[$field] = $v;
350                         }
351                 }
352
353                 $sig_block = ActivityPub::parseSigHeader($http_headers['HTTP_SIGNATURE']);
354
355                 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
356                         return false;
357                 }
358
359                 $signed_data = '';
360                 foreach ($sig_block['headers'] as $h) {
361                         if (array_key_exists($h, $headers)) {
362                                 $signed_data .= $h . ': ' . $headers[$h] . "\n";
363                         }
364                 }
365                 $signed_data = rtrim($signed_data, "\n");
366
367                 if (empty($signed_data)) {
368                         return false;
369                 }
370
371                 $algorithm = null;
372
373                 if ($sig_block['algorithm'] === 'rsa-sha256') {
374                         $algorithm = 'sha256';
375                 }
376
377                 if ($sig_block['algorithm'] === 'rsa-sha512') {
378                         $algorithm = 'sha512';
379                 }
380
381                 if (empty($algorithm)) {
382                         return false;
383                 }
384
385                 $key = self::fetchKey($sig_block['keyId'], $actor);
386
387                 if (empty($key)) {
388                         return false;
389                 }
390
391                 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm)) {
392                         return false;
393                 }
394
395                 // Check the digest if it was part of the signed data
396                 if (in_array('digest', $sig_block['headers'])) {
397                         $digest = explode('=', $headers['digest'], 2);
398                         if ($digest[0] === 'SHA-256') {
399                                 $hashalg = 'sha256';
400                         }
401                         if ($digest[0] === 'SHA-512') {
402                                 $hashalg = 'sha512';
403                         }
404
405                         /// @todo add all hashes from the rfc
406
407                         if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
408                                 return false;
409                         }
410                 }
411
412                 // Check the content-length if it was part of the signed data
413                 if (in_array('content-length', $sig_block['headers'])) {
414                         if (strlen($content) != $headers['content-length']) {
415                                 return false;
416                         }
417                 }
418
419                 return true;
420
421         }
422
423         private static function fetchKey($id, $actor)
424         {
425                 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
426
427                 $profile = Probe::uri($url, Protocol::ACTIVITYPUB);
428                 if (!empty($profile)) {
429                         return $profile['pubkey'];
430                 } elseif ($url != $actor) {
431                         $profile = Probe::uri($actor, Protocol::ACTIVITYPUB);
432                         if (!empty($profile)) {
433                                 return $profile['pubkey'];
434                         }
435                 }
436
437                 return false;
438         }
439
440         /**
441          * @brief
442          *
443          * @param string $header
444          * @return array associate array with
445          *   - \e string \b keyID
446          *   - \e string \b algorithm
447          *   - \e array  \b headers
448          *   - \e string \b signature
449          */
450         private static function parseSigHeader($header)
451         {
452                 $ret = [];
453                 $matches = [];
454
455                 if (preg_match('/keyId="(.*?)"/ism',$header,$matches)) {
456                         $ret['keyId'] = $matches[1];
457                 }
458
459                 if (preg_match('/algorithm="(.*?)"/ism',$header,$matches)) {
460                         $ret['algorithm'] = $matches[1];
461                 }
462
463                 if (preg_match('/headers="(.*?)"/ism',$header,$matches)) {
464                         $ret['headers'] = explode(' ', $matches[1]);
465                 }
466
467                 if (preg_match('/signature="(.*?)"/ism',$header,$matches)) {
468                         $ret['signature'] = base64_decode(preg_replace('/\s+/','',$matches[1]));
469                 }
470
471                 return $ret;
472         }
473
474         /**
475          * Fetches a profile from the given url
476          *
477          * @param string $url profile url
478          * @return array
479          */
480         public static function fetchProfile($url)
481         {
482                 if (empty(parse_url($url, PHP_URL_SCHEME))) {
483                         $url = self::addrToUrl($url);
484                         if (empty($url)) {
485                                 return false;
486                         }
487                 }
488
489                 $data = self::fetchContent($url);
490
491                 if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
492                         return false;
493                 }
494
495                 $profile = ['network' => Protocol::ACTIVITYPUB];
496                 $profile['nick'] = $data['preferredUsername'];
497                 $profile['name'] = defaults($data, 'name', $profile['nick']);
498                 $profile['guid'] = defaults($data, 'uuid', null);
499                 $profile['url'] = $data['id'];
500
501                 $parts = parse_url($profile['url']);
502                 unset($parts['scheme']);
503                 unset($parts['path']);
504                 $profile['addr'] = $profile['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
505                 $profile['alias'] = self::processElement($data, 'url', 'href');
506                 $profile['photo'] = self::processElement($data, 'icon', 'url');
507                 // $profile['community']
508                 // $profile['keywords']
509                 // $profile['location']
510                 $profile['about'] = defaults($data, 'summary', '');
511                 $profile['batch'] = self::processElement($data, 'endpoints', 'sharedInbox');
512                 $profile['notify'] = $data['inbox'];
513                 $profile['poll'] = $data['outbox'];
514                 $profile['pubkey'] = self::processElement($data, 'publicKey', 'publicKeyPem');
515
516                 // Check if the address is resolvable
517                 if (self::addrToUrl($profile['addr']) == $profile['url']) {
518                         $parts = parse_url($profile['url']);
519                         unset($parts['path']);
520                         $profile['baseurl'] = Network::unparseURL($parts);
521                 } else {
522                         unset($profile['addr']);
523                 }
524
525                 if ($profile['url'] == $profile['alias']) {
526                         unset($profile['alias']);
527                 }
528
529                 // Remove all "null" fields
530                 foreach ($profile as $field => $content) {
531                         if (is_null($content)) {
532                                 unset($profile[$field]);
533                         }
534                 }
535
536 /*
537                 // To-Do
538                 unset($data['type']);
539                 unset($data['manuallyApprovesFollowers']);
540
541                 // Unhandled
542                 unset($data['@context']);
543                 unset($data['tag']);
544                 unset($data['attachment']);
545                 unset($data['image']);
546                 unset($data['nomadicLocations']);
547                 unset($data['signature']);
548                 unset($data['following']);
549                 unset($data['followers']);
550                 unset($data['featured']);
551                 unset($data['movedTo']);
552                 unset($data['liked']);
553                 unset($data['sharedInbox']); // Misskey
554                 unset($data['isCat']); // Misskey
555                 unset($data['kroeg:blocks']); // Kroeg
556                 unset($data['updated']); // Kroeg
557 */
558                 return $profile;
559         }
560
561         public static function processInbox($body, $header, $uid)
562         {
563                 logger('Incoming message for user ' . $uid, LOGGER_DEBUG);
564
565                 if (!self::verifySignature($body, $header)) {
566                         logger('Invalid signature, message will be discarded.', LOGGER_DEBUG);
567                         return;
568                 }
569
570                 $activity = json_decode($body, true);
571
572                 if (!is_array($activity)) {
573                         logger('Invalid body.', LOGGER_DEBUG);
574                         return;
575                 }
576
577                 self::processActivity($activity, $body, $uid);
578         }
579
580         public static function fetchOutbox($url)
581         {
582                 $data = self::fetchContent($url);
583                 if (empty($data)) {
584                         return;
585                 }
586
587                 if (!empty($data['orderedItems'])) {
588                         $items = $data['orderedItems'];
589                 } elseif (!empty($data['first']['orderedItems'])) {
590                         $items = $data['first']['orderedItems'];
591                 } elseif (!empty($data['first'])) {
592                         self::fetchOutbox($data['first']);
593                         return;
594                 } else {
595                         $items = [];
596                 }
597
598                 foreach ($items as $activity) {
599                         self::processActivity($activity);
600                 }
601         }
602
603         function processActivity($activity, $body = '', $uid = null)
604         {
605                 if (empty($activity['type'])) {
606                         logger('Empty type', LOGGER_DEBUG);
607                         return;
608                 }
609
610                 if (empty($activity['object'])) {
611                         logger('Empty object', LOGGER_DEBUG);
612                         return;
613                 }
614
615                 if (empty($activity['actor'])) {
616                         logger('Empty actor', LOGGER_DEBUG);
617                         return;
618
619                 }
620
621                 $actor = self::processElement($activity, 'actor', 'id');
622                 if (empty($actor)) {
623                         logger('Empty actor - 2', LOGGER_DEBUG);
624                         return;
625                 }
626
627                 if (is_string($activity['object'])) {
628                         $object_url = $activity['object'];
629                 } elseif (!empty($activity['object']['id'])) {
630                         $object_url = $activity['object']['id'];
631                 } else {
632                         logger('No object found', LOGGER_DEBUG);
633                         return;
634                 }
635
636                 // ----------------------------------
637 /*
638                 // unhandled
639                 unset($activity['@context']);
640                 unset($activity['id']);
641
642                 // Non standard
643                 unset($activity['title']);
644                 unset($activity['atomUri']);
645                 unset($activity['context_id']);
646                 unset($activity['statusnetConversationId']);
647
648                 // To-Do?
649                 unset($activity['context']);
650                 unset($activity['location']);
651                 unset($activity['signature']);
652 */
653                 // Fetch all receivers from to, cc, bto and bcc
654                 $receivers = self::getReceivers($activity);
655
656                 // When it is a delivery to a personal inbox we add that user to the receivers
657                 if (!empty($uid)) {
658                         $owner = User::getOwnerDataById($uid);
659                         $additional = [$owner['url'] => $uid];
660                         $receivers = array_merge($receivers, $additional);
661                 }
662
663                 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
664
665                 logger('Processing activity: ' . $activity['type'], LOGGER_DEBUG);
666
667                 // Fetch the content only on activities where this matters
668                 if (in_array($activity['type'], ['Create', 'Update', 'Announce'])) {
669                         $item = self::fetchObject($object_url, $activity['object']);
670                         if (empty($item)) {
671                                 logger("Object data couldn't be processed", LOGGER_DEBUG);
672                                 return;
673                         }
674                 } else {
675                         if (in_array($activity['type'], ['Accept'])) {
676                                 $item['object'] = self::processElement($activity, 'object', 'actor', 'type', 'Follow');
677                         } elseif (in_array($activity['type'], ['Undo'])) {
678                                 $item['object'] = self::processElement($activity, 'object', 'object', 'type', 'Follow');
679                         } else {
680                                 $item['uri'] = $activity['id'];
681                                 $item['author'] = $activity['actor'];
682                                 $item['updated'] = $item['published'] = $activity['published'];
683                                 $item['uuid'] = '';
684                                 $item['name'] = $activity['type'];
685                                 $item['summary'] = '';
686                                 $item['content'] = '';
687                                 $item['location'] = '';
688                                 $item['tags'] = [];
689                                 $item['sensitive'] = false;
690                                 $item['service'] = '';
691                                 $item['attachments'] = [];
692                                 $item['conversation'] = '';
693                                 $item['object'] = $object_url;
694                         }
695                         $item['id'] = $activity['id'];
696                         $item['receiver'] = [];
697                         $item['type'] = $activity['type'];
698                 }
699
700                 $item = self::addActivityFields($item, $activity);
701
702                 $item['owner'] = $actor;
703
704                 $item['receiver'] = array_merge($item['receiver'], $receivers);
705
706                 switch ($activity['type']) {
707                         case 'Create':
708                         case 'Update':
709                         case 'Announce':
710                                 self::createItem($item, $body);
711                                 break;
712
713                         case 'Like':
714                                 self::likeItem($item, $body);
715                                 break;
716
717                         case 'Dislike':
718                                 break;
719
720                         case 'Delete':
721                                 break;
722
723                         case 'Follow':
724                                 self::followUser($item);
725                                 break;
726
727                         case 'Accept':
728                                 self::acceptFollowUser($item);
729                                 break;
730
731                         case 'Undo':
732                                 self::undoFollowUser($item);
733                                 break;
734
735                         default:
736                                 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
737                                 break;
738                 }
739         }
740
741         private static function getReceivers($activity)
742         {
743                 $receivers = [];
744
745                 $elements = ['to', 'cc', 'bto', 'bcc'];
746                 foreach ($elements as $element) {
747                         if (empty($activity[$element])) {
748                                 continue;
749                         }
750
751                         // The receiver can be an arror or a string
752                         if (is_string($activity[$element])) {
753                                 $activity[$element] = [$activity[$element]];
754                         }
755
756                         foreach ($activity[$element] as $receiver) {
757                                 if ($receiver == self::PUBLIC) {
758                                         $receivers[$receiver] = 0;
759                                 }
760
761                                 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
762                                 $contact = DBA::selectFirst('contact', ['uid'], $condition);
763                                 if (!DBA::isResult($contact)) {
764                                         continue;
765                                 }
766                                 $receivers[$receiver] = $contact['uid'];
767                         }
768                 }
769                 return $receivers;
770         }
771
772         private static function addActivityFields($item, $activity)
773         {
774                 if (!empty($activity['published']) && empty($item['published'])) {
775                         $item['published'] = $activity['published'];
776                 }
777
778                 if (!empty($activity['updated']) && empty($item['updated'])) {
779                         $item['updated'] = $activity['updated'];
780                 }
781
782                 if (!empty($activity['inReplyTo']) && empty($item['parent-uri'])) {
783                         $item['parent-uri'] = self::processElement($activity, 'inReplyTo', 'id');
784                 }
785
786                 if (!empty($activity['instrument'])) {
787                         $item['service'] = self::processElement($activity, 'instrument', 'name', 'type', 'Service');
788                 }
789                 return $item;
790         }
791
792         private static function fetchObject($object_url, $object = [])
793         {
794                 $data = self::fetchContent($object_url);
795                 if (empty($data)) {
796                         $data = $object;
797                         if (empty($data)) {
798                                 logger('Empty content', LOGGER_DEBUG);
799                                 return false;
800                         } elseif (is_string($data)) {
801                                 logger('No object array provided.', LOGGER_DEBUG);
802                                 $item = Item::selectFirst([], ['uri' => $data]);
803                                 if (!DBA::isResult($item)) {
804                                         logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
805                                         return false;
806                                 }
807                                 logger('Using already stored item', LOGGER_DEBUG);
808                                 $data = self::createNote($item);
809                         } else {
810                                 logger('Using provided object', LOGGER_DEBUG);
811                         }
812                 }
813
814                 if (empty($data['type'])) {
815                         logger('Empty type', LOGGER_DEBUG);
816                         return false;
817                 } else {
818                         $type = $data['type'];
819                         logger('Type ' . $type, LOGGER_DEBUG);
820                 }
821
822                 if (in_array($type, ['Note', 'Article', 'Video'])) {
823                         $common = self::processCommonData($data);
824                 }
825
826                 switch ($type) {
827                         case 'Note':
828                                 return array_merge($common, self::processNote($data));
829                         case 'Article':
830                                 return array_merge($common, self::processArticle($data));
831                         case 'Video':
832                                 return array_merge($common, self::processVideo($data));
833
834                         case 'Announce':
835                                 if (empty($data['object'])) {
836                                         return false;
837                                 }
838                                 return self::fetchObject($data['object']);
839
840                         case 'Person':
841                         case 'Tombstone':
842                                 break;
843
844                         default:
845                                 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
846                                 break;
847                 }
848         }
849
850         private static function processCommonData(&$object)
851         {
852                 if (empty($object['id']) || empty($object['attributedTo'])) {
853                         return false;
854                 }
855
856                 $item = [];
857                 $item['type'] = $object['type'];
858                 $item['uri'] = $object['id'];
859
860                 if (!empty($object['inReplyTo'])) {
861                         $item['reply-to-uri'] = self::processElement($object, 'inReplyTo', 'id');
862                 } else {
863                         $item['reply-to-uri'] = $item['uri'];
864                 }
865
866                 $item['published'] = defaults($object, 'published', null);
867                 $item['updated'] = defaults($object, 'updated', $item['published']);
868
869                 if (empty($item['published']) && !empty($item['updated'])) {
870                         $item['published'] = $item['updated'];
871                 }
872
873                 $item['uuid'] = defaults($object, 'uuid', null);
874                 $item['owner'] = $item['author'] = self::processElement($object, 'attributedTo', 'id');
875                 $item['context'] = defaults($object, 'context', null);
876                 $item['conversation'] = defaults($object, 'conversation', null);
877                 $item['sensitive'] = defaults($object, 'sensitive', null);
878                 $item['name'] = defaults($object, 'title', null);
879                 $item['name'] = defaults($object, 'name', $item['name']);
880                 $item['summary'] = defaults($object, 'summary', null);
881                 $item['content'] = defaults($object, 'content', null);
882                 $item['source'] = defaults($object, 'source', null);
883                 $item['location'] = self::processElement($object, 'location', 'name', 'type', 'Place');
884                 $item['attachments'] = defaults($object, 'attachment', null);
885                 $item['tags'] = defaults($object, 'tag', null);
886                 $item['service'] = self::processElement($object, 'instrument', 'name', 'type', 'Service');
887                 $item['alternate-url'] = self::processElement($object, 'url', 'href');
888                 $item['receiver'] = self::getReceivers($object);
889
890 /*
891                 // To-Do
892                 unset($object['source']);
893
894                 // Unhandled
895                 unset($object['@context']);
896                 unset($object['type']);
897                 unset($object['actor']);
898                 unset($object['signature']);
899                 unset($object['mediaType']);
900                 unset($object['duration']);
901                 unset($object['replies']);
902                 unset($object['icon']);
903
904                 // Also missing:
905                 audience, preview, endTime, startTime, generator, image
906 */
907                 return $item;
908         }
909
910         private static function processNote($object)
911         {
912                 $item = [];
913
914 /*
915                 // To-Do?
916                 unset($object['emoji']);
917                 unset($object['atomUri']);
918                 unset($object['inReplyToAtomUri']);
919
920                 // Unhandled
921                 unset($object['contentMap']);
922                 unset($object['announcement_count']);
923                 unset($object['announcements']);
924                 unset($object['context_id']);
925                 unset($object['likes']);
926                 unset($object['like_count']);
927                 unset($object['inReplyToStatusId']);
928                 unset($object['shares']);
929                 unset($object['quoteUrl']);
930                 unset($object['statusnetConversationId']);
931 */
932                 return $item;
933         }
934
935         private static function processArticle($object)
936         {
937                 $item = [];
938
939                 return $item;
940         }
941
942         private static function processVideo($object)
943         {
944                 $item = [];
945 /*
946                 // To-Do?
947                 unset($object['category']);
948                 unset($object['licence']);
949                 unset($object['language']);
950                 unset($object['commentsEnabled']);
951
952                 // Unhandled
953                 unset($object['views']);
954                 unset($object['waitTranscoding']);
955                 unset($object['state']);
956                 unset($object['support']);
957                 unset($object['subtitleLanguage']);
958                 unset($object['likes']);
959                 unset($object['dislikes']);
960                 unset($object['shares']);
961                 unset($object['comments']);
962 */
963                 return $item;
964         }
965
966         private static function processElement($array, $element, $key, $type = null, $type_value = null)
967         {
968                 if (empty($array)) {
969                         return false;
970                 }
971
972                 if (empty($array[$element])) {
973                         return false;
974                 }
975
976                 if (is_string($array[$element])) {
977                         return $array[$element];
978                 }
979
980                 if (is_null($type_value)) {
981                         if (!empty($array[$element][$key])) {
982                                 return $array[$element][$key];
983                         }
984
985                         if (!empty($array[$element][0][$key])) {
986                                 return $array[$element][0][$key];
987                         }
988
989                         return false;
990                 }
991
992                 if (!empty($array[$element][$key]) && !empty($array[$element][$type]) && ($array[$element][$type] == $type_value)) {
993                         return $array[$element][$key];
994                 }
995
996                 /// @todo Add array search
997
998                 return false;
999         }
1000
1001         private static function convertMentions($body)
1002         {
1003                 $URLSearchString = "^\[\]";
1004                 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1005
1006                 return $body;
1007         }
1008
1009         private static function constructTagList($tags, $sensitive)
1010         {
1011                 if (empty($tags)) {
1012                         return '';
1013                 }
1014
1015                 $tag_text = '';
1016                 foreach ($tags as $tag) {
1017                         if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1018                                 if (!empty($tag_text)) {
1019                                         $tag_text .= ',';
1020                                 }
1021
1022                                 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1023                         }
1024                 }
1025
1026                 /// @todo add nsfw for $sensitive
1027
1028                 return $tag_text;
1029         }
1030
1031         private static function constructAttachList($attachments, $item)
1032         {
1033                 if (empty($attachments)) {
1034                         return $item;
1035                 }
1036
1037                 foreach ($attachments as $attach) {
1038                         $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1039                         if ($filetype == 'image') {
1040                                 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1041                         } else {
1042                                 if (!empty($item["attach"])) {
1043                                         $item["attach"] .= ',';
1044                                 } else {
1045                                         $item["attach"] = '';
1046                                 }
1047                                 if (!isset($attach['length'])) {
1048                                         $attach['length'] = "0";
1049                                 }
1050                                 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1051                         }
1052                 }
1053
1054                 return $item;
1055         }
1056
1057         private static function createItem($activity, $body)
1058         {
1059                 $item = [];
1060                 $item['verb'] = ACTIVITY_POST;
1061                 $item['parent-uri'] = $activity['reply-to-uri'];
1062
1063                 if ($activity['reply-to-uri'] == $activity['uri']) {
1064                         $item['gravity'] = GRAVITY_PARENT;
1065                         $item['object-type'] = ACTIVITY_OBJ_NOTE;
1066                 } else {
1067                         $item['gravity'] = GRAVITY_COMMENT;
1068                         $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1069                 }
1070
1071                 self::postItem($activity, $item, $body);
1072         }
1073
1074         private static function likeItem($activity, $body)
1075         {
1076                 $item = [];
1077                 $item['verb'] = ACTIVITY_LIKE;
1078                 $item['parent-uri'] = $activity['object'];
1079                 $item['gravity'] = GRAVITY_ACTIVITY;
1080                 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1081
1082                 self::postItem($activity, $item, $body);
1083         }
1084
1085         private static function postItem($activity, $item, $body)
1086         {
1087                 /// @todo What to do with $activity['context']?
1088
1089                 $item['network'] = Protocol::ACTIVITYPUB;
1090                 $item['private'] = !in_array(0, $activity['receiver']);
1091                 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1092                 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1093                 $item['uri'] = $activity['uri'];
1094                 $item['created'] = $activity['published'];
1095                 $item['edited'] = $activity['updated'];
1096                 $item['guid'] = $activity['uuid'];
1097                 $item['title'] = HTML::toBBCode($activity['name']);
1098                 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1099                 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1100                 $item['location'] = $activity['location'];
1101                 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1102                 $item['app'] = $activity['service'];
1103                 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1104
1105                 $item = self::constructAttachList($activity['attachments'], $item);
1106
1107                 $source = self::processElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1108                 if (!empty($source)) {
1109                         $item['body'] = $source;
1110                 }
1111
1112                 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1113                 $item['source'] = $body;
1114                 $item['conversation-uri'] = $activity['conversation'];
1115
1116                 foreach ($activity['receiver'] as $receiver) {
1117                         $item['uid'] = $receiver;
1118                         $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1119
1120                         if (($receiver != 0) && empty($item['contact-id'])) {
1121                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1122                         }
1123
1124                         $item_id = Item::insert($item);
1125                         logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1126                         if (!empty($item_id) && ($item['uid'] == 0)) {
1127                                 Item::distribute($item_id);
1128                         }
1129                 }
1130         }
1131
1132         private static function followUser($activity)
1133         {
1134                 if (empty($activity['receiver'][$activity['object']])) {
1135                         return;
1136                 }
1137
1138                 $uid = $activity['receiver'][$activity['object']];
1139                 $owner = User::getOwnerDataById($uid);
1140
1141                 $cid = Contact::getIdForURL($activity['owner'], $uid);
1142                 if (!empty($cid)) {
1143                         $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1144                 } else {
1145                         $contact = false;
1146                 }
1147
1148                 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1149                         'author-link' => $activity['owner']];
1150
1151                 Contact::addRelationship($owner, $contact, $item);
1152                 $cid = Contact::getIdForURL($activity['owner'], $uid);
1153                 if (empty($cid)) {
1154                         return;
1155                 }
1156
1157                 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1158                 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1159                         Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1160                 }
1161
1162                 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1163                 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1164         }
1165
1166         private static function acceptFollowUser($activity)
1167         {
1168                 if (empty($activity['receiver'][$activity['object']])) {
1169                         return;
1170                 }
1171
1172                 $uid = $activity['receiver'][$activity['object']];
1173                 $owner = User::getOwnerDataById($uid);
1174
1175                 $cid = Contact::getIdForURL($activity['owner'], $uid);
1176                 if (empty($cid)) {
1177                         logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1178                         return;
1179                 }
1180
1181                 $fields = ['pending' => false];
1182
1183                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1184                 if ($contact['rel'] == Contact::FOLLOWER) {
1185                         $fields['rel'] = Contact::FRIEND;
1186                 }
1187
1188                 $condition = ['id' => $cid];
1189                 DBA::update('contact', $fields, $condition);
1190                 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1191         }
1192
1193         private static function undoFollowUser($activity)
1194         {
1195                 if (empty($activity['receiver'][$activity['object']])) {
1196                         return;
1197                 }
1198
1199                 $uid = $activity['receiver'][$activity['object']];
1200                 $owner = User::getOwnerDataById($uid);
1201
1202                 $cid = Contact::getIdForURL($activity['owner'], $uid);
1203                 if (empty($cid)) {
1204                         logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1205                         return;
1206                 }
1207
1208                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1209                 if (!DBA::isResult($contact)) {
1210                         return;
1211                 }
1212
1213                 Contact::removeFollower($owner, $contact);
1214                 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1215         }
1216 }