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