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