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