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