]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Diaspora.php
Remove mod/ping from 2fa exception list
[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                 // Check for Diaspora (and Friendica) typical paths
1429                 if (!preg_match("=(https?://.+)/(?:posts|display)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1430                         return false;
1431                 }
1432
1433                 $guid = urldecode($matches[2]);
1434
1435                 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1436                 if (DBA::isResult($item)) {
1437                         return $item['id'];
1438                 }
1439
1440                 self::storeByGuid($guid, $matches[1], $uid);
1441
1442                 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1443                 if (DBA::isResult($item)) {
1444                         return $item['id'];
1445                 } else {
1446                         return false;
1447                 }
1448         }
1449
1450         /**
1451          * @brief Fetches the item record of a given guid
1452          *
1453          * @param int    $uid     The user id
1454          * @param string $guid    message guid
1455          * @param string $author  The handle of the item
1456          * @param array  $contact The contact of the item owner
1457          *
1458          * @return array the item record
1459          * @throws \Exception
1460          */
1461         private static function parentItem($uid, $guid, $author, array $contact)
1462         {
1463                 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1464                         'author-name', 'author-link', 'author-avatar',
1465                         'owner-name', 'owner-link', 'owner-avatar'];
1466                 $condition = ['uid' => $uid, 'guid' => $guid];
1467                 $item = Item::selectFirst($fields, $condition);
1468
1469                 if (!DBA::isResult($item)) {
1470                         $person = self::personByHandle($author);
1471                         $result = self::storeByGuid($guid, $person["url"], $uid);
1472
1473                         // We don't have an url for items that arrived at the public dispatcher
1474                         if (!$result && !empty($contact["url"])) {
1475                                 $result = self::storeByGuid($guid, $contact["url"], $uid);
1476                         }
1477
1478                         if ($result) {
1479                                 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1480
1481                                 $item = Item::selectFirst($fields, $condition);
1482                         }
1483                 }
1484
1485                 if (!DBA::isResult($item)) {
1486                         Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1487                         return false;
1488                 } else {
1489                         Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1490                         return $item;
1491                 }
1492         }
1493
1494         /**
1495          * @brief returns contact details
1496          *
1497          * @param array $def_contact The default contact if the person isn't found
1498          * @param array $person      The record of the person
1499          * @param int   $uid         The user id
1500          *
1501          * @return array
1502          *      'cid' => contact id
1503          *      'network' => network type
1504          * @throws \Exception
1505          */
1506         private static function authorContactByUrl($def_contact, $person, $uid)
1507         {
1508                 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1509                 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1510                 if (DBA::isResult($contact)) {
1511                         $cid = $contact["id"];
1512                         $network = $contact["network"];
1513                 } else {
1514                         $cid = $def_contact["id"];
1515                         $network = Protocol::DIASPORA;
1516                 }
1517
1518                 return ["cid" => $cid, "network" => $network];
1519         }
1520
1521         /**
1522          * @brief Is the profile a hubzilla profile?
1523          *
1524          * @param string $url The profile link
1525          *
1526          * @return bool is it a hubzilla server?
1527          */
1528         public static function isRedmatrix($url)
1529         {
1530                 return(strstr($url, "/channel/"));
1531         }
1532
1533         /**
1534          * @brief Generate a post link with a given handle and message guid
1535          *
1536          * @param string $addr        The user handle
1537          * @param string $guid        message guid
1538          * @param string $parent_guid optional parent guid
1539          *
1540          * @return string the post link
1541          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1542          * @throws \ImagickException
1543          */
1544         private static function plink($addr, $guid, $parent_guid = '')
1545         {
1546                 $contact = Contact::getDetailsByAddr($addr);
1547
1548                 // Fallback
1549                 if (!$contact) {
1550                         if ($parent_guid != '') {
1551                                 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1552                         } else {
1553                                 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1554                         }
1555                 }
1556
1557                 if ($contact["network"] == Protocol::DFRN) {
1558                         return str_replace("/profile/" . $contact["nick"] . "/", "/display/" . $guid, $contact["url"] . "/");
1559                 }
1560
1561                 if (self::isRedmatrix($contact["url"])) {
1562                         return $contact["url"] . "/?f=&mid=" . $guid;
1563                 }
1564
1565                 if ($parent_guid != '') {
1566                         return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1567                 } else {
1568                         return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1569                 }
1570         }
1571
1572         /**
1573          * @brief Receives account migration
1574          *
1575          * @param array  $importer Array of the importer user
1576          * @param object $data     The message object
1577          *
1578          * @return bool Success
1579          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1580          * @throws \ImagickException
1581          */
1582         private static function receiveAccountMigration(array $importer, $data)
1583         {
1584                 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1585                 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1586                 $signature = Strings::escapeTags(XML::unescape($data->signature));
1587
1588                 $contact = self::contactByHandle($importer["uid"], $old_handle);
1589                 if (!$contact) {
1590                         Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1591                         return false;
1592                 }
1593
1594                 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1595
1596                 // Check signature
1597                 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1598                 $key = self::key($old_handle);
1599                 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1600                         Logger::log('No valid signature for migration.');
1601                         return false;
1602                 }
1603
1604                 // Update the profile
1605                 self::receiveProfile($importer, $data->profile);
1606
1607                 // change the technical stuff in contact and gcontact
1608                 $data = Probe::uri($new_handle);
1609                 if ($data['network'] == Protocol::PHANTOM) {
1610                         Logger::log('Account for '.$new_handle." couldn't be probed.");
1611                         return false;
1612                 }
1613
1614                 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1615                                 'name' => $data['name'], 'nick' => $data['nick'],
1616                                 'addr' => $data['addr'], 'batch' => $data['batch'],
1617                                 'notify' => $data['notify'], 'poll' => $data['poll'],
1618                                 'network' => $data['network']];
1619
1620                 DBA::update('contact', $fields, ['addr' => $old_handle]);
1621
1622                 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1623                                 'name' => $data['name'], 'nick' => $data['nick'],
1624                                 'addr' => $data['addr'], 'connect' => $data['addr'],
1625                                 'notify' => $data['notify'], 'photo' => $data['photo'],
1626                                 'server_url' => $data['baseurl'], 'network' => $data['network']];
1627
1628                 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1629
1630                 Logger::log('Contacts are updated.');
1631
1632                 return true;
1633         }
1634
1635         /**
1636          * @brief Processes an account deletion
1637          *
1638          * @param object $data The message object
1639          *
1640          * @return bool Success
1641          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1642          */
1643         private static function receiveAccountDeletion($data)
1644         {
1645                 $author = Strings::escapeTags(XML::unescape($data->author));
1646
1647                 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1648                 while ($contact = DBA::fetch($contacts)) {
1649                         Contact::remove($contact["id"]);
1650                 }
1651
1652                 DBA::delete('gcontact', ['addr' => $author]);
1653
1654                 Logger::log('Removed contacts for ' . $author);
1655
1656                 return true;
1657         }
1658
1659         /**
1660          * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1661          *
1662          * @param string  $author    Author handle
1663          * @param string  $guid      Message guid
1664          * @param boolean $onlyfound Only return uri when found in the database
1665          *
1666          * @return string The constructed uri or the one from our database
1667          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1668          * @throws \ImagickException
1669          */
1670         private static function getUriFromGuid($author, $guid, $onlyfound = false)
1671         {
1672                 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1673                 if (DBA::isResult($item)) {
1674                         return $item["uri"];
1675                 } elseif (!$onlyfound) {
1676                         $person = self::personByHandle($author);
1677
1678                         $parts = parse_url($person['url']);
1679                         unset($parts['path']);
1680                         $host_url = Network::unparseURL($parts);
1681
1682                         return $host_url . '/objects/' . $guid;
1683                 }
1684
1685                 return "";
1686         }
1687
1688         /**
1689          * @brief Fetch the guid from our database with a given uri
1690          *
1691          * @param string $uri Message uri
1692          * @param string $uid Author handle
1693          *
1694          * @return string The post guid
1695          * @throws \Exception
1696          */
1697         private static function getGuidFromUri($uri, $uid)
1698         {
1699                 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1700                 if (DBA::isResult($item)) {
1701                         return $item["guid"];
1702                 } else {
1703                         return false;
1704                 }
1705         }
1706
1707         /**
1708          * @brief Find the best importer for a comment, like, ...
1709          *
1710          * @param string $guid The guid of the item
1711          *
1712          * @return array|boolean the origin owner of that post - or false
1713          * @throws \Exception
1714          */
1715         private static function importerForGuid($guid)
1716         {
1717                 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1718                 if (DBA::isResult($item)) {
1719                         Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1720                         $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1721                         if (DBA::isResult($contact)) {
1722                                 return $contact;
1723                         }
1724                 }
1725                 return false;
1726         }
1727
1728         /**
1729          * @brief Processes an incoming comment
1730          *
1731          * @param array  $importer Array of the importer user
1732          * @param string $sender   The sender of the message
1733          * @param object $data     The message object
1734          * @param string $xml      The original XML of the message
1735          *
1736          * @return int The message id of the generated comment or "false" if there was an error
1737          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1738          * @throws \ImagickException
1739          */
1740         private static function receiveComment(array $importer, $sender, $data, $xml)
1741         {
1742                 $author = Strings::escapeTags(XML::unescape($data->author));
1743                 $guid = Strings::escapeTags(XML::unescape($data->guid));
1744                 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1745                 $text = XML::unescape($data->text);
1746
1747                 if (isset($data->created_at)) {
1748                         $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1749                 } else {
1750                         $created_at = DateTimeFormat::utcNow();
1751                 }
1752
1753                 if (isset($data->thread_parent_guid)) {
1754                         $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1755                         $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1756                 } else {
1757                         $thr_uri = "";
1758                 }
1759
1760                 $contact = self::allowedContactByHandle($importer, $sender, true);
1761                 if (!$contact) {
1762                         return false;
1763                 }
1764
1765                 $message_id = self::messageExists($importer["uid"], $guid);
1766                 if ($message_id) {
1767                         return true;
1768                 }
1769
1770                 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1771                 if (!$parent_item) {
1772                         return false;
1773                 }
1774
1775                 $person = self::personByHandle($author);
1776                 if (!is_array($person)) {
1777                         Logger::log("unable to find author details");
1778                         return false;
1779                 }
1780
1781                 // Fetch the contact id - if we know this contact
1782                 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1783
1784                 $datarray = [];
1785
1786                 $datarray["uid"] = $importer["uid"];
1787                 $datarray["contact-id"] = $author_contact["cid"];
1788                 $datarray["network"]  = $author_contact["network"];
1789
1790                 $datarray["author-link"] = $person["url"];
1791                 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1792
1793                 $datarray["owner-link"] = $contact["url"];
1794                 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1795
1796                 $datarray["guid"] = $guid;
1797                 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1798
1799                 $datarray["verb"] = ACTIVITY_POST;
1800                 $datarray["gravity"] = GRAVITY_COMMENT;
1801
1802                 if ($thr_uri != "") {
1803                         $datarray["parent-uri"] = $thr_uri;
1804                 } else {
1805                         $datarray["parent-uri"] = $parent_item["uri"];
1806                 }
1807
1808                 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1809
1810                 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1811                 $datarray["source"] = $xml;
1812
1813                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1814
1815                 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1816
1817                 $body = Markdown::toBBCode($text);
1818
1819                 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1820
1821                 self::fetchGuid($datarray);
1822
1823                 // If we are the origin of the parent we store the original data.
1824                 // We notify our followers during the item storage.
1825                 if ($parent_item["origin"]) {
1826                         $datarray['diaspora_signed_text'] = json_encode($data);
1827                 }
1828
1829                 $message_id = Item::insert($datarray);
1830
1831                 if ($message_id <= 0) {
1832                         return false;
1833                 }
1834
1835                 if ($message_id) {
1836                         Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1837                         if ($datarray['uid'] == 0) {
1838                                 Item::distribute($message_id, json_encode($data));
1839                         }
1840                 }
1841
1842                 return true;
1843         }
1844
1845         /**
1846          * @brief processes and stores private messages
1847          *
1848          * @param array  $importer     Array of the importer user
1849          * @param array  $contact      The contact of the message
1850          * @param object $data         The message object
1851          * @param array  $msg          Array of the processed message, author handle and key
1852          * @param object $mesg         The private message
1853          * @param array  $conversation The conversation record to which this message belongs
1854          *
1855          * @return bool "true" if it was successful
1856          * @throws \Exception
1857          */
1858         private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1859         {
1860                 $author = Strings::escapeTags(XML::unescape($data->author));
1861                 $guid = Strings::escapeTags(XML::unescape($data->guid));
1862                 $subject = Strings::escapeTags(XML::unescape($data->subject));
1863
1864                 // "diaspora_handle" is the element name from the old version
1865                 // "author" is the element name from the new version
1866                 if ($mesg->author) {
1867                         $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1868                 } elseif ($mesg->diaspora_handle) {
1869                         $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1870                 } else {
1871                         return false;
1872                 }
1873
1874                 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1875                 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1876                 $msg_text = XML::unescape($mesg->text);
1877                 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1878
1879                 if ($msg_conversation_guid != $guid) {
1880                         Logger::log("message conversation guid does not belong to the current conversation.");
1881                         return false;
1882                 }
1883
1884                 $body = Markdown::toBBCode($msg_text);
1885                 $message_uri = $msg_author.":".$msg_guid;
1886
1887                 $person = self::personByHandle($msg_author);
1888
1889                 return Mail::insert([
1890                         'uid'        => $importer['uid'],
1891                         'guid'       => $msg_guid,
1892                         'convid'     => $conversation['id'],
1893                         'from-name'  => $person['name'],
1894                         'from-photo' => $person['photo'],
1895                         'from-url'   => $person['url'],
1896                         'contact-id' => $contact['id'],
1897                         'title'      => $subject,
1898                         'body'       => $body,
1899                         'uri'        => $message_uri,
1900                         'parent-uri' => $author . ':' . $guid,
1901                         'created'    => $msg_created_at
1902                 ]);
1903         }
1904
1905         /**
1906          * @brief Processes new private messages (answers to private messages are processed elsewhere)
1907          *
1908          * @param array  $importer Array of the importer user
1909          * @param array  $msg      Array of the processed message, author handle and key
1910          * @param object $data     The message object
1911          *
1912          * @return bool Success
1913          * @throws \Exception
1914          */
1915         private static function receiveConversation(array $importer, $msg, $data)
1916         {
1917                 $author = Strings::escapeTags(XML::unescape($data->author));
1918                 $guid = Strings::escapeTags(XML::unescape($data->guid));
1919                 $subject = Strings::escapeTags(XML::unescape($data->subject));
1920                 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1921                 $participants = Strings::escapeTags(XML::unescape($data->participants));
1922
1923                 $messages = $data->message;
1924
1925                 if (!count($messages)) {
1926                         Logger::log("empty conversation");
1927                         return false;
1928                 }
1929
1930                 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1931                 if (!$contact) {
1932                         return false;
1933                 }
1934
1935                 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1936                 if (!DBA::isResult($conversation)) {
1937                         $r = q(
1938                                 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1939                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1940                                 intval($importer["uid"]),
1941                                 DBA::escape($guid),
1942                                 DBA::escape($author),
1943                                 DBA::escape($created_at),
1944                                 DBA::escape(DateTimeFormat::utcNow()),
1945                                 DBA::escape($subject),
1946                                 DBA::escape($participants)
1947                         );
1948                         if ($r) {
1949                                 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1950                         }
1951                 }
1952                 if (!$conversation) {
1953                         Logger::log("unable to create conversation.");
1954                         return false;
1955                 }
1956
1957                 foreach ($messages as $mesg) {
1958                         self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1959                 }
1960
1961                 return true;
1962         }
1963
1964         /**
1965          * @brief Processes "like" messages
1966          *
1967          * @param array  $importer Array of the importer user
1968          * @param string $sender   The sender of the message
1969          * @param object $data     The message object
1970          *
1971          * @return int The message id of the generated like or "false" if there was an error
1972          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1973          * @throws \ImagickException
1974          */
1975         private static function receiveLike(array $importer, $sender, $data)
1976         {
1977                 $author = Strings::escapeTags(XML::unescape($data->author));
1978                 $guid = Strings::escapeTags(XML::unescape($data->guid));
1979                 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1980                 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
1981                 $positive = Strings::escapeTags(XML::unescape($data->positive));
1982
1983                 // likes on comments aren't supported by Diaspora - only on posts
1984                 // But maybe this will be supported in the future, so we will accept it.
1985                 if (!in_array($parent_type, ["Post", "Comment"])) {
1986                         return false;
1987                 }
1988
1989                 $contact = self::allowedContactByHandle($importer, $sender, true);
1990                 if (!$contact) {
1991                         return false;
1992                 }
1993
1994                 $message_id = self::messageExists($importer["uid"], $guid);
1995                 if ($message_id) {
1996                         return true;
1997                 }
1998
1999                 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2000                 if (!$parent_item) {
2001                         return false;
2002                 }
2003
2004                 $person = self::personByHandle($author);
2005                 if (!is_array($person)) {
2006                         Logger::log("unable to find author details");
2007                         return false;
2008                 }
2009
2010                 // Fetch the contact id - if we know this contact
2011                 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2012
2013                 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2014                 // We would accept this anyhow.
2015                 if ($positive == "true") {
2016                         $verb = ACTIVITY_LIKE;
2017                 } else {
2018                         $verb = ACTIVITY_DISLIKE;
2019                 }
2020
2021                 $datarray = [];
2022
2023                 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2024
2025                 $datarray["uid"] = $importer["uid"];
2026                 $datarray["contact-id"] = $author_contact["cid"];
2027                 $datarray["network"]  = $author_contact["network"];
2028
2029                 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2030                 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2031
2032                 $datarray["guid"] = $guid;
2033                 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2034
2035                 $datarray["verb"] = $verb;
2036                 $datarray["gravity"] = GRAVITY_ACTIVITY;
2037                 $datarray["parent-uri"] = $parent_item["uri"];
2038
2039                 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2040
2041                 $datarray["body"] = $verb;
2042
2043                 // Diaspora doesn't provide a date for likes
2044                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2045
2046                 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2047                 if ($parent_item["id"] != $parent_item["parent"]) {
2048                         $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
2049                         $origin = $toplevel["origin"];
2050                 } else {
2051                         $origin = $parent_item["origin"];
2052                 }
2053
2054                 // If we are the origin of the parent we store the original data.
2055                 // We notify our followers during the item storage.
2056                 if ($origin) {
2057                         $datarray['diaspora_signed_text'] = json_encode($data);
2058                 }
2059
2060                 $message_id = Item::insert($datarray);
2061
2062                 if ($message_id <= 0) {
2063                         return false;
2064                 }
2065
2066                 if ($message_id) {
2067                         Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2068                         if ($datarray['uid'] == 0) {
2069                                 Item::distribute($message_id, json_encode($data));
2070                         }
2071                 }
2072
2073                 return true;
2074         }
2075
2076         /**
2077          * @brief Processes private messages
2078          *
2079          * @param array  $importer Array of the importer user
2080          * @param object $data     The message object
2081          *
2082          * @return bool Success?
2083          * @throws \Exception
2084          */
2085         private static function receiveMessage(array $importer, $data)
2086         {
2087                 $author = Strings::escapeTags(XML::unescape($data->author));
2088                 $guid = Strings::escapeTags(XML::unescape($data->guid));
2089                 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2090                 $text = XML::unescape($data->text);
2091                 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2092
2093                 $contact = self::allowedContactByHandle($importer, $author, true);
2094                 if (!$contact) {
2095                         return false;
2096                 }
2097
2098                 $conversation = null;
2099
2100                 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2101                 $conversation = DBA::selectFirst('conv', [], $condition);
2102
2103                 if (!DBA::isResult($conversation)) {
2104                         Logger::log("conversation not available.");
2105                         return false;
2106                 }
2107
2108                 $message_uri = $author.":".$guid;
2109
2110                 $person = self::personByHandle($author);
2111                 if (!$person) {
2112                         Logger::log("unable to find author details");
2113                         return false;
2114                 }
2115
2116                 $body = Markdown::toBBCode($text);
2117
2118                 $body = self::replacePeopleGuid($body, $person["url"]);
2119
2120                 return Mail::insert([
2121                         'uid'        => $importer['uid'],
2122                         'guid'       => $guid,
2123                         'convid'     => $conversation['id'],
2124                         'from-name'  => $person['name'],
2125                         'from-photo' => $person['photo'],
2126                         'from-url'   => $person['url'],
2127                         'contact-id' => $contact['id'],
2128                         'title'      => $conversation['subject'],
2129                         'body'       => $body,
2130                         'reply'      => 1,
2131                         'uri'        => $message_uri,
2132                         'parent-uri' => $author.":".$conversation['guid'],
2133                         'created'    => $created_at
2134                 ]);
2135         }
2136
2137         /**
2138          * @brief Processes participations - unsupported by now
2139          *
2140          * @param array  $importer Array of the importer user
2141          * @param object $data     The message object
2142          *
2143          * @return bool always true
2144          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2145          * @throws \ImagickException
2146          */
2147         private static function receiveParticipation(array $importer, $data)
2148         {
2149                 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2150                 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2151
2152                 $contact_id = Contact::getIdForURL($author);
2153                 if (!$contact_id) {
2154                         Logger::log('Contact not found: '.$author);
2155                         return false;
2156                 }
2157
2158                 $person = self::personByHandle($author);
2159                 if (!is_array($person)) {
2160                         Logger::log("Person not found: ".$author);
2161                         return false;
2162                 }
2163
2164                 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2165                 if (!DBA::isResult($item)) {
2166                         Logger::log('Item not found, no origin or private: '.$parent_guid);
2167                         return false;
2168                 }
2169
2170                 $author_parts = explode('@', $author);
2171                 if (isset($author_parts[1])) {
2172                         $server = $author_parts[1];
2173                 } else {
2174                         // Should never happen
2175                         $server = $author;
2176                 }
2177
2178                 Logger::log('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, Logger::DEBUG);
2179
2180                 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2181                         DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2182                 }
2183
2184                 // Send all existing comments and likes to the requesting server
2185                 $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2186                 while ($comment = Item::fetch($comments)) {
2187                         if ($comment['id'] == $comment['parent']) {
2188                                 continue;
2189                         }
2190
2191                         Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $contact_id]);
2192                         Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $contact_id);
2193                 }
2194                 DBA::close($comments);
2195
2196                 return true;
2197         }
2198
2199         /**
2200          * @brief Processes photos - unneeded
2201          *
2202          * @param array  $importer Array of the importer user
2203          * @param object $data     The message object
2204          *
2205          * @return bool always true
2206          */
2207         private static function receivePhoto(array $importer, $data)
2208         {
2209                 // There doesn't seem to be a reason for this function,
2210                 // since the photo data is transmitted in the status message as well
2211                 return true;
2212         }
2213
2214         /**
2215          * @brief Processes poll participations - unssupported
2216          *
2217          * @param array  $importer Array of the importer user
2218          * @param object $data     The message object
2219          *
2220          * @return bool always true
2221          */
2222         private static function receivePollParticipation(array $importer, $data)
2223         {
2224                 // We don't support polls by now
2225                 return true;
2226         }
2227
2228         /**
2229          * @brief Processes incoming profile updates
2230          *
2231          * @param array  $importer Array of the importer user
2232          * @param object $data     The message object
2233          *
2234          * @return bool Success
2235          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2236          * @throws \ImagickException
2237          */
2238         private static function receiveProfile(array $importer, $data)
2239         {
2240                 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2241
2242                 $contact = self::contactByHandle($importer["uid"], $author);
2243                 if (!$contact) {
2244                         return false;
2245                 }
2246
2247                 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2248                 $image_url = XML::unescape($data->image_url);
2249                 $birthday = XML::unescape($data->birthday);
2250                 $gender = XML::unescape($data->gender);
2251                 $about = Markdown::toBBCode(XML::unescape($data->bio));
2252                 $location = Markdown::toBBCode(XML::unescape($data->location));
2253                 $searchable = (XML::unescape($data->searchable) == "true");
2254                 $nsfw = (XML::unescape($data->nsfw) == "true");
2255                 $tags = XML::unescape($data->tag_string);
2256
2257                 $tags = explode("#", $tags);
2258
2259                 $keywords = [];
2260                 foreach ($tags as $tag) {
2261                         $tag = trim(strtolower($tag));
2262                         if ($tag != "") {
2263                                 $keywords[] = $tag;
2264                         }
2265                 }
2266
2267                 $keywords = implode(", ", $keywords);
2268
2269                 $handle_parts = explode("@", $author);
2270                 $nick = $handle_parts[0];
2271
2272                 if ($name === "") {
2273                         $name = $handle_parts[0];
2274                 }
2275
2276                 if (preg_match("|^https?://|", $image_url) === 0) {
2277                         $image_url = "http://".$handle_parts[1].$image_url;
2278                 }
2279
2280                 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2281
2282                 // Generic birthday. We don't know the timezone. The year is irrelevant.
2283
2284                 $birthday = str_replace("1000", "1901", $birthday);
2285
2286                 if ($birthday != "") {
2287                         $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2288                 }
2289
2290                 // this is to prevent multiple birthday notifications in a single year
2291                 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2292
2293                 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2294                         $birthday = $contact["bd"];
2295                 }
2296
2297                 $fields = ['name' => $name, 'location' => $location,
2298                         'name-date' => DateTimeFormat::utcNow(),
2299                         'about' => $about, 'gender' => $gender,
2300                         'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2301                         'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2302
2303                 if (!empty($birthday)) {
2304                         $fields['bd'] = $birthday;
2305                 }
2306
2307                 DBA::update('contact', $fields, ['id' => $contact['id']]);
2308
2309                 // @todo Update the public contact, then update the gcontact from that
2310
2311                 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2312                                         "photo" => $image_url, "name" => $name, "location" => $location,
2313                                         "about" => $about, "birthday" => $birthday, "gender" => $gender,
2314                                         "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2315                                         "hide" => !$searchable, "nsfw" => $nsfw];
2316
2317                 $gcid = GContact::update($gcontact);
2318
2319                 GContact::link($gcid, $importer["uid"], $contact["id"]);
2320
2321                 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2322
2323                 return true;
2324         }
2325
2326         /**
2327          * @brief Processes incoming friend requests
2328          *
2329          * @param array $importer Array of the importer user
2330          * @param array $contact  The contact that send the request
2331          * @return void
2332          * @throws \Exception
2333          */
2334         private static function receiveRequestMakeFriend(array $importer, array $contact)
2335         {
2336                 if ($contact["rel"] == Contact::SHARING) {
2337                         DBA::update(
2338                                 'contact',
2339                                 ['rel' => Contact::FRIEND, 'writable' => true],
2340                                 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2341                         );
2342                 }
2343         }
2344
2345         /**
2346          * @brief Processes incoming sharing notification
2347          *
2348          * @param array  $importer Array of the importer user
2349          * @param object $data     The message object
2350          *
2351          * @return bool Success
2352          * @throws \Exception
2353          */
2354         private static function receiveContactRequest(array $importer, $data)
2355         {
2356                 $author = XML::unescape($data->author);
2357                 $recipient = XML::unescape($data->recipient);
2358
2359                 if (!$author || !$recipient) {
2360                         return false;
2361                 }
2362
2363                 // the current protocol version doesn't know these fields
2364                 // That means that we will assume their existance
2365                 if (isset($data->following)) {
2366                         $following = (XML::unescape($data->following) == "true");
2367                 } else {
2368                         $following = true;
2369                 }
2370
2371                 if (isset($data->sharing)) {
2372                         $sharing = (XML::unescape($data->sharing) == "true");
2373                 } else {
2374                         $sharing = true;
2375                 }
2376
2377                 $contact = self::contactByHandle($importer["uid"], $author);
2378
2379                 // perhaps we were already sharing with this person. Now they're sharing with us.
2380                 // That makes us friends.
2381                 if ($contact) {
2382                         if ($following) {
2383                                 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2384                                 self::receiveRequestMakeFriend($importer, $contact);
2385
2386                                 // refetch the contact array
2387                                 $contact = self::contactByHandle($importer["uid"], $author);
2388
2389                                 // If we are now friends, we are sending a share message.
2390                                 // Normally we needn't to do so, but the first message could have been vanished.
2391                                 if (in_array($contact["rel"], [Contact::FRIEND])) {
2392                                         $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2393                                         if (DBA::isResult($user)) {
2394                                                 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2395                                                 self::sendShare($user, $contact);
2396                                         }
2397                                 }
2398                                 return true;
2399                         } else {
2400                                 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2401                                 Contact::removeFollower($importer, $contact);
2402                                 return true;
2403                         }
2404                 }
2405
2406                 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2407                         Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2408                         return false;
2409                 } elseif (!$following && !$sharing) {
2410                         Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2411                         return false;
2412                 } elseif (!$following && $sharing) {
2413                         Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2414                 } elseif ($following && $sharing) {
2415                         Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2416                 } elseif ($following && !$sharing) {
2417                         Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2418                 }
2419
2420                 $ret = self::personByHandle($author);
2421
2422                 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2423                         Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2424                         return false;
2425                 }
2426
2427                 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2428
2429                 q(
2430                         "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2431                         VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2432                         intval($importer["uid"]),
2433                         DBA::escape($ret["network"]),
2434                         DBA::escape($ret["addr"]),
2435                         DateTimeFormat::utcNow(),
2436                         DBA::escape($ret["url"]),
2437                         DBA::escape(Strings::normaliseLink($ret["url"])),
2438                         DBA::escape($batch),
2439                         DBA::escape($ret["name"]),
2440                         DBA::escape($ret["nick"]),
2441                         DBA::escape($ret["photo"]),
2442                         DBA::escape($ret["pubkey"]),
2443                         DBA::escape($ret["notify"]),
2444                         DBA::escape($ret["poll"]),
2445                         1,
2446                         2
2447                 );
2448
2449                 // find the contact record we just created
2450
2451                 $contact_record = self::contactByHandle($importer["uid"], $author);
2452
2453                 if (!$contact_record) {
2454                         Logger::log("unable to locate newly created contact record.");
2455                         return;
2456                 }
2457
2458                 Logger::log("Author ".$author." was added as contact number ".$contact_record["id"].".", Logger::DEBUG);
2459
2460                 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2461
2462                 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2463
2464                 if (in_array($importer["page-flags"], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])) {
2465                         Logger::log("Sending intra message for author ".$author.".", Logger::DEBUG);
2466
2467                         $hash = Strings::getRandomHex().(string)time();   // Generate a confirm_key
2468
2469                         q(
2470                                 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2471                                 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2472                                 intval($importer["uid"]),
2473                                 intval($contact_record["id"]),
2474                                 0,
2475                                 0,
2476                                 DBA::escape(L10n::t("Sharing notification from Diaspora network")),
2477                                 DBA::escape($hash),
2478                                 DBA::escape(DateTimeFormat::utcNow())
2479                         );
2480                 } else {
2481                         // automatic friend approval
2482
2483                         Logger::log("Does an automatic friend approval for author ".$author.".", Logger::DEBUG);
2484
2485                         Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2486
2487                         /*
2488                          * technically they are sharing with us (Contact::SHARING),
2489                          * but if our page-type is Profile::PAGE_COMMUNITY or Profile::PAGE_SOAPBOX
2490                          * we are going to change the relationship and make them a follower.
2491                          */
2492                         if (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing && $following) {
2493                                 $new_relation = Contact::FRIEND;
2494                         } elseif (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing) {
2495                                 $new_relation = Contact::SHARING;
2496                         } else {
2497                                 $new_relation = Contact::FOLLOWER;
2498                         }
2499
2500                         q(
2501                                 "UPDATE `contact` SET `rel` = %d,
2502                                 `name-date` = '%s',
2503                                 `uri-date` = '%s',
2504                                 `blocked` = 0,
2505                                 `pending` = 0,
2506                                 `writable` = 1
2507                                 WHERE `id` = %d
2508                                 ",
2509                                 intval($new_relation),
2510                                 DBA::escape(DateTimeFormat::utcNow()),
2511                                 DBA::escape(DateTimeFormat::utcNow()),
2512                                 intval($contact_record["id"])
2513                         );
2514
2515                         $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2516                         if (DBA::isResult($user)) {
2517                                 Logger::log("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2518                                 self::sendShare($user, $contact_record);
2519
2520                                 // Send the profile data, maybe it weren't transmitted before
2521                                 self::sendProfile($importer["uid"], [$contact_record]);
2522                         }
2523                 }
2524
2525                 return true;
2526         }
2527
2528         /**
2529          * @brief Fetches a message with a given guid
2530          *
2531          * @param string $guid        message guid
2532          * @param string $orig_author handle of the original post
2533          * @return array The fetched item
2534          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2535          * @throws \ImagickException
2536          */
2537         public static function originalItem($guid, $orig_author)
2538         {
2539                 if (empty($guid)) {
2540                         Logger::log('Empty guid. Quitting.');
2541                         return false;
2542                 }
2543
2544                 // Do we already have this item?
2545                 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2546                         'author-name', 'author-link', 'author-avatar'];
2547                 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2548                 $item = Item::selectFirst($fields, $condition);
2549
2550                 if (DBA::isResult($item)) {
2551                         Logger::log("reshared message ".$guid." already exists on system.");
2552
2553                         // Maybe it is already a reshared item?
2554                         // Then refetch the content, if it is a reshare from a reshare.
2555                         // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2556                         if (self::isReshare($item["body"], true)) {
2557                                 $item = [];
2558                         } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2559                                 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2560
2561                                 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2562
2563                                 // Add OEmbed and other information to the body
2564                                 $item["body"] = add_page_info_to_body($item["body"], false, true);
2565
2566                                 return $item;
2567                         } else {
2568                                 return $item;
2569                         }
2570                 }
2571
2572                 if (!DBA::isResult($item)) {
2573                         if (empty($orig_author)) {
2574                                 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2575                                 return false;
2576                         }
2577
2578                         $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2579                         Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2580                         $stored = self::storeByGuid($guid, $server);
2581
2582                         if (!$stored) {
2583                                 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2584                                 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2585                                 $stored = self::storeByGuid($guid, $server);
2586                         }
2587
2588                         if ($stored) {
2589                                 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2590                                         'author-name', 'author-link', 'author-avatar'];
2591                                 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2592                                 $item = Item::selectFirst($fields, $condition);
2593
2594                                 if (DBA::isResult($item)) {
2595                                         // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2596                                         if (self::isReshare($item["body"], false)) {
2597                                                 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2598                                                 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2599                                         }
2600
2601                                         return $item;
2602                                 }
2603                         }
2604                 }
2605                 return false;
2606         }
2607
2608         /**
2609          * @brief Stores a reshare activity
2610          *
2611          * @param array   $item              Array of reshare post
2612          * @param integer $parent_message_id Id of the parent post
2613          * @param string  $guid              GUID string of reshare action
2614          * @param string  $author            Author handle
2615          */
2616         private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2617         {
2618                 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2619
2620                 $datarray = [];
2621
2622                 $datarray['uid'] = $item['uid'];
2623                 $datarray['contact-id'] = $item['contact-id'];
2624                 $datarray['network'] = $item['network'];
2625
2626                 $datarray['author-link'] = $item['author-link'];
2627                 $datarray['author-id'] = $item['author-id'];
2628
2629                 $datarray['owner-link'] = $datarray['author-link'];
2630                 $datarray['owner-id'] = $datarray['author-id'];
2631
2632                 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2633                 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2634                 $datarray['parent-uri'] = $parent['uri'];
2635
2636                 $datarray['verb'] = $datarray['body'] = ACTIVITY2_ANNOUNCE;
2637                 $datarray['gravity'] = GRAVITY_ACTIVITY;
2638                 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
2639
2640                 $datarray['protocol'] = $item['protocol'];
2641
2642                 $datarray['plink'] = self::plink($author, $datarray['guid']);
2643                 $datarray['private'] = $item['private'];
2644                 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2645
2646                 $message_id = Item::insert($datarray);
2647
2648                 if ($message_id) {
2649                         Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2650                         if ($datarray['uid'] == 0) {
2651                                 Item::distribute($message_id);
2652                         }
2653                 }
2654         }
2655
2656         /**
2657          * @brief Processes a reshare message
2658          *
2659          * @param array  $importer Array of the importer user
2660          * @param object $data     The message object
2661          * @param string $xml      The original XML of the message
2662          *
2663          * @return int the message id
2664          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2665          * @throws \ImagickException
2666          */
2667         private static function receiveReshare(array $importer, $data, $xml)
2668         {
2669                 $author = Strings::escapeTags(XML::unescape($data->author));
2670                 $guid = Strings::escapeTags(XML::unescape($data->guid));
2671                 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2672                 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2673                 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2674                 /// @todo handle unprocessed property "provider_display_name"
2675                 $public = Strings::escapeTags(XML::unescape($data->public));
2676
2677                 $contact = self::allowedContactByHandle($importer, $author, false);
2678                 if (!$contact) {
2679                         return false;
2680                 }
2681
2682                 $message_id = self::messageExists($importer["uid"], $guid);
2683                 if ($message_id) {
2684                         return true;
2685                 }
2686
2687                 $original_item = self::originalItem($root_guid, $root_author);
2688                 if (!$original_item) {
2689                         return false;
2690                 }
2691
2692                 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2693
2694                 $datarray = [];
2695
2696                 $datarray["uid"] = $importer["uid"];
2697                 $datarray["contact-id"] = $contact["id"];
2698                 $datarray["network"]  = Protocol::DIASPORA;
2699
2700                 $datarray["author-link"] = $contact["url"];
2701                 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2702
2703                 $datarray["owner-link"] = $datarray["author-link"];
2704                 $datarray["owner-id"] = $datarray["author-id"];
2705
2706                 $datarray["guid"] = $guid;
2707                 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2708
2709                 $datarray["verb"] = ACTIVITY_POST;
2710                 $datarray["gravity"] = GRAVITY_PARENT;
2711
2712                 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2713                 $datarray["source"] = $xml;
2714
2715                 $prefix = share_header(
2716                         $original_item["author-name"],
2717                         $original_item["author-link"],
2718                         $original_item["author-avatar"],
2719                         $original_item["guid"],
2720                         $original_item["created"],
2721                         $orig_url
2722                 );
2723                 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2724
2725                 $datarray["tag"] = $original_item["tag"];
2726                 $datarray["app"]  = $original_item["app"];
2727
2728                 $datarray["plink"] = self::plink($author, $guid);
2729                 $datarray["private"] = (($public == "false") ? 1 : 0);
2730                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2731
2732                 $datarray["object-type"] = $original_item["object-type"];
2733
2734                 self::fetchGuid($datarray);
2735                 $message_id = Item::insert($datarray);
2736
2737                 self::sendParticipation($contact, $datarray);
2738
2739                 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2740                 if ($root_message_id) {
2741                         self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2742                 }
2743
2744                 if ($message_id) {
2745                         Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2746                         if ($datarray['uid'] == 0) {
2747                                 Item::distribute($message_id);
2748                         }
2749                         return true;
2750                 } else {
2751                         return false;
2752                 }
2753         }
2754
2755         /**
2756          * @brief Processes retractions
2757          *
2758          * @param array  $importer Array of the importer user
2759          * @param array  $contact  The contact of the item owner
2760          * @param object $data     The message object
2761          *
2762          * @return bool success
2763          * @throws \Exception
2764          */
2765         private static function itemRetraction(array $importer, array $contact, $data)
2766         {
2767                 $author = Strings::escapeTags(XML::unescape($data->author));
2768                 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2769                 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2770
2771                 $person = self::personByHandle($author);
2772                 if (!is_array($person)) {
2773                         Logger::log("unable to find author detail for ".$author);
2774                         return false;
2775                 }
2776
2777                 if (empty($contact["url"])) {
2778                         $contact["url"] = $person["url"];
2779                 }
2780
2781                 // Fetch items that are about to be deleted
2782                 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2783
2784                 // When we receive a public retraction, we delete every item that we find.
2785                 if ($importer['uid'] == 0) {
2786                         $condition = ['guid' => $target_guid, 'deleted' => false];
2787                 } else {
2788                         $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2789                 }
2790
2791                 $r = Item::select($fields, $condition);
2792                 if (!DBA::isResult($r)) {
2793                         Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2794                         return false;
2795                 }
2796
2797                 while ($item = Item::fetch($r)) {
2798                         if (strstr($item['file'], '[')) {
2799                                 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2800                                 continue;
2801                         }
2802
2803                         // Fetch the parent item
2804                         $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2805
2806                         // Only delete it if the parent author really fits
2807                         if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2808                                 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2809                                 continue;
2810                         }
2811
2812                         Item::delete(['id' => $item['id']]);
2813
2814                         Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], Logger::DEBUG);
2815                 }
2816
2817                 return true;
2818         }
2819
2820         /**
2821          * @brief Receives retraction messages
2822          *
2823          * @param array  $importer Array of the importer user
2824          * @param string $sender   The sender of the message
2825          * @param object $data     The message object
2826          *
2827          * @return bool Success
2828          * @throws \Exception
2829          */
2830         private static function receiveRetraction(array $importer, $sender, $data)
2831         {
2832                 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2833
2834                 $contact = self::contactByHandle($importer["uid"], $sender);
2835                 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2836                         Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2837                         return false;
2838                 }
2839
2840                 if (!$contact) {
2841                         $contact = [];
2842                 }
2843
2844                 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2845
2846                 switch ($target_type) {
2847                         case "Comment":
2848                         case "Like":
2849                         case "Post":
2850                         case "Reshare":
2851                         case "StatusMessage":
2852                                 return self::itemRetraction($importer, $contact, $data);
2853
2854                         case "PollParticipation":
2855                         case "Photo":
2856                                 // Currently unsupported
2857                                 break;
2858
2859                         default:
2860                                 Logger::log("Unknown target type ".$target_type);
2861                                 return false;
2862                 }
2863                 return true;
2864         }
2865
2866         /**
2867          * @brief Receives status messages
2868          *
2869          * @param array            $importer Array of the importer user
2870          * @param SimpleXMLElement $data     The message object
2871          * @param string           $xml      The original XML of the message
2872          *
2873          * @return int The message id of the newly created item
2874          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2875          * @throws \ImagickException
2876          */
2877         private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2878         {
2879                 $author = Strings::escapeTags(XML::unescape($data->author));
2880                 $guid = Strings::escapeTags(XML::unescape($data->guid));
2881                 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2882                 $public = Strings::escapeTags(XML::unescape($data->public));
2883                 $text = XML::unescape($data->text);
2884                 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2885
2886                 $contact = self::allowedContactByHandle($importer, $author, false);
2887                 if (!$contact) {
2888                         return false;
2889                 }
2890
2891                 $message_id = self::messageExists($importer["uid"], $guid);
2892                 if ($message_id) {
2893                         return true;
2894                 }
2895
2896                 $address = [];
2897                 if ($data->location) {
2898                         foreach ($data->location->children() as $fieldname => $data) {
2899                                 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2900                         }
2901                 }
2902
2903                 $body = Markdown::toBBCode($text);
2904
2905                 $datarray = [];
2906
2907                 // Attach embedded pictures to the body
2908                 if ($data->photo) {
2909                         foreach ($data->photo as $photo) {
2910                                 $body = "[img]".XML::unescape($photo->remote_photo_path).
2911                                         XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2912                         }
2913
2914                         $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2915                 } else {
2916                         $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2917
2918                         // Add OEmbed and other information to the body
2919                         if (!self::isRedmatrix($contact["url"])) {
2920                                 $body = add_page_info_to_body($body, false, true);
2921                         }
2922                 }
2923
2924                 /// @todo enable support for polls
2925                 //if ($data->poll) {
2926                 //      foreach ($data->poll AS $poll)
2927                 //              print_r($poll);
2928                 //      die("poll!\n");
2929                 //}
2930
2931                 /// @todo enable support for events
2932
2933                 $datarray["uid"] = $importer["uid"];
2934                 $datarray["contact-id"] = $contact["id"];
2935                 $datarray["network"] = Protocol::DIASPORA;
2936
2937                 $datarray["author-link"] = $contact["url"];
2938                 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2939
2940                 $datarray["owner-link"] = $datarray["author-link"];
2941                 $datarray["owner-id"] = $datarray["author-id"];
2942
2943                 $datarray["guid"] = $guid;
2944                 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2945
2946                 $datarray["verb"] = ACTIVITY_POST;
2947                 $datarray["gravity"] = GRAVITY_PARENT;
2948
2949                 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2950                 $datarray["source"] = $xml;
2951
2952                 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2953
2954                 if ($provider_display_name != "") {
2955                         $datarray["app"] = $provider_display_name;
2956                 }
2957
2958                 $datarray["plink"] = self::plink($author, $guid);
2959                 $datarray["private"] = (($public == "false") ? 1 : 0);
2960                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2961
2962                 if (isset($address["address"])) {
2963                         $datarray["location"] = $address["address"];
2964                 }
2965
2966                 if (isset($address["lat"]) && isset($address["lng"])) {
2967                         $datarray["coord"] = $address["lat"]." ".$address["lng"];
2968                 }
2969
2970                 self::fetchGuid($datarray);
2971                 $message_id = Item::insert($datarray);
2972
2973                 self::sendParticipation($contact, $datarray);
2974
2975                 if ($message_id) {
2976                         Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2977                         if ($datarray['uid'] == 0) {
2978                                 Item::distribute($message_id);
2979                         }
2980                         return true;
2981                 } else {
2982                         return false;
2983                 }
2984         }
2985
2986         /* ************************************************************************************** *
2987          * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2988          * ************************************************************************************** */
2989
2990         /**
2991          * @brief returnes the handle of a contact
2992          *
2993          * @param array $contact contact array
2994          *
2995          * @return string the handle in the format user@domain.tld
2996          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2997          */
2998         private static function myHandle(array $contact)
2999         {
3000                 if (!empty($contact["addr"])) {
3001                         return $contact["addr"];
3002                 }
3003
3004                 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3005                 // So - just in case - we build the the address here.
3006                 if ($contact["nickname"] != "") {
3007                         $nick = $contact["nickname"];
3008                 } else {
3009                         $nick = $contact["nick"];
3010                 }
3011
3012                 return $nick . "@" . substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
3013         }
3014
3015
3016         /**
3017          * @brief Creates the data for a private message in the new format
3018          *
3019          * @param string $msg     The message that is to be transmitted
3020          * @param array  $user    The record of the sender
3021          * @param array  $contact Target of the communication
3022          * @param string $prvkey  The private key of the sender
3023          * @param string $pubkey  The public key of the receiver
3024          *
3025          * @return string The encrypted data
3026          * @throws \Exception
3027          */
3028         public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
3029         {
3030                 Logger::log("Message: ".$msg, Logger::DATA);
3031
3032                 // without a public key nothing will work
3033                 if (!$pubkey) {
3034                         Logger::log("pubkey missing: contact id: ".$contact["id"]);
3035                         return false;
3036                 }
3037
3038                 $aes_key = openssl_random_pseudo_bytes(32);
3039                 $b_aes_key = base64_encode($aes_key);
3040                 $iv = openssl_random_pseudo_bytes(16);
3041                 $b_iv = base64_encode($iv);
3042
3043                 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3044
3045                 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3046
3047                 $encrypted_key_bundle = "";
3048                 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3049
3050                 $json_object = json_encode(
3051                         ["aes_key" => base64_encode($encrypted_key_bundle),
3052                                         "encrypted_magic_envelope" => base64_encode($ciphertext)]
3053                 );
3054
3055                 return $json_object;
3056         }
3057
3058         /**
3059          * @brief Creates the envelope for the "fetch" endpoint and for the new format
3060          *
3061          * @param string $msg  The message that is to be transmitted
3062          * @param array  $user The record of the sender
3063          *
3064          * @return string The envelope
3065          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3066          */
3067         public static function buildMagicEnvelope($msg, array $user)
3068         {
3069                 $b64url_data = Strings::base64UrlEncode($msg);
3070                 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3071
3072                 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3073                 $type = "application/xml";
3074                 $encoding = "base64url";
3075                 $alg = "RSA-SHA256";
3076                 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3077
3078                 // Fallback if the private key wasn't transmitted in the expected field
3079                 if ($user['uprvkey'] == "") {
3080                         $user['uprvkey'] = $user['prvkey'];
3081                 }
3082
3083                 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3084                 $sig = Strings::base64UrlEncode($signature);
3085
3086                 $xmldata = ["me:env" => ["me:data" => $data,
3087                                                         "@attributes" => ["type" => $type],
3088                                                         "me:encoding" => $encoding,
3089                                                         "me:alg" => $alg,
3090                                                         "me:sig" => $sig,
3091                                                         "@attributes2" => ["key_id" => $key_id]]];
3092
3093                 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3094
3095                 return XML::fromArray($xmldata, $xml, false, $namespaces);
3096         }
3097
3098         /**
3099          * @brief Create the envelope for a message
3100          *
3101          * @param string $msg     The message that is to be transmitted
3102          * @param array  $user    The record of the sender
3103          * @param array  $contact Target of the communication
3104          * @param string $prvkey  The private key of the sender
3105          * @param string $pubkey  The public key of the receiver
3106          * @param bool   $public  Is the message public?
3107          *
3108          * @return string The message that will be transmitted to other servers
3109          * @throws \Exception
3110          */
3111         public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3112         {
3113                 // The message is put into an envelope with the sender's signature
3114                 $envelope = self::buildMagicEnvelope($msg, $user);
3115
3116                 // Private messages are put into a second envelope, encrypted with the receivers public key
3117                 if (!$public) {
3118                         $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3119                 }
3120
3121                 return $envelope;
3122         }
3123
3124         /**
3125          * @brief Creates a signature for a message
3126          *
3127          * @param array $owner   the array of the owner of the message
3128          * @param array $message The message that is to be signed
3129          *
3130          * @return string The signature
3131          */
3132         private static function signature($owner, $message)
3133         {
3134                 $sigmsg = $message;
3135                 unset($sigmsg["author_signature"]);
3136                 unset($sigmsg["parent_author_signature"]);
3137
3138                 $signed_text = implode(";", $sigmsg);
3139
3140                 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3141         }
3142
3143         /**
3144          * @brief Transmit a message to a target server
3145          *
3146          * @param array  $owner        the array of the item owner
3147          * @param array  $contact      Target of the communication
3148          * @param string $envelope     The message that is to be transmitted
3149          * @param bool   $public_batch Is it a public post?
3150          * @param string $guid         message guid
3151          *
3152          * @return int Result of the transmission
3153          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3154          * @throws \ImagickException
3155          */
3156         private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3157         {
3158                 $enabled = intval(Config::get("system", "diaspora_enabled"));
3159                 if (!$enabled) {
3160                         return 200;
3161                 }
3162
3163                 $logid = Strings::getRandomHex(4);
3164
3165                 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3166
3167                 // We always try to use the data from the fcontact table.
3168                 // This is important for transmitting data to Friendica servers.
3169                 if (!empty($contact['addr'])) {
3170                         $fcontact = self::personByHandle($contact['addr']);
3171                         if (!empty($fcontact)) {
3172                                 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3173                         }
3174                 }
3175
3176                 if (!$dest_url) {
3177                         Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3178                         return 0;
3179                 }
3180
3181                 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3182
3183                 if (!intval(Config::get("system", "diaspora_test"))) {
3184                         $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3185
3186                         $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3187                         $return_code = $postResult->getReturnCode();
3188                 } else {
3189                         Logger::log("test_mode");
3190                         return 200;
3191                 }
3192
3193                 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3194
3195                 return $return_code ? $return_code : -1;
3196         }
3197
3198
3199         /**
3200          * @brief Build the post xml
3201          *
3202          * @param string $type    The message type
3203          * @param array  $message The message data
3204          *
3205          * @return string The post XML
3206          */
3207         public static function buildPostXml($type, $message)
3208         {
3209                 $data = [$type => $message];
3210
3211                 return XML::fromArray($data, $xml);
3212         }
3213
3214         /**
3215          * @brief Builds and transmit messages
3216          *
3217          * @param array  $owner        the array of the item owner
3218          * @param array  $contact      Target of the communication
3219          * @param string $type         The message type
3220          * @param array  $message      The message data
3221          * @param bool   $public_batch Is it a public post?
3222          * @param string $guid         message guid
3223          *
3224          * @return int Result of the transmission
3225          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3226          * @throws \ImagickException
3227          */
3228         private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3229         {
3230                 $msg = self::buildPostXml($type, $message);
3231
3232                 Logger::log('message: '.$msg, Logger::DATA);
3233                 Logger::log('send guid '.$guid, Logger::DEBUG);
3234
3235                 // Fallback if the private key wasn't transmitted in the expected field
3236                 if (empty($owner['uprvkey'])) {
3237                         $owner['uprvkey'] = $owner['prvkey'];
3238                 }
3239
3240                 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3241
3242                 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3243
3244                 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3245
3246                 return $return_code;
3247         }
3248
3249         /**
3250          * @brief sends a participation (Used to get all further updates)
3251          *
3252          * @param array $contact Target of the communication
3253          * @param array $item    Item array
3254          *
3255          * @return int The result of the transmission
3256          * @throws \Exception
3257          */
3258         private static function sendParticipation(array $contact, array $item)
3259         {
3260                 // Don't send notifications for private postings
3261                 if ($item['private']) {
3262                         return;
3263                 }
3264
3265                 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3266
3267                 $result = Cache::get($cachekey);
3268                 if (!is_null($result)) {
3269                         return;
3270                 }
3271
3272                 // Fetch some user id to have a valid handle to transmit the participation.
3273                 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3274                 // If the item belongs to a user, we take this user id.
3275                 if ($item['uid'] == 0) {
3276                         $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3277                         $first_user = DBA::selectFirst('user', ['uid'], $condition);
3278                         $owner = User::getOwnerDataById($first_user['uid']);
3279                 } else {
3280                         $owner = User::getOwnerDataById($item['uid']);
3281                 }
3282
3283                 $author = self::myHandle($owner);
3284
3285                 $message = ["author" => $author,
3286                                 "guid" => System::createUUID(),
3287                                 "parent_type" => "Post",
3288                                 "parent_guid" => $item["guid"]];
3289
3290                 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3291
3292                 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3293                 Cache::set($cachekey, $item["guid"], Cache::QUARTER_HOUR);
3294
3295                 return self::buildAndTransmit($owner, $contact, "participation", $message);
3296         }
3297
3298         /**
3299          * @brief sends an account migration
3300          *
3301          * @param array $owner   the array of the item owner
3302          * @param array $contact Target of the communication
3303          * @param int   $uid     User ID
3304          *
3305          * @return int The result of the transmission
3306          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3307          * @throws \ImagickException
3308          */
3309         public static function sendAccountMigration(array $owner, array $contact, $uid)
3310         {
3311                 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3312                 $profile = self::createProfileData($uid);
3313
3314                 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3315                 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3316
3317                 $message = ["author" => $old_handle,
3318                                 "profile" => $profile,
3319                                 "signature" => $signature];
3320
3321                 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3322
3323                 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3324         }
3325
3326         /**
3327          * @brief Sends a "share" message
3328          *
3329          * @param array $owner   the array of the item owner
3330          * @param array $contact Target of the communication
3331          *
3332          * @return int The result of the transmission
3333          * @throws \Exception
3334          */
3335         public static function sendShare(array $owner, array $contact)
3336         {
3337                 /**
3338                  * @todo support the different possible combinations of "following" and "sharing"
3339                  * Currently, Diaspora only interprets the "sharing" field
3340                  *
3341                  * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3342                  */
3343
3344                 /*
3345                 switch ($contact["rel"]) {
3346                         case Contact::FRIEND:
3347                                 $following = true;
3348                                 $sharing = true;
3349
3350                         case Contact::SHARING:
3351                                 $following = false;
3352                                 $sharing = true;
3353
3354                         case Contact::FOLLOWER:
3355                                 $following = true;
3356                                 $sharing = false;
3357                 }
3358                 */
3359
3360                 $message = ["author" => self::myHandle($owner),
3361                                 "recipient" => $contact["addr"],
3362                                 "following" => "true",
3363                                 "sharing" => "true"];
3364
3365                 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3366
3367                 return self::buildAndTransmit($owner, $contact, "contact", $message);
3368         }
3369
3370         /**
3371          * @brief sends an "unshare"
3372          *
3373          * @param array $owner   the array of the item owner
3374          * @param array $contact Target of the communication
3375          *
3376          * @return int The result of the transmission
3377          * @throws \Exception
3378          */
3379         public static function sendUnshare(array $owner, array $contact)
3380         {
3381                 $message = ["author" => self::myHandle($owner),
3382                                 "recipient" => $contact["addr"],
3383                                 "following" => "false",
3384                                 "sharing" => "false"];
3385
3386                 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3387
3388                 return self::buildAndTransmit($owner, $contact, "contact", $message);
3389         }
3390
3391         /**
3392          * @brief Checks a message body if it is a reshare
3393          *
3394          * @param string $body     The message body that is to be check
3395          * @param bool   $complete Should it be a complete check or a simple check?
3396          *
3397          * @return array|bool Reshare details or "false" if no reshare
3398          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3399          * @throws \ImagickException
3400          */
3401         public static function isReshare($body, $complete = true)
3402         {
3403                 $body = trim($body);
3404
3405                 // Skip if it isn't a pure repeated messages
3406                 // Does it start with a share?
3407                 if ((strpos($body, "[share") > 0) && $complete) {
3408                         return false;
3409                 }
3410
3411                 // Does it end with a share?
3412                 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3413                         return false;
3414                 }
3415
3416                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3417                 // Skip if there is no shared message in there
3418                 if ($body == $attributes) {
3419                         return false;
3420                 }
3421
3422                 // If we don't do the complete check we quit here
3423
3424                 $guid = "";
3425                 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3426                 if (!empty($matches[1])) {
3427                         $guid = $matches[1];
3428                 }
3429
3430                 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3431                 if (!empty($matches[1])) {
3432                         $guid = $matches[1];
3433                 }
3434
3435                 if (($guid != "") && $complete) {
3436                         $condition = ['guid' => $guid, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3437                         $item = Item::selectFirst(['contact-id'], $condition);
3438                         if (DBA::isResult($item)) {
3439                                 $ret= [];
3440                                 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3441                                 $ret["root_guid"] = $guid;
3442                                 return $ret;
3443                         } elseif ($complete) {
3444                                 // We are resharing something that isn't a DFRN or Diaspora post.
3445                                 // So we have to return "false" on "$complete" to not trigger a reshare.
3446                                 return false;
3447                         }
3448                 } elseif (($guid == "") && $complete) {
3449                         return false;
3450                 }
3451
3452                 $ret["root_guid"] = $guid;
3453
3454                 $profile = "";
3455                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3456                 if (!empty($matches[1])) {
3457                         $profile = $matches[1];
3458                 }
3459
3460                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3461                 if (!empty($matches[1])) {
3462                         $profile = $matches[1];
3463                 }
3464
3465                 $ret= [];
3466
3467                 if ($profile != "") {
3468                         if (Contact::getIdForURL($profile)) {
3469                                 $author = Contact::getDetailsByURL($profile);
3470                                 $ret["root_handle"] = $author['addr'];
3471                         }
3472                 }
3473
3474                 if (empty($ret) && !$complete) {
3475                         return true;
3476                 }
3477
3478                 return $ret;
3479         }
3480
3481         /**
3482          * @brief Create an event array
3483          *
3484          * @param integer $event_id The id of the event
3485          *
3486          * @return array with event data
3487          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3488          */
3489         private static function buildEvent($event_id)
3490         {
3491                 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3492                 if (!DBA::isResult($r)) {
3493                         return [];
3494                 }
3495
3496                 $event = $r[0];
3497
3498                 $eventdata = [];
3499
3500                 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3501                 if (!DBA::isResult($r)) {
3502                         return [];
3503                 }
3504
3505                 $user = $r[0];
3506
3507                 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3508                 if (!DBA::isResult($r)) {
3509                         return [];
3510                 }
3511
3512                 $owner = $r[0];
3513
3514                 $eventdata['author'] = self::myHandle($owner);
3515
3516                 if ($event['guid']) {
3517                         $eventdata['guid'] = $event['guid'];
3518                 }
3519
3520                 $mask = DateTimeFormat::ATOM;
3521
3522                 /// @todo - establish "all day" events in Friendica
3523                 $eventdata["all_day"] = "false";
3524
3525                 $eventdata['timezone'] = 'UTC';
3526                 if (!$event['adjust'] && $user['timezone']) {
3527                         $eventdata['timezone'] = $user['timezone'];
3528                 }
3529
3530                 if ($event['start']) {
3531                         $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3532                 }
3533                 if ($event['finish'] && !$event['nofinish']) {
3534                         $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3535                 }
3536                 if ($event['summary']) {
3537                         $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3538                 }
3539                 if ($event['desc']) {
3540                         $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3541                 }
3542                 if ($event['location']) {
3543                         $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3544                         $coord = Map::getCoordinates($event['location']);
3545
3546                         $location = [];
3547                         $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3548                         if (!empty($coord['lat']) && !empty($coord['lon'])) {
3549                                 $location["lat"] = $coord['lat'];
3550                                 $location["lng"] = $coord['lon'];
3551                         } else {
3552                                 $location["lat"] = 0;
3553                                 $location["lng"] = 0;
3554                         }
3555                         $eventdata['location'] = $location;
3556                 }
3557
3558                 return $eventdata;
3559         }
3560
3561         /**
3562          * @brief Create a post (status message or reshare)
3563          *
3564          * @param array $item  The item that will be exported
3565          * @param array $owner the array of the item owner
3566          *
3567          * @return array
3568          * 'type' -> Message type ("status_message" or "reshare")
3569          * 'message' -> Array of XML elements of the status
3570          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3571          * @throws \ImagickException
3572          */
3573         public static function buildStatus(array $item, array $owner)
3574         {
3575                 $cachekey = "diaspora:buildStatus:".$item['guid'];
3576
3577                 $result = Cache::get($cachekey);
3578                 if (!is_null($result)) {
3579                         return $result;
3580                 }
3581
3582                 $myaddr = self::myHandle($owner);
3583
3584                 $public = ($item["private"] ? "false" : "true");
3585
3586                 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3587                 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3588
3589                 // Detect a share element and do a reshare
3590                 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3591                         $message = ["author" => $myaddr,
3592                                         "guid" => $item["guid"],
3593                                         "created_at" => $created,
3594                                         "root_author" => $ret["root_handle"],
3595                                         "root_guid" => $ret["root_guid"],
3596                                         "provider_display_name" => $item["app"],
3597                                         "public" => $public];
3598
3599                         $type = "reshare";
3600                 } else {
3601                         $title = $item["title"];
3602                         $body = $item["body"];
3603
3604                         if ($item['author-link'] != $item['owner-link']) {
3605                                 require_once 'mod/share.php';
3606                                 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3607                                         "", $item['created'], $item['plink']) . $body . '[/share]';
3608                         }
3609
3610                         // convert to markdown
3611                         $body = html_entity_decode(BBCode::toMarkdown($body));
3612
3613                         // Adding the title
3614                         if (strlen($title)) {
3615                                 $body = "## ".html_entity_decode($title)."\n\n".$body;
3616                         }
3617
3618                         if ($item["attach"]) {
3619                                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3620                                 if ($cnt) {
3621                                         $body .= "\n".L10n::t("Attachments:")."\n";
3622                                         foreach ($matches as $mtch) {
3623                                                 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3624                                         }
3625                                 }
3626                         }
3627
3628                         $location = [];
3629
3630                         if ($item["location"] != "")
3631                                 $location["address"] = $item["location"];
3632
3633                         if ($item["coord"] != "") {
3634                                 $coord = explode(" ", $item["coord"]);
3635                                 $location["lat"] = $coord[0];
3636                                 $location["lng"] = $coord[1];
3637                         }
3638
3639                         $message = ["author" => $myaddr,
3640                                         "guid" => $item["guid"],
3641                                         "created_at" => $created,
3642                                         "edited_at" => $edited,
3643                                         "public" => $public,
3644                                         "text" => $body,
3645                                         "provider_display_name" => $item["app"],
3646                                         "location" => $location];
3647
3648                         // Diaspora rejects messages when they contain a location without "lat" or "lng"
3649                         if (!isset($location["lat"]) || !isset($location["lng"])) {
3650                                 unset($message["location"]);
3651                         }
3652
3653                         if ($item['event-id'] > 0) {
3654                                 $event = self::buildEvent($item['event-id']);
3655                                 if (count($event)) {
3656                                         $message['event'] = $event;
3657
3658                                         if (!empty($event['location']['address']) &&
3659                                                 !empty($event['location']['lat']) &&
3660                                                 !empty($event['location']['lng'])) {
3661                                                 $message['location'] = $event['location'];
3662                                         }
3663
3664                                         /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3665                                         // $message['text'] = '';
3666                                 }
3667                         }
3668
3669                         $type = "status_message";
3670                 }
3671
3672                 $msg = ["type" => $type, "message" => $message];
3673
3674                 Cache::set($cachekey, $msg, Cache::QUARTER_HOUR);
3675
3676                 return $msg;
3677         }
3678
3679         private static function prependParentAuthorMention($body, $profile_url)
3680         {
3681                 $profile = Contact::getDetailsByURL($profile_url);
3682                 if (!empty($profile['addr'])
3683                         && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3684                         && !strstr($body, $profile['addr'])
3685                         && !strstr($body, $profile_url)
3686                 ) {
3687                         $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3688                 }
3689
3690                 return $body;
3691         }
3692
3693         /**
3694          * @brief Sends a post
3695          *
3696          * @param array $item         The item that will be exported
3697          * @param array $owner        the array of the item owner
3698          * @param array $contact      Target of the communication
3699          * @param bool  $public_batch Is it a public post?
3700          *
3701          * @return int The result of the transmission
3702          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3703          * @throws \ImagickException
3704          */
3705         public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3706         {
3707                 $status = self::buildStatus($item, $owner);
3708
3709                 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3710         }
3711
3712         /**
3713          * @brief Creates a "like" object
3714          *
3715          * @param array $item  The item that will be exported
3716          * @param array $owner the array of the item owner
3717          *
3718          * @return array The data for a "like"
3719          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3720          */
3721         private static function constructLike(array $item, array $owner)
3722         {
3723                 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3724                 if (!DBA::isResult($parent)) {
3725                         return false;
3726                 }
3727
3728                 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3729                 $positive = null;
3730                 if ($item['verb'] === ACTIVITY_LIKE) {
3731                         $positive = "true";
3732                 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3733                         $positive = "false";
3734                 }
3735
3736                 return(["author" => self::myHandle($owner),
3737                                 "guid" => $item["guid"],
3738                                 "parent_guid" => $parent["guid"],
3739                                 "parent_type" => $target_type,
3740                                 "positive" => $positive,
3741                                 "author_signature" => ""]);
3742         }
3743
3744         /**
3745          * @brief Creates an "EventParticipation" object
3746          *
3747          * @param array $item  The item that will be exported
3748          * @param array $owner the array of the item owner
3749          *
3750          * @return array The data for an "EventParticipation"
3751          * @throws \Exception
3752          */
3753         private static function constructAttend(array $item, array $owner)
3754         {
3755                 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3756                 if (!DBA::isResult($parent)) {
3757                         return false;
3758                 }
3759
3760                 switch ($item['verb']) {
3761                         case ACTIVITY_ATTEND:
3762                                 $attend_answer = 'accepted';
3763                                 break;
3764                         case ACTIVITY_ATTENDNO:
3765                                 $attend_answer = 'declined';
3766                                 break;
3767                         case ACTIVITY_ATTENDMAYBE:
3768                                 $attend_answer = 'tentative';
3769                                 break;
3770                         default:
3771                                 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3772                                 return false;
3773                 }
3774
3775                 return(["author" => self::myHandle($owner),
3776                                 "guid" => $item["guid"],
3777                                 "parent_guid" => $parent["guid"],
3778                                 "status" => $attend_answer,
3779                                 "author_signature" => ""]);
3780         }
3781
3782         /**
3783          * @brief Creates the object for a comment
3784          *
3785          * @param array $item  The item that will be exported
3786          * @param array $owner the array of the item owner
3787          *
3788          * @return array|false The data for a comment
3789          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3790          */
3791         private static function constructComment(array $item, array $owner)
3792         {
3793                 $cachekey = "diaspora:constructComment:".$item['guid'];
3794
3795                 $result = Cache::get($cachekey);
3796                 if (!is_null($result)) {
3797                         return $result;
3798                 }
3799
3800                 $toplevel_item = Item::selectFirst(['guid', 'author-link'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3801                 if (!DBA::isResult($toplevel_item)) {
3802                         Logger::error('Missing parent conversation item', ['parent' => $item["parent"]]);
3803                         return false;
3804                 }
3805
3806                 $thread_parent_item = $toplevel_item;
3807                 if ($item['thr-parent'] != $item['parent-uri']) {
3808                         $thread_parent_item = Item::selectFirst(['guid', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3809                 }
3810
3811                 $body = $item["body"];
3812
3813                 if ((empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3814                         && !Config::get('system', 'disable_implicit_mentions')
3815                 ) {
3816                         $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3817                 }
3818
3819                 $text = html_entity_decode(BBCode::toMarkdown($body));
3820                 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3821                 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3822
3823                 $comment = [
3824                         "author"      => self::myHandle($owner),
3825                         "guid"        => $item["guid"],
3826                         "created_at"  => $created,
3827                         "edited_at"   => $edited,
3828                         "parent_guid" => $toplevel_item["guid"],
3829                         "text"        => $text,
3830                         "author_signature" => ""
3831                 ];
3832
3833                 // Send the thread parent guid only if it is a threaded comment
3834                 if ($item['thr-parent'] != $item['parent-uri']) {
3835                         $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3836                 }
3837
3838                 Cache::set($cachekey, $comment, Cache::QUARTER_HOUR);
3839
3840                 return($comment);
3841         }
3842
3843         /**
3844          * @brief Send a like or a comment
3845          *
3846          * @param array $item         The item that will be exported
3847          * @param array $owner        the array of the item owner
3848          * @param array $contact      Target of the communication
3849          * @param bool  $public_batch Is it a public post?
3850          *
3851          * @return int The result of the transmission
3852          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3853          * @throws \ImagickException
3854          */
3855         public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3856         {
3857                 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3858                         $message = self::constructAttend($item, $owner);
3859                         $type = "event_participation";
3860                 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3861                         $message = self::constructLike($item, $owner);
3862                         $type = "like";
3863                 } elseif (!in_array($item["verb"], [ACTIVITY_FOLLOW, ACTIVITY_TAG])) {
3864                         $message = self::constructComment($item, $owner);
3865                         $type = "comment";
3866                 }
3867
3868                 if (empty($message)) {
3869                         return false;
3870                 }
3871
3872                 $message["author_signature"] = self::signature($owner, $message);
3873
3874                 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3875         }
3876
3877         /**
3878          * @brief Creates a message from a signature record entry
3879          *
3880          * @param array $item The item that will be exported
3881          * @return array The message
3882          */
3883         private static function messageFromSignature(array $item)
3884         {
3885                 // Split the signed text
3886                 $signed_parts = explode(";", $item['signed_text']);
3887
3888                 if ($item["deleted"]) {
3889                         $message = ["author" => $item['signer'],
3890                                         "target_guid" => $signed_parts[0],
3891                                         "target_type" => $signed_parts[1]];
3892                 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3893                         $message = ["author" => $signed_parts[4],
3894                                         "guid" => $signed_parts[1],
3895                                         "parent_guid" => $signed_parts[3],
3896                                         "parent_type" => $signed_parts[2],
3897                                         "positive" => $signed_parts[0],
3898                                         "author_signature" => $item['signature'],
3899                                         "parent_author_signature" => ""];
3900                 } else {
3901                         // Remove the comment guid
3902                         $guid = array_shift($signed_parts);
3903
3904                         // Remove the parent guid
3905                         $parent_guid = array_shift($signed_parts);
3906
3907                         // Remove the handle
3908                         $handle = array_pop($signed_parts);
3909
3910                         $message = [
3911                                 "author" => $handle,
3912                                 "guid" => $guid,
3913                                 "parent_guid" => $parent_guid,
3914                                 "text" => implode(";", $signed_parts),
3915                                 "author_signature" => $item['signature'],
3916                                 "parent_author_signature" => ""
3917                         ];
3918                 }
3919                 return $message;
3920         }
3921
3922         /**
3923          * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3924          *
3925          * @param array $item         The item that will be exported
3926          * @param array $owner        the array of the item owner
3927          * @param array $contact      Target of the communication
3928          * @param bool  $public_batch Is it a public post?
3929          *
3930          * @return int The result of the transmission
3931          * @throws \Exception
3932          */
3933         public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3934         {
3935                 if ($item["deleted"]) {
3936                         return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3937                 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3938                         $type = "like";
3939                 } else {
3940                         $type = "comment";
3941                 }
3942
3943                 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3944
3945                 // Old way - is used by the internal Friendica functions
3946                 /// @todo Change all signatur storing functions to the new format
3947                 if ($item['signed_text'] && $item['signature'] && $item['signer']) {
3948                         $message = self::messageFromSignature($item);
3949                 } else {// New way
3950                         $msg = json_decode($item['signed_text'], true);
3951
3952                         $message = [];
3953                         if (is_array($msg)) {
3954                                 foreach ($msg as $field => $data) {
3955                                         if (!$item["deleted"]) {
3956                                                 if ($field == "diaspora_handle") {
3957                                                         $field = "author";
3958                                                 }
3959                                                 if ($field == "target_type") {
3960                                                         $field = "parent_type";
3961                                                 }
3962                                         }
3963
3964                                         $message[$field] = $data;
3965                                 }
3966                         } else {
3967                                 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
3968                         }
3969                 }
3970
3971                 $message["parent_author_signature"] = self::signature($owner, $message);
3972
3973                 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
3974
3975                 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3976         }
3977
3978         /**
3979          * @brief Sends a retraction (deletion) of a message, like or comment
3980          *
3981          * @param array $item         The item that will be exported
3982          * @param array $owner        the array of the item owner
3983          * @param array $contact      Target of the communication
3984          * @param bool  $public_batch Is it a public post?
3985          * @param bool  $relay        Is the retraction transmitted from a relay?
3986          *
3987          * @return int The result of the transmission
3988          * @throws \Exception
3989          */
3990         public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
3991         {
3992                 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3993
3994                 $msg_type = "retraction";
3995
3996                 if ($item['id'] == $item['parent']) {
3997                         $target_type = "Post";
3998                 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3999                         $target_type = "Like";
4000                 } else {
4001                         $target_type = "Comment";
4002                 }
4003
4004                 $message = ["author" => $itemaddr,
4005                                 "target_guid" => $item['guid'],
4006                                 "target_type" => $target_type];
4007
4008                 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
4009
4010                 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4011         }
4012
4013         /**
4014          * @brief Sends a mail
4015          *
4016          * @param array $item    The item that will be exported
4017          * @param array $owner   The owner
4018          * @param array $contact Target of the communication
4019          *
4020          * @return int The result of the transmission
4021          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4022          * @throws \ImagickException
4023          */
4024         public static function sendMail(array $item, array $owner, array $contact)
4025         {
4026                 $myaddr = self::myHandle($owner);
4027
4028                 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
4029                 if (!DBA::isResult($cnv)) {
4030                         Logger::log("conversation not found.");
4031                         return;
4032                 }
4033
4034                 $body = BBCode::toMarkdown($item["body"]);
4035                 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4036
4037                 $msg = [
4038                         "author" => $myaddr,
4039                         "guid" => $item["guid"],
4040                         "conversation_guid" => $cnv["guid"],
4041                         "text" => $body,
4042                         "created_at" => $created,
4043                 ];
4044
4045                 if ($item["reply"]) {
4046                         $message = $msg;
4047                         $type = "message";
4048                 } else {
4049                         $message = [
4050                                 "author" => $cnv["creator"],
4051                                 "guid" => $cnv["guid"],
4052                                 "subject" => $cnv["subject"],
4053                                 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4054                                 "participants" => $cnv["recips"],
4055                                 "message" => $msg
4056                         ];
4057
4058                         $type = "conversation";
4059                 }
4060
4061                 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4062         }
4063
4064         /**
4065          * @brief Split a name into first name and last name
4066          *
4067          * @param string $name The name
4068          *
4069          * @return array The array with "first" and "last"
4070          */
4071         public static function splitName($name) {
4072                 $name = trim($name);
4073
4074                 // Is the name longer than 64 characters? Then cut the rest of it.
4075                 if (strlen($name) > 64) {
4076                         if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4077                                 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4078                         } else {
4079                                 $name = substr($name, 0, 64);
4080                         }
4081                 }
4082
4083                 // Take the first word as first name
4084                 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4085                 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4086                 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4087                         return ['first' => $first, 'last' => $last];
4088                 }
4089
4090                 // Take the last word as last name
4091                 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4092                 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4093
4094                 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4095                         return ['first' => $first, 'last' => $last];
4096                 }
4097
4098                 // Take the first 32 characters if there is no space in the first 32 characters
4099                 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4100                         $first = substr($name, 0, 32);
4101                         $last = substr($name, 32);
4102                         return ['first' => $first, 'last' => $last];
4103                 }
4104
4105                 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4106                 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4107
4108                 // Check if the last name is longer than 32 characters
4109                 if (strlen($last) > 32) {
4110                         if (strpos($last, ' ') <= 32) {
4111                                 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4112                         } else {
4113                                 $last = substr($last, 0, 32);
4114                         }
4115                 }
4116
4117                 return ['first' => $first, 'last' => $last];
4118         }
4119
4120         /**
4121          * @brief Create profile data
4122          *
4123          * @param int $uid The user id
4124          *
4125          * @return array The profile data
4126          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4127          */
4128         private static function createProfileData($uid)
4129         {
4130                 $r = q(
4131                         "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4132                         FROM `profile`
4133                         INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4134                         INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4135                         WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4136                         intval($uid)
4137                 );
4138
4139                 if (!$r) {
4140                         return [];
4141                 }
4142
4143                 $profile = $r[0];
4144                 $handle = $profile["addr"];
4145
4146                 $split_name = self::splitName($profile['name']);
4147                 $first = $split_name['first'];
4148                 $last = $split_name['last'];
4149
4150                 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4151                 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4152                 $small = System::baseUrl().'/photo/custom/50/'  .$profile['uid'].'.jpg';
4153                 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4154
4155                 $dob = null;
4156                 $about = null;
4157                 $location = null;
4158                 $tags = null;
4159                 if ($searchable === 'true') {
4160                         $dob = '';
4161
4162                         if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4163                                 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4164                                 if ($year < 1004) {
4165                                         $year = 1004;
4166                                 }
4167                                 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4168                         }
4169
4170                         $about = $profile['about'];
4171                         $about = strip_tags(BBCode::convert($about));
4172
4173                         $location = Profile::formatLocation($profile);
4174                         $tags = '';
4175                         if ($profile['pub_keywords']) {
4176                                 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4177                                 $kw = str_replace('  ', ' ', $kw);
4178                                 $arr = explode(' ', $kw);
4179                                 if (count($arr)) {
4180                                         for ($x = 0; $x < 5; $x ++) {
4181                                                 if (!empty($arr[$x])) {
4182                                                         $tags .= '#'. trim($arr[$x]) .' ';
4183                                                 }
4184                                         }
4185                                 }
4186                         }
4187                         $tags = trim($tags);
4188                 }
4189
4190                 return ["author" => $handle,
4191                                 "first_name" => $first,
4192                                 "last_name" => $last,
4193                                 "image_url" => $large,
4194                                 "image_url_medium" => $medium,
4195                                 "image_url_small" => $small,
4196                                 "birthday" => $dob,
4197                                 "gender" => $profile['gender'],
4198                                 "bio" => $about,
4199                                 "location" => $location,
4200                                 "searchable" => $searchable,
4201                                 "nsfw" => "false",
4202                                 "tag_string" => $tags];
4203         }
4204
4205         /**
4206          * @brief Sends profile data
4207          *
4208          * @param int  $uid    The user id
4209          * @param bool $recips optional, default false
4210          * @return void
4211          * @throws \Exception
4212          */
4213         public static function sendProfile($uid, $recips = false)
4214         {
4215                 if (!$uid) {
4216                         return;
4217                 }
4218
4219                 $owner = User::getOwnerDataById($uid);
4220                 if (!$owner) {
4221                         return;
4222                 }
4223
4224                 if (!$recips) {
4225                         $recips = q(
4226                                 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4227                                 AND `uid` = %d AND `rel` != %d",
4228                                 DBA::escape(Protocol::DIASPORA),
4229                                 intval($uid),
4230                                 intval(Contact::SHARING)
4231                         );
4232                 }
4233
4234                 if (!$recips) {
4235                         return;
4236                 }
4237
4238                 $message = self::createProfileData($uid);
4239
4240                 // @ToDo Split this into single worker jobs
4241                 foreach ($recips as $recip) {
4242                         Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4243                         self::buildAndTransmit($owner, $recip, "profile", $message);
4244                 }
4245         }
4246
4247         /**
4248          * @brief Creates the signature for likes that are created on our system
4249          *
4250          * @param integer $uid  The user of that comment
4251          * @param array   $item Item array
4252          *
4253          * @return array Signed content
4254          * @throws \Exception
4255          */
4256         public static function createLikeSignature($uid, array $item)
4257         {
4258                 $owner = User::getOwnerDataById($uid);
4259                 if (empty($owner)) {
4260                         Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4261                         return false;
4262                 }
4263
4264                 if (!in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4265                         return false;
4266                 }
4267
4268                 $message = self::constructLike($item, $owner);
4269                 if ($message === false) {
4270                         return false;
4271                 }
4272
4273                 $message["author_signature"] = self::signature($owner, $message);
4274
4275                 return $message;
4276         }
4277
4278         /**
4279          * @brief Creates the signature for Comments that are created on our system
4280          *
4281          * @param integer $uid  The user of that comment
4282          * @param array   $item Item array
4283          *
4284          * @return array Signed content
4285          * @throws \Exception
4286          */
4287         public static function createCommentSignature($uid, array $item)
4288         {
4289                 $owner = User::getOwnerDataById($uid);
4290                 if (empty($owner)) {
4291                         Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4292                         return false;
4293                 }
4294
4295                 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4296                 $item['thr-parent'] = $item['parent-uri'];
4297
4298                 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4299                 if (!DBA::isResult($parent)) {
4300                         return;
4301                 }
4302
4303                 $item['parent-uri'] = $parent['parent-uri'];
4304
4305                 $message = self::constructComment($item, $owner);
4306                 if ($message === false) {
4307                         return false;
4308                 }
4309
4310                 $message["author_signature"] = self::signature($owner, $message);
4311
4312                 return $message;
4313         }
4314 }