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