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