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