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