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