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\Probe;
46 use Friendica\Util\Crypto;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Map;
49 use Friendica\Util\Network;
50 use Friendica\Util\Strings;
51 use Friendica\Util\XML;
52 use Friendica\Worker\Delivery;
53 use GuzzleHttp\Psr7\Uri;
57 * This class contain functions to create and send Diaspora XML files
63 const FORCED_FETCH = 2;
66 * Return a list of participating contacts for a thread
68 * This is used for the participation feature.
69 * One of the parameters is a contact array.
70 * This is done to avoid duplicates.
72 * @param array $item Item that is about to be delivered
73 * @param array $contacts The previously fetched contacts
75 * @return array of relay servers
78 public static function participantsForThread(array $item, array $contacts): array
80 if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
81 Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]);
85 $items = Post::select(['author-id', 'author-link', 'parent-author-link', 'parent-guid', 'guid'],
86 ['parent' => $item['parent'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
87 while ($item = Post::fetch($items)) {
88 $contact = DBA::selectFirst('contact', ['id', 'url', 'name', 'protocol', 'batch', 'network'],
89 ['id' => $item['author-id']]);
90 if (!DBA::isResult($contact) || empty($contact['batch']) ||
91 ($contact['network'] != Protocol::DIASPORA) ||
92 Strings::compareLink($item['parent-author-link'], $item['author-link'])) {
97 foreach ($contacts as $entry) {
98 if ($entry['batch'] == $contact['batch']) {
104 Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]);
105 $contacts[] = $contact;
114 * verify the envelope and return the verified data
116 * @param string $envelope The magic envelope
118 * @return string|bool verified data or false on error
119 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
120 * @throws \ImagickException
122 private static function verifyMagicEnvelope(string $envelope)
124 $basedom = XML::parseString($envelope, true);
126 if (!is_object($basedom)) {
127 Logger::notice("Envelope is no XML file");
131 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
133 if (sizeof($children) == 0) {
134 Logger::notice("XML has no children");
140 $data = Strings::base64UrlDecode($children->data);
141 $type = $children->data->attributes()->type[0];
143 $encoding = $children->encoding;
145 $alg = $children->alg;
147 $sig = Strings::base64UrlDecode($children->sig);
148 $key_id = $children->sig->attributes()->key_id[0];
150 $handle = Strings::base64UrlDecode($key_id);
153 $b64url_data = Strings::base64UrlEncode($data);
154 $msg = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
156 $signable_data = $msg . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
159 Logger::notice('No author could be decoded. Discarding. Message: ' . $envelope);
163 $key = self::key($handle);
165 Logger::notice("Couldn't get a key for handle " . $handle . ". Discarding.");
169 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
171 Logger::notice('Message from ' . $handle . ' did not verify. Discarding.');
179 * encrypts data via AES
181 * @param string $key The AES key
182 * @param string $iv The IV (is used for CBC encoding)
183 * @param string $data The data that is to be encrypted
185 * @return string encrypted data
187 private static function aesEncrypt(string $key, string $iv, string $data): string
189 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
193 * decrypts data via AES
195 * @param string $key The AES key
196 * @param string $iv The IV (is used for CBC encoding)
197 * @param string $encrypted The encrypted data
199 * @return string decrypted data
201 private static function aesDecrypt(string $key, string $iv, string $encrypted): string
203 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
207 * Decodes incoming Diaspora message in the new format. This method returns false on an error.
209 * @param string $raw raw post message
210 * @param string $privKey The private key of the importer
211 * @param boolean $no_exit Don't do an http exit on error
214 * 'message' -> decoded Diaspora XML message
215 * 'author' -> author diaspora handle
216 * 'key' -> author public key (converted to pkcs#8)
217 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
218 * @throws \ImagickException
220 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
222 $data = json_decode($raw);
224 // Is it a private post? Then decrypt the outer Salmon
225 if (is_object($data)) {
226 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
227 $ciphertext = base64_decode($data->encrypted_magic_envelope);
229 $outer_key_bundle = '';
230 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
231 $j_outer_key_bundle = json_decode($outer_key_bundle);
233 if (!is_object($j_outer_key_bundle)) {
234 Logger::notice('Outer Salmon did not verify. Discarding.');
238 throw new \Friendica\Network\HTTPException\BadRequestException();
242 $outer_iv = base64_decode($j_outer_key_bundle->iv);
243 $outer_key = base64_decode($j_outer_key_bundle->key);
245 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
250 $basedom = XML::parseString($xml, true);
252 if (!is_object($basedom)) {
253 Logger::notice('Received data does not seem to be an XML. Discarding. '.$xml);
257 throw new \Friendica\Network\HTTPException\BadRequestException();
261 $base = $basedom->children(ActivityNamespace::SALMON_ME);
263 // Not sure if this cleaning is needed
264 $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
266 // Build the signed data
267 $type = $base->data[0]->attributes()->type[0];
268 $encoding = $base->encoding;
270 $signed_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
272 // This is the signature
273 $signature = Strings::base64UrlDecode($base->sig);
275 // Get the senders' public key
276 $key_id = $base->sig[0]->attributes()->key_id[0];
277 $author_addr = base64_decode($key_id);
278 if ($author_addr == '') {
279 Logger::notice('No author could be decoded. Discarding. Message: ' . $xml);
283 throw new \Friendica\Network\HTTPException\BadRequestException();
287 $key = self::key($author_addr);
289 Logger::notice("Couldn't get a key for handle " . $author_addr . ". Discarding.");
293 throw new \Friendica\Network\HTTPException\BadRequestException();
297 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
299 Logger::notice('Message did not verify. Discarding.');
303 throw new \Friendica\Network\HTTPException\BadRequestException();
308 'message' => (string)Strings::base64UrlDecode($base->data),
309 'author' => XML::unescape($author_addr),
310 'key' => (string)$key
315 * Decodes incoming Diaspora message in the deprecated format
317 * @param string $xml urldecoded Diaspora salmon
318 * @param string $privKey The private key of the importer
321 * 'message' -> decoded Diaspora XML message
322 * 'author' -> author diaspora handle
323 * 'key' -> author public key (converted to pkcs#8)
324 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
325 * @throws \ImagickException
327 public static function decode(string $xml, string $privKey = '')
330 $basedom = XML::parseString($xml);
332 if (!is_object($basedom)) {
333 Logger::notice('XML is not parseable.');
336 $children = $basedom->children('https://joindiaspora.com/protocol');
338 $inner_aes_key = null;
341 if ($children->header) {
343 $author_link = str_replace('acct:', '', $children->header->author_id);
345 // This happens with posts from a relais
346 if (empty($privKey)) {
347 Logger::info('This is no private post in the old format');
351 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
353 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
354 $ciphertext = base64_decode($encrypted_header->ciphertext);
356 $outer_key_bundle = '';
357 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
359 $j_outer_key_bundle = json_decode($outer_key_bundle);
361 $outer_iv = base64_decode($j_outer_key_bundle->iv);
362 $outer_key = base64_decode($j_outer_key_bundle->key);
364 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
366 Logger::info('decrypted', ['data' => $decrypted]);
367 $idom = XML::parseString($decrypted);
369 $inner_iv = base64_decode($idom->iv);
370 $inner_aes_key = base64_decode($idom->aes_key);
372 $author_link = str_replace('acct:', '', $idom->author_id);
375 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
377 // figure out where in the DOM tree our data is hiding
380 if ($dom->provenance->data) {
381 $base = $dom->provenance;
382 } elseif ($dom->env->data) {
384 } elseif ($dom->data) {
389 Logger::notice('unable to locate salmon data in xml');
390 throw new \Friendica\Network\HTTPException\BadRequestException();
394 // Stash the signature away for now. We have to find their key or it won't be good for anything.
395 $signature = Strings::base64UrlDecode($base->sig);
399 // strip whitespace so our data element will return to one big base64 blob
400 $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
403 // stash away some other stuff for later
405 $type = $base->data[0]->attributes()->type[0];
406 $keyhash = $base->sig[0]->attributes()->keyhash[0];
407 $encoding = $base->encoding;
411 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
415 $data = Strings::base64UrlDecode($data);
419 $inner_decrypted = $data;
421 // Decode the encrypted blob
422 $inner_encrypted = base64_decode($data);
423 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
427 Logger::notice('Could not retrieve author URI.');
428 throw new \Friendica\Network\HTTPException\BadRequestException();
430 // Once we have the author URI, go to the web and try to find their public key
431 // (first this will look it up locally if it is in the fcontact cache)
432 // This will also convert diaspora public key from pkcs#1 to pkcs#8
434 Logger::notice('Fetching key for '.$author_link);
435 $key = self::key($author_link);
438 Logger::notice('Could not retrieve author key.');
439 throw new \Friendica\Network\HTTPException\BadRequestException();
442 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
445 Logger::notice('Message did not verify. Discarding.');
446 throw new \Friendica\Network\HTTPException\BadRequestException();
449 Logger::notice('Message verified.');
452 'message' => (string)$inner_decrypted,
453 'author' => XML::unescape($author_link),
454 'key' => (string)$key
460 * Dispatches public messages and find the fitting receivers
462 * @param array $msg The post that will be dispatched
463 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
465 * @return int|bool The message id of the generated message, "true" or "false" if there was an error
466 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
467 * @throws \ImagickException
469 public static function dispatchPublic(array $msg, int $direction)
471 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
473 Logger::notice("diaspora is disabled");
477 if (!($fields = self::validPosting($msg))) {
478 Logger::notice("Invalid posting");
484 'page-flags' => User::PAGE_FLAGS_FREELOVE
486 $success = self::dispatch($importer, $msg, $fields, $direction);
492 * Dispatches the different message types to the different functions
494 * @param array $importer Array of the importer user
495 * @param array $msg The post that will be dispatched
496 * @param SimpleXMLElement $fields SimpleXML object that contains the message
497 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
499 * @return int|bool The message id of the generated message, "true" or "false" if there was an error
500 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
501 * @throws \ImagickException
503 public static function dispatch(array $importer, array $msg, SimpleXMLElement $fields = null, int $direction = self::PUSHED)
505 // The sender is the handle of the contact that sent the message.
506 // This will often be different with relayed messages (for example "like" and "comment")
507 $sender = $msg['author'];
509 // This is only needed for private postings since this is already done for public ones before
510 if (is_null($fields)) {
512 if (!($fields = self::validPosting($msg))) {
513 Logger::notice("Invalid posting");
520 $type = $fields->getName();
522 Logger::info('Received message', ['type' => $type, 'sender' => $sender, 'user' => $importer['uid']]);
525 case 'account_migration':
527 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
530 return self::receiveAccountMigration($importer, $fields);
532 case 'account_deletion':
533 return self::receiveAccountDeletion($fields);
536 return self::receiveComment($importer, $sender, $fields, $msg['message'], $direction);
540 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
543 return self::receiveContactRequest($importer, $fields);
547 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
550 return self::receiveConversation($importer, $msg, $fields);
553 return self::receiveLike($importer, $sender, $fields, $direction);
557 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
560 return self::receiveMessage($importer, $fields);
562 case 'participation':
564 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
567 return self::receiveParticipation($importer, $fields, $direction);
569 case 'photo': // Not implemented
570 return self::receivePhoto($importer, $fields);
572 case 'poll_participation': // Not implemented
573 return self::receivePollParticipation($importer, $fields);
577 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
580 return self::receiveProfile($importer, $fields);
583 return self::receiveReshare($importer, $fields, $msg['message'], $direction);
586 return self::receiveRetraction($importer, $sender, $fields);
588 case 'status_message':
589 return self::receiveStatusMessage($importer, $fields, $msg['message'], $direction);
592 Logger::notice("Unknown message type " . $type);
598 * Checks if a posting is valid and fetches the data fields.
600 * This function does not only check the signature.
601 * It also does the conversion between the old and the new diaspora format.
603 * @param array $msg Array with the XML, the sender handle and the sender signature
605 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
606 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
607 * @throws \ImagickException
609 private static function validPosting(array $msg)
611 $data = XML::parseString($msg['message']);
613 if (!is_object($data)) {
614 Logger::info('No valid XML', ['message' => $msg['message']]);
618 // Is this the new or the old version?
619 if ($data->getName() == 'XML') {
621 foreach ($data->post->children() as $child) {
629 $type = $element->getName();
632 Logger::debug("Got message type " . $type . ": " . $msg['message']);
634 // All retractions are handled identically from now on.
635 // In the new version there will only be "retraction".
636 if (in_array($type, ['signed_retraction', 'relayable_retraction']))
637 $type = 'retraction';
639 if ($type == 'request') {
643 $fields = new SimpleXMLElement('<' . $type . '/>');
646 $author_signature = null;
647 $parent_author_signature = null;
649 foreach ($element->children() as $fieldname => $entry) {
651 // Translation for the old XML structure
652 if ($fieldname == 'diaspora_handle') {
653 $fieldname = 'author';
655 if ($fieldname == 'participant_handles') {
656 $fieldname = 'participants';
658 if (in_array($type, ['like', 'participation'])) {
659 if ($fieldname == 'target_type') {
660 $fieldname = 'parent_type';
663 if ($fieldname == 'sender_handle') {
664 $fieldname = 'author';
666 if ($fieldname == 'recipient_handle') {
667 $fieldname = 'recipient';
669 if ($fieldname == 'root_diaspora_id') {
670 $fieldname = 'root_author';
672 if ($type == 'status_message') {
673 if ($fieldname == 'raw_message') {
677 if ($type == 'retraction') {
678 if ($fieldname == 'post_guid') {
679 $fieldname = 'target_guid';
681 if ($fieldname == 'type') {
682 $fieldname = 'target_type';
687 if (($fieldname == 'author_signature') && ($entry != '')) {
688 $author_signature = base64_decode($entry);
689 } elseif (($fieldname == 'parent_author_signature') && ($entry != '')) {
690 $parent_author_signature = base64_decode($entry);
691 } elseif (!in_array($fieldname, ['author_signature', 'parent_author_signature', 'target_author_signature'])) {
692 if ($signed_data != '') {
696 $signed_data .= $entry;
698 if (!in_array($fieldname, ['parent_author_signature', 'target_author_signature'])
699 || ($orig_type == 'relayable_retraction')
701 XML::copy($entry, $fields, $fieldname);
705 // This is something that shouldn't happen at all.
706 if (in_array($type, ['status_message', 'reshare', 'profile'])) {
707 if ($msg['author'] != $fields->author) {
708 Logger::notice("Message handle is not the same as envelope sender. Quitting this message.");
713 // Only some message types have signatures. So we quit here for the other types.
714 if (!in_array($type, ['comment', 'like'])) {
717 // No author_signature? This is a must, so we quit.
718 if (!isset($author_signature)) {
719 Logger::info("No author signature for type " . $type . " - Message: " . $msg['message']);
723 if (isset($parent_author_signature)) {
724 $key = self::key($msg['author']);
726 Logger::info('No key found for parent', ['author' => $msg['author']]);
730 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, 'sha256')) {
731 Logger::info("No valid parent author signature for parent author " . $msg['author'] . " in type " . $type . " - signed data: " . $signed_data . " - Message: " . $msg['message'] . " - Signature " . $parent_author_signature);
736 $key = self::key($fields->author);
738 Logger::info('No key found', ['author' => $fields->author]);
742 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, 'sha256')) {
743 Logger::info("No valid author signature for author " . $fields->author . " in type " . $type . " - signed data: " . $signed_data . " - Message: " . $msg['message'] . " - Signature " . $author_signature);
751 * Fetches the public key for a given handle
753 * @param string $handle The handle
755 * @return string The public key
756 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
757 * @throws \ImagickException
759 private static function key(string $handle = null): string
761 $handle = strval($handle);
763 Logger::notice("Fetching diaspora key for: " . $handle);
765 $fcontact = FContact::getByURL($handle);
766 if (!empty($fcontact['pubkey'])) {
767 return $fcontact['pubkey'];
774 * get a handle (user@domain.tld) from a given contact id
776 * @param int $contact_id The id in the contact table
777 * @param int $pcontact_id The id in the contact table (Used for the public contact)
779 * @return string the handle
782 private static function handleFromContact(int $contact_id, int $pcontact_id = 0): string
786 if ($pcontact_id != 0) {
787 $contact = Contact::getById($pcontact_id, ['addr']);
788 if (DBA::isResult($contact)) {
789 $handle = $contact['addr'];
793 if (empty($handle)) {
794 $contact = Contact::getById($contact_id, ['addr']);
795 if (DBA::isResult($contact)) {
796 $handle = $contact['addr'];
800 return strtolower($handle);
804 * Get a contact id for a given handle
806 * @todo Move to Friendica\Model\Contact
808 * @param int $uid The user id
809 * @param string $handle The handle in the format user@domain.tld
811 * @return array Contact data
812 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
813 * @throws \ImagickException
815 private static function contactByHandle(int $uid, string $handle): array
817 return Contact::getByURL($handle, null, [], $uid);
821 * Checks if the given contact url does support ActivityPub
823 * @param string $url profile url
824 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
826 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
827 * @throws \ImagickException
829 public static function isSupportedByContactUrl(string $url, $update = null)
831 return !empty(FContact::getByURL($url, $update));
835 * Check if posting is allowed for this contact
837 * @param array $importer Array of the importer user
838 * @param array $contact The contact that is checked
839 * @param bool $is_comment Is the check for a comment?
841 * @return bool is the contact allowed to post?
843 private static function postAllow(array $importer, array $contact, bool $is_comment = false): bool
846 * Perhaps we were already sharing with this person. Now they're sharing with us.
847 * That makes us friends.
848 * Normally this should have handled by getting a request - but this could get lost
850 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
851 // It is not removed by now. Possibly the code is needed?
852 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
854 // array('rel' => Contact::FRIEND, 'writable' => true),
855 // array('id' => $contact["id"], 'uid' => $contact["uid"])
858 // $contact["rel"] = Contact::FRIEND;
859 // Logger::notice("defining user ".$contact["nick"]." as friend");
862 // Contact server is blocked
863 if (Network::isUrlBlocked($contact['url'])) {
865 // We don't seem to like that person
866 } elseif ($contact['blocked']) {
867 // Maybe blocked, don't accept.
869 // We are following this person?
870 } elseif (($contact['rel'] == Contact::SHARING) || ($contact['rel'] == Contact::FRIEND)) {
871 // Yes, then it is fine.
873 // Is the message a global user or a comment?
874 } elseif (($importer['uid'] == 0) || $is_comment) {
875 // Messages for the global users and comments are always accepted
883 * Fetches the contact id for a handle and checks if posting is allowed
885 * @param array $importer Array of the importer user
886 * @param string $handle The checked handle in the format user@domain.tld
887 * @param bool $is_comment Is the check for a comment?
889 * @return array|bool The contact data or false on error
892 private static function allowedContactByHandle(array $importer, string $handle, bool $is_comment = false)
894 $contact = self::contactByHandle($importer['uid'], $handle);
896 Logger::notice("A Contact for handle " . $handle . " and user " . $importer['uid'] . " was not found");
897 // If a contact isn't found, we accept it anyway if it is a comment
898 if ($is_comment && ($importer['uid'] != 0)) {
899 return self::contactByHandle(0, $handle);
900 } elseif ($is_comment) {
907 if (!self::postAllow($importer, $contact, $is_comment)) {
908 Logger::notice("The handle: " . $handle . " is not allowed to post to user " . $importer['uid']);
915 * Does the message already exists on the system?
917 * @param int $uid The user id
918 * @param string $guid The guid of the message
920 * @return int|bool message id if the message already was stored into the system - or false.
923 private static function messageExists(int $uid, string $guid)
925 $item = Post::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
926 if (DBA::isResult($item)) {
927 Logger::notice("message " . $guid . " already exists for user " . $uid);
935 * Checks for links to posts in a message
937 * @param array $item The item array
940 private static function fetchGuid(array $item)
942 preg_replace_callback(
943 "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism",
944 function ($match) use ($item) {
945 self::fetchGuidSub($match, $item);
950 preg_replace_callback(
951 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
952 function ($match) use ($item) {
953 self::fetchGuidSub($match, $item);
960 * Checks for relative /people/* links in an item body to match local
961 * contacts or prepends the remote host taken from the author link.
963 * @param string $body The item body to replace links from
964 * @param string $author_link The author link for missing local contact fallback
966 * @return string the replaced string
968 public static function replacePeopleGuid(string $body, string $author_link): string
970 $return = preg_replace_callback(
971 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
972 function ($match) use ($author_link) {
974 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
975 // 1 => '0123456789abcdef'
977 $handle = FContact::getUrlByGuid($match[1]);
980 $return = '@[url=' . $handle . ']' . $match[2] . '[/url]';
982 // No local match, restoring absolute remote URL from author scheme and host
983 $author_url = parse_url($author_link);
984 $return = '[url=' . $author_url['scheme'] . '://' . $author_url['host'] . '/people/' . $match[1] . ']' . $match[2] . '[/url]';
996 * sub function of "fetchGuid" which checks for links in messages
998 * @param array $match array containing a link that has to be checked for a message link
999 * @param array $item The item array
1001 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1002 * @throws \ImagickException
1004 private static function fetchGuidSub(array $match, array $item)
1006 if (!self::storeByGuid($match[1], $item['author-link'], true)) {
1007 self::storeByGuid($match[1], $item['owner-link'], true);
1012 * Fetches an item with a given guid from a given server
1014 * @param string $guid the message guid
1015 * @param string $server The server address
1016 * @param bool $force Forced fetch
1018 * @return int|bool the message id of the stored message or false
1019 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1020 * @throws \ImagickException
1022 private static function storeByGuid(string $guid, string $server, bool $force)
1024 $serverparts = parse_url($server);
1026 if (empty($serverparts['host']) || empty($serverparts['scheme'])) {
1030 $server = $serverparts['scheme'] . '://' . $serverparts['host'];
1032 Logger::info("Trying to fetch item " . $guid . " from " . $server);
1034 $msg = self::message($guid, $server);
1040 Logger::info("Successfully fetched item " . $guid . " from " . $server);
1042 // Now call the dispatcher
1043 return self::dispatchPublic($msg, $force ? self::FORCED_FETCH : self::FETCHED);
1047 * Fetches a message from a server
1049 * @param string $guid message guid
1050 * @param string $server The url of the server
1051 * @param int $level Endless loop prevention
1054 * 'message' => The message XML
1055 * 'author' => The author handle
1056 * 'key' => The public key of the author
1057 * @throws \Exception
1059 public static function message(string $guid, string $server, int $level = 0)
1065 // This will work for new Diaspora servers and Friendica servers from 3.5
1066 $source_url = $server . '/fetch/post/' . urlencode($guid);
1068 Logger::info("Fetch post from " . $source_url);
1070 $envelope = DI::httpClient()->fetch($source_url, HttpClientAccept::MAGIC);
1072 Logger::info("Envelope was fetched.");
1073 $x = self::verifyMagicEnvelope($envelope);
1075 Logger::info("Envelope could not be verified.");
1077 Logger::info("Envelope was verified.");
1087 $source_xml = XML::parseString($x);
1089 if (!is_object($source_xml)) {
1093 if ($source_xml->post->reshare) {
1094 // Reshare of a reshare - old Diaspora version
1095 Logger::info("Message is a reshare");
1096 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1097 } elseif ($source_xml->getName() == "reshare") {
1098 // Reshare of a reshare - new Diaspora version
1099 Logger::info("Message is a new reshare");
1100 return self::message($source_xml->root_guid, $server, ++$level);
1105 // Fetch the author - for the old and the new Diaspora version
1106 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1107 $author = (string)$source_xml->post->status_message->diaspora_handle;
1108 } elseif ($source_xml->author && ($source_xml->getName() == 'status_message')) {
1109 $author = (string)$source_xml->author;
1112 // If this isn't a "status_message" then quit
1114 Logger::info("Message doesn't seem to be a status message");
1120 'author' => $author,
1121 'key' => self::key($author)
1126 * Fetches an item with a given URL
1128 * @param string $url the message url
1129 * @param int $uid User id
1131 * @return int|bool the message id of the stored message or false
1132 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1133 * @throws \ImagickException
1135 public static function fetchByURL(string $url, int $uid = 0)
1137 // Check for Diaspora (and Friendica) typical paths
1138 if (!preg_match('=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i', $url, $matches)) {
1139 Logger::info('Invalid url', ['url' => $url]);
1143 $guid = urldecode($matches[2]);
1145 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1146 if (DBA::isResult($item)) {
1147 Logger::info('Found', ['id' => $item['id']]);
1151 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1152 $ret = self::storeByGuid($guid, $matches[1], true);
1153 Logger::info('Result', ['ret' => $ret]);
1155 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1156 if (DBA::isResult($item)) {
1157 Logger::info('Found', ['id' => $item['id']]);
1160 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1166 * Fetches the item record of a given guid
1168 * @param int $uid The user id
1169 * @param string $guid message guid
1170 * @param string $author The handle of the item
1171 * @param array $contact The contact of the item owner
1173 * @return array|bool the item record or false on failure
1174 * @throws \Exception
1176 private static function parentItem(int $uid, string $guid, string $author, array $contact)
1178 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1179 'author-name', 'author-link', 'author-avatar', 'gravity',
1180 'owner-name', 'owner-link', 'owner-avatar'];
1181 $condition = ['uid' => $uid, 'guid' => $guid];
1182 $item = Post::selectFirst($fields, $condition);
1184 if (!DBA::isResult($item)) {
1185 $person = FContact::getByURL($author);
1186 $result = self::storeByGuid($guid, $person['url'], false);
1188 // We don't have an url for items that arrived at the public dispatcher
1189 if (!$result && !empty($contact['url'])) {
1190 $result = self::storeByGuid($guid, $contact['url'], false);
1194 Logger::info("Fetched missing item " . $guid . " - result: " . $result);
1196 $item = Post::selectFirst($fields, $condition);
1200 if (!DBA::isResult($item)) {
1201 Logger::notice("parent item not found: parent: " . $guid . " - user: " . $uid);
1204 Logger::notice("parent item found: parent: " . $guid . " - user: " . $uid);
1210 * returns contact details
1212 * @param array $def_contact The default contact if the person isn't found
1213 * @param array $person The record of the person
1214 * @param int $uid The user id
1217 * 'cid' => contact id
1218 * 'network' => network type
1219 * @throws \Exception
1221 private static function authorContactByUrl(array $def_contact, array $person, int $uid): array
1223 $condition = ['nurl' => Strings::normaliseLink($person['url']), 'uid' => $uid];
1224 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1225 if (DBA::isResult($contact)) {
1226 $cid = $contact['id'];
1227 $network = $contact['network'];
1229 $cid = $def_contact['id'];
1230 $network = Protocol::DIASPORA;
1235 'network' => $network
1240 * Is the profile a hubzilla profile?
1242 * @param string $url The profile link
1244 * @return bool is it a hubzilla server?
1246 private static function isHubzilla(string $url): bool
1248 return strstr($url, '/channel/');
1252 * Generate a post link with a given handle and message guid
1254 * @param string $addr The user handle
1255 * @param string $guid message guid
1256 * @param string $parent_guid optional parent guid
1258 * @return string the post link
1259 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1260 * @throws \ImagickException
1262 private static function plink(string $addr, string $guid, string $parent_guid = ''): string
1264 $contact = Contact::getByURL($addr);
1265 if (empty($contact)) {
1266 Logger::info('No contact data for address', ['addr' => $addr]);
1270 if (empty($contact['baseurl'])) {
1271 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1272 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1276 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1277 if (!empty($gserver['platform'])) {
1278 $platform = strtolower($gserver['platform']);
1279 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1282 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1283 if (self::isHubzilla($contact['url'])) {
1284 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1285 $platform = 'hubzilla';
1286 } elseif ($contact['network'] == Protocol::DFRN) {
1287 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1288 $platform = 'friendica';
1292 if ($platform == 'friendica') {
1293 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1296 if ($platform == 'hubzilla') {
1297 return $contact['baseurl'] . '/item/' . $guid;
1300 if ($platform == 'socialhome') {
1301 return $contact['baseurl'] . '/content/' . $guid;
1304 if ($platform != 'diaspora') {
1305 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1309 if ($parent_guid != '') {
1310 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1312 return $contact['baseurl'] . '/posts/' . $guid;
1317 * Receives account migration
1319 * @param array $importer Array of the importer user
1320 * @param SimpleXMLElement $data The message object
1322 * @return bool Success
1323 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1324 * @throws \ImagickException
1326 private static function receiveAccountMigration(array $importer, SimpleXMLElement $data): bool
1328 $old_handle = XML::unescape($data->author);
1329 $new_handle = XML::unescape($data->profile->author);
1330 $signature = XML::unescape($data->signature);
1332 $contact = self::contactByHandle($importer['uid'], $old_handle);
1334 Logger::notice("cannot find contact for sender: " . $old_handle . " and user " . $importer['uid']);
1338 Logger::notice("Got migration for " . $old_handle . ", to " . $new_handle . " with user " . $importer['uid']);
1341 $signed_text = 'AccountMigration:' . $old_handle . ':' . $new_handle;
1342 $key = self::key($old_handle);
1343 if (!Crypto::rsaVerify($signed_text, $signature, $key, 'sha256')) {
1344 Logger::notice('No valid signature for migration.');
1348 // Update the profile
1349 self::receiveProfile($importer, $data->profile);
1351 // change the technical stuff in contact
1352 $data = Probe::uri($new_handle);
1353 if ($data['network'] == Protocol::PHANTOM) {
1354 Logger::notice("Account for " . $new_handle . " couldn't be probed.");
1359 'url' => $data['url'],
1360 'nurl' => Strings::normaliseLink($data['url']),
1361 'name' => $data['name'],
1362 'nick' => $data['nick'],
1363 'addr' => $data['addr'],
1364 'batch' => $data['batch'],
1365 'notify' => $data['notify'],
1366 'poll' => $data['poll'],
1367 'network' => $data['network']
1370 Contact::update($fields, ['addr' => $old_handle]);
1372 Logger::notice('Contacts are updated.');
1378 * Processes an account deletion
1380 * @param SimpleXMLElement $data The message object
1382 * @return bool Success
1383 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1385 private static function receiveAccountDeletion(SimpleXMLElement $data): bool
1387 $author = XML::unescape($data->author);
1389 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1390 while ($contact = DBA::fetch($contacts)) {
1391 Contact::remove($contact['id']);
1393 DBA::close($contacts);
1395 Logger::notice('Removed contacts for ' . $author);
1401 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1403 * @param string $author Author handle
1404 * @param string $guid Message guid
1405 * @param boolean $onlyfound Only return uri when found in the database
1407 * @return string The constructed uri or the one from our database or empty string on if $onlyfound is true
1408 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1409 * @throws \ImagickException
1411 private static function getUriFromGuid(string $author, string $guid, bool $onlyfound = false): string
1413 $item = Post::selectFirst(['uri'], ['guid' => $guid]);
1414 if (DBA::isResult($item)) {
1415 return $item['uri'];
1416 } elseif (!$onlyfound) {
1417 $person = FContact::getByURL($author);
1419 $parts = parse_url($person['url']);
1420 unset($parts['path']);
1421 $host_url = Uri::fromParts($parts);
1423 return $host_url . '/objects/' . $guid;
1430 * Store the mentions in the tag table
1432 * @param integer $uriid
1433 * @param string $text
1435 private static function storeMentions(int $uriid, string $text)
1437 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1438 if (empty($matches)) {
1443 * Matching values for the preg match
1444 * [1] = mention type (@ or !)
1445 * [2] = name (optional)
1449 foreach ($matches as $match) {
1450 if (empty($match)) {
1454 $person = FContact::getByURL($match[3]);
1455 if (empty($person)) {
1459 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1464 * Processes an incoming comment
1466 * @param array $importer Array of the importer user
1467 * @param string $sender The sender of the message
1468 * @param SimpleXMLElement $data The message object
1469 * @param string $xml The original XML of the message
1470 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1472 * @return int The message id of the generated comment or "false" if there was an error
1473 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1474 * @throws \ImagickException
1476 private static function receiveComment(array $importer, string $sender, SimpleXMLElement $data, string $xml, int $direction): bool
1478 $author = XML::unescape($data->author);
1479 $guid = XML::unescape($data->guid);
1480 $parent_guid = XML::unescape($data->parent_guid);
1481 $text = XML::unescape($data->text);
1483 if (isset($data->created_at)) {
1484 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1486 $created_at = DateTimeFormat::utcNow();
1489 if (isset($data->thread_parent_guid)) {
1490 $thread_parent_guid = XML::unescape($data->thread_parent_guid);
1491 $thr_parent = self::getUriFromGuid('', $thread_parent_guid, true);
1496 $contact = self::allowedContactByHandle($importer, $sender, true);
1501 if (!empty($contact['gsid'])) {
1502 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1505 $message_id = self::messageExists($importer['uid'], $guid);
1510 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1511 if (!$toplevel_parent_item) {
1515 $person = FContact::getByURL($author);
1516 if (!is_array($person)) {
1517 Logger::notice("unable to find author details");
1521 // Fetch the contact id - if we know this contact
1522 $author_contact = self::authorContactByUrl($contact, $person, $importer['uid']);
1526 $datarray['uid'] = $importer['uid'];
1527 $datarray['contact-id'] = $author_contact['cid'];
1528 $datarray['network'] = $author_contact['network'];
1530 $datarray['author-link'] = $person['url'];
1531 $datarray['author-id'] = Contact::getIdForURL($person['url'], 0);
1533 $datarray['owner-link'] = $contact['url'];
1534 $datarray['owner-id'] = Contact::getIdForURL($contact['url'], 0);
1536 // Will be overwritten for sharing accounts in Item::insert
1537 if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
1538 $datarray['post-reason'] = Item::PR_FETCHED;
1539 } elseif ($datarray['uid'] == 0) {
1540 $datarray['post-reason'] = Item::PR_GLOBAL;
1542 $datarray['post-reason'] = Item::PR_COMMENT;
1545 $datarray['guid'] = $guid;
1546 $datarray['uri'] = self::getUriFromGuid($author, $guid);
1547 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1549 $datarray['verb'] = Activity::POST;
1550 $datarray['gravity'] = GRAVITY_COMMENT;
1552 $datarray['thr-parent'] = $thr_parent ?: $toplevel_parent_item['uri'];
1554 $datarray['object-type'] = Activity\ObjectType::COMMENT;
1555 $datarray['post-type'] = Item::PT_NOTE;
1557 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1558 $datarray['source'] = $xml;
1559 $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
1561 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
1563 $datarray['plink'] = self::plink($author, $guid, $toplevel_parent_item['guid']);
1564 $body = Markdown::toBBCode($text);
1566 $datarray['body'] = self::replacePeopleGuid($body, $person['url']);
1568 self::storeMentions($datarray['uri-id'], $text);
1569 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
1571 self::fetchGuid($datarray);
1573 // If we are the origin of the parent we store the original data.
1574 // We notify our followers during the item storage.
1575 if ($toplevel_parent_item['origin']) {
1576 $datarray['diaspora_signed_text'] = json_encode($data);
1579 if (Item::isTooOld($datarray)) {
1580 Logger::info('Comment is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1584 $message_id = Item::insert($datarray);
1586 if ($message_id <= 0) {
1591 Logger::info("Stored comment " . $datarray['guid'] . " with message id " . $message_id);
1592 if ($datarray['uid'] == 0) {
1593 Item::distribute($message_id, json_encode($data));
1601 * processes and stores private messages
1603 * @param array $importer Array of the importer user
1604 * @param array $contact The contact of the message
1605 * @param SimpleXMLElement $data The message object
1606 * @param array $msg Array of the processed message, author handle and key
1607 * @param object $mesg The private message
1608 * @param array $conversation The conversation record to which this message belongs
1610 * @return bool "true" if it was successful
1611 * @throws \Exception
1612 * @todo Find type-hint for $mesg and update documentation
1614 private static function receiveConversationMessage(array $importer, array $contact, SimpleXMLElement $data, array $msg, $mesg, array $conversation): bool
1616 $author = XML::unescape($data->author);
1617 $guid = XML::unescape($data->guid);
1618 $subject = XML::unescape($data->subject);
1620 // "diaspora_handle" is the element name from the old version
1621 // "author" is the element name from the new version
1622 if ($mesg->author) {
1623 $msg_author = XML::unescape($mesg->author);
1624 } elseif ($mesg->diaspora_handle) {
1625 $msg_author = XML::unescape($mesg->diaspora_handle);
1630 $msg_guid = XML::unescape($mesg->guid);
1631 $msg_conversation_guid = XML::unescape($mesg->conversation_guid);
1632 $msg_text = XML::unescape($mesg->text);
1633 $msg_created_at = DateTimeFormat::utc(XML::unescape($mesg->created_at));
1635 if ($msg_conversation_guid != $guid) {
1636 Logger::notice("message conversation guid does not belong to the current conversation.");
1640 $body = Markdown::toBBCode($msg_text);
1641 $message_uri = $msg_author.":".$msg_guid;
1643 $person = FContact::getByURL($msg_author);
1645 return Mail::insert([
1646 'uid' => $importer['uid'],
1647 'guid' => $msg_guid,
1648 'convid' => $conversation['id'],
1649 'from-name' => $person['name'],
1650 'from-photo' => $person['photo'],
1651 'from-url' => $person['url'],
1652 'contact-id' => $contact['id'],
1653 'title' => $subject,
1655 'uri' => $message_uri,
1656 'parent-uri' => $author . ':' . $guid,
1657 'created' => $msg_created_at
1662 * Processes new private messages (answers to private messages are processed elsewhere)
1664 * @param array $importer Array of the importer user
1665 * @param array $msg Array of the processed message, author handle and key
1666 * @param SimpleXMLElement $data The message object
1668 * @return bool Success
1669 * @throws \Exception
1671 private static function receiveConversation(array $importer, array $msg, SimpleXMLElement $data)
1673 $author = XML::unescape($data->author);
1674 $guid = XML::unescape($data->guid);
1675 $subject = XML::unescape($data->subject);
1676 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1677 $participants = XML::unescape($data->participants);
1679 $messages = $data->message;
1681 if (!count($messages)) {
1682 Logger::notice("empty conversation");
1686 $contact = self::allowedContactByHandle($importer, $msg['author'], true);
1691 if (!empty($contact['gsid'])) {
1692 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1695 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1696 if (!DBA::isResult($conversation)) {
1697 $r = DBA::insert('conv', [
1698 'uid' => $importer['uid'],
1700 'creator' => $author,
1701 'created' => $created_at,
1702 'updated' => DateTimeFormat::utcNow(),
1703 'subject' => $subject,
1704 'recips' => $participants]);
1706 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1709 if (!$conversation) {
1710 Logger::notice("unable to create conversation.");
1714 foreach ($messages as $mesg) {
1715 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1722 * Processes "like" messages
1724 * @param array $importer Array of the importer user
1725 * @param string $sender The sender of the message
1726 * @param SimpleXMLElement $data The message object
1727 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1729 * @return bool Success or failure
1730 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1731 * @throws \ImagickException
1733 private static function receiveLike(array $importer, string $sender, SimpleXMLElement $data, int $direction): bool
1735 $author = XML::unescape($data->author);
1736 $guid = XML::unescape($data->guid);
1737 $parent_guid = XML::unescape($data->parent_guid);
1738 $parent_type = XML::unescape($data->parent_type);
1739 $positive = XML::unescape($data->positive);
1741 // likes on comments aren't supported by Diaspora - only on posts
1742 // But maybe this will be supported in the future, so we will accept it.
1743 if (!in_array($parent_type, ['Post', 'Comment'])) {
1747 $contact = self::allowedContactByHandle($importer, $sender, true);
1752 if (!empty($contact['gsid'])) {
1753 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1756 $message_id = self::messageExists($importer['uid'], $guid);
1761 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1762 if (!$toplevel_parent_item) {
1766 $person = FContact::getByURL($author);
1767 if (!is_array($person)) {
1768 Logger::notice("unable to find author details");
1772 // Fetch the contact id - if we know this contact
1773 $author_contact = self::authorContactByUrl($contact, $person, $importer['uid']);
1775 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1776 // We would accept this anyhow.
1777 if ($positive == 'true') {
1778 $verb = Activity::LIKE;
1780 $verb = Activity::DISLIKE;
1785 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1786 $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
1788 $datarray['uid'] = $importer['uid'];
1789 $datarray['contact-id'] = $author_contact['cid'];
1790 $datarray['network'] = $author_contact['network'];
1792 $datarray['owner-link'] = $datarray['author-link'] = $person['url'];
1793 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($person['url'], 0);
1795 $datarray['guid'] = $guid;
1796 $datarray['uri'] = self::getUriFromGuid($author, $guid);
1798 $datarray['verb'] = $verb;
1799 $datarray['gravity'] = GRAVITY_ACTIVITY;
1800 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1802 $datarray['object-type'] = Activity\ObjectType::NOTE;
1804 $datarray['body'] = $verb;
1806 // Diaspora doesn't provide a date for likes
1807 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
1809 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1810 if ($toplevel_parent_item['gravity'] != GRAVITY_PARENT) {
1811 $toplevel = Post::selectFirst(['origin'], ['id' => $toplevel_parent_item['parent']]);
1812 $origin = $toplevel['origin'];
1814 $origin = $toplevel_parent_item['origin'];
1817 // If we are the origin of the parent we store the original data.
1818 // We notify our followers during the item storage.
1820 $datarray['diaspora_signed_text'] = json_encode($data);
1823 if (Item::isTooOld($datarray)) {
1824 Logger::info('Like is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1828 $message_id = Item::insert($datarray);
1830 if ($message_id <= 0) {
1835 Logger::info("Stored like " . $datarray['guid'] . " with message id " . $message_id);
1836 if ($datarray['uid'] == 0) {
1837 Item::distribute($message_id, json_encode($data));
1845 * Processes private messages
1847 * @param array $importer Array of the importer user
1848 * @param SimpleXMLElement $data The message object
1850 * @return bool Success?
1851 * @throws \Exception
1853 private static function receiveMessage(array $importer, SimpleXMLElement $data): bool
1855 $author = XML::unescape($data->author);
1856 $guid = XML::unescape($data->guid);
1857 $conversation_guid = XML::unescape($data->conversation_guid);
1858 $text = XML::unescape($data->text);
1859 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1861 $contact = self::allowedContactByHandle($importer, $author, true);
1866 if (!empty($contact['gsid'])) {
1867 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1870 $conversation = null;
1872 $condition = ['uid' => $importer['uid'], 'guid' => $conversation_guid];
1873 $conversation = DBA::selectFirst('conv', [], $condition);
1875 if (!DBA::isResult($conversation)) {
1876 Logger::notice("conversation not available.");
1880 $message_uri = $author . ':' . $guid;
1882 $person = FContact::getByURL($author);
1884 Logger::notice("unable to find author details");
1888 $body = Markdown::toBBCode($text);
1890 $body = self::replacePeopleGuid($body, $person["url"]);
1892 return Mail::insert([
1893 'uid' => $importer['uid'],
1895 'convid' => $conversation['id'],
1896 'from-name' => $person['name'],
1897 'from-photo' => $person['photo'],
1898 'from-url' => $person['url'],
1899 'contact-id' => $contact['id'],
1900 'title' => $conversation['subject'],
1903 'uri' => $message_uri,
1904 'parent-uri' => $author.":".$conversation['guid'],
1905 'created' => $created_at
1910 * Processes participations - unsupported by now
1912 * @param array $importer Array of the importer user
1913 * @param SimpleXMLElement $data The message object
1914 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1916 * @return bool success
1917 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1918 * @throws \ImagickException
1920 private static function receiveParticipation(array $importer, SimpleXMLElement $data, int $direction): bool
1922 $author = strtolower(XML::unescape($data->author));
1923 $guid = XML::unescape($data->guid);
1924 $parent_guid = XML::unescape($data->parent_guid);
1926 $contact = self::allowedContactByHandle($importer, $author, true);
1931 if (!empty($contact['gsid'])) {
1932 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1935 if (self::messageExists($importer['uid'], $guid)) {
1939 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1940 if (!$toplevel_parent_item) {
1944 if (!$toplevel_parent_item['origin']) {
1945 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1948 if (!in_array($toplevel_parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
1949 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1953 $person = FContact::getByURL($author);
1954 if (!is_array($person)) {
1955 Logger::notice("Person not found: " . $author);
1959 $author_contact = self::authorContactByUrl($contact, $person, $importer['uid']);
1961 // Store participation
1964 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1965 $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
1967 $datarray['uid'] = $importer['uid'];
1968 $datarray['contact-id'] = $author_contact['cid'];
1969 $datarray['network'] = $author_contact['network'];
1971 $datarray['owner-link'] = $datarray['author-link'] = $person['url'];
1972 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($person['url'], 0);
1974 $datarray['guid'] = $guid;
1975 $datarray['uri'] = self::getUriFromGuid($author, $guid);
1977 $datarray['verb'] = Activity::FOLLOW;
1978 $datarray['gravity'] = GRAVITY_ACTIVITY;
1979 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1981 $datarray['object-type'] = Activity\ObjectType::NOTE;
1983 $datarray['body'] = Activity::FOLLOW;
1985 // Diaspora doesn't provide a date for a participation
1986 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
1988 if (Item::isTooOld($datarray)) {
1989 Logger::info('Participation is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1993 $message_id = Item::insert($datarray);
1995 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
1997 // Send all existing comments and likes to the requesting server
1998 $comments = Post::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb'],
1999 ['parent' => $toplevel_parent_item['id'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
2000 while ($comment = Post::fetch($comments)) {
2001 if (in_array($comment['verb'], [Activity::FOLLOW, Activity::TAG])) {
2002 Logger::info('participation messages are not relayed', ['item' => $comment['id']]);
2006 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
2007 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2011 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
2012 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2016 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact['cid']]);
2017 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $author_contact['cid'])) {
2018 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2021 DBA::close($comments);
2027 * Processes photos - unneeded
2029 * @param array $importer Array of the importer user
2030 * @param SimpleXMLElement $data The message object
2032 * @return bool always true
2034 private static function receivePhoto(array $importer, $data)
2036 // There doesn't seem to be a reason for this function,
2037 // since the photo data is transmitted in the status message as well
2042 * Processes poll participations - unssupported
2044 * @param array $importer Array of the importer user
2045 * @param object $data The message object
2047 * @return bool always true
2049 private static function receivePollParticipation(array $importer, $data)
2051 // We don't support polls by now
2056 * Processes incoming profile updates
2058 * @param array $importer Array of the importer user
2059 * @param SimpleXMLElement $data The message object
2061 * @return bool Success
2062 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2063 * @throws \ImagickException
2065 private static function receiveProfile(array $importer, SimpleXMLElement $data): bool
2067 $author = strtolower(XML::unescape($data->author));
2069 $contact = self::contactByHandle($importer['uid'], $author);
2074 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? ' ' . XML::unescape($data->last_name) : '');
2075 $image_url = XML::unescape($data->image_url);
2076 $birthday = XML::unescape($data->birthday);
2077 $about = Markdown::toBBCode(XML::unescape($data->bio));
2078 $location = Markdown::toBBCode(XML::unescape($data->location));
2079 $searchable = (XML::unescape($data->searchable) == 'true');
2080 $nsfw = (XML::unescape($data->nsfw) == 'true');
2081 $tags = XML::unescape($data->tag_string);
2083 $tags = explode('#', $tags);
2086 foreach ($tags as $tag) {
2087 $tag = trim(strtolower($tag));
2093 $keywords = implode(', ', $keywords);
2095 $handle_parts = explode('@', $author);
2096 $nick = $handle_parts[0];
2099 $name = $handle_parts[0];
2102 if (preg_match('|^https?://|', $image_url) === 0) {
2103 // @TODO No HTTPS here?
2104 $image_url = 'http://' . $handle_parts[1] . $image_url;
2107 Contact::updateAvatar($contact['id'], $image_url);
2109 // Generic birthday. We don't know the timezone. The year is irrelevant.
2111 $birthday = str_replace('1000', '1901', $birthday);
2113 if ($birthday != '') {
2114 $birthday = DateTimeFormat::utc($birthday, 'Y-m-d');
2117 // this is to prevent multiple birthday notifications in a single year
2118 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2120 if (substr($birthday, 5) === substr($contact['bd'], 5)) {
2121 $birthday = $contact['bd'];
2124 $fields = ['name' => $name, 'location' => $location,
2125 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2126 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2127 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2129 if (!empty($birthday)) {
2130 $fields['bd'] = $birthday;
2133 Contact::update($fields, ['id' => $contact['id']]);
2135 Logger::info("Profile of contact " . $contact['id'] . " stored for user " . $importer['uid']);
2141 * Processes incoming friend requests
2143 * @param array $importer Array of the importer user
2144 * @param array $contact The contact that send the request
2146 * @throws \Exception
2148 private static function receiveRequestMakeFriend(array $importer, array $contact)
2150 if ($contact['rel'] == Contact::SHARING) {
2152 ['rel' => Contact::FRIEND, 'writable' => true],
2153 ['id' => $contact['id'], 'uid' => $importer['uid']]
2159 * Processes incoming sharing notification
2161 * @param array $importer Array of the importer user
2162 * @param SimpleXMLElement $data The message object
2164 * @return bool Success
2165 * @throws \Exception
2167 private static function receiveContactRequest(array $importer, SimpleXMLElement $data): bool
2169 $author = XML::unescape($data->author);
2170 $recipient = XML::unescape($data->recipient);
2172 if (!$author || !$recipient) {
2176 // the current protocol version doesn't know these fields
2177 // That means that we will assume their existance
2178 if (isset($data->following)) {
2179 $following = (XML::unescape($data->following) == 'true');
2184 if (isset($data->sharing)) {
2185 $sharing = (XML::unescape($data->sharing) == 'true');
2190 $contact = self::contactByHandle($importer['uid'], $author);
2192 // perhaps we were already sharing with this person. Now they're sharing with us.
2193 // That makes us friends.
2196 Logger::info("Author " . $author . " (Contact " . $contact['id'] . ") wants to follow us.");
2197 self::receiveRequestMakeFriend($importer, $contact);
2199 // refetch the contact array
2200 $contact = self::contactByHandle($importer['uid'], $author);
2202 // If we are now friends, we are sending a share message.
2203 // Normally we needn't to do so, but the first message could have been vanished.
2204 if (in_array($contact['rel'], [Contact::FRIEND])) {
2205 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2206 if (DBA::isResult($user)) {
2207 Logger::info("Sending share message to author " . $author . " - Contact: " . $contact['id'] . " - User: " . $importer['uid']);
2208 self::sendShare($user, $contact);
2213 Logger::info("Author " . $author . " doesn't want to follow us anymore.");
2214 Contact::removeFollower($contact);
2219 if (!$following && $sharing && in_array($importer['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2220 Logger::info("Author " . $author . " wants to share with us - but doesn't want to listen. Request is ignored.");
2222 } elseif (!$following && !$sharing) {
2223 Logger::info("Author " . $author . " doesn't want anything - and we don't know the author. Request is ignored.");
2225 } elseif (!$following && $sharing) {
2226 Logger::info("Author " . $author . " wants to share with us.");
2227 } elseif ($following && $sharing) {
2228 Logger::info("Author " . $author . " wants to have a bidirectional conection.");
2229 } elseif ($following && !$sharing) {
2230 Logger::info("Author " . $author . " wants to listen to us.");
2233 $ret = FContact::getByURL($author);
2235 if (!$ret || ($ret['network'] != Protocol::DIASPORA)) {
2236 Logger::notice("Cannot resolve diaspora handle " . $author . " for ".$recipient);
2240 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2242 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2247 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2248 'author-link' => $ret['url']];
2250 $result = Contact::addRelationship($importer, $contact, $item, false);
2251 if ($result === true) {
2252 $contact_record = self::contactByHandle($importer['uid'], $author);
2253 if (!$contact_record) {
2254 Logger::info('unable to locate newly created contact record.');
2258 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2259 if (DBA::isResult($user)) {
2260 self::sendShare($user, $contact_record);
2262 // Send the profile data, maybe it weren't transmitted before
2263 self::sendProfile($importer['uid'], [$contact_record]);
2271 * Fetches a message with a given guid
2273 * @param string $guid message guid
2274 * @param string $orig_author handle of the original post
2275 * @return array|bool The fetched item or false on failure
2276 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2277 * @throws \ImagickException
2279 public static function originalItem(string $guid, string $orig_author)
2282 Logger::notice('Empty guid. Quitting.');
2286 // Do we already have this item?
2287 $fields = ['body', 'title', 'app', 'created', 'object-type', 'uri', 'guid',
2288 'author-name', 'author-link', 'author-avatar', 'plink', 'uri-id'];
2289 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2290 $item = Post::selectFirst($fields, $condition);
2292 if (DBA::isResult($item)) {
2293 Logger::notice("reshared message " . $guid . " already exists on system.");
2295 // Maybe it is already a reshared item?
2296 // Then refetch the content, if it is a reshare from a reshare.
2297 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2298 if (self::isReshare($item['body'], true)) {
2300 } elseif (self::isReshare($item['body'], false) || strstr($item['body'], '[share')) {
2301 $item['body'] = Markdown::toBBCode(BBCode::toMarkdown($item['body']));
2303 $item['body'] = self::replacePeopleGuid($item['body'], $item['author-link']);
2311 if (!DBA::isResult($item)) {
2312 if (empty($orig_author)) {
2313 Logger::notice('Empty author for guid ' . $guid . '. Quitting.');
2317 $server = 'https://' . substr($orig_author, strpos($orig_author, '@') + 1);
2318 Logger::notice("1st try: reshared message " . $guid . " will be fetched via SSL from the server " . $server);
2319 $stored = self::storeByGuid($guid, $server, true);
2322 $server = 'http://' . substr($orig_author, strpos($orig_author, '@') + 1);
2323 Logger::notice("2nd try: reshared message " . $guid . " will be fetched without SSL from the server " . $server);
2324 $stored = self::storeByGuid($guid, $server, true);
2328 $fields = ['body', 'title', 'app', 'created', 'object-type', 'uri', 'guid',
2329 'author-name', 'author-link', 'author-avatar', 'plink', 'uri-id'];
2330 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2331 $item = Post::selectFirst($fields, $condition);
2333 if (DBA::isResult($item)) {
2334 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2335 if (self::isReshare($item['body'], false)) {
2336 $item['body'] = Markdown::toBBCode(BBCode::toMarkdown($item['body']));
2337 $item['body'] = self::replacePeopleGuid($item['body'], $item['author-link']);
2348 * Stores a reshare activity
2350 * @param array $item Array of reshare post
2351 * @param integer $parent_message_id Id of the parent post
2352 * @param string $guid GUID string of reshare action
2353 * @param string $author Author handle
2355 private static function addReshareActivity(array $item, int $parent_message_id, string $guid, string $author)
2357 $parent = Post::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2361 $datarray['uid'] = $item['uid'];
2362 $datarray['contact-id'] = $item['contact-id'];
2363 $datarray['network'] = $item['network'];
2365 $datarray['author-link'] = $item['author-link'];
2366 $datarray['author-id'] = $item['author-id'];
2368 $datarray['owner-link'] = $datarray['author-link'];
2369 $datarray['owner-id'] = $datarray['author-id'];
2371 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2372 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2373 $datarray['thr-parent'] = $parent['uri'];
2375 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2376 $datarray['gravity'] = GRAVITY_ACTIVITY;
2377 $datarray['object-type'] = Activity\ObjectType::NOTE;
2379 $datarray['protocol'] = $item['protocol'];
2380 $datarray['source'] = $item['source'];
2381 $datarray['direction'] = $item['direction'];
2383 $datarray['plink'] = self::plink($author, $datarray['guid']);
2384 $datarray['private'] = $item['private'];
2385 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2387 if (Item::isTooOld($datarray)) {
2388 Logger::info('Reshare activity is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2392 $message_id = Item::insert($datarray);
2395 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2396 if ($datarray['uid'] == 0) {
2397 Item::distribute($message_id);
2403 * Processes a reshare message
2405 * @param array $importer Array of the importer user
2406 * @param SimpleXMLElement $data The message object
2407 * @param string $xml The original XML of the message
2408 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2410 * @return bool Success or failure
2411 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2412 * @throws \ImagickException
2414 private static function receiveReshare(array $importer, SimpleXMLElement $data, string $xml, int $direction): bool
2416 $author = XML::unescape($data->author);
2417 $guid = XML::unescape($data->guid);
2418 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2419 $root_author = XML::unescape($data->root_author);
2420 $root_guid = XML::unescape($data->root_guid);
2421 /// @todo handle unprocessed property "provider_display_name"
2422 $public = XML::unescape($data->public);
2424 $contact = self::allowedContactByHandle($importer, $author, false);
2429 if (!empty($contact['gsid'])) {
2430 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2433 $message_id = self::messageExists($importer['uid'], $guid);
2438 $original_item = self::originalItem($root_guid, $root_author);
2439 if (!$original_item) {
2443 if (empty($original_item['plink'])) {
2444 $original_item['plink'] = self::plink($root_author, $root_guid);
2449 $datarray['uid'] = $importer['uid'];
2450 $datarray['contact-id'] = $contact['id'];
2451 $datarray['network'] = Protocol::DIASPORA;
2453 $datarray['author-link'] = $contact['url'];
2454 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2456 $datarray['owner-link'] = $datarray['author-link'];
2457 $datarray['owner-id'] = $datarray['author-id'];
2459 $datarray['guid'] = $guid;
2460 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($author, $guid);
2461 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2463 $datarray['verb'] = Activity::POST;
2464 $datarray['gravity'] = GRAVITY_PARENT;
2466 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2467 $datarray['source'] = $xml;
2468 $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
2470 /// @todo Copy tag data from original post
2472 $prefix = BBCode::getShareOpeningTag(
2473 $original_item['author-name'],
2474 $original_item['author-link'],
2475 $original_item['author-avatar'],
2476 $original_item['plink'],
2477 $original_item['created'],
2478 $original_item['guid']
2481 if (!empty($original_item['title'])) {
2482 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2485 $datarray['body'] = $prefix.$original_item['body'] . '[/share]';
2487 Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
2489 $datarray['app'] = $original_item['app'];
2491 $datarray['plink'] = self::plink($author, $guid);
2492 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2493 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2495 $datarray['object-type'] = $original_item['object-type'];
2497 self::fetchGuid($datarray);
2499 if (Item::isTooOld($datarray)) {
2500 Logger::info('Reshare is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2504 $message_id = Item::insert($datarray);
2506 self::sendParticipation($contact, $datarray);
2508 $root_message_id = self::messageExists($importer['uid'], $root_guid);
2509 if ($root_message_id) {
2510 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2514 Logger::info("Stored reshare " . $datarray['guid'] . " with message id " . $message_id);
2515 if ($datarray['uid'] == 0) {
2516 Item::distribute($message_id);
2525 * Processes retractions
2527 * @param array $importer Array of the importer user
2528 * @param array $contact The contact of the item owner
2529 * @param SimpleXMLElement $data The message object
2531 * @return bool success
2532 * @throws \Exception
2534 private static function itemRetraction(array $importer, array $contact, SimpleXMLElement $data): bool
2536 $author = XML::unescape($data->author);
2537 $target_guid = XML::unescape($data->target_guid);
2538 $target_type = XML::unescape($data->target_type);
2540 $person = FContact::getByURL($author);
2541 if (!is_array($person)) {
2542 Logger::notice("unable to find author detail for " . $author);
2546 if (empty($contact['url'])) {
2547 $contact['url'] = $person['url'];
2550 // Fetch items that are about to be deleted
2551 $fields = ['uid', 'id', 'parent', 'author-link', 'uri-id'];
2553 // When we receive a public retraction, we delete every item that we find.
2554 if ($importer['uid'] == 0) {
2555 $condition = ['guid' => $target_guid, 'deleted' => false];
2557 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2560 $r = Post::select($fields, $condition);
2561 if (!DBA::isResult($r)) {
2562 Logger::notice("Target guid " . $target_guid . " was not found on this system for user " . $importer['uid'] . ".");
2566 while ($item = Post::fetch($r)) {
2567 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2568 Logger::info("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.");
2572 // Fetch the parent item
2573 $parent = Post::selectFirst(['author-link'], ['id' => $item['parent']]);
2575 // Only delete it if the parent author really fits
2576 if (!Strings::compareLink($parent['author-link'], $contact['url']) && !Strings::compareLink($item['author-link'], $contact['url'])) {
2577 Logger::info("Thread author " . $parent['author-link'] . " and item author " . $item['author-link'] . " don't fit to expected contact " . $contact['url']);
2581 Item::markForDeletion(['id' => $item['id']]);
2583 Logger::info("Deleted target " . $target_guid . " (" . $item['id'] . ") from user " . $item['uid'] . " parent: " . $item['parent']);
2591 * Receives retraction messages
2593 * @param array $importer Array of the importer user
2594 * @param string $sender The sender of the message
2595 * @param SimpleXMLElement $data The message object
2597 * @return bool Success
2598 * @throws \Exception
2600 private static function receiveRetraction(array $importer, string $sender, SimpleXMLElement $data)
2602 $target_type = XML::unescape($data->target_type);
2604 $contact = self::contactByHandle($importer['uid'], $sender);
2605 if (!$contact && (in_array($target_type, ['Contact', 'Person']))) {
2606 Logger::notice("cannot find contact for sender: " . $sender . " and user " . $importer['uid']);
2614 Logger::info("Got retraction for " . $target_type . ", sender " . $sender . " and user " . $importer['uid']);
2616 switch ($target_type) {
2621 case 'StatusMessage':
2622 return self::itemRetraction($importer, $contact, $data);
2624 case 'PollParticipation':
2626 // Currently unsupported
2630 Logger::notice("Unknown target type " . $target_type);
2637 * Checks if an incoming message is wanted
2639 * @param array $item
2640 * @param string $author
2641 * @param string $body
2642 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2644 * @return boolean Is the message wanted?
2646 private static function isSolicitedMessage(array $item, string $author, string $body, int $direction): bool
2648 $contact = Contact::getByURL($author);
2649 if (DBA::exists('contact', ['`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)', $contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) {
2650 Logger::debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2654 if ($direction == self::FORCED_FETCH) {
2655 Logger::debug('Post is a forced fetch - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2659 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
2660 if (Relay::isSolicitedPost($tags, $body, $contact['id'], $item['uri'], Protocol::DIASPORA)) {
2661 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2669 * Store an attached photo in the post-media table
2672 * @param object $photo
2675 private static function storePhotoAsMedia(int $uriid, $photo)
2677 // @TODO Need to find object type, roland@f.haeder.net
2678 Logger::debug('photo='.get_class($photo));
2680 $data['uri-id'] = $uriid;
2681 $data['type'] = Post\Media::IMAGE;
2682 $data['url'] = XML::unescape($photo->remote_photo_path) . XML::unescape($photo->remote_photo_name);
2683 $data['height'] = (int)XML::unescape($photo->height ?? 0);
2684 $data['width'] = (int)XML::unescape($photo->width ?? 0);
2685 $data['description'] = XML::unescape($photo->text ?? '');
2687 Post\Media::insert($data);
2691 * Receives status messages
2693 * @param array $importer Array of the importer user
2694 * @param SimpleXMLElement $data The message object
2695 * @param string $xml The original XML of the message
2696 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2698 * @return int|bool The message id of the newly created item or false on error
2699 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2700 * @throws \ImagickException
2702 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, string $xml, int $direction)
2704 $author = XML::unescape($data->author);
2705 $guid = XML::unescape($data->guid);
2706 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2707 $public = XML::unescape($data->public);
2708 $text = XML::unescape($data->text);
2709 $provider_display_name = XML::unescape($data->provider_display_name);
2711 $contact = self::allowedContactByHandle($importer, $author, false);
2716 if (!empty($contact['gsid'])) {
2717 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2720 $message_id = self::messageExists($importer['uid'], $guid);
2726 if ($data->location) {
2727 foreach ($data->location->children() as $fieldname => $data) {
2728 $address[$fieldname] = XML::unescape($data);
2732 $raw_body = $body = Markdown::toBBCode($text);
2736 $datarray['guid'] = $guid;
2737 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($author, $guid);
2738 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2740 // Attach embedded pictures to the body
2742 foreach ($data->photo as $photo) {
2743 self::storePhotoAsMedia($datarray['uri-id'], $photo);
2746 $datarray['object-type'] = Activity\ObjectType::IMAGE;
2747 $datarray['post-type'] = Item::PT_IMAGE;
2748 } elseif ($data->poll) {
2749 $datarray['object-type'] = Activity\ObjectType::NOTE;
2750 $datarray['post-type'] = Item::PT_POLL;
2752 $datarray['object-type'] = Activity\ObjectType::NOTE;
2753 $datarray['post-type'] = Item::PT_NOTE;
2756 /// @todo enable support for polls
2757 //if ($data->poll) {
2758 // foreach ($data->poll as $poll)
2763 /// @todo enable support for events
2765 $datarray['uid'] = $importer['uid'];
2766 $datarray['contact-id'] = $contact['id'];
2767 $datarray['network'] = Protocol::DIASPORA;
2769 $datarray['author-link'] = $contact['url'];
2770 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2772 $datarray['owner-link'] = $datarray['author-link'];
2773 $datarray['owner-id'] = $datarray['author-id'];
2775 $datarray['verb'] = Activity::POST;
2776 $datarray['gravity'] = GRAVITY_PARENT;
2778 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2779 $datarray['source'] = $xml;
2780 $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
2782 if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
2783 $datarray['post-reason'] = Item::PR_FETCHED;
2784 } elseif ($datarray['uid'] == 0) {
2785 $datarray['post-reason'] = Item::PR_GLOBAL;
2788 $datarray['body'] = self::replacePeopleGuid($body, $contact['url']);
2789 $datarray['raw-body'] = self::replacePeopleGuid($raw_body, $contact['url']);
2791 self::storeMentions($datarray['uri-id'], $text);
2792 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
2794 if (!self::isSolicitedMessage($datarray, $author, $body, $direction)) {
2795 DBA::delete('item-uri', ['uri' => $datarray['uri']]);
2799 if ($provider_display_name != '') {
2800 $datarray['app'] = $provider_display_name;
2803 $datarray['plink'] = self::plink($author, $guid);
2804 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2805 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2807 if (isset($address['address'])) {
2808 $datarray['location'] = $address['address'];
2811 if (isset($address['lat']) && isset($address['lng'])) {
2812 $datarray['coord'] = $address['lat'] . " " . $address['lng'];
2815 self::fetchGuid($datarray);
2817 if (Item::isTooOld($datarray)) {
2818 Logger::info('Status is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2822 $message_id = Item::insert($datarray);
2824 self::sendParticipation($contact, $datarray);
2827 Logger::info("Stored item " . $datarray['guid'] . " with message id " . $message_id);
2828 if ($datarray['uid'] == 0) {
2829 Item::distribute($message_id);
2837 /* ************************************************************************************** *
2838 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2839 * ************************************************************************************** */
2842 * returnes the handle of a contact
2844 * @param array $contact contact array
2846 * @return string the handle in the format user@domain.tld
2847 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2849 private static function myHandle(array $contact): string
2851 if (!empty($contact['addr'])) {
2852 return $contact['addr'];
2855 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2856 // So - just in case - we build the the address here.
2857 if ($contact['nickname'] != '') {
2858 $nick = $contact['nickname'];
2860 $nick = $contact['nick'];
2863 return $nick . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
2868 * Creates the data for a private message in the new format
2870 * @param string $msg The message that is to be transmitted
2871 * @param array $user The record of the sender
2872 * @param array $contact Target of the communication
2873 * @param string $prvkey The private key of the sender
2874 * @param string $pubkey The public key of the receiver
2876 * @return string The encrypted data
2877 * @throws \Exception
2879 public static function encodePrivateData(string $msg, array $user, array $contact, string $prvkey, string $pubkey): string
2881 Logger::debug("Message: ".$msg);
2883 // without a public key nothing will work
2885 Logger::notice("pubkey missing: contact id: ".$contact["id"]);
2889 $aes_key = random_bytes(32);
2890 $b_aes_key = base64_encode($aes_key);
2891 $iv = random_bytes(16);
2892 $b_iv = base64_encode($iv);
2894 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2896 $json = json_encode(['iv' => $b_iv, 'key' => $b_aes_key]);
2898 $encrypted_key_bundle = '';
2899 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
2903 $json_object = json_encode(
2905 'aes_key' => base64_encode($encrypted_key_bundle),
2906 'encrypted_magic_envelope' => base64_encode($ciphertext)
2910 return $json_object;
2914 * Creates the envelope for the "fetch" endpoint and for the new format
2916 * @param string $msg The message that is to be transmitted
2917 * @param array $user The record of the sender
2919 * @return string The envelope
2920 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2922 public static function buildMagicEnvelope(string $msg, array $user): string
2924 $b64url_data = Strings::base64UrlEncode($msg);
2925 $data = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
2927 $key_id = Strings::base64UrlEncode(self::myHandle($user));
2928 $type = 'application/xml';
2929 $encoding = 'base64url';
2930 $alg = 'RSA-SHA256';
2931 $signable_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
2933 // Fallback if the private key wasn't transmitted in the expected field
2934 if ($user['uprvkey'] == '') {
2935 $user['uprvkey'] = $user['prvkey'];
2938 $signature = Crypto::rsaSign($signable_data, $user['uprvkey']);
2939 $sig = Strings::base64UrlEncode($signature);
2944 '@attributes' => ['type' => $type],
2945 'me:encoding' => $encoding,
2948 '@attributes2' => ['key_id' => $key_id]
2952 $namespaces = ['me' => 'http://salmon-protocol.org/ns/magic-env'];
2954 return XML::fromArray($xmldata, $xml, false, $namespaces);
2958 * Create the envelope for a message
2960 * @param string $msg The message that is to be transmitted
2961 * @param array $user The record of the sender
2962 * @param array $contact Target of the communication
2963 * @param string $prvkey The private key of the sender
2964 * @param string $pubkey The public key of the receiver
2965 * @param bool $public Is the message public?
2967 * @return string The message that will be transmitted to other servers
2968 * @throws \Exception
2970 public static function buildMessage(string $msg, array $user, array $contact, string $prvkey, string $pubkey, bool $public = false): string
2972 // The message is put into an envelope with the sender's signature
2973 $envelope = self::buildMagicEnvelope($msg, $user);
2975 // Private messages are put into a second envelope, encrypted with the receivers public key
2977 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
2984 * Creates a signature for a message
2986 * @param array $owner the array of the owner of the message
2987 * @param array $message The message that is to be signed
2989 * @return string The signature
2991 private static function signature(array $owner, array $message): string
2994 unset($sigmsg['author_signature']);
2995 unset($sigmsg['parent_author_signature']);
2997 $signed_text = implode(';', $sigmsg);
2999 return base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
3003 * Transmit a message to a target server
3005 * @param array $owner the array of the item owner
3006 * @param array $contact Target of the communication
3007 * @param string $envelope The message that is to be transmitted
3008 * @param bool $public_batch Is it a public post?
3009 * @param string $guid message guid
3011 * @return int Result of the transmission
3012 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3013 * @throws \ImagickException
3015 private static function transmit(array $owner, array $contact, string $envelope, bool $public_batch, string $guid = ''): int
3017 $enabled = intval(DI::config()->get('system', 'diaspora_enabled'));
3022 $logid = Strings::getRandomHex(4);
3024 // We always try to use the data from the fcontact table.
3025 // This is important for transmitting data to Friendica servers.
3026 if (!empty($contact['addr'])) {
3027 $fcontact = FContact::getByURL($contact['addr']);
3028 if (!empty($fcontact)) {
3029 $dest_url = ($public_batch ? $fcontact['batch'] : $fcontact['notify']);
3033 if (empty($dest_url)) {
3034 $dest_url = ($public_batch ? $contact['batch'] : $contact['notify']);
3038 Logger::notice("no url for contact: " . $contact['id'] . " batch mode =" . $public_batch);
3042 Logger::notice("transmit: " . $logid . "-" . $guid . " " . $dest_url);
3044 if (!intval(DI::config()->get('system', 'diaspora_test'))) {
3045 $content_type = (($public_batch) ? 'application/magic-envelope+xml' : 'application/json');
3047 $postResult = DI::httpClient()->post($dest_url . '/', $envelope, ['Content-Type' => $content_type]);
3048 $return_code = $postResult->getReturnCode();
3050 Logger::notice('test_mode');
3054 Logger::notice("transmit: " . $logid . "-" . $guid . " to " . $dest_url . " returns: " . $return_code);
3056 return $return_code ? $return_code : -1;
3061 * Build the post xml
3063 * @param string $type The message type
3064 * @param array $message The message data
3066 * @return string The post XML
3068 public static function buildPostXml(string $type, array $message): string
3070 $data = [$type => $message];
3072 return XML::fromArray($data, $xml);
3076 * Builds and transmit messages
3078 * @param array $owner the array of the item owner
3079 * @param array $contact Target of the communication
3080 * @param string $type The message type
3081 * @param array $message The message data
3082 * @param bool $public_batch Is it a public post?
3083 * @param string $guid message guid
3085 * @return int Result of the transmission
3086 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3087 * @throws \ImagickException
3089 private static function buildAndTransmit(array $owner, array $contact, string $type, array $message, bool $public_batch = false, string $guid = '')
3091 $msg = self::buildPostXml($type, $message);
3093 // Fallback if the private key wasn't transmitted in the expected field
3094 if (empty($owner['uprvkey'])) {
3095 $owner['uprvkey'] = $owner['prvkey'];
3098 // When sending content to Friendica contacts using the Diaspora protocol
3099 // we have to fetch the public key from the fcontact.
3100 // This is due to the fact that legacy DFRN had unique keys for every contact.
3101 $pubkey = $contact['pubkey'];
3102 if (!empty($contact['addr'])) {
3103 $fcontact = FContact::getByURL($contact['addr']);
3104 if (!empty($fcontact)) {
3105 $pubkey = $fcontact['pubkey'];
3108 // The "addr" field should always be filled.
3109 // If this isn't the case, it will raise a notice some lines later.
3110 // And in the log we will see where it came from and we can handle it there.
3111 Logger::notice('Empty addr', ['contact' => $contact ?? [], 'callstack' => System::callstack(20)]);
3114 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
3116 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3118 Logger::info('Transmitted message', ['owner' => $owner['uid'], 'target' => $contact['addr'], 'type' => $type, 'guid' => $guid, 'result' => $return_code]);
3120 return $return_code;
3124 * sends a participation (Used to get all further updates)
3126 * @param array $contact Target of the communication
3127 * @param array $item Item array
3129 * @return int The result of the transmission
3130 * @throws \Exception
3132 private static function sendParticipation(array $contact, array $item): int
3134 // Don't send notifications for private postings
3135 if ($item['private'] == Item::PRIVATE) {
3139 $cachekey = 'diaspora:sendParticipation:' . $item['guid'];
3141 $result = DI::cache()->get($cachekey);
3142 if (!is_null($result)) {
3146 // Fetch some user id to have a valid handle to transmit the participation.
3147 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3148 // If the item belongs to a user, we take this user id.
3149 if ($item['uid'] == 0) {
3150 // @todo Possibly use an administrator account?
3151 $condition = ['verified' => true, 'blocked' => false,
3152 'account_removed' => false, 'account_expired' => false, 'account-type' => User::ACCOUNT_TYPE_PERSON];
3153 $first_user = DBA::selectFirst('user', ['uid'], $condition, ['order' => ['uid']]);
3154 $owner = User::getOwnerDataById($first_user['uid']);
3156 $owner = User::getOwnerDataById($item['uid']);
3159 $author = self::myHandle($owner);
3162 'author' => $author,
3163 'guid' => System::createUUID(),
3164 'parent_type' => 'Post',
3165 'parent_guid' => $item['guid']
3168 Logger::info("Send participation for " . $item['guid'] . " by " . $author);
3170 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3171 DI::cache()->set($cachekey, $item['guid'], Duration::QUARTER_HOUR);
3173 return self::buildAndTransmit($owner, $contact, 'participation', $message);
3177 * sends an account migration
3179 * @param array $owner the array of the item owner
3180 * @param array $contact Target of the communication
3181 * @param int $uid User ID
3183 * @return int The result of the transmission
3184 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3185 * @throws \ImagickException
3187 public static function sendAccountMigration(array $owner, array $contact, int $uid): int
3189 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3190 $profile = self::createProfileData($uid);
3192 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3193 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
3196 'author' => $old_handle,
3197 'profile' => $profile,
3198 'signature' => $signature
3201 Logger::info('Send account migration', ['msg' => $message]);
3203 return self::buildAndTransmit($owner, $contact, 'account_migration', $message);
3207 * Sends a "share" message
3209 * @param array $owner the array of the item owner
3210 * @param array $contact Target of the communication
3212 * @return int The result of the transmission
3213 * @throws \Exception
3215 public static function sendShare(array $owner, array $contact): int
3218 * @todo support the different possible combinations of "following" and "sharing"
3219 * Currently, Diaspora only interprets the "sharing" field
3221 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3225 switch ($contact["rel"]) {
3226 case Contact::FRIEND:
3230 case Contact::SHARING:
3234 case Contact::FOLLOWER:
3241 'author' => self::myHandle($owner),
3242 'recipient' => $contact['addr'],
3243 'following' => 'true',
3247 Logger::info('Send share', ['msg' => $message]);
3249 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3253 * sends an "unshare"
3255 * @param array $owner the array of the item owner
3256 * @param array $contact Target of the communication
3258 * @return int The result of the transmission
3259 * @throws \Exception
3261 public static function sendUnshare(array $owner, array $contact): int
3264 'author' => self::myHandle($owner),
3265 'recipient' => $contact['addr'],
3266 'following' => 'false',
3267 'sharing' => 'false'
3270 Logger::info('Send unshare', ['msg' => $message]);
3272 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3276 * Checks a message body if it is a reshare
3278 * @param string $body The message body that is to be check
3279 * @param bool $complete Should it be a complete check or a simple check?
3281 * @return array|bool Reshare details or "false" if no reshare
3282 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3283 * @throws \ImagickException
3285 public static function isReshare(string $body, bool $complete = true)
3287 $body = trim($body);
3289 $reshared = Item::getShareArray(['body' => $body]);
3290 if (empty($reshared)) {
3294 // Skip if it isn't a pure repeated messages
3295 // Does it start with a share?
3296 if (!empty($reshared['comment']) && $complete) {
3300 if (!empty($reshared['guid']) && $complete) {
3301 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3302 $item = Post::selectFirst(['contact-id'], $condition);
3303 if (DBA::isResult($item)) {
3305 $ret['root_handle'] = self::handleFromContact($item['contact-id']);
3306 $ret['root_guid'] = $reshared['guid'];
3308 } elseif ($complete) {
3309 // We are resharing something that isn't a DFRN or Diaspora post.
3310 // So we have to return "false" on "$complete" to not trigger a reshare.
3313 } elseif (empty($reshared['guid']) && $complete) {
3319 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3320 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3321 if (!empty($contact['addr'])) {
3322 $ret['root_handle'] = $contact['addr'];
3326 if (empty($ret) && !$complete) {
3334 * Create an event array
3336 * @param integer $event_id The id of the event
3338 * @return array with event data
3339 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3341 private static function buildEvent(string $event_id): array
3343 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
3344 if (!DBA::isResult($event)) {
3350 $owner = User::getOwnerDataById($event['uid']);
3355 $eventdata['author'] = self::myHandle($owner);
3357 if ($event['guid']) {
3358 $eventdata['guid'] = $event['guid'];
3361 $mask = DateTimeFormat::ATOM;
3363 /// @todo - establish "all day" events in Friendica
3364 $eventdata['all_day'] = 'false';
3366 $eventdata['timezone'] = 'UTC';
3368 if ($event['start']) {
3369 $eventdata['start'] = DateTimeFormat::utc($event['start'], $mask);
3371 if ($event['finish'] && !$event['nofinish']) {
3372 $eventdata['end'] = DateTimeFormat::utc($event['finish'], $mask);
3374 if ($event['summary']) {
3375 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3377 if ($event['desc']) {
3378 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3380 if ($event['location']) {
3381 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3382 $coord = Map::getCoordinates($event['location']);
3385 $location['address'] = html_entity_decode(BBCode::toMarkdown($event['location']));
3386 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3387 $location['lat'] = $coord['lat'];
3388 $location['lng'] = $coord['lon'];
3390 $location['lat'] = 0;
3391 $location['lng'] = 0;
3393 $eventdata['location'] = $location;
3400 * Create a post (status message or reshare)
3402 * @param array $item The item that will be exported
3403 * @param array $owner the array of the item owner
3406 * 'type' -> Message type ("status_message" or "reshare")
3407 * 'message' -> Array of XML elements of the status
3408 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3409 * @throws \ImagickException
3411 public static function buildStatus(array $item, array $owner)
3413 $cachekey = 'diaspora:buildStatus:' . $item['guid'];
3415 $result = DI::cache()->get($cachekey);
3416 if (!is_null($result)) {
3420 $myaddr = self::myHandle($owner);
3422 $public = ($item['private'] == Item::PRIVATE ? 'false' : 'true');
3423 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3424 $edited = DateTimeFormat::utc($item['edited'] ?? $item['created'], DateTimeFormat::ATOM);
3426 // Detect a share element and do a reshare
3427 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item['body']))) {
3429 'author' => $myaddr,
3430 'guid' => $item['guid'],
3431 'created_at' => $created,
3432 'root_author' => $ret['root_handle'],
3433 'root_guid' => $ret['root_guid'],
3434 'provider_display_name' => $item['app'],
3440 $title = $item['title'];
3441 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
3443 // Fetch the title from an attached link - if there is one
3444 if (empty($item['title']) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3445 $page_data = BBCode::getAttachmentData($item['body']);
3446 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3447 $title = $page_data['title'];
3451 if ($item['author-link'] != $item['owner-link']) {
3452 $body = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'],
3453 $item['plink'], $item['created']) . $body . '[/share]';
3456 // convert to markdown
3457 $body = html_entity_decode(BBCode::toMarkdown($body));
3460 if (strlen($title)) {
3461 $body = '### ' . html_entity_decode($title) . "\n\n" . $body;
3464 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]);
3465 if (!empty($attachments)) {
3466 $body .= "\n[hr]\n";
3467 foreach ($attachments as $attachment) {
3468 $body .= "[" . $attachment['description'] . "](" . $attachment['url'] . ")\n";
3474 if ($item['location'] != '')
3475 $location['address'] = $item['location'];
3477 if ($item['coord'] != '') {
3478 $coord = explode(' ', $item['coord']);
3479 $location['lat'] = $coord[0];
3480 $location['lng'] = $coord[1];
3484 'author' => $myaddr,
3485 'guid' => $item['guid'],
3486 'created_at' => $created,
3487 'edited_at' => $edited,
3488 'public' => $public,
3490 'provider_display_name' => $item['app'],
3491 'location' => $location
3494 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3495 if (!isset($location['lat']) || !isset($location['lng'])) {
3496 unset($message['location']);
3499 if ($item['event-id'] > 0) {
3500 $event = self::buildEvent($item['event-id']);
3501 if (count($event)) {
3502 $message['event'] = $event;
3504 if (!empty($event['location']['address']) &&
3505 !empty($event['location']['lat']) &&
3506 !empty($event['location']['lng'])) {
3507 $message['location'] = $event['location'];
3510 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3511 // $message['text'] = '';
3515 $type = 'status_message';
3520 'message' => $message
3523 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3528 private static function prependParentAuthorMention(string $body, string $profile_url): string
3530 $profile = Contact::getByURL($profile_url, false, ['addr', 'name']);
3531 if (!empty($profile['addr'])
3532 && !strstr($body, $profile['addr'])
3533 && !strstr($body, $profile_url)
3535 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3544 * @param array $item The item that will be exported
3545 * @param array $owner the array of the item owner
3546 * @param array $contact Target of the communication
3547 * @param bool $public_batch Is it a public post?
3549 * @return int The result of the transmission
3550 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3551 * @throws \ImagickException
3553 public static function sendStatus(array $item, array $owner, array $contact, bool $public_batch = false): int
3555 $status = self::buildStatus($item, $owner);
3557 return self::buildAndTransmit($owner, $contact, $status['type'], $status['message'], $public_batch, $item['guid']);
3561 * Creates a "like" object
3563 * @param array $item The item that will be exported
3564 * @param array $owner the array of the item owner
3566 * @return array|bool The data for a "like" or false on error
3567 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3569 private static function constructLike(array $item, array $owner)
3571 $parent = Post::selectFirst(['guid', 'uri', 'thr-parent'], ['uri' => $item['thr-parent']]);
3572 if (!DBA::isResult($parent)) {
3576 $target_type = ($parent['uri'] === $parent['thr-parent'] ? 'Post' : 'Comment');
3578 if ($item['verb'] === Activity::LIKE) {
3580 } elseif ($item['verb'] === Activity::DISLIKE) {
3581 $positive = 'false';
3585 'author' => self::myHandle($owner),
3586 'guid' => $item['guid'],
3587 'parent_guid' => $parent['guid'],
3588 'parent_type' => $target_type,
3589 'positive' => $positive,
3590 'author_signature' => ''
3595 * Creates an "EventParticipation" object
3597 * @param array $item The item that will be exported
3598 * @param array $owner the array of the item owner
3600 * @return array|bool The data for an "EventParticipation" or false on error
3601 * @throws \Exception
3603 private static function constructAttend(array $item, array $owner)
3605 $parent = Post::selectFirst(['guid'], ['uri' => $item['thr-parent']]);
3606 if (!DBA::isResult($parent)) {
3610 switch ($item['verb']) {
3611 case Activity::ATTEND:
3612 $attend_answer = 'accepted';
3614 case Activity::ATTENDNO:
3615 $attend_answer = 'declined';
3617 case Activity::ATTENDMAYBE:
3618 $attend_answer = 'tentative';
3621 Logger::notice('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3626 'author' => self::myHandle($owner),
3627 'guid' => $item['guid'],
3628 'parent_guid' => $parent['guid'],
3629 'status' => $attend_answer,
3630 'author_signature' => ''
3635 * Creates the object for a comment
3637 * @param array $item The item that will be exported
3638 * @param array $owner the array of the item owner
3640 * @return array|false The data for a comment
3641 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3643 private static function constructComment(array $item, array $owner)
3645 $cachekey = 'diaspora:constructComment:' . $item['guid'];
3647 $result = DI::cache()->get($cachekey);
3648 if (!is_null($result)) {
3652 $toplevel_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3653 if (!DBA::isResult($toplevel_item)) {
3654 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3658 $thread_parent_item = $toplevel_item;
3659 if ($item['thr-parent'] != $item['parent-uri']) {
3660 $thread_parent_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3663 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
3665 // The replied to autor mention is prepended for clarity if:
3666 // - Item replied isn't yours
3667 // - Item is public or explicit mentions are disabled
3668 // - Implicit mentions are enabled
3670 $item['author-id'] != $thread_parent_item['author-id']
3671 && ($thread_parent_item['gravity'] != GRAVITY_PARENT)
3672 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3673 && !DI::config()->get('system', 'disable_implicit_mentions')
3675 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3678 $text = html_entity_decode(BBCode::toMarkdown($body));
3679 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3680 $edited = DateTimeFormat::utc($item['edited'], DateTimeFormat::ATOM);
3683 'author' => self::myHandle($owner),
3684 'guid' => $item['guid'],
3685 'created_at' => $created,
3686 'edited_at' => $edited,
3687 'parent_guid' => $toplevel_item['guid'],
3689 'author_signature' => ''
3692 // Send the thread parent guid only if it is a threaded comment
3693 if ($item['thr-parent'] != $item['parent-uri']) {
3694 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3697 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3703 * Send a like or a comment
3705 * @param array $item The item that will be exported
3706 * @param array $owner the array of the item owner
3707 * @param array $contact Target of the communication
3708 * @param bool $public_batch Is it a public post?
3710 * @return int The result of the transmission
3711 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3712 * @throws \ImagickException
3714 public static function sendFollowup(array $item, array $owner, array $contact, bool $public_batch = false): int
3716 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3717 $message = self::constructAttend($item, $owner);
3718 $type = 'event_participation';
3719 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3720 $message = self::constructLike($item, $owner);
3722 } elseif (!in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
3723 $message = self::constructComment($item, $owner);
3727 if (empty($message)) {
3731 $message['author_signature'] = self::signature($owner, $message);
3733 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3737 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3739 * @param array $item The item that will be exported
3740 * @param array $owner the array of the item owner
3741 * @param array $contact Target of the communication
3742 * @param bool $public_batch Is it a public post?
3744 * @return int The result of the transmission
3745 * @throws \Exception
3747 public static function sendRelay(array $item, array $owner, array $contact, bool $public_batch = false): int
3749 if ($item['deleted']) {
3750 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3751 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3757 Logger::info("Got relayable data " . $type . " for item " . $item['guid'] . " (" . $item['id'] . ")");
3759 $msg = json_decode($item['signed_text'], true);
3762 if (is_array($msg)) {
3763 foreach ($msg as $field => $data) {
3764 if (!$item['deleted']) {
3765 if ($field == 'diaspora_handle') {
3768 if ($field == 'target_type') {
3769 $field = 'parent_type';
3773 $message[$field] = $data;
3776 Logger::info("Signature text for item " . $item["guid"] . " (" . $item["id"] . ") couldn't be extracted: " . $item['signed_text']);
3779 $message['parent_author_signature'] = self::signature($owner, $message);
3781 Logger::info('Relayed data', ['msg' => $message]);
3783 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3787 * Sends a retraction (deletion) of a message, like or comment
3789 * @param array $item The item that will be exported
3790 * @param array $owner the array of the item owner
3791 * @param array $contact Target of the communication
3792 * @param bool $public_batch Is it a public post?
3793 * @param bool $relay Is the retraction transmitted from a relay?
3795 * @return int The result of the transmission
3796 * @throws \Exception
3798 public static function sendRetraction(array $item, array $owner, array $contact, bool $public_batch = false, bool $relay = false): int
3800 $itemaddr = self::handleFromContact($item['contact-id'], $item['author-id']);
3802 $msg_type = 'retraction';
3804 if ($item['gravity'] == GRAVITY_PARENT) {
3805 $target_type = 'Post';
3806 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3807 $target_type = 'Like';
3809 $target_type = 'Comment';
3813 'author' => $itemaddr,
3814 'target_guid' => $item['guid'],
3815 'target_type' => $target_type
3818 Logger::info('Got message', ['msg' => $message]);
3820 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item['guid']);
3826 * @param array $item The item that will be exported
3827 * @param array $owner The owner
3828 * @param array $contact Target of the communication
3830 * @return int The result of the transmission
3831 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3832 * @throws \ImagickException
3834 public static function sendMail(array $item, array $owner, array $contact): int
3836 $myaddr = self::myHandle($owner);
3838 $cnv = DBA::selectFirst('conv', [], ['id' => $item['convid'], 'uid' => $item['uid']]);
3839 if (!DBA::isResult($cnv)) {
3840 Logger::notice("conversation not found.");
3844 $body = BBCode::toMarkdown($item['body']);
3845 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3848 'author' => $myaddr,
3849 'guid' => $item['guid'],
3850 'conversation_guid' => $cnv['guid'],
3852 'created_at' => $created,
3855 if ($item['reply']) {
3860 'author' => $cnv['creator'],
3861 'guid' => $cnv['guid'],
3862 'subject' => $cnv['subject'],
3863 'created_at' => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3864 'participants' => $cnv['recips'],
3868 $type = 'conversation';
3871 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item['guid']);
3875 * Split a name into first name and last name
3877 * @param string $name The name
3879 * @return array The array with "first" and "last"
3881 public static function splitName(string $name): array
3883 $name = trim($name);
3885 // Is the name longer than 64 characters? Then cut the rest of it.
3886 if (strlen($name) > 64) {
3887 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3888 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3890 $name = substr($name, 0, 64);
3894 // Take the first word as first name
3895 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3896 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3897 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3898 return ['first' => $first, 'last' => $last];
3901 // Take the last word as last name
3902 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3903 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3905 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3906 return ['first' => $first, 'last' => $last];
3909 // Take the first 32 characters if there is no space in the first 32 characters
3910 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3911 $first = substr($name, 0, 32);
3912 $last = substr($name, 32);
3913 return ['first' => $first, 'last' => $last];
3916 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3917 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3919 // Check if the last name is longer than 32 characters
3920 if (strlen($last) > 32) {
3921 if (strpos($last, ' ') <= 32) {
3922 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
3924 $last = substr($last, 0, 32);
3928 return ['first' => $first, 'last' => $last];
3932 * Create profile data
3934 * @param int $uid The user id
3936 * @return array The profile data
3937 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3939 private static function createProfileData(int $uid): array
3941 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
3942 if (!DBA::isResult($profile)) {
3946 $handle = $profile['addr'];
3948 $split_name = self::splitName($profile['name']);
3949 $first = $split_name['first'];
3950 $last = $split_name['last'];
3952 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3953 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3954 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3955 $searchable = ($profile['net-publish'] ? 'true' : 'false');
3961 if ($searchable === 'true') {
3964 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
3965 [$year, $month, $day] = sscanf($profile['dob'], '%4d-%2d-%2d');
3969 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
3972 $about = BBCode::toMarkdown($profile['about']);
3974 $location = $profile['location'];
3976 if ($profile['pub_keywords']) {
3977 $kw = str_replace(',', ' ', $profile['pub_keywords']);
3978 $kw = str_replace(' ', ' ', $kw);
3979 $arr = explode(' ', $kw);
3981 for ($x = 0; $x < 5; $x ++) {
3982 if (!empty($arr[$x])) {
3983 $tags .= '#'. trim($arr[$x]) .' ';
3988 $tags = trim($tags);
3992 'author' => $handle,
3993 'first_name' => $first,
3994 'last_name' => $last,
3995 'image_url' => $large,
3996 'image_url_medium' => $medium,
3997 'image_url_small' => $small,
4000 'location' => $location,
4001 'searchable' => $searchable,
4003 'tag_string' => $tags
4008 * Sends profile data
4010 * @param int $uid The user id
4011 * @param array $recips optional, default empty array
4013 * @throws \Exception
4015 public static function sendProfile(int $uid, array $recips = [])
4021 $owner = User::getOwnerDataById($uid);
4027 $recips = DBA::selectToArray('contact', [], ['network' => Protocol::DIASPORA, 'uid' => $uid, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
4034 $message = self::createProfileData($uid);
4036 // @ToDo Split this into single worker jobs
4037 foreach ($recips as $recip) {
4038 Logger::info("Send updated profile data for user " . $uid . " to contact " . $recip['id']);
4039 self::buildAndTransmit($owner, $recip, 'profile', $message);
4044 * Creates the signature for likes that are created on our system
4046 * @param integer $uid The user of that comment
4047 * @param array $item Item array
4049 * @return array|bool Signed content or false on error
4050 * @throws \Exception
4052 public static function createLikeSignature(int $uid, array $item)
4054 $owner = User::getOwnerDataById($uid);
4055 if (empty($owner)) {
4056 Logger::info('No owner post, so not storing signature');
4060 if (!in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
4064 $message = self::constructLike($item, $owner);
4065 if ($message === false) {
4069 $message['author_signature'] = self::signature($owner, $message);
4075 * Creates the signature for Comments that are created on our system
4077 * @param array $item Item array
4079 * @return array|bool Signed content or false on error
4080 * @throws \Exception
4082 public static function createCommentSignature(array $item)
4085 if (!empty($item['author-link'])) {
4086 $url = $item['author-link'];
4088 $contact = Contact::getById($item['author-id'], ['url']);
4089 if (empty($contact['url'])) {
4090 Logger::warning('Author Contact not found', ['author-id' => $item['author-id']]);
4093 $url = $contact['url'];
4096 $uid = User::getIdForURL($url);
4098 Logger::info('No owner post, so not storing signature', ['url' => $contact['url'] ?? 'No contact loaded']);
4102 $owner = User::getOwnerDataById($uid);
4103 if (empty($owner)) {
4104 Logger::info('No owner post, so not storing signature');
4108 // This is only needed for the automated tests
4109 if (empty($owner['uprvkey'])) {
4113 $message = self::constructComment($item, $owner);
4114 if ($message === false) {
4118 $message['author_signature'] = self::signature($owner, $message);
4123 public static function performReshare(int $UriId, int $uid): int
4125 $fields = ['uri-id', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
4126 $item = Post::selectFirst($fields, ['uri-id' => $UriId, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
4127 if (!DBA::isResult($item)) {
4131 if (strpos($item['body'], '[/share]') !== false) {
4132 $pos = strpos($item['body'], '[share');
4133 $post = substr($item['body'], $pos);
4135 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
4137 if (!empty($item['title'])) {
4138 $post .= '[h3]' . $item['title'] . "[/h3]\n";
4141 $post .= $item['body'];
4142 $post .= '[/share]';
4145 $owner = User::getOwnerDataById($uid);
4146 $author = Contact::getPublicIdByUserId($uid);
4150 'verb' => Activity::POST,
4151 'contact-id' => $owner['id'],
4152 'author-id' => $author,
4153 'owner-id' => $author,
4155 'allow_cid' => $owner['allow_cid'] ?? '',
4156 'allow_gid' => $owner['allow_gid']?? '',
4157 'deny_cid' => $owner['deny_cid'] ?? '',
4158 'deny_gid' => $owner['deny_gid'] ?? '',
4161 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
4162 $item['private'] = Item::PRIVATE;
4163 } elseif (DI::pConfig()->get($uid, 'system', 'unlisted')) {
4164 $item['private'] = Item::UNLISTED;
4166 $item['private'] = Item::PUBLIC;
4169 // Don't trigger the addons
4170 $item['api_source'] = false;
4172 return Item::insert($item, true);