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