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