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