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;
56 * This class contain functions to create and send Diaspora XML files
62 const FORCED_FETCH = 2;
65 * Return a list of participating contacts for a thread
67 * This is used for the participation feature.
68 * One of the parameters is a contact array.
69 * This is done to avoid duplicates.
71 * @param array $item Item that is about to be delivered
72 * @param array $contacts The previously fetched contacts
74 * @return array of relay servers
77 public static function participantsForThread(array $item, array $contacts): array
79 if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
80 Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]);
84 $items = Post::select(['author-id', 'author-link', 'parent-author-link', 'parent-guid', 'guid'],
85 ['parent' => $item['parent'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
86 while ($item = Post::fetch($items)) {
87 $contact = DBA::selectFirst('contact', ['id', 'url', 'name', 'protocol', 'batch', 'network'],
88 ['id' => $item['author-id']]);
89 if (!DBA::isResult($contact) || empty($contact['batch']) ||
90 ($contact['network'] != Protocol::DIASPORA) ||
91 Strings::compareLink($item['parent-author-link'], $item['author-link'])) {
96 foreach ($contacts as $entry) {
97 if ($entry['batch'] == $contact['batch']) {
103 Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]);
104 $contacts[] = $contact;
113 * verify the envelope and return the verified data
115 * @param string $envelope The magic envelope
117 * @return string|bool verified data or false on error
118 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
119 * @throws \ImagickException
121 private static function verifyMagicEnvelope(string $envelope)
123 $basedom = XML::parseString($envelope, true);
125 if (!is_object($basedom)) {
126 Logger::notice("Envelope is no XML file");
130 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
132 if (sizeof($children) == 0) {
133 Logger::notice("XML has no children");
139 $data = Strings::base64UrlDecode($children->data);
140 $type = $children->data->attributes()->type[0];
142 $encoding = $children->encoding;
144 $alg = $children->alg;
146 $sig = Strings::base64UrlDecode($children->sig);
147 $key_id = $children->sig->attributes()->key_id[0];
149 $handle = Strings::base64UrlDecode($key_id);
152 $b64url_data = Strings::base64UrlEncode($data);
153 $msg = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
155 $signable_data = $msg . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
158 Logger::notice('No author could be decoded. Discarding. Message: ' . $envelope);
162 $key = self::key($handle);
164 Logger::notice("Couldn't get a key for handle " . $handle . ". Discarding.");
168 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
170 Logger::notice('Message from ' . $handle . ' did not verify. Discarding.');
178 * encrypts data via AES
180 * @param string $key The AES key
181 * @param string $iv The IV (is used for CBC encoding)
182 * @param string $data The data that is to be encrypted
184 * @return string encrypted data
186 private static function aesEncrypt(string $key, string $iv, string $data): string
188 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
192 * decrypts data via AES
194 * @param string $key The AES key
195 * @param string $iv The IV (is used for CBC encoding)
196 * @param string $encrypted The encrypted data
198 * @return string decrypted data
200 private static function aesDecrypt(string $key, string $iv, string $encrypted): string
202 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
206 * Decodes incoming Diaspora message in the new format. This method returns false on an error.
208 * @param string $raw raw post message
209 * @param string $privKey The private key of the importer
210 * @param boolean $no_exit Don't do an http exit on error
213 * 'message' -> decoded Diaspora XML message
214 * 'author' -> author diaspora handle
215 * 'key' -> author public key (converted to pkcs#8)
216 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
217 * @throws \ImagickException
219 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
221 $data = json_decode($raw);
223 // Is it a private post? Then decrypt the outer Salmon
224 if (is_object($data)) {
225 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
226 $ciphertext = base64_decode($data->encrypted_magic_envelope);
228 $outer_key_bundle = '';
229 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
230 $j_outer_key_bundle = json_decode($outer_key_bundle);
232 if (!is_object($j_outer_key_bundle)) {
233 Logger::notice('Outer Salmon did not verify. Discarding.');
237 throw new \Friendica\Network\HTTPException\BadRequestException();
241 $outer_iv = base64_decode($j_outer_key_bundle->iv);
242 $outer_key = base64_decode($j_outer_key_bundle->key);
244 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
249 $basedom = XML::parseString($xml, true);
251 if (!is_object($basedom)) {
252 Logger::notice('Received data does not seem to be an XML. Discarding. '.$xml);
256 throw new \Friendica\Network\HTTPException\BadRequestException();
260 $base = $basedom->children(ActivityNamespace::SALMON_ME);
262 // Not sure if this cleaning is needed
263 $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
265 // Build the signed data
266 $type = $base->data[0]->attributes()->type[0];
267 $encoding = $base->encoding;
269 $signed_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
271 // This is the signature
272 $signature = Strings::base64UrlDecode($base->sig);
274 // Get the senders' public key
275 $key_id = $base->sig[0]->attributes()->key_id[0];
276 $author_addr = base64_decode($key_id);
277 if ($author_addr == '') {
278 Logger::notice('No author could be decoded. Discarding. Message: ' . $xml);
282 throw new \Friendica\Network\HTTPException\BadRequestException();
286 $key = self::key($author_addr);
288 Logger::notice("Couldn't get a key for handle " . $author_addr . ". Discarding.");
292 throw new \Friendica\Network\HTTPException\BadRequestException();
296 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
298 Logger::notice('Message did not verify. Discarding.');
302 throw new \Friendica\Network\HTTPException\BadRequestException();
307 'message' => (string)Strings::base64UrlDecode($base->data),
308 'author' => XML::unescape($author_addr),
309 'key' => (string)$key
314 * Decodes incoming Diaspora message in the deprecated format
316 * @param string $xml urldecoded Diaspora salmon
317 * @param string $privKey The private key of the importer
320 * 'message' -> decoded Diaspora XML message
321 * 'author' -> author diaspora handle
322 * 'key' -> author public key (converted to pkcs#8)
323 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
324 * @throws \ImagickException
326 public static function decode(string $xml, string $privKey = '')
329 $basedom = XML::parseString($xml);
331 if (!is_object($basedom)) {
332 Logger::notice('XML is not parseable.');
335 $children = $basedom->children('https://joindiaspora.com/protocol');
337 $inner_aes_key = null;
340 if ($children->header) {
342 $author_link = str_replace('acct:', '', $children->header->author_id);
344 // This happens with posts from a relais
345 if (empty($privKey)) {
346 Logger::info('This is no private post in the old format');
350 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
352 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
353 $ciphertext = base64_decode($encrypted_header->ciphertext);
355 $outer_key_bundle = '';
356 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
358 $j_outer_key_bundle = json_decode($outer_key_bundle);
360 $outer_iv = base64_decode($j_outer_key_bundle->iv);
361 $outer_key = base64_decode($j_outer_key_bundle->key);
363 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
365 Logger::info('decrypted', ['data' => $decrypted]);
366 $idom = XML::parseString($decrypted);
368 $inner_iv = base64_decode($idom->iv);
369 $inner_aes_key = base64_decode($idom->aes_key);
371 $author_link = str_replace('acct:', '', $idom->author_id);
374 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
376 // figure out where in the DOM tree our data is hiding
379 if ($dom->provenance->data) {
380 $base = $dom->provenance;
381 } elseif ($dom->env->data) {
383 } elseif ($dom->data) {
388 Logger::notice('unable to locate salmon data in xml');
389 throw new \Friendica\Network\HTTPException\BadRequestException();
393 // Stash the signature away for now. We have to find their key or it won't be good for anything.
394 $signature = Strings::base64UrlDecode($base->sig);
398 // strip whitespace so our data element will return to one big base64 blob
399 $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
402 // stash away some other stuff for later
404 $type = $base->data[0]->attributes()->type[0];
405 $keyhash = $base->sig[0]->attributes()->keyhash[0];
406 $encoding = $base->encoding;
410 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
414 $data = Strings::base64UrlDecode($data);
418 $inner_decrypted = $data;
420 // Decode the encrypted blob
421 $inner_encrypted = base64_decode($data);
422 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
426 Logger::notice('Could not retrieve author URI.');
427 throw new \Friendica\Network\HTTPException\BadRequestException();
429 // Once we have the author URI, go to the web and try to find their public key
430 // (first this will look it up locally if it is in the fcontact cache)
431 // This will also convert diaspora public key from pkcs#1 to pkcs#8
433 Logger::notice('Fetching key for '.$author_link);
434 $key = self::key($author_link);
437 Logger::notice('Could not retrieve author key.');
438 throw new \Friendica\Network\HTTPException\BadRequestException();
441 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
444 Logger::notice('Message did not verify. Discarding.');
445 throw new \Friendica\Network\HTTPException\BadRequestException();
448 Logger::notice('Message verified.');
451 'message' => (string)$inner_decrypted,
452 'author' => XML::unescape($author_link),
453 'key' => (string)$key
459 * Dispatches public messages and find the fitting receivers
461 * @param array $msg The post that will be dispatched
462 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
464 * @return int|bool The message id of the generated message, "true" or "false" if there was an error
465 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
466 * @throws \ImagickException
468 public static function dispatchPublic(array $msg, int $direction)
470 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
472 Logger::notice("diaspora is disabled");
476 if (!($fields = self::validPosting($msg))) {
477 Logger::notice("Invalid posting");
483 'page-flags' => User::PAGE_FLAGS_FREELOVE
485 $success = self::dispatch($importer, $msg, $fields, $direction);
491 * Dispatches the different message types to the different functions
493 * @param array $importer Array of the importer user
494 * @param array $msg The post that will be dispatched
495 * @param SimpleXMLElement $fields SimpleXML object that contains the message
496 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
498 * @return int|bool The message id of the generated message, "true" or "false" if there was an error
499 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
500 * @throws \ImagickException
502 public static function dispatch(array $importer, array $msg, SimpleXMLElement $fields = null, int $direction = self::PUSHED)
504 // The sender is the handle of the contact that sent the message.
505 // This will often be different with relayed messages (for example "like" and "comment")
506 $sender = $msg['author'];
508 // This is only needed for private postings since this is already done for public ones before
509 if (is_null($fields)) {
511 if (!($fields = self::validPosting($msg))) {
512 Logger::notice("Invalid posting");
519 $type = $fields->getName();
521 Logger::info('Received message', ['type' => $type, 'sender' => $sender, 'user' => $importer['uid']]);
524 case 'account_migration':
526 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
529 return self::receiveAccountMigration($importer, $fields);
531 case 'account_deletion':
532 return self::receiveAccountDeletion($fields);
535 return self::receiveComment($importer, $sender, $fields, $msg['message'], $direction);
539 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
542 return self::receiveContactRequest($importer, $fields);
546 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
549 return self::receiveConversation($importer, $msg, $fields);
552 return self::receiveLike($importer, $sender, $fields, $direction);
556 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
559 return self::receiveMessage($importer, $fields);
561 case 'participation':
563 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
566 return self::receiveParticipation($importer, $fields, $direction);
568 case 'photo': // Not implemented
569 return self::receivePhoto($importer, $fields);
571 case 'poll_participation': // Not implemented
572 return self::receivePollParticipation($importer, $fields);
576 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
579 return self::receiveProfile($importer, $fields);
582 return self::receiveReshare($importer, $fields, $msg['message'], $direction);
585 return self::receiveRetraction($importer, $sender, $fields);
587 case 'status_message':
588 return self::receiveStatusMessage($importer, $fields, $msg['message'], $direction);
591 Logger::notice("Unknown message type " . $type);
597 * Checks if a posting is valid and fetches the data fields.
599 * This function does not only check the signature.
600 * It also does the conversion between the old and the new diaspora format.
602 * @param array $msg Array with the XML, the sender handle and the sender signature
604 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
605 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
606 * @throws \ImagickException
608 private static function validPosting(array $msg)
610 $data = XML::parseString($msg['message']);
612 if (!is_object($data)) {
613 Logger::info('No valid XML', ['message' => $msg['message']]);
617 // Is this the new or the old version?
618 if ($data->getName() == 'XML') {
620 foreach ($data->post->children() as $child) {
628 $type = $element->getName();
631 Logger::debug("Got message type " . $type . ": " . $msg['message']);
633 // All retractions are handled identically from now on.
634 // In the new version there will only be "retraction".
635 if (in_array($type, ['signed_retraction', 'relayable_retraction']))
636 $type = 'retraction';
638 if ($type == 'request') {
642 $fields = new SimpleXMLElement('<' . $type . '/>');
645 $author_signature = null;
646 $parent_author_signature = null;
648 foreach ($element->children() as $fieldname => $entry) {
650 // Translation for the old XML structure
651 if ($fieldname == 'diaspora_handle') {
652 $fieldname = 'author';
654 if ($fieldname == 'participant_handles') {
655 $fieldname = 'participants';
657 if (in_array($type, ['like', 'participation'])) {
658 if ($fieldname == 'target_type') {
659 $fieldname = 'parent_type';
662 if ($fieldname == 'sender_handle') {
663 $fieldname = 'author';
665 if ($fieldname == 'recipient_handle') {
666 $fieldname = 'recipient';
668 if ($fieldname == 'root_diaspora_id') {
669 $fieldname = 'root_author';
671 if ($type == 'status_message') {
672 if ($fieldname == 'raw_message') {
676 if ($type == 'retraction') {
677 if ($fieldname == 'post_guid') {
678 $fieldname = 'target_guid';
680 if ($fieldname == 'type') {
681 $fieldname = 'target_type';
686 if (($fieldname == 'author_signature') && ($entry != '')) {
687 $author_signature = base64_decode($entry);
688 } elseif (($fieldname == 'parent_author_signature') && ($entry != '')) {
689 $parent_author_signature = base64_decode($entry);
690 } elseif (!in_array($fieldname, ['author_signature', 'parent_author_signature', 'target_author_signature'])) {
691 if ($signed_data != '') {
695 $signed_data .= $entry;
697 if (!in_array($fieldname, ['parent_author_signature', 'target_author_signature'])
698 || ($orig_type == 'relayable_retraction')
700 XML::copy($entry, $fields, $fieldname);
704 // This is something that shouldn't happen at all.
705 if (in_array($type, ['status_message', 'reshare', 'profile'])) {
706 if ($msg['author'] != $fields->author) {
707 Logger::notice("Message handle is not the same as envelope sender. Quitting this message.");
712 // Only some message types have signatures. So we quit here for the other types.
713 if (!in_array($type, ['comment', 'like'])) {
716 // No author_signature? This is a must, so we quit.
717 if (!isset($author_signature)) {
718 Logger::info("No author signature for type " . $type . " - Message: " . $msg['message']);
722 if (isset($parent_author_signature)) {
723 $key = self::key($msg['author']);
725 Logger::info('No key found for parent', ['author' => $msg['author']]);
729 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, 'sha256')) {
730 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);
735 $key = self::key($fields->author);
737 Logger::info('No key found', ['author' => $fields->author]);
741 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, 'sha256')) {
742 Logger::info("No valid author signature for author " . $fields->author . " in type " . $type . " - signed data: " . $signed_data . " - Message: " . $msg['message'] . " - Signature " . $author_signature);
750 * Fetches the public key for a given handle
752 * @param string $handle The handle
754 * @return string The public key
755 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
756 * @throws \ImagickException
758 private static function key(string $handle): string
760 $handle = strval($handle);
762 Logger::notice("Fetching diaspora key for: " . $handle);
764 $fcontact = FContact::getByURL($handle);
766 return $fcontact['pubkey'];
773 * get a handle (user@domain.tld) from a given contact id
775 * @param int $contact_id The id in the contact table
776 * @param int $pcontact_id The id in the contact table (Used for the public contact)
778 * @return string the handle
781 private static function handleFromContact(int $contact_id, int $pcontact_id = 0): string
785 if ($pcontact_id != 0) {
786 $contact = Contact::getById($pcontact_id, ['addr']);
787 if (DBA::isResult($contact)) {
788 $handle = $contact['addr'];
792 if (empty($handle)) {
793 $contact = Contact::getById($contact_id, ['addr']);
794 if (DBA::isResult($contact)) {
795 $handle = $contact['addr'];
799 return strtolower($handle);
803 * Get a contact id for a given handle
805 * @todo Move to Friendica\Model\Contact
807 * @param int $uid The user id
808 * @param string $handle The handle in the format user@domain.tld
810 * @return array Contact data
811 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
812 * @throws \ImagickException
814 private static function contactByHandle(int $uid, string $handle): array
816 return Contact::getByURL($handle, null, [], $uid);
820 * Checks if the given contact url does support ActivityPub
822 * @param string $url profile url
823 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
825 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
826 * @throws \ImagickException
828 public static function isSupportedByContactUrl(string $url, $update = null)
830 return !empty(FContact::getByURL($url, $update));
834 * Check if posting is allowed for this contact
836 * @param array $importer Array of the importer user
837 * @param array $contact The contact that is checked
838 * @param bool $is_comment Is the check for a comment?
840 * @return bool is the contact allowed to post?
842 private static function postAllow(array $importer, array $contact, bool $is_comment = false): bool
845 * Perhaps we were already sharing with this person. Now they're sharing with us.
846 * That makes us friends.
847 * Normally this should have handled by getting a request - but this could get lost
849 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
850 // It is not removed by now. Possibly the code is needed?
851 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
853 // array('rel' => Contact::FRIEND, 'writable' => true),
854 // array('id' => $contact["id"], 'uid' => $contact["uid"])
857 // $contact["rel"] = Contact::FRIEND;
858 // Logger::notice("defining user ".$contact["nick"]." as friend");
861 // Contact server is blocked
862 if (Network::isUrlBlocked($contact['url'])) {
864 // We don't seem to like that person
865 } elseif ($contact['blocked']) {
866 // Maybe blocked, don't accept.
868 // We are following this person?
869 } elseif (($contact['rel'] == Contact::SHARING) || ($contact['rel'] == Contact::FRIEND)) {
870 // Yes, then it is fine.
872 // Is the message a global user or a comment?
873 } elseif (($importer['uid'] == 0) || $is_comment) {
874 // Messages for the global users and comments are always accepted
882 * Fetches the contact id for a handle and checks if posting is allowed
884 * @param array $importer Array of the importer user
885 * @param string $handle The checked handle in the format user@domain.tld
886 * @param bool $is_comment Is the check for a comment?
888 * @return array|bool The contact data or false on error
891 private static function allowedContactByHandle(array $importer, string $handle, bool $is_comment = false)
893 $contact = self::contactByHandle($importer['uid'], $handle);
895 Logger::notice("A Contact for handle " . $handle . " and user " . $importer['uid'] . " was not found");
896 // If a contact isn't found, we accept it anyway if it is a comment
897 if ($is_comment && ($importer['uid'] != 0)) {
898 return self::contactByHandle(0, $handle);
899 } elseif ($is_comment) {
906 if (!self::postAllow($importer, $contact, $is_comment)) {
907 Logger::notice("The handle: " . $handle . " is not allowed to post to user " . $importer['uid']);
914 * Does the message already exists on the system?
916 * @param int $uid The user id
917 * @param string $guid The guid of the message
919 * @return int|bool message id if the message already was stored into the system - or false.
922 private static function messageExists(int $uid, string $guid)
924 $item = Post::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
925 if (DBA::isResult($item)) {
926 Logger::notice("message " . $guid . " already exists for user " . $uid);
934 * Checks for links to posts in a message
936 * @param array $item The item array
939 private static function fetchGuid(array $item)
941 preg_replace_callback(
942 "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism",
943 function ($match) use ($item) {
944 self::fetchGuidSub($match, $item);
949 preg_replace_callback(
950 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
951 function ($match) use ($item) {
952 self::fetchGuidSub($match, $item);
959 * Checks for relative /people/* links in an item body to match local
960 * contacts or prepends the remote host taken from the author link.
962 * @param string $body The item body to replace links from
963 * @param string $author_link The author link for missing local contact fallback
965 * @return string the replaced string
967 public static function replacePeopleGuid(string $body, string $author_link): string
969 $return = preg_replace_callback(
970 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
971 function ($match) use ($author_link) {
973 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
974 // 1 => '0123456789abcdef'
976 $handle = FContact::getUrlByGuid($match[1]);
979 $return = '@[url=' . $handle . ']' . $match[2] . '[/url]';
981 // No local match, restoring absolute remote URL from author scheme and host
982 $author_url = parse_url($author_link);
983 $return = '[url=' . $author_url['scheme'] . '://' . $author_url['host'] . '/people/' . $match[1] . ']' . $match[2] . '[/url]';
995 * sub function of "fetchGuid" which checks for links in messages
997 * @param array $match array containing a link that has to be checked for a message link
998 * @param array $item The item array
1000 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1001 * @throws \ImagickException
1003 private static function fetchGuidSub(array $match, array $item)
1005 if (!self::storeByGuid($match[1], $item['author-link'], true)) {
1006 self::storeByGuid($match[1], $item['owner-link'], true);
1011 * Fetches an item with a given guid from a given server
1013 * @param string $guid the message guid
1014 * @param string $server The server address
1015 * @param bool $force Forced fetch
1017 * @return int|bool the message id of the stored message or false
1018 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1019 * @throws \ImagickException
1021 private static function storeByGuid(string $guid, string $server, bool $force)
1023 $serverparts = parse_url($server);
1025 if (empty($serverparts['host']) || empty($serverparts['scheme'])) {
1029 $server = $serverparts['scheme'] . '://' . $serverparts['host'];
1031 Logger::info("Trying to fetch item " . $guid . " from " . $server);
1033 $msg = self::message($guid, $server);
1039 Logger::info("Successfully fetched item " . $guid . " from " . $server);
1041 // Now call the dispatcher
1042 return self::dispatchPublic($msg, $force ? self::FORCED_FETCH : self::FETCHED);
1046 * Fetches a message from a server
1048 * @param string $guid message guid
1049 * @param string $server The url of the server
1050 * @param int $level Endless loop prevention
1053 * 'message' => The message XML
1054 * 'author' => The author handle
1055 * 'key' => The public key of the author
1056 * @throws \Exception
1058 public static function message(string $guid, string $server, int $level = 0)
1064 // This will work for new Diaspora servers and Friendica servers from 3.5
1065 $source_url = $server . '/fetch/post/' . urlencode($guid);
1067 Logger::info("Fetch post from " . $source_url);
1069 $envelope = DI::httpClient()->fetch($source_url, HttpClientAccept::MAGIC);
1071 Logger::info("Envelope was fetched.");
1072 $x = self::verifyMagicEnvelope($envelope);
1074 Logger::info("Envelope could not be verified.");
1076 Logger::info("Envelope was verified.");
1086 $source_xml = XML::parseString($x);
1088 if (!is_object($source_xml)) {
1092 if ($source_xml->post->reshare) {
1093 // Reshare of a reshare - old Diaspora version
1094 Logger::info("Message is a reshare");
1095 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1096 } elseif ($source_xml->getName() == "reshare") {
1097 // Reshare of a reshare - new Diaspora version
1098 Logger::info("Message is a new reshare");
1099 return self::message($source_xml->root_guid, $server, ++$level);
1104 // Fetch the author - for the old and the new Diaspora version
1105 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1106 $author = (string)$source_xml->post->status_message->diaspora_handle;
1107 } elseif ($source_xml->author && ($source_xml->getName() == 'status_message')) {
1108 $author = (string)$source_xml->author;
1111 // If this isn't a "status_message" then quit
1113 Logger::info("Message doesn't seem to be a status message");
1119 'author' => $author,
1120 'key' => self::key($author)
1125 * Fetches an item with a given URL
1127 * @param string $url the message url
1128 * @param int $uid User id
1130 * @return int|bool the message id of the stored message or false
1131 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1132 * @throws \ImagickException
1134 public static function fetchByURL(string $url, int $uid = 0)
1136 // Check for Diaspora (and Friendica) typical paths
1137 if (!preg_match('=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i', $url, $matches)) {
1138 Logger::info('Invalid url', ['url' => $url]);
1142 $guid = urldecode($matches[2]);
1144 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1145 if (DBA::isResult($item)) {
1146 Logger::info('Found', ['id' => $item['id']]);
1150 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1151 $ret = self::storeByGuid($guid, $matches[1], true);
1152 Logger::info('Result', ['ret' => $ret]);
1154 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1155 if (DBA::isResult($item)) {
1156 Logger::info('Found', ['id' => $item['id']]);
1159 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1165 * Fetches the item record of a given guid
1167 * @param int $uid The user id
1168 * @param string $guid message guid
1169 * @param string $author The handle of the item
1170 * @param array $contact The contact of the item owner
1172 * @return array|bool the item record or false on failure
1173 * @throws \Exception
1175 private static function parentItem(int $uid, string $guid, string $author, array $contact)
1177 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1178 'author-name', 'author-link', 'author-avatar', 'gravity',
1179 'owner-name', 'owner-link', 'owner-avatar'];
1180 $condition = ['uid' => $uid, 'guid' => $guid];
1181 $item = Post::selectFirst($fields, $condition);
1183 if (!DBA::isResult($item)) {
1184 $person = FContact::getByURL($author);
1185 $result = self::storeByGuid($guid, $person['url'], false);
1187 // We don't have an url for items that arrived at the public dispatcher
1188 if (!$result && !empty($contact['url'])) {
1189 $result = self::storeByGuid($guid, $contact['url'], false);
1193 Logger::info("Fetched missing item " . $guid . " - result: " . $result);
1195 $item = Post::selectFirst($fields, $condition);
1199 if (!DBA::isResult($item)) {
1200 Logger::notice("parent item not found: parent: " . $guid . " - user: " . $uid);
1203 Logger::notice("parent item found: parent: " . $guid . " - user: " . $uid);
1209 * returns contact details
1211 * @param array $def_contact The default contact if the person isn't found
1212 * @param array $person The record of the person
1213 * @param int $uid The user id
1216 * 'cid' => contact id
1217 * 'network' => network type
1218 * @throws \Exception
1220 private static function authorContactByUrl(array $def_contact, array $person, int $uid): array
1222 $condition = ['nurl' => Strings::normaliseLink($person['url']), 'uid' => $uid];
1223 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1224 if (DBA::isResult($contact)) {
1225 $cid = $contact['id'];
1226 $network = $contact['network'];
1228 $cid = $def_contact['id'];
1229 $network = Protocol::DIASPORA;
1234 'network' => $network
1239 * Is the profile a hubzilla profile?
1241 * @param string $url The profile link
1243 * @return bool is it a hubzilla server?
1245 private static function isHubzilla(string $url): bool
1247 return strstr($url, '/channel/');
1251 * Generate a post link with a given handle and message guid
1253 * @param string $addr The user handle
1254 * @param string $guid message guid
1255 * @param string $parent_guid optional parent guid
1257 * @return string the post link
1258 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1259 * @throws \ImagickException
1261 private static function plink(string $addr, string $guid, string $parent_guid = ''): string
1263 $contact = Contact::getByURL($addr);
1264 if (empty($contact)) {
1265 Logger::info('No contact data for address', ['addr' => $addr]);
1269 if (empty($contact['baseurl'])) {
1270 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1271 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1275 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1276 if (!empty($gserver['platform'])) {
1277 $platform = strtolower($gserver['platform']);
1278 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1281 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1282 if (self::isHubzilla($contact['url'])) {
1283 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1284 $platform = 'hubzilla';
1285 } elseif ($contact['network'] == Protocol::DFRN) {
1286 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1287 $platform = 'friendica';
1291 if ($platform == 'friendica') {
1292 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1295 if ($platform == 'hubzilla') {
1296 return $contact['baseurl'] . '/item/' . $guid;
1299 if ($platform == 'socialhome') {
1300 return $contact['baseurl'] . '/content/' . $guid;
1303 if ($platform != 'diaspora') {
1304 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1308 if ($parent_guid != '') {
1309 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1311 return $contact['baseurl'] . '/posts/' . $guid;
1316 * Receives account migration
1318 * @param array $importer Array of the importer user
1319 * @param SimpleXMLElement $data The message object
1321 * @return bool Success
1322 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1323 * @throws \ImagickException
1325 private static function receiveAccountMigration(array $importer, SimpleXMLElement $data): bool
1327 $old_handle = XML::unescape($data->author);
1328 $new_handle = XML::unescape($data->profile->author);
1329 $signature = XML::unescape($data->signature);
1331 $contact = self::contactByHandle($importer['uid'], $old_handle);
1333 Logger::notice("cannot find contact for sender: " . $old_handle . " and user " . $importer['uid']);
1337 Logger::notice("Got migration for " . $old_handle . ", to " . $new_handle . " with user " . $importer['uid']);
1340 $signed_text = 'AccountMigration:' . $old_handle . ':' . $new_handle;
1341 $key = self::key($old_handle);
1342 if (!Crypto::rsaVerify($signed_text, $signature, $key, 'sha256')) {
1343 Logger::notice('No valid signature for migration.');
1347 // Update the profile
1348 self::receiveProfile($importer, $data->profile);
1350 // change the technical stuff in contact
1351 $data = Probe::uri($new_handle);
1352 if ($data['network'] == Protocol::PHANTOM) {
1353 Logger::notice("Account for " . $new_handle . " couldn't be probed.");
1358 'url' => $data['url'],
1359 'nurl' => Strings::normaliseLink($data['url']),
1360 'name' => $data['name'],
1361 'nick' => $data['nick'],
1362 'addr' => $data['addr'],
1363 'batch' => $data['batch'],
1364 'notify' => $data['notify'],
1365 'poll' => $data['poll'],
1366 'network' => $data['network']
1369 Contact::update($fields, ['addr' => $old_handle]);
1371 Logger::notice('Contacts are updated.');
1377 * Processes an account deletion
1379 * @param SimpleXMLElement $data The message object
1381 * @return bool Success
1382 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1384 private static function receiveAccountDeletion(SimpleXMLElement $data): bool
1386 $author = XML::unescape($data->author);
1388 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1389 while ($contact = DBA::fetch($contacts)) {
1390 Contact::remove($contact['id']);
1392 DBA::close($contacts);
1394 Logger::notice('Removed contacts for ' . $author);
1400 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1402 * @param string $author Author handle
1403 * @param string $guid Message guid
1404 * @param boolean $onlyfound Only return uri when found in the database
1406 * @return string The constructed uri or the one from our database or empty string on if $onlyfound is true
1407 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1408 * @throws \ImagickException
1410 private static function getUriFromGuid(string $author, string $guid, bool $onlyfound = false): string
1412 $item = Post::selectFirst(['uri'], ['guid' => $guid]);
1413 if (DBA::isResult($item)) {
1414 return $item['uri'];
1415 } elseif (!$onlyfound) {
1416 $person = FContact::getByURL($author);
1418 $parts = parse_url($person['url']);
1419 unset($parts['path']);
1420 $host_url = Network::unparseURL($parts);
1422 return $host_url . '/objects/' . $guid;
1429 * Store the mentions in the tag table
1431 * @param integer $uriid
1432 * @param string $text
1434 private static function storeMentions(int $uriid, string $text)
1436 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1437 if (empty($matches)) {
1442 * Matching values for the preg match
1443 * [1] = mention type (@ or !)
1444 * [2] = name (optional)
1448 foreach ($matches as $match) {
1449 if (empty($match)) {
1453 $person = FContact::getByURL($match[3]);
1454 if (empty($person)) {
1458 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1463 * Processes an incoming comment
1465 * @param array $importer Array of the importer user
1466 * @param string $sender The sender of the message
1467 * @param SimpleXMLElement $data The message object
1468 * @param string $xml The original XML of the message
1469 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1471 * @return int The message id of the generated comment or "false" if there was an error
1472 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1473 * @throws \ImagickException
1475 private static function receiveComment(array $importer, string $sender, SimpleXMLElement $data, string $xml, int $direction): bool
1477 $author = XML::unescape($data->author);
1478 $guid = XML::unescape($data->guid);
1479 $parent_guid = XML::unescape($data->parent_guid);
1480 $text = XML::unescape($data->text);
1482 if (isset($data->created_at)) {
1483 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1485 $created_at = DateTimeFormat::utcNow();
1488 if (isset($data->thread_parent_guid)) {
1489 $thread_parent_guid = XML::unescape($data->thread_parent_guid);
1490 $thr_parent = self::getUriFromGuid('', $thread_parent_guid, true);
1495 $contact = self::allowedContactByHandle($importer, $sender, true);
1500 if (!empty($contact['gsid'])) {
1501 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1504 $message_id = self::messageExists($importer['uid'], $guid);
1509 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1510 if (!$toplevel_parent_item) {
1514 $person = FContact::getByURL($author);
1515 if (!is_array($person)) {
1516 Logger::notice("unable to find author details");
1520 // Fetch the contact id - if we know this contact
1521 $author_contact = self::authorContactByUrl($contact, $person, $importer['uid']);
1525 $datarray['uid'] = $importer['uid'];
1526 $datarray['contact-id'] = $author_contact['cid'];
1527 $datarray['network'] = $author_contact['network'];
1529 $datarray['author-link'] = $person['url'];
1530 $datarray['author-id'] = Contact::getIdForURL($person['url'], 0);
1532 $datarray['owner-link'] = $contact['url'];
1533 $datarray['owner-id'] = Contact::getIdForURL($contact['url'], 0);
1535 // Will be overwritten for sharing accounts in Item::insert
1536 if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
1537 $datarray['post-reason'] = Item::PR_FETCHED;
1538 } elseif ($datarray['uid'] == 0) {
1539 $datarray['post-reason'] = Item::PR_GLOBAL;
1541 $datarray['post-reason'] = Item::PR_COMMENT;
1544 $datarray['guid'] = $guid;
1545 $datarray['uri'] = self::getUriFromGuid($author, $guid);
1546 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1548 $datarray['verb'] = Activity::POST;
1549 $datarray['gravity'] = GRAVITY_COMMENT;
1551 $datarray['thr-parent'] = $thr_parent ?: $toplevel_parent_item['uri'];
1553 $datarray['object-type'] = Activity\ObjectType::COMMENT;
1554 $datarray['post-type'] = Item::PT_NOTE;
1556 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1557 $datarray['source'] = $xml;
1558 $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
1560 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
1562 $datarray['plink'] = self::plink($author, $guid, $toplevel_parent_item['guid']);
1563 $body = Markdown::toBBCode($text);
1565 $datarray['body'] = self::replacePeopleGuid($body, $person['url']);
1567 self::storeMentions($datarray['uri-id'], $text);
1568 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
1570 self::fetchGuid($datarray);
1572 // If we are the origin of the parent we store the original data.
1573 // We notify our followers during the item storage.
1574 if ($toplevel_parent_item['origin']) {
1575 $datarray['diaspora_signed_text'] = json_encode($data);
1578 if (Item::isTooOld($datarray)) {
1579 Logger::info('Comment is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1583 $message_id = Item::insert($datarray);
1585 if ($message_id <= 0) {
1590 Logger::info("Stored comment " . $datarray['guid'] . " with message id " . $message_id);
1591 if ($datarray['uid'] == 0) {
1592 Item::distribute($message_id, json_encode($data));
1600 * processes and stores private messages
1602 * @param array $importer Array of the importer user
1603 * @param array $contact The contact of the message
1604 * @param SimpleXMLElement $data The message object
1605 * @param array $msg Array of the processed message, author handle and key
1606 * @param object $mesg The private message
1607 * @param array $conversation The conversation record to which this message belongs
1609 * @return bool "true" if it was successful
1610 * @throws \Exception
1611 * @todo Find type-hint for $mesg and update documentation
1613 private static function receiveConversationMessage(array $importer, array $contact, SimpleXMLElement $data, array $msg, $mesg, array $conversation): bool
1615 $author = XML::unescape($data->author);
1616 $guid = XML::unescape($data->guid);
1617 $subject = XML::unescape($data->subject);
1619 // "diaspora_handle" is the element name from the old version
1620 // "author" is the element name from the new version
1621 if ($mesg->author) {
1622 $msg_author = XML::unescape($mesg->author);
1623 } elseif ($mesg->diaspora_handle) {
1624 $msg_author = XML::unescape($mesg->diaspora_handle);
1629 $msg_guid = XML::unescape($mesg->guid);
1630 $msg_conversation_guid = XML::unescape($mesg->conversation_guid);
1631 $msg_text = XML::unescape($mesg->text);
1632 $msg_created_at = DateTimeFormat::utc(XML::unescape($mesg->created_at));
1634 if ($msg_conversation_guid != $guid) {
1635 Logger::notice("message conversation guid does not belong to the current conversation.");
1639 $body = Markdown::toBBCode($msg_text);
1640 $message_uri = $msg_author.":".$msg_guid;
1642 $person = FContact::getByURL($msg_author);
1644 return Mail::insert([
1645 'uid' => $importer['uid'],
1646 'guid' => $msg_guid,
1647 'convid' => $conversation['id'],
1648 'from-name' => $person['name'],
1649 'from-photo' => $person['photo'],
1650 'from-url' => $person['url'],
1651 'contact-id' => $contact['id'],
1652 'title' => $subject,
1654 'uri' => $message_uri,
1655 'parent-uri' => $author . ':' . $guid,
1656 'created' => $msg_created_at
1661 * Processes new private messages (answers to private messages are processed elsewhere)
1663 * @param array $importer Array of the importer user
1664 * @param array $msg Array of the processed message, author handle and key
1665 * @param SimpleXMLElement $data The message object
1667 * @return bool Success
1668 * @throws \Exception
1670 private static function receiveConversation(array $importer, array $msg, SimpleXMLElement $data)
1672 $author = XML::unescape($data->author);
1673 $guid = XML::unescape($data->guid);
1674 $subject = XML::unescape($data->subject);
1675 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1676 $participants = XML::unescape($data->participants);
1678 $messages = $data->message;
1680 if (!count($messages)) {
1681 Logger::notice("empty conversation");
1685 $contact = self::allowedContactByHandle($importer, $msg['author'], true);
1690 if (!empty($contact['gsid'])) {
1691 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1694 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1695 if (!DBA::isResult($conversation)) {
1696 $r = DBA::insert('conv', [
1697 'uid' => $importer['uid'],
1699 'creator' => $author,
1700 'created' => $created_at,
1701 'updated' => DateTimeFormat::utcNow(),
1702 'subject' => $subject,
1703 'recips' => $participants]);
1705 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1708 if (!$conversation) {
1709 Logger::notice("unable to create conversation.");
1713 foreach ($messages as $mesg) {
1714 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1721 * Processes "like" messages
1723 * @param array $importer Array of the importer user
1724 * @param string $sender The sender of the message
1725 * @param SimpleXMLElement $data The message object
1726 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1728 * @return bool Success or failure
1729 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1730 * @throws \ImagickException
1732 private static function receiveLike(array $importer, string $sender, SimpleXMLElement $data, int $direction): bool
1734 $author = XML::unescape($data->author);
1735 $guid = XML::unescape($data->guid);
1736 $parent_guid = XML::unescape($data->parent_guid);
1737 $parent_type = XML::unescape($data->parent_type);
1738 $positive = XML::unescape($data->positive);
1740 // likes on comments aren't supported by Diaspora - only on posts
1741 // But maybe this will be supported in the future, so we will accept it.
1742 if (!in_array($parent_type, ['Post', 'Comment'])) {
1746 $contact = self::allowedContactByHandle($importer, $sender, true);
1751 if (!empty($contact['gsid'])) {
1752 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1755 $message_id = self::messageExists($importer['uid'], $guid);
1760 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1761 if (!$toplevel_parent_item) {
1765 $person = FContact::getByURL($author);
1766 if (!is_array($person)) {
1767 Logger::notice("unable to find author details");
1771 // Fetch the contact id - if we know this contact
1772 $author_contact = self::authorContactByUrl($contact, $person, $importer['uid']);
1774 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1775 // We would accept this anyhow.
1776 if ($positive == 'true') {
1777 $verb = Activity::LIKE;
1779 $verb = Activity::DISLIKE;
1784 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1785 $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
1787 $datarray['uid'] = $importer['uid'];
1788 $datarray['contact-id'] = $author_contact['cid'];
1789 $datarray['network'] = $author_contact['network'];
1791 $datarray['owner-link'] = $datarray['author-link'] = $person['url'];
1792 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($person['url'], 0);
1794 $datarray['guid'] = $guid;
1795 $datarray['uri'] = self::getUriFromGuid($author, $guid);
1797 $datarray['verb'] = $verb;
1798 $datarray['gravity'] = GRAVITY_ACTIVITY;
1799 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1801 $datarray['object-type'] = Activity\ObjectType::NOTE;
1803 $datarray['body'] = $verb;
1805 // Diaspora doesn't provide a date for likes
1806 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
1808 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1809 if ($toplevel_parent_item['gravity'] != GRAVITY_PARENT) {
1810 $toplevel = Post::selectFirst(['origin'], ['id' => $toplevel_parent_item['parent']]);
1811 $origin = $toplevel['origin'];
1813 $origin = $toplevel_parent_item['origin'];
1816 // If we are the origin of the parent we store the original data.
1817 // We notify our followers during the item storage.
1819 $datarray['diaspora_signed_text'] = json_encode($data);
1822 if (Item::isTooOld($datarray)) {
1823 Logger::info('Like is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1827 $message_id = Item::insert($datarray);
1829 if ($message_id <= 0) {
1834 Logger::info("Stored like " . $datarray['guid'] . " with message id " . $message_id);
1835 if ($datarray['uid'] == 0) {
1836 Item::distribute($message_id, json_encode($data));
1844 * Processes private messages
1846 * @param array $importer Array of the importer user
1847 * @param SimpleXMLElement $data The message object
1849 * @return bool Success?
1850 * @throws \Exception
1852 private static function receiveMessage(array $importer, SimpleXMLElement $data): bool
1854 $author = XML::unescape($data->author);
1855 $guid = XML::unescape($data->guid);
1856 $conversation_guid = XML::unescape($data->conversation_guid);
1857 $text = XML::unescape($data->text);
1858 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1860 $contact = self::allowedContactByHandle($importer, $author, true);
1865 if (!empty($contact['gsid'])) {
1866 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1869 $conversation = null;
1871 $condition = ['uid' => $importer['uid'], 'guid' => $conversation_guid];
1872 $conversation = DBA::selectFirst('conv', [], $condition);
1874 if (!DBA::isResult($conversation)) {
1875 Logger::notice("conversation not available.");
1879 $message_uri = $author . ':' . $guid;
1881 $person = FContact::getByURL($author);
1883 Logger::notice("unable to find author details");
1887 $body = Markdown::toBBCode($text);
1889 $body = self::replacePeopleGuid($body, $person["url"]);
1891 return Mail::insert([
1892 'uid' => $importer['uid'],
1894 'convid' => $conversation['id'],
1895 'from-name' => $person['name'],
1896 'from-photo' => $person['photo'],
1897 'from-url' => $person['url'],
1898 'contact-id' => $contact['id'],
1899 'title' => $conversation['subject'],
1902 'uri' => $message_uri,
1903 'parent-uri' => $author.":".$conversation['guid'],
1904 'created' => $created_at
1909 * Processes participations - unsupported by now
1911 * @param array $importer Array of the importer user
1912 * @param SimpleXMLElement $data The message object
1913 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1915 * @return bool success
1916 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1917 * @throws \ImagickException
1919 private static function receiveParticipation(array $importer, SimpleXMLElement $data, int $direction): bool
1921 $author = strtolower(XML::unescape($data->author));
1922 $guid = XML::unescape($data->guid);
1923 $parent_guid = XML::unescape($data->parent_guid);
1925 $contact = self::allowedContactByHandle($importer, $author, true);
1930 if (!empty($contact['gsid'])) {
1931 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1934 if (self::messageExists($importer['uid'], $guid)) {
1938 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1939 if (!$toplevel_parent_item) {
1943 if (!$toplevel_parent_item['origin']) {
1944 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1947 if (!in_array($toplevel_parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
1948 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1952 $person = FContact::getByURL($author);
1953 if (!is_array($person)) {
1954 Logger::notice("Person not found: " . $author);
1958 $author_contact = self::authorContactByUrl($contact, $person, $importer['uid']);
1960 // Store participation
1963 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1964 $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
1966 $datarray['uid'] = $importer['uid'];
1967 $datarray['contact-id'] = $author_contact['cid'];
1968 $datarray['network'] = $author_contact['network'];
1970 $datarray['owner-link'] = $datarray['author-link'] = $person['url'];
1971 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($person['url'], 0);
1973 $datarray['guid'] = $guid;
1974 $datarray['uri'] = self::getUriFromGuid($author, $guid);
1976 $datarray['verb'] = Activity::FOLLOW;
1977 $datarray['gravity'] = GRAVITY_ACTIVITY;
1978 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1980 $datarray['object-type'] = Activity\ObjectType::NOTE;
1982 $datarray['body'] = Activity::FOLLOW;
1984 // Diaspora doesn't provide a date for a participation
1985 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
1987 if (Item::isTooOld($datarray)) {
1988 Logger::info('Participation is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1992 $message_id = Item::insert($datarray);
1994 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
1996 // Send all existing comments and likes to the requesting server
1997 $comments = Post::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb'],
1998 ['parent' => $toplevel_parent_item['id'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
1999 while ($comment = Post::fetch($comments)) {
2000 if (in_array($comment['verb'], [Activity::FOLLOW, Activity::TAG])) {
2001 Logger::info('participation messages are not relayed', ['item' => $comment['id']]);
2005 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
2006 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2010 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
2011 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2015 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact['cid']]);
2016 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $author_contact['cid'])) {
2017 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2020 DBA::close($comments);
2026 * Processes photos - unneeded
2028 * @param array $importer Array of the importer user
2029 * @param SimpleXMLElement $data The message object
2031 * @return bool always true
2033 private static function receivePhoto(array $importer, $data)
2035 // There doesn't seem to be a reason for this function,
2036 // since the photo data is transmitted in the status message as well
2041 * Processes poll participations - unssupported
2043 * @param array $importer Array of the importer user
2044 * @param object $data The message object
2046 * @return bool always true
2048 private static function receivePollParticipation(array $importer, $data)
2050 // We don't support polls by now
2055 * Processes incoming profile updates
2057 * @param array $importer Array of the importer user
2058 * @param SimpleXMLElement $data The message object
2060 * @return bool Success
2061 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2062 * @throws \ImagickException
2064 private static function receiveProfile(array $importer, SimpleXMLElement $data): bool
2066 $author = strtolower(XML::unescape($data->author));
2068 $contact = self::contactByHandle($importer['uid'], $author);
2073 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? ' ' . XML::unescape($data->last_name) : '');
2074 $image_url = XML::unescape($data->image_url);
2075 $birthday = XML::unescape($data->birthday);
2076 $about = Markdown::toBBCode(XML::unescape($data->bio));
2077 $location = Markdown::toBBCode(XML::unescape($data->location));
2078 $searchable = (XML::unescape($data->searchable) == 'true');
2079 $nsfw = (XML::unescape($data->nsfw) == 'true');
2080 $tags = XML::unescape($data->tag_string);
2082 $tags = explode('#', $tags);
2085 foreach ($tags as $tag) {
2086 $tag = trim(strtolower($tag));
2092 $keywords = implode(', ', $keywords);
2094 $handle_parts = explode('@', $author);
2095 $nick = $handle_parts[0];
2098 $name = $handle_parts[0];
2101 if (preg_match('|^https?://|', $image_url) === 0) {
2102 // @TODO No HTTPS here?
2103 $image_url = 'http://' . $handle_parts[1] . $image_url;
2106 Contact::updateAvatar($contact['id'], $image_url);
2108 // Generic birthday. We don't know the timezone. The year is irrelevant.
2110 $birthday = str_replace('1000', '1901', $birthday);
2112 if ($birthday != '') {
2113 $birthday = DateTimeFormat::utc($birthday, 'Y-m-d');
2116 // this is to prevent multiple birthday notifications in a single year
2117 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2119 if (substr($birthday, 5) === substr($contact['bd'], 5)) {
2120 $birthday = $contact['bd'];
2123 $fields = ['name' => $name, 'location' => $location,
2124 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2125 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2126 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2128 if (!empty($birthday)) {
2129 $fields['bd'] = $birthday;
2132 Contact::update($fields, ['id' => $contact['id']]);
2134 Logger::info("Profile of contact " . $contact['id'] . " stored for user " . $importer['uid']);
2140 * Processes incoming friend requests
2142 * @param array $importer Array of the importer user
2143 * @param array $contact The contact that send the request
2145 * @throws \Exception
2147 private static function receiveRequestMakeFriend(array $importer, array $contact)
2149 if ($contact['rel'] == Contact::SHARING) {
2151 ['rel' => Contact::FRIEND, 'writable' => true],
2152 ['id' => $contact['id'], 'uid' => $importer['uid']]
2158 * Processes incoming sharing notification
2160 * @param array $importer Array of the importer user
2161 * @param SimpleXMLElement $data The message object
2163 * @return bool Success
2164 * @throws \Exception
2166 private static function receiveContactRequest(array $importer, SimpleXMLElement $data): bool
2168 $author = XML::unescape($data->author);
2169 $recipient = XML::unescape($data->recipient);
2171 if (!$author || !$recipient) {
2175 // the current protocol version doesn't know these fields
2176 // That means that we will assume their existance
2177 if (isset($data->following)) {
2178 $following = (XML::unescape($data->following) == 'true');
2183 if (isset($data->sharing)) {
2184 $sharing = (XML::unescape($data->sharing) == 'true');
2189 $contact = self::contactByHandle($importer['uid'], $author);
2191 // perhaps we were already sharing with this person. Now they're sharing with us.
2192 // That makes us friends.
2195 Logger::info("Author " . $author . " (Contact " . $contact['id'] . ") wants to follow us.");
2196 self::receiveRequestMakeFriend($importer, $contact);
2198 // refetch the contact array
2199 $contact = self::contactByHandle($importer['uid'], $author);
2201 // If we are now friends, we are sending a share message.
2202 // Normally we needn't to do so, but the first message could have been vanished.
2203 if (in_array($contact['rel'], [Contact::FRIEND])) {
2204 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2205 if (DBA::isResult($user)) {
2206 Logger::info("Sending share message to author " . $author . " - Contact: " . $contact['id'] . " - User: " . $importer['uid']);
2207 self::sendShare($user, $contact);
2212 Logger::info("Author " . $author . " doesn't want to follow us anymore.");
2213 Contact::removeFollower($contact);
2218 if (!$following && $sharing && in_array($importer['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2219 Logger::info("Author " . $author . " wants to share with us - but doesn't want to listen. Request is ignored.");
2221 } elseif (!$following && !$sharing) {
2222 Logger::info("Author " . $author . " doesn't want anything - and we don't know the author. Request is ignored.");
2224 } elseif (!$following && $sharing) {
2225 Logger::info("Author " . $author . " wants to share with us.");
2226 } elseif ($following && $sharing) {
2227 Logger::info("Author " . $author . " wants to have a bidirectional conection.");
2228 } elseif ($following && !$sharing) {
2229 Logger::info("Author " . $author . " wants to listen to us.");
2232 $ret = FContact::getByURL($author);
2234 if (!$ret || ($ret['network'] != Protocol::DIASPORA)) {
2235 Logger::notice("Cannot resolve diaspora handle " . $author . " for ".$recipient);
2239 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2241 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2246 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2247 'author-link' => $ret['url']];
2249 $result = Contact::addRelationship($importer, $contact, $item, false);
2250 if ($result === true) {
2251 $contact_record = self::contactByHandle($importer['uid'], $author);
2252 if (!$contact_record) {
2253 Logger::info('unable to locate newly created contact record.');
2257 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2258 if (DBA::isResult($user)) {
2259 self::sendShare($user, $contact_record);
2261 // Send the profile data, maybe it weren't transmitted before
2262 self::sendProfile($importer['uid'], [$contact_record]);
2270 * Fetches a message with a given guid
2272 * @param string $guid message guid
2273 * @param string $orig_author handle of the original post
2274 * @return array|bool The fetched item or false on failure
2275 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2276 * @throws \ImagickException
2278 public static function originalItem(string $guid, string $orig_author)
2281 Logger::notice('Empty guid. Quitting.');
2285 // Do we already have this item?
2286 $fields = ['body', 'title', 'app', 'created', 'object-type', 'uri', 'guid',
2287 'author-name', 'author-link', 'author-avatar', 'plink', 'uri-id'];
2288 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2289 $item = Post::selectFirst($fields, $condition);
2291 if (DBA::isResult($item)) {
2292 Logger::notice("reshared message " . $guid . " already exists on system.");
2294 // Maybe it is already a reshared item?
2295 // Then refetch the content, if it is a reshare from a reshare.
2296 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2297 if (self::isReshare($item['body'], true)) {
2299 } elseif (self::isReshare($item['body'], false) || strstr($item['body'], '[share')) {
2300 $item['body'] = Markdown::toBBCode(BBCode::toMarkdown($item['body']));
2302 $item['body'] = self::replacePeopleGuid($item['body'], $item['author-link']);
2310 if (!DBA::isResult($item)) {
2311 if (empty($orig_author)) {
2312 Logger::notice('Empty author for guid ' . $guid . '. Quitting.');
2316 $server = 'https://' . substr($orig_author, strpos($orig_author, '@') + 1);
2317 Logger::notice("1st try: reshared message " . $guid . " will be fetched via SSL from the server " . $server);
2318 $stored = self::storeByGuid($guid, $server, true);
2321 $server = 'http://' . substr($orig_author, strpos($orig_author, '@') + 1);
2322 Logger::notice("2nd try: reshared message " . $guid . " will be fetched without SSL from the server " . $server);
2323 $stored = self::storeByGuid($guid, $server, true);
2327 $fields = ['body', 'title', 'app', 'created', 'object-type', 'uri', 'guid',
2328 'author-name', 'author-link', 'author-avatar', 'plink', 'uri-id'];
2329 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2330 $item = Post::selectFirst($fields, $condition);
2332 if (DBA::isResult($item)) {
2333 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2334 if (self::isReshare($item['body'], false)) {
2335 $item['body'] = Markdown::toBBCode(BBCode::toMarkdown($item['body']));
2336 $item['body'] = self::replacePeopleGuid($item['body'], $item['author-link']);
2347 * Stores a reshare activity
2349 * @param array $item Array of reshare post
2350 * @param integer $parent_message_id Id of the parent post
2351 * @param string $guid GUID string of reshare action
2352 * @param string $author Author handle
2354 private static function addReshareActivity(array $item, int $parent_message_id, string $guid, string $author)
2356 $parent = Post::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2360 $datarray['uid'] = $item['uid'];
2361 $datarray['contact-id'] = $item['contact-id'];
2362 $datarray['network'] = $item['network'];
2364 $datarray['author-link'] = $item['author-link'];
2365 $datarray['author-id'] = $item['author-id'];
2367 $datarray['owner-link'] = $datarray['author-link'];
2368 $datarray['owner-id'] = $datarray['author-id'];
2370 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2371 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2372 $datarray['thr-parent'] = $parent['uri'];
2374 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2375 $datarray['gravity'] = GRAVITY_ACTIVITY;
2376 $datarray['object-type'] = Activity\ObjectType::NOTE;
2378 $datarray['protocol'] = $item['protocol'];
2379 $datarray['source'] = $item['source'];
2380 $datarray['direction'] = $item['direction'];
2382 $datarray['plink'] = self::plink($author, $datarray['guid']);
2383 $datarray['private'] = $item['private'];
2384 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2386 if (Item::isTooOld($datarray)) {
2387 Logger::info('Reshare activity is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2391 $message_id = Item::insert($datarray);
2394 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2395 if ($datarray['uid'] == 0) {
2396 Item::distribute($message_id);
2402 * Processes a reshare message
2404 * @param array $importer Array of the importer user
2405 * @param SimpleXMLElement $data The message object
2406 * @param string $xml The original XML of the message
2407 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2409 * @return bool Success or failure
2410 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2411 * @throws \ImagickException
2413 private static function receiveReshare(array $importer, SimpleXMLElement $data, string $xml, int $direction): bool
2415 $author = XML::unescape($data->author);
2416 $guid = XML::unescape($data->guid);
2417 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2418 $root_author = XML::unescape($data->root_author);
2419 $root_guid = XML::unescape($data->root_guid);
2420 /// @todo handle unprocessed property "provider_display_name"
2421 $public = XML::unescape($data->public);
2423 $contact = self::allowedContactByHandle($importer, $author, false);
2428 if (!empty($contact['gsid'])) {
2429 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2432 $message_id = self::messageExists($importer['uid'], $guid);
2437 $original_item = self::originalItem($root_guid, $root_author);
2438 if (!$original_item) {
2442 if (empty($original_item['plink'])) {
2443 $original_item['plink'] = self::plink($root_author, $root_guid);
2448 $datarray['uid'] = $importer['uid'];
2449 $datarray['contact-id'] = $contact['id'];
2450 $datarray['network'] = Protocol::DIASPORA;
2452 $datarray['author-link'] = $contact['url'];
2453 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2455 $datarray['owner-link'] = $datarray['author-link'];
2456 $datarray['owner-id'] = $datarray['author-id'];
2458 $datarray['guid'] = $guid;
2459 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($author, $guid);
2460 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2462 $datarray['verb'] = Activity::POST;
2463 $datarray['gravity'] = GRAVITY_PARENT;
2465 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2466 $datarray['source'] = $xml;
2467 $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
2469 /// @todo Copy tag data from original post
2471 $prefix = BBCode::getShareOpeningTag(
2472 $original_item['author-name'],
2473 $original_item['author-link'],
2474 $original_item['author-avatar'],
2475 $original_item['plink'],
2476 $original_item['created'],
2477 $original_item['guid']
2480 if (!empty($original_item['title'])) {
2481 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2484 $datarray['body'] = $prefix.$original_item['body'] . '[/share]';
2486 Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
2488 $datarray['app'] = $original_item['app'];
2490 $datarray['plink'] = self::plink($author, $guid);
2491 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2492 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2494 $datarray['object-type'] = $original_item['object-type'];
2496 self::fetchGuid($datarray);
2498 if (Item::isTooOld($datarray)) {
2499 Logger::info('Reshare is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2503 $message_id = Item::insert($datarray);
2505 self::sendParticipation($contact, $datarray);
2507 $root_message_id = self::messageExists($importer['uid'], $root_guid);
2508 if ($root_message_id) {
2509 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2513 Logger::info("Stored reshare " . $datarray['guid'] . " with message id " . $message_id);
2514 if ($datarray['uid'] == 0) {
2515 Item::distribute($message_id);
2524 * Processes retractions
2526 * @param array $importer Array of the importer user
2527 * @param array $contact The contact of the item owner
2528 * @param SimpleXMLElement $data The message object
2530 * @return bool success
2531 * @throws \Exception
2533 private static function itemRetraction(array $importer, array $contact, SimpleXMLElement $data): bool
2535 $author = XML::unescape($data->author);
2536 $target_guid = XML::unescape($data->target_guid);
2537 $target_type = XML::unescape($data->target_type);
2539 $person = FContact::getByURL($author);
2540 if (!is_array($person)) {
2541 Logger::notice("unable to find author detail for " . $author);
2545 if (empty($contact['url'])) {
2546 $contact['url'] = $person['url'];
2549 // Fetch items that are about to be deleted
2550 $fields = ['uid', 'id', 'parent', 'author-link', 'uri-id'];
2552 // When we receive a public retraction, we delete every item that we find.
2553 if ($importer['uid'] == 0) {
2554 $condition = ['guid' => $target_guid, 'deleted' => false];
2556 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2559 $r = Post::select($fields, $condition);
2560 if (!DBA::isResult($r)) {
2561 Logger::notice("Target guid " . $target_guid . " was not found on this system for user " . $importer['uid'] . ".");
2565 while ($item = Post::fetch($r)) {
2566 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2567 Logger::info("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.");
2571 // Fetch the parent item
2572 $parent = Post::selectFirst(['author-link'], ['id' => $item['parent']]);
2574 // Only delete it if the parent author really fits
2575 if (!Strings::compareLink($parent['author-link'], $contact['url']) && !Strings::compareLink($item['author-link'], $contact['url'])) {
2576 Logger::info("Thread author " . $parent['author-link'] . " and item author " . $item['author-link'] . " don't fit to expected contact " . $contact['url']);
2580 Item::markForDeletion(['id' => $item['id']]);
2582 Logger::info("Deleted target " . $target_guid . " (" . $item['id'] . ") from user " . $item['uid'] . " parent: " . $item['parent']);
2590 * Receives retraction messages
2592 * @param array $importer Array of the importer user
2593 * @param string $sender The sender of the message
2594 * @param SimpleXMLElement $data The message object
2596 * @return bool Success
2597 * @throws \Exception
2599 private static function receiveRetraction(array $importer, string $sender, SimpleXMLElement $data)
2601 $target_type = XML::unescape($data->target_type);
2603 $contact = self::contactByHandle($importer['uid'], $sender);
2604 if (!$contact && (in_array($target_type, ['Contact', 'Person']))) {
2605 Logger::notice("cannot find contact for sender: " . $sender . " and user " . $importer['uid']);
2613 Logger::info("Got retraction for " . $target_type . ", sender " . $sender . " and user " . $importer['uid']);
2615 switch ($target_type) {
2620 case 'StatusMessage':
2621 return self::itemRetraction($importer, $contact, $data);
2623 case 'PollParticipation':
2625 // Currently unsupported
2629 Logger::notice("Unknown target type " . $target_type);
2636 * Checks if an incoming message is wanted
2638 * @param array $item
2639 * @param string $author
2640 * @param string $body
2641 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2643 * @return boolean Is the message wanted?
2645 private static function isSolicitedMessage(array $item, string $author, string $body, int $direction): bool
2647 $contact = Contact::getByURL($author);
2648 if (DBA::exists('contact', ['`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)', $contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) {
2649 Logger::debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2653 if ($direction == self::FORCED_FETCH) {
2654 Logger::debug('Post is a forced fetch - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2658 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
2659 if (Relay::isSolicitedPost($tags, $body, $contact['id'], $item['uri'], Protocol::DIASPORA)) {
2660 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2668 * Store an attached photo in the post-media table
2671 * @param object $photo
2674 private static function storePhotoAsMedia(int $uriid, $photo)
2676 // @TODO Need to find object type, roland@f.haeder.net
2677 Logger::debug('photo='.get_class($photo));
2679 $data['uri-id'] = $uriid;
2680 $data['type'] = Post\Media::IMAGE;
2681 $data['url'] = XML::unescape($photo->remote_photo_path) . XML::unescape($photo->remote_photo_name);
2682 $data['height'] = (int)XML::unescape($photo->height ?? 0);
2683 $data['width'] = (int)XML::unescape($photo->width ?? 0);
2684 $data['description'] = XML::unescape($photo->text ?? '');
2686 Post\Media::insert($data);
2690 * Receives status messages
2692 * @param array $importer Array of the importer user
2693 * @param SimpleXMLElement $data The message object
2694 * @param string $xml The original XML of the message
2695 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2697 * @return int|bool The message id of the newly created item or false on error
2698 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2699 * @throws \ImagickException
2701 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, string $xml, int $direction)
2703 $author = XML::unescape($data->author);
2704 $guid = XML::unescape($data->guid);
2705 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2706 $public = XML::unescape($data->public);
2707 $text = XML::unescape($data->text);
2708 $provider_display_name = XML::unescape($data->provider_display_name);
2710 $contact = self::allowedContactByHandle($importer, $author, false);
2715 if (!empty($contact['gsid'])) {
2716 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2719 $message_id = self::messageExists($importer['uid'], $guid);
2725 if ($data->location) {
2726 foreach ($data->location->children() as $fieldname => $data) {
2727 $address[$fieldname] = XML::unescape($data);
2731 $raw_body = $body = Markdown::toBBCode($text);
2735 $datarray['guid'] = $guid;
2736 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($author, $guid);
2737 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2739 // Attach embedded pictures to the body
2741 foreach ($data->photo as $photo) {
2742 self::storePhotoAsMedia($datarray['uri-id'], $photo);
2745 $datarray['object-type'] = Activity\ObjectType::IMAGE;
2746 $datarray['post-type'] = Item::PT_IMAGE;
2747 } elseif ($data->poll) {
2748 $datarray['object-type'] = Activity\ObjectType::NOTE;
2749 $datarray['post-type'] = Item::PT_POLL;
2751 $datarray['object-type'] = Activity\ObjectType::NOTE;
2752 $datarray['post-type'] = Item::PT_NOTE;
2755 /// @todo enable support for polls
2756 //if ($data->poll) {
2757 // foreach ($data->poll as $poll)
2762 /// @todo enable support for events
2764 $datarray['uid'] = $importer['uid'];
2765 $datarray['contact-id'] = $contact['id'];
2766 $datarray['network'] = Protocol::DIASPORA;
2768 $datarray['author-link'] = $contact['url'];
2769 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2771 $datarray['owner-link'] = $datarray['author-link'];
2772 $datarray['owner-id'] = $datarray['author-id'];
2774 $datarray['verb'] = Activity::POST;
2775 $datarray['gravity'] = GRAVITY_PARENT;
2777 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2778 $datarray['source'] = $xml;
2779 $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
2781 if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
2782 $datarray['post-reason'] = Item::PR_FETCHED;
2783 } elseif ($datarray['uid'] == 0) {
2784 $datarray['post-reason'] = Item::PR_GLOBAL;
2787 $datarray['body'] = self::replacePeopleGuid($body, $contact['url']);
2788 $datarray['raw-body'] = self::replacePeopleGuid($raw_body, $contact['url']);
2790 self::storeMentions($datarray['uri-id'], $text);
2791 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
2793 if (!self::isSolicitedMessage($datarray, $author, $body, $direction)) {
2794 DBA::delete('item-uri', ['uri' => $datarray['uri']]);
2798 if ($provider_display_name != '') {
2799 $datarray['app'] = $provider_display_name;
2802 $datarray['plink'] = self::plink($author, $guid);
2803 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2804 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2806 if (isset($address['address'])) {
2807 $datarray['location'] = $address['address'];
2810 if (isset($address['lat']) && isset($address['lng'])) {
2811 $datarray['coord'] = $address['lat'] . " " . $address['lng'];
2814 self::fetchGuid($datarray);
2816 if (Item::isTooOld($datarray)) {
2817 Logger::info('Status is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2821 $message_id = Item::insert($datarray);
2823 self::sendParticipation($contact, $datarray);
2826 Logger::info("Stored item " . $datarray['guid'] . " with message id " . $message_id);
2827 if ($datarray['uid'] == 0) {
2828 Item::distribute($message_id);
2836 /* ************************************************************************************** *
2837 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2838 * ************************************************************************************** */
2841 * returnes the handle of a contact
2843 * @param array $contact contact array
2845 * @return string the handle in the format user@domain.tld
2846 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2848 private static function myHandle(array $contact): string
2850 if (!empty($contact['addr'])) {
2851 return $contact['addr'];
2854 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2855 // So - just in case - we build the the address here.
2856 if ($contact['nickname'] != '') {
2857 $nick = $contact['nickname'];
2859 $nick = $contact['nick'];
2862 return $nick . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
2867 * Creates the data for a private message in the new format
2869 * @param string $msg The message that is to be transmitted
2870 * @param array $user The record of the sender
2871 * @param array $contact Target of the communication
2872 * @param string $prvkey The private key of the sender
2873 * @param string $pubkey The public key of the receiver
2875 * @return string The encrypted data
2876 * @throws \Exception
2878 public static function encodePrivateData(string $msg, array $user, array $contact, string $prvkey, string $pubkey): string
2880 Logger::debug("Message: ".$msg);
2882 // without a public key nothing will work
2884 Logger::notice("pubkey missing: contact id: ".$contact["id"]);
2888 $aes_key = random_bytes(32);
2889 $b_aes_key = base64_encode($aes_key);
2890 $iv = random_bytes(16);
2891 $b_iv = base64_encode($iv);
2893 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2895 $json = json_encode(['iv' => $b_iv, 'key' => $b_aes_key]);
2897 $encrypted_key_bundle = '';
2898 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
2902 $json_object = json_encode(
2904 'aes_key' => base64_encode($encrypted_key_bundle),
2905 'encrypted_magic_envelope' => base64_encode($ciphertext)
2909 return $json_object;
2913 * Creates the envelope for the "fetch" endpoint and for the new format
2915 * @param string $msg The message that is to be transmitted
2916 * @param array $user The record of the sender
2918 * @return string The envelope
2919 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2921 public static function buildMagicEnvelope(string $msg, array $user): string
2923 $b64url_data = Strings::base64UrlEncode($msg);
2924 $data = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
2926 $key_id = Strings::base64UrlEncode(self::myHandle($user));
2927 $type = 'application/xml';
2928 $encoding = 'base64url';
2929 $alg = 'RSA-SHA256';
2930 $signable_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
2932 // Fallback if the private key wasn't transmitted in the expected field
2933 if ($user['uprvkey'] == '') {
2934 $user['uprvkey'] = $user['prvkey'];
2937 $signature = Crypto::rsaSign($signable_data, $user['uprvkey']);
2938 $sig = Strings::base64UrlEncode($signature);
2943 '@attributes' => ['type' => $type],
2944 'me:encoding' => $encoding,
2947 '@attributes2' => ['key_id' => $key_id]
2951 $namespaces = ['me' => 'http://salmon-protocol.org/ns/magic-env'];
2953 return XML::fromArray($xmldata, $xml, false, $namespaces);
2957 * Create the envelope for a message
2959 * @param string $msg The message that is to be transmitted
2960 * @param array $user The record of the sender
2961 * @param array $contact Target of the communication
2962 * @param string $prvkey The private key of the sender
2963 * @param string $pubkey The public key of the receiver
2964 * @param bool $public Is the message public?
2966 * @return string The message that will be transmitted to other servers
2967 * @throws \Exception
2969 public static function buildMessage(string $msg, array $user, array $contact, string $prvkey, string $pubkey, bool $public = false): string
2971 // The message is put into an envelope with the sender's signature
2972 $envelope = self::buildMagicEnvelope($msg, $user);
2974 // Private messages are put into a second envelope, encrypted with the receivers public key
2976 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
2983 * Creates a signature for a message
2985 * @param array $owner the array of the owner of the message
2986 * @param array $message The message that is to be signed
2988 * @return string The signature
2990 private static function signature(array $owner, array $message): string
2993 unset($sigmsg['author_signature']);
2994 unset($sigmsg['parent_author_signature']);
2996 $signed_text = implode(';', $sigmsg);
2998 return base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
3002 * Transmit a message to a target server
3004 * @param array $owner the array of the item owner
3005 * @param array $contact Target of the communication
3006 * @param string $envelope The message that is to be transmitted
3007 * @param bool $public_batch Is it a public post?
3008 * @param string $guid message guid
3010 * @return int Result of the transmission
3011 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3012 * @throws \ImagickException
3014 private static function transmit(array $owner, array $contact, string $envelope, bool $public_batch, string $guid = ''): int
3016 $enabled = intval(DI::config()->get('system', 'diaspora_enabled'));
3021 $logid = Strings::getRandomHex(4);
3023 // We always try to use the data from the fcontact table.
3024 // This is important for transmitting data to Friendica servers.
3025 if (!empty($contact['addr'])) {
3026 $fcontact = FContact::getByURL($contact['addr']);
3027 if (!empty($fcontact)) {
3028 $dest_url = ($public_batch ? $fcontact['batch'] : $fcontact['notify']);
3032 if (empty($dest_url)) {
3033 $dest_url = ($public_batch ? $contact['batch'] : $contact['notify']);
3037 Logger::notice("no url for contact: " . $contact['id'] . " batch mode =" . $public_batch);
3041 Logger::notice("transmit: " . $logid . "-" . $guid . " " . $dest_url);
3043 if (!intval(DI::config()->get('system', 'diaspora_test'))) {
3044 $content_type = (($public_batch) ? 'application/magic-envelope+xml' : 'application/json');
3046 $postResult = DI::httpClient()->post($dest_url . '/', $envelope, ['Content-Type' => $content_type]);
3047 $return_code = $postResult->getReturnCode();
3049 Logger::notice('test_mode');
3053 Logger::notice("transmit: " . $logid . "-" . $guid . " to " . $dest_url . " returns: " . $return_code);
3055 return $return_code ? $return_code : -1;
3060 * Build the post xml
3062 * @param string $type The message type
3063 * @param array $message The message data
3065 * @return string The post XML
3067 public static function buildPostXml(string $type, array $message): string
3069 $data = [$type => $message];
3071 return XML::fromArray($data, $xml);
3075 * Builds and transmit messages
3077 * @param array $owner the array of the item owner
3078 * @param array $contact Target of the communication
3079 * @param string $type The message type
3080 * @param array $message The message data
3081 * @param bool $public_batch Is it a public post?
3082 * @param string $guid message guid
3084 * @return int Result of the transmission
3085 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3086 * @throws \ImagickException
3088 private static function buildAndTransmit(array $owner, array $contact, string $type, array $message, bool $public_batch = false, string $guid = '')
3090 $msg = self::buildPostXml($type, $message);
3092 // Fallback if the private key wasn't transmitted in the expected field
3093 if (empty($owner['uprvkey'])) {
3094 $owner['uprvkey'] = $owner['prvkey'];
3097 // When sending content to Friendica contacts using the Diaspora protocol
3098 // we have to fetch the public key from the fcontact.
3099 // This is due to the fact that legacy DFRN had unique keys for every contact.
3100 $pubkey = $contact['pubkey'];
3101 if (!empty($contact['addr'])) {
3102 $fcontact = FContact::getByURL($contact['addr']);
3103 if (!empty($fcontact)) {
3104 $pubkey = $fcontact['pubkey'];
3107 // The "addr" field should always be filled.
3108 // If this isn't the case, it will raise a notice some lines later.
3109 // And in the log we will see where it came from and we can handle it there.
3110 Logger::notice('Empty addr', ['contact' => $contact ?? [], 'callstack' => System::callstack(20)]);
3113 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
3115 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3117 Logger::info('Transmitted message', ['owner' => $owner['uid'], 'target' => $contact['addr'], 'type' => $type, 'guid' => $guid, 'result' => $return_code]);
3119 return $return_code;
3123 * sends a participation (Used to get all further updates)
3125 * @param array $contact Target of the communication
3126 * @param array $item Item array
3128 * @return int The result of the transmission
3129 * @throws \Exception
3131 private static function sendParticipation(array $contact, array $item): int
3133 // Don't send notifications for private postings
3134 if ($item['private'] == Item::PRIVATE) {
3138 $cachekey = 'diaspora:sendParticipation:' . $item['guid'];
3140 $result = DI::cache()->get($cachekey);
3141 if (!is_null($result)) {
3145 // Fetch some user id to have a valid handle to transmit the participation.
3146 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3147 // If the item belongs to a user, we take this user id.
3148 if ($item['uid'] == 0) {
3149 // @todo Possibly use an administrator account?
3150 $condition = ['verified' => true, 'blocked' => false,
3151 'account_removed' => false, 'account_expired' => false, 'account-type' => User::ACCOUNT_TYPE_PERSON];
3152 $first_user = DBA::selectFirst('user', ['uid'], $condition, ['order' => ['uid']]);
3153 $owner = User::getOwnerDataById($first_user['uid']);
3155 $owner = User::getOwnerDataById($item['uid']);
3158 $author = self::myHandle($owner);
3161 'author' => $author,
3162 'guid' => System::createUUID(),
3163 'parent_type' => 'Post',
3164 'parent_guid' => $item['guid']
3167 Logger::info("Send participation for " . $item['guid'] . " by " . $author);
3169 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3170 DI::cache()->set($cachekey, $item['guid'], Duration::QUARTER_HOUR);
3172 return self::buildAndTransmit($owner, $contact, 'participation', $message);
3176 * sends an account migration
3178 * @param array $owner the array of the item owner
3179 * @param array $contact Target of the communication
3180 * @param int $uid User ID
3182 * @return int The result of the transmission
3183 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3184 * @throws \ImagickException
3186 public static function sendAccountMigration(array $owner, array $contact, int $uid): int
3188 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3189 $profile = self::createProfileData($uid);
3191 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3192 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
3195 'author' => $old_handle,
3196 'profile' => $profile,
3197 'signature' => $signature
3200 Logger::info('Send account migration', ['msg' => $message]);
3202 return self::buildAndTransmit($owner, $contact, 'account_migration', $message);
3206 * Sends a "share" message
3208 * @param array $owner the array of the item owner
3209 * @param array $contact Target of the communication
3211 * @return int The result of the transmission
3212 * @throws \Exception
3214 public static function sendShare(array $owner, array $contact): int
3217 * @todo support the different possible combinations of "following" and "sharing"
3218 * Currently, Diaspora only interprets the "sharing" field
3220 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3224 switch ($contact["rel"]) {
3225 case Contact::FRIEND:
3229 case Contact::SHARING:
3233 case Contact::FOLLOWER:
3240 'author' => self::myHandle($owner),
3241 'recipient' => $contact['addr'],
3242 'following' => 'true',
3246 Logger::info('Send share', ['msg' => $message]);
3248 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3252 * sends an "unshare"
3254 * @param array $owner the array of the item owner
3255 * @param array $contact Target of the communication
3257 * @return int The result of the transmission
3258 * @throws \Exception
3260 public static function sendUnshare(array $owner, array $contact): int
3263 'author' => self::myHandle($owner),
3264 'recipient' => $contact['addr'],
3265 'following' => 'false',
3266 'sharing' => 'false'
3269 Logger::info('Send unshare', ['msg' => $message]);
3271 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3275 * Checks a message body if it is a reshare
3277 * @param string $body The message body that is to be check
3278 * @param bool $complete Should it be a complete check or a simple check?
3280 * @return array|bool Reshare details or "false" if no reshare
3281 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3282 * @throws \ImagickException
3284 public static function isReshare(string $body, bool $complete = true)
3286 $body = trim($body);
3288 $reshared = Item::getShareArray(['body' => $body]);
3289 if (empty($reshared)) {
3293 // Skip if it isn't a pure repeated messages
3294 // Does it start with a share?
3295 if (!empty($reshared['comment']) && $complete) {
3299 if (!empty($reshared['guid']) && $complete) {
3300 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3301 $item = Post::selectFirst(['contact-id'], $condition);
3302 if (DBA::isResult($item)) {
3304 $ret['root_handle'] = self::handleFromContact($item['contact-id']);
3305 $ret['root_guid'] = $reshared['guid'];
3307 } elseif ($complete) {
3308 // We are resharing something that isn't a DFRN or Diaspora post.
3309 // So we have to return "false" on "$complete" to not trigger a reshare.
3312 } elseif (empty($reshared['guid']) && $complete) {
3318 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3319 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3320 if (!empty($contact['addr'])) {
3321 $ret['root_handle'] = $contact['addr'];
3325 if (empty($ret) && !$complete) {
3333 * Create an event array
3335 * @param integer $event_id The id of the event
3337 * @return array with event data
3338 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3340 private static function buildEvent(string $event_id): array
3342 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
3343 if (!DBA::isResult($event)) {
3349 $owner = User::getOwnerDataById($event['uid']);
3354 $eventdata['author'] = self::myHandle($owner);
3356 if ($event['guid']) {
3357 $eventdata['guid'] = $event['guid'];
3360 $mask = DateTimeFormat::ATOM;
3362 /// @todo - establish "all day" events in Friendica
3363 $eventdata['all_day'] = 'false';
3365 $eventdata['timezone'] = 'UTC';
3367 if ($event['start']) {
3368 $eventdata['start'] = DateTimeFormat::utc($event['start'], $mask);
3370 if ($event['finish'] && !$event['nofinish']) {
3371 $eventdata['end'] = DateTimeFormat::utc($event['finish'], $mask);
3373 if ($event['summary']) {
3374 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3376 if ($event['desc']) {
3377 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3379 if ($event['location']) {
3380 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3381 $coord = Map::getCoordinates($event['location']);
3384 $location['address'] = html_entity_decode(BBCode::toMarkdown($event['location']));
3385 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3386 $location['lat'] = $coord['lat'];
3387 $location['lng'] = $coord['lon'];
3389 $location['lat'] = 0;
3390 $location['lng'] = 0;
3392 $eventdata['location'] = $location;
3399 * Create a post (status message or reshare)
3401 * @param array $item The item that will be exported
3402 * @param array $owner the array of the item owner
3405 * 'type' -> Message type ("status_message" or "reshare")
3406 * 'message' -> Array of XML elements of the status
3407 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3408 * @throws \ImagickException
3410 public static function buildStatus(array $item, array $owner)
3412 $cachekey = 'diaspora:buildStatus:' . $item['guid'];
3414 $result = DI::cache()->get($cachekey);
3415 if (!is_null($result)) {
3419 $myaddr = self::myHandle($owner);
3421 $public = ($item['private'] == Item::PRIVATE ? 'false' : 'true');
3422 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3423 $edited = DateTimeFormat::utc($item['edited'] ?? $item['created'], DateTimeFormat::ATOM);
3425 // Detect a share element and do a reshare
3426 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item['body']))) {
3428 'author' => $myaddr,
3429 'guid' => $item['guid'],
3430 'created_at' => $created,
3431 'root_author' => $ret['root_handle'],
3432 'root_guid' => $ret['root_guid'],
3433 'provider_display_name' => $item['app'],
3439 $title = $item['title'];
3440 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
3442 // Fetch the title from an attached link - if there is one
3443 if (empty($item['title']) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3444 $page_data = BBCode::getAttachmentData($item['body']);
3445 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3446 $title = $page_data['title'];
3450 if ($item['author-link'] != $item['owner-link']) {
3451 $body = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'],
3452 $item['plink'], $item['created']) . $body . '[/share]';
3455 // convert to markdown
3456 $body = html_entity_decode(BBCode::toMarkdown($body));
3459 if (strlen($title)) {
3460 $body = '### ' . html_entity_decode($title) . "\n\n" . $body;
3463 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]);
3464 if (!empty($attachments)) {
3465 $body .= "\n[hr]\n";
3466 foreach ($attachments as $attachment) {
3467 $body .= "[" . $attachment['description'] . "](" . $attachment['url'] . ")\n";
3473 if ($item['location'] != '')
3474 $location['address'] = $item['location'];
3476 if ($item['coord'] != '') {
3477 $coord = explode(' ', $item['coord']);
3478 $location['lat'] = $coord[0];
3479 $location['lng'] = $coord[1];
3483 'author' => $myaddr,
3484 'guid' => $item['guid'],
3485 'created_at' => $created,
3486 'edited_at' => $edited,
3487 'public' => $public,
3489 'provider_display_name' => $item['app'],
3490 'location' => $location
3493 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3494 if (!isset($location['lat']) || !isset($location['lng'])) {
3495 unset($message['location']);
3498 if ($item['event-id'] > 0) {
3499 $event = self::buildEvent($item['event-id']);
3500 if (count($event)) {
3501 $message['event'] = $event;
3503 if (!empty($event['location']['address']) &&
3504 !empty($event['location']['lat']) &&
3505 !empty($event['location']['lng'])) {
3506 $message['location'] = $event['location'];
3509 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3510 // $message['text'] = '';
3514 $type = 'status_message';
3519 'message' => $message
3522 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3527 private static function prependParentAuthorMention(string $body, string $profile_url): string
3529 $profile = Contact::getByURL($profile_url, false, ['addr', 'name']);
3530 if (!empty($profile['addr'])
3531 && !strstr($body, $profile['addr'])
3532 && !strstr($body, $profile_url)
3534 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3543 * @param array $item The item that will be exported
3544 * @param array $owner the array of the item owner
3545 * @param array $contact Target of the communication
3546 * @param bool $public_batch Is it a public post?
3548 * @return int The result of the transmission
3549 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3550 * @throws \ImagickException
3552 public static function sendStatus(array $item, array $owner, array $contact, bool $public_batch = false): int
3554 $status = self::buildStatus($item, $owner);
3556 return self::buildAndTransmit($owner, $contact, $status['type'], $status['message'], $public_batch, $item['guid']);
3560 * Creates a "like" object
3562 * @param array $item The item that will be exported
3563 * @param array $owner the array of the item owner
3565 * @return array|bool The data for a "like" or false on error
3566 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3568 private static function constructLike(array $item, array $owner)
3570 $parent = Post::selectFirst(['guid', 'uri', 'thr-parent'], ['uri' => $item['thr-parent']]);
3571 if (!DBA::isResult($parent)) {
3575 $target_type = ($parent['uri'] === $parent['thr-parent'] ? 'Post' : 'Comment');
3577 if ($item['verb'] === Activity::LIKE) {
3579 } elseif ($item['verb'] === Activity::DISLIKE) {
3580 $positive = 'false';
3584 'author' => self::myHandle($owner),
3585 'guid' => $item['guid'],
3586 'parent_guid' => $parent['guid'],
3587 'parent_type' => $target_type,
3588 'positive' => $positive,
3589 'author_signature' => ''
3594 * Creates an "EventParticipation" object
3596 * @param array $item The item that will be exported
3597 * @param array $owner the array of the item owner
3599 * @return array|bool The data for an "EventParticipation" or false on error
3600 * @throws \Exception
3602 private static function constructAttend(array $item, array $owner)
3604 $parent = Post::selectFirst(['guid'], ['uri' => $item['thr-parent']]);
3605 if (!DBA::isResult($parent)) {
3609 switch ($item['verb']) {
3610 case Activity::ATTEND:
3611 $attend_answer = 'accepted';
3613 case Activity::ATTENDNO:
3614 $attend_answer = 'declined';
3616 case Activity::ATTENDMAYBE:
3617 $attend_answer = 'tentative';
3620 Logger::notice('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3625 'author' => self::myHandle($owner),
3626 'guid' => $item['guid'],
3627 'parent_guid' => $parent['guid'],
3628 'status' => $attend_answer,
3629 'author_signature' => ''
3634 * Creates the object for a comment
3636 * @param array $item The item that will be exported
3637 * @param array $owner the array of the item owner
3639 * @return array|false The data for a comment
3640 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3642 private static function constructComment(array $item, array $owner)
3644 $cachekey = 'diaspora:constructComment:' . $item['guid'];
3646 $result = DI::cache()->get($cachekey);
3647 if (!is_null($result)) {
3651 $toplevel_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3652 if (!DBA::isResult($toplevel_item)) {
3653 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3657 $thread_parent_item = $toplevel_item;
3658 if ($item['thr-parent'] != $item['parent-uri']) {
3659 $thread_parent_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3662 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
3664 // The replied to autor mention is prepended for clarity if:
3665 // - Item replied isn't yours
3666 // - Item is public or explicit mentions are disabled
3667 // - Implicit mentions are enabled
3669 $item['author-id'] != $thread_parent_item['author-id']
3670 && ($thread_parent_item['gravity'] != GRAVITY_PARENT)
3671 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3672 && !DI::config()->get('system', 'disable_implicit_mentions')
3674 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3677 $text = html_entity_decode(BBCode::toMarkdown($body));
3678 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3679 $edited = DateTimeFormat::utc($item['edited'], DateTimeFormat::ATOM);
3682 'author' => self::myHandle($owner),
3683 'guid' => $item['guid'],
3684 'created_at' => $created,
3685 'edited_at' => $edited,
3686 'parent_guid' => $toplevel_item['guid'],
3688 'author_signature' => ''
3691 // Send the thread parent guid only if it is a threaded comment
3692 if ($item['thr-parent'] != $item['parent-uri']) {
3693 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3696 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3702 * Send a like or a comment
3704 * @param array $item The item that will be exported
3705 * @param array $owner the array of the item owner
3706 * @param array $contact Target of the communication
3707 * @param bool $public_batch Is it a public post?
3709 * @return int The result of the transmission
3710 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3711 * @throws \ImagickException
3713 public static function sendFollowup(array $item, array $owner, array $contact, bool $public_batch = false): int
3715 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3716 $message = self::constructAttend($item, $owner);
3717 $type = 'event_participation';
3718 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3719 $message = self::constructLike($item, $owner);
3721 } elseif (!in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
3722 $message = self::constructComment($item, $owner);
3726 if (empty($message)) {
3730 $message['author_signature'] = self::signature($owner, $message);
3732 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3736 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3738 * @param array $item The item that will be exported
3739 * @param array $owner the array of the item owner
3740 * @param array $contact Target of the communication
3741 * @param bool $public_batch Is it a public post?
3743 * @return int The result of the transmission
3744 * @throws \Exception
3746 public static function sendRelay(array $item, array $owner, array $contact, bool $public_batch = false): int
3748 if ($item['deleted']) {
3749 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3750 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3756 Logger::info("Got relayable data " . $type . " for item " . $item['guid'] . " (" . $item['id'] . ")");
3758 $msg = json_decode($item['signed_text'], true);
3761 if (is_array($msg)) {
3762 foreach ($msg as $field => $data) {
3763 if (!$item['deleted']) {
3764 if ($field == 'diaspora_handle') {
3767 if ($field == 'target_type') {
3768 $field = 'parent_type';
3772 $message[$field] = $data;
3775 Logger::info("Signature text for item " . $item["guid"] . " (" . $item["id"] . ") couldn't be extracted: " . $item['signed_text']);
3778 $message['parent_author_signature'] = self::signature($owner, $message);
3780 Logger::info('Relayed data', ['msg' => $message]);
3782 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3786 * Sends a retraction (deletion) of a message, like or comment
3788 * @param array $item The item that will be exported
3789 * @param array $owner the array of the item owner
3790 * @param array $contact Target of the communication
3791 * @param bool $public_batch Is it a public post?
3792 * @param bool $relay Is the retraction transmitted from a relay?
3794 * @return int The result of the transmission
3795 * @throws \Exception
3797 public static function sendRetraction(array $item, array $owner, array $contact, bool $public_batch = false, bool $relay = false): int
3799 $itemaddr = self::handleFromContact($item['contact-id'], $item['author-id']);
3801 $msg_type = 'retraction';
3803 if ($item['gravity'] == GRAVITY_PARENT) {
3804 $target_type = 'Post';
3805 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3806 $target_type = 'Like';
3808 $target_type = 'Comment';
3812 'author' => $itemaddr,
3813 'target_guid' => $item['guid'],
3814 'target_type' => $target_type
3817 Logger::info('Got message', ['msg' => $message]);
3819 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item['guid']);
3825 * @param array $item The item that will be exported
3826 * @param array $owner The owner
3827 * @param array $contact Target of the communication
3829 * @return int The result of the transmission
3830 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3831 * @throws \ImagickException
3833 public static function sendMail(array $item, array $owner, array $contact): int
3835 $myaddr = self::myHandle($owner);
3837 $cnv = DBA::selectFirst('conv', [], ['id' => $item['convid'], 'uid' => $item['uid']]);
3838 if (!DBA::isResult($cnv)) {
3839 Logger::notice("conversation not found.");
3843 $body = BBCode::toMarkdown($item['body']);
3844 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3847 'author' => $myaddr,
3848 'guid' => $item['guid'],
3849 'conversation_guid' => $cnv['guid'],
3851 'created_at' => $created,
3854 if ($item['reply']) {
3859 'author' => $cnv['creator'],
3860 'guid' => $cnv['guid'],
3861 'subject' => $cnv['subject'],
3862 'created_at' => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3863 'participants' => $cnv['recips'],
3867 $type = 'conversation';
3870 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item['guid']);
3874 * Split a name into first name and last name
3876 * @param string $name The name
3878 * @return array The array with "first" and "last"
3880 public static function splitName(string $name): array
3882 $name = trim($name);
3884 // Is the name longer than 64 characters? Then cut the rest of it.
3885 if (strlen($name) > 64) {
3886 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3887 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3889 $name = substr($name, 0, 64);
3893 // Take the first word as first name
3894 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3895 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3896 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3897 return ['first' => $first, 'last' => $last];
3900 // Take the last word as last name
3901 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3902 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3904 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3905 return ['first' => $first, 'last' => $last];
3908 // Take the first 32 characters if there is no space in the first 32 characters
3909 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3910 $first = substr($name, 0, 32);
3911 $last = substr($name, 32);
3912 return ['first' => $first, 'last' => $last];
3915 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3916 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3918 // Check if the last name is longer than 32 characters
3919 if (strlen($last) > 32) {
3920 if (strpos($last, ' ') <= 32) {
3921 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
3923 $last = substr($last, 0, 32);
3927 return ['first' => $first, 'last' => $last];
3931 * Create profile data
3933 * @param int $uid The user id
3935 * @return array The profile data
3936 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3938 private static function createProfileData(int $uid): array
3940 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
3941 if (!DBA::isResult($profile)) {
3945 $handle = $profile['addr'];
3947 $split_name = self::splitName($profile['name']);
3948 $first = $split_name['first'];
3949 $last = $split_name['last'];
3951 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3952 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3953 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3954 $searchable = ($profile['net-publish'] ? 'true' : 'false');
3960 if ($searchable === 'true') {
3963 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
3964 [$year, $month, $day] = sscanf($profile['dob'], '%4d-%2d-%2d');
3968 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
3971 $about = BBCode::toMarkdown($profile['about']);
3973 $location = $profile['location'];
3975 if ($profile['pub_keywords']) {
3976 $kw = str_replace(',', ' ', $profile['pub_keywords']);
3977 $kw = str_replace(' ', ' ', $kw);
3978 $arr = explode(' ', $kw);
3980 for ($x = 0; $x < 5; $x ++) {
3981 if (!empty($arr[$x])) {
3982 $tags .= '#'. trim($arr[$x]) .' ';
3987 $tags = trim($tags);
3991 'author' => $handle,
3992 'first_name' => $first,
3993 'last_name' => $last,
3994 'image_url' => $large,
3995 'image_url_medium' => $medium,
3996 'image_url_small' => $small,
3999 'location' => $location,
4000 'searchable' => $searchable,
4002 'tag_string' => $tags
4007 * Sends profile data
4009 * @param int $uid The user id
4010 * @param bool $recips optional, default false
4012 * @throws \Exception
4014 public static function sendProfile(int $uid, bool $recips = false)
4020 $owner = User::getOwnerDataById($uid);
4026 $recips = DBA::selectToArray('contact', [], ['network' => Protocol::DIASPORA, 'uid' => $uid, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
4033 $message = self::createProfileData($uid);
4035 // @ToDo Split this into single worker jobs
4036 foreach ($recips as $recip) {
4037 Logger::info("Send updated profile data for user " . $uid . " to contact " . $recip['id']);
4038 self::buildAndTransmit($owner, $recip, 'profile', $message);
4043 * Creates the signature for likes that are created on our system
4045 * @param integer $uid The user of that comment
4046 * @param array $item Item array
4048 * @return array|bool Signed content or false on error
4049 * @throws \Exception
4051 public static function createLikeSignature(int $uid, array $item)
4053 $owner = User::getOwnerDataById($uid);
4054 if (empty($owner)) {
4055 Logger::info('No owner post, so not storing signature');
4059 if (!in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
4063 $message = self::constructLike($item, $owner);
4064 if ($message === false) {
4068 $message['author_signature'] = self::signature($owner, $message);
4074 * Creates the signature for Comments that are created on our system
4076 * @param array $item Item array
4078 * @return array|bool Signed content or false on error
4079 * @throws \Exception
4081 public static function createCommentSignature(array $item)
4083 if (!empty($item['author-link'])) {
4084 $url = $item['author-link'];
4086 $contact = Contact::getById($item['author-id'], ['url']);
4087 if (empty($contact['url'])) {
4088 Logger::warning('Author Contact not found', ['author-id' => $item['author-id']]);
4091 $url = $contact['url'];
4094 $uid = User::getIdForURL($url);
4096 Logger::info('No owner post, so not storing signature', ['url' => $contact['url']]);
4100 $owner = User::getOwnerDataById($uid);
4101 if (empty($owner)) {
4102 Logger::info('No owner post, so not storing signature');
4106 // This is only needed for the automated tests
4107 if (empty($owner['uprvkey'])) {
4111 $message = self::constructComment($item, $owner);
4112 if ($message === false) {
4116 $message['author_signature'] = self::signature($owner, $message);
4121 public static function performReshare(int $UriId, int $uid): int
4123 $fields = ['uri-id', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
4124 $item = Post::selectFirst($fields, ['uri-id' => $UriId, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
4125 if (!DBA::isResult($item)) {
4129 if (strpos($item['body'], '[/share]') !== false) {
4130 $pos = strpos($item['body'], '[share');
4131 $post = substr($item['body'], $pos);
4133 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
4135 if (!empty($item['title'])) {
4136 $post .= '[h3]' . $item['title'] . "[/h3]\n";
4139 $post .= $item['body'];
4140 $post .= '[/share]';
4143 $owner = User::getOwnerDataById($uid);
4144 $author = Contact::getPublicIdByUserId($uid);
4148 'verb' => Activity::POST,
4149 'contact-id' => $owner['id'],
4150 'author-id' => $author,
4151 'owner-id' => $author,
4153 'allow_cid' => $owner['allow_cid'] ?? '',
4154 'allow_gid' => $owner['allow_gid']?? '',
4155 'deny_cid' => $owner['deny_cid'] ?? '',
4156 'deny_gid' => $owner['deny_gid'] ?? '',
4159 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
4160 $item['private'] = Item::PRIVATE;
4161 } elseif (DI::pConfig()->get($uid, 'system', 'unlisted')) {
4162 $item['private'] = Item::UNLISTED;
4164 $item['private'] = Item::PUBLIC;
4167 // Don't trigger the addons
4168 $item['api_source'] = false;
4170 return Item::insert($item, true);