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