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