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\GServer;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\Mail;
40 use Friendica\Model\Post;
41 use Friendica\Model\Tag;
42 use Friendica\Model\User;
43 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
44 use Friendica\Network\HTTPException;
45 use Friendica\Network\Probe;
46 use Friendica\Util\Crypto;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Map;
49 use Friendica\Util\Network;
50 use Friendica\Util\Strings;
51 use Friendica\Util\XML;
52 use Friendica\Worker\Delivery;
53 use GuzzleHttp\Psr7\Uri;
57 * This class contains functions to communicate via the Diaspora protocol
58 * @see https://diaspora.github.io/diaspora_federation/
64 const FORCED_FETCH = 2;
67 * Return a list of participating contacts for a thread
69 * This is used for the participation feature.
70 * One of the parameters is a contact array.
71 * This is done to avoid duplicates.
73 * @param array $item Item that is about to be delivered
74 * @param array $contacts The previously fetched contacts
76 * @return array of relay servers
79 public static function participantsForThread(array $item, array $contacts): array
81 if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
82 Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]);
86 $items = Post::select(['author-id', 'author-link', 'parent-author-link', 'parent-guid', 'guid'],
87 ['parent' => $item['parent'], 'gravity' => [Item::GRAVITY_COMMENT, Item::GRAVITY_ACTIVITY]]);
88 while ($item = Post::fetch($items)) {
89 $contact = DBA::selectFirst('contact', ['id', 'url', 'name', 'protocol', 'batch', 'network'],
90 ['id' => $item['author-id']]);
91 if (!DBA::isResult($contact) || empty($contact['batch']) ||
92 ($contact['network'] != Protocol::DIASPORA) ||
93 Strings::compareLink($item['parent-author-link'], $item['author-link'])) {
98 foreach ($contacts as $entry) {
99 if ($entry['batch'] == $contact['batch']) {
105 Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]);
106 $contacts[] = $contact;
115 * verify the envelope and return the verified data
117 * @param string $envelope The magic envelope
119 * @return string|bool verified data or false on error
120 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
121 * @throws \ImagickException
123 private static function verifyMagicEnvelope(string $envelope)
125 $basedom = XML::parseString($envelope, true);
127 if (!is_object($basedom)) {
128 Logger::notice('Envelope is no XML file');
132 $children = $basedom->children(ActivityNamespace::SALMON_ME);
134 if (sizeof($children) == 0) {
135 Logger::notice('XML has no children');
141 $data = Strings::base64UrlDecode($children->data);
142 $type = $children->data->attributes()->type[0];
144 $encoding = $children->encoding;
146 $alg = $children->alg;
148 $sig = Strings::base64UrlDecode($children->sig);
149 $key_id = $children->sig->attributes()->key_id[0];
151 $handle = Strings::base64UrlDecode($key_id);
154 $b64url_data = Strings::base64UrlEncode($data);
155 $msg = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
157 $signable_data = $msg . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
160 Logger::notice('No author could be decoded. Discarding. Message: ' . $envelope);
165 $key = self::key(WebFingerUri::fromString($handle));
167 throw new \InvalidArgumentException();
169 } catch (\InvalidArgumentException $e) {
170 Logger::notice("Couldn't get a key for handle " . $handle . ". Discarding.");
174 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
176 Logger::notice('Message from ' . $handle . ' did not verify. Discarding.');
184 * encrypts data via AES
186 * @param string $key The AES key
187 * @param string $iv The IV (is used for CBC encoding)
188 * @param string $data The data that is to be encrypted
190 * @return string encrypted data
192 private static function aesEncrypt(string $key, string $iv, string $data): string
194 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
198 * decrypts data via AES
200 * @param string $key The AES key
201 * @param string $iv The IV (is used for CBC encoding)
202 * @param string $encrypted The encrypted data
204 * @return string decrypted data
206 private static function aesDecrypt(string $key, string $iv, string $encrypted): string
208 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
212 * Decodes incoming Diaspora message in the new format. This method returns false on an error.
214 * @param string $raw raw post message
215 * @param string $privKey The private key of the importer
216 * @param boolean $no_exit Don't do an http exit on error
219 * 'message' -> decoded Diaspora XML message
220 * 'author' -> author diaspora handle
221 * 'key' -> author public key (converted to pkcs#8)
222 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
223 * @throws \ImagickException
225 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
227 $data = json_decode($raw);
229 // Is it a private post? Then decrypt the outer Salmon
230 if (is_object($data)) {
232 if (!isset($data->aes_key) || !isset($data->encrypted_magic_envelope)) {
233 Logger::info('Missing keys "aes_key" and/or "encrypted_magic_envelope"', ['data' => $data]);
234 throw new \RuntimeException('Missing keys "aes_key" and/or "encrypted_magic_envelope"');
237 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
238 $ciphertext = base64_decode($data->encrypted_magic_envelope);
240 $outer_key_bundle = '';
241 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
242 $j_outer_key_bundle = json_decode($outer_key_bundle);
244 if (!is_object($j_outer_key_bundle)) {
245 Logger::info('Unable to decode outer key bundle', ['outer_key_bundle' => $outer_key_bundle]);
246 throw new \RuntimeException('Unable to decode outer key bundle');
249 if (!isset($j_outer_key_bundle->iv) || !isset($j_outer_key_bundle->key)) {
250 Logger::info('Missing keys "iv" and/or "key" from outer Salmon', ['j_outer_key_bundle' => $j_outer_key_bundle]);
251 throw new \RuntimeException('Missing keys "iv" and/or "key" from outer Salmon');
254 $outer_iv = base64_decode($j_outer_key_bundle->iv);
255 $outer_key = base64_decode($j_outer_key_bundle->key);
257 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
258 } catch (\Throwable $e) {
259 Logger::notice('Outer Salmon did not verify. Discarding.');
263 throw new \Friendica\Network\HTTPException\BadRequestException();
270 $basedom = XML::parseString($xml, true);
272 if (!is_object($basedom)) {
273 Logger::notice('Received data does not seem to be an XML. Discarding. '.$xml);
277 throw new \Friendica\Network\HTTPException\BadRequestException();
281 $base = $basedom->children(ActivityNamespace::SALMON_ME);
283 // Not sure if this cleaning is needed
284 $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
286 // Build the signed data
287 $type = $base->data[0]->attributes()->type[0];
288 $encoding = $base->encoding;
290 $signed_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
292 // This is the signature
293 $signature = Strings::base64UrlDecode($base->sig);
295 // Get the senders' public key
296 $key_id = $base->sig[0]->attributes()->key_id[0];
297 $author_addr = base64_decode($key_id);
298 if ($author_addr == '') {
299 Logger::notice('No author could be decoded. Discarding. Message: ' . $xml);
303 throw new \Friendica\Network\HTTPException\BadRequestException();
308 $author = WebFingerUri::fromString($author_addr);
309 $key = self::key($author);
311 throw new \InvalidArgumentException();
313 } catch (\InvalidArgumentException $e) {
314 Logger::notice("Couldn't get a key for handle " . $author_addr . ". Discarding.");
318 throw new \Friendica\Network\HTTPException\BadRequestException();
322 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
324 Logger::notice('Message did not verify. Discarding.');
328 throw new \Friendica\Network\HTTPException\BadRequestException();
333 'message' => (string)Strings::base64UrlDecode($base->data),
334 'author' => $author->getAddr(),
335 'key' => (string)$key
340 * Decodes incoming Diaspora message in the deprecated format
342 * @param string $xml urldecoded Diaspora salmon
343 * @param string $privKey The private key of the importer
346 * 'message' -> decoded Diaspora XML message
347 * 'author' -> author diaspora handle
348 * 'key' -> author public key (converted to pkcs#8)
349 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
350 * @throws \ImagickException
352 public static function decode(string $xml, string $privKey = '')
355 $basedom = XML::parseString($xml);
357 if (!is_object($basedom)) {
358 Logger::notice('XML is not parseable.');
361 $children = $basedom->children('https://joindiaspora.com/protocol');
363 $inner_aes_key = null;
366 if ($children->header) {
368 $idom = $children->header;
370 // This happens with posts from a relais
371 if (empty($privKey)) {
372 Logger::info('This is no private post in the old format');
376 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
378 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
379 $ciphertext = base64_decode($encrypted_header->ciphertext);
381 $outer_key_bundle = '';
382 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
384 $j_outer_key_bundle = json_decode($outer_key_bundle);
386 $outer_iv = base64_decode($j_outer_key_bundle->iv);
387 $outer_key = base64_decode($j_outer_key_bundle->key);
389 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
391 Logger::info('decrypted', ['data' => $decrypted]);
392 $idom = XML::parseString($decrypted);
394 $inner_iv = base64_decode($idom->iv);
395 $inner_aes_key = base64_decode($idom->aes_key);
399 $author = WebFingerUri::fromString($idom->author_id);
400 } catch (\Throwable $e) {
401 Logger::notice('Could not retrieve author URI.', ['idom' => $idom]);
402 throw new \Friendica\Network\HTTPException\BadRequestException();
405 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
407 // figure out where in the DOM tree our data is hiding
410 if ($dom->provenance->data) {
411 $base = $dom->provenance;
412 } elseif ($dom->env->data) {
414 } elseif ($dom->data) {
419 Logger::notice('unable to locate salmon data in xml');
420 throw new \Friendica\Network\HTTPException\BadRequestException();
424 // Stash the signature away for now. We have to find their key or it won't be good for anything.
425 $signature = Strings::base64UrlDecode($base->sig);
429 // strip whitespace so our data element will return to one big base64 blob
430 $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
433 // stash away some other stuff for later
435 $type = $base->data[0]->attributes()->type[0];
436 $keyhash = $base->sig[0]->attributes()->keyhash[0];
437 $encoding = $base->encoding;
441 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
445 $data = Strings::base64UrlDecode($data);
449 $inner_decrypted = $data;
451 // Decode the encrypted blob
452 $inner_encrypted = base64_decode($data);
453 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
456 // Once we have the author URI, go to the web and try to find their public key
457 // (first this will look it up locally if it is in the diaspora-contact cache)
458 // This will also convert diaspora public key from pkcs#1 to pkcs#8
459 Logger::notice('Fetching key for ' . $author);
460 $key = self::key($author);
462 Logger::notice('Could not retrieve author key.');
463 throw new \Friendica\Network\HTTPException\BadRequestException();
466 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
469 Logger::notice('Message did not verify. Discarding.');
470 throw new \Friendica\Network\HTTPException\BadRequestException();
473 Logger::notice('Message verified.');
476 'message' => $inner_decrypted,
477 'author' => $author->getAddr(),
484 * Dispatches public messages and find the fitting receivers
486 * @param array $msg The post that will be dispatched
487 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
489 * @return int|bool The message id of the generated message, "true" or "false" if there was an error
490 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
491 * @throws \ImagickException
493 public static function dispatchPublic(array $msg, int $direction)
495 $enabled = intval(DI::config()->get('system', 'diaspora_enabled'));
497 Logger::notice('Diaspora is disabled');
501 if (!($fields = self::validPosting($msg))) {
502 Logger::notice('Invalid posting', ['msg' => $msg]);
508 'page-flags' => User::PAGE_FLAGS_FREELOVE
510 $success = self::dispatch($importer, $msg, $fields, $direction);
516 * Dispatches the different message types to the different functions
518 * @param array $importer Array of the importer user
519 * @param array $msg The post that will be dispatched
520 * @param SimpleXMLElement $fields SimpleXML object that contains the message
521 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
523 * @return int|bool The message id of the generated message, "true" or "false" if there was an error
524 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
525 * @throws \ImagickException
527 public static function dispatch(array $importer, array $msg, SimpleXMLElement $fields = null, int $direction = self::PUSHED)
529 // The sender is the handle of the contact that sent the message.
530 // This will often be different with relayed messages (for example "like" and "comment")
531 $sender = WebFingerUri::fromString($msg['author']);
533 // This is only needed for private postings since this is already done for public ones before
534 if (is_null($fields)) {
536 if (!($fields = self::validPosting($msg))) {
537 Logger::warning('Invalid posting', ['msg' => $msg]);
544 $type = $fields->getName();
546 Logger::info('Received message', ['type' => $type, 'sender' => $sender->getAddr(), 'user' => $importer['uid']]);
549 case 'account_migration':
551 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
554 return self::receiveAccountMigration($importer, $fields);
556 case 'account_deletion':
557 return self::receiveAccountDeletion($fields);
560 return self::receiveComment($importer, $sender, $fields, $msg['message'], $direction);
564 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
567 return self::receiveContactRequest($importer, $fields);
571 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
574 return self::receiveConversation($importer, $msg, $fields);
577 return self::receiveLike($importer, $sender, $fields, $direction);
581 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
584 return self::receiveMessage($importer, $fields);
586 case 'participation':
588 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
591 return self::receiveParticipation($importer, $fields, $direction);
593 case 'photo': // Not implemented
594 return self::receivePhoto($importer, $fields);
596 case 'poll_participation': // Not implemented
597 return self::receivePollParticipation($importer, $fields);
601 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
604 return self::receiveProfile($importer, $fields);
607 return self::receiveReshare($importer, $fields, $msg['message'], $direction);
610 return self::receiveRetraction($importer, $sender, $fields);
612 case 'status_message':
613 return self::receiveStatusMessage($importer, $fields, $msg['message'], $direction);
616 Logger::notice('Unknown message type ' . $type);
622 * Checks if a posting is valid and fetches the data fields.
624 * This function does not only check the signature.
625 * It also does the conversion between the old and the new diaspora format.
627 * @param array $msg Array with the XML, the sender handle and the sender signature
629 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
630 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
631 * @throws \ImagickException
633 private static function validPosting(array $msg)
635 $data = XML::parseString($msg['message']);
637 if (!is_object($data)) {
638 Logger::info('No valid XML', ['message' => $msg['message']]);
642 // Is this the new or the old version?
643 if ($data->getName() == 'XML') {
645 foreach ($data->post->children() as $child) {
653 $type = $element->getName();
656 Logger::debug('Got message', ['type' => $type, 'message' => $msg['message']]);
658 // All retractions are handled identically from now on.
659 // In the new version there will only be "retraction".
660 if (in_array($type, ['signed_retraction', 'relayable_retraction']))
661 $type = 'retraction';
663 if ($type == 'request') {
667 $fields = new SimpleXMLElement('<' . $type . '/>');
670 $author_signature = null;
671 $parent_author_signature = null;
673 foreach ($element->children() as $fieldname => $entry) {
675 // Translation for the old XML structure
676 if ($fieldname == 'diaspora_handle') {
677 $fieldname = 'author';
679 if ($fieldname == 'participant_handles') {
680 $fieldname = 'participants';
682 if (in_array($type, ['like', 'participation'])) {
683 if ($fieldname == 'target_type') {
684 $fieldname = 'parent_type';
687 if ($fieldname == 'sender_handle') {
688 $fieldname = 'author';
690 if ($fieldname == 'recipient_handle') {
691 $fieldname = 'recipient';
693 if ($fieldname == 'root_diaspora_id') {
694 $fieldname = 'root_author';
696 if ($type == 'status_message') {
697 if ($fieldname == 'raw_message') {
701 if ($type == 'retraction') {
702 if ($fieldname == 'post_guid') {
703 $fieldname = 'target_guid';
705 if ($fieldname == 'type') {
706 $fieldname = 'target_type';
711 if (($fieldname == 'author_signature') && ($entry != '')) {
712 $author_signature = base64_decode($entry);
713 } elseif (($fieldname == 'parent_author_signature') && ($entry != '')) {
714 $parent_author_signature = base64_decode($entry);
715 } elseif (!in_array($fieldname, ['author_signature', 'parent_author_signature', 'target_author_signature'])) {
716 if ($signed_data != '') {
720 $signed_data .= $entry;
722 if (!in_array($fieldname, ['parent_author_signature', 'target_author_signature'])
723 || ($orig_type == 'relayable_retraction')
725 XML::copy($entry, $fields, $fieldname);
729 // This is something that shouldn't happen at all.
730 if (in_array($type, ['status_message', 'reshare', 'profile'])) {
731 if ($msg['author'] != $fields->author) {
732 Logger::notice('Message handle is not the same as envelope sender. Quitting this message.', ['author1' => $msg['author'], 'author2' => $fields->author]);
737 // Only some message types have signatures. So we quit here for the other types.
738 if (!in_array($type, ['comment', 'like'])) {
742 if (!isset($author_signature) && ($msg['author'] == $fields->author)) {
743 Logger::debug('No author signature, but the sender matches the author', ['type' => $type, 'msg-author' => $msg['author'], 'message' => $msg['message']]);
747 // No author_signature? This is a must, so we quit.
748 if (!isset($author_signature)) {
749 Logger::info('No author signature', ['type' => $type, 'msg-author' => $msg['author'], 'fields-author' => $fields->author, 'message' => $msg['message']]);
753 if (isset($parent_author_signature)) {
754 $key = self::key(WebFingerUri::fromString($msg['author']));
756 Logger::info('No key found for parent', ['author' => $msg['author']]);
760 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, 'sha256')) {
761 Logger::info('No valid parent author signature', ['author' => $msg['author'], 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $parent_author_signature]);
767 $key = self::key(WebFingerUri::fromString($fields->author));
769 throw new \InvalidArgumentException();
771 } catch (\Throwable $e) {
772 Logger::info('No key found', ['author' => $fields->author]);
776 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, 'sha256')) {
777 Logger::info('No valid author signature for author', ['author' => $fields->author, 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $author_signature]);
785 * Fetches the public key for a given handle
787 * @param WebFingerUri $uri The handle
789 * @return string The public key
790 * @throws InternalServerErrorException
791 * @throws \ImagickException
793 private static function key(WebFingerUri $uri): string
795 Logger::notice('Fetching diaspora key', ['handle' => $uri->getAddr(), 'callstack' => System::callstack(20)]);
797 return DI::dsprContact()->getByAddr($uri)->pubKey;
798 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
804 * Get a contact id for a given handle
806 * @param int $uid The user id
807 * @param WebFingerUri $uri
809 * @return array Contact data
810 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
811 * @throws \ImagickException
813 private static function contactByHandle(int $uid, WebFingerUri $uri): array
815 return Contact::getByURL($uri->getAddr(), null, [], $uid);
819 * Checks if the given contact url does support ActivityPub
821 * @param string $url profile url or WebFinger address
822 * @param boolean|null $update true = always update, false = never update, null = update when not found or outdated
824 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
825 * @throws \ImagickException
827 public static function isSupportedByContactUrl(string $url, ?bool $update = null): bool
829 $contact = Contact::getByURL($url, $update, ['uri-id', 'network']);
831 $supported = DI::dsprContact()->existsByUriId($contact['uri-id'] ?? 0);
833 if (!$supported && is_null($update) && ($contact['network'] == Protocol::DFRN)) {
834 $supported = self::isSupportedByContactUrl($url, true);
841 * Check if posting is allowed for this contact
843 * @param array $importer Array of the importer user
844 * @param array $contact The contact that is checked
845 * @param bool $is_comment Is the check for a comment?
847 * @return bool is the contact allowed to post?
849 private static function postAllow(array $importer, array $contact, bool $is_comment = false): bool
852 * Perhaps we were already sharing with this person. Now they're sharing with us.
853 * That makes us friends.
854 * Normally this should have handled by getting a request - but this could get lost
856 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
857 // It is not removed by now. Possibly the code is needed?
858 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
860 // array('rel' => Contact::FRIEND, 'writable' => true),
861 // array('id' => $contact["id"], 'uid' => $contact["uid"])
864 // $contact["rel"] = Contact::FRIEND;
865 // Logger::notice("defining user ".$contact["nick"]." as friend");
868 // Contact server is blocked
869 if (Network::isUrlBlocked($contact['url'])) {
871 // We don't seem to like that person
872 } elseif ($contact['blocked']) {
873 // Maybe blocked, don't accept.
875 // We are following this person?
876 } elseif (($contact['rel'] == Contact::SHARING) || ($contact['rel'] == Contact::FRIEND)) {
877 // Yes, then it is fine.
879 // Is the message a global user or a comment?
880 } elseif (($importer['uid'] == 0) || $is_comment) {
881 // Messages for the global users and comments are always accepted
889 * Fetches the contact id for a handle and checks if posting is allowed
891 * @param array $importer Array of the importer user
892 * @param WebFingerUri $contact_uri The checked contact
893 * @param bool $is_comment Is the check for a comment?
895 * @return array|bool The contact data or false on error
896 * @throws InternalServerErrorException
897 * @throws \ImagickException
899 private static function allowedContactByHandle(array $importer, WebFingerUri $contact_uri, bool $is_comment = false)
901 $contact = self::contactByHandle($importer['uid'], $contact_uri);
903 Logger::notice('A Contact for handle ' . $contact_uri . ' and user ' . $importer['uid'] . ' was not found');
904 // If a contact isn't found, we accept it anyway if it is a comment
905 if ($is_comment && ($importer['uid'] != 0)) {
906 return self::contactByHandle(0, $contact_uri);
907 } elseif ($is_comment) {
914 if (!self::postAllow($importer, $contact, $is_comment)) {
915 Logger::notice('The handle: ' . $contact_uri . ' is not allowed to post to user ' . $importer['uid']);
922 * Does the message already exists on the system?
924 * @param int $uid The user id
925 * @param string $guid The guid of the message
927 * @return int|bool message id if the message already was stored into the system - or false.
930 private static function messageExists(int $uid, string $guid)
932 $item = Post::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
933 if (DBA::isResult($item)) {
934 Logger::notice('Message ' . $guid . ' already exists for user ' . $uid);
942 * Checks for links to posts in a message
944 * @param array $item The item array
947 private static function fetchGuid(array $item)
949 preg_replace_callback(
950 "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism",
951 function ($match) use ($item) {
952 self::fetchGuidSub($match, $item);
957 preg_replace_callback(
958 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
959 function ($match) use ($item) {
960 self::fetchGuidSub($match, $item);
967 * Checks for relative /people/* links in an item body to match local
968 * contacts or prepends the remote host taken from the author link.
970 * @param string $body The item body to replace links from
971 * @param string $author_link The author link for missing local contact fallback
973 * @return string the replaced string
975 public static function replacePeopleGuid(string $body, string $author_link): string
977 $return = preg_replace_callback(
978 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
979 function ($match) use ($author_link) {
981 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
982 // 1 => '0123456789abcdef'
984 $handle = DI::dsprContact()->getUrlByGuid($match[1]);
987 $return = '@[url=' . $handle . ']' . $match[2] . '[/url]';
989 // No local match, restoring absolute remote URL from author scheme and host
990 $author_url = parse_url($author_link);
991 $return = '[url=' . $author_url['scheme'] . '://' . $author_url['host'] . '/people/' . $match[1] . ']' . $match[2] . '[/url]';
1003 * sub function of "fetchGuid" which checks for links in messages
1005 * @param array $match array containing a link that has to be checked for a message link
1006 * @param array $item The item array
1008 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1009 * @throws \ImagickException
1011 private static function fetchGuidSub(array $match, array $item)
1013 if (!self::storeByGuid($match[1], $item['author-link'], true)) {
1014 self::storeByGuid($match[1], $item['owner-link'], true);
1019 * Fetches an item with a given guid from a given server
1021 * @param string $guid the message guid
1022 * @param string $server The server address
1023 * @param bool $force Forced fetch
1025 * @return int|bool the message id of the stored message or false
1026 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1027 * @throws \ImagickException
1029 private static function storeByGuid(string $guid, string $server, bool $force)
1031 $serverparts = parse_url($server);
1033 if (empty($serverparts['host']) || empty($serverparts['scheme'])) {
1037 $server = $serverparts['scheme'] . '://' . $serverparts['host'];
1039 Logger::info('Trying to fetch item ' . $guid . ' from ' . $server);
1041 $msg = self::message($guid, $server);
1047 Logger::info('Successfully fetched item ' . $guid . ' from ' . $server);
1049 // Now call the dispatcher
1050 return self::dispatchPublic($msg, $force ? self::FORCED_FETCH : self::FETCHED);
1054 * Fetches a message from a server
1056 * @param string $guid message guid
1057 * @param string $server The url of the server
1058 * @param int $level Endless loop prevention
1061 * 'message' => The message XML
1062 * 'author' => The author handle
1063 * 'key' => The public key of the author
1064 * @throws \Exception
1066 public static function message(string $guid, string $server, int $level = 0)
1072 // This will work for new Diaspora servers and Friendica servers from 3.5
1073 $source_url = $server . '/fetch/post/' . urlencode($guid);
1075 Logger::info('Fetch post from ' . $source_url);
1077 $envelope = DI::httpClient()->fetch($source_url, HttpClientAccept::MAGIC);
1079 Logger::info('Envelope was fetched.');
1080 $x = self::verifyMagicEnvelope($envelope);
1082 Logger::info('Envelope could not be verified.');
1084 Logger::info('Envelope was verified.');
1094 $source_xml = XML::parseString($x);
1096 if (!is_object($source_xml)) {
1100 if ($source_xml->post->reshare) {
1101 // Reshare of a reshare - old Diaspora version
1102 Logger::info('Message is a reshare');
1103 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1104 } elseif ($source_xml->getName() == 'reshare') {
1105 // Reshare of a reshare - new Diaspora version
1106 Logger::info('Message is a new reshare');
1107 return self::message($source_xml->root_guid, $server, ++$level);
1110 $author_handle = '';
1112 // Fetch the author - for the old and the new Diaspora version
1113 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1114 $author_handle = (string)$source_xml->post->status_message->diaspora_handle;
1115 } elseif ($source_xml->author && ($source_xml->getName() == 'status_message')) {
1116 $author_handle = (string)$source_xml->author;
1120 $author = WebFingerUri::fromString($author_handle);
1121 } catch (\InvalidArgumentException $e) {
1122 // If this isn't a "status_message" then quit
1123 Logger::info("Message doesn't seem to be a status message");
1129 'author' => $author->getAddr(),
1130 'key' => self::key($author)
1135 * Fetches an item with a given URL
1137 * @param string $url the message url
1138 * @param int $uid User id
1140 * @return int|bool the message id of the stored message or false
1141 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1142 * @throws \ImagickException
1144 public static function fetchByURL(string $url, int $uid = 0)
1146 // Check for Diaspora (and Friendica) typical paths
1147 if (!preg_match('=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i', $url, $matches)) {
1148 Logger::info('Invalid url', ['url' => $url]);
1152 $guid = urldecode($matches[2]);
1154 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1155 if (DBA::isResult($item)) {
1156 Logger::info('Found', ['id' => $item['id']]);
1160 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1161 $ret = self::storeByGuid($guid, $matches[1], true);
1162 Logger::info('Result', ['ret' => $ret]);
1164 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1165 if (DBA::isResult($item)) {
1166 Logger::info('Found', ['id' => $item['id']]);
1169 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1175 * Fetches the item record of a given guid
1177 * @param int $uid The user id
1178 * @param string $guid message guid
1179 * @param WebFingerUri $author
1180 * @param array $contact The contact of the item owner
1182 * @return array|bool the item record or false on failure
1183 * @throws \Exception
1185 private static function parentItem(int $uid, string $guid, WebFingerUri $author, array $contact)
1187 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1188 'author-name', 'author-link', 'author-avatar', 'gravity',
1189 'owner-name', 'owner-link', 'owner-avatar'];
1191 $condition = ['uid' => $uid, 'guid' => $guid];
1192 $item = Post::selectFirst($fields, $condition);
1194 if (!DBA::isResult($item)) {
1196 $result = self::storeByGuid($guid, DI::dsprContact()->getByAddr($author)->url, false);
1198 // We don't have an url for items that arrived at the public dispatcher
1199 if (!$result && !empty($contact['url'])) {
1200 $result = self::storeByGuid($guid, $contact['url'], false);
1204 Logger::info('Fetched missing item ' . $guid . ' - result: ' . $result);
1206 $item = Post::selectFirst($fields, $condition);
1208 } catch (HTTPException\NotFoundException $e) {
1209 Logger::notice('Unable to retrieve author details', ['author' => $author->getAddr()]);
1213 if (!DBA::isResult($item)) {
1214 Logger::notice('Parent item not found: parent: ' . $guid . ' - user: ' . $uid);
1217 Logger::notice('Parent item found: parent: ' . $guid . ' - user: ' . $uid);
1223 * returns contact details for the given user
1225 * @param array $def_contact The default details if the contact isn't found
1226 * @param string $contact_url The url of the contact
1227 * @param int $uid The user id
1230 * 'cid' => contact id
1231 * 'network' => network type
1232 * @throws \Exception
1234 private static function authorContactByUrl(array $def_contact, string $contact_url, int $uid): array
1236 $condition = ['nurl' => Strings::normaliseLink($contact_url), 'uid' => $uid];
1237 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1238 if (DBA::isResult($contact)) {
1239 $cid = $contact['id'];
1240 $network = $contact['network'];
1242 $cid = $def_contact['id'];
1243 $network = Protocol::DIASPORA;
1248 'network' => $network
1253 * Is the profile a hubzilla profile?
1255 * @param string $url The profile link
1257 * @return bool is it a hubzilla server?
1259 private static function isHubzilla(string $url): bool
1261 return strstr($url, '/channel/');
1265 * Generate a post link with a given handle and message guid
1267 * @param string $addr The user handle
1268 * @param string $guid message guid
1269 * @param string $parent_guid optional parent guid
1271 * @return string the post link
1272 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1273 * @throws \ImagickException
1275 private static function plink(string $addr, string $guid, string $parent_guid = ''): string
1277 $contact = Contact::getByURL($addr);
1278 if (empty($contact)) {
1279 Logger::info('No contact data for address', ['addr' => $addr]);
1283 if (empty($contact['baseurl'])) {
1284 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1285 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1289 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1290 if (!empty($gserver['platform'])) {
1291 $platform = strtolower($gserver['platform']);
1292 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1295 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1296 if (self::isHubzilla($contact['url'])) {
1297 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1298 $platform = 'hubzilla';
1299 } elseif ($contact['network'] == Protocol::DFRN) {
1300 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1301 $platform = 'friendica';
1305 if ($platform == 'friendica') {
1306 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1309 if ($platform == 'hubzilla') {
1310 return $contact['baseurl'] . '/item/' . $guid;
1313 if ($platform == 'socialhome') {
1314 return $contact['baseurl'] . '/content/' . $guid;
1317 if ($platform != 'diaspora') {
1318 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1322 if ($parent_guid != '') {
1323 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1325 return $contact['baseurl'] . '/posts/' . $guid;
1330 * Receives account migration
1332 * @param array $importer Array of the importer user
1333 * @param SimpleXMLElement $data The message object
1335 * @return bool Success
1336 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1337 * @throws \ImagickException
1339 private static function receiveAccountMigration(array $importer, SimpleXMLElement $data): bool
1342 $old_author = WebFingerUri::fromString(XML::unescape($data->author));
1343 $new_author = WebFingerUri::fromString(XML::unescape($data->profile->author));
1344 } catch (\Throwable $e) {
1345 Logger::notice('Cannot find handles for sender and user', ['data' => $data]);
1349 $signature = XML::unescape($data->signature);
1351 $contact = self::contactByHandle($importer['uid'], $old_author);
1353 Logger::notice('Cannot find contact for sender: ' . $old_author . ' and user ' . $importer['uid']);
1357 Logger::notice('Got migration for ' . $old_author . ', to ' . $new_author . ' with user ' . $importer['uid']);
1360 $signed_text = 'AccountMigration:' . $old_author . ':' . $new_author;
1361 $key = self::key($old_author);
1362 if (!Crypto::rsaVerify($signed_text, $signature, $key, 'sha256')) {
1363 Logger::notice('No valid signature for migration.');
1367 // Update the profile
1368 self::receiveProfile($importer, $data->profile);
1370 // change the technical stuff in contact
1371 $data = Probe::uri($new_author);
1372 if ($data['network'] == Protocol::PHANTOM) {
1373 Logger::notice("Account for " . $new_author . " couldn't be probed.");
1378 'url' => $data['url'],
1379 'nurl' => Strings::normaliseLink($data['url']),
1380 'name' => $data['name'],
1381 'nick' => $data['nick'],
1382 'addr' => $data['addr'],
1383 'batch' => $data['batch'],
1384 'notify' => $data['notify'],
1385 'poll' => $data['poll'],
1386 'network' => $data['network'],
1389 Contact::update($fields, ['addr' => $old_author->getAddr()]);
1391 Logger::notice('Contacts are updated.');
1397 * Processes an account deletion
1399 * @param SimpleXMLElement $data The message object
1401 * @return bool Success
1402 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1404 private static function receiveAccountDeletion(SimpleXMLElement $data): bool
1406 $author_handle = XML::unescape($data->author);
1408 $contacts = DBA::select('contact', ['id'], ['addr' => $author_handle]);
1409 while ($contact = DBA::fetch($contacts)) {
1410 Contact::remove($contact['id']);
1412 DBA::close($contacts);
1414 Logger::notice('Removed contacts for ' . $author_handle);
1420 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1422 * @param string $guid Message guid
1423 * @param WebFingerUri|null $person_uri Optional person to derive the base URL from
1425 * @return string The constructed uri or the one from our database or empty string
1426 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1427 * @throws \ImagickException
1429 private static function getUriFromGuid(string $guid, WebFingerUri $person_uri = null): string
1431 $item = Post::selectFirst(['uri'], ['guid' => $guid]);
1433 return $item['uri'];
1434 } elseif ($person_uri) {
1436 return DI::dsprContact()->selectOneByAddr($person_uri)->baseurl . '/objects/' . $guid;
1437 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
1446 * Store the mentions in the tag table
1448 * @param integer $uriid
1449 * @param string $text
1451 private static function storeMentions(int $uriid, string $text)
1453 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1454 if (empty($matches)) {
1459 * Matching values for the preg match
1460 * [1] = mention type (@ or !)
1461 * [2] = name (optional)
1465 foreach ($matches as $match) {
1466 if (empty($match)) {
1471 $contact = DI::dsprContact()->getByUrl(new Uri($match[3]));
1472 Tag::storeByHash($uriid, $match[1], $contact->name ?: $contact->nick, $contact->url);
1473 } catch (\Throwable $e) {
1480 * Processes an incoming comment
1482 * @param array $importer Array of the importer user
1483 * @param WebFingerUri $sender The sender of the message
1484 * @param SimpleXMLElement $data The message object
1485 * @param string $xml The original XML of the message
1486 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1488 * @return bool The message id of the generated comment or "false" if there was an error
1489 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1490 * @throws \ImagickException
1492 private static function receiveComment(array $importer, WebFingerUri $sender, SimpleXMLElement $data, string $xml, int $direction): bool
1494 $author = WebFingerUri::fromString(XML::unescape($data->author));
1495 $guid = XML::unescape($data->guid);
1496 $parent_guid = XML::unescape($data->parent_guid);
1497 $text = XML::unescape($data->text);
1499 if (isset($data->created_at)) {
1500 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1502 $created_at = DateTimeFormat::utcNow();
1505 if (isset($data->thread_parent_guid)) {
1506 $thread_parent_guid = XML::unescape($data->thread_parent_guid);
1507 $thr_parent = self::getUriFromGuid($thread_parent_guid);
1512 $contact = self::allowedContactByHandle($importer, $sender, true);
1517 if (!empty($contact['gsid'])) {
1518 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1521 $message_id = self::messageExists($importer['uid'], $guid);
1526 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1527 if (!$toplevel_parent_item) {
1532 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
1533 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
1534 Logger::notice('Unable to find author details', ['author' => $author->getAddr()]);
1538 // Fetch the contact id - if we know this contact
1539 $author_contact = self::authorContactByUrl($contact, $author_url, $importer['uid']);
1543 $datarray['uid'] = $importer['uid'];
1544 $datarray['contact-id'] = $author_contact['cid'];
1545 $datarray['network'] = $author_contact['network'];
1547 $datarray['author-link'] = $author_url;
1548 $datarray['author-id'] = Contact::getIdForURL($author_url);
1550 $datarray['owner-link'] = $contact['url'];
1551 $datarray['owner-id'] = Contact::getIdForURL($contact['url']);
1553 // Will be overwritten for sharing accounts in Item::insert
1554 $datarray = self::setDirection($datarray, $direction);
1556 $datarray['guid'] = $guid;
1557 $datarray['uri'] = self::getUriFromGuid($guid, $author);
1558 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1560 $datarray['verb'] = Activity::POST;
1561 $datarray['gravity'] = Item::GRAVITY_COMMENT;
1563 $datarray['thr-parent'] = $thr_parent ?: $toplevel_parent_item['uri'];
1565 $datarray['object-type'] = Activity\ObjectType::COMMENT;
1566 $datarray['post-type'] = Item::PT_NOTE;
1568 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1569 $datarray['source'] = $xml;
1571 $datarray = self::setDirection($datarray, $direction);
1573 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
1575 $datarray['plink'] = self::plink($author, $guid, $toplevel_parent_item['guid']);
1576 $body = Markdown::toBBCode($text);
1578 $datarray['body'] = self::replacePeopleGuid($body, $author_url);
1580 self::storeMentions($datarray['uri-id'], $text);
1581 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
1583 self::fetchGuid($datarray);
1585 // If we are the origin of the parent we store the original data.
1586 // We notify our followers during the item storage.
1587 if ($toplevel_parent_item['origin']) {
1588 $datarray['diaspora_signed_text'] = json_encode($data);
1591 if (Item::isTooOld($datarray)) {
1592 Logger::info('Comment is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1596 $message_id = Item::insert($datarray);
1598 if ($message_id <= 0) {
1603 Logger::info('Stored comment ' . $datarray['guid'] . ' with message id ' . $message_id);
1604 if ($datarray['uid'] == 0) {
1605 Item::distribute($message_id, json_encode($data));
1613 * processes and stores private messages
1615 * @param array $importer Array of the importer user
1616 * @param array $contact The contact of the message
1617 * @param SimpleXMLElement $data The message object
1618 * @param array $msg Array of the processed message, author handle and key
1619 * @param object $mesg The private message
1620 * @param array $conversation The conversation record to which this message belongs
1622 * @return bool "true" if it was successful
1623 * @throws \Exception
1624 * @todo Find type-hint for $mesg and update documentation
1626 private static function receiveConversationMessage(array $importer, array $contact, SimpleXMLElement $data, array $msg, $mesg, array $conversation): bool
1628 $author_handle = XML::unescape($data->author);
1629 $guid = XML::unescape($data->guid);
1630 $subject = XML::unescape($data->subject);
1632 // "diaspora_handle" is the element name from the old version
1633 // "author" is the element name from the new version
1634 if ($mesg->author) {
1635 $msg_author_handle = XML::unescape($mesg->author);
1636 } elseif ($mesg->diaspora_handle) {
1637 $msg_author_handle = XML::unescape($mesg->diaspora_handle);
1643 $msg_author_uri = WebFingerUri::fromString($msg_author_handle);
1644 } catch (\InvalidArgumentException $e) {
1648 $msg_guid = XML::unescape($mesg->guid);
1649 $msg_conversation_guid = XML::unescape($mesg->conversation_guid);
1650 $msg_text = XML::unescape($mesg->text);
1651 $msg_created_at = DateTimeFormat::utc(XML::unescape($mesg->created_at));
1653 if ($msg_conversation_guid != $guid) {
1654 Logger::notice('Message conversation guid does not belong to the current conversation.', ['guid' => $guid]);
1658 $msg_author = DI::dsprContact()->getByAddr($msg_author_uri);
1660 return Mail::insert([
1661 'uid' => $importer['uid'],
1662 'guid' => $msg_guid,
1663 'convid' => $conversation['id'],
1664 'from-name' => $msg_author->name,
1665 'from-photo' => (string)$msg_author->photo,
1666 'from-url' => (string)$msg_author->url,
1667 'contact-id' => $contact['id'],
1668 'title' => $subject,
1669 'body' => Markdown::toBBCode($msg_text),
1670 'uri' => $msg_author_handle . ':' . $msg_guid,
1671 'parent-uri' => $author_handle . ':' . $guid,
1672 'created' => $msg_created_at
1677 * Processes new private messages (answers to private messages are processed elsewhere)
1679 * @param array $importer Array of the importer user
1680 * @param array $msg Array of the processed message, author handle and key
1681 * @param SimpleXMLElement $data The message object
1683 * @return bool Success
1684 * @throws \Exception
1686 private static function receiveConversation(array $importer, array $msg, SimpleXMLElement $data)
1688 $author_handle = XML::unescape($data->author);
1689 $guid = XML::unescape($data->guid);
1690 $subject = XML::unescape($data->subject);
1691 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1692 $participants = XML::unescape($data->participants);
1694 $messages = $data->message;
1696 if (!count($messages)) {
1697 Logger::notice('Empty conversation');
1701 $contact = self::allowedContactByHandle($importer, WebFingerUri::fromString($msg['author']), true);
1706 if (!empty($contact['gsid'])) {
1707 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1710 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1711 if (!DBA::isResult($conversation)) {
1712 $r = DBA::insert('conv', [
1713 'uid' => $importer['uid'],
1715 'creator' => $author_handle,
1716 'created' => $created_at,
1717 'updated' => DateTimeFormat::utcNow(),
1718 'subject' => $subject,
1719 'recips' => $participants
1723 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1726 if (!$conversation) {
1727 Logger::warning('Unable to create conversation.');
1731 foreach ($messages as $mesg) {
1732 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1739 * Processes "like" messages
1741 * @param array $importer Array of the importer user
1742 * @param WebFingerUri $sender The sender of the message
1743 * @param SimpleXMLElement $data The message object
1744 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1746 * @return bool Success or failure
1747 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1748 * @throws \ImagickException
1750 private static function receiveLike(array $importer, WebFingerUri $sender, SimpleXMLElement $data, int $direction): bool
1752 $author = WebFingerUri::fromString(XML::unescape($data->author));
1753 $guid = XML::unescape($data->guid);
1754 $parent_guid = XML::unescape($data->parent_guid);
1755 $parent_type = XML::unescape($data->parent_type);
1756 $positive = XML::unescape($data->positive);
1758 // likes on comments aren't supported by Diaspora - only on posts
1759 // But maybe this will be supported in the future, so we will accept it.
1760 if (!in_array($parent_type, ['Post', 'Comment'])) {
1764 $contact = self::allowedContactByHandle($importer, $sender, true);
1769 if (!empty($contact['gsid'])) {
1770 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1773 $message_id = self::messageExists($importer['uid'], $guid);
1778 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1779 if (!$toplevel_parent_item) {
1784 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
1785 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
1786 Logger::notice('Unable to find author details', ['author' => $author->getAddr()]);
1790 // Fetch the contact id - if we know this contact
1791 $author_contact = self::authorContactByUrl($contact, $author_url, $importer['uid']);
1793 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1794 // We would accept this anyhow.
1795 if ($positive == 'true') {
1796 $verb = Activity::LIKE;
1798 $verb = Activity::DISLIKE;
1803 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1805 $datarray['uid'] = $importer['uid'];
1806 $datarray['contact-id'] = $author_contact['cid'];
1807 $datarray['network'] = $author_contact['network'];
1809 $datarray = self::setDirection($datarray, $direction);
1811 $datarray['owner-link'] = $datarray['author-link'] = $author_url;
1812 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($author_url);
1814 $datarray['guid'] = $guid;
1815 $datarray['uri'] = self::getUriFromGuid($guid, $author);
1817 $datarray['verb'] = $verb;
1818 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
1819 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1821 $datarray['object-type'] = Activity\ObjectType::NOTE;
1823 $datarray['body'] = $verb;
1825 // Diaspora doesn't provide a date for likes
1826 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
1828 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1829 if ($toplevel_parent_item['gravity'] != Item::GRAVITY_PARENT) {
1830 $toplevel = Post::selectFirst(['origin'], ['id' => $toplevel_parent_item['parent']]);
1831 $origin = $toplevel['origin'];
1833 $origin = $toplevel_parent_item['origin'];
1836 // If we are the origin of the parent we store the original data.
1837 // We notify our followers during the item storage.
1839 $datarray['diaspora_signed_text'] = json_encode($data);
1842 if (Item::isTooOld($datarray)) {
1843 Logger::info('Like is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1847 $message_id = Item::insert($datarray);
1849 if ($message_id <= 0) {
1854 Logger::info('Stored like ' . $datarray['guid'] . ' with message id ' . $message_id);
1855 if ($datarray['uid'] == 0) {
1856 Item::distribute($message_id, json_encode($data));
1864 * Processes private messages
1866 * @param array $importer Array of the importer user
1867 * @param SimpleXMLElement $data The message object
1869 * @return bool Success?
1870 * @throws \Exception
1872 private static function receiveMessage(array $importer, SimpleXMLElement $data): bool
1874 $author_uri = WebFingerUri::fromString(XML::unescape($data->author));
1875 $guid = XML::unescape($data->guid);
1876 $conversation_guid = XML::unescape($data->conversation_guid);
1877 $text = XML::unescape($data->text);
1878 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1880 $contact = self::allowedContactByHandle($importer, $author_uri, true);
1885 if (!empty($contact['gsid'])) {
1886 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1889 $condition = ['uid' => $importer['uid'], 'guid' => $conversation_guid];
1890 $conversation = DBA::selectFirst('conv', [], $condition);
1891 if (!DBA::isResult($conversation)) {
1892 Logger::notice('Conversation not available.');
1897 $author = DI::dsprContact()->getByAddr($author_uri);
1898 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
1899 Logger::notice('Unable to find author details', ['author' => $author_uri->getAddr()]);
1903 $body = Markdown::toBBCode($text);
1905 $body = self::replacePeopleGuid($body, $author->url);
1907 return Mail::insert([
1908 'uid' => $importer['uid'],
1910 'convid' => $conversation['id'],
1911 'from-name' => $author->name,
1912 'from-photo' => (string)$author->photo,
1913 'from-url' => (string)$author->url,
1914 'contact-id' => $contact['id'],
1915 'title' => $conversation['subject'],
1918 'uri' => $author_uri . ':' . $guid,
1919 'parent-uri' => $author_uri . ':' . $conversation['guid'],
1920 'created' => $created_at
1925 * Processes participations - unsupported by now
1927 * @param array $importer Array of the importer user
1928 * @param SimpleXMLElement $data The message object
1929 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1931 * @return bool success
1932 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1933 * @throws \ImagickException
1935 private static function receiveParticipation(array $importer, SimpleXMLElement $data, int $direction): bool
1937 $author = WebFingerUri::fromString(strtolower(XML::unescape($data->author)));
1938 $guid = XML::unescape($data->guid);
1939 $parent_guid = XML::unescape($data->parent_guid);
1941 $contact = self::allowedContactByHandle($importer, $author, true);
1946 if (!empty($contact['gsid'])) {
1947 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1950 if (self::messageExists($importer['uid'], $guid)) {
1954 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1955 if (!$toplevel_parent_item) {
1959 if (!$toplevel_parent_item['origin']) {
1960 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1963 if (!in_array($toplevel_parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
1964 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1969 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
1970 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
1971 Logger::notice('unable to find author details', ['author' => $author->getAddr()]);
1975 $author_contact = self::authorContactByUrl($contact, $author_url, $importer['uid']);
1977 // Store participation
1980 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1982 $datarray['uid'] = $importer['uid'];
1983 $datarray['contact-id'] = $author_contact['cid'];
1984 $datarray['network'] = $author_contact['network'];
1986 $datarray = self::setDirection($datarray, $direction);
1988 $datarray['owner-link'] = $datarray['author-link'] = $author_url;
1989 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($author_url);
1991 $datarray['guid'] = $guid;
1992 $datarray['uri'] = self::getUriFromGuid($guid, $author);
1994 $datarray['verb'] = Activity::FOLLOW;
1995 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
1996 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1998 $datarray['object-type'] = Activity\ObjectType::NOTE;
2000 $datarray['body'] = Activity::FOLLOW;
2002 // Diaspora doesn't provide a date for a participation
2003 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
2005 if (Item::isTooOld($datarray)) {
2006 Logger::info('Participation is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2010 $message_id = Item::insert($datarray);
2012 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
2014 // Send all existing comments and likes to the requesting server
2015 $comments = Post::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb', 'gravity'],
2016 ['parent' => $toplevel_parent_item['id'], 'gravity' => [Item::GRAVITY_COMMENT, Item::GRAVITY_ACTIVITY]]);
2017 while ($comment = Post::fetch($comments)) {
2018 if (($comment['gravity'] == Item::GRAVITY_ACTIVITY) && !in_array($comment['verb'], [Activity::LIKE, Activity::DISLIKE])) {
2019 Logger::info('Unsupported activities are not relayed', ['item' => $comment['id'], 'verb' => $comment['verb']]);
2023 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
2024 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2028 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
2029 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2033 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact['cid']]);
2034 if (Worker::add(Worker::PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['uri-id'], $author_contact['cid'], $datarray['uid'])) {
2035 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2038 DBA::close($comments);
2044 * Processes photos - unneeded
2046 * @param array $importer Array of the importer user
2047 * @param SimpleXMLElement $data The message object
2049 * @return bool always true
2051 private static function receivePhoto(array $importer, $data)
2053 // There doesn't seem to be a reason for this function,
2054 // since the photo data is transmitted in the status message as well
2059 * Processes poll participations - unssupported
2061 * @param array $importer Array of the importer user
2062 * @param object $data The message object
2064 * @return bool always true
2066 private static function receivePollParticipation(array $importer, $data)
2068 // We don't support polls by now
2073 * Processes incoming profile updates
2075 * @param array $importer Array of the importer user
2076 * @param SimpleXMLElement $data The message object
2078 * @return bool Success
2079 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2080 * @throws \ImagickException
2082 private static function receiveProfile(array $importer, SimpleXMLElement $data): bool
2084 $author = WebFingerUri::fromString(strtolower(XML::unescape($data->author)));
2086 $contact = self::contactByHandle($importer['uid'], $author);
2091 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? ' ' . XML::unescape($data->last_name) : '');
2092 $image_url = XML::unescape($data->image_url);
2093 $birthday = XML::unescape($data->birthday);
2094 $about = Markdown::toBBCode(XML::unescape($data->bio));
2095 $location = Markdown::toBBCode(XML::unescape($data->location));
2096 $searchable = (XML::unescape($data->searchable) == 'true');
2097 $nsfw = (XML::unescape($data->nsfw) == 'true');
2098 $tags = XML::unescape($data->tag_string);
2100 $tags = explode('#', $tags);
2103 foreach ($tags as $tag) {
2104 $tag = trim(strtolower($tag));
2110 $keywords = implode(', ', $keywords);
2113 $name = $author->getUser();
2116 if (preg_match('|^https?://|', $image_url) === 0) {
2117 // @TODO No HTTPS here?
2118 $image_url = 'http://' . $author->getFullHost() . $image_url;
2121 Contact::updateAvatar($contact['id'], $image_url);
2123 // Generic birthday. We don't know the timezone. The year is irrelevant.
2125 $birthday = str_replace('1000', '1901', $birthday);
2127 if ($birthday != '') {
2128 $birthday = DateTimeFormat::utc($birthday, 'Y-m-d');
2131 // this is to prevent multiple birthday notifications in a single year
2132 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2134 if (substr($birthday, 5) === substr($contact['bd'], 5)) {
2135 $birthday = $contact['bd'];
2138 $fields = ['name' => $name, 'location' => $location,
2139 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2140 'addr' => $author->getAddr(), 'nick' => $author->getUser(), 'keywords' => $keywords,
2141 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2143 if (!empty($birthday)) {
2144 $fields['bd'] = $birthday;
2147 Contact::update($fields, ['id' => $contact['id']]);
2149 Logger::info('Profile of contact ' . $contact['id'] . ' stored for user ' . $importer['uid']);
2155 * Processes incoming friend requests
2157 * @param array $importer Array of the importer user
2158 * @param array $contact The contact that send the request
2160 * @throws \Exception
2162 private static function receiveRequestMakeFriend(array $importer, array $contact)
2164 if ($contact['rel'] == Contact::SHARING) {
2166 ['rel' => Contact::FRIEND, 'writable' => true],
2167 ['id' => $contact['id'], 'uid' => $importer['uid']]
2173 * Processes incoming sharing notification
2175 * @param array $importer Array of the importer user
2176 * @param SimpleXMLElement $data The message object
2178 * @return bool Success
2179 * @throws \Exception
2181 private static function receiveContactRequest(array $importer, SimpleXMLElement $data): bool
2183 $author_handle = XML::unescape($data->author);
2184 $recipient = XML::unescape($data->recipient);
2186 if (!$author_handle || !$recipient) {
2190 $author = WebFingerUri::fromString($author_handle);
2192 // the current protocol version doesn't know these fields
2193 // That means that we will assume their existance
2194 if (isset($data->following)) {
2195 $following = (XML::unescape($data->following) == 'true');
2200 if (isset($data->sharing)) {
2201 $sharing = (XML::unescape($data->sharing) == 'true');
2206 $contact = self::contactByHandle($importer['uid'], $author);
2208 // perhaps we were already sharing with this person. Now they're sharing with us.
2209 // That makes us friends.
2212 Logger::info('Author ' . $author . ' (Contact ' . $contact['id'] . ') wants to follow us.');
2213 self::receiveRequestMakeFriend($importer, $contact);
2215 // refetch the contact array
2216 $contact = self::contactByHandle($importer['uid'], $author);
2218 // If we are now friends, we are sending a share message.
2219 // Normally we needn't to do so, but the first message could have been vanished.
2220 if (in_array($contact['rel'], [Contact::FRIEND])) {
2221 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2222 if (DBA::isResult($user)) {
2223 Logger::info('Sending share message to author ' . $author . ' - Contact: ' . $contact['id'] . ' - User: ' . $importer['uid']);
2224 self::sendShare($user, $contact);
2229 Logger::info("Author " . $author . " doesn't want to follow us anymore.");
2230 Contact::removeFollower($contact);
2235 if (!$following && $sharing && in_array($importer['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2236 Logger::info("Author " . $author . " wants to share with us - but doesn't want to listen. Request is ignored.");
2238 } elseif (!$following && !$sharing) {
2239 Logger::info("Author " . $author . " doesn't want anything - and we don't know the author. Request is ignored.");
2241 } elseif (!$following && $sharing) {
2242 Logger::info("Author " . $author . " wants to share with us.");
2243 } elseif ($following && $sharing) {
2244 Logger::info("Author " . $author . " wants to have a bidirectional conection.");
2245 } elseif ($following && !$sharing) {
2246 Logger::info("Author " . $author . " wants to listen to us.");
2250 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
2251 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
2252 Logger::notice('Cannot resolve diaspora handle for recipient', ['author' => $author->getAddr(), 'recipient' => $recipient]);
2256 $cid = Contact::getIdForURL($author_url, $importer['uid']);
2258 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2264 'author-id' => Contact::getIdForURL($author_url),
2265 'author-link' => $author_url
2268 $result = Contact::addRelationship($importer, $contact, $item, false);
2269 if ($result === true) {
2270 $contact_record = self::contactByHandle($importer['uid'], $author);
2271 if (!$contact_record) {
2272 Logger::info('unable to locate newly created contact record.');
2276 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2277 if (DBA::isResult($user)) {
2278 self::sendShare($user, $contact_record);
2280 // Send the profile data, maybe it weren't transmitted before
2281 self::sendProfile($importer['uid'], [$contact_record]);
2289 * Processes a reshare message
2291 * @param array $importer Array of the importer user
2292 * @param SimpleXMLElement $data The message object
2293 * @param string $xml The original XML of the message
2294 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2296 * @return bool Success or failure
2297 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2298 * @throws \ImagickException
2300 private static function receiveReshare(array $importer, SimpleXMLElement $data, string $xml, int $direction): bool
2302 $author = WebFingerUri::fromString(XML::unescape($data->author));
2303 $guid = XML::unescape($data->guid);
2304 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2306 $root_author = WebFingerUri::fromString(XML::unescape($data->root_author));
2307 } catch (\InvalidArgumentException $e) {
2311 $root_guid = XML::unescape($data->root_guid);
2312 /// @todo handle unprocessed property "provider_display_name"
2313 $public = XML::unescape($data->public);
2315 $contact = self::allowedContactByHandle($importer, $author);
2320 if (!empty($contact['gsid'])) {
2321 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2324 $message_id = self::messageExists($importer['uid'], $guid);
2330 $original_person = DI::dsprContact()->getByAddr($root_author);
2331 } catch (HTTPException\NotFoundException $e) {
2337 $datarray['uid'] = $importer['uid'];
2338 $datarray['contact-id'] = $contact['id'];
2339 $datarray['network'] = Protocol::DIASPORA;
2341 $datarray['author-link'] = $contact['url'];
2342 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2344 $datarray['owner-link'] = $datarray['author-link'];
2345 $datarray['owner-id'] = $datarray['author-id'];
2347 $datarray['guid'] = $guid;
2348 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($guid, $author);
2349 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2351 $datarray['verb'] = Activity::POST;
2352 $datarray['gravity'] = Item::GRAVITY_PARENT;
2354 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2355 $datarray['source'] = $xml;
2357 $datarray = self::setDirection($datarray, $direction);
2359 $datarray['quote-uri-id'] = self::getQuoteUriId($root_guid, $importer['uid'], $original_person->url);
2360 if (empty($datarray['quote-uri-id'])) {
2364 $datarray['body'] = '';
2365 $datarray['plink'] = self::plink($author, $guid);
2366 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2367 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2369 self::fetchGuid($datarray);
2371 if (Item::isTooOld($datarray)) {
2372 Logger::info('Reshare is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2376 $message_id = Item::insert($datarray);
2378 self::sendParticipation($contact, $datarray);
2381 Logger::info('Stored reshare ' . $datarray['guid'] . ' with message id ' . $message_id);
2382 if ($datarray['uid'] == 0) {
2383 Item::distribute($message_id);
2391 private static function getQuoteUriId(string $guid, int $uid, string $host): int
2393 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2395 if (!DBA::isResult($shared_item) && !empty($host) && Diaspora::storeByGuid($guid, $host, true)) {
2396 Logger::debug('Fetched post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2397 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2398 } elseif (DBA::isResult($shared_item)) {
2399 Logger::debug('Found existing post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2402 if (!DBA::isResult($shared_item)) {
2403 Logger::notice('Post does not exist.', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2407 return $shared_item['uri-id'];
2411 * Processes retractions
2413 * @param array $importer Array of the importer user
2414 * @param array $contact The contact of the item owner
2415 * @param SimpleXMLElement $data The message object
2417 * @return bool success
2418 * @throws \Exception
2420 private static function itemRetraction(array $importer, array $contact, SimpleXMLElement $data): bool
2422 $author_uri = WebFingerUri::fromString(XML::unescape($data->author));
2423 $target_guid = XML::unescape($data->target_guid);
2424 $target_type = XML::unescape($data->target_type);
2427 $author = DI::dsprContact()->getByAddr($author_uri);
2428 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
2429 Logger::notice('Unable to find details for author', ['author' => $author_uri->getAddr()]);
2433 $contact_url = $contact['url'] ?? '' ?: (string)$author->url;
2435 // Fetch items that are about to be deleted
2436 $fields = ['uid', 'id', 'parent', 'author-link', 'uri-id'];
2438 // When we receive a public retraction, we delete every item that we find.
2439 if ($importer['uid'] == 0) {
2440 $condition = ['guid' => $target_guid, 'deleted' => false];
2442 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2445 $r = Post::select($fields, $condition);
2446 if (!DBA::isResult($r)) {
2447 Logger::notice('Target guid ' . $target_guid . ' was not found on this system for user ' . $importer['uid'] . '.');
2451 while ($item = Post::fetch($r)) {
2452 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2453 Logger::info("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.");
2457 // Fetch the parent item
2458 $parent = Post::selectFirst(['author-link'], ['id' => $item['parent']]);
2460 // Only delete it if the parent author really fits
2461 if (!Strings::compareLink($parent['author-link'], $contact_url) && !Strings::compareLink($item['author-link'], $contact_url)) {
2462 Logger::info("Thread author " . $parent['author-link'] . " and item author " . $item['author-link'] . " don't fit to expected contact " . $contact_url);
2466 Item::markForDeletion(['id' => $item['id']]);
2468 Logger::info('Deleted target ' . $target_guid . ' (' . $item['id'] . ') from user ' . $item['uid'] . ' parent: ' . $item['parent']);
2476 * Receives retraction messages
2478 * @param array $importer Array of the importer user
2479 * @param WebFingerUri $sender The sender of the message
2480 * @param SimpleXMLElement $data The message object
2482 * @return bool Success
2483 * @throws \Exception
2485 private static function receiveRetraction(array $importer, WebFingerUri $sender, SimpleXMLElement $data)
2487 $target_type = XML::unescape($data->target_type);
2489 $contact = self::contactByHandle($importer['uid'], $sender);
2490 if (!$contact && (in_array($target_type, ['Contact', 'Person']))) {
2491 Logger::notice('Cannot find contact for sender: ' . $sender . ' and user ' . $importer['uid']);
2499 Logger::info('Got retraction for ' . $target_type . ', sender ' . $sender . ' and user ' . $importer['uid']);
2501 switch ($target_type) {
2506 case 'StatusMessage':
2507 return self::itemRetraction($importer, $contact, $data);
2509 case 'PollParticipation':
2511 // Currently unsupported
2515 Logger::notice('Unknown target type ' . $target_type);
2522 * Checks if an incoming message is wanted
2524 * @param array $item
2525 * @param string $author
2526 * @param string $body
2527 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2529 * @return boolean Is the message wanted?
2531 private static function isSolicitedMessage(array $item, string $author, string $body, int $direction): bool
2533 $contact = Contact::getByURL($author);
2534 if (DBA::exists('contact', ['`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)', $contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) {
2535 Logger::debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2539 if ($direction == self::FORCED_FETCH) {
2540 Logger::debug('Post is a forced fetch - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2544 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
2545 if (Relay::isSolicitedPost($tags, $body, $contact['id'], $item['uri'], Protocol::DIASPORA)) {
2546 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2554 * Store an attached photo in the post-media table
2557 * @param object $photo
2560 private static function storePhotoAsMedia(int $uriid, $photo)
2562 // @TODO Need to find object type, roland@f.haeder.net
2563 Logger::debug('photo='.get_class($photo));
2565 $data['uri-id'] = $uriid;
2566 $data['type'] = Post\Media::IMAGE;
2567 $data['url'] = XML::unescape($photo->remote_photo_path) . XML::unescape($photo->remote_photo_name);
2568 $data['height'] = (int)XML::unescape($photo->height ?? 0);
2569 $data['width'] = (int)XML::unescape($photo->width ?? 0);
2570 $data['description'] = XML::unescape($photo->text ?? '');
2572 Post\Media::insert($data);
2576 * Set direction and post reason
2578 * @param array $datarray
2579 * @param integer $direction
2583 public static function setDirection(array $datarray, int $direction): array
2585 $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
2587 if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
2588 $datarray['post-reason'] = Item::PR_FETCHED;
2589 } elseif ($datarray['uid'] == 0) {
2590 $datarray['post-reason'] = Item::PR_GLOBAL;
2592 $datarray['post-reason'] = Item::PR_PUSHED;
2599 * Receives status messages
2601 * @param array $importer Array of the importer user
2602 * @param SimpleXMLElement $data The message object
2603 * @param string $xml The original XML of the message
2604 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2606 * @return int|bool The message id of the newly created item or false on error
2607 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2608 * @throws \ImagickException
2610 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, string $xml, int $direction)
2612 $author = WebFingerUri::fromString(XML::unescape($data->author));
2613 $guid = XML::unescape($data->guid);
2614 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2615 $public = XML::unescape($data->public);
2616 $text = XML::unescape($data->text);
2617 $provider_display_name = XML::unescape($data->provider_display_name);
2619 $contact = self::allowedContactByHandle($importer, $author);
2624 if (!empty($contact['gsid'])) {
2625 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2628 $message_id = self::messageExists($importer['uid'], $guid);
2634 if ($data->location) {
2635 foreach ($data->location->children() as $fieldname => $data) {
2636 $address[$fieldname] = XML::unescape($data);
2640 $raw_body = $body = Markdown::toBBCode($text);
2644 $datarray['guid'] = $guid;
2645 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($guid, $author);
2646 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2648 // Attach embedded pictures to the body
2650 foreach ($data->photo as $photo) {
2651 self::storePhotoAsMedia($datarray['uri-id'], $photo);
2654 $datarray['object-type'] = Activity\ObjectType::IMAGE;
2655 $datarray['post-type'] = Item::PT_IMAGE;
2656 } elseif ($data->poll) {
2657 $datarray['object-type'] = Activity\ObjectType::NOTE;
2658 $datarray['post-type'] = Item::PT_POLL;
2660 $datarray['object-type'] = Activity\ObjectType::NOTE;
2661 $datarray['post-type'] = Item::PT_NOTE;
2664 /// @todo enable support for polls
2665 //if ($data->poll) {
2666 // foreach ($data->poll as $poll)
2671 /// @todo enable support for events
2673 $datarray['uid'] = $importer['uid'];
2674 $datarray['contact-id'] = $contact['id'];
2675 $datarray['network'] = Protocol::DIASPORA;
2677 $datarray['author-link'] = $contact['url'];
2678 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2680 $datarray['owner-link'] = $datarray['author-link'];
2681 $datarray['owner-id'] = $datarray['author-id'];
2683 $datarray['verb'] = Activity::POST;
2684 $datarray['gravity'] = Item::GRAVITY_PARENT;
2686 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2687 $datarray['source'] = $xml;
2689 $datarray = self::setDirection($datarray, $direction);
2691 $datarray['body'] = self::replacePeopleGuid($body, $contact['url']);
2692 $datarray['raw-body'] = self::replacePeopleGuid($raw_body, $contact['url']);
2694 self::storeMentions($datarray['uri-id'], $text);
2695 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
2697 if (!self::isSolicitedMessage($datarray, $author, $body, $direction)) {
2698 DBA::delete('item-uri', ['uri' => $datarray['uri']]);
2702 if ($provider_display_name != '') {
2703 $datarray['app'] = $provider_display_name;
2706 $datarray['plink'] = self::plink($author, $guid);
2707 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2708 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2710 if (isset($address['address'])) {
2711 $datarray['location'] = $address['address'];
2714 if (isset($address['lat']) && isset($address['lng'])) {
2715 $datarray['coord'] = $address['lat'] . ' ' . $address['lng'];
2718 self::fetchGuid($datarray);
2720 if (Item::isTooOld($datarray)) {
2721 Logger::info('Status is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2725 $message_id = Item::insert($datarray);
2727 self::sendParticipation($contact, $datarray);
2730 Logger::info('Stored item ' . $datarray['guid'] . ' with message id ' . $message_id);
2731 if ($datarray['uid'] == 0) {
2732 Item::distribute($message_id);
2740 /* ************************************************************************************** *
2741 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2742 * ************************************************************************************** */
2745 * returnes the handle of a contact
2747 * @param array $contact contact array
2749 * @return string the handle in the format user@domain.tld
2750 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2752 private static function myHandle(array $contact): string
2754 if (!empty($contact['addr'])) {
2755 return $contact['addr'];
2758 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2759 // So - just in case - we build the the address here.
2760 if ($contact['nickname'] != '') {
2761 $nick = $contact['nickname'];
2763 $nick = $contact['nick'];
2766 return $nick . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
2771 * Creates the data for a private message in the new format
2773 * @param string $msg The message that is to be transmitted
2774 * @param array $user The record of the sender
2775 * @param array $contact Target of the communication
2776 * @param string $prvkey The private key of the sender
2777 * @param string $pubkey The public key of the receiver
2779 * @return string The encrypted data
2780 * @throws \Exception
2782 public static function encodePrivateData(string $msg, array $user, array $contact, string $prvkey, string $pubkey): string
2784 Logger::debug('Message: ' . $msg);
2786 // without a public key nothing will work
2788 Logger::notice('pubkey missing: contact id: ' . $contact['id']);
2792 $aes_key = random_bytes(32);
2793 $b_aes_key = base64_encode($aes_key);
2794 $iv = random_bytes(16);
2795 $b_iv = base64_encode($iv);
2797 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2799 $json = json_encode(['iv' => $b_iv, 'key' => $b_aes_key]);
2801 $encrypted_key_bundle = '';
2802 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
2806 $json_object = json_encode(
2808 'aes_key' => base64_encode($encrypted_key_bundle),
2809 'encrypted_magic_envelope' => base64_encode($ciphertext)
2813 return $json_object;
2817 * Creates the envelope for the "fetch" endpoint and for the new format
2819 * @param string $msg The message that is to be transmitted
2820 * @param array $user The record of the sender
2822 * @return string The envelope
2823 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2825 public static function buildMagicEnvelope(string $msg, array $user): string
2827 $b64url_data = Strings::base64UrlEncode($msg);
2828 $data = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
2830 $key_id = Strings::base64UrlEncode(self::myHandle($user));
2831 $type = 'application/xml';
2832 $encoding = 'base64url';
2833 $alg = 'RSA-SHA256';
2834 $signable_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
2836 // Fallback if the private key wasn't transmitted in the expected field
2837 if ($user['uprvkey'] == '') {
2838 $user['uprvkey'] = $user['prvkey'];
2841 $signature = Crypto::rsaSign($signable_data, $user['uprvkey']);
2842 $sig = Strings::base64UrlEncode($signature);
2847 '@attributes' => ['type' => $type],
2848 'me:encoding' => $encoding,
2851 '@attributes2' => ['key_id' => $key_id]
2855 $namespaces = ['me' => ActivityNamespace::SALMON_ME];
2857 return XML::fromArray($xmldata, $xml, false, $namespaces);
2861 * Create the envelope for a message
2863 * @param string $msg The message that is to be transmitted
2864 * @param array $user The record of the sender
2865 * @param array $contact Target of the communication
2866 * @param string $prvkey The private key of the sender
2867 * @param string $pubkey The public key of the receiver
2868 * @param bool $public Is the message public?
2870 * @return string The message that will be transmitted to other servers
2871 * @throws \Exception
2873 public static function buildMessage(string $msg, array $user, array $contact, string $prvkey, string $pubkey, bool $public = false): string
2875 // The message is put into an envelope with the sender's signature
2876 $envelope = self::buildMagicEnvelope($msg, $user);
2878 // Private messages are put into a second envelope, encrypted with the receivers public key
2880 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
2887 * Creates a signature for a message
2889 * @param array $owner the array of the owner of the message
2890 * @param array $message The message that is to be signed
2892 * @return string The signature
2894 private static function signature(array $owner, array $message): string
2897 unset($sigmsg['author_signature']);
2898 unset($sigmsg['parent_author_signature']);
2900 $signed_text = implode(';', $sigmsg);
2902 return base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
2906 * Transmit a message to a target server
2908 * @param array $owner the array of the item owner
2909 * @param array $contact Target of the communication
2910 * @param string $envelope The message that is to be transmitted
2911 * @param bool $public_batch Is it a public post?
2912 * @param string $guid message guid
2914 * @return int Result of the transmission
2915 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2916 * @throws \ImagickException
2918 private static function transmit(array $owner, array $contact, string $envelope, bool $public_batch, string $guid = ''): int
2920 $enabled = intval(DI::config()->get('system', 'diaspora_enabled'));
2925 $logid = Strings::getRandomHex(4);
2927 // We always try to use the data from the diaspora-contact table.
2928 // This is important for transmitting data to Friendica servers.
2930 $target = DI::dsprContact()->getByAddr(WebFingerUri::fromString($contact['addr']));
2931 $dest_url = $public_batch ? $target->batch : $target->notify;
2932 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
2936 if (empty($dest_url)) {
2937 $dest_url = ($public_batch ? $contact['batch'] : $contact['notify']);
2941 Logger::notice('No URL for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2945 Logger::notice('transmit: ' . $logid . '-' . $guid . ' ' . $dest_url);
2947 if (!intval(DI::config()->get('system', 'diaspora_test'))) {
2948 $content_type = (($public_batch) ? 'application/magic-envelope+xml' : 'application/json');
2950 $postResult = DI::httpClient()->post($dest_url . '/', $envelope, ['Content-Type' => $content_type]);
2951 $return_code = $postResult->getReturnCode();
2953 Logger::notice('test_mode');
2957 Logger::notice('transmit: ' . $logid . '-' . $guid . ' to ' . $dest_url . ' returns: ' . $return_code);
2959 return $return_code ? $return_code : -1;
2964 * Build the post xml
2966 * @param string $type The message type
2967 * @param array $message The message data
2969 * @return string The post XML
2971 public static function buildPostXml(string $type, array $message): string
2973 $data = [$type => $message];
2975 return XML::fromArray($data, $xml);
2979 * Builds and transmit messages
2981 * @param array $owner the array of the item owner
2982 * @param array $contact Target of the communication
2983 * @param string $type The message type
2984 * @param array $message The message data
2985 * @param bool $public_batch Is it a public post?
2986 * @param string $guid message guid
2988 * @return int Result of the transmission
2989 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2990 * @throws \ImagickException
2992 private static function buildAndTransmit(array $owner, array $contact, string $type, array $message, bool $public_batch = false, string $guid = '')
2994 $msg = self::buildPostXml($type, $message);
2996 // Fallback if the private key wasn't transmitted in the expected field
2997 if (empty($owner['uprvkey'])) {
2998 $owner['uprvkey'] = $owner['prvkey'];
3001 // When sending content to Friendica contacts using the Diaspora protocol
3002 // we have to fetch the public key from the diaspora-contact.
3003 // This is due to the fact that legacy DFRN had unique keys for every contact.
3004 $pubkey = $contact['pubkey'];
3005 if (!empty($contact['addr'])) {
3007 $pubkey = DI::dsprContact()->getByAddr(WebFingerUri::fromString($contact['addr']))->pubKey;
3008 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
3012 // The "addr" field should always be filled.
3013 // If this isn't the case, it will raise a notice some lines later.
3014 // And in the log we will see where it came from, and we can handle it there.
3015 Logger::notice('Empty addr', ['contact' => $contact ?? [], 'callstack' => System::callstack(20)]);
3018 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $pubkey ?? '', $public_batch);
3020 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3022 Logger::info('Transmitted message', ['owner' => $owner['uid'], 'target' => $contact['addr'], 'type' => $type, 'guid' => $guid, 'result' => $return_code]);
3024 return $return_code;
3028 * sends a participation (Used to get all further updates)
3030 * @param array $contact Target of the communication
3031 * @param array $item Item array
3033 * @return int The result of the transmission
3034 * @throws \Exception
3036 private static function sendParticipation(array $contact, array $item): int
3038 // Don't send notifications for private postings
3039 if ($item['private'] == Item::PRIVATE) {
3043 $cachekey = 'diaspora:sendParticipation:' . $item['guid'];
3045 $result = DI::cache()->get($cachekey);
3046 if (!is_null($result)) {
3050 // Fetch some user id to have a valid handle to transmit the participation.
3051 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3052 // If the item belongs to a user, we take this user id.
3053 if ($item['uid'] == 0) {
3054 // @todo Possibly use an administrator account?
3055 $condition = ['verified' => true, 'blocked' => false,
3056 'account_removed' => false, 'account_expired' => false, 'account-type' => User::ACCOUNT_TYPE_PERSON];
3057 $first_user = DBA::selectFirst('user', ['uid'], $condition, ['order' => ['uid']]);
3058 $owner = User::getOwnerDataById($first_user['uid']);
3060 $owner = User::getOwnerDataById($item['uid']);
3063 $author_handle = self::myHandle($owner);
3066 'author' => $author_handle,
3067 'guid' => System::createUUID(),
3068 'parent_type' => 'Post',
3069 'parent_guid' => $item['guid']
3072 Logger::info('Send participation for ' . $item['guid'] . ' by ' . $author_handle);
3074 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3075 DI::cache()->set($cachekey, $item['guid'], Duration::QUARTER_HOUR);
3077 return self::buildAndTransmit($owner, $contact, 'participation', $message);
3081 * sends an account migration
3083 * @param array $owner the array of the item owner
3084 * @param array $contact Target of the communication
3085 * @param int $uid User ID
3087 * @return int The result of the transmission
3088 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3089 * @throws \ImagickException
3091 public static function sendAccountMigration(array $owner, array $contact, int $uid): int
3093 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3094 $profile = self::createProfileData($uid);
3096 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3097 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
3100 'author' => $old_handle,
3101 'profile' => $profile,
3102 'signature' => $signature
3105 Logger::info('Send account migration', ['msg' => $message]);
3107 return self::buildAndTransmit($owner, $contact, 'account_migration', $message);
3111 * Sends a "share" message
3113 * @param array $owner the array of the item owner
3114 * @param array $contact Target of the communication
3116 * @return int The result of the transmission
3117 * @throws \Exception
3119 public static function sendShare(array $owner, array $contact): int
3122 * @todo support the different possible combinations of "following" and "sharing"
3123 * Currently, Diaspora only interprets the "sharing" field
3125 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3129 switch ($contact["rel"]) {
3130 case Contact::FRIEND:
3134 case Contact::SHARING:
3138 case Contact::FOLLOWER:
3145 'author' => self::myHandle($owner),
3146 'recipient' => $contact['addr'],
3147 'following' => 'true',
3151 Logger::info('Send share', ['msg' => $message]);
3153 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3157 * sends an "unshare"
3159 * @param array $owner the array of the item owner
3160 * @param array $contact Target of the communication
3162 * @return int The result of the transmission
3163 * @throws \Exception
3165 public static function sendUnshare(array $owner, array $contact): int
3168 'author' => self::myHandle($owner),
3169 'recipient' => $contact['addr'],
3170 'following' => 'false',
3171 'sharing' => 'false'
3174 Logger::info('Send unshare', ['msg' => $message]);
3176 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3180 * Fetch reshare details
3182 * @param array $item The message body that is to be check
3184 * @return array Reshare details (empty if the item is no reshare)
3185 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3186 * @throws \ImagickException
3188 public static function getReshareDetails(array $item): array
3190 $reshared = DI::contentItem()->getSharedPost($item, ['guid', 'network', 'author-addr']);
3191 if (empty($reshared)) {
3195 // Skip if it isn't a pure repeated messages or not a real reshare
3196 if (!empty($reshared['comment']) || !in_array($reshared['post']['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
3201 'root_handle' => strtolower($reshared['post']['author-addr']),
3202 'root_guid' => $reshared['post']['guid'],
3207 * Create an event array
3209 * @param integer $event_id The id of the event
3211 * @return array with event data
3212 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3214 private static function buildEvent(string $event_id): array
3216 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
3217 if (!DBA::isResult($event)) {
3223 $owner = User::getOwnerDataById($event['uid']);
3228 $eventdata['author'] = self::myHandle($owner);
3230 if ($event['guid']) {
3231 $eventdata['guid'] = $event['guid'];
3234 $mask = DateTimeFormat::ATOM;
3236 /// @todo - establish "all day" events in Friendica
3237 $eventdata['all_day'] = 'false';
3239 $eventdata['timezone'] = 'UTC';
3241 if ($event['start']) {
3242 $eventdata['start'] = DateTimeFormat::utc($event['start'], $mask);
3244 if ($event['finish'] && !$event['nofinish']) {
3245 $eventdata['end'] = DateTimeFormat::utc($event['finish'], $mask);
3247 if ($event['summary']) {
3248 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3250 if ($event['desc']) {
3251 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3253 if ($event['location']) {
3254 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3255 $coord = Map::getCoordinates($event['location']);
3258 $location['address'] = html_entity_decode(BBCode::toMarkdown($event['location']));
3259 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3260 $location['lat'] = $coord['lat'];
3261 $location['lng'] = $coord['lon'];
3263 $location['lat'] = 0;
3264 $location['lng'] = 0;
3266 $eventdata['location'] = $location;
3273 * Create a post (status message or reshare)
3275 * @param array $item The item that will be exported
3276 * @param array $owner the array of the item owner
3279 * 'type' -> Message type ("status_message" or "reshare")
3280 * 'message' -> Array of XML elements of the status
3281 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3282 * @throws \ImagickException
3284 public static function buildStatus(array $item, array $owner)
3286 $cachekey = 'diaspora:buildStatus:' . $item['guid'];
3288 $result = DI::cache()->get($cachekey);
3289 if (!is_null($result)) {
3293 $myaddr = self::myHandle($owner);
3295 $public = ($item['private'] == Item::PRIVATE ? 'false' : 'true');
3296 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3297 $edited = DateTimeFormat::utc($item['edited'] ?? $item['created'], DateTimeFormat::ATOM);
3299 // Detect a share element and do a reshare
3300 if (($item['private'] != Item::PRIVATE) && ($ret = self::getReshareDetails($item))) {
3302 'author' => $myaddr,
3303 'guid' => $item['guid'],
3304 'created_at' => $created,
3305 'root_author' => $ret['root_handle'],
3306 'root_guid' => $ret['root_guid'],
3307 'provider_display_name' => $item['app'],
3313 $title = $item['title'];
3314 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
3316 // Fetch the title from an attached link - if there is one
3317 if (empty($item['title']) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3318 $page_data = BBCode::getAttachmentData($item['body']);
3319 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3320 $title = $page_data['title'];
3324 // convert to markdown
3325 $body = html_entity_decode(BBCode::toMarkdown($body));
3328 if (strlen($title)) {
3329 $body = '### ' . html_entity_decode($title) . "\n\n" . $body;
3332 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT]);
3333 if (!empty($attachments)) {
3334 $body .= "\n[hr]\n";
3335 foreach ($attachments as $attachment) {
3336 $body .= "[" . $attachment['description'] . "](" . $attachment['url'] . ")\n";
3342 if ($item['location'] != '')
3343 $location['address'] = $item['location'];
3345 if ($item['coord'] != '') {
3346 $coord = explode(' ', $item['coord']);
3347 $location['lat'] = $coord[0];
3348 $location['lng'] = $coord[1];
3352 'author' => $myaddr,
3353 'guid' => $item['guid'],
3354 'created_at' => $created,
3355 'edited_at' => $edited,
3356 'public' => $public,
3358 'provider_display_name' => $item['app'],
3359 'location' => $location
3362 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3363 if (!isset($location['lat']) || !isset($location['lng'])) {
3364 unset($message['location']);
3367 if ($item['event-id'] > 0) {
3368 $event = self::buildEvent($item['event-id']);
3369 if (count($event)) {
3370 $message['event'] = $event;
3372 if (!empty($event['location']['address']) &&
3373 !empty($event['location']['lat']) &&
3374 !empty($event['location']['lng'])) {
3375 $message['location'] = $event['location'];
3378 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3379 // $message['text'] = '';
3383 $type = 'status_message';
3388 'message' => $message
3391 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3396 private static function prependParentAuthorMention(string $body, string $profile_url): string
3398 $profile = Contact::getByURL($profile_url, false, ['addr', 'name']);
3399 if (!empty($profile['addr'])
3400 && !strstr($body, $profile['addr'])
3401 && !strstr($body, $profile_url)
3403 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3412 * @param array $item The item that will be exported
3413 * @param array $owner the array of the item owner
3414 * @param array $contact Target of the communication
3415 * @param bool $public_batch Is it a public post?
3417 * @return int The result of the transmission
3418 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3419 * @throws \ImagickException
3421 public static function sendStatus(array $item, array $owner, array $contact, bool $public_batch = false): int
3423 $status = self::buildStatus($item, $owner);
3425 return self::buildAndTransmit($owner, $contact, $status['type'], $status['message'], $public_batch, $item['guid']);
3429 * Creates a "like" object
3431 * @param array $item The item that will be exported
3432 * @param array $owner the array of the item owner
3434 * @return array|bool The data for a "like" or false on error
3435 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3437 private static function constructLike(array $item, array $owner)
3439 $parent = Post::selectFirst(['guid', 'uri', 'thr-parent'], ['uri' => $item['thr-parent']]);
3440 if (!DBA::isResult($parent)) {
3444 $target_type = ($parent['uri'] === $parent['thr-parent'] ? 'Post' : 'Comment');
3446 if ($item['verb'] === Activity::LIKE) {
3448 } elseif ($item['verb'] === Activity::DISLIKE) {
3449 $positive = 'false';
3453 'author' => self::myHandle($owner),
3454 'guid' => $item['guid'],
3455 'parent_guid' => $parent['guid'],
3456 'parent_type' => $target_type,
3457 'positive' => $positive,
3458 'author_signature' => '',
3463 * Creates an "EventParticipation" object
3465 * @param array $item The item that will be exported
3466 * @param array $owner the array of the item owner
3468 * @return array|bool The data for an "EventParticipation" or false on error
3469 * @throws \Exception
3471 private static function constructAttend(array $item, array $owner)
3473 $parent = Post::selectFirst(['guid'], ['uri' => $item['thr-parent']]);
3474 if (!DBA::isResult($parent)) {
3478 switch ($item['verb']) {
3479 case Activity::ATTEND:
3480 $attend_answer = 'accepted';
3482 case Activity::ATTENDNO:
3483 $attend_answer = 'declined';
3485 case Activity::ATTENDMAYBE:
3486 $attend_answer = 'tentative';
3489 Logger::warning('Unknown verb ' . $item['verb'] . ' in item ' . $item['guid']);
3494 'author' => self::myHandle($owner),
3495 'guid' => $item['guid'],
3496 'parent_guid' => $parent['guid'],
3497 'status' => $attend_answer,
3498 'author_signature' => ''
3503 * Creates the object for a comment
3505 * @param array $item The item that will be exported
3506 * @param array $owner the array of the item owner
3508 * @return array|false The data for a comment
3509 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3511 private static function constructComment(array $item, array $owner)
3513 $cachekey = 'diaspora:constructComment:' . $item['guid'];
3515 $result = DI::cache()->get($cachekey);
3516 if (!is_null($result)) {
3520 $toplevel_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3521 if (!DBA::isResult($toplevel_item)) {
3522 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3526 $thread_parent_item = $toplevel_item;
3527 if ($item['thr-parent'] != $item['parent-uri']) {
3528 $thread_parent_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3531 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
3533 // The replied to autor mention is prepended for clarity if:
3534 // - Item replied isn't yours
3535 // - Item is public or explicit mentions are disabled
3536 // - Implicit mentions are enabled
3538 $item['author-id'] != $thread_parent_item['author-id']
3539 && ($thread_parent_item['gravity'] != Item::GRAVITY_PARENT)
3540 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3541 && !DI::config()->get('system', 'disable_implicit_mentions')
3543 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3546 $text = html_entity_decode(BBCode::toMarkdown($body));
3547 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3548 $edited = DateTimeFormat::utc($item['edited'], DateTimeFormat::ATOM);
3551 'author' => self::myHandle($owner),
3552 'guid' => $item['guid'],
3553 'created_at' => $created,
3554 'edited_at' => $edited,
3555 'parent_guid' => $toplevel_item['guid'],
3557 'author_signature' => '',
3560 // Send the thread parent guid only if it is a threaded comment
3561 if ($item['thr-parent'] != $item['parent-uri']) {
3562 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3565 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3571 * Send a like or a comment
3573 * @param array $item The item that will be exported
3574 * @param array $owner the array of the item owner
3575 * @param array $contact Target of the communication
3576 * @param bool $public_batch Is it a public post?
3578 * @return int The result of the transmission
3579 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3580 * @throws \ImagickException
3582 public static function sendFollowup(array $item, array $owner, array $contact, bool $public_batch = false): int
3584 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3585 $message = self::constructAttend($item, $owner);
3586 $type = 'event_participation';
3587 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3588 $message = self::constructLike($item, $owner);
3590 } elseif (!in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
3591 $message = self::constructComment($item, $owner);
3595 if (empty($message)) {
3599 $message['author_signature'] = self::signature($owner, $message);
3601 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3605 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3607 * @param array $item The item that will be exported
3608 * @param array $owner the array of the item owner
3609 * @param array $contact Target of the communication
3610 * @param bool $public_batch Is it a public post?
3612 * @return int The result of the transmission
3613 * @throws \Exception
3615 public static function sendRelay(array $item, array $owner, array $contact, bool $public_batch = false): int
3617 if ($item['deleted']) {
3618 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3619 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3625 Logger::info('Got relayable data ' . $type . ' for item ' . $item['guid'] . ' (' . $item['id'] . ')');
3627 $msg = json_decode($item['signed_text'] ?? '', true);
3630 if (is_array($msg)) {
3631 foreach ($msg as $field => $data) {
3632 if (!$item['deleted']) {
3633 if ($field == 'diaspora_handle') {
3636 if ($field == 'target_type') {
3637 $field = 'parent_type';
3641 $message[$field] = $data;
3644 Logger::info('Signature text for item ' . $item['guid'] . ' (' . $item['id'] . ') could not be extracted: ' . $item['signed_text']);
3647 $message['parent_author_signature'] = self::signature($owner, $message);
3649 Logger::info('Relayed data', ['msg' => $message]);
3651 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3655 * Sends a retraction (deletion) of a message, like or comment
3657 * @param array $item The item that will be exported
3658 * @param array $owner the array of the item owner
3659 * @param array $contact Target of the communication
3660 * @param bool $public_batch Is it a public post?
3661 * @param bool $relay Is the retraction transmitted from a relay?
3663 * @return int The result of the transmission
3664 * @throws \Exception
3666 public static function sendRetraction(array $item, array $owner, array $contact, bool $public_batch = false, bool $relay = false): int
3668 $itemaddr = strtolower($item['author-addr']);
3670 $msg_type = 'retraction';
3672 if ($item['gravity'] == Item::GRAVITY_PARENT) {
3673 $target_type = 'Post';
3674 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3675 $target_type = 'Like';
3677 $target_type = 'Comment';
3681 'author' => $itemaddr,
3682 'target_guid' => $item['guid'],
3683 'target_type' => $target_type
3686 Logger::info('Got message', ['msg' => $message]);
3688 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item['guid']);
3694 * @param array $item The item that will be exported
3695 * @param array $owner The owner
3696 * @param array $contact Target of the communication
3698 * @return int The result of the transmission
3699 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3700 * @throws \ImagickException
3702 public static function sendMail(array $item, array $owner, array $contact): int
3704 $myaddr = self::myHandle($owner);
3706 $cnv = DBA::selectFirst('conv', [], ['id' => $item['convid'], 'uid' => $item['uid']]);
3707 if (!DBA::isResult($cnv)) {
3708 Logger::notice('Conversation not found.');
3712 $body = BBCode::toMarkdown($item['body']);
3713 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3716 'author' => $myaddr,
3717 'guid' => $item['guid'],
3718 'conversation_guid' => $cnv['guid'],
3720 'created_at' => $created,
3723 if ($item['reply']) {
3728 'author' => $cnv['creator'],
3729 'guid' => $cnv['guid'],
3730 'subject' => $cnv['subject'],
3731 'created_at' => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3732 'participants' => $cnv['recips'],
3736 $type = 'conversation';
3739 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item['guid']);
3743 * Split a name into first name and last name
3745 * @param string $name The name
3747 * @return array The array with "first" and "last"
3749 public static function splitName(string $name): array
3751 $name = trim($name);
3753 // Is the name longer than 64 characters? Then cut the rest of it.
3754 if (strlen($name) > 64) {
3755 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3756 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3758 $name = substr($name, 0, 64);
3762 // Take the first word as first name
3763 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3764 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3765 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3766 return ['first' => $first, 'last' => $last];
3769 // Take the last word as last name
3770 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3771 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3773 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3774 return ['first' => $first, 'last' => $last];
3777 // Take the first 32 characters if there is no space in the first 32 characters
3778 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3779 $first = substr($name, 0, 32);
3780 $last = substr($name, 32);
3781 return ['first' => $first, 'last' => $last];
3784 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3785 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3787 // Check if the last name is longer than 32 characters
3788 if (strlen($last) > 32) {
3789 if (strpos($last, ' ') <= 32) {
3790 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
3792 $last = substr($last, 0, 32);
3796 return ['first' => $first, 'last' => $last];
3800 * Create profile data
3802 * @param int $uid The user id
3804 * @return array The profile data
3805 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3807 private static function createProfileData(int $uid): array
3809 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
3811 if (!DBA::isResult($profile)) {
3815 $split_name = self::splitName($profile['name']);
3818 'author' => $profile['addr'],
3819 'first_name' => $split_name['first'],
3820 'last_name' => $split_name['last'],
3821 'image_url' => DI::baseUrl() . '/photo/custom/300/' . $profile['uid'] . '.jpg',
3822 'image_url_medium' => DI::baseUrl() . '/photo/custom/100/' . $profile['uid'] . '.jpg',
3823 'image_url_small' => DI::baseUrl() . '/photo/custom/50/' . $profile['uid'] . '.jpg',
3824 'searchable' => ($profile['net-publish'] ? 'true' : 'false'),
3828 'tag_string' => null,
3832 if ($data['searchable'] === 'true') {
3833 $data['birthday'] = '';
3835 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
3836 [$year, $month, $day] = sscanf($profile['dob'], '%4d-%2d-%2d');
3840 $data['birthday'] = DateTimeFormat::utc($year . '-' . $month . '-' . $day, 'Y-m-d');
3843 $data['about'] = BBCode::toMarkdown($profile['about'] ?? '');
3845 $data['location'] = $profile['location'];
3846 $data['tag_string'] = '';
3848 if ($profile['pub_keywords']) {
3849 $kw = str_replace(',', ' ', $profile['pub_keywords']);
3850 $kw = str_replace(' ', ' ', $kw);
3851 $arr = explode(' ', $kw);
3853 for ($x = 0; $x < 5; $x ++) {
3854 if (!empty($arr[$x])) {
3855 $data['tag_string'] .= '#'. trim($arr[$x]) .' ';
3860 $data['tag_string'] = trim($data['tag_string']);
3867 * Sends profile data
3869 * @param int $uid The user id
3870 * @param array $recipients optional, default empty array
3873 * @throws \Exception
3875 public static function sendProfile(int $uid, array $recipients = [])
3878 Logger::warning('Parameter "uid" is empty');
3882 $owner = User::getOwnerDataById($uid);
3883 if (empty($owner)) {
3884 Logger::warning('Cannot fetch User record', ['uid' => $uid]);
3888 if (empty($recipients)) {
3889 Logger::debug('No recipients provided, fetching for user', ['uid' => $uid]);
3890 $recipients = DBA::selectToArray('contact', [], ['network' => Protocol::DIASPORA, 'uid' => $uid, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
3893 if (empty($recipients)) {
3894 Logger::warning('Cannot fetch recipients', ['uid' => $uid]);
3898 $message = self::createProfileData($uid);
3900 // @todo Split this into single worker jobs
3901 foreach ($recipients as $recipient) {
3902 Logger::info('Send updated profile data for user ' . $uid . ' to contact ' . $recipient['id']);
3903 self::buildAndTransmit($owner, $recipient, 'profile', $message);
3908 * Creates the signature for likes that are created on our system
3910 * @param integer $uid The user of that comment
3911 * @param array $item Item array
3913 * @return array|bool Signed content or false on error
3914 * @throws \Exception
3916 public static function createLikeSignature(int $uid, array $item)
3918 $owner = User::getOwnerDataById($uid);
3919 if (empty($owner)) {
3920 Logger::info('No owner post, so not storing signature', ['uid' => $uid]);
3924 if (!in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3925 Logger::warning('Item is neither a like nor a dislike', ['uid' => $uid, 'item[verb]' => $item['verb']]);;
3929 $message = self::constructLike($item, $owner);
3930 if ($message === false) {
3934 $message['author_signature'] = self::signature($owner, $message);
3940 * Creates the signature for Comments that are created on our system
3942 * @param array $item Item array
3944 * @return array|bool Signed content or false on error
3945 * @throws \Exception
3947 public static function createCommentSignature(array $item)
3950 if (!empty($item['author-link'])) {
3951 $url = $item['author-link'];
3953 $contact = Contact::getById($item['author-id'], ['url']);
3954 if (empty($contact['url'])) {
3955 Logger::warning('Author Contact not found', ['author-id' => $item['author-id']]);
3958 $url = $contact['url'];
3961 $uid = User::getIdForURL($url);
3963 Logger::info('No owner post, so not storing signature', ['url' => $contact['url'] ?? 'No contact loaded']);
3967 $owner = User::getOwnerDataById($uid);
3968 if (empty($owner)) {
3969 Logger::info('No owner post, so not storing signature');
3973 // This is only needed for the automated tests
3974 if (empty($owner['uprvkey'])) {
3978 if (!self::parentSupportDiaspora($item['thr-parent-id'])) {
3979 Logger::info('One of the parents does not support Diaspora. A signature will not be created.', ['uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
3983 $message = self::constructComment($item, $owner);
3984 if ($message === false) {
3988 $message['author_signature'] = self::signature($owner, $message);
3994 * Check if the parent and their parents support Diaspora
3996 * @param integer $parent_id
3998 * @throws InternalServerErrorException
3999 * @throws \ImagickException
4001 private static function parentSupportDiaspora(int $parent_id): bool
4003 $parent_post = Post::selectFirstPost(['gravity', 'signed_text', 'author-link', 'thr-parent-id'], ['uri-id' => $parent_id]);
4004 if (empty($parent_post['thr-parent-id'])) {
4005 Logger::warning('Parent post does not exist.', ['parent-id' => $parent_id]);
4009 if (!self::isSupportedByContactUrl($parent_post['author-link'])) {
4010 Logger::info('Parent author is no Diaspora contact.', ['parent-id' => $parent_id]);
4014 if (($parent_post['gravity'] == Item::GRAVITY_COMMENT) && empty($parent_post['signed_text'])) {
4015 Logger::info('Parent comment has got no Diaspora signature.', ['parent-id' => $parent_id]);
4019 if ($parent_post['gravity'] == Item::GRAVITY_COMMENT) {
4020 return self::parentSupportDiaspora($parent_post['thr-parent-id']);
4026 public static function performReshare(int $UriId, int $uid): int
4028 $owner = User::getOwnerDataById($uid);
4029 $author = Contact::getPublicIdByUserId($uid);
4033 'verb' => Activity::POST,
4034 'contact-id' => $owner['id'],
4035 'author-id' => $author,
4036 'owner-id' => $author,
4038 'quote-uri-id' => $UriId,
4039 'allow_cid' => $owner['allow_cid'] ?? '',
4040 'allow_gid' => $owner['allow_gid']?? '',
4041 'deny_cid' => $owner['deny_cid'] ?? '',
4042 'deny_gid' => $owner['deny_gid'] ?? '',
4045 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
4046 $item['private'] = Item::PRIVATE;
4047 } elseif (DI::pConfig()->get($uid, 'system', 'unlisted')) {
4048 $item['private'] = Item::UNLISTED;
4050 $item['private'] = Item::PUBLIC;
4053 // Don't trigger the addons
4054 $item['api_source'] = false;
4056 return Item::insert($item, true);