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