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