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