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