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