3 * @copyright Copyright (C) 2010-2022, 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\FContact;
37 use Friendica\Model\GServer;
38 use Friendica\Model\Item;
39 use Friendica\Model\ItemURI;
40 use Friendica\Model\Mail;
41 use Friendica\Model\Post;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
45 use Friendica\Network\HTTPException\InternalServerErrorException;
46 use Friendica\Network\Probe;
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 Friendica\Worker\Delivery;
54 use GuzzleHttp\Psr7\Uri;
58 * This class contains functions to communicate via the Diaspora protocol
59 * @see https://diaspora.github.io/diaspora_federation/
65 const FORCED_FETCH = 2;
68 * Return a list of participating contacts for a thread
70 * This is used for the participation feature.
71 * One of the parameters is a contact array.
72 * This is done to avoid duplicates.
74 * @param array $item Item that is about to be delivered
75 * @param array $contacts The previously fetched contacts
77 * @return array of relay servers
80 public static function participantsForThread(array $item, array $contacts): array
82 if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
83 Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]);
87 $items = Post::select(['author-id', 'author-link', 'parent-author-link', 'parent-guid', 'guid'],
88 ['parent' => $item['parent'], 'gravity' => [Item::GRAVITY_COMMENT, Item::GRAVITY_ACTIVITY]]);
89 while ($item = Post::fetch($items)) {
90 $contact = DBA::selectFirst('contact', ['id', 'url', 'name', 'protocol', 'batch', 'network'],
91 ['id' => $item['author-id']]);
92 if (!DBA::isResult($contact) || empty($contact['batch']) ||
93 ($contact['network'] != Protocol::DIASPORA) ||
94 Strings::compareLink($item['parent-author-link'], $item['author-link'])) {
99 foreach ($contacts as $entry) {
100 if ($entry['batch'] == $contact['batch']) {
106 Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]);
107 $contacts[] = $contact;
116 * verify the envelope and return the verified data
118 * @param string $envelope The magic envelope
120 * @return string|bool verified data or false on error
121 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
122 * @throws \ImagickException
124 private static function verifyMagicEnvelope(string $envelope)
126 $basedom = XML::parseString($envelope, true);
128 if (!is_object($basedom)) {
129 Logger::notice('Envelope is no XML file');
133 $children = $basedom->children(ActivityNamespace::SALMON_ME);
135 if (sizeof($children) == 0) {
136 Logger::notice('XML has no children');
142 $data = Strings::base64UrlDecode($children->data);
143 $type = $children->data->attributes()->type[0];
145 $encoding = $children->encoding;
147 $alg = $children->alg;
149 $sig = Strings::base64UrlDecode($children->sig);
150 $key_id = $children->sig->attributes()->key_id[0];
152 $handle = Strings::base64UrlDecode($key_id);
155 $b64url_data = Strings::base64UrlEncode($data);
156 $msg = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
158 $signable_data = $msg . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
161 Logger::notice('No author could be decoded. Discarding. Message: ' . $envelope);
166 $key = self::key(WebFingerUri::fromString($handle));
168 throw new \InvalidArgumentException();
170 } catch (\InvalidArgumentException $e) {
171 Logger::notice("Couldn't get a key for handle " . $handle . ". Discarding.");
175 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
177 Logger::notice('Message from ' . $handle . ' did not verify. Discarding.');
185 * encrypts data via AES
187 * @param string $key The AES key
188 * @param string $iv The IV (is used for CBC encoding)
189 * @param string $data The data that is to be encrypted
191 * @return string encrypted data
193 private static function aesEncrypt(string $key, string $iv, string $data): string
195 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
199 * decrypts data via AES
201 * @param string $key The AES key
202 * @param string $iv The IV (is used for CBC encoding)
203 * @param string $encrypted The encrypted data
205 * @return string decrypted data
207 private static function aesDecrypt(string $key, string $iv, string $encrypted): string
209 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
213 * Decodes incoming Diaspora message in the new format. This method returns false on an error.
215 * @param string $raw raw post message
216 * @param string $privKey The private key of the importer
217 * @param boolean $no_exit Don't do an http exit on error
220 * 'message' -> decoded Diaspora XML message
221 * 'author' -> author diaspora handle
222 * 'key' -> author public key (converted to pkcs#8)
223 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
224 * @throws \ImagickException
226 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
228 $data = json_decode($raw);
230 // Is it a private post? Then decrypt the outer Salmon
231 if (is_object($data)) {
233 if (!isset($data->aes_key) || !isset($data->encrypted_magic_envelope)) {
234 Logger::info('Missing keys "aes_key" and/or "encrypted_magic_envelope"', ['data' => $data]);
235 throw new \RuntimeException('Missing keys "aes_key" and/or "encrypted_magic_envelope"');
238 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
239 $ciphertext = base64_decode($data->encrypted_magic_envelope);
241 $outer_key_bundle = '';
242 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
243 $j_outer_key_bundle = json_decode($outer_key_bundle);
245 if (!is_object($j_outer_key_bundle)) {
246 Logger::info('Unable to decode outer key bundle', ['outer_key_bundle' => $outer_key_bundle]);
247 throw new \RuntimeException('Unable to decode outer key bundle');
250 if (!isset($j_outer_key_bundle->iv) || !isset($j_outer_key_bundle->key)) {
251 Logger::info('Missing keys "iv" and/or "key" from outer Salmon', ['j_outer_key_bundle' => $j_outer_key_bundle]);
252 throw new \RuntimeException('Missing keys "iv" and/or "key" from outer Salmon');
255 $outer_iv = base64_decode($j_outer_key_bundle->iv);
256 $outer_key = base64_decode($j_outer_key_bundle->key);
258 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
259 } catch (\Throwable $e) {
260 Logger::notice('Outer Salmon did not verify. Discarding.');
264 throw new \Friendica\Network\HTTPException\BadRequestException();
271 $basedom = XML::parseString($xml, true);
273 if (!is_object($basedom)) {
274 Logger::notice('Received data does not seem to be an XML. Discarding. '.$xml);
278 throw new \Friendica\Network\HTTPException\BadRequestException();
282 $base = $basedom->children(ActivityNamespace::SALMON_ME);
284 // Not sure if this cleaning is needed
285 $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
287 // Build the signed data
288 $type = $base->data[0]->attributes()->type[0];
289 $encoding = $base->encoding;
291 $signed_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
293 // This is the signature
294 $signature = Strings::base64UrlDecode($base->sig);
296 // Get the senders' public key
297 $key_id = $base->sig[0]->attributes()->key_id[0];
298 $author_addr = base64_decode($key_id);
299 if ($author_addr == '') {
300 Logger::notice('No author could be decoded. Discarding. Message: ' . $xml);
304 throw new \Friendica\Network\HTTPException\BadRequestException();
309 $author = WebFingerUri::fromString($author_addr);
310 $key = self::key($author);
312 throw new \InvalidArgumentException();
314 } catch (\InvalidArgumentException $e) {
315 Logger::notice("Couldn't get a key for handle " . $author_addr . ". Discarding.");
319 throw new \Friendica\Network\HTTPException\BadRequestException();
323 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
325 Logger::notice('Message did not verify. Discarding.');
329 throw new \Friendica\Network\HTTPException\BadRequestException();
334 'message' => (string)Strings::base64UrlDecode($base->data),
335 'author' => $author->getAddr(),
336 'key' => (string)$key
341 * Decodes incoming Diaspora message in the deprecated format
343 * @param string $xml urldecoded Diaspora salmon
344 * @param string $privKey The private key of the importer
347 * 'message' -> decoded Diaspora XML message
348 * 'author' -> author diaspora handle
349 * 'key' -> author public key (converted to pkcs#8)
350 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
351 * @throws \ImagickException
353 public static function decode(string $xml, string $privKey = '')
356 $basedom = XML::parseString($xml);
358 if (!is_object($basedom)) {
359 Logger::notice('XML is not parseable.');
362 $children = $basedom->children('https://joindiaspora.com/protocol');
364 $inner_aes_key = null;
367 if ($children->header) {
369 $idom = $children->header;
371 // This happens with posts from a relais
372 if (empty($privKey)) {
373 Logger::info('This is no private post in the old format');
377 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
379 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
380 $ciphertext = base64_decode($encrypted_header->ciphertext);
382 $outer_key_bundle = '';
383 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
385 $j_outer_key_bundle = json_decode($outer_key_bundle);
387 $outer_iv = base64_decode($j_outer_key_bundle->iv);
388 $outer_key = base64_decode($j_outer_key_bundle->key);
390 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
392 Logger::info('decrypted', ['data' => $decrypted]);
393 $idom = XML::parseString($decrypted);
395 $inner_iv = base64_decode($idom->iv);
396 $inner_aes_key = base64_decode($idom->aes_key);
400 $author = WebFingerUri::fromString($idom->author_id);
401 } catch (\Throwable $e) {
402 Logger::notice('Could not retrieve author URI.', ['idom' => $idom]);
403 throw new \Friendica\Network\HTTPException\BadRequestException();
406 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
408 // figure out where in the DOM tree our data is hiding
411 if ($dom->provenance->data) {
412 $base = $dom->provenance;
413 } elseif ($dom->env->data) {
415 } elseif ($dom->data) {
420 Logger::notice('unable to locate salmon data in xml');
421 throw new \Friendica\Network\HTTPException\BadRequestException();
425 // Stash the signature away for now. We have to find their key or it won't be good for anything.
426 $signature = Strings::base64UrlDecode($base->sig);
430 // strip whitespace so our data element will return to one big base64 blob
431 $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
434 // stash away some other stuff for later
436 $type = $base->data[0]->attributes()->type[0];
437 $keyhash = $base->sig[0]->attributes()->keyhash[0];
438 $encoding = $base->encoding;
442 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
446 $data = Strings::base64UrlDecode($data);
450 $inner_decrypted = $data;
452 // Decode the encrypted blob
453 $inner_encrypted = base64_decode($data);
454 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
457 // Once we have the author URI, go to the web and try to find their public key
458 // (first this will look it up locally if it is in the fcontact cache)
459 // This will also convert diaspora public key from pkcs#1 to pkcs#8
461 Logger::notice('Fetching key for ' . $author);
462 $key = self::key($author);
464 Logger::notice('Could not retrieve author key.');
465 throw new \Friendica\Network\HTTPException\BadRequestException();
468 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
471 Logger::notice('Message did not verify. Discarding.');
472 throw new \Friendica\Network\HTTPException\BadRequestException();
475 Logger::notice('Message verified.');
478 'message' => $inner_decrypted,
479 'author' => $author->getAddr(),
486 * Dispatches public messages and find the fitting receivers
488 * @param array $msg The post that will be dispatched
489 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
491 * @return int|bool The message id of the generated message, "true" or "false" if there was an error
492 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
493 * @throws \ImagickException
495 public static function dispatchPublic(array $msg, int $direction)
497 $enabled = intval(DI::config()->get('system', 'diaspora_enabled'));
499 Logger::notice('Diaspora is disabled');
503 if (!($fields = self::validPosting($msg))) {
504 Logger::warning('Invalid posting');
510 'page-flags' => User::PAGE_FLAGS_FREELOVE
512 $success = self::dispatch($importer, $msg, $fields, $direction);
518 * Dispatches the different message types to the different functions
520 * @param array $importer Array of the importer user
521 * @param array $msg The post that will be dispatched
522 * @param SimpleXMLElement $fields SimpleXML object that contains the message
523 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
525 * @return int|bool The message id of the generated message, "true" or "false" if there was an error
526 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
527 * @throws \ImagickException
529 public static function dispatch(array $importer, array $msg, SimpleXMLElement $fields = null, int $direction = self::PUSHED)
531 // The sender is the handle of the contact that sent the message.
532 // This will often be different with relayed messages (for example "like" and "comment")
533 $sender = WebFingerUri::fromString($msg['author']);
535 // This is only needed for private postings since this is already done for public ones before
536 if (is_null($fields)) {
538 if (!($fields = self::validPosting($msg))) {
539 Logger::warning('Invalid posting');
546 $type = $fields->getName();
548 Logger::info('Received message', ['type' => $type, 'sender' => $sender->getAddr(), 'user' => $importer['uid']]);
551 case 'account_migration':
553 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
556 return self::receiveAccountMigration($importer, $fields);
558 case 'account_deletion':
559 return self::receiveAccountDeletion($fields);
562 return self::receiveComment($importer, $sender, $fields, $msg['message'], $direction);
566 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
569 return self::receiveContactRequest($importer, $fields);
573 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
576 return self::receiveConversation($importer, $msg, $fields);
579 return self::receiveLike($importer, $sender, $fields, $direction);
583 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
586 return self::receiveMessage($importer, $fields);
588 case 'participation':
590 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
593 return self::receiveParticipation($importer, $fields, $direction);
595 case 'photo': // Not implemented
596 return self::receivePhoto($importer, $fields);
598 case 'poll_participation': // Not implemented
599 return self::receivePollParticipation($importer, $fields);
603 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
606 return self::receiveProfile($importer, $fields);
609 return self::receiveReshare($importer, $fields, $msg['message'], $direction);
612 return self::receiveRetraction($importer, $sender, $fields);
614 case 'status_message':
615 return self::receiveStatusMessage($importer, $fields, $msg['message'], $direction);
618 Logger::notice('Unknown message type ' . $type);
624 * Checks if a posting is valid and fetches the data fields.
626 * This function does not only check the signature.
627 * It also does the conversion between the old and the new diaspora format.
629 * @param array $msg Array with the XML, the sender handle and the sender signature
631 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
632 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
633 * @throws \ImagickException
635 private static function validPosting(array $msg)
637 $data = XML::parseString($msg['message']);
639 if (!is_object($data)) {
640 Logger::info('No valid XML', ['message' => $msg['message']]);
644 // Is this the new or the old version?
645 if ($data->getName() == 'XML') {
647 foreach ($data->post->children() as $child) {
655 $type = $element->getName();
658 Logger::debug('Got message', ['type' => $type, 'message' => $msg['message']]);
660 // All retractions are handled identically from now on.
661 // In the new version there will only be "retraction".
662 if (in_array($type, ['signed_retraction', 'relayable_retraction']))
663 $type = 'retraction';
665 if ($type == 'request') {
669 $fields = new SimpleXMLElement('<' . $type . '/>');
672 $author_signature = null;
673 $parent_author_signature = null;
675 foreach ($element->children() as $fieldname => $entry) {
677 // Translation for the old XML structure
678 if ($fieldname == 'diaspora_handle') {
679 $fieldname = 'author';
681 if ($fieldname == 'participant_handles') {
682 $fieldname = 'participants';
684 if (in_array($type, ['like', 'participation'])) {
685 if ($fieldname == 'target_type') {
686 $fieldname = 'parent_type';
689 if ($fieldname == 'sender_handle') {
690 $fieldname = 'author';
692 if ($fieldname == 'recipient_handle') {
693 $fieldname = 'recipient';
695 if ($fieldname == 'root_diaspora_id') {
696 $fieldname = 'root_author';
698 if ($type == 'status_message') {
699 if ($fieldname == 'raw_message') {
703 if ($type == 'retraction') {
704 if ($fieldname == 'post_guid') {
705 $fieldname = 'target_guid';
707 if ($fieldname == 'type') {
708 $fieldname = 'target_type';
713 if (($fieldname == 'author_signature') && ($entry != '')) {
714 $author_signature = base64_decode($entry);
715 } elseif (($fieldname == 'parent_author_signature') && ($entry != '')) {
716 $parent_author_signature = base64_decode($entry);
717 } elseif (!in_array($fieldname, ['author_signature', 'parent_author_signature', 'target_author_signature'])) {
718 if ($signed_data != '') {
722 $signed_data .= $entry;
724 if (!in_array($fieldname, ['parent_author_signature', 'target_author_signature'])
725 || ($orig_type == 'relayable_retraction')
727 XML::copy($entry, $fields, $fieldname);
731 // This is something that shouldn't happen at all.
732 if (in_array($type, ['status_message', 'reshare', 'profile'])) {
733 if ($msg['author'] != $fields->author) {
734 Logger::notice('Message handle is not the same as envelope sender. Quitting this message.', ['author1' => $msg['author'], 'author2' => $fields->author]);
739 // Only some message types have signatures. So we quit here for the other types.
740 if (!in_array($type, ['comment', 'like'])) {
744 if (!isset($author_signature) && ($msg['author'] == $fields->author)) {
745 Logger::debug('No author signature, but the sender matches the author', ['type' => $type, 'msg-author' => $msg['author'], 'message' => $msg['message']]);
749 // No author_signature? This is a must, so we quit.
750 if (!isset($author_signature)) {
751 Logger::info('No author signature', ['type' => $type, 'msg-author' => $msg['author'], 'fields-author' => $fields->author, 'message' => $msg['message']]);
755 if (isset($parent_author_signature)) {
756 $key = self::key(WebFingerUri::fromString($msg['author']));
758 Logger::info('No key found for parent', ['author' => $msg['author']]);
762 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, 'sha256')) {
763 Logger::info('No valid parent author signature', ['author' => $msg['author'], 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $parent_author_signature]);
769 $key = self::key(WebFingerUri::fromString($fields->author));
771 throw new \InvalidArgumentException();
773 } catch (\Throwable $e) {
774 Logger::info('No key found', ['author' => $fields->author]);
778 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, 'sha256')) {
779 Logger::info('No valid author signature for author', ['author' => $fields->author, 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $author_signature]);
787 * Fetches the public key for a given handle
789 * @param WebFingerUri $uri The handle
791 * @return string The public key
792 * @throws InternalServerErrorException
793 * @throws \ImagickException
795 private static function key(WebFingerUri $uri): string
797 Logger::notice('Fetching diaspora key', ['handle' => $uri->getAddr(), 'callstack' => System::callstack(20)]);
799 $fcontact = FContact::getByURL($uri);
800 if (!empty($fcontact['pubkey'])) {
801 return $fcontact['pubkey'];
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 return Contact::getByURL($uri->getAddr(), null, [], $uid);
823 * Checks if the given contact url does support ActivityPub
825 * @param string $url profile url
826 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
828 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
829 * @throws \ImagickException
831 public static function isSupportedByContactUrl(string $url, $update = null)
833 return !empty(FContact::getByURL($url, $update));
837 * Check if posting is allowed for this contact
839 * @param array $importer Array of the importer user
840 * @param array $contact The contact that is checked
841 * @param bool $is_comment Is the check for a comment?
843 * @return bool is the contact allowed to post?
845 private static function postAllow(array $importer, array $contact, bool $is_comment = false): bool
848 * Perhaps we were already sharing with this person. Now they're sharing with us.
849 * That makes us friends.
850 * Normally this should have handled by getting a request - but this could get lost
852 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
853 // It is not removed by now. Possibly the code is needed?
854 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
856 // array('rel' => Contact::FRIEND, 'writable' => true),
857 // array('id' => $contact["id"], 'uid' => $contact["uid"])
860 // $contact["rel"] = Contact::FRIEND;
861 // Logger::notice("defining user ".$contact["nick"]." as friend");
864 // Contact server is blocked
865 if (Network::isUrlBlocked($contact['url'])) {
867 // We don't seem to like that person
868 } elseif ($contact['blocked']) {
869 // Maybe blocked, don't accept.
871 // We are following this person?
872 } elseif (($contact['rel'] == Contact::SHARING) || ($contact['rel'] == Contact::FRIEND)) {
873 // Yes, then it is fine.
875 // Is the message a global user or a comment?
876 } elseif (($importer['uid'] == 0) || $is_comment) {
877 // Messages for the global users and comments are always accepted
885 * Fetches the contact id for a handle and checks if posting is allowed
887 * @param array $importer Array of the importer user
888 * @param WebFingerUri $contact_uri The checked contact
889 * @param bool $is_comment Is the check for a comment?
891 * @return array|bool The contact data or false on error
892 * @throws InternalServerErrorException
893 * @throws \ImagickException
895 private static function allowedContactByHandle(array $importer, WebFingerUri $contact_uri, bool $is_comment = false)
897 $contact = self::contactByHandle($importer['uid'], $contact_uri);
899 Logger::notice('A Contact for handle ' . $contact_uri . ' and user ' . $importer['uid'] . ' was not found');
900 // If a contact isn't found, we accept it anyway if it is a comment
901 if ($is_comment && ($importer['uid'] != 0)) {
902 return self::contactByHandle(0, $contact_uri);
903 } elseif ($is_comment) {
910 if (!self::postAllow($importer, $contact, $is_comment)) {
911 Logger::notice('The handle: ' . $contact_uri . ' is not allowed to post to user ' . $importer['uid']);
918 * Does the message already exists on the system?
920 * @param int $uid The user id
921 * @param string $guid The guid of the message
923 * @return int|bool message id if the message already was stored into the system - or false.
926 private static function messageExists(int $uid, string $guid)
928 $item = Post::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
929 if (DBA::isResult($item)) {
930 Logger::notice('Message ' . $guid . ' already exists for user ' . $uid);
938 * Checks for links to posts in a message
940 * @param array $item The item array
943 private static function fetchGuid(array $item)
945 preg_replace_callback(
946 "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism",
947 function ($match) use ($item) {
948 self::fetchGuidSub($match, $item);
953 preg_replace_callback(
954 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
955 function ($match) use ($item) {
956 self::fetchGuidSub($match, $item);
963 * Checks for relative /people/* links in an item body to match local
964 * contacts or prepends the remote host taken from the author link.
966 * @param string $body The item body to replace links from
967 * @param string $author_link The author link for missing local contact fallback
969 * @return string the replaced string
971 public static function replacePeopleGuid(string $body, string $author_link): string
973 $return = preg_replace_callback(
974 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
975 function ($match) use ($author_link) {
977 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
978 // 1 => '0123456789abcdef'
980 $handle = FContact::getUrlByGuid($match[1]);
983 $return = '@[url=' . $handle . ']' . $match[2] . '[/url]';
985 // No local match, restoring absolute remote URL from author scheme and host
986 $author_url = parse_url($author_link);
987 $return = '[url=' . $author_url['scheme'] . '://' . $author_url['host'] . '/people/' . $match[1] . ']' . $match[2] . '[/url]';
999 * sub function of "fetchGuid" which checks for links in messages
1001 * @param array $match array containing a link that has to be checked for a message link
1002 * @param array $item The item array
1004 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1005 * @throws \ImagickException
1007 private static function fetchGuidSub(array $match, array $item)
1009 if (!self::storeByGuid($match[1], $item['author-link'], true)) {
1010 self::storeByGuid($match[1], $item['owner-link'], true);
1015 * Fetches an item with a given guid from a given server
1017 * @param string $guid the message guid
1018 * @param string $server The server address
1019 * @param bool $force Forced fetch
1021 * @return int|bool the message id of the stored message or false
1022 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1023 * @throws \ImagickException
1025 private static function storeByGuid(string $guid, string $server, bool $force)
1027 $serverparts = parse_url($server);
1029 if (empty($serverparts['host']) || empty($serverparts['scheme'])) {
1033 $server = $serverparts['scheme'] . '://' . $serverparts['host'];
1035 Logger::info('Trying to fetch item ' . $guid . ' from ' . $server);
1037 $msg = self::message($guid, $server);
1043 Logger::info('Successfully fetched item ' . $guid . ' from ' . $server);
1045 // Now call the dispatcher
1046 return self::dispatchPublic($msg, $force ? self::FORCED_FETCH : self::FETCHED);
1050 * Fetches a message from a server
1052 * @param string $guid message guid
1053 * @param string $server The url of the server
1054 * @param int $level Endless loop prevention
1057 * 'message' => The message XML
1058 * 'author' => The author handle
1059 * 'key' => The public key of the author
1060 * @throws \Exception
1062 public static function message(string $guid, string $server, int $level = 0)
1068 // This will work for new Diaspora servers and Friendica servers from 3.5
1069 $source_url = $server . '/fetch/post/' . urlencode($guid);
1071 Logger::info('Fetch post from ' . $source_url);
1073 $envelope = DI::httpClient()->fetch($source_url, HttpClientAccept::MAGIC);
1075 Logger::info('Envelope was fetched.');
1076 $x = self::verifyMagicEnvelope($envelope);
1078 Logger::info('Envelope could not be verified.');
1080 Logger::info('Envelope was verified.');
1090 $source_xml = XML::parseString($x);
1092 if (!is_object($source_xml)) {
1096 if ($source_xml->post->reshare) {
1097 // Reshare of a reshare - old Diaspora version
1098 Logger::info('Message is a reshare');
1099 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1100 } elseif ($source_xml->getName() == 'reshare') {
1101 // Reshare of a reshare - new Diaspora version
1102 Logger::info('Message is a new reshare');
1103 return self::message($source_xml->root_guid, $server, ++$level);
1106 $author_handle = '';
1108 // Fetch the author - for the old and the new Diaspora version
1109 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1110 $author_handle = (string)$source_xml->post->status_message->diaspora_handle;
1111 } elseif ($source_xml->author && ($source_xml->getName() == 'status_message')) {
1112 $author_handle = (string)$source_xml->author;
1116 $author = WebFingerUri::fromString($author_handle);
1117 } catch (\InvalidArgumentException $e) {
1118 // If this isn't a "status_message" then quit
1119 Logger::info("Message doesn't seem to be a status message");
1125 'author' => $author->getAddr(),
1126 'key' => self::key($author)
1131 * Fetches an item with a given URL
1133 * @param string $url the message url
1134 * @param int $uid User id
1136 * @return int|bool the message id of the stored message or false
1137 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1138 * @throws \ImagickException
1140 public static function fetchByURL(string $url, int $uid = 0)
1142 // Check for Diaspora (and Friendica) typical paths
1143 if (!preg_match('=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i', $url, $matches)) {
1144 Logger::info('Invalid url', ['url' => $url]);
1148 $guid = urldecode($matches[2]);
1150 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1151 if (DBA::isResult($item)) {
1152 Logger::info('Found', ['id' => $item['id']]);
1156 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1157 $ret = self::storeByGuid($guid, $matches[1], true);
1158 Logger::info('Result', ['ret' => $ret]);
1160 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1161 if (DBA::isResult($item)) {
1162 Logger::info('Found', ['id' => $item['id']]);
1165 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1171 * Fetches the item record of a given guid
1173 * @param int $uid The user id
1174 * @param string $guid message guid
1175 * @param WebFingerUri $author
1176 * @param array $contact The contact of the item owner
1178 * @return array|bool the item record or false on failure
1179 * @throws \Exception
1181 private static function parentItem(int $uid, string $guid, WebFingerUri $author, array $contact)
1183 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1184 'author-name', 'author-link', 'author-avatar', 'gravity',
1185 'owner-name', 'owner-link', 'owner-avatar'];
1187 $condition = ['uid' => $uid, 'guid' => $guid];
1188 $item = Post::selectFirst($fields, $condition);
1190 if (!DBA::isResult($item)) {
1191 $person = FContact::getByURL($author);
1192 $result = self::storeByGuid($guid, $person['url'], false);
1194 // We don't have an url for items that arrived at the public dispatcher
1195 if (!$result && !empty($contact['url'])) {
1196 $result = self::storeByGuid($guid, $contact['url'], false);
1200 Logger::info('Fetched missing item ' . $guid . ' - result: ' . $result);
1202 $item = Post::selectFirst($fields, $condition);
1206 if (!DBA::isResult($item)) {
1207 Logger::notice('Parent item not found: parent: ' . $guid . ' - user: ' . $uid);
1210 Logger::notice('Parent item found: parent: ' . $guid . ' - user: ' . $uid);
1216 * returns contact details for the given user
1218 * @param array $def_contact The default details if the contact isn't found
1219 * @param string $contact_url The url of the contact
1220 * @param int $uid The user id
1223 * 'cid' => contact id
1224 * 'network' => network type
1225 * @throws \Exception
1227 private static function authorContactByUrl(array $def_contact, string $contact_url, int $uid): array
1229 $condition = ['nurl' => Strings::normaliseLink($contact_url), 'uid' => $uid];
1230 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1231 if (DBA::isResult($contact)) {
1232 $cid = $contact['id'];
1233 $network = $contact['network'];
1235 $cid = $def_contact['id'];
1236 $network = Protocol::DIASPORA;
1241 'network' => $network
1246 * Is the profile a hubzilla profile?
1248 * @param string $url The profile link
1250 * @return bool is it a hubzilla server?
1252 private static function isHubzilla(string $url): bool
1254 return strstr($url, '/channel/');
1258 * Generate a post link with a given handle and message guid
1260 * @param string $addr The user handle
1261 * @param string $guid message guid
1262 * @param string $parent_guid optional parent guid
1264 * @return string the post link
1265 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1266 * @throws \ImagickException
1268 private static function plink(string $addr, string $guid, string $parent_guid = ''): string
1270 $contact = Contact::getByURL($addr);
1271 if (empty($contact)) {
1272 Logger::info('No contact data for address', ['addr' => $addr]);
1276 if (empty($contact['baseurl'])) {
1277 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1278 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1282 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1283 if (!empty($gserver['platform'])) {
1284 $platform = strtolower($gserver['platform']);
1285 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1288 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1289 if (self::isHubzilla($contact['url'])) {
1290 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1291 $platform = 'hubzilla';
1292 } elseif ($contact['network'] == Protocol::DFRN) {
1293 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1294 $platform = 'friendica';
1298 if ($platform == 'friendica') {
1299 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1302 if ($platform == 'hubzilla') {
1303 return $contact['baseurl'] . '/item/' . $guid;
1306 if ($platform == 'socialhome') {
1307 return $contact['baseurl'] . '/content/' . $guid;
1310 if ($platform != 'diaspora') {
1311 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1315 if ($parent_guid != '') {
1316 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1318 return $contact['baseurl'] . '/posts/' . $guid;
1323 * Receives account migration
1325 * @param array $importer Array of the importer user
1326 * @param SimpleXMLElement $data The message object
1328 * @return bool Success
1329 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1330 * @throws \ImagickException
1332 private static function receiveAccountMigration(array $importer, SimpleXMLElement $data): bool
1335 $old_author = WebFingerUri::fromString(XML::unescape($data->author));
1336 $new_author = WebFingerUri::fromString(XML::unescape($data->profile->author));
1337 } catch (\Throwable $e) {
1338 Logger::notice('Cannot find handles for sender and user', ['data' => $data]);
1342 $signature = XML::unescape($data->signature);
1344 $contact = self::contactByHandle($importer['uid'], $old_author);
1346 Logger::notice('Cannot find contact for sender: ' . $old_author . ' and user ' . $importer['uid']);
1350 Logger::notice('Got migration for ' . $old_author . ', to ' . $new_author . ' with user ' . $importer['uid']);
1353 $signed_text = 'AccountMigration:' . $old_author . ':' . $new_author;
1354 $key = self::key($old_author);
1355 if (!Crypto::rsaVerify($signed_text, $signature, $key, 'sha256')) {
1356 Logger::notice('No valid signature for migration.');
1360 // Update the profile
1361 self::receiveProfile($importer, $data->profile);
1363 // change the technical stuff in contact
1364 $data = Probe::uri($new_author);
1365 if ($data['network'] == Protocol::PHANTOM) {
1366 Logger::notice("Account for " . $new_author . " couldn't be probed.");
1371 'url' => $data['url'],
1372 'nurl' => Strings::normaliseLink($data['url']),
1373 'name' => $data['name'],
1374 'nick' => $data['nick'],
1375 'addr' => $data['addr'],
1376 'batch' => $data['batch'],
1377 'notify' => $data['notify'],
1378 'poll' => $data['poll'],
1379 'network' => $data['network'],
1382 Contact::update($fields, ['addr' => $old_author->getAddr()]);
1384 Logger::notice('Contacts are updated.');
1390 * Processes an account deletion
1392 * @param SimpleXMLElement $data The message object
1394 * @return bool Success
1395 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1397 private static function receiveAccountDeletion(SimpleXMLElement $data): bool
1399 $author_handle = XML::unescape($data->author);
1401 $contacts = DBA::select('contact', ['id'], ['addr' => $author_handle]);
1402 while ($contact = DBA::fetch($contacts)) {
1403 Contact::remove($contact['id']);
1405 DBA::close($contacts);
1407 Logger::notice('Removed contacts for ' . $author_handle);
1413 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1415 * @param string $guid Message guid
1416 * @param WebFingerUri|null $person_uri Optional person to derive the base URL from
1418 * @return string The constructed uri or the one from our database or empty string
1419 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1420 * @throws \ImagickException
1422 private static function getUriFromGuid(string $guid, WebFingerUri $person_uri = null): string
1424 $item = Post::selectFirst(['uri'], ['guid' => $guid]);
1425 if (DBA::isResult($item)) {
1426 return $item['uri'];
1427 } elseif ($person_uri) {
1428 $person = FContact::getByURL($person_uri);
1430 $parts = parse_url($person['url']);
1431 unset($parts['path']);
1432 $host_url = (string)Uri::fromParts($parts);
1434 return $host_url . '/objects/' . $guid;
1441 * Store the mentions in the tag table
1443 * @param integer $uriid
1444 * @param string $text
1446 private static function storeMentions(int $uriid, string $text)
1448 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1449 if (empty($matches)) {
1454 * Matching values for the preg match
1455 * [1] = mention type (@ or !)
1456 * [2] = name (optional)
1460 foreach ($matches as $match) {
1461 if (empty($match)) {
1465 $person = FContact::getByURL($match[3]);
1466 if (empty($person)) {
1470 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1475 * Processes an incoming comment
1477 * @param array $importer Array of the importer user
1478 * @param WebFingerUri $sender The sender of the message
1479 * @param SimpleXMLElement $data The message object
1480 * @param string $xml The original XML of the message
1481 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1483 * @return bool The message id of the generated comment or "false" if there was an error
1484 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1485 * @throws \ImagickException
1487 private static function receiveComment(array $importer, WebFingerUri $sender, SimpleXMLElement $data, string $xml, int $direction): bool
1489 $author = WebFingerUri::fromString(XML::unescape($data->author));
1490 $guid = XML::unescape($data->guid);
1491 $parent_guid = XML::unescape($data->parent_guid);
1492 $text = XML::unescape($data->text);
1494 if (isset($data->created_at)) {
1495 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1497 $created_at = DateTimeFormat::utcNow();
1500 if (isset($data->thread_parent_guid)) {
1501 $thread_parent_guid = XML::unescape($data->thread_parent_guid);
1502 $thr_parent = self::getUriFromGuid($thread_parent_guid);
1507 $contact = self::allowedContactByHandle($importer, $sender, true);
1512 if (!empty($contact['gsid'])) {
1513 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1516 $message_id = self::messageExists($importer['uid'], $guid);
1521 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1522 if (!$toplevel_parent_item) {
1526 $person = FContact::getByURL($author);
1527 if (!is_array($person)) {
1528 Logger::notice('Unable to find author details');
1532 // Fetch the contact id - if we know this contact
1533 $author_contact = self::authorContactByUrl($contact, $person['url'], $importer['uid']);
1537 $datarray['uid'] = $importer['uid'];
1538 $datarray['contact-id'] = $author_contact['cid'];
1539 $datarray['network'] = $author_contact['network'];
1541 $datarray['author-link'] = $person['url'];
1542 $datarray['author-id'] = Contact::getIdForURL($person['url'], 0);
1544 $datarray['owner-link'] = $contact['url'];
1545 $datarray['owner-id'] = Contact::getIdForURL($contact['url'], 0);
1547 // Will be overwritten for sharing accounts in Item::insert
1548 $datarray = self::setDirection($datarray, $direction);
1550 $datarray['guid'] = $guid;
1551 $datarray['uri'] = self::getUriFromGuid($guid, $author);
1552 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1554 $datarray['verb'] = Activity::POST;
1555 $datarray['gravity'] = Item::GRAVITY_COMMENT;
1557 $datarray['thr-parent'] = $thr_parent ?: $toplevel_parent_item['uri'];
1559 $datarray['object-type'] = Activity\ObjectType::COMMENT;
1560 $datarray['post-type'] = Item::PT_NOTE;
1562 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1563 $datarray['source'] = $xml;
1565 $datarray = self::setDirection($datarray, $direction);
1567 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
1569 $datarray['plink'] = self::plink($author, $guid, $toplevel_parent_item['guid']);
1570 $body = Markdown::toBBCode($text);
1572 $datarray['body'] = self::replacePeopleGuid($body, $person['url']);
1574 self::storeMentions($datarray['uri-id'], $text);
1575 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
1577 self::fetchGuid($datarray);
1579 // If we are the origin of the parent we store the original data.
1580 // We notify our followers during the item storage.
1581 if ($toplevel_parent_item['origin']) {
1582 $datarray['diaspora_signed_text'] = json_encode($data);
1585 if (Item::isTooOld($datarray)) {
1586 Logger::info('Comment is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1590 $message_id = Item::insert($datarray);
1592 if ($message_id <= 0) {
1597 Logger::info('Stored comment ' . $datarray['guid'] . ' with message id ' . $message_id);
1598 if ($datarray['uid'] == 0) {
1599 Item::distribute($message_id, json_encode($data));
1607 * processes and stores private messages
1609 * @param array $importer Array of the importer user
1610 * @param array $contact The contact of the message
1611 * @param SimpleXMLElement $data The message object
1612 * @param array $msg Array of the processed message, author handle and key
1613 * @param object $mesg The private message
1614 * @param array $conversation The conversation record to which this message belongs
1616 * @return bool "true" if it was successful
1617 * @throws \Exception
1618 * @todo Find type-hint for $mesg and update documentation
1620 private static function receiveConversationMessage(array $importer, array $contact, SimpleXMLElement $data, array $msg, $mesg, array $conversation): bool
1622 $author_handle = XML::unescape($data->author);
1623 $guid = XML::unescape($data->guid);
1624 $subject = XML::unescape($data->subject);
1626 // "diaspora_handle" is the element name from the old version
1627 // "author" is the element name from the new version
1628 if ($mesg->author) {
1629 $msg_author_handle = XML::unescape($mesg->author);
1630 } elseif ($mesg->diaspora_handle) {
1631 $msg_author_handle = XML::unescape($mesg->diaspora_handle);
1636 $msg_guid = XML::unescape($mesg->guid);
1637 $msg_conversation_guid = XML::unescape($mesg->conversation_guid);
1638 $msg_text = XML::unescape($mesg->text);
1639 $msg_created_at = DateTimeFormat::utc(XML::unescape($mesg->created_at));
1641 if ($msg_conversation_guid != $guid) {
1642 Logger::notice('Message conversation guid does not belong to the current conversation.', ['guid' => $guid]);
1646 $body = Markdown::toBBCode($msg_text);
1648 $person = FContact::getByURL($msg_author_handle);
1650 return Mail::insert([
1651 'uid' => $importer['uid'],
1652 'guid' => $msg_guid,
1653 'convid' => $conversation['id'],
1654 'from-name' => $person['name'],
1655 'from-photo' => $person['photo'],
1656 'from-url' => $person['url'],
1657 'contact-id' => $contact['id'],
1658 'title' => $subject,
1660 'uri' => $msg_author_handle . ':' . $msg_guid,
1661 'parent-uri' => $author_handle . ':' . $guid,
1662 'created' => $msg_created_at
1667 * Processes new private messages (answers to private messages are processed elsewhere)
1669 * @param array $importer Array of the importer user
1670 * @param array $msg Array of the processed message, author handle and key
1671 * @param SimpleXMLElement $data The message object
1673 * @return bool Success
1674 * @throws \Exception
1676 private static function receiveConversation(array $importer, array $msg, SimpleXMLElement $data)
1678 $author_handle = XML::unescape($data->author);
1679 $guid = XML::unescape($data->guid);
1680 $subject = XML::unescape($data->subject);
1681 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1682 $participants = XML::unescape($data->participants);
1684 $messages = $data->message;
1686 if (!count($messages)) {
1687 Logger::notice('Empty conversation');
1691 $contact = self::allowedContactByHandle($importer, WebFingerUri::fromString($msg['author']), true);
1696 if (!empty($contact['gsid'])) {
1697 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1700 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1701 if (!DBA::isResult($conversation)) {
1702 $r = DBA::insert('conv', [
1703 'uid' => $importer['uid'],
1705 'creator' => $author_handle,
1706 'created' => $created_at,
1707 'updated' => DateTimeFormat::utcNow(),
1708 'subject' => $subject,
1709 'recips' => $participants
1713 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1716 if (!$conversation) {
1717 Logger::warning('Unable to create conversation.');
1721 foreach ($messages as $mesg) {
1722 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1729 * Processes "like" messages
1731 * @param array $importer Array of the importer user
1732 * @param WebFingerUri $sender The sender of the message
1733 * @param SimpleXMLElement $data The message object
1734 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1736 * @return bool Success or failure
1737 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1738 * @throws \ImagickException
1740 private static function receiveLike(array $importer, WebFingerUri $sender, SimpleXMLElement $data, int $direction): bool
1742 $author = WebFingerUri::fromString(XML::unescape($data->author));
1743 $guid = XML::unescape($data->guid);
1744 $parent_guid = XML::unescape($data->parent_guid);
1745 $parent_type = XML::unescape($data->parent_type);
1746 $positive = XML::unescape($data->positive);
1748 // likes on comments aren't supported by Diaspora - only on posts
1749 // But maybe this will be supported in the future, so we will accept it.
1750 if (!in_array($parent_type, ['Post', 'Comment'])) {
1754 $contact = self::allowedContactByHandle($importer, $sender, true);
1759 if (!empty($contact['gsid'])) {
1760 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1763 $message_id = self::messageExists($importer['uid'], $guid);
1768 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1769 if (!$toplevel_parent_item) {
1773 $person = FContact::getByURL($author);
1774 if (!is_array($person)) {
1775 Logger::notice('Unable to find author details');
1779 // Fetch the contact id - if we know this contact
1780 $author_contact = self::authorContactByUrl($contact, $person['url'], $importer['uid']);
1782 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1783 // We would accept this anyhow.
1784 if ($positive == 'true') {
1785 $verb = Activity::LIKE;
1787 $verb = Activity::DISLIKE;
1792 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1794 $datarray['uid'] = $importer['uid'];
1795 $datarray['contact-id'] = $author_contact['cid'];
1796 $datarray['network'] = $author_contact['network'];
1798 $datarray = self::setDirection($datarray, $direction);
1800 $datarray['owner-link'] = $datarray['author-link'] = $person['url'];
1801 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($person['url'], 0);
1803 $datarray['guid'] = $guid;
1804 $datarray['uri'] = self::getUriFromGuid($guid, $author);
1806 $datarray['verb'] = $verb;
1807 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
1808 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1810 $datarray['object-type'] = Activity\ObjectType::NOTE;
1812 $datarray['body'] = $verb;
1814 // Diaspora doesn't provide a date for likes
1815 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
1817 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1818 if ($toplevel_parent_item['gravity'] != Item::GRAVITY_PARENT) {
1819 $toplevel = Post::selectFirst(['origin'], ['id' => $toplevel_parent_item['parent']]);
1820 $origin = $toplevel['origin'];
1822 $origin = $toplevel_parent_item['origin'];
1825 // If we are the origin of the parent we store the original data.
1826 // We notify our followers during the item storage.
1828 $datarray['diaspora_signed_text'] = json_encode($data);
1831 if (Item::isTooOld($datarray)) {
1832 Logger::info('Like is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1836 $message_id = Item::insert($datarray);
1838 if ($message_id <= 0) {
1843 Logger::info('Stored like ' . $datarray['guid'] . ' with message id ' . $message_id);
1844 if ($datarray['uid'] == 0) {
1845 Item::distribute($message_id, json_encode($data));
1853 * Processes private messages
1855 * @param array $importer Array of the importer user
1856 * @param SimpleXMLElement $data The message object
1858 * @return bool Success?
1859 * @throws \Exception
1861 private static function receiveMessage(array $importer, SimpleXMLElement $data): bool
1863 $author = WebFingerUri::fromString(XML::unescape($data->author));
1864 $guid = XML::unescape($data->guid);
1865 $conversation_guid = XML::unescape($data->conversation_guid);
1866 $text = XML::unescape($data->text);
1867 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1869 $contact = self::allowedContactByHandle($importer, $author, true);
1874 if (!empty($contact['gsid'])) {
1875 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1878 $condition = ['uid' => $importer['uid'], 'guid' => $conversation_guid];
1879 $conversation = DBA::selectFirst('conv', [], $condition);
1880 if (!DBA::isResult($conversation)) {
1881 Logger::notice('Conversation not available.');
1885 $person = FContact::getByURL($author);
1887 Logger::notice('Unable to find author details');
1891 $body = Markdown::toBBCode($text);
1893 $body = self::replacePeopleGuid($body, $person['url']);
1895 return Mail::insert([
1896 'uid' => $importer['uid'],
1898 'convid' => $conversation['id'],
1899 'from-name' => $person['name'],
1900 'from-photo' => $person['photo'],
1901 'from-url' => $person['url'],
1902 'contact-id' => $contact['id'],
1903 'title' => $conversation['subject'],
1906 'uri' => $author . ':' . $guid,
1907 'parent-uri' => $author . ':' . $conversation['guid'],
1908 'created' => $created_at
1913 * Processes participations - unsupported by now
1915 * @param array $importer Array of the importer user
1916 * @param SimpleXMLElement $data The message object
1917 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1919 * @return bool success
1920 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1921 * @throws \ImagickException
1923 private static function receiveParticipation(array $importer, SimpleXMLElement $data, int $direction): bool
1925 $author = WebFingerUri::fromString(strtolower(XML::unescape($data->author)));
1926 $guid = XML::unescape($data->guid);
1927 $parent_guid = XML::unescape($data->parent_guid);
1929 $contact = self::allowedContactByHandle($importer, $author, true);
1934 if (!empty($contact['gsid'])) {
1935 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1938 if (self::messageExists($importer['uid'], $guid)) {
1942 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1943 if (!$toplevel_parent_item) {
1947 if (!$toplevel_parent_item['origin']) {
1948 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1951 if (!in_array($toplevel_parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
1952 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1956 $person = FContact::getByURL($author);
1957 if (!is_array($person)) {
1958 Logger::notice('Person not found: ' . $author);
1962 $author_contact = self::authorContactByUrl($contact, $person['url'], $importer['uid']);
1964 // Store participation
1967 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1969 $datarray['uid'] = $importer['uid'];
1970 $datarray['contact-id'] = $author_contact['cid'];
1971 $datarray['network'] = $author_contact['network'];
1973 $datarray = self::setDirection($datarray, $direction);
1975 $datarray['owner-link'] = $datarray['author-link'] = $person['url'];
1976 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($person['url'], 0);
1978 $datarray['guid'] = $guid;
1979 $datarray['uri'] = self::getUriFromGuid($guid, $author);
1981 $datarray['verb'] = Activity::FOLLOW;
1982 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
1983 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1985 $datarray['object-type'] = Activity\ObjectType::NOTE;
1987 $datarray['body'] = Activity::FOLLOW;
1989 // Diaspora doesn't provide a date for a participation
1990 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
1992 if (Item::isTooOld($datarray)) {
1993 Logger::info('Participation is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1997 $message_id = Item::insert($datarray);
1999 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
2001 // Send all existing comments and likes to the requesting server
2002 $comments = Post::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb', 'gravity'],
2003 ['parent' => $toplevel_parent_item['id'], 'gravity' => [Item::GRAVITY_COMMENT, Item::GRAVITY_ACTIVITY]]);
2004 while ($comment = Post::fetch($comments)) {
2005 if (($comment['gravity'] == Item::GRAVITY_ACTIVITY) && !in_array($comment['verb'], [Activity::LIKE, Activity::DISLIKE])) {
2006 Logger::info('Unsupported activities are not relayed', ['item' => $comment['id'], 'verb' => $comment['verb']]);
2010 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
2011 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2015 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
2016 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2020 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact['cid']]);
2021 if (Worker::add(Worker::PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['uri-id'], $author_contact['cid'], $datarray['uid'])) {
2022 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2025 DBA::close($comments);
2031 * Processes photos - unneeded
2033 * @param array $importer Array of the importer user
2034 * @param SimpleXMLElement $data The message object
2036 * @return bool always true
2038 private static function receivePhoto(array $importer, $data)
2040 // There doesn't seem to be a reason for this function,
2041 // since the photo data is transmitted in the status message as well
2046 * Processes poll participations - unssupported
2048 * @param array $importer Array of the importer user
2049 * @param object $data The message object
2051 * @return bool always true
2053 private static function receivePollParticipation(array $importer, $data)
2055 // We don't support polls by now
2060 * Processes incoming profile updates
2062 * @param array $importer Array of the importer user
2063 * @param SimpleXMLElement $data The message object
2065 * @return bool Success
2066 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2067 * @throws \ImagickException
2069 private static function receiveProfile(array $importer, SimpleXMLElement $data): bool
2071 $author = WebFingerUri::fromString(strtolower(XML::unescape($data->author)));
2073 $contact = self::contactByHandle($importer['uid'], $author);
2078 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? ' ' . XML::unescape($data->last_name) : '');
2079 $image_url = XML::unescape($data->image_url);
2080 $birthday = XML::unescape($data->birthday);
2081 $about = Markdown::toBBCode(XML::unescape($data->bio));
2082 $location = Markdown::toBBCode(XML::unescape($data->location));
2083 $searchable = (XML::unescape($data->searchable) == 'true');
2084 $nsfw = (XML::unescape($data->nsfw) == 'true');
2085 $tags = XML::unescape($data->tag_string);
2087 $tags = explode('#', $tags);
2090 foreach ($tags as $tag) {
2091 $tag = trim(strtolower($tag));
2097 $keywords = implode(', ', $keywords);
2100 $name = $author->getUser();
2103 if (preg_match('|^https?://|', $image_url) === 0) {
2104 // @TODO No HTTPS here?
2105 $image_url = 'http://' . $author->getFullHost() . $image_url;
2108 Contact::updateAvatar($contact['id'], $image_url);
2110 // Generic birthday. We don't know the timezone. The year is irrelevant.
2112 $birthday = str_replace('1000', '1901', $birthday);
2114 if ($birthday != '') {
2115 $birthday = DateTimeFormat::utc($birthday, 'Y-m-d');
2118 // this is to prevent multiple birthday notifications in a single year
2119 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2121 if (substr($birthday, 5) === substr($contact['bd'], 5)) {
2122 $birthday = $contact['bd'];
2125 $fields = ['name' => $name, 'location' => $location,
2126 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2127 'addr' => $author->getAddr(), 'nick' => $author->getUser(), 'keywords' => $keywords,
2128 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2130 if (!empty($birthday)) {
2131 $fields['bd'] = $birthday;
2134 Contact::update($fields, ['id' => $contact['id']]);
2136 Logger::info('Profile of contact ' . $contact['id'] . ' stored for user ' . $importer['uid']);
2142 * Processes incoming friend requests
2144 * @param array $importer Array of the importer user
2145 * @param array $contact The contact that send the request
2147 * @throws \Exception
2149 private static function receiveRequestMakeFriend(array $importer, array $contact)
2151 if ($contact['rel'] == Contact::SHARING) {
2153 ['rel' => Contact::FRIEND, 'writable' => true],
2154 ['id' => $contact['id'], 'uid' => $importer['uid']]
2160 * Processes incoming sharing notification
2162 * @param array $importer Array of the importer user
2163 * @param SimpleXMLElement $data The message object
2165 * @return bool Success
2166 * @throws \Exception
2168 private static function receiveContactRequest(array $importer, SimpleXMLElement $data): bool
2170 $author_handle = XML::unescape($data->author);
2171 $recipient = XML::unescape($data->recipient);
2173 if (!$author_handle || !$recipient) {
2177 $author = WebFingerUri::fromString($author_handle);
2179 // the current protocol version doesn't know these fields
2180 // That means that we will assume their existance
2181 if (isset($data->following)) {
2182 $following = (XML::unescape($data->following) == 'true');
2187 if (isset($data->sharing)) {
2188 $sharing = (XML::unescape($data->sharing) == 'true');
2193 $contact = self::contactByHandle($importer['uid'], $author);
2195 // perhaps we were already sharing with this person. Now they're sharing with us.
2196 // That makes us friends.
2199 Logger::info('Author ' . $author . ' (Contact ' . $contact['id'] . ') wants to follow us.');
2200 self::receiveRequestMakeFriend($importer, $contact);
2202 // refetch the contact array
2203 $contact = self::contactByHandle($importer['uid'], $author);
2205 // If we are now friends, we are sending a share message.
2206 // Normally we needn't to do so, but the first message could have been vanished.
2207 if (in_array($contact['rel'], [Contact::FRIEND])) {
2208 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2209 if (DBA::isResult($user)) {
2210 Logger::info('Sending share message to author ' . $author . ' - Contact: ' . $contact['id'] . ' - User: ' . $importer['uid']);
2211 self::sendShare($user, $contact);
2216 Logger::info("Author " . $author . " doesn't want to follow us anymore.");
2217 Contact::removeFollower($contact);
2222 if (!$following && $sharing && in_array($importer['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2223 Logger::info("Author " . $author . " wants to share with us - but doesn't want to listen. Request is ignored.");
2225 } elseif (!$following && !$sharing) {
2226 Logger::info("Author " . $author . " doesn't want anything - and we don't know the author. Request is ignored.");
2228 } elseif (!$following && $sharing) {
2229 Logger::info("Author " . $author . " wants to share with us.");
2230 } elseif ($following && $sharing) {
2231 Logger::info("Author " . $author . " wants to have a bidirectional conection.");
2232 } elseif ($following && !$sharing) {
2233 Logger::info("Author " . $author . " wants to listen to us.");
2236 $ret = FContact::getByURL($author);
2238 if (!$ret || ($ret['network'] != Protocol::DIASPORA)) {
2239 Logger::notice("Cannot resolve diaspora handle " . $author . " for ".$recipient);
2243 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2245 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2250 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2251 'author-link' => $ret['url']];
2253 $result = Contact::addRelationship($importer, $contact, $item, false);
2254 if ($result === true) {
2255 $contact_record = self::contactByHandle($importer['uid'], $author);
2256 if (!$contact_record) {
2257 Logger::info('unable to locate newly created contact record.');
2261 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2262 if (DBA::isResult($user)) {
2263 self::sendShare($user, $contact_record);
2265 // Send the profile data, maybe it weren't transmitted before
2266 self::sendProfile($importer['uid'], [$contact_record]);
2274 * Stores a reshare activity
2276 * @param array $item Array of reshare post
2277 * @param integer $parent_message_id Id of the parent post
2278 * @param string $guid GUID string of reshare action
2279 * @param WebFingerUri $author Author handle
2280 * @return false|void
2281 * @throws InternalServerErrorException
2282 * @throws \ImagickException
2284 private static function addReshareActivity(array $item, int $parent_message_id, string $guid, WebFingerUri $author)
2286 $parent = Post::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2290 $datarray['uid'] = $item['uid'];
2291 $datarray['contact-id'] = $item['contact-id'];
2292 $datarray['network'] = $item['network'];
2294 $datarray['author-link'] = $item['author-link'];
2295 $datarray['author-id'] = $item['author-id'];
2297 $datarray['owner-link'] = $datarray['author-link'];
2298 $datarray['owner-id'] = $datarray['author-id'];
2300 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2301 $datarray['uri'] = self::getUriFromGuid($datarray['guid'], $author);
2302 $datarray['thr-parent'] = $parent['uri'];
2304 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2305 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
2306 $datarray['object-type'] = Activity\ObjectType::NOTE;
2308 $datarray['protocol'] = $item['protocol'];
2309 $datarray['source'] = $item['source'];
2310 $datarray['direction'] = $item['direction'];
2311 $datarray['post-reason'] = $item['post-reason'];
2313 $datarray['plink'] = self::plink($author, $datarray['guid']);
2314 $datarray['private'] = $item['private'];
2315 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2317 if (Item::isTooOld($datarray)) {
2318 Logger::info('Reshare activity is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2322 $message_id = Item::insert($datarray);
2325 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2326 if ($datarray['uid'] == 0) {
2327 Item::distribute($message_id);
2333 * Processes a reshare message
2335 * @param array $importer Array of the importer user
2336 * @param SimpleXMLElement $data The message object
2337 * @param string $xml The original XML of the message
2338 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2340 * @return bool Success or failure
2341 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2342 * @throws \ImagickException
2344 private static function receiveReshare(array $importer, SimpleXMLElement $data, string $xml, int $direction): bool
2346 $author = WebFingerUri::fromString(XML::unescape($data->author));
2347 $guid = XML::unescape($data->guid);
2348 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2349 $root_author = XML::unescape($data->root_author);
2350 $root_guid = XML::unescape($data->root_guid);
2351 /// @todo handle unprocessed property "provider_display_name"
2352 $public = XML::unescape($data->public);
2354 $contact = self::allowedContactByHandle($importer, $author);
2359 if (!empty($contact['gsid'])) {
2360 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2363 $message_id = self::messageExists($importer['uid'], $guid);
2368 $original_person = FContact::getByURL($root_author);
2369 if (!$original_person) {
2375 $datarray['uid'] = $importer['uid'];
2376 $datarray['contact-id'] = $contact['id'];
2377 $datarray['network'] = Protocol::DIASPORA;
2379 $datarray['author-link'] = $contact['url'];
2380 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2382 $datarray['owner-link'] = $datarray['author-link'];
2383 $datarray['owner-id'] = $datarray['author-id'];
2385 $datarray['guid'] = $guid;
2386 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($guid, $author);
2387 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2389 $datarray['verb'] = Activity::POST;
2390 $datarray['gravity'] = Item::GRAVITY_PARENT;
2392 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2393 $datarray['source'] = $xml;
2395 $datarray = self::setDirection($datarray, $direction);
2397 $datarray['quote-uri-id'] = self::getQuoteUriId($root_guid, $importer['uid'], $original_person['url']);
2398 if (empty($datarray['quote-uri-id'])) {
2402 $datarray['body'] = '';
2403 $datarray['plink'] = self::plink($author, $guid);
2404 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2405 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2407 self::fetchGuid($datarray);
2409 if (Item::isTooOld($datarray)) {
2410 Logger::info('Reshare is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2414 $message_id = Item::insert($datarray);
2416 self::sendParticipation($contact, $datarray);
2418 $root_message_id = self::messageExists($importer['uid'], $root_guid);
2419 if ($root_message_id) {
2420 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2424 Logger::info('Stored reshare ' . $datarray['guid'] . ' with message id ' . $message_id);
2425 if ($datarray['uid'] == 0) {
2426 Item::distribute($message_id);
2434 private static function getQuoteUriId(string $guid, int $uid, string $host): int
2436 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2438 if (!DBA::isResult($shared_item) && !empty($host) && Diaspora::storeByGuid($guid, $host, true)) {
2439 Logger::debug('Fetched post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2440 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2441 } elseif (DBA::isResult($shared_item)) {
2442 Logger::debug('Found existing post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2445 if (!DBA::isResult($shared_item)) {
2446 Logger::notice('Post does not exist.', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2450 return $shared_item['uri-id'];
2454 * Processes retractions
2456 * @param array $importer Array of the importer user
2457 * @param array $contact The contact of the item owner
2458 * @param SimpleXMLElement $data The message object
2460 * @return bool success
2461 * @throws \Exception
2463 private static function itemRetraction(array $importer, array $contact, SimpleXMLElement $data): bool
2465 $author_handle = XML::unescape($data->author);
2466 $target_guid = XML::unescape($data->target_guid);
2467 $target_type = XML::unescape($data->target_type);
2469 $person = FContact::getByURL($author_handle);
2470 if (!is_array($person)) {
2471 Logger::notice('Unable to find author detail for ' . $author_handle);
2475 if (empty($contact['url'])) {
2476 $contact['url'] = $person['url'];
2479 // Fetch items that are about to be deleted
2480 $fields = ['uid', 'id', 'parent', 'author-link', 'uri-id'];
2482 // When we receive a public retraction, we delete every item that we find.
2483 if ($importer['uid'] == 0) {
2484 $condition = ['guid' => $target_guid, 'deleted' => false];
2486 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2489 $r = Post::select($fields, $condition);
2490 if (!DBA::isResult($r)) {
2491 Logger::notice('Target guid ' . $target_guid . ' was not found on this system for user ' . $importer['uid'] . '.');
2495 while ($item = Post::fetch($r)) {
2496 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2497 Logger::info("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.");
2501 // Fetch the parent item
2502 $parent = Post::selectFirst(['author-link'], ['id' => $item['parent']]);
2504 // Only delete it if the parent author really fits
2505 if (!Strings::compareLink($parent['author-link'], $contact['url']) && !Strings::compareLink($item['author-link'], $contact['url'])) {
2506 Logger::info("Thread author " . $parent['author-link'] . " and item author " . $item['author-link'] . " don't fit to expected contact " . $contact['url']);
2510 Item::markForDeletion(['id' => $item['id']]);
2512 Logger::info('Deleted target ' . $target_guid . ' (' . $item['id'] . ') from user ' . $item['uid'] . ' parent: ' . $item['parent']);
2520 * Receives retraction messages
2522 * @param array $importer Array of the importer user
2523 * @param WebFingerUri $sender The sender of the message
2524 * @param SimpleXMLElement $data The message object
2526 * @return bool Success
2527 * @throws \Exception
2529 private static function receiveRetraction(array $importer, WebFingerUri $sender, SimpleXMLElement $data)
2531 $target_type = XML::unescape($data->target_type);
2533 $contact = self::contactByHandle($importer['uid'], $sender);
2534 if (!$contact && (in_array($target_type, ['Contact', 'Person']))) {
2535 Logger::notice('Cannot find contact for sender: ' . $sender . ' and user ' . $importer['uid']);
2543 Logger::info('Got retraction for ' . $target_type . ', sender ' . $sender . ' and user ' . $importer['uid']);
2545 switch ($target_type) {
2550 case 'StatusMessage':
2551 return self::itemRetraction($importer, $contact, $data);
2553 case 'PollParticipation':
2555 // Currently unsupported
2559 Logger::notice('Unknown target type ' . $target_type);
2566 * Checks if an incoming message is wanted
2568 * @param array $item
2569 * @param string $author
2570 * @param string $body
2571 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2573 * @return boolean Is the message wanted?
2575 private static function isSolicitedMessage(array $item, string $author, string $body, int $direction): bool
2577 $contact = Contact::getByURL($author);
2578 if (DBA::exists('contact', ['`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)', $contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) {
2579 Logger::debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2583 if ($direction == self::FORCED_FETCH) {
2584 Logger::debug('Post is a forced fetch - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2588 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
2589 if (Relay::isSolicitedPost($tags, $body, $contact['id'], $item['uri'], Protocol::DIASPORA)) {
2590 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2598 * Store an attached photo in the post-media table
2601 * @param object $photo
2604 private static function storePhotoAsMedia(int $uriid, $photo)
2606 // @TODO Need to find object type, roland@f.haeder.net
2607 Logger::debug('photo='.get_class($photo));
2609 $data['uri-id'] = $uriid;
2610 $data['type'] = Post\Media::IMAGE;
2611 $data['url'] = XML::unescape($photo->remote_photo_path) . XML::unescape($photo->remote_photo_name);
2612 $data['height'] = (int)XML::unescape($photo->height ?? 0);
2613 $data['width'] = (int)XML::unescape($photo->width ?? 0);
2614 $data['description'] = XML::unescape($photo->text ?? '');
2616 Post\Media::insert($data);
2620 * Set direction and post reason
2622 * @param array $datarray
2623 * @param integer $direction
2627 public static function setDirection(array $datarray, int $direction): array
2629 $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
2631 if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
2632 $datarray['post-reason'] = Item::PR_FETCHED;
2633 } elseif ($datarray['uid'] == 0) {
2634 $datarray['post-reason'] = Item::PR_GLOBAL;
2636 $datarray['post-reason'] = Item::PR_PUSHED;
2643 * Receives status messages
2645 * @param array $importer Array of the importer user
2646 * @param SimpleXMLElement $data The message object
2647 * @param string $xml The original XML of the message
2648 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2650 * @return int|bool The message id of the newly created item or false on error
2651 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2652 * @throws \ImagickException
2654 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, string $xml, int $direction)
2656 $author = WebFingerUri::fromString(XML::unescape($data->author));
2657 $guid = XML::unescape($data->guid);
2658 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2659 $public = XML::unescape($data->public);
2660 $text = XML::unescape($data->text);
2661 $provider_display_name = XML::unescape($data->provider_display_name);
2663 $contact = self::allowedContactByHandle($importer, $author);
2668 if (!empty($contact['gsid'])) {
2669 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2672 $message_id = self::messageExists($importer['uid'], $guid);
2678 if ($data->location) {
2679 foreach ($data->location->children() as $fieldname => $data) {
2680 $address[$fieldname] = XML::unescape($data);
2684 $raw_body = $body = Markdown::toBBCode($text);
2688 $datarray['guid'] = $guid;
2689 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($guid, $author);
2690 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2692 // Attach embedded pictures to the body
2694 foreach ($data->photo as $photo) {
2695 self::storePhotoAsMedia($datarray['uri-id'], $photo);
2698 $datarray['object-type'] = Activity\ObjectType::IMAGE;
2699 $datarray['post-type'] = Item::PT_IMAGE;
2700 } elseif ($data->poll) {
2701 $datarray['object-type'] = Activity\ObjectType::NOTE;
2702 $datarray['post-type'] = Item::PT_POLL;
2704 $datarray['object-type'] = Activity\ObjectType::NOTE;
2705 $datarray['post-type'] = Item::PT_NOTE;
2708 /// @todo enable support for polls
2709 //if ($data->poll) {
2710 // foreach ($data->poll as $poll)
2715 /// @todo enable support for events
2717 $datarray['uid'] = $importer['uid'];
2718 $datarray['contact-id'] = $contact['id'];
2719 $datarray['network'] = Protocol::DIASPORA;
2721 $datarray['author-link'] = $contact['url'];
2722 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2724 $datarray['owner-link'] = $datarray['author-link'];
2725 $datarray['owner-id'] = $datarray['author-id'];
2727 $datarray['verb'] = Activity::POST;
2728 $datarray['gravity'] = Item::GRAVITY_PARENT;
2730 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2731 $datarray['source'] = $xml;
2733 $datarray = self::setDirection($datarray, $direction);
2735 $datarray['body'] = self::replacePeopleGuid($body, $contact['url']);
2736 $datarray['raw-body'] = self::replacePeopleGuid($raw_body, $contact['url']);
2738 self::storeMentions($datarray['uri-id'], $text);
2739 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
2741 if (!self::isSolicitedMessage($datarray, $author, $body, $direction)) {
2742 DBA::delete('item-uri', ['uri' => $datarray['uri']]);
2746 if ($provider_display_name != '') {
2747 $datarray['app'] = $provider_display_name;
2750 $datarray['plink'] = self::plink($author, $guid);
2751 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2752 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2754 if (isset($address['address'])) {
2755 $datarray['location'] = $address['address'];
2758 if (isset($address['lat']) && isset($address['lng'])) {
2759 $datarray['coord'] = $address['lat'] . ' ' . $address['lng'];
2762 self::fetchGuid($datarray);
2764 if (Item::isTooOld($datarray)) {
2765 Logger::info('Status is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2769 $message_id = Item::insert($datarray);
2771 self::sendParticipation($contact, $datarray);
2774 Logger::info('Stored item ' . $datarray['guid'] . ' with message id ' . $message_id);
2775 if ($datarray['uid'] == 0) {
2776 Item::distribute($message_id);
2784 /* ************************************************************************************** *
2785 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2786 * ************************************************************************************** */
2789 * returnes the handle of a contact
2791 * @param array $contact contact array
2793 * @return string the handle in the format user@domain.tld
2794 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2796 private static function myHandle(array $contact): string
2798 if (!empty($contact['addr'])) {
2799 return $contact['addr'];
2802 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2803 // So - just in case - we build the the address here.
2804 if ($contact['nickname'] != '') {
2805 $nick = $contact['nickname'];
2807 $nick = $contact['nick'];
2810 return $nick . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
2815 * Creates the data for a private message in the new format
2817 * @param string $msg The message that is to be transmitted
2818 * @param array $user The record of the sender
2819 * @param array $contact Target of the communication
2820 * @param string $prvkey The private key of the sender
2821 * @param string $pubkey The public key of the receiver
2823 * @return string The encrypted data
2824 * @throws \Exception
2826 public static function encodePrivateData(string $msg, array $user, array $contact, string $prvkey, string $pubkey): string
2828 Logger::debug('Message: ' . $msg);
2830 // without a public key nothing will work
2832 Logger::notice('pubkey missing: contact id: ' . $contact['id']);
2836 $aes_key = random_bytes(32);
2837 $b_aes_key = base64_encode($aes_key);
2838 $iv = random_bytes(16);
2839 $b_iv = base64_encode($iv);
2841 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2843 $json = json_encode(['iv' => $b_iv, 'key' => $b_aes_key]);
2845 $encrypted_key_bundle = '';
2846 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
2850 $json_object = json_encode(
2852 'aes_key' => base64_encode($encrypted_key_bundle),
2853 'encrypted_magic_envelope' => base64_encode($ciphertext)
2857 return $json_object;
2861 * Creates the envelope for the "fetch" endpoint and for the new format
2863 * @param string $msg The message that is to be transmitted
2864 * @param array $user The record of the sender
2866 * @return string The envelope
2867 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2869 public static function buildMagicEnvelope(string $msg, array $user): string
2871 $b64url_data = Strings::base64UrlEncode($msg);
2872 $data = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
2874 $key_id = Strings::base64UrlEncode(self::myHandle($user));
2875 $type = 'application/xml';
2876 $encoding = 'base64url';
2877 $alg = 'RSA-SHA256';
2878 $signable_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
2880 // Fallback if the private key wasn't transmitted in the expected field
2881 if ($user['uprvkey'] == '') {
2882 $user['uprvkey'] = $user['prvkey'];
2885 $signature = Crypto::rsaSign($signable_data, $user['uprvkey']);
2886 $sig = Strings::base64UrlEncode($signature);
2891 '@attributes' => ['type' => $type],
2892 'me:encoding' => $encoding,
2895 '@attributes2' => ['key_id' => $key_id]
2899 $namespaces = ['me' => ActivityNamespace::SALMON_ME];
2901 return XML::fromArray($xmldata, $xml, false, $namespaces);
2905 * Create the envelope for a message
2907 * @param string $msg The message that is to be transmitted
2908 * @param array $user The record of the sender
2909 * @param array $contact Target of the communication
2910 * @param string $prvkey The private key of the sender
2911 * @param string $pubkey The public key of the receiver
2912 * @param bool $public Is the message public?
2914 * @return string The message that will be transmitted to other servers
2915 * @throws \Exception
2917 public static function buildMessage(string $msg, array $user, array $contact, string $prvkey, string $pubkey, bool $public = false): string
2919 // The message is put into an envelope with the sender's signature
2920 $envelope = self::buildMagicEnvelope($msg, $user);
2922 // Private messages are put into a second envelope, encrypted with the receivers public key
2924 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
2931 * Creates a signature for a message
2933 * @param array $owner the array of the owner of the message
2934 * @param array $message The message that is to be signed
2936 * @return string The signature
2938 private static function signature(array $owner, array $message): string
2941 unset($sigmsg['author_signature']);
2942 unset($sigmsg['parent_author_signature']);
2944 $signed_text = implode(';', $sigmsg);
2946 return base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
2950 * Transmit a message to a target server
2952 * @param array $owner the array of the item owner
2953 * @param array $contact Target of the communication
2954 * @param string $envelope The message that is to be transmitted
2955 * @param bool $public_batch Is it a public post?
2956 * @param string $guid message guid
2958 * @return int Result of the transmission
2959 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2960 * @throws \ImagickException
2962 private static function transmit(array $owner, array $contact, string $envelope, bool $public_batch, string $guid = ''): int
2964 $enabled = intval(DI::config()->get('system', 'diaspora_enabled'));
2969 $logid = Strings::getRandomHex(4);
2971 // We always try to use the data from the fcontact table.
2972 // This is important for transmitting data to Friendica servers.
2973 if (!empty($contact['addr'])) {
2974 $fcontact = FContact::getByURL($contact['addr']);
2975 if (!empty($fcontact)) {
2976 $dest_url = ($public_batch ? $fcontact['batch'] : $fcontact['notify']);
2980 if (empty($dest_url)) {
2981 $dest_url = ($public_batch ? $contact['batch'] : $contact['notify']);
2985 Logger::notice('No URL for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2989 Logger::notice('transmit: ' . $logid . '-' . $guid . ' ' . $dest_url);
2991 if (!intval(DI::config()->get('system', 'diaspora_test'))) {
2992 $content_type = (($public_batch) ? 'application/magic-envelope+xml' : 'application/json');
2994 $postResult = DI::httpClient()->post($dest_url . '/', $envelope, ['Content-Type' => $content_type]);
2995 $return_code = $postResult->getReturnCode();
2997 Logger::notice('test_mode');
3001 Logger::notice('transmit: ' . $logid . '-' . $guid . ' to ' . $dest_url . ' returns: ' . $return_code);
3003 return $return_code ? $return_code : -1;
3008 * Build the post xml
3010 * @param string $type The message type
3011 * @param array $message The message data
3013 * @return string The post XML
3015 public static function buildPostXml(string $type, array $message): string
3017 $data = [$type => $message];
3019 return XML::fromArray($data, $xml);
3023 * Builds and transmit messages
3025 * @param array $owner the array of the item owner
3026 * @param array $contact Target of the communication
3027 * @param string $type The message type
3028 * @param array $message The message data
3029 * @param bool $public_batch Is it a public post?
3030 * @param string $guid message guid
3032 * @return int Result of the transmission
3033 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3034 * @throws \ImagickException
3036 private static function buildAndTransmit(array $owner, array $contact, string $type, array $message, bool $public_batch = false, string $guid = '')
3038 $msg = self::buildPostXml($type, $message);
3040 // Fallback if the private key wasn't transmitted in the expected field
3041 if (empty($owner['uprvkey'])) {
3042 $owner['uprvkey'] = $owner['prvkey'];
3045 // When sending content to Friendica contacts using the Diaspora protocol
3046 // we have to fetch the public key from the fcontact.
3047 // This is due to the fact that legacy DFRN had unique keys for every contact.
3048 $pubkey = $contact['pubkey'];
3049 if (!empty($contact['addr'])) {
3050 $fcontact = FContact::getByURL($contact['addr']);
3051 if (!empty($fcontact)) {
3052 $pubkey = $fcontact['pubkey'];
3055 // The "addr" field should always be filled.
3056 // If this isn't the case, it will raise a notice some lines later.
3057 // And in the log we will see where it came from and we can handle it there.
3058 Logger::notice('Empty addr', ['contact' => $contact ?? [], 'callstack' => System::callstack(20)]);
3061 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $pubkey ?? '', $public_batch);
3063 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3065 Logger::info('Transmitted message', ['owner' => $owner['uid'], 'target' => $contact['addr'], 'type' => $type, 'guid' => $guid, 'result' => $return_code]);
3067 return $return_code;
3071 * sends a participation (Used to get all further updates)
3073 * @param array $contact Target of the communication
3074 * @param array $item Item array
3076 * @return int The result of the transmission
3077 * @throws \Exception
3079 private static function sendParticipation(array $contact, array $item): int
3081 // Don't send notifications for private postings
3082 if ($item['private'] == Item::PRIVATE) {
3086 $cachekey = 'diaspora:sendParticipation:' . $item['guid'];
3088 $result = DI::cache()->get($cachekey);
3089 if (!is_null($result)) {
3093 // Fetch some user id to have a valid handle to transmit the participation.
3094 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3095 // If the item belongs to a user, we take this user id.
3096 if ($item['uid'] == 0) {
3097 // @todo Possibly use an administrator account?
3098 $condition = ['verified' => true, 'blocked' => false,
3099 'account_removed' => false, 'account_expired' => false, 'account-type' => User::ACCOUNT_TYPE_PERSON];
3100 $first_user = DBA::selectFirst('user', ['uid'], $condition, ['order' => ['uid']]);
3101 $owner = User::getOwnerDataById($first_user['uid']);
3103 $owner = User::getOwnerDataById($item['uid']);
3106 $author_handle = self::myHandle($owner);
3109 'author' => $author_handle,
3110 'guid' => System::createUUID(),
3111 'parent_type' => 'Post',
3112 'parent_guid' => $item['guid']
3115 Logger::info('Send participation for ' . $item['guid'] . ' by ' . $author_handle);
3117 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3118 DI::cache()->set($cachekey, $item['guid'], Duration::QUARTER_HOUR);
3120 return self::buildAndTransmit($owner, $contact, 'participation', $message);
3124 * sends an account migration
3126 * @param array $owner the array of the item owner
3127 * @param array $contact Target of the communication
3128 * @param int $uid User ID
3130 * @return int The result of the transmission
3131 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3132 * @throws \ImagickException
3134 public static function sendAccountMigration(array $owner, array $contact, int $uid): int
3136 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3137 $profile = self::createProfileData($uid);
3139 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3140 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
3143 'author' => $old_handle,
3144 'profile' => $profile,
3145 'signature' => $signature
3148 Logger::info('Send account migration', ['msg' => $message]);
3150 return self::buildAndTransmit($owner, $contact, 'account_migration', $message);
3154 * Sends a "share" message
3156 * @param array $owner the array of the item owner
3157 * @param array $contact Target of the communication
3159 * @return int The result of the transmission
3160 * @throws \Exception
3162 public static function sendShare(array $owner, array $contact): int
3165 * @todo support the different possible combinations of "following" and "sharing"
3166 * Currently, Diaspora only interprets the "sharing" field
3168 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3172 switch ($contact["rel"]) {
3173 case Contact::FRIEND:
3177 case Contact::SHARING:
3181 case Contact::FOLLOWER:
3188 'author' => self::myHandle($owner),
3189 'recipient' => $contact['addr'],
3190 'following' => 'true',
3194 Logger::info('Send share', ['msg' => $message]);
3196 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3200 * sends an "unshare"
3202 * @param array $owner the array of the item owner
3203 * @param array $contact Target of the communication
3205 * @return int The result of the transmission
3206 * @throws \Exception
3208 public static function sendUnshare(array $owner, array $contact): int
3211 'author' => self::myHandle($owner),
3212 'recipient' => $contact['addr'],
3213 'following' => 'false',
3214 'sharing' => 'false'
3217 Logger::info('Send unshare', ['msg' => $message]);
3219 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3223 * Fetch reshare details
3225 * @param array $item The message body that is to be check
3227 * @return array Reshare details (empty if the item is no reshare)
3228 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3229 * @throws \ImagickException
3231 public static function getReshareDetails(array $item): array
3233 $reshared = DI::contentItem()->getSharedPost($item, ['guid', 'network', 'author-addr']);
3234 if (empty($reshared)) {
3238 // Skip if it isn't a pure repeated messages or not a real reshare
3239 if (!empty($reshared['comment']) || !in_array($reshared['post']['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
3244 'root_handle' => strtolower($reshared['post']['author-addr']),
3245 'root_guid' => $reshared['post']['guid'],
3250 * Create an event array
3252 * @param integer $event_id The id of the event
3254 * @return array with event data
3255 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3257 private static function buildEvent(string $event_id): array
3259 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
3260 if (!DBA::isResult($event)) {
3266 $owner = User::getOwnerDataById($event['uid']);
3271 $eventdata['author'] = self::myHandle($owner);
3273 if ($event['guid']) {
3274 $eventdata['guid'] = $event['guid'];
3277 $mask = DateTimeFormat::ATOM;
3279 /// @todo - establish "all day" events in Friendica
3280 $eventdata['all_day'] = 'false';
3282 $eventdata['timezone'] = 'UTC';
3284 if ($event['start']) {
3285 $eventdata['start'] = DateTimeFormat::utc($event['start'], $mask);
3287 if ($event['finish'] && !$event['nofinish']) {
3288 $eventdata['end'] = DateTimeFormat::utc($event['finish'], $mask);
3290 if ($event['summary']) {
3291 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3293 if ($event['desc']) {
3294 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3296 if ($event['location']) {
3297 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3298 $coord = Map::getCoordinates($event['location']);
3301 $location['address'] = html_entity_decode(BBCode::toMarkdown($event['location']));
3302 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3303 $location['lat'] = $coord['lat'];
3304 $location['lng'] = $coord['lon'];
3306 $location['lat'] = 0;
3307 $location['lng'] = 0;
3309 $eventdata['location'] = $location;
3316 * Create a post (status message or reshare)
3318 * @param array $item The item that will be exported
3319 * @param array $owner the array of the item owner
3322 * 'type' -> Message type ("status_message" or "reshare")
3323 * 'message' -> Array of XML elements of the status
3324 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3325 * @throws \ImagickException
3327 public static function buildStatus(array $item, array $owner)
3329 $cachekey = 'diaspora:buildStatus:' . $item['guid'];
3331 $result = DI::cache()->get($cachekey);
3332 if (!is_null($result)) {
3336 $myaddr = self::myHandle($owner);
3338 $public = ($item['private'] == Item::PRIVATE ? 'false' : 'true');
3339 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3340 $edited = DateTimeFormat::utc($item['edited'] ?? $item['created'], DateTimeFormat::ATOM);
3342 // Detect a share element and do a reshare
3343 if (($item['private'] != Item::PRIVATE) && ($ret = self::getReshareDetails($item))) {
3345 'author' => $myaddr,
3346 'guid' => $item['guid'],
3347 'created_at' => $created,
3348 'root_author' => $ret['root_handle'],
3349 'root_guid' => $ret['root_guid'],
3350 'provider_display_name' => $item['app'],
3356 $title = $item['title'];
3357 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
3359 // Fetch the title from an attached link - if there is one
3360 if (empty($item['title']) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3361 $page_data = BBCode::getAttachmentData($item['body']);
3362 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3363 $title = $page_data['title'];
3367 // convert to markdown
3368 $body = html_entity_decode(BBCode::toMarkdown($body));
3371 if (strlen($title)) {
3372 $body = '### ' . html_entity_decode($title) . "\n\n" . $body;
3375 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]);
3376 if (!empty($attachments)) {
3377 $body .= "\n[hr]\n";
3378 foreach ($attachments as $attachment) {
3379 $body .= "[" . $attachment['description'] . "](" . $attachment['url'] . ")\n";
3385 if ($item['location'] != '')
3386 $location['address'] = $item['location'];
3388 if ($item['coord'] != '') {
3389 $coord = explode(' ', $item['coord']);
3390 $location['lat'] = $coord[0];
3391 $location['lng'] = $coord[1];
3395 'author' => $myaddr,
3396 'guid' => $item['guid'],
3397 'created_at' => $created,
3398 'edited_at' => $edited,
3399 'public' => $public,
3401 'provider_display_name' => $item['app'],
3402 'location' => $location
3405 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3406 if (!isset($location['lat']) || !isset($location['lng'])) {
3407 unset($message['location']);
3410 if ($item['event-id'] > 0) {
3411 $event = self::buildEvent($item['event-id']);
3412 if (count($event)) {
3413 $message['event'] = $event;
3415 if (!empty($event['location']['address']) &&
3416 !empty($event['location']['lat']) &&
3417 !empty($event['location']['lng'])) {
3418 $message['location'] = $event['location'];
3421 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3422 // $message['text'] = '';
3426 $type = 'status_message';
3431 'message' => $message
3434 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3439 private static function prependParentAuthorMention(string $body, string $profile_url): string
3441 $profile = Contact::getByURL($profile_url, false, ['addr', 'name']);
3442 if (!empty($profile['addr'])
3443 && !strstr($body, $profile['addr'])
3444 && !strstr($body, $profile_url)
3446 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3455 * @param array $item The item that will be exported
3456 * @param array $owner the array of the item owner
3457 * @param array $contact Target of the communication
3458 * @param bool $public_batch Is it a public post?
3460 * @return int The result of the transmission
3461 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3462 * @throws \ImagickException
3464 public static function sendStatus(array $item, array $owner, array $contact, bool $public_batch = false): int
3466 $status = self::buildStatus($item, $owner);
3468 return self::buildAndTransmit($owner, $contact, $status['type'], $status['message'], $public_batch, $item['guid']);
3472 * Creates a "like" object
3474 * @param array $item The item that will be exported
3475 * @param array $owner the array of the item owner
3477 * @return array|bool The data for a "like" or false on error
3478 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3480 private static function constructLike(array $item, array $owner)
3482 $parent = Post::selectFirst(['guid', 'uri', 'thr-parent'], ['uri' => $item['thr-parent']]);
3483 if (!DBA::isResult($parent)) {
3487 $target_type = ($parent['uri'] === $parent['thr-parent'] ? 'Post' : 'Comment');
3489 if ($item['verb'] === Activity::LIKE) {
3491 } elseif ($item['verb'] === Activity::DISLIKE) {
3492 $positive = 'false';
3496 'author' => self::myHandle($owner),
3497 'guid' => $item['guid'],
3498 'parent_guid' => $parent['guid'],
3499 'parent_type' => $target_type,
3500 'positive' => $positive,
3501 'author_signature' => '',
3506 * Creates an "EventParticipation" object
3508 * @param array $item The item that will be exported
3509 * @param array $owner the array of the item owner
3511 * @return array|bool The data for an "EventParticipation" or false on error
3512 * @throws \Exception
3514 private static function constructAttend(array $item, array $owner)
3516 $parent = Post::selectFirst(['guid'], ['uri' => $item['thr-parent']]);
3517 if (!DBA::isResult($parent)) {
3521 switch ($item['verb']) {
3522 case Activity::ATTEND:
3523 $attend_answer = 'accepted';
3525 case Activity::ATTENDNO:
3526 $attend_answer = 'declined';
3528 case Activity::ATTENDMAYBE:
3529 $attend_answer = 'tentative';
3532 Logger::warning('Unknown verb ' . $item['verb'] . ' in item ' . $item['guid']);
3537 'author' => self::myHandle($owner),
3538 'guid' => $item['guid'],
3539 'parent_guid' => $parent['guid'],
3540 'status' => $attend_answer,
3541 'author_signature' => ''
3546 * Creates the object for a comment
3548 * @param array $item The item that will be exported
3549 * @param array $owner the array of the item owner
3551 * @return array|false The data for a comment
3552 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3554 private static function constructComment(array $item, array $owner)
3556 $cachekey = 'diaspora:constructComment:' . $item['guid'];
3558 $result = DI::cache()->get($cachekey);
3559 if (!is_null($result)) {
3563 $toplevel_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3564 if (!DBA::isResult($toplevel_item)) {
3565 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3569 $thread_parent_item = $toplevel_item;
3570 if ($item['thr-parent'] != $item['parent-uri']) {
3571 $thread_parent_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3574 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
3576 // The replied to autor mention is prepended for clarity if:
3577 // - Item replied isn't yours
3578 // - Item is public or explicit mentions are disabled
3579 // - Implicit mentions are enabled
3581 $item['author-id'] != $thread_parent_item['author-id']
3582 && ($thread_parent_item['gravity'] != Item::GRAVITY_PARENT)
3583 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3584 && !DI::config()->get('system', 'disable_implicit_mentions')
3586 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3589 $text = html_entity_decode(BBCode::toMarkdown($body));
3590 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3591 $edited = DateTimeFormat::utc($item['edited'], DateTimeFormat::ATOM);
3594 'author' => self::myHandle($owner),
3595 'guid' => $item['guid'],
3596 'created_at' => $created,
3597 'edited_at' => $edited,
3598 'parent_guid' => $toplevel_item['guid'],
3600 'author_signature' => '',
3603 // Send the thread parent guid only if it is a threaded comment
3604 if ($item['thr-parent'] != $item['parent-uri']) {
3605 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3608 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3614 * Send a like or a comment
3616 * @param array $item The item that will be exported
3617 * @param array $owner the array of the item owner
3618 * @param array $contact Target of the communication
3619 * @param bool $public_batch Is it a public post?
3621 * @return int The result of the transmission
3622 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3623 * @throws \ImagickException
3625 public static function sendFollowup(array $item, array $owner, array $contact, bool $public_batch = false): int
3627 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3628 $message = self::constructAttend($item, $owner);
3629 $type = 'event_participation';
3630 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3631 $message = self::constructLike($item, $owner);
3633 } elseif (!in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
3634 $message = self::constructComment($item, $owner);
3638 if (empty($message)) {
3642 $message['author_signature'] = self::signature($owner, $message);
3644 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3648 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3650 * @param array $item The item that will be exported
3651 * @param array $owner the array of the item owner
3652 * @param array $contact Target of the communication
3653 * @param bool $public_batch Is it a public post?
3655 * @return int The result of the transmission
3656 * @throws \Exception
3658 public static function sendRelay(array $item, array $owner, array $contact, bool $public_batch = false): int
3660 if ($item['deleted']) {
3661 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3662 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3668 Logger::info('Got relayable data ' . $type . ' for item ' . $item['guid'] . ' (' . $item['id'] . ')');
3670 $msg = json_decode($item['signed_text'] ?? '', true);
3673 if (is_array($msg)) {
3674 foreach ($msg as $field => $data) {
3675 if (!$item['deleted']) {
3676 if ($field == 'diaspora_handle') {
3679 if ($field == 'target_type') {
3680 $field = 'parent_type';
3684 $message[$field] = $data;
3687 Logger::info('Signature text for item ' . $item['guid'] . ' (' . $item['id'] . ') could not be extracted: ' . $item['signed_text']);
3690 $message['parent_author_signature'] = self::signature($owner, $message);
3692 Logger::info('Relayed data', ['msg' => $message]);
3694 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3698 * Sends a retraction (deletion) of a message, like or comment
3700 * @param array $item The item that will be exported
3701 * @param array $owner the array of the item owner
3702 * @param array $contact Target of the communication
3703 * @param bool $public_batch Is it a public post?
3704 * @param bool $relay Is the retraction transmitted from a relay?
3706 * @return int The result of the transmission
3707 * @throws \Exception
3709 public static function sendRetraction(array $item, array $owner, array $contact, bool $public_batch = false, bool $relay = false): int
3711 $itemaddr = strtolower($item['author-addr']);
3713 $msg_type = 'retraction';
3715 if ($item['gravity'] == Item::GRAVITY_PARENT) {
3716 $target_type = 'Post';
3717 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3718 $target_type = 'Like';
3720 $target_type = 'Comment';
3724 'author' => $itemaddr,
3725 'target_guid' => $item['guid'],
3726 'target_type' => $target_type
3729 Logger::info('Got message', ['msg' => $message]);
3731 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item['guid']);
3737 * @param array $item The item that will be exported
3738 * @param array $owner The owner
3739 * @param array $contact Target of the communication
3741 * @return int The result of the transmission
3742 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3743 * @throws \ImagickException
3745 public static function sendMail(array $item, array $owner, array $contact): int
3747 $myaddr = self::myHandle($owner);
3749 $cnv = DBA::selectFirst('conv', [], ['id' => $item['convid'], 'uid' => $item['uid']]);
3750 if (!DBA::isResult($cnv)) {
3751 Logger::notice('Conversation not found.');
3755 $body = BBCode::toMarkdown($item['body']);
3756 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3759 'author' => $myaddr,
3760 'guid' => $item['guid'],
3761 'conversation_guid' => $cnv['guid'],
3763 'created_at' => $created,
3766 if ($item['reply']) {
3771 'author' => $cnv['creator'],
3772 'guid' => $cnv['guid'],
3773 'subject' => $cnv['subject'],
3774 'created_at' => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3775 'participants' => $cnv['recips'],
3779 $type = 'conversation';
3782 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item['guid']);
3786 * Split a name into first name and last name
3788 * @param string $name The name
3790 * @return array The array with "first" and "last"
3792 public static function splitName(string $name): array
3794 $name = trim($name);
3796 // Is the name longer than 64 characters? Then cut the rest of it.
3797 if (strlen($name) > 64) {
3798 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3799 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3801 $name = substr($name, 0, 64);
3805 // Take the first word as first name
3806 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3807 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3808 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3809 return ['first' => $first, 'last' => $last];
3812 // Take the last word as last name
3813 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3814 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3816 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3817 return ['first' => $first, 'last' => $last];
3820 // Take the first 32 characters if there is no space in the first 32 characters
3821 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3822 $first = substr($name, 0, 32);
3823 $last = substr($name, 32);
3824 return ['first' => $first, 'last' => $last];
3827 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3828 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3830 // Check if the last name is longer than 32 characters
3831 if (strlen($last) > 32) {
3832 if (strpos($last, ' ') <= 32) {
3833 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
3835 $last = substr($last, 0, 32);
3839 return ['first' => $first, 'last' => $last];
3843 * Create profile data
3845 * @param int $uid The user id
3847 * @return array The profile data
3848 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3850 private static function createProfileData(int $uid): array
3852 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
3854 if (!DBA::isResult($profile)) {
3858 $split_name = self::splitName($profile['name']);
3861 'author' => $profile['addr'],
3862 'first_name' => $split_name['first'],
3863 'last_name' => $split_name['last'],
3864 'image_url' => DI::baseUrl() . '/photo/custom/300/' . $profile['uid'] . '.jpg',
3865 'image_url_medium' => DI::baseUrl() . '/photo/custom/100/' . $profile['uid'] . '.jpg',
3866 'image_url_small' => DI::baseUrl() . '/photo/custom/50/' . $profile['uid'] . '.jpg',
3867 'searchable' => ($profile['net-publish'] ? 'true' : 'false'),
3871 'tag_string' => null,
3875 if ($data['searchable'] === 'true') {
3876 $data['birthday'] = '';
3878 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
3879 [$year, $month, $day] = sscanf($profile['dob'], '%4d-%2d-%2d');
3883 $data['birthday'] = DateTimeFormat::utc($year . '-' . $month . '-' . $day, 'Y-m-d');
3886 $data['about'] = BBCode::toMarkdown($profile['about'] ?? '');
3888 $data['location'] = $profile['location'];
3889 $data['tag_string'] = '';
3891 if ($profile['pub_keywords']) {
3892 $kw = str_replace(',', ' ', $profile['pub_keywords']);
3893 $kw = str_replace(' ', ' ', $kw);
3894 $arr = explode(' ', $kw);
3896 for ($x = 0; $x < 5; $x ++) {
3897 if (!empty($arr[$x])) {
3898 $data['tag_string'] .= '#'. trim($arr[$x]) .' ';
3903 $data['tag_string'] = trim($data['tag_string']);
3910 * Sends profile data
3912 * @param int $uid The user id
3913 * @param array $recipients optional, default empty array
3916 * @throws \Exception
3918 public static function sendProfile(int $uid, array $recipients = [])
3921 Logger::warning('Parameter "uid" is empty');
3925 $owner = User::getOwnerDataById($uid);
3926 if (empty($owner)) {
3927 Logger::warning('Cannot fetch User record', ['uid' => $uid]);
3931 if (empty($recipients)) {
3932 Logger::debug('No recipients provided, fetching for user', ['uid' => $uid]);
3933 $recipients = DBA::selectToArray('contact', [], ['network' => Protocol::DIASPORA, 'uid' => $uid, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
3936 if (empty($recipients)) {
3937 Logger::warning('Cannot fetch recipients', ['uid' => $uid]);
3941 $message = self::createProfileData($uid);
3943 // @todo Split this into single worker jobs
3944 foreach ($recipients as $recipient) {
3945 Logger::info('Send updated profile data for user ' . $uid . ' to contact ' . $recipient['id']);
3946 self::buildAndTransmit($owner, $recipient, 'profile', $message);
3951 * Creates the signature for likes that are created on our system
3953 * @param integer $uid The user of that comment
3954 * @param array $item Item array
3956 * @return array|bool Signed content or false on error
3957 * @throws \Exception
3959 public static function createLikeSignature(int $uid, array $item)
3961 $owner = User::getOwnerDataById($uid);
3962 if (empty($owner)) {
3963 Logger::info('No owner post, so not storing signature', ['uid' => $uid]);
3967 if (!in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3968 Logger::warning('Item is neither a like nor a dislike', ['uid' => $uid, 'item[verb]' => $item['verb']]);;
3972 $message = self::constructLike($item, $owner);
3973 if ($message === false) {
3977 $message['author_signature'] = self::signature($owner, $message);
3983 * Creates the signature for Comments that are created on our system
3985 * @param array $item Item array
3987 * @return array|bool Signed content or false on error
3988 * @throws \Exception
3990 public static function createCommentSignature(array $item)
3993 if (!empty($item['author-link'])) {
3994 $url = $item['author-link'];
3996 $contact = Contact::getById($item['author-id'], ['url']);
3997 if (empty($contact['url'])) {
3998 Logger::warning('Author Contact not found', ['author-id' => $item['author-id']]);
4001 $url = $contact['url'];
4004 $uid = User::getIdForURL($url);
4006 Logger::info('No owner post, so not storing signature', ['url' => $contact['url'] ?? 'No contact loaded']);
4010 $owner = User::getOwnerDataById($uid);
4011 if (empty($owner)) {
4012 Logger::info('No owner post, so not storing signature');
4016 // This is only needed for the automated tests
4017 if (empty($owner['uprvkey'])) {
4021 if (!self::parentSupportDiaspora($item['thr-parent-id'])) {
4022 Logger::info('One of the parents does not support Diaspora. A signature will not be created.', ['uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
4026 $message = self::constructComment($item, $owner);
4027 if ($message === false) {
4031 $message['author_signature'] = self::signature($owner, $message);
4037 * Check if the parent and their parents support Diaspora
4039 * @param integer $parent_id
4042 private static function parentSupportDiaspora(int $parent_id): bool
4044 $parent_post = Post::selectFirstPost(['gravity', 'signed_text', 'author-link', 'thr-parent-id'], ['uri-id' => $parent_id]);
4045 if (empty($parent_post['thr-parent-id'])) {
4046 Logger::warning('Parent post does not exist.', ['parent-id' => $parent_id]);
4050 if (empty(FContact::getByURL($parent_post['author-link'], false))) {
4051 Logger::info('Parent author is no Diaspora contact.', ['parent-id' => $parent_id]);
4055 if (($parent_post['gravity'] == Item::GRAVITY_COMMENT) && empty($parent_post['signed_text'])) {
4056 Logger::info('Parent comment has got no Diaspora signature.', ['parent-id' => $parent_id]);
4060 if ($parent_post['gravity'] == Item::GRAVITY_COMMENT) {
4061 return self::parentSupportDiaspora($parent_post['thr-parent-id']);
4067 public static function performReshare(int $UriId, int $uid): int
4069 $owner = User::getOwnerDataById($uid);
4070 $author = Contact::getPublicIdByUserId($uid);
4074 'verb' => Activity::POST,
4075 'contact-id' => $owner['id'],
4076 'author-id' => $author,
4077 'owner-id' => $author,
4079 'quote-uri-id' => $UriId,
4080 'allow_cid' => $owner['allow_cid'] ?? '',
4081 'allow_gid' => $owner['allow_gid']?? '',
4082 'deny_cid' => $owner['deny_cid'] ?? '',
4083 'deny_gid' => $owner['deny_gid'] ?? '',
4086 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
4087 $item['private'] = Item::PRIVATE;
4088 } elseif (DI::pConfig()->get($uid, 'system', 'unlisted')) {
4089 $item['private'] = Item::UNLISTED;
4091 $item['private'] = Item::PUBLIC;
4094 // Don't trigger the addons
4095 $item['api_source'] = false;
4097 return Item::insert($item, true);