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