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