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