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