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