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