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