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