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