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