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