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