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