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