]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Diaspora.php
b3108c8ff321abdf2c868cf2821f07925f767d96
[friendica.git] / src / Protocol / Diaspora.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Protocol;
23
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\Markdown;
27 use Friendica\Core\Cache\Enum\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
33 use Friendica\DI;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\FContact;
37 use Friendica\Model\GServer;
38 use Friendica\Model\Item;
39 use Friendica\Model\ItemURI;
40 use Friendica\Model\Mail;
41 use Friendica\Model\Post;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
45 use Friendica\Network\Probe;
46 use Friendica\Util\Crypto;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Map;
49 use Friendica\Util\Network;
50 use Friendica\Util\Strings;
51 use Friendica\Util\XML;
52 use Friendica\Worker\Delivery;
53 use GuzzleHttp\Psr7\Uri;
54 use SimpleXMLElement;
55
56 /**
57  * This class contain functions to create and send Diaspora XML files
58  */
59 class Diaspora
60 {
61         const PUSHED       = 0;
62         const FETCHED      = 1;
63         const FORCED_FETCH = 2;
64
65         /**
66          * Return a list of participating contacts for a thread
67          *
68          * This is used for the participation feature.
69          * One of the parameters is a contact array.
70          * This is done to avoid duplicates.
71          *
72          * @param array $item     Item that is about to be delivered
73          * @param array $contacts The previously fetched contacts
74          *
75          * @return array of relay servers
76          * @throws \Exception
77          */
78         public static function participantsForThread(array $item, array $contacts): array
79         {
80                 if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
81                         Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]);
82                         return $contacts;
83                 }
84
85                 $items = Post::select(['author-id', 'author-link', 'parent-author-link', 'parent-guid', 'guid'],
86                         ['parent' => $item['parent'], 'gravity' => [Item::GRAVITY_COMMENT, Item::GRAVITY_ACTIVITY]]);
87                 while ($item = Post::fetch($items)) {
88                         $contact = DBA::selectFirst('contact', ['id', 'url', 'name', 'protocol', 'batch', 'network'],
89                                 ['id' => $item['author-id']]);
90                         if (!DBA::isResult($contact) || empty($contact['batch']) ||
91                                 ($contact['network'] != Protocol::DIASPORA) ||
92                                 Strings::compareLink($item['parent-author-link'], $item['author-link'])) {
93                                 continue;
94                         }
95
96                         $exists = false;
97                         foreach ($contacts as $entry) {
98                                 if ($entry['batch'] == $contact['batch']) {
99                                         $exists = true;
100                                 }
101                         }
102
103                         if (!$exists) {
104                                 Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]);
105                                 $contacts[] = $contact;
106                         }
107                 }
108                 DBA::close($items);
109
110                 return $contacts;
111         }
112
113         /**
114          * verify the envelope and return the verified data
115          *
116          * @param string $envelope The magic envelope
117          *
118          * @return string|bool verified data or false on error
119          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
120          * @throws \ImagickException
121          */
122         private static function verifyMagicEnvelope(string $envelope)
123         {
124                 $basedom = XML::parseString($envelope, true);
125
126                 if (!is_object($basedom)) {
127                         Logger::notice('Envelope is no XML file');
128                         return false;
129                 }
130
131                 $children = $basedom->children(ActivityNamespace::SALMON_ME);
132
133                 if (sizeof($children) == 0) {
134                         Logger::notice('XML has no children');
135                         return false;
136                 }
137
138                 $handle = '';
139
140                 $data = Strings::base64UrlDecode($children->data);
141                 $type = $children->data->attributes()->type[0];
142
143                 $encoding = $children->encoding;
144
145                 $alg = $children->alg;
146
147                 $sig = Strings::base64UrlDecode($children->sig);
148                 $key_id = $children->sig->attributes()->key_id[0];
149                 if ($key_id != '') {
150                         $handle = Strings::base64UrlDecode($key_id);
151                 }
152
153                 $b64url_data = Strings::base64UrlEncode($data);
154                 $msg = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
155
156                 $signable_data = $msg . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
157
158                 if ($handle == '') {
159                         Logger::notice('No author could be decoded. Discarding. Message: ' . $envelope);
160                         return false;
161                 }
162
163                 $key = self::key($handle);
164                 if ($key == '') {
165                         Logger::notice("Couldn't get a key for handle " . $handle . ". Discarding.");
166                         return false;
167                 }
168
169                 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
170                 if (!$verify) {
171                         Logger::notice('Message from ' . $handle . ' did not verify. Discarding.');
172                         return false;
173                 }
174
175                 return $data;
176         }
177
178         /**
179          * encrypts data via AES
180          *
181          * @param string $key  The AES key
182          * @param string $iv   The IV (is used for CBC encoding)
183          * @param string $data The data that is to be encrypted
184          *
185          * @return string encrypted data
186          */
187         private static function aesEncrypt(string $key, string $iv, string $data): string
188         {
189                 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
190         }
191
192         /**
193          * decrypts data via AES
194          *
195          * @param string $key       The AES key
196          * @param string $iv        The IV (is used for CBC encoding)
197          * @param string $encrypted The encrypted data
198          *
199          * @return string decrypted data
200          */
201         private static function aesDecrypt(string $key, string $iv, string $encrypted): string
202         {
203                 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
204         }
205
206         /**
207          * Decodes incoming Diaspora message in the new format. This method returns false on an error.
208          *
209          * @param string  $raw      raw post message
210          * @param string  $privKey   The private key of the importer
211          * @param boolean $no_exit  Don't do an http exit on error
212          *
213          * @return bool|array
214          * 'message' -> decoded Diaspora XML message
215          * 'author' -> author diaspora handle
216          * 'key' -> author public key (converted to pkcs#8)
217          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
218          * @throws \ImagickException
219          */
220         public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
221         {
222                 $data = json_decode($raw);
223
224                 // Is it a private post? Then decrypt the outer Salmon
225                 if (is_object($data)) {
226                         $encrypted_aes_key_bundle = base64_decode($data->aes_key);
227                         $ciphertext = base64_decode($data->encrypted_magic_envelope);
228
229                         $outer_key_bundle = '';
230                         @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
231                         $j_outer_key_bundle = json_decode($outer_key_bundle);
232
233                         if (!is_object($j_outer_key_bundle)) {
234                                 Logger::notice('Outer Salmon did not verify. Discarding.');
235                                 if ($no_exit) {
236                                         return false;
237                                 } else {
238                                         throw new \Friendica\Network\HTTPException\BadRequestException();
239                                 }
240                         }
241
242                         $outer_iv = base64_decode($j_outer_key_bundle->iv);
243                         $outer_key = base64_decode($j_outer_key_bundle->key);
244
245                         $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
246                 } else {
247                         $xml = $raw;
248                 }
249
250                 $basedom = XML::parseString($xml, true);
251
252                 if (!is_object($basedom)) {
253                         Logger::notice('Received data does not seem to be an XML. Discarding. '.$xml);
254                         if ($no_exit) {
255                                 return false;
256                         } else {
257                                 throw new \Friendica\Network\HTTPException\BadRequestException();
258                         }
259                 }
260
261                 $base = $basedom->children(ActivityNamespace::SALMON_ME);
262
263                 // Not sure if this cleaning is needed
264                 $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
265
266                 // Build the signed data
267                 $type = $base->data[0]->attributes()->type[0];
268                 $encoding = $base->encoding;
269                 $alg = $base->alg;
270                 $signed_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
271
272                 // This is the signature
273                 $signature = Strings::base64UrlDecode($base->sig);
274
275                 // Get the senders' public key
276                 $key_id = $base->sig[0]->attributes()->key_id[0];
277                 $author_addr = base64_decode($key_id);
278                 if ($author_addr == '') {
279                         Logger::notice('No author could be decoded. Discarding. Message: ' . $xml);
280                         if ($no_exit) {
281                                 return false;
282                         } else {
283                                 throw new \Friendica\Network\HTTPException\BadRequestException();
284                         }
285                 }
286
287                 $key = self::key($author_addr);
288                 if ($key == '') {
289                         Logger::notice("Couldn't get a key for handle " . $author_addr . ". Discarding.");
290                         if ($no_exit) {
291                                 return false;
292                         } else {
293                                 throw new \Friendica\Network\HTTPException\BadRequestException();
294                         }
295                 }
296
297                 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
298                 if (!$verify) {
299                         Logger::notice('Message did not verify. Discarding.');
300                         if ($no_exit) {
301                                 return false;
302                         } else {
303                                 throw new \Friendica\Network\HTTPException\BadRequestException();
304                         }
305                 }
306
307                 return [
308                         'message' => (string)Strings::base64UrlDecode($base->data),
309                         'author' => XML::unescape($author_addr),
310                         'key' => (string)$key
311                 ];
312         }
313
314         /**
315          * Decodes incoming Diaspora message in the deprecated format
316          *
317          * @param string $xml      urldecoded Diaspora salmon
318          * @param string $privKey  The private key of the importer
319          *
320          * @return array
321          * 'message' -> decoded Diaspora XML message
322          * 'author' -> author diaspora handle
323          * 'key' -> author public key (converted to pkcs#8)
324          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
325          * @throws \ImagickException
326          */
327         public static function decode(string $xml, string $privKey = '')
328         {
329                 $public = false;
330                 $basedom = XML::parseString($xml);
331
332                 if (!is_object($basedom)) {
333                         Logger::notice('XML is not parseable.');
334                         return false;
335                 }
336                 $children = $basedom->children('https://joindiaspora.com/protocol');
337
338                 $inner_aes_key = null;
339                 $inner_iv = null;
340
341                 if ($children->header) {
342                         $public = true;
343                         $author_link = str_replace('acct:', '', $children->header->author_id);
344                 } else {
345                         // This happens with posts from a relais
346                         if (empty($privKey)) {
347                                 Logger::info('This is no private post in the old format');
348                                 return false;
349                         }
350
351                         $encrypted_header = json_decode(base64_decode($children->encrypted_header));
352
353                         $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
354                         $ciphertext = base64_decode($encrypted_header->ciphertext);
355
356                         $outer_key_bundle = '';
357                         openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
358
359                         $j_outer_key_bundle = json_decode($outer_key_bundle);
360
361                         $outer_iv = base64_decode($j_outer_key_bundle->iv);
362                         $outer_key = base64_decode($j_outer_key_bundle->key);
363
364                         $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
365
366                         Logger::info('decrypted', ['data' => $decrypted]);
367                         $idom = XML::parseString($decrypted);
368
369                         $inner_iv = base64_decode($idom->iv);
370                         $inner_aes_key = base64_decode($idom->aes_key);
371
372                         $author_link = str_replace('acct:', '', $idom->author_id);
373                 }
374
375                 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
376
377                 // figure out where in the DOM tree our data is hiding
378
379                 $base = null;
380                 if ($dom->provenance->data) {
381                         $base = $dom->provenance;
382                 } elseif ($dom->env->data) {
383                         $base = $dom->env;
384                 } elseif ($dom->data) {
385                         $base = $dom;
386                 }
387
388                 if (!$base) {
389                         Logger::notice('unable to locate salmon data in xml');
390                         throw new \Friendica\Network\HTTPException\BadRequestException();
391                 }
392
393
394                 // Stash the signature away for now. We have to find their key or it won't be good for anything.
395                 $signature = Strings::base64UrlDecode($base->sig);
396
397                 // unpack the  data
398
399                 // strip whitespace so our data element will return to one big base64 blob
400                 $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
401
402
403                 // stash away some other stuff for later
404
405                 $type = $base->data[0]->attributes()->type[0];
406                 $keyhash = $base->sig[0]->attributes()->keyhash[0];
407                 $encoding = $base->encoding;
408                 $alg = $base->alg;
409
410
411                 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
412
413
414                 // decode the data
415                 $data = Strings::base64UrlDecode($data);
416
417
418                 if ($public) {
419                         $inner_decrypted = $data;
420                 } else {
421                         // Decode the encrypted blob
422                         $inner_encrypted = base64_decode($data);
423                         $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
424                 }
425
426                 if (!$author_link) {
427                         Logger::notice('Could not retrieve author URI.');
428                         throw new \Friendica\Network\HTTPException\BadRequestException();
429                 }
430                 // Once we have the author URI, go to the web and try to find their public key
431                 // (first this will look it up locally if it is in the fcontact cache)
432                 // This will also convert diaspora public key from pkcs#1 to pkcs#8
433
434                 Logger::notice('Fetching key for '.$author_link);
435                 $key = self::key($author_link);
436
437                 if (!$key) {
438                         Logger::notice('Could not retrieve author key.');
439                         throw new \Friendica\Network\HTTPException\BadRequestException();
440                 }
441
442                 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
443
444                 if (!$verify) {
445                         Logger::notice('Message did not verify. Discarding.');
446                         throw new \Friendica\Network\HTTPException\BadRequestException();
447                 }
448
449                 Logger::notice('Message verified.');
450
451                 return [
452                         'message' => (string)$inner_decrypted,
453                         'author' => XML::unescape($author_link),
454                         'key' => (string)$key
455                 ];
456         }
457
458
459         /**
460          * Dispatches public messages and find the fitting receivers
461          *
462          * @param array $msg       The post that will be dispatched
463          * @param int   $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
464          *
465          * @return int|bool The message id of the generated message, "true" or "false" if there was an error
466          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
467          * @throws \ImagickException
468          */
469         public static function dispatchPublic(array $msg, int $direction)
470         {
471                 $enabled = intval(DI::config()->get('system', 'diaspora_enabled'));
472                 if (!$enabled) {
473                         Logger::notice('Diaspora is disabled');
474                         return false;
475                 }
476
477                 if (!($fields = self::validPosting($msg))) {
478                         Logger::warning('Invalid posting');
479                         return false;
480                 }
481
482                 $importer = [
483                         'uid' => 0,
484                         'page-flags' => User::PAGE_FLAGS_FREELOVE
485                 ];
486                 $success = self::dispatch($importer, $msg, $fields, $direction);
487
488                 return $success;
489         }
490
491         /**
492          * Dispatches the different message types to the different functions
493          *
494          * @param array            $importer  Array of the importer user
495          * @param array            $msg       The post that will be dispatched
496          * @param SimpleXMLElement $fields    SimpleXML object that contains the message
497          * @param int              $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
498          *
499          * @return int|bool The message id of the generated message, "true" or "false" if there was an error
500          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
501          * @throws \ImagickException
502          */
503         public static function dispatch(array $importer, array $msg, SimpleXMLElement $fields = null, int $direction = self::PUSHED)
504         {
505                 // The sender is the handle of the contact that sent the message.
506                 // This will often be different with relayed messages (for example "like" and "comment")
507                 $sender = $msg['author'];
508
509                 // This is only needed for private postings since this is already done for public ones before
510                 if (is_null($fields)) {
511                         $private = true;
512                         if (!($fields = self::validPosting($msg))) {
513                                 Logger::warning('Invalid posting');
514                                 return false;
515                         }
516                 } else {
517                         $private = false;
518                 }
519
520                 $type = $fields->getName();
521
522                 Logger::info('Received message', ['type' => $type, 'sender' => $sender, 'user' => $importer['uid']]);
523
524                 switch ($type) {
525                         case 'account_migration':
526                                 if (!$private) {
527                                         Logger::notice('Message with type ' . $type . ' is not private, quitting.');
528                                         return false;
529                                 }
530                                 return self::receiveAccountMigration($importer, $fields);
531
532                         case 'account_deletion':
533                                 return self::receiveAccountDeletion($fields);
534
535                         case 'comment':
536                                 return self::receiveComment($importer, $sender, $fields, $msg['message'], $direction);
537
538                         case 'contact':
539                                 if (!$private) {
540                                         Logger::notice('Message with type ' . $type . ' is not private, quitting.');
541                                         return false;
542                                 }
543                                 return self::receiveContactRequest($importer, $fields);
544
545                         case 'conversation':
546                                 if (!$private) {
547                                         Logger::notice('Message with type ' . $type . ' is not private, quitting.');
548                                         return false;
549                                 }
550                                 return self::receiveConversation($importer, $msg, $fields);
551
552                         case 'like':
553                                 return self::receiveLike($importer, $sender, $fields, $direction);
554
555                         case 'message':
556                                 if (!$private) {
557                                         Logger::notice('Message with type ' . $type . ' is not private, quitting.');
558                                         return false;
559                                 }
560                                 return self::receiveMessage($importer, $fields);
561
562                         case 'participation':
563                                 if (!$private) {
564                                         Logger::notice('Message with type ' . $type . ' is not private, quitting.');
565                                         return false;
566                                 }
567                                 return self::receiveParticipation($importer, $fields, $direction);
568
569                         case 'photo': // Not implemented
570                                 return self::receivePhoto($importer, $fields);
571
572                         case 'poll_participation': // Not implemented
573                                 return self::receivePollParticipation($importer, $fields);
574
575                         case 'profile':
576                                 if (!$private) {
577                                         Logger::notice('Message with type ' . $type . ' is not private, quitting.');
578                                         return false;
579                                 }
580                                 return self::receiveProfile($importer, $fields);
581
582                         case 'reshare':
583                                 return self::receiveReshare($importer, $fields, $msg['message'], $direction);
584
585                         case 'retraction':
586                                 return self::receiveRetraction($importer, $sender, $fields);
587
588                         case 'status_message':
589                                 return self::receiveStatusMessage($importer, $fields, $msg['message'], $direction);
590
591                         default:
592                                 Logger::notice('Unknown message type ' . $type);
593                                 return false;
594                 }
595         }
596
597         /**
598          * Checks if a posting is valid and fetches the data fields.
599          *
600          * This function does not only check the signature.
601          * It also does the conversion between the old and the new diaspora format.
602          *
603          * @param array $msg Array with the XML, the sender handle and the sender signature
604          *
605          * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
606          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
607          * @throws \ImagickException
608          */
609         private static function validPosting(array $msg)
610         {
611                 $data = XML::parseString($msg['message']);
612
613                 if (!is_object($data)) {
614                         Logger::info('No valid XML', ['message' => $msg['message']]);
615                         return false;
616                 }
617
618                 // Is this the new or the old version?
619                 if ($data->getName() == 'XML') {
620                         $oldXML = true;
621                         foreach ($data->post->children() as $child) {
622                                 $element = $child;
623                         }
624                 } else {
625                         $oldXML = false;
626                         $element = $data;
627                 }
628
629                 $type = $element->getName();
630                 $orig_type = $type;
631
632                 Logger::debug('Got message', ['type' => $type, 'message' => $msg['message']]);
633
634                 // All retractions are handled identically from now on.
635                 // In the new version there will only be "retraction".
636                 if (in_array($type, ['signed_retraction', 'relayable_retraction']))
637                         $type = 'retraction';
638
639                 if ($type == 'request') {
640                         $type = 'contact';
641                 }
642
643                 $fields = new SimpleXMLElement('<' . $type . '/>');
644
645                 $signed_data = '';
646                 $author_signature = null;
647                 $parent_author_signature = null;
648
649                 foreach ($element->children() as $fieldname => $entry) {
650                         if ($oldXML) {
651                                 // Translation for the old XML structure
652                                 if ($fieldname == 'diaspora_handle') {
653                                         $fieldname = 'author';
654                                 }
655                                 if ($fieldname == 'participant_handles') {
656                                         $fieldname = 'participants';
657                                 }
658                                 if (in_array($type, ['like', 'participation'])) {
659                                         if ($fieldname == 'target_type') {
660                                                 $fieldname = 'parent_type';
661                                         }
662                                 }
663                                 if ($fieldname == 'sender_handle') {
664                                         $fieldname = 'author';
665                                 }
666                                 if ($fieldname == 'recipient_handle') {
667                                         $fieldname = 'recipient';
668                                 }
669                                 if ($fieldname == 'root_diaspora_id') {
670                                         $fieldname = 'root_author';
671                                 }
672                                 if ($type == 'status_message') {
673                                         if ($fieldname == 'raw_message') {
674                                                 $fieldname = 'text';
675                                         }
676                                 }
677                                 if ($type == 'retraction') {
678                                         if ($fieldname == 'post_guid') {
679                                                 $fieldname = 'target_guid';
680                                         }
681                                         if ($fieldname == 'type') {
682                                                 $fieldname = 'target_type';
683                                         }
684                                 }
685                         }
686
687                         if (($fieldname == 'author_signature') && ($entry != '')) {
688                                 $author_signature = base64_decode($entry);
689                         } elseif (($fieldname == 'parent_author_signature') && ($entry != '')) {
690                                 $parent_author_signature = base64_decode($entry);
691                         } elseif (!in_array($fieldname, ['author_signature', 'parent_author_signature', 'target_author_signature'])) {
692                                 if ($signed_data != '') {
693                                         $signed_data .= ';';
694                                 }
695
696                                 $signed_data .= $entry;
697                         }
698                         if (!in_array($fieldname, ['parent_author_signature', 'target_author_signature'])
699                                 || ($orig_type == 'relayable_retraction')
700                         ) {
701                                 XML::copy($entry, $fields, $fieldname);
702                         }
703                 }
704
705                 // This is something that shouldn't happen at all.
706                 if (in_array($type, ['status_message', 'reshare', 'profile'])) {
707                         if ($msg['author'] != $fields->author) {
708                                 Logger::notice('Message handle is not the same as envelope sender. Quitting this message.', ['author1' => $msg['author'], 'author2' => $fields->author]);
709                                 return false;
710                         }
711                 }
712
713                 // Only some message types have signatures. So we quit here for the other types.
714                 if (!in_array($type, ['comment', 'like'])) {
715                         return $fields;
716                 }
717
718                 if (!isset($author_signature) && ($msg['author'] == $fields->author)) {
719                         Logger::debug('No author signature, but the sender matches the author', ['type' => $type, 'msg-author' => $msg['author'], 'message' => $msg['message']]);
720                         return $fields;
721                 }
722
723                 // No author_signature? This is a must, so we quit.
724                 if (!isset($author_signature)) {
725                         Logger::info('No author signature', ['type' => $type, 'msg-author' => $msg['author'], 'fields-author' => $fields->author, 'message' => $msg['message']]);
726                         return false;
727                 }
728
729                 if (isset($parent_author_signature)) {
730                         $key = self::key($msg['author']);
731                         if (empty($key)) {
732                                 Logger::info('No key found for parent', ['author' => $msg['author']]);
733                                 return false;
734                         }
735
736                         if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, 'sha256')) {
737                                 Logger::info('No valid parent author signature', ['author' => $msg['author'], 'type' => $type, 'signed data' => $signed_data, 'message'  => $msg['message'], 'signature' => $parent_author_signature]);
738                                 return false;
739                         }
740                 }
741
742                 $key = self::key($fields->author);
743                 if (empty($key)) {
744                         Logger::info('No key found', ['author' => $fields->author]);
745                         return false;
746                 }
747
748                 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, 'sha256')) {
749                         Logger::info('No valid author signature for author', ['author' => $fields->author, 'type' => $type, 'signed data' => $signed_data, 'message'  => $msg['message'], 'signature' => $author_signature]);
750                         return false;
751                 } else {
752                         return $fields;
753                 }
754         }
755
756         /**
757          * Fetches the public key for a given handle
758          *
759          * @param string $handle The handle
760          *
761          * @return string The public key
762          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
763          * @throws \ImagickException
764          */
765         private static function key(string $handle = null): string
766         {
767                 $handle = strval($handle);
768
769                 Logger::notice('Fetching diaspora key', ['handle' => $handle, 'callstack' => System::callstack(20)]);
770
771                 $fcontact = FContact::getByURL($handle);
772                 if (!empty($fcontact['pubkey'])) {
773                         return $fcontact['pubkey'];
774                 }
775
776                 return '';
777         }
778
779         /**
780          * Get a contact id for a given handle
781          *
782          * @todo  Move to Friendica\Model\Contact
783          *
784          * @param int    $uid    The user id
785          * @param string $handle The handle in the format user@domain.tld
786          *
787          * @return array Contact data
788          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
789          * @throws \ImagickException
790          */
791         private static function contactByHandle(int $uid, string $handle): array
792         {
793                 return Contact::getByURL($handle, null, [], $uid);
794         }
795
796         /**
797          * Checks if the given contact url does support ActivityPub
798          *
799          * @param string  $url    profile url
800          * @param boolean $update true = always update, false = never update, null = update when not found or outdated
801          * @return boolean
802          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
803          * @throws \ImagickException
804          */
805         public static function isSupportedByContactUrl(string $url, $update = null)
806         {
807                 return !empty(FContact::getByURL($url, $update));
808         }
809
810         /**
811          * Check if posting is allowed for this contact
812          *
813          * @param array $importer   Array of the importer user
814          * @param array $contact    The contact that is checked
815          * @param bool  $is_comment Is the check for a comment?
816          *
817          * @return bool is the contact allowed to post?
818          */
819         private static function postAllow(array $importer, array $contact, bool $is_comment = false): bool
820         {
821                 /*
822                  * Perhaps we were already sharing with this person. Now they're sharing with us.
823                  * That makes us friends.
824                  * Normally this should have handled by getting a request - but this could get lost
825                  */
826                 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
827                 // It is not removed by now. Possibly the code is needed?
828                 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
829                 //      Contact::update(
830                 //              array('rel' => Contact::FRIEND, 'writable' => true),
831                 //              array('id' => $contact["id"], 'uid' => $contact["uid"])
832                 //      );
833                 //
834                 //      $contact["rel"] = Contact::FRIEND;
835                 //      Logger::notice("defining user ".$contact["nick"]." as friend");
836                 //}
837
838                 // Contact server is blocked
839                 if (Network::isUrlBlocked($contact['url'])) {
840                         return false;
841                         // We don't seem to like that person
842                 } elseif ($contact['blocked']) {
843                         // Maybe blocked, don't accept.
844                         return false;
845                         // We are following this person?
846                 } elseif (($contact['rel'] == Contact::SHARING) || ($contact['rel'] == Contact::FRIEND)) {
847                         // Yes, then it is fine.
848                         return true;
849                         // Is the message a global user or a comment?
850                 } elseif (($importer['uid'] == 0) || $is_comment) {
851                         // Messages for the global users and comments are always accepted
852                         return true;
853                 }
854
855                 return false;
856         }
857
858         /**
859          * Fetches the contact id for a handle and checks if posting is allowed
860          *
861          * @param array  $importer   Array of the importer user
862          * @param string $handle     The checked handle in the format user@domain.tld
863          * @param bool   $is_comment Is the check for a comment?
864          *
865          * @return array|bool The contact data or false on error
866          * @throws \Exception
867          */
868         private static function allowedContactByHandle(array $importer, string $handle, bool $is_comment = false)
869         {
870                 $contact = self::contactByHandle($importer['uid'], $handle);
871                 if (!$contact) {
872                         Logger::notice('A Contact for handle ' . $handle . ' and user ' . $importer['uid'] . ' was not found');
873                         // If a contact isn't found, we accept it anyway if it is a comment
874                         if ($is_comment && ($importer['uid'] != 0)) {
875                                 return self::contactByHandle(0, $handle);
876                         } elseif ($is_comment) {
877                                 return $importer;
878                         } else {
879                                 return false;
880                         }
881                 }
882
883                 if (!self::postAllow($importer, $contact, $is_comment)) {
884                         Logger::notice('The handle: ' . $handle . ' is not allowed to post to user ' . $importer['uid']);
885                         return false;
886                 }
887                 return $contact;
888         }
889
890         /**
891          * Does the message already exists on the system?
892          *
893          * @param int    $uid  The user id
894          * @param string $guid The guid of the message
895          *
896          * @return int|bool message id if the message already was stored into the system - or false.
897          * @throws \Exception
898          */
899         private static function messageExists(int $uid, string $guid)
900         {
901                 $item = Post::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
902                 if (DBA::isResult($item)) {
903                         Logger::notice('Message ' . $guid . ' already exists for user ' . $uid);
904                         return $item['id'];
905                 }
906
907                 return false;
908         }
909
910         /**
911          * Checks for links to posts in a message
912          *
913          * @param array $item The item array
914          * @return void
915          */
916         private static function fetchGuid(array $item)
917         {
918                 preg_replace_callback(
919                         "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism",
920                         function ($match) use ($item) {
921                                 self::fetchGuidSub($match, $item);
922                         },
923                         $item['body']
924                 );
925
926                 preg_replace_callback(
927                         "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
928                         function ($match) use ($item) {
929                                 self::fetchGuidSub($match, $item);
930                         },
931                         $item['body']
932                 );
933         }
934
935         /**
936          * Checks for relative /people/* links in an item body to match local
937          * contacts or prepends the remote host taken from the author link.
938          *
939          * @param string $body        The item body to replace links from
940          * @param string $author_link The author link for missing local contact fallback
941          *
942          * @return string the replaced string
943          */
944         public static function replacePeopleGuid(string $body, string $author_link): string
945         {
946                 $return = preg_replace_callback(
947                         "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
948                         function ($match) use ($author_link) {
949                                 // $match
950                                 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
951                                 // 1 => '0123456789abcdef'
952                                 // 2 => 'Foo Bar'
953                                 $handle = FContact::getUrlByGuid($match[1]);
954
955                                 if ($handle) {
956                                         $return = '@[url=' . $handle . ']' . $match[2] . '[/url]';
957                                 } else {
958                                         // No local match, restoring absolute remote URL from author scheme and host
959                                         $author_url = parse_url($author_link);
960                                         $return = '[url=' . $author_url['scheme'] . '://' . $author_url['host'] . '/people/' . $match[1] . ']' . $match[2] . '[/url]';
961                                 }
962
963                                 return $return;
964                         },
965                         $body
966                 );
967
968                 return $return;
969         }
970
971         /**
972          * sub function of "fetchGuid" which checks for links in messages
973          *
974          * @param array $match array containing a link that has to be checked for a message link
975          * @param array $item  The item array
976          * @return void
977          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
978          * @throws \ImagickException
979          */
980         private static function fetchGuidSub(array $match, array $item)
981         {
982                 if (!self::storeByGuid($match[1], $item['author-link'], true)) {
983                         self::storeByGuid($match[1], $item['owner-link'], true);
984                 }
985         }
986
987         /**
988          * Fetches an item with a given guid from a given server
989          *
990          * @param string $guid   the message guid
991          * @param string $server The server address
992          * @param bool   $force  Forced fetch
993          *
994          * @return int|bool the message id of the stored message or false
995          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
996          * @throws \ImagickException
997          */
998         public static function storeByGuid(string $guid, string $server, bool $force)
999         {
1000                 $serverparts = parse_url($server);
1001
1002                 if (empty($serverparts['host']) || empty($serverparts['scheme'])) {
1003                         return false;
1004                 }
1005
1006                 $server = $serverparts['scheme'] . '://' . $serverparts['host'];
1007
1008                 Logger::info('Trying to fetch item ' . $guid . ' from ' . $server);
1009
1010                 $msg = self::message($guid, $server);
1011
1012                 if (!$msg) {
1013                         return false;
1014                 }
1015
1016                 Logger::info('Successfully fetched item ' . $guid . ' from ' . $server);
1017
1018                 // Now call the dispatcher
1019                 return self::dispatchPublic($msg, $force ? self::FORCED_FETCH : self::FETCHED);
1020         }
1021
1022         /**
1023          * Fetches a message from a server
1024          *
1025          * @param string $guid   message guid
1026          * @param string $server The url of the server
1027          * @param int    $level  Endless loop prevention
1028          *
1029          * @return array
1030          *      'message' => The message XML
1031          *      'author' => The author handle
1032          *      'key' => The public key of the author
1033          * @throws \Exception
1034          */
1035         public static function message(string $guid, string $server, int $level = 0)
1036         {
1037                 if ($level > 5) {
1038                         return false;
1039                 }
1040
1041                 // This will work for new Diaspora servers and Friendica servers from 3.5
1042                 $source_url = $server . '/fetch/post/' . urlencode($guid);
1043
1044                 Logger::info('Fetch post from ' . $source_url);
1045
1046                 $envelope = DI::httpClient()->fetch($source_url, HttpClientAccept::MAGIC);
1047                 if ($envelope) {
1048                         Logger::info('Envelope was fetched.');
1049                         $x = self::verifyMagicEnvelope($envelope);
1050                         if (!$x) {
1051                                 Logger::info('Envelope could not be verified.');
1052                         } else {
1053                                 Logger::info('Envelope was verified.');
1054                         }
1055                 } else {
1056                         $x = false;
1057                 }
1058
1059                 if (!$x) {
1060                         return false;
1061                 }
1062
1063                 $source_xml = XML::parseString($x);
1064
1065                 if (!is_object($source_xml)) {
1066                         return false;
1067                 }
1068
1069                 if ($source_xml->post->reshare) {
1070                         // Reshare of a reshare - old Diaspora version
1071                         Logger::info('Message is a reshare');
1072                         return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1073                 } elseif ($source_xml->getName() == 'reshare') {
1074                         // Reshare of a reshare - new Diaspora version
1075                         Logger::info('Message is a new reshare');
1076                         return self::message($source_xml->root_guid, $server, ++$level);
1077                 }
1078
1079                 $author = '';
1080
1081                 // Fetch the author - for the old and the new Diaspora version
1082                 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1083                         $author = (string)$source_xml->post->status_message->diaspora_handle;
1084                 } elseif ($source_xml->author && ($source_xml->getName() == 'status_message')) {
1085                         $author = (string)$source_xml->author;
1086                 }
1087
1088                 // If this isn't a "status_message" then quit
1089                 if (!$author) {
1090                         Logger::info("Message doesn't seem to be a status message");
1091                         return false;
1092                 }
1093
1094                 return [
1095                         'message' => $x,
1096                         'author' => $author,
1097                         'key' => self::key($author)
1098                 ];
1099         }
1100
1101         /**
1102          * Fetches an item with a given URL
1103          *
1104          * @param string $url the message url
1105          * @param int $uid User id
1106          *
1107          * @return int|bool the message id of the stored message or false
1108          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1109          * @throws \ImagickException
1110          */
1111         public static function fetchByURL(string $url, int $uid = 0)
1112         {
1113                 // Check for Diaspora (and Friendica) typical paths
1114                 if (!preg_match('=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i', $url, $matches)) {
1115                         Logger::info('Invalid url', ['url' => $url]);
1116                         return false;
1117                 }
1118
1119                 $guid = urldecode($matches[2]);
1120
1121                 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1122                 if (DBA::isResult($item)) {
1123                         Logger::info('Found', ['id' => $item['id']]);
1124                         return $item['id'];
1125                 }
1126
1127                 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1128                 $ret = self::storeByGuid($guid, $matches[1], true);
1129                 Logger::info('Result', ['ret' => $ret]);
1130
1131                 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1132                 if (DBA::isResult($item)) {
1133                         Logger::info('Found', ['id' => $item['id']]);
1134                         return $item['id'];
1135                 } else {
1136                         Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1137                         return false;
1138                 }
1139         }
1140
1141         /**
1142          * Fetches the item record of a given guid
1143          *
1144          * @param int    $uid     The user id
1145          * @param string $guid    message guid
1146          * @param string $author  The handle of the item
1147          * @param array  $contact The contact of the item owner
1148          *
1149          * @return array|bool the item record or false on failure
1150          * @throws \Exception
1151          */
1152         private static function parentItem(int $uid, string $guid, string $author, array $contact)
1153         {
1154                 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1155                         'author-name', 'author-link', 'author-avatar', 'gravity',
1156                         'owner-name', 'owner-link', 'owner-avatar'];
1157
1158                 $condition = ['uid' => $uid, 'guid' => $guid];
1159                 $item = Post::selectFirst($fields, $condition);
1160
1161                 if (!DBA::isResult($item)) {
1162                         $person = FContact::getByURL($author);
1163                         $result = self::storeByGuid($guid, $person['url'], false);
1164
1165                         // We don't have an url for items that arrived at the public dispatcher
1166                         if (!$result && !empty($contact['url'])) {
1167                                 $result = self::storeByGuid($guid, $contact['url'], false);
1168                         }
1169
1170                         if ($result) {
1171                                 Logger::info('Fetched missing item ' . $guid . ' - result: ' . $result);
1172
1173                                 $item = Post::selectFirst($fields, $condition);
1174                         }
1175                 }
1176
1177                 if (!DBA::isResult($item)) {
1178                         Logger::notice('Parent item not found: parent: ' . $guid . ' - user: ' . $uid);
1179                         return false;
1180                 } else {
1181                         Logger::notice('Parent item found: parent: ' . $guid . ' - user: ' . $uid);
1182                         return $item;
1183                 }
1184         }
1185
1186         /**
1187          * returns contact details
1188          *
1189          * @param array $def_contact The default contact if the person isn't found
1190          * @param array $person      The record of the person
1191          * @param int   $uid         The user id
1192          *
1193          * @return array
1194          *      'cid' => contact id
1195          *      'network' => network type
1196          * @throws \Exception
1197          */
1198         private static function authorContactByUrl(array $def_contact, array $person, int $uid): array
1199         {
1200                 $condition = ['nurl' => Strings::normaliseLink($person['url']), 'uid' => $uid];
1201                 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1202                 if (DBA::isResult($contact)) {
1203                         $cid = $contact['id'];
1204                         $network = $contact['network'];
1205                 } else {
1206                         $cid = $def_contact['id'];
1207                         $network = Protocol::DIASPORA;
1208                 }
1209
1210                 return [
1211                         'cid' => $cid,
1212                         'network' => $network
1213                 ];
1214         }
1215
1216         /**
1217          * Is the profile a hubzilla profile?
1218          *
1219          * @param string $url The profile link
1220          *
1221          * @return bool is it a hubzilla server?
1222          */
1223         private static function isHubzilla(string $url): bool
1224         {
1225                 return strstr($url, '/channel/');
1226         }
1227
1228         /**
1229          * Generate a post link with a given handle and message guid
1230          *
1231          * @param string $addr        The user handle
1232          * @param string $guid        message guid
1233          * @param string $parent_guid optional parent guid
1234          *
1235          * @return string the post link
1236          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1237          * @throws \ImagickException
1238          */
1239         private static function plink(string $addr, string $guid, string $parent_guid = ''): string
1240         {
1241                 $contact = Contact::getByURL($addr);
1242                 if (empty($contact)) {
1243                         Logger::info('No contact data for address', ['addr' => $addr]);
1244                         return '';
1245                 }
1246
1247                 if (empty($contact['baseurl'])) {
1248                         $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1249                         Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1250                 }
1251
1252                 $platform = '';
1253                 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1254                 if (!empty($gserver['platform'])) {
1255                         $platform = strtolower($gserver['platform']);
1256                         Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1257                 }
1258
1259                 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1260                         if (self::isHubzilla($contact['url'])) {
1261                                 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1262                                 $platform = 'hubzilla';
1263                         } elseif ($contact['network'] == Protocol::DFRN) {
1264                                 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1265                                 $platform = 'friendica';
1266                         }
1267                 }
1268
1269                 if ($platform == 'friendica') {
1270                         return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1271                 }
1272
1273                 if ($platform == 'hubzilla') {
1274                         return $contact['baseurl'] . '/item/' . $guid;
1275                 }
1276
1277                 if ($platform == 'socialhome') {
1278                         return $contact['baseurl'] . '/content/' . $guid;
1279                 }
1280
1281                 if ($platform != 'diaspora') {
1282                         Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1283                         return '';
1284                 }
1285
1286                 if ($parent_guid != '') {
1287                         return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1288                 } else {
1289                         return $contact['baseurl'] . '/posts/' . $guid;
1290                 }
1291         }
1292
1293         /**
1294          * Receives account migration
1295          *
1296          * @param array  $importer Array of the importer user
1297          * @param SimpleXMLElement $data The message object
1298          *
1299          * @return bool Success
1300          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1301          * @throws \ImagickException
1302          */
1303         private static function receiveAccountMigration(array $importer, SimpleXMLElement $data): bool
1304         {
1305                 $old_handle = XML::unescape($data->author);
1306                 $new_handle = XML::unescape($data->profile->author);
1307                 $signature = XML::unescape($data->signature);
1308
1309                 $contact = self::contactByHandle($importer['uid'], $old_handle);
1310                 if (!$contact) {
1311                         Logger::notice('Cannot find contact for sender: ' . $old_handle . ' and user ' . $importer['uid']);
1312                         return false;
1313                 }
1314
1315                 Logger::notice('Got migration for ' . $old_handle . ', to ' . $new_handle . ' with user ' . $importer['uid']);
1316
1317                 // Check signature
1318                 $signed_text = 'AccountMigration:' . $old_handle . ':' . $new_handle;
1319                 $key = self::key($old_handle);
1320                 if (!Crypto::rsaVerify($signed_text, $signature, $key, 'sha256')) {
1321                         Logger::notice('No valid signature for migration.');
1322                         return false;
1323                 }
1324
1325                 // Update the profile
1326                 self::receiveProfile($importer, $data->profile);
1327
1328                 // change the technical stuff in contact
1329                 $data = Probe::uri($new_handle);
1330                 if ($data['network'] == Protocol::PHANTOM) {
1331                         Logger::notice("Account for " . $new_handle . " couldn't be probed.");
1332                         return false;
1333                 }
1334
1335                 $fields = [
1336                         'url'     => $data['url'],
1337                         'nurl'    => Strings::normaliseLink($data['url']),
1338                         'name'    => $data['name'],
1339                         'nick'    => $data['nick'],
1340                         'addr'    => $data['addr'],
1341                         'batch'   => $data['batch'],
1342                         'notify'  => $data['notify'],
1343                         'poll'    => $data['poll'],
1344                         'network' => $data['network'],
1345                 ];
1346
1347                 Contact::update($fields, ['addr' => $old_handle]);
1348
1349                 Logger::notice('Contacts are updated.');
1350
1351                 return true;
1352         }
1353
1354         /**
1355          * Processes an account deletion
1356          *
1357          * @param SimpleXMLElement $data The message object
1358          *
1359          * @return bool Success
1360          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1361          */
1362         private static function receiveAccountDeletion(SimpleXMLElement $data): bool
1363         {
1364                 $author = XML::unescape($data->author);
1365
1366                 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1367                 while ($contact = DBA::fetch($contacts)) {
1368                         Contact::remove($contact['id']);
1369                 }
1370                 DBA::close($contacts);
1371
1372                 Logger::notice('Removed contacts for ' . $author);
1373
1374                 return true;
1375         }
1376
1377         /**
1378          * Fetch the uri from our database if we already have this item (maybe from ourselves)
1379          *
1380          * @param string  $author    Author handle
1381          * @param string  $guid      Message guid
1382          * @param boolean $onlyfound Only return uri when found in the database
1383          *
1384          * @return string The constructed uri or the one from our database or empty string on if $onlyfound is true
1385          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1386          * @throws \ImagickException
1387          */
1388         private static function getUriFromGuid(string $author, string $guid, bool $onlyfound = false): string
1389         {
1390                 $item = Post::selectFirst(['uri'], ['guid' => $guid]);
1391                 if (DBA::isResult($item)) {
1392                         return $item['uri'];
1393                 } elseif (!$onlyfound) {
1394                         $person = FContact::getByURL($author);
1395
1396                         $parts = parse_url($person['url']);
1397                         unset($parts['path']);
1398                         $host_url = (string)Uri::fromParts($parts);
1399
1400                         return $host_url . '/objects/' . $guid;
1401                 }
1402
1403                 return '';
1404         }
1405
1406         /**
1407          * Store the mentions in the tag table
1408          *
1409          * @param integer $uriid
1410          * @param string $text
1411          */
1412         private static function storeMentions(int $uriid, string $text)
1413         {
1414                 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1415                 if (empty($matches)) {
1416                         return;
1417                 }
1418
1419                 /*
1420                  * Matching values for the preg match
1421                  * [1] = mention type (@ or !)
1422                  * [2] = name (optional)
1423                  * [3] = profile URL
1424                  */
1425
1426                 foreach ($matches as $match) {
1427                         if (empty($match)) {
1428                                 continue;
1429                         }
1430
1431                         $person = FContact::getByURL($match[3]);
1432                         if (empty($person)) {
1433                                 continue;
1434                         }
1435
1436                         Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1437                 }
1438         }
1439
1440         /**
1441          * Processes an incoming comment
1442          *
1443          * @param array  $importer  Array of the importer user
1444          * @param string $sender    The sender of the message
1445          * @param SimpleXMLElement $data      The message object
1446          * @param string $xml       The original XML of the message
1447          * @param int    $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1448          *
1449          * @return int The message id of the generated comment or "false" if there was an error
1450          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1451          * @throws \ImagickException
1452          */
1453         private static function receiveComment(array $importer, string $sender, SimpleXMLElement $data, string $xml, int $direction): bool
1454         {
1455                 $author = XML::unescape($data->author);
1456                 $guid = XML::unescape($data->guid);
1457                 $parent_guid = XML::unescape($data->parent_guid);
1458                 $text = XML::unescape($data->text);
1459
1460                 if (isset($data->created_at)) {
1461                         $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1462                 } else {
1463                         $created_at = DateTimeFormat::utcNow();
1464                 }
1465
1466                 if (isset($data->thread_parent_guid)) {
1467                         $thread_parent_guid = XML::unescape($data->thread_parent_guid);
1468                         $thr_parent = self::getUriFromGuid('', $thread_parent_guid, true);
1469                 } else {
1470                         $thr_parent = '';
1471                 }
1472
1473                 $contact = self::allowedContactByHandle($importer, $sender, true);
1474                 if (!$contact) {
1475                         return false;
1476                 }
1477
1478                 if (!empty($contact['gsid'])) {
1479                         GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1480                 }
1481
1482                 $message_id = self::messageExists($importer['uid'], $guid);
1483                 if ($message_id) {
1484                         return true;
1485                 }
1486
1487                 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1488                 if (!$toplevel_parent_item) {
1489                         return false;
1490                 }
1491
1492                 $person = FContact::getByURL($author);
1493                 if (!is_array($person)) {
1494                         Logger::notice('Unable to find author details');
1495                         return false;
1496                 }
1497
1498                 // Fetch the contact id - if we know this contact
1499                 $author_contact = self::authorContactByUrl($contact, $person, $importer['uid']);
1500
1501                 $datarray = [];
1502
1503                 $datarray['uid'] = $importer['uid'];
1504                 $datarray['contact-id'] = $author_contact['cid'];
1505                 $datarray['network']  = $author_contact['network'];
1506
1507                 $datarray['author-link'] = $person['url'];
1508                 $datarray['author-id'] = Contact::getIdForURL($person['url'], 0);
1509
1510                 $datarray['owner-link'] = $contact['url'];
1511                 $datarray['owner-id'] = Contact::getIdForURL($contact['url'], 0);
1512
1513                 // Will be overwritten for sharing accounts in Item::insert
1514                 $datarray = self::setDirection($datarray, $direction);
1515
1516                 $datarray['guid'] = $guid;
1517                 $datarray['uri'] = self::getUriFromGuid($author, $guid);
1518                 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1519
1520                 $datarray['verb'] = Activity::POST;
1521                 $datarray['gravity'] = Item::GRAVITY_COMMENT;
1522
1523                 $datarray['thr-parent'] = $thr_parent ?: $toplevel_parent_item['uri'];
1524
1525                 $datarray['object-type'] = Activity\ObjectType::COMMENT;
1526                 $datarray['post-type'] = Item::PT_NOTE;
1527
1528                 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1529                 $datarray['source'] = $xml;
1530
1531                 $datarray = self::setDirection($datarray, $direction);
1532
1533                 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
1534
1535                 $datarray['plink'] = self::plink($author, $guid, $toplevel_parent_item['guid']);
1536                 $body = Markdown::toBBCode($text);
1537
1538                 $datarray['body'] = self::replacePeopleGuid($body, $person['url']);
1539
1540                 self::storeMentions($datarray['uri-id'], $text);
1541                 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
1542
1543                 self::fetchGuid($datarray);
1544
1545                 // If we are the origin of the parent we store the original data.
1546                 // We notify our followers during the item storage.
1547                 if ($toplevel_parent_item['origin']) {
1548                         $datarray['diaspora_signed_text'] = json_encode($data);
1549                 }
1550
1551                 if (Item::isTooOld($datarray)) {
1552                         Logger::info('Comment is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1553                         return false;
1554                 }
1555
1556                 $message_id = Item::insert($datarray);
1557
1558                 if ($message_id <= 0) {
1559                         return false;
1560                 }
1561
1562                 if ($message_id) {
1563                         Logger::info('Stored comment ' . $datarray['guid'] . ' with message id ' . $message_id);
1564                         if ($datarray['uid'] == 0) {
1565                                 Item::distribute($message_id, json_encode($data));
1566                         }
1567                 }
1568
1569                 return true;
1570         }
1571
1572         /**
1573          * processes and stores private messages
1574          *
1575          * @param array  $importer     Array of the importer user
1576          * @param array  $contact      The contact of the message
1577          * @param SimpleXMLElement $data         The message object
1578          * @param array  $msg          Array of the processed message, author handle and key
1579          * @param object $mesg         The private message
1580          * @param array  $conversation The conversation record to which this message belongs
1581          *
1582          * @return bool "true" if it was successful
1583          * @throws \Exception
1584          * @todo Find type-hint for $mesg and update documentation
1585          */
1586         private static function receiveConversationMessage(array $importer, array $contact, SimpleXMLElement $data, array $msg, $mesg, array $conversation): bool
1587         {
1588                 $author = XML::unescape($data->author);
1589                 $guid = XML::unescape($data->guid);
1590                 $subject = XML::unescape($data->subject);
1591
1592                 // "diaspora_handle" is the element name from the old version
1593                 // "author" is the element name from the new version
1594                 if ($mesg->author) {
1595                         $msg_author = XML::unescape($mesg->author);
1596                 } elseif ($mesg->diaspora_handle) {
1597                         $msg_author = XML::unescape($mesg->diaspora_handle);
1598                 } else {
1599                         return false;
1600                 }
1601
1602                 $msg_guid = XML::unescape($mesg->guid);
1603                 $msg_conversation_guid = XML::unescape($mesg->conversation_guid);
1604                 $msg_text = XML::unescape($mesg->text);
1605                 $msg_created_at = DateTimeFormat::utc(XML::unescape($mesg->created_at));
1606
1607                 if ($msg_conversation_guid != $guid) {
1608                         Logger::notice('Message conversation guid does not belong to the current conversation.', ['guid' => $guid]);
1609                         return false;
1610                 }
1611
1612                 $body = Markdown::toBBCode($msg_text);
1613                 $message_uri = $msg_author . ':' . $msg_guid;
1614
1615                 $person = FContact::getByURL($msg_author);
1616
1617                 return Mail::insert([
1618                         'uid'        => $importer['uid'],
1619                         'guid'       => $msg_guid,
1620                         'convid'     => $conversation['id'],
1621                         'from-name'  => $person['name'],
1622                         'from-photo' => $person['photo'],
1623                         'from-url'   => $person['url'],
1624                         'contact-id' => $contact['id'],
1625                         'title'      => $subject,
1626                         'body'       => $body,
1627                         'uri'        => $message_uri,
1628                         'parent-uri' => $author . ':' . $guid,
1629                         'created'    => $msg_created_at
1630                 ]);
1631         }
1632
1633         /**
1634          * Processes new private messages (answers to private messages are processed elsewhere)
1635          *
1636          * @param array  $importer Array of the importer user
1637          * @param array  $msg      Array of the processed message, author handle and key
1638          * @param SimpleXMLElement $data     The message object
1639          *
1640          * @return bool Success
1641          * @throws \Exception
1642          */
1643         private static function receiveConversation(array $importer, array $msg, SimpleXMLElement $data)
1644         {
1645                 $author = XML::unescape($data->author);
1646                 $guid = XML::unescape($data->guid);
1647                 $subject = XML::unescape($data->subject);
1648                 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1649                 $participants = XML::unescape($data->participants);
1650
1651                 $messages = $data->message;
1652
1653                 if (!count($messages)) {
1654                         Logger::notice('Empty conversation');
1655                         return false;
1656                 }
1657
1658                 $contact = self::allowedContactByHandle($importer, $msg['author'], true);
1659                 if (!$contact) {
1660                         return false;
1661                 }
1662
1663                 if (!empty($contact['gsid'])) {
1664                         GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1665                 }
1666
1667                 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1668                 if (!DBA::isResult($conversation)) {
1669                         $r = DBA::insert('conv', [
1670                                 'uid'     => $importer['uid'],
1671                                 'guid'    => $guid,
1672                                 'creator' => $author,
1673                                 'created' => $created_at,
1674                                 'updated' => DateTimeFormat::utcNow(),
1675                                 'subject' => $subject,
1676                                 'recips'  => $participants
1677                         ]);
1678
1679                         if ($r) {
1680                                 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1681                         }
1682                 }
1683                 if (!$conversation) {
1684                         Logger::warning('Unable to create conversation.');
1685                         return false;
1686                 }
1687
1688                 foreach ($messages as $mesg) {
1689                         self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1690                 }
1691
1692                 return true;
1693         }
1694
1695         /**
1696          * Processes "like" messages
1697          *
1698          * @param array  $importer  Array of the importer user
1699          * @param string $sender    The sender of the message
1700          * @param SimpleXMLElement $data      The message object
1701          * @param int    $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1702          *
1703          * @return bool Success or failure
1704          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1705          * @throws \ImagickException
1706          */
1707         private static function receiveLike(array $importer, string $sender, SimpleXMLElement $data, int $direction): bool
1708         {
1709                 $author = XML::unescape($data->author);
1710                 $guid = XML::unescape($data->guid);
1711                 $parent_guid = XML::unescape($data->parent_guid);
1712                 $parent_type = XML::unescape($data->parent_type);
1713                 $positive = XML::unescape($data->positive);
1714
1715                 // likes on comments aren't supported by Diaspora - only on posts
1716                 // But maybe this will be supported in the future, so we will accept it.
1717                 if (!in_array($parent_type, ['Post', 'Comment'])) {
1718                         return false;
1719                 }
1720
1721                 $contact = self::allowedContactByHandle($importer, $sender, true);
1722                 if (!$contact) {
1723                         return false;
1724                 }
1725
1726                 if (!empty($contact['gsid'])) {
1727                         GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1728                 }
1729
1730                 $message_id = self::messageExists($importer['uid'], $guid);
1731                 if ($message_id) {
1732                         return true;
1733                 }
1734
1735                 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1736                 if (!$toplevel_parent_item) {
1737                         return false;
1738                 }
1739
1740                 $person = FContact::getByURL($author);
1741                 if (!is_array($person)) {
1742                         Logger::notice('Unable to find author details');
1743                         return false;
1744                 }
1745
1746                 // Fetch the contact id - if we know this contact
1747                 $author_contact = self::authorContactByUrl($contact, $person, $importer['uid']);
1748
1749                 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1750                 // We would accept this anyhow.
1751                 if ($positive == 'true') {
1752                         $verb = Activity::LIKE;
1753                 } else {
1754                         $verb = Activity::DISLIKE;
1755                 }
1756
1757                 $datarray = [];
1758
1759                 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1760
1761                 $datarray['uid'] = $importer['uid'];
1762                 $datarray['contact-id'] = $author_contact['cid'];
1763                 $datarray['network']  = $author_contact['network'];
1764
1765                 $datarray = self::setDirection($datarray, $direction);
1766
1767                 $datarray['owner-link'] = $datarray['author-link'] = $person['url'];
1768                 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($person['url'], 0);
1769
1770                 $datarray['guid'] = $guid;
1771                 $datarray['uri'] = self::getUriFromGuid($author, $guid);
1772
1773                 $datarray['verb'] = $verb;
1774                 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
1775                 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1776
1777                 $datarray['object-type'] = Activity\ObjectType::NOTE;
1778
1779                 $datarray['body'] = $verb;
1780
1781                 // Diaspora doesn't provide a date for likes
1782                 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
1783
1784                 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1785                 if ($toplevel_parent_item['gravity'] != Item::GRAVITY_PARENT) {
1786                         $toplevel = Post::selectFirst(['origin'], ['id' => $toplevel_parent_item['parent']]);
1787                         $origin = $toplevel['origin'];
1788                 } else {
1789                         $origin = $toplevel_parent_item['origin'];
1790                 }
1791
1792                 // If we are the origin of the parent we store the original data.
1793                 // We notify our followers during the item storage.
1794                 if ($origin) {
1795                         $datarray['diaspora_signed_text'] = json_encode($data);
1796                 }
1797
1798                 if (Item::isTooOld($datarray)) {
1799                         Logger::info('Like is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1800                         return false;
1801                 }
1802
1803                 $message_id = Item::insert($datarray);
1804
1805                 if ($message_id <= 0) {
1806                         return false;
1807                 }
1808
1809                 if ($message_id) {
1810                         Logger::info('Stored like ' . $datarray['guid'] . ' with message id ' . $message_id);
1811                         if ($datarray['uid'] == 0) {
1812                                 Item::distribute($message_id, json_encode($data));
1813                         }
1814                 }
1815
1816                 return true;
1817         }
1818
1819         /**
1820          * Processes private messages
1821          *
1822          * @param array  $importer Array of the importer user
1823          * @param SimpleXMLElement $data     The message object
1824          *
1825          * @return bool Success?
1826          * @throws \Exception
1827          */
1828         private static function receiveMessage(array $importer, SimpleXMLElement $data): bool
1829         {
1830                 $author = XML::unescape($data->author);
1831                 $guid = XML::unescape($data->guid);
1832                 $conversation_guid = XML::unescape($data->conversation_guid);
1833                 $text = XML::unescape($data->text);
1834                 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1835
1836                 $contact = self::allowedContactByHandle($importer, $author, true);
1837                 if (!$contact) {
1838                         return false;
1839                 }
1840
1841                 if (!empty($contact['gsid'])) {
1842                         GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1843                 }
1844
1845                 $conversation = null;
1846
1847                 $condition = ['uid' => $importer['uid'], 'guid' => $conversation_guid];
1848                 $conversation = DBA::selectFirst('conv', [], $condition);
1849
1850                 if (!DBA::isResult($conversation)) {
1851                         Logger::notice('Conversation not available.');
1852                         return false;
1853                 }
1854
1855                 $message_uri = $author . ':' . $guid;
1856
1857                 $person = FContact::getByURL($author);
1858                 if (!$person) {
1859                         Logger::notice('Unable to find author details');
1860                         return false;
1861                 }
1862
1863                 $body = Markdown::toBBCode($text);
1864
1865                 $body = self::replacePeopleGuid($body, $person['url']);
1866
1867                 return Mail::insert([
1868                         'uid'        => $importer['uid'],
1869                         'guid'       => $guid,
1870                         'convid'     => $conversation['id'],
1871                         'from-name'  => $person['name'],
1872                         'from-photo' => $person['photo'],
1873                         'from-url'   => $person['url'],
1874                         'contact-id' => $contact['id'],
1875                         'title'      => $conversation['subject'],
1876                         'body'       => $body,
1877                         'reply'      => 1,
1878                         'uri'        => $message_uri,
1879                         'parent-uri' => $author . ':' . $conversation['guid'],
1880                         'created'    => $created_at
1881                 ]);
1882         }
1883
1884         /**
1885          * Processes participations - unsupported by now
1886          *
1887          * @param array  $importer  Array of the importer user
1888          * @param SimpleXMLElement $data      The message object
1889          * @param int    $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1890          *
1891          * @return bool success
1892          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1893          * @throws \ImagickException
1894          */
1895         private static function receiveParticipation(array $importer, SimpleXMLElement $data, int $direction): bool
1896         {
1897                 $author = strtolower(XML::unescape($data->author));
1898                 $guid = XML::unescape($data->guid);
1899                 $parent_guid = XML::unescape($data->parent_guid);
1900
1901                 $contact = self::allowedContactByHandle($importer, $author, true);
1902                 if (!$contact) {
1903                         return false;
1904                 }
1905
1906                 if (!empty($contact['gsid'])) {
1907                         GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1908                 }
1909
1910                 if (self::messageExists($importer['uid'], $guid)) {
1911                         return true;
1912                 }
1913
1914                 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1915                 if (!$toplevel_parent_item) {
1916                         return false;
1917                 }
1918
1919                 if (!$toplevel_parent_item['origin']) {
1920                         Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1921                 }
1922
1923                 if (!in_array($toplevel_parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
1924                         Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1925                         return false;
1926                 }
1927
1928                 $person = FContact::getByURL($author);
1929                 if (!is_array($person)) {
1930                         Logger::notice('Person not found: ' . $author);
1931                         return false;
1932                 }
1933
1934                 $author_contact = self::authorContactByUrl($contact, $person, $importer['uid']);
1935
1936                 // Store participation
1937                 $datarray = [];
1938
1939                 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1940
1941                 $datarray['uid'] = $importer['uid'];
1942                 $datarray['contact-id'] = $author_contact['cid'];
1943                 $datarray['network']  = $author_contact['network'];
1944
1945                 $datarray = self::setDirection($datarray, $direction);
1946
1947                 $datarray['owner-link'] = $datarray['author-link'] = $person['url'];
1948                 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($person['url'], 0);
1949
1950                 $datarray['guid'] = $guid;
1951                 $datarray['uri'] = self::getUriFromGuid($author, $guid);
1952
1953                 $datarray['verb'] = Activity::FOLLOW;
1954                 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
1955                 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1956
1957                 $datarray['object-type'] = Activity\ObjectType::NOTE;
1958
1959                 $datarray['body'] = Activity::FOLLOW;
1960
1961                 // Diaspora doesn't provide a date for a participation
1962                 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
1963
1964                 if (Item::isTooOld($datarray)) {
1965                         Logger::info('Participation is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1966                         return false;
1967                 }
1968
1969                 $message_id = Item::insert($datarray);
1970
1971                 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
1972
1973                 // Send all existing comments and likes to the requesting server
1974                 $comments = Post::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb', 'gravity'],
1975                         ['parent' => $toplevel_parent_item['id'], 'gravity' => [Item::GRAVITY_COMMENT, Item::GRAVITY_ACTIVITY]]);
1976                 while ($comment = Post::fetch($comments)) {
1977                         if (($comment['gravity'] == Item::GRAVITY_ACTIVITY) && !in_array($comment['verb'], [Activity::LIKE, Activity::DISLIKE])) {
1978                                 Logger::info('Unsupported activities are not relayed', ['item' => $comment['id'], 'verb' => $comment['verb']]);
1979                                 continue;
1980                         }
1981
1982                         if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
1983                                 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
1984                                 continue;
1985                         }
1986
1987                         if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
1988                                 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
1989                                 continue;
1990                         }
1991
1992                         Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact['cid']]);
1993                         if (Worker::add(Worker::PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['uri-id'], $author_contact['cid'], $datarray['uid'])) {
1994                                 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
1995                         }
1996                 }
1997                 DBA::close($comments);
1998
1999                 return true;
2000         }
2001
2002         /**
2003          * Processes photos - unneeded
2004          *
2005          * @param array  $importer Array of the importer user
2006          * @param SimpleXMLElement $data     The message object
2007          *
2008          * @return bool always true
2009          */
2010         private static function receivePhoto(array $importer, $data)
2011         {
2012                 // There doesn't seem to be a reason for this function,
2013                 // since the photo data is transmitted in the status message as well
2014                 return true;
2015         }
2016
2017         /**
2018          * Processes poll participations - unssupported
2019          *
2020          * @param array  $importer Array of the importer user
2021          * @param object $data     The message object
2022          *
2023          * @return bool always true
2024          */
2025         private static function receivePollParticipation(array $importer, $data)
2026         {
2027                 // We don't support polls by now
2028                 return true;
2029         }
2030
2031         /**
2032          * Processes incoming profile updates
2033          *
2034          * @param array  $importer Array of the importer user
2035          * @param SimpleXMLElement $data     The message object
2036          *
2037          * @return bool Success
2038          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2039          * @throws \ImagickException
2040          */
2041         private static function receiveProfile(array $importer, SimpleXMLElement $data): bool
2042         {
2043                 $author = strtolower(XML::unescape($data->author));
2044
2045                 $contact = self::contactByHandle($importer['uid'], $author);
2046                 if (!$contact) {
2047                         return false;
2048                 }
2049
2050                 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? ' ' . XML::unescape($data->last_name) : '');
2051                 $image_url = XML::unescape($data->image_url);
2052                 $birthday = XML::unescape($data->birthday);
2053                 $about = Markdown::toBBCode(XML::unescape($data->bio));
2054                 $location = Markdown::toBBCode(XML::unescape($data->location));
2055                 $searchable = (XML::unescape($data->searchable) == 'true');
2056                 $nsfw = (XML::unescape($data->nsfw) == 'true');
2057                 $tags = XML::unescape($data->tag_string);
2058
2059                 $tags = explode('#', $tags);
2060
2061                 $keywords = [];
2062                 foreach ($tags as $tag) {
2063                         $tag = trim(strtolower($tag));
2064                         if ($tag != '') {
2065                                 $keywords[] = $tag;
2066                         }
2067                 }
2068
2069                 $keywords = implode(', ', $keywords);
2070
2071                 $handle_parts = explode('@', $author);
2072                 $nick = $handle_parts[0];
2073
2074                 if ($name === '') {
2075                         $name = $handle_parts[0];
2076                 }
2077
2078                 if (preg_match('|^https?://|', $image_url) === 0) {
2079                         // @TODO No HTTPS here?
2080                         $image_url = 'http://' . $handle_parts[1] . $image_url;
2081                 }
2082
2083                 Contact::updateAvatar($contact['id'], $image_url);
2084
2085                 // Generic birthday. We don't know the timezone. The year is irrelevant.
2086
2087                 $birthday = str_replace('1000', '1901', $birthday);
2088
2089                 if ($birthday != '') {
2090                         $birthday = DateTimeFormat::utc($birthday, 'Y-m-d');
2091                 }
2092
2093                 // this is to prevent multiple birthday notifications in a single year
2094                 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2095
2096                 if (substr($birthday, 5) === substr($contact['bd'], 5)) {
2097                         $birthday = $contact['bd'];
2098                 }
2099
2100                 $fields = ['name' => $name, 'location' => $location,
2101                         'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2102                         'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2103                         'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2104
2105                 if (!empty($birthday)) {
2106                         $fields['bd'] = $birthday;
2107                 }
2108
2109                 Contact::update($fields, ['id' => $contact['id']]);
2110
2111                 Logger::info('Profile of contact ' . $contact['id'] . ' stored for user ' . $importer['uid']);
2112
2113                 return true;
2114         }
2115
2116         /**
2117          * Processes incoming friend requests
2118          *
2119          * @param array $importer Array of the importer user
2120          * @param array $contact  The contact that send the request
2121          * @return void
2122          * @throws \Exception
2123          */
2124         private static function receiveRequestMakeFriend(array $importer, array $contact)
2125         {
2126                 if ($contact['rel'] == Contact::SHARING) {
2127                         Contact::update(
2128                                 ['rel' => Contact::FRIEND, 'writable' => true],
2129                                 ['id' => $contact['id'], 'uid' => $importer['uid']]
2130                         );
2131                 }
2132         }
2133
2134         /**
2135          * Processes incoming sharing notification
2136          *
2137          * @param array  $importer Array of the importer user
2138          * @param SimpleXMLElement $data     The message object
2139          *
2140          * @return bool Success
2141          * @throws \Exception
2142          */
2143         private static function receiveContactRequest(array $importer, SimpleXMLElement $data): bool
2144         {
2145                 $author = XML::unescape($data->author);
2146                 $recipient = XML::unescape($data->recipient);
2147
2148                 if (!$author || !$recipient) {
2149                         return false;
2150                 }
2151
2152                 // the current protocol version doesn't know these fields
2153                 // That means that we will assume their existance
2154                 if (isset($data->following)) {
2155                         $following = (XML::unescape($data->following) == 'true');
2156                 } else {
2157                         $following = true;
2158                 }
2159
2160                 if (isset($data->sharing)) {
2161                         $sharing = (XML::unescape($data->sharing) == 'true');
2162                 } else {
2163                         $sharing = true;
2164                 }
2165
2166                 $contact = self::contactByHandle($importer['uid'], $author);
2167
2168                 // perhaps we were already sharing with this person. Now they're sharing with us.
2169                 // That makes us friends.
2170                 if ($contact) {
2171                         if ($following) {
2172                                 Logger::info('Author ' . $author . ' (Contact ' . $contact['id'] . ') wants to follow us.');
2173                                 self::receiveRequestMakeFriend($importer, $contact);
2174
2175                                 // refetch the contact array
2176                                 $contact = self::contactByHandle($importer['uid'], $author);
2177
2178                                 // If we are now friends, we are sending a share message.
2179                                 // Normally we needn't to do so, but the first message could have been vanished.
2180                                 if (in_array($contact['rel'], [Contact::FRIEND])) {
2181                                         $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2182                                         if (DBA::isResult($user)) {
2183                                                 Logger::info('Sending share message to author ' . $author . ' - Contact: ' . $contact['id'] . ' - User: ' . $importer['uid']);
2184                                                 self::sendShare($user, $contact);
2185                                         }
2186                                 }
2187                                 return true;
2188                         } else {
2189                                 Logger::info("Author " . $author . " doesn't want to follow us anymore.");
2190                                 Contact::removeFollower($contact);
2191                                 return true;
2192                         }
2193                 }
2194
2195                 if (!$following && $sharing && in_array($importer['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2196                         Logger::info("Author " . $author . " wants to share with us - but doesn't want to listen. Request is ignored.");
2197                         return false;
2198                 } elseif (!$following && !$sharing) {
2199                         Logger::info("Author " . $author . " doesn't want anything - and we don't know the author. Request is ignored.");
2200                         return false;
2201                 } elseif (!$following && $sharing) {
2202                         Logger::info("Author " . $author . " wants to share with us.");
2203                 } elseif ($following && $sharing) {
2204                         Logger::info("Author " . $author . " wants to have a bidirectional conection.");
2205                 } elseif ($following && !$sharing) {
2206                         Logger::info("Author " . $author . " wants to listen to us.");
2207                 }
2208
2209                 $ret = FContact::getByURL($author);
2210
2211                 if (!$ret || ($ret['network'] != Protocol::DIASPORA)) {
2212                         Logger::notice("Cannot resolve diaspora handle " . $author . " for ".$recipient);
2213                         return false;
2214                 }
2215
2216                 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2217                 if (!empty($cid)) {
2218                         $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2219                 } else {
2220                         $contact = [];
2221                 }
2222
2223                 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2224                         'author-link' => $ret['url']];
2225
2226                 $result = Contact::addRelationship($importer, $contact, $item, false);
2227                 if ($result === true) {
2228                         $contact_record = self::contactByHandle($importer['uid'], $author);
2229                         if (!$contact_record) {
2230                                 Logger::info('unable to locate newly created contact record.');
2231                                 return false;
2232                         }
2233
2234                         $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2235                         if (DBA::isResult($user)) {
2236                                 self::sendShare($user, $contact_record);
2237
2238                                 // Send the profile data, maybe it weren't transmitted before
2239                                 self::sendProfile($importer['uid'], [$contact_record]);
2240                         }
2241                 }
2242
2243                 return true;
2244         }
2245
2246         /**
2247          * Stores a reshare activity
2248          *
2249          * @param array   $item              Array of reshare post
2250          * @param integer $parent_message_id Id of the parent post
2251          * @param string  $guid              GUID string of reshare action
2252          * @param string  $author            Author handle
2253          */
2254         private static function addReshareActivity(array $item, int $parent_message_id, string $guid, string $author)
2255         {
2256                 $parent = Post::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2257
2258                 $datarray = [];
2259
2260                 $datarray['uid'] = $item['uid'];
2261                 $datarray['contact-id'] = $item['contact-id'];
2262                 $datarray['network'] = $item['network'];
2263
2264                 $datarray['author-link'] = $item['author-link'];
2265                 $datarray['author-id'] = $item['author-id'];
2266
2267                 $datarray['owner-link'] = $datarray['author-link'];
2268                 $datarray['owner-id'] = $datarray['author-id'];
2269
2270                 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2271                 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2272                 $datarray['thr-parent'] = $parent['uri'];
2273
2274                 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2275                 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
2276                 $datarray['object-type'] = Activity\ObjectType::NOTE;
2277
2278                 $datarray['protocol'] = $item['protocol'];
2279                 $datarray['source'] = $item['source'];
2280                 $datarray['direction'] = $item['direction'];
2281                 $datarray['post-reason'] = $item['post-reason'];
2282
2283                 $datarray['plink'] = self::plink($author, $datarray['guid']);
2284                 $datarray['private'] = $item['private'];
2285                 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2286
2287                 if (Item::isTooOld($datarray)) {
2288                         Logger::info('Reshare activity is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2289                         return false;
2290                 }
2291
2292                 $message_id = Item::insert($datarray);
2293
2294                 if ($message_id) {
2295                         Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2296                         if ($datarray['uid'] == 0) {
2297                                 Item::distribute($message_id);
2298                         }
2299                 }
2300         }
2301
2302         /**
2303          * Processes a reshare message
2304          *
2305          * @param array  $importer  Array of the importer user
2306          * @param SimpleXMLElement $data      The message object
2307          * @param string $xml       The original XML of the message
2308          * @param int    $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2309          *
2310          * @return bool Success or failure
2311          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2312          * @throws \ImagickException
2313          */
2314         private static function receiveReshare(array $importer, SimpleXMLElement $data, string $xml, int $direction): bool
2315         {
2316                 $author = XML::unescape($data->author);
2317                 $guid = XML::unescape($data->guid);
2318                 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2319                 $root_author = XML::unescape($data->root_author);
2320                 $root_guid = XML::unescape($data->root_guid);
2321                 /// @todo handle unprocessed property "provider_display_name"
2322                 $public = XML::unescape($data->public);
2323
2324                 $contact = self::allowedContactByHandle($importer, $author, false);
2325                 if (!$contact) {
2326                         return false;
2327                 }
2328
2329                 if (!empty($contact['gsid'])) {
2330                         GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2331                 }
2332
2333                 $message_id = self::messageExists($importer['uid'], $guid);
2334                 if ($message_id) {
2335                         return true;
2336                 }
2337
2338                 $original_person = FContact::getByURL($root_author);
2339                 if (!$original_person) {
2340                         return false;
2341                 }
2342
2343                 $datarray = [];
2344
2345                 $datarray['uid'] = $importer['uid'];
2346                 $datarray['contact-id'] = $contact['id'];
2347                 $datarray['network']  = Protocol::DIASPORA;
2348
2349                 $datarray['author-link'] = $contact['url'];
2350                 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2351
2352                 $datarray['owner-link'] = $datarray['author-link'];
2353                 $datarray['owner-id'] = $datarray['author-id'];
2354
2355                 $datarray['guid'] = $guid;
2356                 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($author, $guid);
2357                 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2358
2359                 $datarray['verb'] = Activity::POST;
2360                 $datarray['gravity'] = Item::GRAVITY_PARENT;
2361
2362                 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2363                 $datarray['source'] = $xml;
2364
2365                 $datarray = self::setDirection($datarray, $direction);
2366
2367                 $datarray['body'] = DI::contentItem()->createSharedPostByGuid($root_guid, $importer['uid'], $original_person['url']);
2368                 $datarray['body'] = Diaspora::replacePeopleGuid($datarray['body'], $datarray['author-link']);
2369
2370                 /// @todo Copy tag data from original post
2371                 Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
2372
2373                 $datarray['plink'] = self::plink($author, $guid);
2374                 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2375                 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2376
2377                 self::fetchGuid($datarray);
2378
2379                 if (Item::isTooOld($datarray)) {
2380                         Logger::info('Reshare is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2381                         return false;
2382                 }
2383
2384                 $message_id = Item::insert($datarray);
2385
2386                 self::sendParticipation($contact, $datarray);
2387
2388                 $root_message_id = self::messageExists($importer['uid'], $root_guid);
2389                 if ($root_message_id) {
2390                         self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2391                 }
2392
2393                 if ($message_id) {
2394                         Logger::info('Stored reshare ' . $datarray['guid'] . ' with message id ' . $message_id);
2395                         if ($datarray['uid'] == 0) {
2396                                 Item::distribute($message_id);
2397                         }
2398                         return true;
2399                 } else {
2400                         return false;
2401                 }
2402         }
2403
2404         /**
2405          * Processes retractions
2406          *
2407          * @param array  $importer Array of the importer user
2408          * @param array  $contact  The contact of the item owner
2409          * @param SimpleXMLElement $data     The message object
2410          *
2411          * @return bool success
2412          * @throws \Exception
2413          */
2414         private static function itemRetraction(array $importer, array $contact, SimpleXMLElement $data): bool
2415         {
2416                 $author = XML::unescape($data->author);
2417                 $target_guid = XML::unescape($data->target_guid);
2418                 $target_type = XML::unescape($data->target_type);
2419
2420                 $person = FContact::getByURL($author);
2421                 if (!is_array($person)) {
2422                         Logger::notice('Unable to find author detail for ' . $author);
2423                         return false;
2424                 }
2425
2426                 if (empty($contact['url'])) {
2427                         $contact['url'] = $person['url'];
2428                 }
2429
2430                 // Fetch items that are about to be deleted
2431                 $fields = ['uid', 'id', 'parent', 'author-link', 'uri-id'];
2432
2433                 // When we receive a public retraction, we delete every item that we find.
2434                 if ($importer['uid'] == 0) {
2435                         $condition = ['guid' => $target_guid, 'deleted' => false];
2436                 } else {
2437                         $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2438                 }
2439
2440                 $r = Post::select($fields, $condition);
2441                 if (!DBA::isResult($r)) {
2442                         Logger::notice('Target guid ' . $target_guid . ' was not found on this system for user ' . $importer['uid'] . '.');
2443                         return false;
2444                 }
2445
2446                 while ($item = Post::fetch($r)) {
2447                         if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2448                                 Logger::info("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.");
2449                                 continue;
2450                         }
2451
2452                         // Fetch the parent item
2453                         $parent = Post::selectFirst(['author-link'], ['id' => $item['parent']]);
2454
2455                         // Only delete it if the parent author really fits
2456                         if (!Strings::compareLink($parent['author-link'], $contact['url']) && !Strings::compareLink($item['author-link'], $contact['url'])) {
2457                                 Logger::info("Thread author " . $parent['author-link'] . " and item author " . $item['author-link'] . " don't fit to expected contact " . $contact['url']);
2458                                 continue;
2459                         }
2460
2461                         Item::markForDeletion(['id' => $item['id']]);
2462
2463                         Logger::info('Deleted target ' . $target_guid . ' (' . $item['id'] . ') from user ' . $item['uid'] . ' parent: ' . $item['parent']);
2464                 }
2465                 DBA::close($r);
2466
2467                 return true;
2468         }
2469
2470         /**
2471          * Receives retraction messages
2472          *
2473          * @param array  $importer Array of the importer user
2474          * @param string $sender   The sender of the message
2475          * @param SimpleXMLElement $data     The message object
2476          *
2477          * @return bool Success
2478          * @throws \Exception
2479          */
2480         private static function receiveRetraction(array $importer, string $sender, SimpleXMLElement $data)
2481         {
2482                 $target_type = XML::unescape($data->target_type);
2483
2484                 $contact = self::contactByHandle($importer['uid'], $sender);
2485                 if (!$contact && (in_array($target_type, ['Contact', 'Person']))) {
2486                         Logger::notice('Cannot find contact for sender: ' . $sender . ' and user ' . $importer['uid']);
2487                         return false;
2488                 }
2489
2490                 if (!$contact) {
2491                         $contact = [];
2492                 }
2493
2494                 Logger::info('Got retraction for ' . $target_type . ', sender ' . $sender . ' and user ' . $importer['uid']);
2495
2496                 switch ($target_type) {
2497                         case 'Comment':
2498                         case 'Like':
2499                         case 'Post':
2500                         case 'Reshare':
2501                         case 'StatusMessage':
2502                                 return self::itemRetraction($importer, $contact, $data);
2503
2504                         case 'PollParticipation':
2505                         case 'Photo':
2506                                 // Currently unsupported
2507                                 break;
2508
2509                         default:
2510                                 Logger::notice('Unknown target type ' . $target_type);
2511                                 return false;
2512                 }
2513                 return true;
2514         }
2515
2516         /**
2517          * Checks if an incoming message is wanted
2518          *
2519          * @param array  $item
2520          * @param string $author
2521          * @param string $body
2522          * @param int    $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2523          *
2524          * @return boolean Is the message wanted?
2525          */
2526         private static function isSolicitedMessage(array $item, string $author, string $body, int $direction): bool
2527         {
2528                 $contact = Contact::getByURL($author);
2529                 if (DBA::exists('contact', ['`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)', $contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) {
2530                         Logger::debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2531                         return true;
2532                 }
2533
2534                 if ($direction == self::FORCED_FETCH) {
2535                         Logger::debug('Post is a forced fetch - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2536                         return true;
2537                 }
2538
2539                 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
2540                 if (Relay::isSolicitedPost($tags, $body, $contact['id'], $item['uri'], Protocol::DIASPORA)) {
2541                         Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2542                         return true;
2543                 } else {
2544                         return false;
2545                 }
2546         }
2547
2548         /**
2549          * Store an attached photo in the post-media table
2550          *
2551          * @param int $uriid
2552          * @param object $photo
2553          * @return void
2554          */
2555         private static function storePhotoAsMedia(int $uriid, $photo)
2556         {
2557                 // @TODO Need to find object type, roland@f.haeder.net
2558                 Logger::debug('photo='.get_class($photo));
2559                 $data = [];
2560                 $data['uri-id'] = $uriid;
2561                 $data['type'] = Post\Media::IMAGE;
2562                 $data['url'] = XML::unescape($photo->remote_photo_path) . XML::unescape($photo->remote_photo_name);
2563                 $data['height'] = (int)XML::unescape($photo->height ?? 0);
2564                 $data['width'] = (int)XML::unescape($photo->width ?? 0);
2565                 $data['description'] = XML::unescape($photo->text ?? '');
2566
2567                 Post\Media::insert($data);
2568         }
2569
2570         /**
2571          * Set direction and post reason
2572          *
2573          * @param array $datarray
2574          * @param integer $direction
2575          *
2576          * @return array
2577          */
2578         public static function setDirection(array $datarray, int $direction): array
2579         {
2580                 $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
2581
2582                 if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
2583                         $datarray['post-reason'] = Item::PR_FETCHED;
2584                 } elseif ($datarray['uid'] == 0) {
2585                         $datarray['post-reason'] = Item::PR_GLOBAL;
2586                 } else {
2587                         $datarray['post-reason'] = Item::PR_PUSHED;
2588                 }
2589
2590                 return $datarray;
2591         }
2592
2593         /**
2594          * Receives status messages
2595          *
2596          * @param array            $importer  Array of the importer user
2597          * @param SimpleXMLElement $data      The message object
2598          * @param string           $xml       The original XML of the message
2599          * @param int              $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2600          *
2601          * @return int|bool The message id of the newly created item or false on error
2602          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2603          * @throws \ImagickException
2604          */
2605         private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, string $xml, int $direction)
2606         {
2607                 $author = XML::unescape($data->author);
2608                 $guid = XML::unescape($data->guid);
2609                 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2610                 $public = XML::unescape($data->public);
2611                 $text = XML::unescape($data->text);
2612                 $provider_display_name = XML::unescape($data->provider_display_name);
2613
2614                 $contact = self::allowedContactByHandle($importer, $author, false);
2615                 if (!$contact) {
2616                         return false;
2617                 }
2618
2619                 if (!empty($contact['gsid'])) {
2620                         GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2621                 }
2622
2623                 $message_id = self::messageExists($importer['uid'], $guid);
2624                 if ($message_id) {
2625                         return true;
2626                 }
2627
2628                 $address = [];
2629                 if ($data->location) {
2630                         foreach ($data->location->children() as $fieldname => $data) {
2631                                 $address[$fieldname] = XML::unescape($data);
2632                         }
2633                 }
2634
2635                 $raw_body = $body = Markdown::toBBCode($text);
2636
2637                 $datarray = [];
2638
2639                 $datarray['guid'] = $guid;
2640                 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($author, $guid);
2641                 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2642
2643                 // Attach embedded pictures to the body
2644                 if ($data->photo) {
2645                         foreach ($data->photo as $photo) {
2646                                 self::storePhotoAsMedia($datarray['uri-id'], $photo);
2647                         }
2648
2649                         $datarray['object-type'] = Activity\ObjectType::IMAGE;
2650                         $datarray['post-type'] = Item::PT_IMAGE;
2651                 } elseif ($data->poll) {
2652                         $datarray['object-type'] = Activity\ObjectType::NOTE;
2653                         $datarray['post-type'] = Item::PT_POLL;
2654                 } else {
2655                         $datarray['object-type'] = Activity\ObjectType::NOTE;
2656                         $datarray['post-type'] = Item::PT_NOTE;
2657                 }
2658
2659                 /// @todo enable support for polls
2660                 //if ($data->poll) {
2661                 //      foreach ($data->poll as $poll)
2662                 //              print_r($poll);
2663                 //      die("poll!\n");
2664                 //}
2665
2666                 /// @todo enable support for events
2667
2668                 $datarray['uid'] = $importer['uid'];
2669                 $datarray['contact-id'] = $contact['id'];
2670                 $datarray['network'] = Protocol::DIASPORA;
2671
2672                 $datarray['author-link'] = $contact['url'];
2673                 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2674
2675                 $datarray['owner-link'] = $datarray['author-link'];
2676                 $datarray['owner-id'] = $datarray['author-id'];
2677
2678                 $datarray['verb'] = Activity::POST;
2679                 $datarray['gravity'] = Item::GRAVITY_PARENT;
2680
2681                 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2682                 $datarray['source'] = $xml;
2683
2684                 $datarray = self::setDirection($datarray, $direction);
2685
2686                 $datarray['body'] = self::replacePeopleGuid($body, $contact['url']);
2687                 $datarray['raw-body'] = self::replacePeopleGuid($raw_body, $contact['url']);
2688
2689                 self::storeMentions($datarray['uri-id'], $text);
2690                 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
2691
2692                 if (!self::isSolicitedMessage($datarray, $author, $body, $direction)) {
2693                         DBA::delete('item-uri', ['uri' => $datarray['uri']]);
2694                         return false;
2695                 }
2696
2697                 if ($provider_display_name != '') {
2698                         $datarray['app'] = $provider_display_name;
2699                 }
2700
2701                 $datarray['plink'] = self::plink($author, $guid);
2702                 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2703                 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2704
2705                 if (isset($address['address'])) {
2706                         $datarray['location'] = $address['address'];
2707                 }
2708
2709                 if (isset($address['lat']) && isset($address['lng'])) {
2710                         $datarray['coord'] = $address['lat'] . ' ' . $address['lng'];
2711                 }
2712
2713                 self::fetchGuid($datarray);
2714
2715                 if (Item::isTooOld($datarray)) {
2716                         Logger::info('Status is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2717                         return false;
2718                 }
2719
2720                 $message_id = Item::insert($datarray);
2721
2722                 self::sendParticipation($contact, $datarray);
2723
2724                 if ($message_id) {
2725                         Logger::info('Stored item ' . $datarray['guid'] . ' with message id ' . $message_id);
2726                         if ($datarray['uid'] == 0) {
2727                                 Item::distribute($message_id);
2728                         }
2729                         return true;
2730                 } else {
2731                         return false;
2732                 }
2733         }
2734
2735         /* ************************************************************************************** *
2736          * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2737          * ************************************************************************************** */
2738
2739         /**
2740          * returnes the handle of a contact
2741          *
2742          * @param array $contact contact array
2743          *
2744          * @return string the handle in the format user@domain.tld
2745          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2746          */
2747         private static function myHandle(array $contact): string
2748         {
2749                 if (!empty($contact['addr'])) {
2750                         return $contact['addr'];
2751                 }
2752
2753                 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2754                 // So - just in case - we build the the address here.
2755                 if ($contact['nickname'] != '') {
2756                         $nick = $contact['nickname'];
2757                 } else {
2758                         $nick = $contact['nick'];
2759                 }
2760
2761                 return $nick . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
2762         }
2763
2764
2765         /**
2766          * Creates the data for a private message in the new format
2767          *
2768          * @param string $msg     The message that is to be transmitted
2769          * @param array  $user    The record of the sender
2770          * @param array  $contact Target of the communication
2771          * @param string $prvkey  The private key of the sender
2772          * @param string $pubkey  The public key of the receiver
2773          *
2774          * @return string The encrypted data
2775          * @throws \Exception
2776          */
2777         public static function encodePrivateData(string $msg, array $user, array $contact, string $prvkey, string $pubkey): string
2778         {
2779                 Logger::debug('Message: ' . $msg);
2780
2781                 // without a public key nothing will work
2782                 if (!$pubkey) {
2783                         Logger::notice('pubkey missing: contact id: ' . $contact['id']);
2784                         return false;
2785                 }
2786
2787                 $aes_key = random_bytes(32);
2788                 $b_aes_key = base64_encode($aes_key);
2789                 $iv = random_bytes(16);
2790                 $b_iv = base64_encode($iv);
2791
2792                 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2793
2794                 $json = json_encode(['iv' => $b_iv, 'key' => $b_aes_key]);
2795
2796                 $encrypted_key_bundle = '';
2797                 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
2798                         return false;
2799                 }
2800
2801                 $json_object = json_encode(
2802                         [
2803                                 'aes_key' => base64_encode($encrypted_key_bundle),
2804                                 'encrypted_magic_envelope' => base64_encode($ciphertext)
2805                         ]
2806                 );
2807
2808                 return $json_object;
2809         }
2810
2811         /**
2812          * Creates the envelope for the "fetch" endpoint and for the new format
2813          *
2814          * @param string $msg  The message that is to be transmitted
2815          * @param array  $user The record of the sender
2816          *
2817          * @return string The envelope
2818          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2819          */
2820         public static function buildMagicEnvelope(string $msg, array $user): string
2821         {
2822                 $b64url_data = Strings::base64UrlEncode($msg);
2823                 $data = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
2824
2825                 $key_id = Strings::base64UrlEncode(self::myHandle($user));
2826                 $type = 'application/xml';
2827                 $encoding = 'base64url';
2828                 $alg = 'RSA-SHA256';
2829                 $signable_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
2830
2831                 // Fallback if the private key wasn't transmitted in the expected field
2832                 if ($user['uprvkey'] == '') {
2833                         $user['uprvkey'] = $user['prvkey'];
2834                 }
2835
2836                 $signature = Crypto::rsaSign($signable_data, $user['uprvkey']);
2837                 $sig = Strings::base64UrlEncode($signature);
2838
2839                 $xmldata = [
2840                         'me:env' => [
2841                                 'me:data' => $data,
2842                                 '@attributes' => ['type' => $type],
2843                                 'me:encoding' => $encoding,
2844                                 'me:alg' => $alg,
2845                                 'me:sig' => $sig,
2846                                 '@attributes2' => ['key_id' => $key_id]
2847                         ]
2848                 ];
2849
2850                 $namespaces = ['me' => ActivityNamespace::SALMON_ME];
2851
2852                 return XML::fromArray($xmldata, $xml, false, $namespaces);
2853         }
2854
2855         /**
2856          * Create the envelope for a message
2857          *
2858          * @param string $msg     The message that is to be transmitted
2859          * @param array  $user    The record of the sender
2860          * @param array  $contact Target of the communication
2861          * @param string $prvkey  The private key of the sender
2862          * @param string $pubkey  The public key of the receiver
2863          * @param bool   $public  Is the message public?
2864          *
2865          * @return string The message that will be transmitted to other servers
2866          * @throws \Exception
2867          */
2868         public static function buildMessage(string $msg, array $user, array $contact, string $prvkey, string $pubkey, bool $public = false): string
2869         {
2870                 // The message is put into an envelope with the sender's signature
2871                 $envelope = self::buildMagicEnvelope($msg, $user);
2872
2873                 // Private messages are put into a second envelope, encrypted with the receivers public key
2874                 if (!$public) {
2875                         $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
2876                 }
2877
2878                 return $envelope;
2879         }
2880
2881         /**
2882          * Creates a signature for a message
2883          *
2884          * @param array $owner   the array of the owner of the message
2885          * @param array $message The message that is to be signed
2886          *
2887          * @return string The signature
2888          */
2889         private static function signature(array $owner, array $message): string
2890         {
2891                 $sigmsg = $message;
2892                 unset($sigmsg['author_signature']);
2893                 unset($sigmsg['parent_author_signature']);
2894
2895                 $signed_text = implode(';', $sigmsg);
2896
2897                 return base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
2898         }
2899
2900         /**
2901          * Transmit a message to a target server
2902          *
2903          * @param array  $owner        the array of the item owner
2904          * @param array  $contact      Target of the communication
2905          * @param string $envelope     The message that is to be transmitted
2906          * @param bool   $public_batch Is it a public post?
2907          * @param string $guid         message guid
2908          *
2909          * @return int Result of the transmission
2910          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2911          * @throws \ImagickException
2912          */
2913         private static function transmit(array $owner, array $contact, string $envelope, bool $public_batch, string $guid = ''): int
2914         {
2915                 $enabled = intval(DI::config()->get('system', 'diaspora_enabled'));
2916                 if (!$enabled) {
2917                         return 200;
2918                 }
2919
2920                 $logid = Strings::getRandomHex(4);
2921
2922                 // We always try to use the data from the fcontact table.
2923                 // This is important for transmitting data to Friendica servers.
2924                 if (!empty($contact['addr'])) {
2925                         $fcontact = FContact::getByURL($contact['addr']);
2926                         if (!empty($fcontact)) {
2927                                 $dest_url = ($public_batch ? $fcontact['batch'] : $fcontact['notify']);
2928                         }
2929                 }
2930
2931                 if (empty($dest_url)) {
2932                         $dest_url = ($public_batch ? $contact['batch'] : $contact['notify']);
2933                 }
2934
2935                 if (!$dest_url) {
2936                         Logger::notice('No URL for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2937                         return 0;
2938                 }
2939
2940                 Logger::notice('transmit: ' . $logid . '-' . $guid . ' ' . $dest_url);
2941
2942                 if (!intval(DI::config()->get('system', 'diaspora_test'))) {
2943                         $content_type = (($public_batch) ? 'application/magic-envelope+xml' : 'application/json');
2944
2945                         $postResult = DI::httpClient()->post($dest_url . '/', $envelope, ['Content-Type' => $content_type]);
2946                         $return_code = $postResult->getReturnCode();
2947                 } else {
2948                         Logger::notice('test_mode');
2949                         return 200;
2950                 }
2951
2952                 Logger::notice('transmit: ' . $logid . '-' . $guid . ' to ' . $dest_url . ' returns: ' . $return_code);
2953
2954                 return $return_code ? $return_code : -1;
2955         }
2956
2957
2958         /**
2959          * Build the post xml
2960          *
2961          * @param string $type    The message type
2962          * @param array  $message The message data
2963          *
2964          * @return string The post XML
2965          */
2966         public static function buildPostXml(string $type, array $message): string
2967         {
2968                 $data = [$type => $message];
2969
2970                 return XML::fromArray($data, $xml);
2971         }
2972
2973         /**
2974          * Builds and transmit messages
2975          *
2976          * @param array  $owner        the array of the item owner
2977          * @param array  $contact      Target of the communication
2978          * @param string $type         The message type
2979          * @param array  $message      The message data
2980          * @param bool   $public_batch Is it a public post?
2981          * @param string $guid         message guid
2982          *
2983          * @return int Result of the transmission
2984          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2985          * @throws \ImagickException
2986          */
2987         private static function buildAndTransmit(array $owner, array $contact, string $type, array $message, bool $public_batch = false, string $guid = '')
2988         {
2989                 $msg = self::buildPostXml($type, $message);
2990
2991                 // Fallback if the private key wasn't transmitted in the expected field
2992                 if (empty($owner['uprvkey'])) {
2993                         $owner['uprvkey'] = $owner['prvkey'];
2994                 }
2995
2996                 // When sending content to Friendica contacts using the Diaspora protocol
2997                 // we have to fetch the public key from the fcontact.
2998                 // This is due to the fact that legacy DFRN had unique keys for every contact.
2999                 $pubkey = $contact['pubkey'];
3000                 if (!empty($contact['addr'])) {
3001                         $fcontact = FContact::getByURL($contact['addr']);
3002                         if (!empty($fcontact)) {
3003                                 $pubkey = $fcontact['pubkey'];
3004                         }
3005                 } else {
3006                         // The "addr" field should always be filled.
3007                         // If this isn't the case, it will raise a notice some lines later.
3008                         // And in the log we will see where it came from and we can handle it there.
3009                         Logger::notice('Empty addr', ['contact' => $contact ?? [], 'callstack' => System::callstack(20)]);
3010                 }
3011
3012                 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $pubkey ?? '', $public_batch);
3013
3014                 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3015
3016                 Logger::info('Transmitted message', ['owner' => $owner['uid'], 'target' => $contact['addr'], 'type' => $type, 'guid' => $guid, 'result' => $return_code]);
3017
3018                 return $return_code;
3019         }
3020
3021         /**
3022          * sends a participation (Used to get all further updates)
3023          *
3024          * @param array $contact Target of the communication
3025          * @param array $item    Item array
3026          *
3027          * @return int The result of the transmission
3028          * @throws \Exception
3029          */
3030         private static function sendParticipation(array $contact, array $item): int
3031         {
3032                 // Don't send notifications for private postings
3033                 if ($item['private'] == Item::PRIVATE) {
3034                         return 0;
3035                 }
3036
3037                 $cachekey = 'diaspora:sendParticipation:' . $item['guid'];
3038
3039                 $result = DI::cache()->get($cachekey);
3040                 if (!is_null($result)) {
3041                         return -1;
3042                 }
3043
3044                 // Fetch some user id to have a valid handle to transmit the participation.
3045                 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3046                 // If the item belongs to a user, we take this user id.
3047                 if ($item['uid'] == 0) {
3048                         // @todo Possibly use an administrator account?
3049                         $condition = ['verified' => true, 'blocked' => false,
3050                                 'account_removed' => false, 'account_expired' => false, 'account-type' => User::ACCOUNT_TYPE_PERSON];
3051                         $first_user = DBA::selectFirst('user', ['uid'], $condition, ['order' => ['uid']]);
3052                         $owner = User::getOwnerDataById($first_user['uid']);
3053                 } else {
3054                         $owner = User::getOwnerDataById($item['uid']);
3055                 }
3056
3057                 $author = self::myHandle($owner);
3058
3059                 $message = [
3060                         'author' => $author,
3061                         'guid' => System::createUUID(),
3062                         'parent_type' => 'Post',
3063                         'parent_guid' => $item['guid']
3064                 ];
3065
3066                 Logger::info('Send participation for ' . $item['guid'] . ' by ' . $author);
3067
3068                 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3069                 DI::cache()->set($cachekey, $item['guid'], Duration::QUARTER_HOUR);
3070
3071                 return self::buildAndTransmit($owner, $contact, 'participation', $message);
3072         }
3073
3074         /**
3075          * sends an account migration
3076          *
3077          * @param array $owner   the array of the item owner
3078          * @param array $contact Target of the communication
3079          * @param int   $uid     User ID
3080          *
3081          * @return int The result of the transmission
3082          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3083          * @throws \ImagickException
3084          */
3085         public static function sendAccountMigration(array $owner, array $contact, int $uid): int
3086         {
3087                 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3088                 $profile = self::createProfileData($uid);
3089
3090                 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3091                 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
3092
3093                 $message = [
3094                         'author' => $old_handle,
3095                         'profile' => $profile,
3096                         'signature' => $signature
3097                 ];
3098
3099                 Logger::info('Send account migration', ['msg' => $message]);
3100
3101                 return self::buildAndTransmit($owner, $contact, 'account_migration', $message);
3102         }
3103
3104         /**
3105          * Sends a "share" message
3106          *
3107          * @param array $owner   the array of the item owner
3108          * @param array $contact Target of the communication
3109          *
3110          * @return int The result of the transmission
3111          * @throws \Exception
3112          */
3113         public static function sendShare(array $owner, array $contact): int
3114         {
3115                 /**
3116                  * @todo support the different possible combinations of "following" and "sharing"
3117                  * Currently, Diaspora only interprets the "sharing" field
3118                  *
3119                  * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3120                  */
3121
3122                 /*
3123                 switch ($contact["rel"]) {
3124                         case Contact::FRIEND:
3125                                 $following = true;
3126                                 $sharing = true;
3127
3128                         case Contact::SHARING:
3129                                 $following = false;
3130                                 $sharing = true;
3131
3132                         case Contact::FOLLOWER:
3133                                 $following = true;
3134                                 $sharing = false;
3135                 }
3136                 */
3137
3138                 $message = [
3139                         'author' => self::myHandle($owner),
3140                         'recipient' => $contact['addr'],
3141                         'following' => 'true',
3142                         'sharing' => 'true'
3143                 ];
3144
3145                 Logger::info('Send share', ['msg' => $message]);
3146
3147                 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3148         }
3149
3150         /**
3151          * sends an "unshare"
3152          *
3153          * @param array $owner   the array of the item owner
3154          * @param array $contact Target of the communication
3155          *
3156          * @return int The result of the transmission
3157          * @throws \Exception
3158          */
3159         public static function sendUnshare(array $owner, array $contact): int
3160         {
3161                 $message = [
3162                         'author'    => self::myHandle($owner),
3163                         'recipient' => $contact['addr'],
3164                         'following' => 'false',
3165                         'sharing'   => 'false'
3166                 ];
3167
3168                 Logger::info('Send unshare', ['msg' => $message]);
3169
3170                 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3171         }
3172
3173         /**
3174          * Checks a message body if it is a reshare
3175          *
3176          * @param array $item The message body that is to be check
3177          *
3178          * @return array Reshare details or "false" if no reshare
3179          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3180          * @throws \ImagickException
3181          */
3182         public static function isReshare(array $item): array
3183         {
3184                 $reshared = Item::getShareArray($item);
3185                 if (empty($reshared)) {
3186                         return [];
3187                 }
3188
3189                 // Skip if it isn't a pure repeated messages or not a real reshare
3190                 if (!empty($reshared['comment']) || empty($reshared['guid'])) {
3191                         return [];
3192                 }
3193
3194                 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3195                 $item = Post::selectFirst(['author-addr'], $condition);
3196                 if (DBA::isResult($item)) {
3197                         return [
3198                                 'root_handle' => strtolower($item['author-addr']),
3199                                 'root_guid'   => $reshared['guid']
3200                         ];
3201                 }
3202
3203                 // We are resharing something that isn't a DFRN or Diaspora post.
3204                 return [];
3205         }
3206
3207         /**
3208          * Create an event array
3209          *
3210          * @param integer $event_id The id of the event
3211          *
3212          * @return array with event data
3213          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3214          */
3215         private static function buildEvent(string $event_id): array
3216         {
3217                 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
3218                 if (!DBA::isResult($event)) {
3219                         return [];
3220                 }
3221
3222                 $eventdata = [];
3223
3224                 $owner = User::getOwnerDataById($event['uid']);
3225                 if (!$owner) {
3226                         return [];
3227                 }
3228
3229                 $eventdata['author'] = self::myHandle($owner);
3230
3231                 if ($event['guid']) {
3232                         $eventdata['guid'] = $event['guid'];
3233                 }
3234
3235                 $mask = DateTimeFormat::ATOM;
3236
3237                 /// @todo - establish "all day" events in Friendica
3238                 $eventdata['all_day'] = 'false';
3239
3240                 $eventdata['timezone'] = 'UTC';
3241
3242                 if ($event['start']) {
3243                         $eventdata['start'] = DateTimeFormat::utc($event['start'], $mask);
3244                 }
3245                 if ($event['finish'] && !$event['nofinish']) {
3246                         $eventdata['end'] = DateTimeFormat::utc($event['finish'], $mask);
3247                 }
3248                 if ($event['summary']) {
3249                         $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3250                 }
3251                 if ($event['desc']) {
3252                         $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3253                 }
3254                 if ($event['location']) {
3255                         $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3256                         $coord = Map::getCoordinates($event['location']);
3257
3258                         $location = [];
3259                         $location['address'] = html_entity_decode(BBCode::toMarkdown($event['location']));
3260                         if (!empty($coord['lat']) && !empty($coord['lon'])) {
3261                                 $location['lat'] = $coord['lat'];
3262                                 $location['lng'] = $coord['lon'];
3263                         } else {
3264                                 $location['lat'] = 0;
3265                                 $location['lng'] = 0;
3266                         }
3267                         $eventdata['location'] = $location;
3268                 }
3269
3270                 return $eventdata;
3271         }
3272
3273         /**
3274          * Create a post (status message or reshare)
3275          *
3276          * @param array $item  The item that will be exported
3277          * @param array $owner the array of the item owner
3278          *
3279          * @return array
3280          * 'type' -> Message type ("status_message" or "reshare")
3281          * 'message' -> Array of XML elements of the status
3282          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3283          * @throws \ImagickException
3284          */
3285         public static function buildStatus(array $item, array $owner)
3286         {
3287                 $cachekey = 'diaspora:buildStatus:' . $item['guid'];
3288
3289                 $result = DI::cache()->get($cachekey);
3290                 if (!is_null($result)) {
3291                         return $result;
3292                 }
3293
3294                 $myaddr = self::myHandle($owner);
3295
3296                 $public = ($item['private'] == Item::PRIVATE ? 'false' : 'true');
3297                 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3298                 $edited = DateTimeFormat::utc($item['edited'] ?? $item['created'], DateTimeFormat::ATOM);
3299
3300                 // Detect a share element and do a reshare
3301                 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item))) {
3302                         $message = [
3303                                 'author'                => $myaddr,
3304                                 'guid'                  => $item['guid'],
3305                                 'created_at'            => $created,
3306                                 'root_author'           => $ret['root_handle'],
3307                                 'root_guid'             => $ret['root_guid'],
3308                                 'provider_display_name' => $item['app'],
3309                                 'public'                => $public
3310                         ];
3311
3312                         $type = 'reshare';
3313                 } else {
3314                         $title = $item['title'];
3315                         $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
3316
3317                         // Fetch the title from an attached link - if there is one
3318                         if (empty($item['title']) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3319                                 $page_data = BBCode::getAttachmentData($item['body']);
3320                                 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3321                                         $title = $page_data['title'];
3322                                 }
3323                         }
3324
3325                         // @todo Check if this is obsolete and if we are still using different owners. (Possibly a fragment from the forum functionality)
3326                         if ($item['author-link'] != $item['owner-link']) {
3327                                 $body = DI::contentItem()->createSharedBlockByArray($item);
3328                         }
3329
3330                         // convert to markdown
3331                         $body = html_entity_decode(BBCode::toMarkdown($body));
3332
3333                         // Adding the title
3334                         if (strlen($title)) {
3335                                 $body = '### ' . html_entity_decode($title) . "\n\n" . $body;
3336                         }
3337
3338                         $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]);
3339                         if (!empty($attachments)) {
3340                                 $body .= "\n[hr]\n";
3341                                 foreach ($attachments as $attachment) {
3342                                         $body .= "[" . $attachment['description'] . "](" . $attachment['url'] . ")\n";
3343                                 }
3344                         }
3345
3346                         $location = [];
3347
3348                         if ($item['location'] != '')
3349                                 $location['address'] = $item['location'];
3350
3351                         if ($item['coord'] != '') {
3352                                 $coord = explode(' ', $item['coord']);
3353                                 $location['lat'] = $coord[0];
3354                                 $location['lng'] = $coord[1];
3355                         }
3356
3357                         $message = [
3358                                 'author' => $myaddr,
3359                                 'guid' => $item['guid'],
3360                                 'created_at' => $created,
3361                                 'edited_at' => $edited,
3362                                 'public' => $public,
3363                                 'text' => $body,
3364                                 'provider_display_name' => $item['app'],
3365                                 'location' => $location
3366                         ];
3367
3368                         // Diaspora rejects messages when they contain a location without "lat" or "lng"
3369                         if (!isset($location['lat']) || !isset($location['lng'])) {
3370                                 unset($message['location']);
3371                         }
3372
3373                         if ($item['event-id'] > 0) {
3374                                 $event = self::buildEvent($item['event-id']);
3375                                 if (count($event)) {
3376                                         $message['event'] = $event;
3377
3378                                         if (!empty($event['location']['address']) &&
3379                                                 !empty($event['location']['lat']) &&
3380                                                 !empty($event['location']['lng'])) {
3381                                                 $message['location'] = $event['location'];
3382                                         }
3383
3384                                         /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3385                                         // $message['text'] = '';
3386                                 }
3387                         }
3388
3389                         $type = 'status_message';
3390                 }
3391
3392                 $msg = [
3393                         'type'    => $type,
3394                         'message' => $message
3395                 ];
3396
3397                 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3398
3399                 return $msg;
3400         }
3401
3402         private static function prependParentAuthorMention(string $body, string $profile_url): string
3403         {
3404                 $profile = Contact::getByURL($profile_url, false, ['addr', 'name']);
3405                 if (!empty($profile['addr'])
3406                         && !strstr($body, $profile['addr'])
3407                         && !strstr($body, $profile_url)
3408                 ) {
3409                         $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3410                 }
3411
3412                 return $body;
3413         }
3414
3415         /**
3416          * Sends a post
3417          *
3418          * @param array $item         The item that will be exported
3419          * @param array $owner        the array of the item owner
3420          * @param array $contact      Target of the communication
3421          * @param bool  $public_batch Is it a public post?
3422          *
3423          * @return int The result of the transmission
3424          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3425          * @throws \ImagickException
3426          */
3427         public static function sendStatus(array $item, array $owner, array $contact, bool $public_batch = false): int
3428         {
3429                 $status = self::buildStatus($item, $owner);
3430
3431                 return self::buildAndTransmit($owner, $contact, $status['type'], $status['message'], $public_batch, $item['guid']);
3432         }
3433
3434         /**
3435          * Creates a "like" object
3436          *
3437          * @param array $item  The item that will be exported
3438          * @param array $owner the array of the item owner
3439          *
3440          * @return array|bool The data for a "like" or false on error
3441          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3442          */
3443         private static function constructLike(array $item, array $owner)
3444         {
3445                 $parent = Post::selectFirst(['guid', 'uri', 'thr-parent'], ['uri' => $item['thr-parent']]);
3446                 if (!DBA::isResult($parent)) {
3447                         return false;
3448                 }
3449
3450                 $target_type = ($parent['uri'] === $parent['thr-parent'] ? 'Post' : 'Comment');
3451                 $positive = null;
3452                 if ($item['verb'] === Activity::LIKE) {
3453                         $positive = 'true';
3454                 } elseif ($item['verb'] === Activity::DISLIKE) {
3455                         $positive = 'false';
3456                 }
3457
3458                 return [
3459                         'author'           => self::myHandle($owner),
3460                         'guid'             => $item['guid'],
3461                         'parent_guid'      => $parent['guid'],
3462                         'parent_type'      => $target_type,
3463                         'positive'         => $positive,
3464                         'author_signature' => '',
3465                 ];
3466         }
3467
3468         /**
3469          * Creates an "EventParticipation" object
3470          *
3471          * @param array $item  The item that will be exported
3472          * @param array $owner the array of the item owner
3473          *
3474          * @return array|bool The data for an "EventParticipation" or false on error
3475          * @throws \Exception
3476          */
3477         private static function constructAttend(array $item, array $owner)
3478         {
3479                 $parent = Post::selectFirst(['guid'], ['uri' => $item['thr-parent']]);
3480                 if (!DBA::isResult($parent)) {
3481                         return false;
3482                 }
3483
3484                 switch ($item['verb']) {
3485                         case Activity::ATTEND:
3486                                 $attend_answer = 'accepted';
3487                                 break;
3488                         case Activity::ATTENDNO:
3489                                 $attend_answer = 'declined';
3490                                 break;
3491                         case Activity::ATTENDMAYBE:
3492                                 $attend_answer = 'tentative';
3493                                 break;
3494                         default:
3495                                 Logger::warning('Unknown verb ' . $item['verb'] . ' in item ' . $item['guid']);
3496                                 return false;
3497                 }
3498
3499                 return [
3500                         'author' => self::myHandle($owner),
3501                         'guid' => $item['guid'],
3502                         'parent_guid' => $parent['guid'],
3503                         'status' => $attend_answer,
3504                         'author_signature' => ''
3505                 ];
3506         }
3507
3508         /**
3509          * Creates the object for a comment
3510          *
3511          * @param array $item  The item that will be exported
3512          * @param array $owner the array of the item owner
3513          *
3514          * @return array|false The data for a comment
3515          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3516          */
3517         private static function constructComment(array $item, array $owner)
3518         {
3519                 $cachekey = 'diaspora:constructComment:' . $item['guid'];
3520
3521                 $result = DI::cache()->get($cachekey);
3522                 if (!is_null($result)) {
3523                         return $result;
3524                 }
3525
3526                 $toplevel_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3527                 if (!DBA::isResult($toplevel_item)) {
3528                         Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3529                         return false;
3530                 }
3531
3532                 $thread_parent_item = $toplevel_item;
3533                 if ($item['thr-parent'] != $item['parent-uri']) {
3534                         $thread_parent_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3535                 }
3536
3537                 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
3538
3539                 // The replied to autor mention is prepended for clarity if:
3540                 // - Item replied isn't yours
3541                 // - Item is public or explicit mentions are disabled
3542                 // - Implicit mentions are enabled
3543                 if (
3544                         $item['author-id'] != $thread_parent_item['author-id']
3545                         && ($thread_parent_item['gravity'] != Item::GRAVITY_PARENT)
3546                         && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3547                         && !DI::config()->get('system', 'disable_implicit_mentions')
3548                 ) {
3549                         $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3550                 }
3551
3552                 $text = html_entity_decode(BBCode::toMarkdown($body));
3553                 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3554                 $edited = DateTimeFormat::utc($item['edited'], DateTimeFormat::ATOM);
3555
3556                 $comment = [
3557                         'author'      => self::myHandle($owner),
3558                         'guid'        => $item['guid'],
3559                         'created_at'  => $created,
3560                         'edited_at'   => $edited,
3561                         'parent_guid' => $toplevel_item['guid'],
3562                         'text'        => $text,
3563                         'author_signature' => '',
3564                 ];
3565
3566                 // Send the thread parent guid only if it is a threaded comment
3567                 if ($item['thr-parent'] != $item['parent-uri']) {
3568                         $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3569                 }
3570
3571                 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3572
3573                 return $comment;
3574         }
3575
3576         /**
3577          * Send a like or a comment
3578          *
3579          * @param array $item         The item that will be exported
3580          * @param array $owner        the array of the item owner
3581          * @param array $contact      Target of the communication
3582          * @param bool  $public_batch Is it a public post?
3583          *
3584          * @return int The result of the transmission
3585          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3586          * @throws \ImagickException
3587          */
3588         public static function sendFollowup(array $item, array $owner, array $contact, bool $public_batch = false): int
3589         {
3590                 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3591                         $message = self::constructAttend($item, $owner);
3592                         $type = 'event_participation';
3593                 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3594                         $message = self::constructLike($item, $owner);
3595                         $type = 'like';
3596                 } elseif (!in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
3597                         $message = self::constructComment($item, $owner);
3598                         $type = 'comment';
3599                 }
3600
3601                 if (empty($message)) {
3602                         return -1;
3603                 }
3604
3605                 $message['author_signature'] = self::signature($owner, $message);
3606
3607                 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3608         }
3609
3610         /**
3611          * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3612          *
3613          * @param array $item         The item that will be exported
3614          * @param array $owner        the array of the item owner
3615          * @param array $contact      Target of the communication
3616          * @param bool  $public_batch Is it a public post?
3617          *
3618          * @return int The result of the transmission
3619          * @throws \Exception
3620          */
3621         public static function sendRelay(array $item, array $owner, array $contact, bool $public_batch = false): int
3622         {
3623                 if ($item['deleted']) {
3624                         return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3625                 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3626                         $type = 'like';
3627                 } else {
3628                         $type = 'comment';
3629                 }
3630
3631                 Logger::info('Got relayable data ' . $type . ' for item ' . $item['guid'] . ' (' . $item['id'] . ')');
3632
3633                 $msg = json_decode($item['signed_text'], true);
3634
3635                 $message = [];
3636                 if (is_array($msg)) {
3637                         foreach ($msg as $field => $data) {
3638                                 if (!$item['deleted']) {
3639                                         if ($field == 'diaspora_handle') {
3640                                                 $field = 'author';
3641                                         }
3642                                         if ($field == 'target_type') {
3643                                                 $field = 'parent_type';
3644                                         }
3645                                 }
3646
3647                                 $message[$field] = $data;
3648                         }
3649                 } else {
3650                         Logger::info('Signature text for item ' . $item['guid'] . ' (' . $item['id'] . ') could not be extracted: ' . $item['signed_text']);
3651                 }
3652
3653                 $message['parent_author_signature'] = self::signature($owner, $message);
3654
3655                 Logger::info('Relayed data', ['msg' => $message]);
3656
3657                 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3658         }
3659
3660         /**
3661          * Sends a retraction (deletion) of a message, like or comment
3662          *
3663          * @param array $item         The item that will be exported
3664          * @param array $owner        the array of the item owner
3665          * @param array $contact      Target of the communication
3666          * @param bool  $public_batch Is it a public post?
3667          * @param bool  $relay        Is the retraction transmitted from a relay?
3668          *
3669          * @return int The result of the transmission
3670          * @throws \Exception
3671          */
3672         public static function sendRetraction(array $item, array $owner, array $contact, bool $public_batch = false, bool $relay = false): int
3673         {
3674                 $itemaddr = strtolower($item['author-addr']);
3675
3676                 $msg_type = 'retraction';
3677
3678                 if ($item['gravity'] == Item::GRAVITY_PARENT) {
3679                         $target_type = 'Post';
3680                 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3681                         $target_type = 'Like';
3682                 } else {
3683                         $target_type = 'Comment';
3684                 }
3685
3686                 $message = [
3687                         'author' => $itemaddr,
3688                         'target_guid' => $item['guid'],
3689                         'target_type' => $target_type
3690                 ];
3691
3692                 Logger::info('Got message', ['msg' => $message]);
3693
3694                 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item['guid']);
3695         }
3696
3697         /**
3698          * Sends a mail
3699          *
3700          * @param array $item    The item that will be exported
3701          * @param array $owner   The owner
3702          * @param array $contact Target of the communication
3703          *
3704          * @return int The result of the transmission
3705          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3706          * @throws \ImagickException
3707          */
3708         public static function sendMail(array $item, array $owner, array $contact): int
3709         {
3710                 $myaddr = self::myHandle($owner);
3711
3712                 $cnv = DBA::selectFirst('conv', [], ['id' => $item['convid'], 'uid' => $item['uid']]);
3713                 if (!DBA::isResult($cnv)) {
3714                         Logger::notice('Conversation not found.');
3715                         return -1;
3716                 }
3717
3718                 $body = BBCode::toMarkdown($item['body']);
3719                 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3720
3721                 $msg = [
3722                         'author' => $myaddr,
3723                         'guid' => $item['guid'],
3724                         'conversation_guid' => $cnv['guid'],
3725                         'text' => $body,
3726                         'created_at' => $created,
3727                 ];
3728
3729                 if ($item['reply']) {
3730                         $message = $msg;
3731                         $type = 'message';
3732                 } else {
3733                         $message = [
3734                                 'author' => $cnv['creator'],
3735                                 'guid' => $cnv['guid'],
3736                                 'subject' => $cnv['subject'],
3737                                 'created_at' => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3738                                 'participants' => $cnv['recips'],
3739                                 'message' => $msg
3740                         ];
3741
3742                         $type = 'conversation';
3743                 }
3744
3745                 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item['guid']);
3746         }
3747
3748         /**
3749          * Split a name into first name and last name
3750          *
3751          * @param string $name The name
3752          *
3753          * @return array The array with "first" and "last"
3754          */
3755         public static function splitName(string $name): array
3756         {
3757                 $name = trim($name);
3758
3759                 // Is the name longer than 64 characters? Then cut the rest of it.
3760                 if (strlen($name) > 64) {
3761                         if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3762                                 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3763                         } else {
3764                                 $name = substr($name, 0, 64);
3765                         }
3766                 }
3767
3768                 // Take the first word as first name
3769                 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3770                 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3771                 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3772                         return ['first' => $first, 'last' => $last];
3773                 }
3774
3775                 // Take the last word as last name
3776                 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3777                 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3778
3779                 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3780                         return ['first' => $first, 'last' => $last];
3781                 }
3782
3783                 // Take the first 32 characters if there is no space in the first 32 characters
3784                 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3785                         $first = substr($name, 0, 32);
3786                         $last = substr($name, 32);
3787                         return ['first' => $first, 'last' => $last];
3788                 }
3789
3790                 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3791                 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3792
3793                 // Check if the last name is longer than 32 characters
3794                 if (strlen($last) > 32) {
3795                         if (strpos($last, ' ') <= 32) {
3796                                 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
3797                         } else {
3798                                 $last = substr($last, 0, 32);
3799                         }
3800                 }
3801
3802                 return ['first' => $first, 'last' => $last];
3803         }
3804
3805         /**
3806          * Create profile data
3807          *
3808          * @param int $uid The user id
3809          *
3810          * @return array The profile data
3811          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3812          */
3813         private static function createProfileData(int $uid): array
3814         {
3815                 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
3816
3817                 if (!DBA::isResult($profile)) {
3818                         return [];
3819                 }
3820
3821                 $split_name = self::splitName($profile['name']);
3822
3823                 $data = [
3824                         'author'           => $profile['addr'],
3825                         'first_name'       => $split_name['first'],
3826                         'last_name'        => $split_name['last'],
3827                         'image_url'        => DI::baseUrl() . '/photo/custom/300/' . $profile['uid'] . '.jpg',
3828                         'image_url_medium' => DI::baseUrl() . '/photo/custom/100/' . $profile['uid'] . '.jpg',
3829                         'image_url_small'  => DI::baseUrl() . '/photo/custom/50/'  . $profile['uid'] . '.jpg',
3830                         'searchable'       => ($profile['net-publish'] ? 'true' : 'false'),
3831                         'birthday'         => null,
3832                         'about'            => null,
3833                         'location'         => null,
3834                         'tag_string'       => null,
3835                         'nsfw'             => 'false',
3836                 ];
3837
3838                 if ($data['searchable'] === 'true') {
3839                         $data['birthday'] = '';
3840
3841                         if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
3842                                 [$year, $month, $day] = sscanf($profile['dob'], '%4d-%2d-%2d');
3843                                 if ($year < 1004) {
3844                                         $year = 1004;
3845                                 }
3846                                 $data['birthday'] = DateTimeFormat::utc($year . '-' . $month . '-' . $day, 'Y-m-d');
3847                         }
3848
3849                         $data['about'] = BBCode::toMarkdown($profile['about'] ?? '');
3850
3851                         $data['location'] = $profile['location'];
3852                         $data['tag_string'] = '';
3853
3854                         if ($profile['pub_keywords']) {
3855                                 $kw = str_replace(',', ' ', $profile['pub_keywords']);
3856                                 $kw = str_replace('  ', ' ', $kw);
3857                                 $arr = explode(' ', $kw);
3858                                 if (count($arr)) {
3859                                         for ($x = 0; $x < 5; $x ++) {
3860                                                 if (!empty($arr[$x])) {
3861                                                         $data['tag_string'] .= '#'. trim($arr[$x]) .' ';
3862                                                 }
3863                                         }
3864                                 }
3865                         }
3866                         $data['tag_string'] = trim($data['tag_string']);
3867                 }
3868
3869                 return $data;
3870         }
3871
3872         /**
3873          * Sends profile data
3874          *
3875          * @param int   $uid        The user id
3876          * @param array $recipients optional, default empty array
3877          *
3878          * @return void
3879          * @throws \Exception
3880          */
3881         public static function sendProfile(int $uid, array $recipients = [])
3882         {
3883                 if (!$uid) {
3884                         Logger::warning('Parameter "uid" is empty');
3885                         return;
3886                 }
3887
3888                 $owner = User::getOwnerDataById($uid);
3889                 if (empty($owner)) {
3890                         Logger::warning('Cannot fetch User record', ['uid' => $uid]);
3891                         return;
3892                 }
3893
3894                 if (empty($recipients)) {
3895                         Logger::debug('No recipients provided, fetching for user', ['uid' => $uid]);
3896                         $recipients = DBA::selectToArray('contact', [], ['network' => Protocol::DIASPORA, 'uid' => $uid, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
3897                 }
3898
3899                 if (empty($recipients)) {
3900                         Logger::warning('Cannot fetch recipients', ['uid' => $uid]);
3901                         return;
3902                 }
3903
3904                 $message = self::createProfileData($uid);
3905
3906                 // @todo Split this into single worker jobs
3907                 foreach ($recipients as $recipient) {
3908                         Logger::info('Send updated profile data for user ' . $uid . ' to contact ' . $recipient['id']);
3909                         self::buildAndTransmit($owner, $recipient, 'profile', $message);
3910                 }
3911         }
3912
3913         /**
3914          * Creates the signature for likes that are created on our system
3915          *
3916          * @param integer $uid  The user of that comment
3917          * @param array   $item Item array
3918          *
3919          * @return array|bool Signed content or false on error
3920          * @throws \Exception
3921          */
3922         public static function createLikeSignature(int $uid, array $item)
3923         {
3924                 $owner = User::getOwnerDataById($uid);
3925                 if (empty($owner)) {
3926                         Logger::info('No owner post, so not storing signature', ['uid' => $uid]);
3927                         return false;
3928                 }
3929
3930                 if (!in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3931                         Logger::warning('Item is neither a like nor a dislike', ['uid' => $uid, 'item[verb]' => $item['verb']]);;
3932                         return false;
3933                 }
3934
3935                 $message = self::constructLike($item, $owner);
3936                 if ($message === false) {
3937                         return false;
3938                 }
3939
3940                 $message['author_signature'] = self::signature($owner, $message);
3941
3942                 return $message;
3943         }
3944
3945         /**
3946          * Creates the signature for Comments that are created on our system
3947          *
3948          * @param array   $item Item array
3949          *
3950          * @return array|bool Signed content or false on error
3951          * @throws \Exception
3952          */
3953         public static function createCommentSignature(array $item)
3954         {
3955                 $contact = [];
3956                 if (!empty($item['author-link'])) {
3957                         $url = $item['author-link'];
3958                 } else {
3959                         $contact = Contact::getById($item['author-id'], ['url']);
3960                         if (empty($contact['url'])) {
3961                                 Logger::warning('Author Contact not found', ['author-id' => $item['author-id']]);
3962                                 return false;
3963                         }
3964                         $url = $contact['url'];
3965                 }
3966
3967                 $uid = User::getIdForURL($url);
3968                 if (empty($uid)) {
3969                         Logger::info('No owner post, so not storing signature', ['url' => $contact['url'] ?? 'No contact loaded']);
3970                         return false;
3971                 }
3972
3973                 $owner = User::getOwnerDataById($uid);
3974                 if (empty($owner)) {
3975                         Logger::info('No owner post, so not storing signature');
3976                         return false;
3977                 }
3978
3979                 // This is only needed for the automated tests
3980                 if (empty($owner['uprvkey'])) {
3981                         return false;
3982                 }
3983
3984                 if (!self::parentSupportDiaspora($item['thr-parent-id'])) {
3985                         Logger::info('One of the parents does not support Diaspora. A signature will not be created.', ['uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
3986                         return false;
3987                 }
3988
3989                 $message = self::constructComment($item, $owner);
3990                 if ($message === false) {
3991                         return false;
3992                 }
3993
3994                 $message['author_signature'] = self::signature($owner, $message);
3995
3996                 return $message;
3997         }
3998
3999         /**
4000          * Check if the parent and their parents support Diaspora
4001          *
4002          * @param integer $parent_id
4003          * @return boolean
4004          */
4005         private static function parentSupportDiaspora(int $parent_id): bool
4006         {
4007                 $parent_post = Post::selectFirstPost(['gravity', 'signed_text', 'author-link', 'thr-parent-id'], ['uri-id' => $parent_id]);
4008                 if (empty($parent_post['thr-parent-id'])) {
4009                         Logger::warning('Parent post does not exist.', ['parent-id' => $parent_id]);
4010                         return false;
4011                 }
4012
4013                 if (empty(FContact::getByURL($parent_post['author-link'], false))) {
4014                         Logger::info('Parent author is no Diaspora contact.', ['parent-id' => $parent_id]);
4015                         return false;
4016                 }
4017
4018                 if (($parent_post['gravity'] == Item::GRAVITY_COMMENT) && empty($parent_post['signed_text'])) {
4019                         Logger::info('Parent comment has got no Diaspora signature.', ['parent-id' => $parent_id]);
4020                         return false;
4021                 }
4022
4023                 if ($parent_post['gravity'] == Item::GRAVITY_COMMENT) {
4024                         return self::parentSupportDiaspora($parent_post['thr-parent-id']);
4025                 }
4026
4027                 return true;
4028         }
4029
4030         public static function performReshare(int $UriId, int $uid): int
4031         {
4032                 $post = DI::contentItem()->createSharedPostByUriId($UriId, $uid);
4033                 if (empty($post)) {
4034                         return 0;
4035                 }
4036
4037                 $owner  = User::getOwnerDataById($uid);
4038                 $author = Contact::getPublicIdByUserId($uid);
4039
4040                 $item = [
4041                         'uid'        => $uid,
4042                         'verb'       => Activity::POST,
4043                         'contact-id' => $owner['id'],
4044                         'author-id'  => $author,
4045                         'owner-id'   => $author,
4046                         'body'       => $post,
4047                         'allow_cid'  => $owner['allow_cid'] ?? '',
4048                         'allow_gid'  => $owner['allow_gid']?? '',
4049                         'deny_cid'   => $owner['deny_cid'] ?? '',
4050                         'deny_gid'   => $owner['deny_gid'] ?? '',
4051                 ];
4052
4053                 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
4054                         $item['private'] = Item::PRIVATE;
4055                 } elseif (DI::pConfig()->get($uid, 'system', 'unlisted')) {
4056                         $item['private'] = Item::UNLISTED;
4057                 } else {
4058                         $item['private'] = Item::PUBLIC;
4059                 }
4060
4061                 // Don't trigger the addons
4062                 $item['api_source'] = false;
4063
4064                 return Item::insert($item, true);
4065         }
4066 }