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