3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Protocol;
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\Markdown;
27 use Friendica\Core\Cache\Enum\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\GServer;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\Mail;
40 use Friendica\Model\Post;
41 use Friendica\Model\Tag;
42 use Friendica\Model\User;
43 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
44 use Friendica\Network\HTTPException;
45 use Friendica\Network\Probe;
46 use Friendica\Protocol\Delivery;
47 use Friendica\Util\Crypto;
48 use Friendica\Util\DateTimeFormat;
49 use Friendica\Util\Map;
50 use Friendica\Util\Network;
51 use Friendica\Util\Strings;
52 use Friendica\Util\XML;
53 use GuzzleHttp\Psr7\Uri;
57 * This class contains functions to communicate via the Diaspora protocol
58 * @see https://diaspora.github.io/diaspora_federation/
64 const FORCED_FETCH = 2;
67 * Return a list of participating contacts for a thread
69 * This is used for the participation feature.
70 * One of the parameters is a contact array.
71 * This is done to avoid duplicates.
73 * @param array $item Item that is about to be delivered
74 * @param array $contacts The previously fetched contacts
76 * @return array of relay servers
79 public static function participantsForThread(array $item, array $contacts): array
81 if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
82 Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]);
86 $items = Post::select(
87 ['author-id', 'author-link', 'parent-author-link', 'parent-guid', 'guid'],
88 ['parent' => $item['parent'], 'gravity' => [Item::GRAVITY_COMMENT, Item::GRAVITY_ACTIVITY]]
90 while ($item = Post::fetch($items)) {
91 $contact = DBA::selectFirst(
93 ['id', 'url', 'name', 'protocol', 'batch', 'network'],
94 ['id' => $item['author-id']]
97 !DBA::isResult($contact) || empty($contact['batch']) ||
98 ($contact['network'] != Protocol::DIASPORA) ||
99 Strings::compareLink($item['parent-author-link'], $item['author-link'])
105 foreach ($contacts as $entry) {
106 if ($entry['batch'] == $contact['batch']) {
112 Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]);
113 $contacts[] = $contact;
122 * verify the envelope and return the verified data
124 * @param string $envelope The magic envelope
126 * @return string|bool verified data or false on error
127 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
128 * @throws \ImagickException
130 private static function verifyMagicEnvelope(string $envelope)
132 $basedom = XML::parseString($envelope, true);
134 if (!is_object($basedom)) {
135 Logger::notice('Envelope is no XML file');
139 $children = $basedom->children(ActivityNamespace::SALMON_ME);
141 if (sizeof($children) == 0) {
142 Logger::notice('XML has no children');
148 $data = Strings::base64UrlDecode($children->data);
149 $type = $children->data->attributes()->type[0];
151 $encoding = $children->encoding;
153 $alg = $children->alg;
155 $sig = Strings::base64UrlDecode($children->sig);
156 $key_id = $children->sig->attributes()->key_id[0];
158 $handle = Strings::base64UrlDecode($key_id);
161 $b64url_data = Strings::base64UrlEncode($data);
162 $msg = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
164 $signable_data = $msg . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
167 Logger::notice('No author could be decoded. Discarding. Message: ' . $envelope);
172 $key = self::key(WebFingerUri::fromString($handle));
174 throw new \InvalidArgumentException();
176 } catch (\InvalidArgumentException $e) {
177 Logger::notice("Couldn't get a key for handle " . $handle . ". Discarding.");
181 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
183 Logger::notice('Message from ' . $handle . ' did not verify. Discarding.');
191 * encrypts data via AES
193 * @param string $key The AES key
194 * @param string $iv The IV (is used for CBC encoding)
195 * @param string $data The data that is to be encrypted
197 * @return string encrypted data
199 private static function aesEncrypt(string $key, string $iv, string $data): string
201 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
205 * decrypts data via AES
207 * @param string $key The AES key
208 * @param string $iv The IV (is used for CBC encoding)
209 * @param string $encrypted The encrypted data
211 * @return string decrypted data
213 private static function aesDecrypt(string $key, string $iv, string $encrypted): string
215 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
219 * Decodes incoming Diaspora message in the new format. This method returns false on an error.
221 * @param string $raw raw post message
222 * @param string $privKey The private key of the importer
223 * @param boolean $no_exit Don't do an http exit on error
226 * 'message' -> decoded Diaspora XML message
227 * 'author' -> author diaspora handle
228 * 'key' -> author public key (converted to pkcs#8)
229 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
230 * @throws \ImagickException
232 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
234 $data = json_decode($raw);
236 // Is it a private post? Then decrypt the outer Salmon
237 if (is_object($data)) {
239 if (!isset($data->aes_key) || !isset($data->encrypted_magic_envelope)) {
240 Logger::info('Missing keys "aes_key" and/or "encrypted_magic_envelope"', ['data' => $data]);
241 throw new \RuntimeException('Missing keys "aes_key" and/or "encrypted_magic_envelope"');
244 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
245 $ciphertext = base64_decode($data->encrypted_magic_envelope);
247 $outer_key_bundle = '';
248 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
249 $j_outer_key_bundle = json_decode($outer_key_bundle);
251 if (!is_object($j_outer_key_bundle)) {
252 Logger::info('Unable to decode outer key bundle', ['outer_key_bundle' => $outer_key_bundle]);
253 throw new \RuntimeException('Unable to decode outer key bundle');
256 if (!isset($j_outer_key_bundle->iv) || !isset($j_outer_key_bundle->key)) {
257 Logger::info('Missing keys "iv" and/or "key" from outer Salmon', ['j_outer_key_bundle' => $j_outer_key_bundle]);
258 throw new \RuntimeException('Missing keys "iv" and/or "key" from outer Salmon');
261 $outer_iv = base64_decode($j_outer_key_bundle->iv);
262 $outer_key = base64_decode($j_outer_key_bundle->key);
264 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
265 } catch (\Throwable $e) {
266 Logger::notice('Outer Salmon did not verify. Discarding.');
270 throw new HTTPException\BadRequestException();
277 $basedom = XML::parseString($xml, true);
279 if (!is_object($basedom)) {
280 Logger::notice('Received data does not seem to be an XML. Discarding. ' . $xml);
284 throw new HTTPException\BadRequestException();
288 $base = $basedom->children(ActivityNamespace::SALMON_ME);
290 // Not sure if this cleaning is needed
291 $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
293 // Build the signed data
294 $type = $base->data[0]->attributes()->type[0];
295 $encoding = $base->encoding;
297 $signed_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
299 // This is the signature
300 $signature = Strings::base64UrlDecode($base->sig);
302 // Get the senders' public key
303 $key_id = $base->sig[0]->attributes()->key_id[0];
304 $author_addr = base64_decode($key_id);
305 if ($author_addr == '') {
306 Logger::notice('No author could be decoded. Discarding. Message: ' . $xml);
310 throw new HTTPException\BadRequestException();
315 $author = WebFingerUri::fromString($author_addr);
316 $key = self::key($author);
318 throw new \InvalidArgumentException();
320 } catch (\InvalidArgumentException $e) {
321 Logger::notice("Couldn't get a key for handle " . $author_addr . ". Discarding.");
325 throw new HTTPException\BadRequestException();
329 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
331 Logger::notice('Message did not verify. Discarding.');
335 throw new HTTPException\BadRequestException();
340 'message' => (string)Strings::base64UrlDecode($base->data),
341 'author' => $author->getAddr(),
342 'key' => (string)$key
347 * Decodes incoming Diaspora message in the deprecated format
349 * @param string $xml urldecoded Diaspora salmon
350 * @param string $privKey The private key of the importer
353 * 'message' -> decoded Diaspora XML message
354 * 'author' -> author diaspora handle
355 * 'key' -> author public key (converted to pkcs#8)
356 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
357 * @throws \ImagickException
359 public static function decode(string $xml, string $privKey = '')
362 $basedom = XML::parseString($xml);
364 if (!is_object($basedom)) {
365 Logger::notice('XML is not parseable.');
368 $children = $basedom->children('https://joindiaspora.com/protocol');
370 $inner_aes_key = null;
373 if ($children->header) {
375 $idom = $children->header;
377 // This happens with posts from a relais
378 if (empty($privKey)) {
379 Logger::info('This is no private post in the old format');
383 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
385 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
386 $ciphertext = base64_decode($encrypted_header->ciphertext);
388 $outer_key_bundle = '';
389 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
391 $j_outer_key_bundle = json_decode($outer_key_bundle);
393 $outer_iv = base64_decode($j_outer_key_bundle->iv);
394 $outer_key = base64_decode($j_outer_key_bundle->key);
396 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
398 Logger::info('decrypted', ['data' => $decrypted]);
399 $idom = XML::parseString($decrypted);
401 $inner_iv = base64_decode($idom->iv);
402 $inner_aes_key = base64_decode($idom->aes_key);
406 $author = WebFingerUri::fromString($idom->author_id);
407 } catch (\Throwable $e) {
408 Logger::notice('Could not retrieve author URI.', ['idom' => $idom]);
409 throw new \Friendica\Network\HTTPException\BadRequestException();
412 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
414 // figure out where in the DOM tree our data is hiding
417 if ($dom->provenance->data) {
418 $base = $dom->provenance;
419 } elseif ($dom->env->data) {
421 } elseif ($dom->data) {
426 Logger::notice('unable to locate salmon data in xml');
427 throw new HTTPException\BadRequestException();
431 // Stash the signature away for now. We have to find their key or it won't be good for anything.
432 $signature = Strings::base64UrlDecode($base->sig);
436 // strip whitespace so our data element will return to one big base64 blob
437 $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
440 // stash away some other stuff for later
442 $type = $base->data[0]->attributes()->type[0];
443 $keyhash = $base->sig[0]->attributes()->keyhash[0];
444 $encoding = $base->encoding;
447 $signed_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
450 $data = Strings::base64UrlDecode($data);
453 $inner_decrypted = $data;
455 // Decode the encrypted blob
456 $inner_encrypted = base64_decode($data);
457 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
460 // Once we have the author URI, go to the web and try to find their public key
461 // (first this will look it up locally if it is in the diaspora-contact cache)
462 // This will also convert diaspora public key from pkcs#1 to pkcs#8
463 Logger::info('Fetching key for ' . $author);
464 $key = self::key($author);
466 Logger::notice('Could not retrieve author key.');
467 throw new HTTPException\BadRequestException();
470 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
473 Logger::notice('Message did not verify. Discarding.');
474 throw new HTTPException\BadRequestException();
477 Logger::info('Message verified.');
480 'message' => $inner_decrypted,
481 'author' => $author->getAddr(),
488 * Dispatches public messages and find the fitting receivers
490 * @param array $msg The post that will be dispatched
491 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
493 * @return int|bool The message id of the generated message, "true" or "false" if there was an error
494 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
495 * @throws \ImagickException
497 public static function dispatchPublic(array $msg, int $direction)
499 if (!DI::config()->get('system', 'diaspora_enabled')) {
500 Logger::notice('Diaspora is disabled');
504 if (!($fields = self::validPosting($msg))) {
505 Logger::notice('Invalid posting', ['msg' => $msg]);
511 'page-flags' => User::PAGE_FLAGS_FREELOVE
513 $success = self::dispatch($importer, $msg, $fields, $direction);
519 * Dispatches the different message types to the different functions
521 * @param array $importer Array of the importer user
522 * @param array $msg The post that will be dispatched
523 * @param SimpleXMLElement $fields SimpleXML object that contains the message
524 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
526 * @return int|bool The message id of the generated message, "true" or "false" if there was an error
527 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
528 * @throws \ImagickException
530 public static function dispatch(array $importer, array $msg, SimpleXMLElement $fields = null, int $direction = self::PUSHED)
532 // The sender is the handle of the contact that sent the message.
533 // This will often be different with relayed messages (for example "like" and "comment")
534 $sender = WebFingerUri::fromString($msg['author']);
536 // This is only needed for private postings since this is already done for public ones before
537 if (is_null($fields)) {
539 if (!($fields = self::validPosting($msg))) {
540 Logger::notice('Invalid posting', ['msg' => $msg]);
547 $type = $fields->getName();
549 Logger::info('Received message', ['type' => $type, 'sender' => $sender->getAddr(), 'user' => $importer['uid']]);
552 case 'account_migration':
554 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
557 return self::receiveAccountMigration($importer, $fields);
559 case 'account_deletion':
560 return self::receiveAccountDeletion($fields);
563 return self::receiveComment($importer, $sender, $fields, $msg['message'], $direction);
567 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
570 return self::receiveContactRequest($importer, $fields);
574 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
577 return self::receiveConversation($importer, $msg, $fields);
580 return self::receiveLike($importer, $sender, $fields, $direction);
584 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
587 return self::receiveMessage($importer, $fields);
589 case 'participation':
591 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
594 return self::receiveParticipation($importer, $fields, $direction);
596 case 'photo': // Not implemented
597 return self::receivePhoto($importer, $fields);
599 case 'poll_participation': // Not implemented
600 return self::receivePollParticipation($importer, $fields);
604 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
607 return self::receiveProfile($importer, $fields);
610 return self::receiveReshare($importer, $fields, $msg['message'], $direction);
613 return self::receiveRetraction($importer, $sender, $fields);
615 case 'status_message':
616 return self::receiveStatusMessage($importer, $fields, $msg['message'], $direction);
619 Logger::notice('Unknown message type ' . $type);
625 * Checks if a posting is valid and fetches the data fields.
627 * This function does not only check the signature.
628 * It also does the conversion between the old and the new diaspora format.
630 * @param array $msg Array with the XML, the sender handle and the sender signature
632 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
633 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
634 * @throws \ImagickException
636 private static function validPosting(array $msg)
638 $data = XML::parseString($msg['message']);
640 if (!is_object($data)) {
641 Logger::info('No valid XML', ['message' => $msg['message']]);
645 // Is this the new or the old version?
646 if ($data->getName() == 'XML') {
648 foreach ($data->post->children() as $child) {
656 $type = $element->getName();
659 Logger::debug('Got message', ['type' => $type, 'message' => $msg['message']]);
661 // All retractions are handled identically from now on.
662 // In the new version there will only be "retraction".
663 if (in_array($type, ['signed_retraction', 'relayable_retraction']))
664 $type = 'retraction';
666 if ($type == 'request') {
670 $fields = new SimpleXMLElement('<' . $type . '/>');
673 $author_signature = null;
674 $parent_author_signature = null;
676 foreach ($element->children() as $fieldname => $entry) {
678 // Translation for the old XML structure
679 if ($fieldname == 'diaspora_handle') {
680 $fieldname = 'author';
682 if ($fieldname == 'participant_handles') {
683 $fieldname = 'participants';
685 if (in_array($type, ['like', 'participation'])) {
686 if ($fieldname == 'target_type') {
687 $fieldname = 'parent_type';
690 if ($fieldname == 'sender_handle') {
691 $fieldname = 'author';
693 if ($fieldname == 'recipient_handle') {
694 $fieldname = 'recipient';
696 if ($fieldname == 'root_diaspora_id') {
697 $fieldname = 'root_author';
699 if ($type == 'status_message') {
700 if ($fieldname == 'raw_message') {
704 if ($type == 'retraction') {
705 if ($fieldname == 'post_guid') {
706 $fieldname = 'target_guid';
708 if ($fieldname == 'type') {
709 $fieldname = 'target_type';
714 if (($fieldname == 'author_signature') && ($entry != '')) {
715 $author_signature = base64_decode($entry);
716 } elseif (($fieldname == 'parent_author_signature') && ($entry != '')) {
717 $parent_author_signature = base64_decode($entry);
718 } elseif (!in_array($fieldname, ['author_signature', 'parent_author_signature', 'target_author_signature'])) {
719 if ($signed_data != '') {
723 $signed_data .= $entry;
726 !in_array($fieldname, ['parent_author_signature', 'target_author_signature'])
727 || ($orig_type == 'relayable_retraction')
729 XML::copy($entry, $fields, $fieldname);
733 // This is something that shouldn't happen at all.
734 if (in_array($type, ['status_message', 'reshare', 'profile'])) {
735 if ($msg['author'] != $fields->author) {
736 Logger::notice('Message handle is not the same as envelope sender. Quitting this message.', ['author1' => $msg['author'], 'author2' => $fields->author]);
741 // Only some message types have signatures. So we quit here for the other types.
742 if (!in_array($type, ['comment', 'like'])) {
746 if (!isset($author_signature) && ($msg['author'] == $fields->author)) {
747 Logger::debug('No author signature, but the sender matches the author', ['type' => $type, 'msg-author' => $msg['author'], 'message' => $msg['message']]);
751 // No author_signature? This is a must, so we quit.
752 if (!isset($author_signature)) {
753 Logger::info('No author signature', ['type' => $type, 'msg-author' => $msg['author'], 'fields-author' => $fields->author, 'message' => $msg['message']]);
757 if (isset($parent_author_signature)) {
758 $key = self::key(WebFingerUri::fromString($msg['author']));
760 Logger::info('No key found for parent', ['author' => $msg['author']]);
764 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, 'sha256')) {
765 Logger::info('No valid parent author signature', ['author' => $msg['author'], 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $parent_author_signature]);
771 $key = self::key(WebFingerUri::fromString($fields->author));
773 throw new \InvalidArgumentException();
775 } catch (\Throwable $e) {
776 Logger::info('No key found', ['author' => $fields->author]);
780 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, 'sha256')) {
781 Logger::info('No valid author signature for author', ['author' => $fields->author, 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $author_signature]);
789 * Fetches the public key for a given handle
791 * @param WebFingerUri $uri The handle
793 * @return string The public key
794 * @throws InternalServerErrorException
795 * @throws \ImagickException
797 private static function key(WebFingerUri $uri): string
799 Logger::info('Fetching diaspora key', ['handle' => $uri->getAddr(), 'callstack' => System::callstack(20)]);
801 return DI::dsprContact()->getByAddr($uri)->pubKey;
802 } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) {
808 * Get a contact id for a given handle
810 * @param int $uid The user id
811 * @param WebFingerUri $uri
813 * @return array Contact data
814 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
815 * @throws \ImagickException
817 private static function contactByHandle(int $uid, WebFingerUri $uri): array
819 Contact::updateByUrlIfNeeded($uri->getAddr());
820 return Contact::getByURL($uri->getAddr(), null, [], $uid);
824 * Checks if the given contact url does support ActivityPub
826 * @param string $url profile url or WebFinger address
827 * @param boolean|null $update true = always update, false = never update, null = update when not found or outdated
829 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
830 * @throws \ImagickException
832 public static function isSupportedByContactUrl(string $url, ?bool $update = null): bool
834 $contact = Contact::getByURL($url, $update, ['uri-id', 'network']);
836 $supported = DI::dsprContact()->existsByUriId($contact['uri-id'] ?? 0);
838 if (!$supported && is_null($update) && ($contact['network'] == Protocol::DFRN)) {
839 $supported = self::isSupportedByContactUrl($url, true);
846 * Check if posting is allowed for this contact
848 * @param array $importer Array of the importer user
849 * @param array $contact The contact that is checked
850 * @param bool $is_comment Is the check for a comment?
852 * @return bool is the contact allowed to post?
854 private static function postAllow(array $importer, array $contact, bool $is_comment = false): bool
857 * Perhaps we were already sharing with this person. Now they're sharing with us.
858 * That makes us friends.
859 * Normally this should have handled by getting a request - but this could get lost
861 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
862 // It is not removed by now. Possibly the code is needed?
863 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
865 // array('rel' => Contact::FRIEND, 'writable' => true),
866 // array('id' => $contact["id"], 'uid' => $contact["uid"])
869 // $contact["rel"] = Contact::FRIEND;
870 // Logger::notice("defining user ".$contact["nick"]." as friend");
873 // Contact server is blocked
874 if (Network::isUrlBlocked($contact['url'])) {
876 // We don't seem to like that person
877 } elseif ($contact['blocked']) {
878 // Maybe blocked, don't accept.
880 // We are following this person?
881 } elseif (($contact['rel'] == Contact::SHARING) || ($contact['rel'] == Contact::FRIEND)) {
882 // Yes, then it is fine.
884 // Is the message a global user or a comment?
885 } elseif (($importer['uid'] == 0) || $is_comment) {
886 // Messages for the global users and comments are always accepted
894 * Fetches the contact id for a handle and checks if posting is allowed
896 * @param array $importer Array of the importer user
897 * @param WebFingerUri $contact_uri The checked contact
898 * @param bool $is_comment Is the check for a comment?
900 * @return array|bool The contact data or false on error
901 * @throws InternalServerErrorException
902 * @throws \ImagickException
904 private static function allowedContactByHandle(array $importer, WebFingerUri $contact_uri, bool $is_comment = false)
906 $contact = self::contactByHandle($importer['uid'], $contact_uri);
908 Logger::notice('A Contact for handle ' . $contact_uri . ' and user ' . $importer['uid'] . ' was not found');
909 // If a contact isn't found, we accept it anyway if it is a comment
910 if ($is_comment && ($importer['uid'] != 0)) {
911 return self::contactByHandle(0, $contact_uri);
912 } elseif ($is_comment) {
919 if (!self::postAllow($importer, $contact, $is_comment)) {
920 Logger::notice('The handle: ' . $contact_uri . ' is not allowed to post to user ' . $importer['uid']);
927 * Does the message already exists on the system?
929 * @param int $uid The user id
930 * @param string $guid The guid of the message
932 * @return int|bool message id if the message already was stored into the system - or false.
935 private static function messageExists(int $uid, string $guid)
937 $item = Post::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
938 if (DBA::isResult($item)) {
939 Logger::notice('Message already exists.', ['uid' => $uid, 'guid' => $guid, 'id' => $item['id']]);
947 * Checks for links to posts in a message
949 * @param array $item The item array
953 private static function fetchGuid(array $item)
955 preg_replace_callback(
956 "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism",
957 function ($match) use ($item) {
958 self::fetchGuidSub($match, $item);
963 preg_replace_callback(
964 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
965 function ($match) use ($item) {
966 self::fetchGuidSub($match, $item);
973 * Checks for relative /people/* links in an item body to match local
974 * contacts or prepends the remote host taken from the author link.
976 * @param string $body The item body to replace links from
977 * @param string $author_link The author link for missing local contact fallback
979 * @return string the replaced string
981 public static function replacePeopleGuid(string $body, string $author_link): string
983 $return = preg_replace_callback(
984 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
985 function ($match) use ($author_link) {
987 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
988 // 1 => '0123456789abcdef'
990 $handle = DI::dsprContact()->getUrlByGuid($match[1]);
993 $return = '@[url=' . $handle . ']' . $match[2] . '[/url]';
995 // No local match, restoring absolute remote URL from author scheme and host
996 $author_url = parse_url($author_link);
997 $return = '[url=' . $author_url['scheme'] . '://' . $author_url['host'] . '/people/' . $match[1] . ']' . $match[2] . '[/url]';
1009 * sub function of "fetchGuid" which checks for links in messages
1011 * @param array $match array containing a link that has to be checked for a message link
1012 * @param array $item The item array
1014 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1015 * @throws \ImagickException
1017 private static function fetchGuidSub(array $match, array $item)
1019 if (!self::storeByGuid($match[1], $item['author-link'], true)) {
1020 self::storeByGuid($match[1], $item['owner-link'], true);
1025 * Fetches an item with a given guid from a given server
1027 * @param string $guid the message guid
1028 * @param string $server The server address
1029 * @param bool $force Forced fetch
1031 * @return int|bool the message id of the stored message or false
1032 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1033 * @throws \ImagickException
1035 private static function storeByGuid(string $guid, string $server, bool $force)
1037 $serverparts = parse_url($server);
1039 if (empty($serverparts['host']) || empty($serverparts['scheme'])) {
1043 $server = $serverparts['scheme'] . '://' . $serverparts['host'];
1045 Logger::info('Trying to fetch item ' . $guid . ' from ' . $server);
1047 $msg = self::message($guid, $server);
1053 Logger::info('Successfully fetched item ' . $guid . ' from ' . $server);
1055 // Now call the dispatcher
1056 return self::dispatchPublic($msg, $force ? self::FORCED_FETCH : self::FETCHED);
1060 * Fetches a message from a server
1062 * @param string $guid message guid
1063 * @param string $server The url of the server
1064 * @param int $level Endless loop prevention
1067 * 'message' => The message XML
1068 * 'author' => The author handle
1069 * 'key' => The public key of the author
1070 * @throws \Exception
1072 public static function message(string $guid, string $server, int $level = 0)
1078 // This will work for new Diaspora servers and Friendica servers from 3.5
1079 $source_url = $server . '/fetch/post/' . urlencode($guid);
1081 Logger::info('Fetch post from ' . $source_url);
1083 $envelope = DI::httpClient()->fetch($source_url, HttpClientAccept::MAGIC);
1085 Logger::info('Envelope was fetched.');
1086 $x = self::verifyMagicEnvelope($envelope);
1088 Logger::info('Envelope could not be verified.');
1090 Logger::info('Envelope was verified.');
1100 $source_xml = XML::parseString($x);
1102 if (!is_object($source_xml)) {
1106 if ($source_xml->post->reshare) {
1107 // Reshare of a reshare - old Diaspora version
1108 Logger::info('Message is a reshare');
1109 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1110 } elseif ($source_xml->getName() == 'reshare') {
1111 // Reshare of a reshare - new Diaspora version
1112 Logger::info('Message is a new reshare');
1113 return self::message($source_xml->root_guid, $server, ++$level);
1116 $author_handle = '';
1118 // Fetch the author - for the old and the new Diaspora version
1119 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1120 $author_handle = (string)$source_xml->post->status_message->diaspora_handle;
1121 } elseif ($source_xml->author && ($source_xml->getName() == 'status_message')) {
1122 $author_handle = (string)$source_xml->author;
1126 $author = WebFingerUri::fromString($author_handle);
1127 } catch (\InvalidArgumentException $e) {
1128 // If this isn't a "status_message" then quit
1129 Logger::info("Message doesn't seem to be a status message");
1135 'author' => $author->getAddr(),
1136 'key' => self::key($author)
1141 * Fetches an item with a given URL
1143 * @param string $url the message url
1144 * @param int $uid User id
1146 * @return int|bool the message id of the stored message or false
1147 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1148 * @throws \ImagickException
1150 public static function fetchByURL(string $url, int $uid = 0)
1152 // Check for Diaspora (and Friendica) typical paths
1153 if (!preg_match('=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i', $url, $matches)) {
1154 Logger::notice('Invalid url', ['url' => $url]);
1158 $guid = urldecode($matches[2]);
1160 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1161 if (DBA::isResult($item)) {
1162 Logger::info('Found', ['id' => $item['id']]);
1166 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1167 $ret = self::storeByGuid($guid, $matches[1], true);
1168 Logger::info('Result', ['ret' => $ret]);
1170 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1171 if (DBA::isResult($item)) {
1172 Logger::info('Found', ['id' => $item['id']]);
1175 Logger::notice('Not found', ['guid' => $guid, 'uid' => $uid]);
1181 * Fetches the item record of a given guid
1183 * @param int $uid The user id
1184 * @param string $guid message guid
1185 * @param WebFingerUri $author
1186 * @param array $contact The contact of the item owner
1188 * @return array|bool the item record or false on failure
1189 * @throws \Exception
1191 private static function parentItem(int $uid, string $guid, WebFingerUri $author, array $contact)
1194 'id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1195 'author-name', 'author-link', 'author-avatar', 'gravity',
1196 'owner-name', 'owner-link', 'owner-avatar'
1199 $condition = ['uid' => $uid, 'guid' => $guid];
1200 $item = Post::selectFirst($fields, $condition);
1202 if (!DBA::isResult($item)) {
1204 $result = self::storeByGuid($guid, DI::dsprContact()->getByAddr($author)->url, false);
1206 // We don't have an url for items that arrived at the public dispatcher
1207 if (!$result && !empty($contact['url'])) {
1208 $result = self::storeByGuid($guid, $contact['url'], false);
1212 Logger::info('Fetched missing item ' . $guid . ' - result: ' . $result);
1214 $item = Post::selectFirst($fields, $condition);
1216 } catch (HTTPException\NotFoundException $e) {
1217 Logger::notice('Unable to retrieve author details', ['author' => $author->getAddr()]);
1221 if (!DBA::isResult($item)) {
1222 Logger::notice('Parent item not found: parent: ' . $guid . ' - user: ' . $uid);
1225 Logger::info('Parent item found: parent: ' . $guid . ' - user: ' . $uid);
1231 * returns contact details for the given user
1233 * @param array $def_contact The default details if the contact isn't found
1234 * @param string $contact_url The url of the contact
1235 * @param int $uid The user id
1238 * 'cid' => contact id
1239 * 'network' => network type
1240 * @throws \Exception
1242 private static function authorContactByUrl(array $def_contact, string $contact_url, int $uid): array
1244 $condition = ['nurl' => Strings::normaliseLink($contact_url), 'uid' => $uid];
1245 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1246 if (DBA::isResult($contact)) {
1247 $cid = $contact['id'];
1248 $network = $contact['network'];
1250 $cid = $def_contact['id'];
1251 $network = Protocol::DIASPORA;
1256 'network' => $network
1261 * Is the profile a hubzilla profile?
1263 * @param string $url The profile link
1265 * @return bool is it a hubzilla server?
1267 private static function isHubzilla(string $url): bool
1269 return strstr($url, '/channel/');
1273 * Generate a post link with a given handle and message guid
1275 * @param string $addr The user handle
1276 * @param string $guid message guid
1277 * @param string $parent_guid optional parent guid
1279 * @return string the post link
1280 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1281 * @throws \ImagickException
1283 private static function plink(string $addr, string $guid, string $parent_guid = ''): string
1285 $contact = Contact::getByURL($addr);
1286 if (empty($contact)) {
1287 Logger::info('No contact data for address', ['addr' => $addr]);
1291 if (empty($contact['baseurl'])) {
1292 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1293 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1297 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1298 if (!empty($gserver['platform'])) {
1299 $platform = strtolower($gserver['platform']);
1300 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1303 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1304 if (self::isHubzilla($contact['url'])) {
1305 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1306 $platform = 'hubzilla';
1307 } elseif ($contact['network'] == Protocol::DFRN) {
1308 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1309 $platform = 'friendica';
1313 if ($platform == 'friendica') {
1314 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1317 if ($platform == 'hubzilla') {
1318 return $contact['baseurl'] . '/item/' . $guid;
1321 if ($platform == 'socialhome') {
1322 return $contact['baseurl'] . '/content/' . $guid;
1325 if ($platform != 'diaspora') {
1326 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1330 if ($parent_guid != '') {
1331 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1333 return $contact['baseurl'] . '/posts/' . $guid;
1338 * Receives account migration
1340 * @param array $importer Array of the importer user
1341 * @param SimpleXMLElement $data The message object
1343 * @return bool Success
1344 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1345 * @throws \ImagickException
1347 private static function receiveAccountMigration(array $importer, SimpleXMLElement $data): bool
1350 $old_author = WebFingerUri::fromString(XML::unescape($data->author));
1351 $new_author = WebFingerUri::fromString(XML::unescape($data->profile->author));
1352 } catch (\Throwable $e) {
1353 Logger::notice('Cannot find handles for sender and user', ['data' => $data]);
1357 $signature = XML::unescape($data->signature);
1359 $contact = self::contactByHandle($importer['uid'], $old_author);
1361 Logger::notice('Cannot find contact for sender: ' . $old_author . ' and user ' . $importer['uid']);
1365 Logger::info('Got migration for ' . $old_author . ', to ' . $new_author . ' with user ' . $importer['uid']);
1368 $signed_text = 'AccountMigration:' . $old_author . ':' . $new_author;
1369 $key = self::key($old_author);
1370 if (!Crypto::rsaVerify($signed_text, $signature, $key, 'sha256')) {
1371 Logger::notice('No valid signature for migration.');
1375 // Update the profile
1376 self::receiveProfile($importer, $data->profile);
1378 // change the technical stuff in contact
1379 $data = Probe::uri($new_author);
1380 if ($data['network'] == Protocol::PHANTOM) {
1381 Logger::notice("Account for " . $new_author . " couldn't be probed.");
1386 'url' => $data['url'],
1387 'nurl' => Strings::normaliseLink($data['url']),
1388 'name' => $data['name'],
1389 'nick' => $data['nick'],
1390 'addr' => $data['addr'],
1391 'batch' => $data['batch'],
1392 'notify' => $data['notify'],
1393 'poll' => $data['poll'],
1394 'network' => $data['network'],
1397 Contact::update($fields, ['addr' => $old_author->getAddr()]);
1399 Logger::info('Contacts are updated.');
1405 * Processes an account deletion
1407 * @param SimpleXMLElement $data The message object
1409 * @return bool Success
1410 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1412 private static function receiveAccountDeletion(SimpleXMLElement $data): bool
1414 $author_handle = XML::unescape($data->author);
1416 $contacts = DBA::select('contact', ['id'], ['addr' => $author_handle]);
1417 while ($contact = DBA::fetch($contacts)) {
1418 Contact::remove($contact['id']);
1420 DBA::close($contacts);
1422 Logger::info('Removed contacts for ' . $author_handle);
1428 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1430 * @param string $guid Message guid
1431 * @param WebFingerUri|null $person_uri Optional person to derive the base URL from
1433 * @return string The constructed uri or the one from our database or empty string
1434 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1435 * @throws \ImagickException
1437 private static function getUriFromGuid(string $guid, WebFingerUri $person_uri = null): string
1439 $item = Post::selectFirst(['uri'], ['guid' => $guid]);
1441 return $item['uri'];
1442 } elseif ($person_uri) {
1444 return DI::dsprContact()->selectOneByAddr($person_uri)->baseurl . '/objects/' . $guid;
1445 } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) {
1454 * Store the mentions in the tag table
1456 * @param integer $uriid
1457 * @param string $text
1459 private static function storeMentions(int $uriid, string $text)
1461 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1462 if (empty($matches)) {
1467 * Matching values for the preg match
1468 * [1] = mention type (@ or !)
1469 * [2] = name (optional)
1473 foreach ($matches as $match) {
1474 if (empty($match)) {
1479 $contact = DI::dsprContact()->getByUrl(new Uri($match[3]));
1480 Tag::storeByHash($uriid, $match[1], $contact->name ?: $contact->nick, $contact->url);
1481 } catch (\Throwable $e) {
1487 * Processes an incoming comment
1489 * @param array $importer Array of the importer user
1490 * @param WebFingerUri $sender The sender of the message
1491 * @param SimpleXMLElement $data The message object
1492 * @param string $xml The original XML of the message
1493 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1495 * @return bool The message id of the generated comment or "false" if there was an error
1496 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1497 * @throws \ImagickException
1499 private static function receiveComment(array $importer, WebFingerUri $sender, SimpleXMLElement $data, string $xml, int $direction): bool
1501 $author = WebFingerUri::fromString(XML::unescape($data->author));
1502 $guid = XML::unescape($data->guid);
1503 $parent_guid = XML::unescape($data->parent_guid);
1504 $text = XML::unescape($data->text);
1506 if (isset($data->created_at)) {
1507 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1509 $created_at = DateTimeFormat::utcNow();
1512 if (isset($data->thread_parent_guid)) {
1513 $thread_parent_guid = XML::unescape($data->thread_parent_guid);
1514 $thr_parent = self::getUriFromGuid($thread_parent_guid);
1519 $contact = self::allowedContactByHandle($importer, $sender, true);
1524 if (!empty($contact['gsid'])) {
1525 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1528 $message_id = self::messageExists($importer['uid'], $guid);
1533 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1534 if (!$toplevel_parent_item) {
1539 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
1540 } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) {
1541 Logger::notice('Unable to find author details', ['author' => $author->getAddr()]);
1545 // Fetch the contact id - if we know this contact
1546 $author_contact = self::authorContactByUrl($contact, $author_url, $importer['uid']);
1550 $datarray['uid'] = $importer['uid'];
1551 $datarray['contact-id'] = $author_contact['cid'];
1552 $datarray['network'] = $author_contact['network'];
1554 $datarray['author-link'] = $author_url;
1555 $datarray['author-id'] = Contact::getIdForURL($author_url);
1557 $datarray['owner-link'] = $contact['url'];
1558 $datarray['owner-id'] = Contact::getIdForURL($contact['url']);
1560 // Will be overwritten for sharing accounts in Item::insert
1561 $datarray = self::setDirection($datarray, $direction);
1563 $datarray['guid'] = $guid;
1564 $datarray['uri'] = self::getUriFromGuid($guid, $author);
1565 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1567 $datarray['verb'] = Activity::POST;
1568 $datarray['gravity'] = Item::GRAVITY_COMMENT;
1570 $datarray['thr-parent'] = $thr_parent ?: $toplevel_parent_item['uri'];
1572 $datarray['object-type'] = Activity\ObjectType::COMMENT;
1573 $datarray['post-type'] = Item::PT_NOTE;
1575 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1576 $datarray['source'] = $xml;
1578 $datarray = self::setDirection($datarray, $direction);
1580 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
1582 $datarray['plink'] = self::plink($author, $guid, $toplevel_parent_item['guid']);
1583 $body = Markdown::toBBCode($text);
1585 $datarray['body'] = self::replacePeopleGuid($body, $author_url);
1587 self::storeMentions($datarray['uri-id'], $text);
1588 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
1590 self::fetchGuid($datarray);
1592 // If we are the origin of the parent we store the original data.
1593 // We notify our followers during the item storage.
1594 if ($toplevel_parent_item['origin']) {
1595 $datarray['diaspora_signed_text'] = json_encode($data);
1598 if (Item::isTooOld($datarray)) {
1599 Logger::info('Comment is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1603 $message_id = Item::insert($datarray);
1605 if ($message_id <= 0) {
1610 Logger::info('Stored comment ' . $datarray['guid'] . ' with message id ' . $message_id);
1611 if ($datarray['uid'] == 0) {
1612 Item::distribute($message_id, json_encode($data));
1620 * processes and stores private messages
1622 * @param array $importer Array of the importer user
1623 * @param array $contact The contact of the message
1624 * @param SimpleXMLElement $data The message object
1625 * @param array $msg Array of the processed message, author handle and key
1626 * @param object $mesg The private message
1627 * @param array $conversation The conversation record to which this message belongs
1629 * @return bool "true" if it was successful
1630 * @throws \Exception
1631 * @todo Find type-hint for $mesg and update documentation
1633 private static function receiveConversationMessage(array $importer, array $contact, SimpleXMLElement $data, array $msg, $mesg, array $conversation): bool
1635 $author_handle = XML::unescape($data->author);
1636 $guid = XML::unescape($data->guid);
1637 $subject = XML::unescape($data->subject);
1639 // "diaspora_handle" is the element name from the old version
1640 // "author" is the element name from the new version
1641 if ($mesg->author) {
1642 $msg_author_handle = XML::unescape($mesg->author);
1643 } elseif ($mesg->diaspora_handle) {
1644 $msg_author_handle = XML::unescape($mesg->diaspora_handle);
1650 $msg_author_uri = WebFingerUri::fromString($msg_author_handle);
1651 } catch (\InvalidArgumentException $e) {
1655 $msg_guid = XML::unescape($mesg->guid);
1656 $msg_conversation_guid = XML::unescape($mesg->conversation_guid);
1657 $msg_text = XML::unescape($mesg->text);
1658 $msg_created_at = DateTimeFormat::utc(XML::unescape($mesg->created_at));
1660 if ($msg_conversation_guid != $guid) {
1661 Logger::notice('Message conversation guid does not belong to the current conversation.', ['guid' => $guid]);
1665 $msg_author = DI::dsprContact()->getByAddr($msg_author_uri);
1667 return Mail::insert([
1668 'uid' => $importer['uid'],
1669 'guid' => $msg_guid,
1670 'convid' => $conversation['id'],
1671 'from-name' => $msg_author->name,
1672 'from-photo' => (string)$msg_author->photo,
1673 'from-url' => (string)$msg_author->url,
1674 'contact-id' => $contact['id'],
1675 'title' => $subject,
1676 'body' => Markdown::toBBCode($msg_text),
1677 'uri' => $msg_author_handle . ':' . $msg_guid,
1678 'parent-uri' => $author_handle . ':' . $guid,
1679 'created' => $msg_created_at
1684 * Processes new private messages (answers to private messages are processed elsewhere)
1686 * @param array $importer Array of the importer user
1687 * @param array $msg Array of the processed message, author handle and key
1688 * @param SimpleXMLElement $data The message object
1690 * @return bool Success
1691 * @throws \Exception
1693 private static function receiveConversation(array $importer, array $msg, SimpleXMLElement $data)
1695 $author_handle = XML::unescape($data->author);
1696 $guid = XML::unescape($data->guid);
1697 $subject = XML::unescape($data->subject);
1698 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1699 $participants = XML::unescape($data->participants);
1701 $messages = $data->message;
1703 if (!count($messages)) {
1704 Logger::notice('Empty conversation');
1708 $contact = self::allowedContactByHandle($importer, WebFingerUri::fromString($msg['author']), true);
1713 if (!empty($contact['gsid'])) {
1714 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1717 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1718 if (!DBA::isResult($conversation)) {
1719 $r = DBA::insert('conv', [
1720 'uid' => $importer['uid'],
1722 'creator' => $author_handle,
1723 'created' => $created_at,
1724 'updated' => DateTimeFormat::utcNow(),
1725 'subject' => $subject,
1726 'recips' => $participants
1730 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1733 if (!$conversation) {
1734 Logger::warning('Unable to create conversation.');
1738 foreach ($messages as $mesg) {
1739 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1746 * Processes "like" messages
1748 * @param array $importer Array of the importer user
1749 * @param WebFingerUri $sender The sender of the message
1750 * @param SimpleXMLElement $data The message object
1751 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1753 * @return bool Success or failure
1754 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1755 * @throws \ImagickException
1757 private static function receiveLike(array $importer, WebFingerUri $sender, SimpleXMLElement $data, int $direction): bool
1759 $author = WebFingerUri::fromString(XML::unescape($data->author));
1760 $guid = XML::unescape($data->guid);
1761 $parent_guid = XML::unescape($data->parent_guid);
1762 $parent_type = XML::unescape($data->parent_type);
1763 $positive = XML::unescape($data->positive);
1765 // likes on comments aren't supported by Diaspora - only on posts
1766 // But maybe this will be supported in the future, so we will accept it.
1767 if (!in_array($parent_type, ['Post', 'Comment'])) {
1771 $contact = self::allowedContactByHandle($importer, $sender, true);
1776 if (!empty($contact['gsid'])) {
1777 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1780 $message_id = self::messageExists($importer['uid'], $guid);
1785 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1786 if (!$toplevel_parent_item) {
1791 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
1792 } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) {
1793 Logger::notice('Unable to find author details', ['author' => $author->getAddr()]);
1797 // Fetch the contact id - if we know this contact
1798 $author_contact = self::authorContactByUrl($contact, $author_url, $importer['uid']);
1800 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1801 // We would accept this anyhow.
1802 if ($positive == 'true') {
1803 $verb = Activity::LIKE;
1805 $verb = Activity::DISLIKE;
1810 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1812 $datarray['uid'] = $importer['uid'];
1813 $datarray['contact-id'] = $author_contact['cid'];
1814 $datarray['network'] = $author_contact['network'];
1816 $datarray = self::setDirection($datarray, $direction);
1818 $datarray['owner-link'] = $datarray['author-link'] = $author_url;
1819 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($author_url);
1821 $datarray['guid'] = $guid;
1822 $datarray['uri'] = self::getUriFromGuid($guid, $author);
1824 $datarray['verb'] = $verb;
1825 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
1826 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1828 $datarray['object-type'] = Activity\ObjectType::NOTE;
1830 $datarray['body'] = $verb;
1832 // Diaspora doesn't provide a date for likes
1833 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
1835 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1836 if ($toplevel_parent_item['gravity'] != Item::GRAVITY_PARENT) {
1837 $toplevel = Post::selectFirst(['origin'], ['id' => $toplevel_parent_item['parent']]);
1838 $origin = $toplevel['origin'];
1840 $origin = $toplevel_parent_item['origin'];
1843 // If we are the origin of the parent we store the original data.
1844 // We notify our followers during the item storage.
1846 $datarray['diaspora_signed_text'] = json_encode($data);
1849 if (Item::isTooOld($datarray)) {
1850 Logger::info('Like is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1854 $message_id = Item::insert($datarray);
1856 if ($message_id <= 0) {
1861 Logger::info('Stored like ' . $datarray['guid'] . ' with message id ' . $message_id);
1862 if ($datarray['uid'] == 0) {
1863 Item::distribute($message_id, json_encode($data));
1871 * Processes private messages
1873 * @param array $importer Array of the importer user
1874 * @param SimpleXMLElement $data The message object
1876 * @return bool Success?
1877 * @throws \Exception
1879 private static function receiveMessage(array $importer, SimpleXMLElement $data): bool
1881 $author_uri = WebFingerUri::fromString(XML::unescape($data->author));
1882 $guid = XML::unescape($data->guid);
1883 $conversation_guid = XML::unescape($data->conversation_guid);
1884 $text = XML::unescape($data->text);
1885 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1887 $contact = self::allowedContactByHandle($importer, $author_uri, true);
1892 if (!empty($contact['gsid'])) {
1893 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1896 $condition = ['uid' => $importer['uid'], 'guid' => $conversation_guid];
1897 $conversation = DBA::selectFirst('conv', [], $condition);
1898 if (!DBA::isResult($conversation)) {
1899 Logger::notice('Conversation not available.');
1904 $author = DI::dsprContact()->getByAddr($author_uri);
1905 } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) {
1906 Logger::notice('Unable to find author details', ['author' => $author_uri->getAddr()]);
1910 $body = Markdown::toBBCode($text);
1912 $body = self::replacePeopleGuid($body, $author->url);
1914 return Mail::insert([
1915 'uid' => $importer['uid'],
1917 'convid' => $conversation['id'],
1918 'from-name' => $author->name,
1919 'from-photo' => (string)$author->photo,
1920 'from-url' => (string)$author->url,
1921 'contact-id' => $contact['id'],
1922 'title' => $conversation['subject'],
1925 'uri' => $author_uri . ':' . $guid,
1926 'parent-uri' => $author_uri . ':' . $conversation['guid'],
1927 'created' => $created_at
1932 * Processes participations - unsupported by now
1934 * @param array $importer Array of the importer user
1935 * @param SimpleXMLElement $data The message object
1936 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1938 * @return bool success
1939 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1940 * @throws \ImagickException
1942 private static function receiveParticipation(array $importer, SimpleXMLElement $data, int $direction): bool
1944 $author = WebFingerUri::fromString(strtolower(XML::unescape($data->author)));
1945 $guid = XML::unescape($data->guid);
1946 $parent_guid = XML::unescape($data->parent_guid);
1948 $contact = self::allowedContactByHandle($importer, $author, true);
1953 if (!empty($contact['gsid'])) {
1954 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1957 if (self::messageExists($importer['uid'], $guid)) {
1961 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1962 if (!$toplevel_parent_item) {
1966 if (!$toplevel_parent_item['origin']) {
1967 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1970 if (!in_array($toplevel_parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
1971 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1976 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
1977 } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) {
1978 Logger::notice('unable to find author details', ['author' => $author->getAddr()]);
1982 $author_contact = self::authorContactByUrl($contact, $author_url, $importer['uid']);
1984 // Store participation
1987 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1989 $datarray['uid'] = $importer['uid'];
1990 $datarray['contact-id'] = $author_contact['cid'];
1991 $datarray['network'] = $author_contact['network'];
1993 $datarray = self::setDirection($datarray, $direction);
1995 $datarray['owner-link'] = $datarray['author-link'] = $author_url;
1996 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($author_url);
1998 $datarray['guid'] = $guid;
1999 $datarray['uri'] = self::getUriFromGuid($guid, $author);
2001 $datarray['verb'] = Activity::FOLLOW;
2002 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
2003 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
2005 $datarray['object-type'] = Activity\ObjectType::NOTE;
2007 $datarray['body'] = Activity::FOLLOW;
2009 // Diaspora doesn't provide a date for a participation
2010 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
2012 if (Item::isTooOld($datarray)) {
2013 Logger::info('Participation is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2017 $message_id = Item::insert($datarray);
2019 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
2021 // Send all existing comments and likes to the requesting server
2022 $comments = Post::select(
2023 ['id', 'uri-id', 'parent-author-network', 'author-network', 'verb', 'gravity'],
2024 ['parent' => $toplevel_parent_item['id'], 'gravity' => [Item::GRAVITY_COMMENT, Item::GRAVITY_ACTIVITY]]
2026 while ($comment = Post::fetch($comments)) {
2027 if (($comment['gravity'] == Item::GRAVITY_ACTIVITY) && !in_array($comment['verb'], [Activity::LIKE, Activity::DISLIKE])) {
2028 Logger::info('Unsupported activities are not relayed', ['item' => $comment['id'], 'verb' => $comment['verb']]);
2032 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
2033 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2037 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
2038 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2042 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact['cid']]);
2043 if (Worker::add(Worker::PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['uri-id'], $author_contact['cid'], $datarray['uid'])) {
2044 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2047 DBA::close($comments);
2053 * Processes photos - unneeded
2055 * @param array $importer Array of the importer user
2056 * @param SimpleXMLElement $data The message object
2058 * @return bool always true
2060 private static function receivePhoto(array $importer, $data)
2062 // There doesn't seem to be a reason for this function,
2063 // since the photo data is transmitted in the status message as well
2068 * Processes poll participations - unsupported
2070 * @param array $importer Array of the importer user
2071 * @param object $data The message object
2073 * @return bool always true
2075 private static function receivePollParticipation(array $importer, $data)
2077 // We don't support polls by now
2082 * Processes incoming profile updates
2084 * @param array $importer Array of the importer user
2085 * @param SimpleXMLElement $data The message object
2087 * @return bool Success
2088 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2089 * @throws \ImagickException
2091 private static function receiveProfile(array $importer, SimpleXMLElement $data): bool
2093 $author = WebFingerUri::fromString(strtolower(XML::unescape($data->author)));
2095 $contact = self::contactByHandle($importer['uid'], $author);
2100 $name = XML::unescape($data->first_name) . ((strlen($data->last_name)) ? ' ' . XML::unescape($data->last_name) : '');
2101 $image_url = XML::unescape($data->image_url);
2102 $birthday = XML::unescape($data->birthday);
2103 $about = Markdown::toBBCode(XML::unescape($data->bio));
2104 $location = Markdown::toBBCode(XML::unescape($data->location));
2105 $searchable = (XML::unescape($data->searchable) == 'true');
2106 $nsfw = (XML::unescape($data->nsfw) == 'true');
2107 $tags = XML::unescape($data->tag_string);
2109 $tags = explode('#', $tags);
2112 foreach ($tags as $tag) {
2113 $tag = trim(strtolower($tag));
2119 $keywords = implode(', ', $keywords);
2122 $name = $author->getUser();
2125 if (preg_match('|^https?://|', $image_url) === 0) {
2126 // @TODO No HTTPS here?
2127 $image_url = 'http://' . $author->getFullHost() . $image_url;
2130 Contact::updateAvatar($contact['id'], $image_url);
2132 // Generic birthday. We don't know the timezone. The year is irrelevant.
2134 $birthday = str_replace('1000', '1901', $birthday);
2136 if ($birthday != '') {
2137 $birthday = DateTimeFormat::utc($birthday, 'Y-m-d');
2140 // this is to prevent multiple birthday notifications in a single year
2141 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2143 if (substr($birthday, 5) === substr($contact['bd'], 5)) {
2144 $birthday = $contact['bd'];
2148 'name' => $name, 'location' => $location,
2149 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2150 'addr' => $author->getAddr(), 'nick' => $author->getUser(), 'keywords' => $keywords,
2151 'unsearchable' => !$searchable, 'sensitive' => $nsfw
2154 if (!empty($birthday)) {
2155 $fields['bd'] = $birthday;
2158 Contact::update($fields, ['id' => $contact['id']]);
2160 Logger::info('Profile of contact ' . $contact['id'] . ' stored for user ' . $importer['uid']);
2166 * Processes incoming friend requests
2168 * @param array $importer Array of the importer user
2169 * @param array $contact The contact that send the request
2171 * @throws \Exception
2173 private static function receiveRequestMakeFriend(array $importer, array $contact)
2175 if ($contact['rel'] == Contact::SHARING) {
2177 ['rel' => Contact::FRIEND, 'writable' => true],
2178 ['id' => $contact['id'], 'uid' => $importer['uid']]
2184 * Processes incoming sharing notification
2186 * @param array $importer Array of the importer user
2187 * @param SimpleXMLElement $data The message object
2189 * @return bool Success
2190 * @throws \Exception
2192 private static function receiveContactRequest(array $importer, SimpleXMLElement $data): bool
2194 $author_handle = XML::unescape($data->author);
2195 $recipient = XML::unescape($data->recipient);
2197 if (!$author_handle || !$recipient) {
2201 $author = WebFingerUri::fromString($author_handle);
2203 // the current protocol version doesn't know these fields
2204 // That means that we will assume their existence
2205 if (isset($data->following)) {
2206 $following = (XML::unescape($data->following) == 'true');
2211 if (isset($data->sharing)) {
2212 $sharing = (XML::unescape($data->sharing) == 'true');
2217 $contact = self::contactByHandle($importer['uid'], $author);
2219 // perhaps we were already sharing with this person. Now they're sharing with us.
2220 // That makes us friends.
2223 Logger::info('Author ' . $author . ' (Contact ' . $contact['id'] . ') wants to follow us.');
2224 self::receiveRequestMakeFriend($importer, $contact);
2226 // refetch the contact array
2227 $contact = self::contactByHandle($importer['uid'], $author);
2229 // If we are now friends, we are sending a share message.
2230 // Normally we needn't to do so, but the first message could have been vanished.
2231 if (in_array($contact['rel'], [Contact::FRIEND])) {
2232 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2233 if (DBA::isResult($user)) {
2234 Logger::info('Sending share message to author ' . $author . ' - Contact: ' . $contact['id'] . ' - User: ' . $importer['uid']);
2235 self::sendShare($user, $contact);
2240 Logger::info("Author " . $author . " doesn't want to follow us anymore.");
2241 Contact::removeFollower($contact);
2246 if (!$following && $sharing && in_array($importer['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2247 Logger::info("Author " . $author . " wants to share with us - but doesn't want to listen. Request is ignored.");
2249 } elseif (!$following && !$sharing) {
2250 Logger::info("Author " . $author . " doesn't want anything - and we don't know the author. Request is ignored.");
2252 } elseif (!$following && $sharing) {
2253 Logger::info("Author " . $author . " wants to share with us.");
2254 } elseif ($following && $sharing) {
2255 Logger::info("Author " . $author . " wants to have a bidirectional connection.");
2256 } elseif ($following && !$sharing) {
2257 Logger::info("Author " . $author . " wants to listen to us.");
2261 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
2262 } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) {
2263 Logger::notice('Cannot resolve diaspora handle for recipient', ['author' => $author->getAddr(), 'recipient' => $recipient]);
2267 $cid = Contact::getIdForURL($author_url, $importer['uid']);
2269 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2275 'author-id' => Contact::getIdForURL($author_url),
2276 'author-link' => $author_url
2279 $result = Contact::addRelationship($importer, $contact, $item, false);
2280 if ($result === true) {
2281 $contact_record = self::contactByHandle($importer['uid'], $author);
2282 if (!$contact_record) {
2283 Logger::info('unable to locate newly created contact record.');
2287 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2288 if (DBA::isResult($user)) {
2289 self::sendShare($user, $contact_record);
2291 // Send the profile data, maybe it weren't transmitted before
2292 self::sendProfile($importer['uid'], [$contact_record]);
2300 * Processes a reshare message
2302 * @param array $importer Array of the importer user
2303 * @param SimpleXMLElement $data The message object
2304 * @param string $xml The original XML of the message
2305 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2307 * @return bool Success or failure
2308 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2309 * @throws \ImagickException
2311 private static function receiveReshare(array $importer, SimpleXMLElement $data, string $xml, int $direction): bool
2313 $author = WebFingerUri::fromString(XML::unescape($data->author));
2314 $guid = XML::unescape($data->guid);
2315 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2317 $root_author = WebFingerUri::fromString(XML::unescape($data->root_author));
2318 } catch (\InvalidArgumentException $e) {
2322 $root_guid = XML::unescape($data->root_guid);
2323 /// @todo handle unprocessed property "provider_display_name"
2324 $public = XML::unescape($data->public);
2326 $contact = self::allowedContactByHandle($importer, $author);
2331 if (!empty($contact['gsid'])) {
2332 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2335 $message_id = self::messageExists($importer['uid'], $guid);
2341 $original_person = DI::dsprContact()->getByAddr($root_author);
2342 } catch (HTTPException\NotFoundException $e) {
2348 $datarray['uid'] = $importer['uid'];
2349 $datarray['contact-id'] = $contact['id'];
2350 $datarray['network'] = Protocol::DIASPORA;
2352 $datarray['author-link'] = $contact['url'];
2353 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2355 $datarray['owner-link'] = $datarray['author-link'];
2356 $datarray['owner-id'] = $datarray['author-id'];
2358 $datarray['guid'] = $guid;
2359 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($guid, $author);
2360 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2362 $datarray['verb'] = Activity::POST;
2363 $datarray['gravity'] = Item::GRAVITY_PARENT;
2365 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2366 $datarray['source'] = $xml;
2368 $datarray = self::setDirection($datarray, $direction);
2370 $datarray['quote-uri-id'] = self::getQuoteUriId($root_guid, $importer['uid'], $original_person->url);
2371 if (empty($datarray['quote-uri-id'])) {
2375 $datarray['body'] = '';
2376 $datarray['plink'] = self::plink($author, $guid);
2377 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2378 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2380 self::fetchGuid($datarray);
2382 if (Item::isTooOld($datarray)) {
2383 Logger::info('Reshare is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2387 $message_id = Item::insert($datarray);
2389 self::sendParticipation($contact, $datarray);
2392 Logger::info('Stored reshare ' . $datarray['guid'] . ' with message id ' . $message_id);
2393 if ($datarray['uid'] == 0) {
2394 Item::distribute($message_id);
2402 private static function getQuoteUriId(string $guid, int $uid, string $host): int
2404 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2406 if (!DBA::isResult($shared_item) && !empty($host) && Diaspora::storeByGuid($guid, $host, true)) {
2407 Logger::debug('Fetched post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2408 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2409 } elseif (DBA::isResult($shared_item)) {
2410 Logger::debug('Found existing post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2413 if (!DBA::isResult($shared_item)) {
2414 Logger::notice('Post does not exist.', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2418 return $shared_item['uri-id'];
2422 * Processes retractions
2424 * @param array $importer Array of the importer user
2425 * @param array $contact The contact of the item owner
2426 * @param SimpleXMLElement $data The message object
2428 * @return bool success
2429 * @throws \Exception
2431 private static function itemRetraction(array $importer, array $contact, SimpleXMLElement $data): bool
2433 $author_uri = WebFingerUri::fromString(XML::unescape($data->author));
2434 $target_guid = XML::unescape($data->target_guid);
2435 $target_type = XML::unescape($data->target_type);
2438 $author = DI::dsprContact()->getByAddr($author_uri);
2439 } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) {
2440 Logger::notice('Unable to find details for author', ['author' => $author_uri->getAddr()]);
2444 $contact_url = $contact['url'] ?? '' ?: (string)$author->url;
2446 // Fetch items that are about to be deleted
2447 $fields = ['uid', 'id', 'parent', 'author-link', 'uri-id'];
2449 // When we receive a public retraction, we delete every item that we find.
2450 if ($importer['uid'] == 0) {
2451 $condition = ['guid' => $target_guid, 'deleted' => false];
2453 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2456 $r = Post::select($fields, $condition);
2457 if (!DBA::isResult($r)) {
2458 Logger::notice('Target guid ' . $target_guid . ' was not found on this system for user ' . $importer['uid'] . '.');
2462 while ($item = Post::fetch($r)) {
2463 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2464 Logger::info("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.");
2468 // Fetch the parent item
2469 $parent = Post::selectFirst(['author-link'], ['id' => $item['parent']]);
2471 // Only delete it if the parent author really fits
2472 if (!Strings::compareLink($parent['author-link'], $contact_url) && !Strings::compareLink($item['author-link'], $contact_url)) {
2473 Logger::info("Thread author " . $parent['author-link'] . " and item author " . $item['author-link'] . " don't fit to expected contact " . $contact_url);
2477 Item::markForDeletion(['id' => $item['id']]);
2479 Logger::info('Deleted target ' . $target_guid . ' (' . $item['id'] . ') from user ' . $item['uid'] . ' parent: ' . $item['parent']);
2487 * Receives retraction messages
2489 * @param array $importer Array of the importer user
2490 * @param WebFingerUri $sender The sender of the message
2491 * @param SimpleXMLElement $data The message object
2493 * @return bool Success
2494 * @throws \Exception
2496 private static function receiveRetraction(array $importer, WebFingerUri $sender, SimpleXMLElement $data)
2498 $target_type = XML::unescape($data->target_type);
2500 $contact = self::contactByHandle($importer['uid'], $sender);
2501 if (!$contact && (in_array($target_type, ['Contact', 'Person']))) {
2502 Logger::notice('Cannot find contact for sender: ' . $sender . ' and user ' . $importer['uid']);
2510 Logger::info('Got retraction for ' . $target_type . ', sender ' . $sender . ' and user ' . $importer['uid']);
2512 switch ($target_type) {
2517 case 'StatusMessage':
2518 return self::itemRetraction($importer, $contact, $data);
2520 case 'PollParticipation':
2522 // Currently unsupported
2526 Logger::notice('Unknown target type ' . $target_type);
2533 * Checks if an incoming message is wanted
2535 * @param array $item
2536 * @param string $author
2537 * @param string $body
2538 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2540 * @return boolean Is the message wanted?
2542 private static function isSolicitedMessage(array $item, string $author, string $body, int $direction): bool
2544 $contact = Contact::getByURL($author);
2545 if (DBA::exists('contact', ['`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)', $contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) {
2546 Logger::debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2550 if ($direction == self::FORCED_FETCH) {
2551 Logger::debug('Post is a forced fetch - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2555 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
2556 if (Relay::isSolicitedPost($tags, $body, $contact['id'], $item['uri'], Protocol::DIASPORA)) {
2557 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2565 * Store an attached photo in the post-media table
2568 * @param object $photo
2572 private static function storePhotoAsMedia(int $uriid, $photo)
2574 // @TODO Need to find object type, roland@f.haeder.net
2575 Logger::debug('photo=' . get_class($photo));
2578 'type' => Post\Media::IMAGE,
2579 'url' => XML::unescape($photo->remote_photo_path) . XML::unescape($photo->remote_photo_name),
2580 'height' => (int)XML::unescape($photo->height ?? 0),
2581 'width' => (int)XML::unescape($photo->width ?? 0),
2582 'description' => XML::unescape($photo->text ?? ''),
2585 Post\Media::insert($data);
2589 * Set direction and post reason
2591 * @param array $datarray
2592 * @param integer $direction
2596 public static function setDirection(array $datarray, int $direction): array
2598 $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
2600 if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
2601 $datarray['post-reason'] = Item::PR_FETCHED;
2602 } elseif ($datarray['uid'] == 0) {
2603 $datarray['post-reason'] = Item::PR_GLOBAL;
2605 $datarray['post-reason'] = Item::PR_PUSHED;
2612 * Receives status messages
2614 * @param array $importer Array of the importer user
2615 * @param SimpleXMLElement $data The message object
2616 * @param string $xml The original XML of the message
2617 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2619 * @return int|bool The message id of the newly created item or false on error
2620 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2621 * @throws \ImagickException
2623 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, string $xml, int $direction)
2625 $author = WebFingerUri::fromString(XML::unescape($data->author));
2626 $guid = XML::unescape($data->guid);
2627 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2628 $public = XML::unescape($data->public);
2629 $text = XML::unescape($data->text);
2630 $provider_display_name = XML::unescape($data->provider_display_name);
2632 $contact = self::allowedContactByHandle($importer, $author);
2637 if (!empty($contact['gsid'])) {
2638 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2641 $message_id = self::messageExists($importer['uid'], $guid);
2647 if ($data->location) {
2648 foreach ($data->location->children() as $fieldname => $data) {
2649 $address[$fieldname] = XML::unescape($data);
2653 $raw_body = $body = Markdown::toBBCode($text);
2657 'plink' => self::plink($author, $guid),
2658 'uid' => $importer['uid'],
2659 'contact-id' => $contact['id'],
2660 'network' => Protocol::DIASPORA,
2661 'author-link' => $contact['url'],
2662 'author-id' => Contact::getIdForURL($contact['url'], 0),
2663 'verb' => Activity::POST,
2664 'gravity' => Item::GRAVITY_PARENT,
2665 'protocol' => Conversation::PARCEL_DIASPORA,
2667 'body' => self::replacePeopleGuid($body, $contact['url']),
2668 'raw-body' => self::replacePeopleGuid($raw_body, $contact['url']),
2669 'private' => (($public == 'false') ? Item::PRIVATE : Item::PUBLIC),
2670 // Default is note (aka. comment), later below is being checked the real type
2671 'object-type' => Activity\ObjectType::NOTE,
2672 'post-type' => Item::PT_NOTE,
2675 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($guid, $author);
2676 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2677 $datarray['owner-link'] = $datarray['author-link'];
2678 $datarray['owner-id'] = $datarray['author-id'];
2680 $datarray = self::setDirection($datarray, $direction);
2682 // Attach embedded pictures to the body
2684 foreach ($data->photo as $photo) {
2685 self::storePhotoAsMedia($datarray['uri-id'], $photo);
2688 $datarray['object-type'] = Activity\ObjectType::IMAGE;
2689 $datarray['post-type'] = Item::PT_IMAGE;
2690 } elseif ($data->poll) {
2691 $datarray['post-type'] = Item::PT_POLL;
2694 /// @todo enable support for polls
2695 //if ($data->poll) {
2696 // foreach ($data->poll as $poll)
2701 /// @todo enable support for events
2703 self::storeMentions($datarray['uri-id'], $text);
2704 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
2706 if (!self::isSolicitedMessage($datarray, $author, $body, $direction)) {
2707 DBA::delete('item-uri', ['uri' => $datarray['uri']]);
2711 if ($provider_display_name != '') {
2712 $datarray['app'] = $provider_display_name;
2715 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2717 if (isset($address['address'])) {
2718 $datarray['location'] = $address['address'];
2721 if (isset($address['lat']) && isset($address['lng'])) {
2722 $datarray['coord'] = $address['lat'] . ' ' . $address['lng'];
2725 self::fetchGuid($datarray);
2727 if (Item::isTooOld($datarray)) {
2728 Logger::info('Status is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2732 $message_id = Item::insert($datarray);
2734 self::sendParticipation($contact, $datarray);
2737 Logger::info('Stored item ' . $datarray['guid'] . ' with message id ' . $message_id);
2738 if ($datarray['uid'] == 0) {
2739 Item::distribute($message_id);
2747 /* ************************************************************************************** *
2748 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2749 * ************************************************************************************** */
2752 * returns the handle of a contact
2754 * @param array $contact contact array
2756 * @return string the handle in the format user@domain.tld
2757 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2759 private static function myHandle(array $contact): string
2761 if (!empty($contact['addr'])) {
2762 return $contact['addr'];
2765 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2766 // So - just in case - we build the address here.
2767 if ($contact['nickname'] != '') {
2768 $nick = $contact['nickname'];
2770 $nick = $contact['nick'];
2773 return $nick . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
2778 * Creates the data for a private message in the new format
2780 * @param string $msg The message that is to be transmitted
2781 * @param array $user The record of the sender
2782 * @param array $contact Target of the communication
2783 * @param string $prvkey The private key of the sender
2784 * @param string $pubkey The public key of the receiver
2786 * @return string The encrypted data
2787 * @throws \Exception
2789 public static function encodePrivateData(string $msg, array $user, array $contact, string $prvkey, string $pubkey): string
2791 Logger::debug('Message: ' . $msg);
2793 // without a public key nothing will work
2795 Logger::notice('pubkey missing: contact id: ' . $contact['id']);
2799 $aes_key = random_bytes(32);
2800 $b_aes_key = base64_encode($aes_key);
2801 $iv = random_bytes(16);
2802 $b_iv = base64_encode($iv);
2804 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2806 $json = json_encode(['iv' => $b_iv, 'key' => $b_aes_key]);
2808 $encrypted_key_bundle = '';
2809 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
2813 $json_object = json_encode(
2815 'aes_key' => base64_encode($encrypted_key_bundle),
2816 'encrypted_magic_envelope' => base64_encode($ciphertext)
2820 return $json_object;
2824 * Creates the envelope for the "fetch" endpoint and for the new format
2826 * @param string $msg The message that is to be transmitted
2827 * @param array $user The record of the sender
2829 * @return string The envelope
2830 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2832 public static function buildMagicEnvelope(string $msg, array $user): string
2834 $b64url_data = Strings::base64UrlEncode($msg);
2835 $data = str_replace(["\n", "\r", ' ', "\t"], ['', '', '', ''], $b64url_data);
2837 $key_id = Strings::base64UrlEncode(self::myHandle($user));
2838 $type = 'application/xml';
2839 $encoding = 'base64url';
2840 $alg = 'RSA-SHA256';
2841 $signable_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
2843 // Fallback if the private key wasn't transmitted in the expected field
2844 if ($user['uprvkey'] == '') {
2845 $user['uprvkey'] = $user['prvkey'];
2848 $signature = Crypto::rsaSign($signable_data, $user['uprvkey']);
2849 $sig = Strings::base64UrlEncode($signature);
2854 '@attributes' => ['type' => $type],
2855 'me:encoding' => $encoding,
2858 '@attributes2' => ['key_id' => $key_id]
2862 $namespaces = ['me' => ActivityNamespace::SALMON_ME];
2864 return XML::fromArray($xmldata, $dummy, false, $namespaces);
2868 * Create the envelope for a message
2870 * @param string $msg The message that is to be transmitted
2871 * @param array $user The record of the sender
2872 * @param array $contact Target of the communication
2873 * @param string $prvkey The private key of the sender
2874 * @param string $pubkey The public key of the receiver
2875 * @param bool $public Is the message public?
2877 * @return string The message that will be transmitted to other servers
2878 * @throws \Exception
2880 public static function buildMessage(string $msg, array $user, array $contact, string $prvkey, string $pubkey, bool $public = false): string
2882 // The message is put into an envelope with the sender's signature
2883 $envelope = self::buildMagicEnvelope($msg, $user);
2885 // Private messages are put into a second envelope, encrypted with the receivers public key
2887 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
2894 * Creates a signature for a message
2896 * @param array $owner the array of the owner of the message
2897 * @param array $message The message that is to be signed
2899 * @return string The signature
2901 private static function signature(array $owner, array $message): string
2904 unset($sigmsg['author_signature']);
2905 unset($sigmsg['parent_author_signature']);
2907 $signed_text = implode(';', $sigmsg);
2909 return base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
2913 * Transmit a message to a target server
2915 * @param array $owner the array of the item owner
2916 * @param array $contact Target of the communication
2917 * @param string $envelope The message that is to be transmitted
2918 * @param bool $public_batch Is it a public post?
2919 * @param string $guid message guid
2921 * @return int Result of the transmission
2922 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2923 * @throws \ImagickException
2925 private static function transmit(array $owner, array $contact, string $envelope, bool $public_batch, string $guid = ''): int
2927 $enabled = intval(DI::config()->get('system', 'diaspora_enabled'));
2932 $logid = Strings::getRandomHex(4);
2934 // We always try to use the data from the diaspora-contact table.
2935 // This is important for transmitting data to Friendica servers.
2937 $target = DI::dsprContact()->getByAddr(WebFingerUri::fromString($contact['addr']));
2938 $dest_url = $public_batch ? $target->batch : $target->notify;
2939 } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) {
2942 if (empty($dest_url)) {
2943 $dest_url = ($public_batch ? $contact['batch'] : $contact['notify']);
2947 Logger::notice('No URL for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2951 Logger::info('transmit: ' . $logid . '-' . $guid . ' ' . $dest_url);
2953 if (!intval(DI::config()->get('system', 'diaspora_test'))) {
2954 $content_type = (($public_batch) ? 'application/magic-envelope+xml' : 'application/json');
2956 $postResult = DI::httpClient()->post($dest_url . '/', $envelope, ['Content-Type' => $content_type]);
2957 $return_code = $postResult->getReturnCode();
2959 Logger::notice('test_mode');
2963 if (!empty($contact['gsid']) && (empty($return_code) || $postResult->isTimeout())) {
2964 GServer::setFailureById($contact['gsid']);
2965 } elseif (!empty($contact['gsid']) && ($return_code >= 200) && ($return_code <= 299)) {
2966 GServer::setReachableById($contact['gsid'], Protocol::DIASPORA);
2969 Logger::info('transmit: ' . $logid . '-' . $guid . ' to ' . $dest_url . ' returns: ' . $return_code);
2971 return $return_code ? $return_code : -1;
2976 * Build the post xml
2978 * @param string $type The message type
2979 * @param array $message The message data
2981 * @return string The post XML
2982 * @throws \Exception
2984 public static function buildPostXml(string $type, array $message): string
2986 return XML::fromArray([$type => $message]);
2990 * Builds and transmit messages
2992 * @param array $owner the array of the item owner
2993 * @param array $contact Target of the communication
2994 * @param string $type The message type
2995 * @param array $message The message data
2996 * @param bool $public_batch Is it a public post?
2997 * @param string $guid message guid
2999 * @return int Result of the transmission
3000 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3001 * @throws \ImagickException
3003 private static function buildAndTransmit(array $owner, array $contact, string $type, array $message, bool $public_batch = false, string $guid = '')
3005 $msg = self::buildPostXml($type, $message);
3007 // Fallback if the private key wasn't transmitted in the expected field
3008 if (empty($owner['uprvkey'])) {
3009 $owner['uprvkey'] = $owner['prvkey'];
3012 // When sending content to Friendica contacts using the Diaspora protocol
3013 // we have to fetch the public key from the diaspora-contact.
3014 // This is due to the fact that legacy DFRN had unique keys for every contact.
3015 $pubkey = $contact['pubkey'];
3016 if (!empty($contact['addr'])) {
3018 $pubkey = DI::dsprContact()->getByAddr(WebFingerUri::fromString($contact['addr']))->pubKey;
3019 } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) {
3022 // The "addr" field should always be filled.
3023 // If this isn't the case, it will raise a notice some lines later.
3024 // And in the log we will see where it came from, and we can handle it there.
3025 Logger::notice('Empty addr', ['contact' => $contact ?? [], 'callstack' => System::callstack(20)]);
3028 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $pubkey ?? '', $public_batch);
3030 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3032 Logger::info('Transmitted message', ['owner' => $owner['uid'], 'target' => $contact['addr'], 'type' => $type, 'guid' => $guid, 'result' => $return_code]);
3034 return $return_code;
3038 * sends a participation (Used to get all further updates)
3040 * @param array $contact Target of the communication
3041 * @param array $item Item array
3043 * @return int The result of the transmission
3044 * @throws \Exception
3046 private static function sendParticipation(array $contact, array $item): int
3048 // Don't send notifications for private postings
3049 if ($item['private'] == Item::PRIVATE) {
3053 $cachekey = 'diaspora:sendParticipation:' . $item['guid'];
3055 $result = DI::cache()->get($cachekey);
3056 if (!is_null($result)) {
3060 // Fetch some user id to have a valid handle to transmit the participation.
3061 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3062 // If the item belongs to a user, we take this user id.
3063 if ($item['uid'] == 0) {
3064 // @todo Possibly use an administrator account?
3065 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'account-type' => User::ACCOUNT_TYPE_PERSON];
3066 $first_user = DBA::selectFirst('user', ['uid'], $condition, ['order' => ['uid']]);
3067 $owner = User::getOwnerDataById($first_user['uid']);
3069 $owner = User::getOwnerDataById($item['uid']);
3072 $author_handle = self::myHandle($owner);
3075 'author' => $author_handle,
3076 'guid' => System::createUUID(),
3077 'parent_type' => 'Post',
3078 'parent_guid' => $item['guid']
3081 Logger::info('Send participation for ' . $item['guid'] . ' by ' . $author_handle);
3083 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3084 DI::cache()->set($cachekey, $item['guid'], Duration::QUARTER_HOUR);
3086 return self::buildAndTransmit($owner, $contact, 'participation', $message);
3090 * sends an account migration
3092 * @param array $owner the array of the item owner
3093 * @param array $contact Target of the communication
3094 * @param int $uid User ID
3096 * @return int The result of the transmission
3097 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3098 * @throws \ImagickException
3100 public static function sendAccountMigration(array $owner, array $contact, int $uid): int
3102 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3103 $profile = self::createProfileData($uid);
3105 $signed_text = 'AccountMigration:' . $old_handle . ':' . $profile['author'];
3106 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
3109 'author' => $old_handle,
3110 'profile' => $profile,
3111 'signature' => $signature
3114 Logger::info('Send account migration', ['msg' => $message]);
3116 return self::buildAndTransmit($owner, $contact, 'account_migration', $message);
3120 * Sends a "share" message
3122 * @param array $owner the array of the item owner
3123 * @param array $contact Target of the communication
3125 * @return int The result of the transmission
3126 * @throws \Exception
3128 public static function sendShare(array $owner, array $contact): int
3131 * @todo support the different possible combinations of "following" and "sharing"
3132 * Currently, Diaspora only interprets the "sharing" field
3134 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3138 switch ($contact["rel"]) {
3139 case Contact::FRIEND:
3143 case Contact::SHARING:
3147 case Contact::FOLLOWER:
3154 'author' => self::myHandle($owner),
3155 'recipient' => $contact['addr'],
3156 'following' => 'true',
3160 Logger::info('Send share', ['msg' => $message]);
3162 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3166 * sends an "unshare"
3168 * @param array $owner the array of the item owner
3169 * @param array $contact Target of the communication
3171 * @return int The result of the transmission
3172 * @throws \Exception
3174 public static function sendUnshare(array $owner, array $contact): int
3177 'author' => self::myHandle($owner),
3178 'recipient' => $contact['addr'],
3179 'following' => 'false',
3180 'sharing' => 'false'
3183 Logger::info('Send unshare', ['msg' => $message]);
3185 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3189 * Fetch reshare details
3191 * @param array $item The message body that is to be check
3193 * @return array Reshare details (empty if the item is no reshare)
3194 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3195 * @throws \ImagickException
3197 public static function getReshareDetails(array $item): array
3199 $reshared = DI::contentItem()->getSharedPost($item, ['guid', 'network', 'author-addr']);
3200 if (empty($reshared)) {
3204 // Skip if it isn't a pure repeated messages or not a real reshare
3205 if (!empty($reshared['comment']) || !in_array($reshared['post']['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
3210 'root_handle' => strtolower($reshared['post']['author-addr']),
3211 'root_guid' => $reshared['post']['guid'],
3216 * Create an event array
3218 * @param integer $event_id The id of the event
3220 * @return array with event data
3221 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3223 private static function buildEvent(string $event_id): array
3225 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
3226 if (!DBA::isResult($event)) {
3232 $owner = User::getOwnerDataById($event['uid']);
3237 $eventdata['author'] = self::myHandle($owner);
3239 if ($event['guid']) {
3240 $eventdata['guid'] = $event['guid'];
3243 $mask = DateTimeFormat::ATOM;
3245 /// @todo - establish "all day" events in Friendica
3246 $eventdata['all_day'] = 'false';
3248 $eventdata['timezone'] = 'UTC';
3250 if ($event['start']) {
3251 $eventdata['start'] = DateTimeFormat::utc($event['start'], $mask);
3253 if ($event['finish'] && !$event['nofinish']) {
3254 $eventdata['end'] = DateTimeFormat::utc($event['finish'], $mask);
3256 if ($event['summary']) {
3257 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3259 if ($event['desc']) {
3260 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3262 if ($event['location']) {
3263 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3264 $coord = Map::getCoordinates($event['location']);
3267 $location['address'] = html_entity_decode(BBCode::toMarkdown($event['location']));
3268 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3269 $location['lat'] = $coord['lat'];
3270 $location['lng'] = $coord['lon'];
3272 $location['lat'] = 0;
3273 $location['lng'] = 0;
3275 $eventdata['location'] = $location;
3282 * Create a post (status message or reshare)
3284 * @param array $item The item that will be exported
3285 * @param array $owner the array of the item owner
3288 * 'type' -> Message type ("status_message" or "reshare")
3289 * 'message' -> Array of XML elements of the status
3290 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3291 * @throws \ImagickException
3293 public static function buildStatus(array $item, array $owner)
3295 $cachekey = 'diaspora:buildStatus:' . $item['guid'];
3297 $result = DI::cache()->get($cachekey);
3298 if (!is_null($result)) {
3302 $myaddr = self::myHandle($owner);
3304 $public = ($item['private'] == Item::PRIVATE ? 'false' : 'true');
3305 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3306 $edited = DateTimeFormat::utc($item['edited'] ?? $item['created'], DateTimeFormat::ATOM);
3308 // Detect a share element and do a reshare
3309 if (($item['private'] != Item::PRIVATE) && ($ret = self::getReshareDetails($item))) {
3311 'author' => $myaddr,
3312 'guid' => $item['guid'],
3313 'created_at' => $created,
3314 'root_author' => $ret['root_handle'],
3315 'root_guid' => $ret['root_guid'],
3316 'provider_display_name' => $item['app'],
3322 $native_photos = DI::config()->get('diaspora', 'native_photos');
3323 if ($native_photos) {
3324 $item['body'] = Post\Media::removeFromEndOfBody($item['body']);
3325 $attach_media = [Post\Media::AUDIO, Post\Media::VIDEO];
3327 $attach_media = [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO];
3330 $title = $item['title'];
3331 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item), $attach_media);
3332 $body = Post\Media::addHTMLLinkToBody($item['uri-id'], $body);
3334 // Fetch the title from an attached link - if there is one
3335 if (empty($item['title']) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3336 $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
3337 if (!empty($media) && !empty($media[0]['name']) && ($media[0]['name'] != $media[0]['url'])) {
3338 $title = $media[0]['name'];
3342 // convert to markdown
3343 $body = html_entity_decode(BBCode::toMarkdown($body));
3346 if (strlen($title)) {
3347 $body = '### ' . html_entity_decode($title) . "\n\n" . $body;
3350 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT]);
3351 if (!empty($attachments)) {
3352 $body .= "\n[hr]\n";
3353 foreach ($attachments as $attachment) {
3354 $body .= "[" . $attachment['description'] . "](" . $attachment['url'] . ")\n";
3360 if ($item['location'] != '')
3361 $location['address'] = $item['location'];
3363 if ($item['coord'] != '') {
3364 $coord = explode(' ', $item['coord']);
3365 $location['lat'] = $coord[0];
3366 $location['lng'] = $coord[1];
3370 'author' => $myaddr,
3371 'guid' => $item['guid'],
3372 'created_at' => $created,
3373 'edited_at' => $edited,
3374 'public' => $public,
3376 'provider_display_name' => $item['app'],
3377 'location' => $location
3380 if ($native_photos) {
3381 $message = self::addPhotos($item, $message);
3384 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3385 if (!isset($location['lat']) || !isset($location['lng'])) {
3386 unset($message['location']);
3389 if ($item['event-id'] > 0) {
3390 $event = self::buildEvent($item['event-id']);
3391 if (count($event)) {
3392 $message['event'] = $event;
3395 !empty($event['location']['address']) &&
3396 !empty($event['location']['lat']) &&
3397 !empty($event['location']['lng'])
3399 $message['location'] = $event['location'];
3402 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3403 // $message['text'] = '';
3407 $type = 'status_message';
3412 'message' => $message
3415 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3421 * Add photo elements to the message array
3423 * @param array $item
3424 * @param array $message
3427 private static function addPhotos(array $item, array $message): array
3429 $medias = Post\Media::getByURIId($item['uri-id'], [Post\Media::IMAGE]);
3430 $public = ($item['private'] == Item::PRIVATE ? 'false' : 'true');
3433 foreach ($medias as $media) {
3434 if (Item::containsLink($item['body'], $media['preview'] ?? $media['url'], $media['type'])) {
3438 $name = basename($media['url']);
3439 $path = str_replace($name, '', $media['url']);
3441 $message[++$counter . ':photo'] = [
3442 'guid' => Item::guid(['uri' => $media['url']], false),
3443 'author' => $item['author-addr'],
3444 'public' => $public,
3445 'created_at' => $item['created'],
3446 'remote_photo_path' => $path,
3447 'remote_photo_name' => $name,
3448 'status_message_guid' => $item['guid'],
3449 'height' => $media['height'],
3450 'width' => $media['width'],
3451 'text' => $media['description'],
3458 private static function prependParentAuthorMention(string $body, string $profile_url): string
3460 $profile = Contact::getByURL($profile_url, false, ['addr', 'name']);
3462 !empty($profile['addr'])
3463 && !strstr($body, $profile['addr'])
3464 && !strstr($body, $profile_url)
3466 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3475 * @param array $item The item that will be exported
3476 * @param array $owner the array of the item owner
3477 * @param array $contact Target of the communication
3478 * @param bool $public_batch Is it a public post?
3480 * @return int The result of the transmission
3481 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3482 * @throws \ImagickException
3484 public static function sendStatus(array $item, array $owner, array $contact, bool $public_batch = false): int
3486 $status = self::buildStatus($item, $owner);
3488 return self::buildAndTransmit($owner, $contact, $status['type'], $status['message'], $public_batch, $item['guid']);
3492 * Creates a "like" object
3494 * @param array $item The item that will be exported
3495 * @param array $owner the array of the item owner
3497 * @return array|bool The data for a "like" or false on error
3498 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3500 private static function constructLike(array $item, array $owner)
3502 $parent = Post::selectFirst(['guid', 'uri', 'thr-parent'], ['uri' => $item['thr-parent']]);
3503 if (!DBA::isResult($parent)) {
3507 $target_type = ($parent['uri'] === $parent['thr-parent'] ? 'Post' : 'Comment');
3509 if ($item['verb'] === Activity::LIKE) {
3511 } elseif ($item['verb'] === Activity::DISLIKE) {
3512 $positive = 'false';
3516 'author' => self::myHandle($owner),
3517 'guid' => $item['guid'],
3518 'parent_guid' => $parent['guid'],
3519 'parent_type' => $target_type,
3520 'positive' => $positive,
3521 'author_signature' => '',
3526 * Creates an "EventParticipation" object
3528 * @param array $item The item that will be exported
3529 * @param array $owner the array of the item owner
3531 * @return array|bool The data for an "EventParticipation" or false on error
3532 * @throws \Exception
3534 private static function constructAttend(array $item, array $owner)
3536 $parent = Post::selectFirst(['guid'], ['uri' => $item['thr-parent']]);
3537 if (!DBA::isResult($parent)) {
3541 switch ($item['verb']) {
3542 case Activity::ATTEND:
3543 $attend_answer = 'accepted';
3545 case Activity::ATTENDNO:
3546 $attend_answer = 'declined';
3548 case Activity::ATTENDMAYBE:
3549 $attend_answer = 'tentative';
3552 Logger::warning('Unknown verb ' . $item['verb'] . ' in item ' . $item['guid']);
3557 'author' => self::myHandle($owner),
3558 'guid' => $item['guid'],
3559 'parent_guid' => $parent['guid'],
3560 'status' => $attend_answer,
3561 'author_signature' => ''
3566 * Creates the object for a comment
3568 * @param array $item The item that will be exported
3569 * @param array $owner the array of the item owner
3571 * @return array|false The data for a comment
3572 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3574 private static function constructComment(array $item, array $owner)
3576 $cachekey = 'diaspora:constructComment:' . $item['guid'];
3578 $result = DI::cache()->get($cachekey);
3579 if (!is_null($result)) {
3583 $toplevel_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3584 if (!DBA::isResult($toplevel_item)) {
3585 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3589 $thread_parent_item = $toplevel_item;
3590 if ($item['thr-parent'] != $item['parent-uri']) {
3591 $thread_parent_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3594 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
3595 $body = Post\Media::addHTMLLinkToBody($item['uri-id'], $body);
3597 // The replied to autor mention is prepended for clarity if:
3598 // - Item replied isn't yours
3599 // - Item is public or explicit mentions are disabled
3600 // - Implicit mentions are enabled
3602 $item['author-id'] != $thread_parent_item['author-id']
3603 && ($thread_parent_item['gravity'] != Item::GRAVITY_PARENT)
3604 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3605 && !DI::config()->get('system', 'disable_implicit_mentions')
3607 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3610 $text = html_entity_decode(BBCode::toMarkdown($body));
3611 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3612 $edited = DateTimeFormat::utc($item['edited'], DateTimeFormat::ATOM);
3615 'author' => self::myHandle($owner),
3616 'guid' => $item['guid'],
3617 'created_at' => $created,
3618 'edited_at' => $edited,
3619 'parent_guid' => $toplevel_item['guid'],
3621 'author_signature' => '',
3624 // Send the thread parent guid only if it is a threaded comment
3625 if ($item['thr-parent'] != $item['parent-uri']) {
3626 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3629 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3635 * Send a like or a comment
3637 * @param array $item The item that will be exported
3638 * @param array $owner the array of the item owner
3639 * @param array $contact Target of the communication
3640 * @param bool $public_batch Is it a public post?
3642 * @return int The result of the transmission
3643 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3644 * @throws \ImagickException
3646 public static function sendFollowup(array $item, array $owner, array $contact, bool $public_batch = false): int
3648 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3649 $message = self::constructAttend($item, $owner);
3650 $type = 'event_participation';
3651 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3652 $message = self::constructLike($item, $owner);
3654 } elseif (!in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
3655 $message = self::constructComment($item, $owner);
3659 if (empty($message)) {
3663 $message['author_signature'] = self::signature($owner, $message);
3665 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3669 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3671 * @param array $item The item that will be exported
3672 * @param array $owner the array of the item owner
3673 * @param array $contact Target of the communication
3674 * @param bool $public_batch Is it a public post?
3676 * @return int The result of the transmission
3677 * @throws \Exception
3679 public static function sendRelay(array $item, array $owner, array $contact, bool $public_batch = false): int
3681 if ($item['deleted']) {
3682 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3683 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3689 Logger::info('Got relayable data ' . $type . ' for item ' . $item['guid'] . ' (' . $item['id'] . ')');
3691 $msg = json_decode($item['signed_text'] ?? '', true);
3694 if (is_array($msg)) {
3695 foreach ($msg as $field => $data) {
3696 if (!$item['deleted']) {
3697 if ($field == 'diaspora_handle') {
3700 if ($field == 'target_type') {
3701 $field = 'parent_type';
3705 $message[$field] = $data;
3708 Logger::info('Signature text for item ' . $item['guid'] . ' (' . $item['id'] . ') could not be extracted: ' . $item['signed_text']);
3711 $message['parent_author_signature'] = self::signature($owner, $message);
3713 Logger::info('Relayed data', ['msg' => $message]);
3715 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3719 * Sends a retraction (deletion) of a message, like or comment
3721 * @param array $item The item that will be exported
3722 * @param array $owner the array of the item owner
3723 * @param array $contact Target of the communication
3724 * @param bool $public_batch Is it a public post?
3725 * @param bool $relay Is the retraction transmitted from a relay?
3727 * @return int The result of the transmission
3728 * @throws \Exception
3730 public static function sendRetraction(array $item, array $owner, array $contact, bool $public_batch = false, bool $relay = false): int
3732 $itemaddr = strtolower($item['author-addr']);
3734 $msg_type = 'retraction';
3736 if ($item['gravity'] == Item::GRAVITY_PARENT) {
3737 $target_type = 'Post';
3738 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3739 $target_type = 'Like';
3741 $target_type = 'Comment';
3745 'author' => $itemaddr,
3746 'target_guid' => $item['guid'],
3747 'target_type' => $target_type
3750 Logger::info('Got message', ['msg' => $message]);
3752 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item['guid']);
3758 * @param array $item The item that will be exported
3759 * @param array $owner The owner
3760 * @param array $contact Target of the communication
3762 * @return int The result of the transmission
3763 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3764 * @throws \ImagickException
3766 public static function sendMail(array $item, array $owner, array $contact): int
3768 $myaddr = self::myHandle($owner);
3770 $cnv = DBA::selectFirst('conv', [], ['id' => $item['convid'], 'uid' => $item['uid']]);
3771 if (!DBA::isResult($cnv)) {
3772 Logger::notice('Conversation not found.');
3776 $body = BBCode::toMarkdown($item['body']);
3777 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3780 'author' => $myaddr,
3781 'guid' => $item['guid'],
3782 'conversation_guid' => $cnv['guid'],
3784 'created_at' => $created,
3787 if ($item['reply']) {
3792 'author' => $cnv['creator'],
3793 'guid' => $cnv['guid'],
3794 'subject' => $cnv['subject'],
3795 'created_at' => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3796 'participants' => $cnv['recips'],
3800 $type = 'conversation';
3803 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item['guid']);
3807 * Split a name into first name and last name
3809 * @param string $name The name
3811 * @return array The array with "first" and "last"
3813 public static function splitName(string $name): array
3815 $name = trim($name);
3817 // Is the name longer than 64 characters? Then cut the rest of it.
3818 if (strlen($name) > 64) {
3819 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3820 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3822 $name = substr($name, 0, 64);
3826 // Take the first word as first name
3827 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3828 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3829 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3830 return ['first' => $first, 'last' => $last];
3833 // Take the last word as last name
3834 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3835 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3837 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3838 return ['first' => $first, 'last' => $last];
3841 // Take the first 32 characters if there is no space in the first 32 characters
3842 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3843 $first = substr($name, 0, 32);
3844 $last = substr($name, 32);
3845 return ['first' => $first, 'last' => $last];
3848 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3849 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3851 // Check if the last name is longer than 32 characters
3852 if (strlen($last) > 32) {
3853 if (strpos($last, ' ') <= 32) {
3854 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
3856 $last = substr($last, 0, 32);
3860 return ['first' => $first, 'last' => $last];
3864 * Create profile data
3866 * @param int $uid The user id
3868 * @return array The profile data
3869 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3871 private static function createProfileData(int $uid): array
3873 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
3875 if (!DBA::isResult($profile)) {
3879 $split_name = self::splitName($profile['name']);
3882 'author' => $profile['addr'],
3883 'first_name' => $split_name['first'],
3884 'last_name' => $split_name['last'],
3885 'image_url' => DI::baseUrl() . '/photo/custom/300/' . $profile['uid'] . '.jpg',
3886 'image_url_medium' => DI::baseUrl() . '/photo/custom/100/' . $profile['uid'] . '.jpg',
3887 'image_url_small' => DI::baseUrl() . '/photo/custom/50/' . $profile['uid'] . '.jpg',
3888 'searchable' => ($profile['net-publish'] ? 'true' : 'false'),
3892 'tag_string' => null,
3896 if ($data['searchable'] === 'true') {
3897 $data['birthday'] = '';
3899 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
3900 [$year, $month, $day] = sscanf($profile['dob'], '%4d-%2d-%2d');
3904 $data['birthday'] = DateTimeFormat::utc($year . '-' . $month . '-' . $day, 'Y-m-d');
3907 $data['about'] = BBCode::toMarkdown($profile['about'] ?? '');
3909 $data['location'] = $profile['location'];
3910 $data['tag_string'] = '';
3912 if ($profile['pub_keywords']) {
3913 $kw = str_replace(',', ' ', $profile['pub_keywords']);
3914 $kw = str_replace(' ', ' ', $kw);
3915 $arr = explode(' ', $kw);
3917 for ($x = 0; $x < 5; $x++) {
3918 if (!empty($arr[$x])) {
3919 $data['tag_string'] .= '#' . trim($arr[$x]) . ' ';
3924 $data['tag_string'] = trim($data['tag_string']);
3931 * Sends profile data
3933 * @param int $uid The user id
3934 * @param array $recipients optional, default empty array
3937 * @throws \Exception
3939 public static function sendProfile(int $uid, array $recipients = [])
3942 Logger::warning('Parameter "uid" is empty');
3946 $owner = User::getOwnerDataById($uid);
3947 if (empty($owner)) {
3948 Logger::warning('Cannot fetch User record', ['uid' => $uid]);
3952 if (empty($recipients)) {
3953 Logger::debug('No recipients provided, fetching for user', ['uid' => $uid]);
3954 $recipients = DBA::selectToArray('contact', [], ['network' => Protocol::DIASPORA, 'uid' => $uid, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
3957 if (empty($recipients)) {
3958 Logger::warning('Cannot fetch recipients', ['uid' => $uid]);
3962 $message = self::createProfileData($uid);
3964 // @todo Split this into single worker jobs
3965 foreach ($recipients as $recipient) {
3966 Logger::info('Send updated profile data for user ' . $uid . ' to contact ' . $recipient['id']);
3967 self::buildAndTransmit($owner, $recipient, 'profile', $message);
3972 * Creates the signature for likes that are created on our system
3974 * @param integer $uid The user of that comment
3975 * @param array $item Item array
3977 * @return array|bool Signed content or false on error
3978 * @throws \Exception
3980 public static function createLikeSignature(int $uid, array $item)
3982 $owner = User::getOwnerDataById($uid);
3983 if (empty($owner)) {
3984 Logger::info('No owner post, so not storing signature', ['uid' => $uid]);
3988 if (!in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3989 Logger::warning('Item is neither a like nor a dislike', ['uid' => $uid, 'item[verb]' => $item['verb']]);;
3993 $message = self::constructLike($item, $owner);
3994 if ($message === false) {
3998 $message['author_signature'] = self::signature($owner, $message);
4004 * Creates the signature for Comments that are created on our system
4006 * @param array $item Item array
4008 * @return array|bool Signed content or false on error
4009 * @throws \Exception
4011 public static function createCommentSignature(array $item)
4014 if (!empty($item['author-link'])) {
4015 $url = $item['author-link'];
4017 $contact = Contact::getById($item['author-id'], ['url']);
4018 if (empty($contact['url'])) {
4019 Logger::warning('Author Contact not found', ['author-id' => $item['author-id']]);
4022 $url = $contact['url'];
4025 $uid = User::getIdForURL($url);
4027 Logger::info('No owner post, so not storing signature', ['url' => $contact['url'] ?? 'No contact loaded']);
4031 $owner = User::getOwnerDataById($uid);
4032 if (empty($owner)) {
4033 Logger::info('No owner post, so not storing signature');
4037 // This is only needed for the automated tests
4038 if (empty($owner['uprvkey'])) {
4042 if (!self::parentSupportDiaspora($item['thr-parent-id'], $uid)) {
4043 Logger::info('One of the parents does not support Diaspora. A signature will not be created.', ['uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
4047 $message = self::constructComment($item, $owner);
4048 if ($message === false) {
4052 $message['author_signature'] = self::signature($owner, $message);
4058 * Check if the parent and their parents support Diaspora
4060 * @param integer $parent_id
4061 * @param integer $uid
4063 * @throws InternalServerErrorException
4064 * @throws \ImagickException
4066 private static function parentSupportDiaspora(int $parent_id, int $uid): bool
4068 $parent_post = Post::selectFirst(['gravity', 'signed_text', 'author-link', 'thr-parent-id', 'protocol'], ['uri-id' => $parent_id, 'uid' => [0, $uid]]);
4069 if (empty($parent_post['thr-parent-id'])) {
4070 Logger::warning('Parent post does not exist.', ['parent-id' => $parent_id]);
4074 if (!self::isSupportedByContactUrl($parent_post['author-link'])) {
4075 Logger::info('Parent author is no Diaspora contact.', ['parent-id' => $parent_id]);
4079 if (($parent_post['protocol'] != Conversation::PARCEL_DIASPORA) && ($parent_post['gravity'] == Item::GRAVITY_COMMENT) && empty($parent_post['signed_text'])) {
4080 Logger::info('Parent comment has got no Diaspora signature.', ['parent-id' => $parent_id]);
4084 if ($parent_post['gravity'] == Item::GRAVITY_COMMENT) {
4085 return self::parentSupportDiaspora($parent_post['thr-parent-id'], $uid);
4091 public static function performReshare(int $UriId, int $uid): int
4093 $owner = User::getOwnerDataById($uid);
4094 $author = Contact::getPublicIdByUserId($uid);
4098 'verb' => Activity::POST,
4099 'contact-id' => $owner['id'],
4100 'author-id' => $author,
4101 'owner-id' => $author,
4103 'quote-uri-id' => $UriId,
4104 'allow_cid' => $owner['allow_cid'] ?? '',
4105 'allow_gid' => $owner['allow_gid'] ?? '',
4106 'deny_cid' => $owner['deny_cid'] ?? '',
4107 'deny_gid' => $owner['deny_gid'] ?? '',
4110 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
4111 $item['private'] = Item::PRIVATE;
4112 } elseif (DI::pConfig()->get($uid, 'system', 'unlisted')) {
4113 $item['private'] = Item::UNLISTED;
4115 $item['private'] = Item::PUBLIC;
4118 // Don't trigger the addons
4119 $item['api_source'] = false;
4121 return Item::insert($item, true);