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