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