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