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