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