3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol;
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\Markdown;
27 use Friendica\Core\Cache\Enum\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\GServer;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\Mail;
40 use Friendica\Model\Post;
41 use Friendica\Model\Tag;
42 use Friendica\Model\User;
43 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
44 use Friendica\Network\HTTPException;
45 use Friendica\Network\Probe;
46 use Friendica\Protocol\Delivery;
47 use Friendica\Util\Crypto;
48 use Friendica\Util\DateTimeFormat;
49 use Friendica\Util\Map;
50 use Friendica\Util\Network;
51 use Friendica\Util\Strings;
52 use Friendica\Util\XML;
53 use GuzzleHttp\Psr7\Uri;
57 * This class contains functions to communicate via the Diaspora protocol
58 * @see https://diaspora.github.io/diaspora_federation/
64 const FORCED_FETCH = 2;
67 * Return a list of participating contacts for a thread
69 * This is used for the participation feature.
70 * One of the parameters is a contact array.
71 * This is done to avoid duplicates.
73 * @param array $item Item that is about to be delivered
74 * @param array $contacts The previously fetched contacts
76 * @return array of relay servers
79 public static function participantsForThread(array $item, array $contacts): array
81 if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
82 Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]);
86 $items = Post::select(['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::notice('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 Contact::updateByUrlIfNeeded($uri->getAddr());
816 return Contact::getByURL($uri->getAddr(), null, [], $uid);
820 * Checks if the given contact url does support ActivityPub
822 * @param string $url profile url or WebFinger address
823 * @param boolean|null $update true = always update, false = never update, null = update when not found or outdated
825 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
826 * @throws \ImagickException
828 public static function isSupportedByContactUrl(string $url, ?bool $update = null): bool
830 $contact = Contact::getByURL($url, $update, ['uri-id', 'network']);
832 $supported = DI::dsprContact()->existsByUriId($contact['uri-id'] ?? 0);
834 if (!$supported && is_null($update) && ($contact['network'] == Protocol::DFRN)) {
835 $supported = self::isSupportedByContactUrl($url, true);
842 * Check if posting is allowed for this contact
844 * @param array $importer Array of the importer user
845 * @param array $contact The contact that is checked
846 * @param bool $is_comment Is the check for a comment?
848 * @return bool is the contact allowed to post?
850 private static function postAllow(array $importer, array $contact, bool $is_comment = false): bool
853 * Perhaps we were already sharing with this person. Now they're sharing with us.
854 * That makes us friends.
855 * Normally this should have handled by getting a request - but this could get lost
857 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
858 // It is not removed by now. Possibly the code is needed?
859 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
861 // array('rel' => Contact::FRIEND, 'writable' => true),
862 // array('id' => $contact["id"], 'uid' => $contact["uid"])
865 // $contact["rel"] = Contact::FRIEND;
866 // Logger::notice("defining user ".$contact["nick"]." as friend");
869 // Contact server is blocked
870 if (Network::isUrlBlocked($contact['url'])) {
872 // We don't seem to like that person
873 } elseif ($contact['blocked']) {
874 // Maybe blocked, don't accept.
876 // We are following this person?
877 } elseif (($contact['rel'] == Contact::SHARING) || ($contact['rel'] == Contact::FRIEND)) {
878 // Yes, then it is fine.
880 // Is the message a global user or a comment?
881 } elseif (($importer['uid'] == 0) || $is_comment) {
882 // Messages for the global users and comments are always accepted
890 * Fetches the contact id for a handle and checks if posting is allowed
892 * @param array $importer Array of the importer user
893 * @param WebFingerUri $contact_uri The checked contact
894 * @param bool $is_comment Is the check for a comment?
896 * @return array|bool The contact data or false on error
897 * @throws InternalServerErrorException
898 * @throws \ImagickException
900 private static function allowedContactByHandle(array $importer, WebFingerUri $contact_uri, bool $is_comment = false)
902 $contact = self::contactByHandle($importer['uid'], $contact_uri);
904 Logger::notice('A Contact for handle ' . $contact_uri . ' and user ' . $importer['uid'] . ' was not found');
905 // If a contact isn't found, we accept it anyway if it is a comment
906 if ($is_comment && ($importer['uid'] != 0)) {
907 return self::contactByHandle(0, $contact_uri);
908 } elseif ($is_comment) {
915 if (!self::postAllow($importer, $contact, $is_comment)) {
916 Logger::notice('The handle: ' . $contact_uri . ' is not allowed to post to user ' . $importer['uid']);
923 * Does the message already exists on the system?
925 * @param int $uid The user id
926 * @param string $guid The guid of the message
928 * @return int|bool message id if the message already was stored into the system - or false.
931 private static function messageExists(int $uid, string $guid)
933 $item = Post::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
934 if (DBA::isResult($item)) {
935 Logger::notice('Message ' . $guid . ' already exists for user ' . $uid);
943 * Checks for links to posts in a message
945 * @param array $item The item array
948 private static function fetchGuid(array $item)
950 preg_replace_callback(
951 "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism",
952 function ($match) use ($item) {
953 self::fetchGuidSub($match, $item);
958 preg_replace_callback(
959 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
960 function ($match) use ($item) {
961 self::fetchGuidSub($match, $item);
968 * Checks for relative /people/* links in an item body to match local
969 * contacts or prepends the remote host taken from the author link.
971 * @param string $body The item body to replace links from
972 * @param string $author_link The author link for missing local contact fallback
974 * @return string the replaced string
976 public static function replacePeopleGuid(string $body, string $author_link): string
978 $return = preg_replace_callback(
979 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
980 function ($match) use ($author_link) {
982 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
983 // 1 => '0123456789abcdef'
985 $handle = DI::dsprContact()->getUrlByGuid($match[1]);
988 $return = '@[url=' . $handle . ']' . $match[2] . '[/url]';
990 // No local match, restoring absolute remote URL from author scheme and host
991 $author_url = parse_url($author_link);
992 $return = '[url=' . $author_url['scheme'] . '://' . $author_url['host'] . '/people/' . $match[1] . ']' . $match[2] . '[/url]';
1004 * sub function of "fetchGuid" which checks for links in messages
1006 * @param array $match array containing a link that has to be checked for a message link
1007 * @param array $item The item array
1009 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1010 * @throws \ImagickException
1012 private static function fetchGuidSub(array $match, array $item)
1014 if (!self::storeByGuid($match[1], $item['author-link'], true)) {
1015 self::storeByGuid($match[1], $item['owner-link'], true);
1020 * Fetches an item with a given guid from a given server
1022 * @param string $guid the message guid
1023 * @param string $server The server address
1024 * @param bool $force Forced fetch
1026 * @return int|bool the message id of the stored message or false
1027 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1028 * @throws \ImagickException
1030 private static function storeByGuid(string $guid, string $server, bool $force)
1032 $serverparts = parse_url($server);
1034 if (empty($serverparts['host']) || empty($serverparts['scheme'])) {
1038 $server = $serverparts['scheme'] . '://' . $serverparts['host'];
1040 Logger::info('Trying to fetch item ' . $guid . ' from ' . $server);
1042 $msg = self::message($guid, $server);
1048 Logger::info('Successfully fetched item ' . $guid . ' from ' . $server);
1050 // Now call the dispatcher
1051 return self::dispatchPublic($msg, $force ? self::FORCED_FETCH : self::FETCHED);
1055 * Fetches a message from a server
1057 * @param string $guid message guid
1058 * @param string $server The url of the server
1059 * @param int $level Endless loop prevention
1062 * 'message' => The message XML
1063 * 'author' => The author handle
1064 * 'key' => The public key of the author
1065 * @throws \Exception
1067 public static function message(string $guid, string $server, int $level = 0)
1073 // This will work for new Diaspora servers and Friendica servers from 3.5
1074 $source_url = $server . '/fetch/post/' . urlencode($guid);
1076 Logger::info('Fetch post from ' . $source_url);
1078 $envelope = DI::httpClient()->fetch($source_url, HttpClientAccept::MAGIC);
1080 Logger::info('Envelope was fetched.');
1081 $x = self::verifyMagicEnvelope($envelope);
1083 Logger::info('Envelope could not be verified.');
1085 Logger::info('Envelope was verified.');
1095 $source_xml = XML::parseString($x);
1097 if (!is_object($source_xml)) {
1101 if ($source_xml->post->reshare) {
1102 // Reshare of a reshare - old Diaspora version
1103 Logger::info('Message is a reshare');
1104 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1105 } elseif ($source_xml->getName() == 'reshare') {
1106 // Reshare of a reshare - new Diaspora version
1107 Logger::info('Message is a new reshare');
1108 return self::message($source_xml->root_guid, $server, ++$level);
1111 $author_handle = '';
1113 // Fetch the author - for the old and the new Diaspora version
1114 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1115 $author_handle = (string)$source_xml->post->status_message->diaspora_handle;
1116 } elseif ($source_xml->author && ($source_xml->getName() == 'status_message')) {
1117 $author_handle = (string)$source_xml->author;
1121 $author = WebFingerUri::fromString($author_handle);
1122 } catch (\InvalidArgumentException $e) {
1123 // If this isn't a "status_message" then quit
1124 Logger::info("Message doesn't seem to be a status message");
1130 'author' => $author->getAddr(),
1131 'key' => self::key($author)
1136 * Fetches an item with a given URL
1138 * @param string $url the message url
1139 * @param int $uid User id
1141 * @return int|bool the message id of the stored message or false
1142 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1143 * @throws \ImagickException
1145 public static function fetchByURL(string $url, int $uid = 0)
1147 // Check for Diaspora (and Friendica) typical paths
1148 if (!preg_match('=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i', $url, $matches)) {
1149 Logger::info('Invalid url', ['url' => $url]);
1153 $guid = urldecode($matches[2]);
1155 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1156 if (DBA::isResult($item)) {
1157 Logger::info('Found', ['id' => $item['id']]);
1161 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1162 $ret = self::storeByGuid($guid, $matches[1], true);
1163 Logger::info('Result', ['ret' => $ret]);
1165 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1166 if (DBA::isResult($item)) {
1167 Logger::info('Found', ['id' => $item['id']]);
1170 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1176 * Fetches the item record of a given guid
1178 * @param int $uid The user id
1179 * @param string $guid message guid
1180 * @param WebFingerUri $author
1181 * @param array $contact The contact of the item owner
1183 * @return array|bool the item record or false on failure
1184 * @throws \Exception
1186 private static function parentItem(int $uid, string $guid, WebFingerUri $author, array $contact)
1188 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1189 'author-name', 'author-link', 'author-avatar', 'gravity',
1190 'owner-name', 'owner-link', 'owner-avatar'];
1192 $condition = ['uid' => $uid, 'guid' => $guid];
1193 $item = Post::selectFirst($fields, $condition);
1195 if (!DBA::isResult($item)) {
1197 $result = self::storeByGuid($guid, DI::dsprContact()->getByAddr($author)->url, false);
1199 // We don't have an url for items that arrived at the public dispatcher
1200 if (!$result && !empty($contact['url'])) {
1201 $result = self::storeByGuid($guid, $contact['url'], false);
1205 Logger::info('Fetched missing item ' . $guid . ' - result: ' . $result);
1207 $item = Post::selectFirst($fields, $condition);
1209 } catch (HTTPException\NotFoundException $e) {
1210 Logger::notice('Unable to retrieve author details', ['author' => $author->getAddr()]);
1214 if (!DBA::isResult($item)) {
1215 Logger::notice('Parent item not found: parent: ' . $guid . ' - user: ' . $uid);
1218 Logger::notice('Parent item found: parent: ' . $guid . ' - user: ' . $uid);
1224 * returns contact details for the given user
1226 * @param array $def_contact The default details if the contact isn't found
1227 * @param string $contact_url The url of the contact
1228 * @param int $uid The user id
1231 * 'cid' => contact id
1232 * 'network' => network type
1233 * @throws \Exception
1235 private static function authorContactByUrl(array $def_contact, string $contact_url, int $uid): array
1237 $condition = ['nurl' => Strings::normaliseLink($contact_url), 'uid' => $uid];
1238 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1239 if (DBA::isResult($contact)) {
1240 $cid = $contact['id'];
1241 $network = $contact['network'];
1243 $cid = $def_contact['id'];
1244 $network = Protocol::DIASPORA;
1249 'network' => $network
1254 * Is the profile a hubzilla profile?
1256 * @param string $url The profile link
1258 * @return bool is it a hubzilla server?
1260 private static function isHubzilla(string $url): bool
1262 return strstr($url, '/channel/');
1266 * Generate a post link with a given handle and message guid
1268 * @param string $addr The user handle
1269 * @param string $guid message guid
1270 * @param string $parent_guid optional parent guid
1272 * @return string the post link
1273 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1274 * @throws \ImagickException
1276 private static function plink(string $addr, string $guid, string $parent_guid = ''): string
1278 $contact = Contact::getByURL($addr);
1279 if (empty($contact)) {
1280 Logger::info('No contact data for address', ['addr' => $addr]);
1284 if (empty($contact['baseurl'])) {
1285 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1286 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1290 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1291 if (!empty($gserver['platform'])) {
1292 $platform = strtolower($gserver['platform']);
1293 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1296 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1297 if (self::isHubzilla($contact['url'])) {
1298 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1299 $platform = 'hubzilla';
1300 } elseif ($contact['network'] == Protocol::DFRN) {
1301 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1302 $platform = 'friendica';
1306 if ($platform == 'friendica') {
1307 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1310 if ($platform == 'hubzilla') {
1311 return $contact['baseurl'] . '/item/' . $guid;
1314 if ($platform == 'socialhome') {
1315 return $contact['baseurl'] . '/content/' . $guid;
1318 if ($platform != 'diaspora') {
1319 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1323 if ($parent_guid != '') {
1324 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1326 return $contact['baseurl'] . '/posts/' . $guid;
1331 * Receives account migration
1333 * @param array $importer Array of the importer user
1334 * @param SimpleXMLElement $data The message object
1336 * @return bool Success
1337 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1338 * @throws \ImagickException
1340 private static function receiveAccountMigration(array $importer, SimpleXMLElement $data): bool
1343 $old_author = WebFingerUri::fromString(XML::unescape($data->author));
1344 $new_author = WebFingerUri::fromString(XML::unescape($data->profile->author));
1345 } catch (\Throwable $e) {
1346 Logger::notice('Cannot find handles for sender and user', ['data' => $data]);
1350 $signature = XML::unescape($data->signature);
1352 $contact = self::contactByHandle($importer['uid'], $old_author);
1354 Logger::notice('Cannot find contact for sender: ' . $old_author . ' and user ' . $importer['uid']);
1358 Logger::notice('Got migration for ' . $old_author . ', to ' . $new_author . ' with user ' . $importer['uid']);
1361 $signed_text = 'AccountMigration:' . $old_author . ':' . $new_author;
1362 $key = self::key($old_author);
1363 if (!Crypto::rsaVerify($signed_text, $signature, $key, 'sha256')) {
1364 Logger::notice('No valid signature for migration.');
1368 // Update the profile
1369 self::receiveProfile($importer, $data->profile);
1371 // change the technical stuff in contact
1372 $data = Probe::uri($new_author);
1373 if ($data['network'] == Protocol::PHANTOM) {
1374 Logger::notice("Account for " . $new_author . " couldn't be probed.");
1379 'url' => $data['url'],
1380 'nurl' => Strings::normaliseLink($data['url']),
1381 'name' => $data['name'],
1382 'nick' => $data['nick'],
1383 'addr' => $data['addr'],
1384 'batch' => $data['batch'],
1385 'notify' => $data['notify'],
1386 'poll' => $data['poll'],
1387 'network' => $data['network'],
1390 Contact::update($fields, ['addr' => $old_author->getAddr()]);
1392 Logger::notice('Contacts are updated.');
1398 * Processes an account deletion
1400 * @param SimpleXMLElement $data The message object
1402 * @return bool Success
1403 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1405 private static function receiveAccountDeletion(SimpleXMLElement $data): bool
1407 $author_handle = XML::unescape($data->author);
1409 $contacts = DBA::select('contact', ['id'], ['addr' => $author_handle]);
1410 while ($contact = DBA::fetch($contacts)) {
1411 Contact::remove($contact['id']);
1413 DBA::close($contacts);
1415 Logger::notice('Removed contacts for ' . $author_handle);
1421 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1423 * @param string $guid Message guid
1424 * @param WebFingerUri|null $person_uri Optional person to derive the base URL from
1426 * @return string The constructed uri or the one from our database or empty string
1427 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1428 * @throws \ImagickException
1430 private static function getUriFromGuid(string $guid, WebFingerUri $person_uri = null): string
1432 $item = Post::selectFirst(['uri'], ['guid' => $guid]);
1434 return $item['uri'];
1435 } elseif ($person_uri) {
1437 return DI::dsprContact()->selectOneByAddr($person_uri)->baseurl . '/objects/' . $guid;
1438 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
1447 * Store the mentions in the tag table
1449 * @param integer $uriid
1450 * @param string $text
1452 private static function storeMentions(int $uriid, string $text)
1454 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1455 if (empty($matches)) {
1460 * Matching values for the preg match
1461 * [1] = mention type (@ or !)
1462 * [2] = name (optional)
1466 foreach ($matches as $match) {
1467 if (empty($match)) {
1472 $contact = DI::dsprContact()->getByUrl(new Uri($match[3]));
1473 Tag::storeByHash($uriid, $match[1], $contact->name ?: $contact->nick, $contact->url);
1474 } catch (\Throwable $e) {
1481 * Processes an incoming comment
1483 * @param array $importer Array of the importer user
1484 * @param WebFingerUri $sender The sender of the message
1485 * @param SimpleXMLElement $data The message object
1486 * @param string $xml The original XML of the message
1487 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1489 * @return bool The message id of the generated comment or "false" if there was an error
1490 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1491 * @throws \ImagickException
1493 private static function receiveComment(array $importer, WebFingerUri $sender, SimpleXMLElement $data, string $xml, int $direction): bool
1495 $author = WebFingerUri::fromString(XML::unescape($data->author));
1496 $guid = XML::unescape($data->guid);
1497 $parent_guid = XML::unescape($data->parent_guid);
1498 $text = XML::unescape($data->text);
1500 if (isset($data->created_at)) {
1501 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1503 $created_at = DateTimeFormat::utcNow();
1506 if (isset($data->thread_parent_guid)) {
1507 $thread_parent_guid = XML::unescape($data->thread_parent_guid);
1508 $thr_parent = self::getUriFromGuid($thread_parent_guid);
1513 $contact = self::allowedContactByHandle($importer, $sender, true);
1518 if (!empty($contact['gsid'])) {
1519 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1522 $message_id = self::messageExists($importer['uid'], $guid);
1527 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1528 if (!$toplevel_parent_item) {
1533 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
1534 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
1535 Logger::notice('Unable to find author details', ['author' => $author->getAddr()]);
1539 // Fetch the contact id - if we know this contact
1540 $author_contact = self::authorContactByUrl($contact, $author_url, $importer['uid']);
1544 $datarray['uid'] = $importer['uid'];
1545 $datarray['contact-id'] = $author_contact['cid'];
1546 $datarray['network'] = $author_contact['network'];
1548 $datarray['author-link'] = $author_url;
1549 $datarray['author-id'] = Contact::getIdForURL($author_url);
1551 $datarray['owner-link'] = $contact['url'];
1552 $datarray['owner-id'] = Contact::getIdForURL($contact['url']);
1554 // Will be overwritten for sharing accounts in Item::insert
1555 $datarray = self::setDirection($datarray, $direction);
1557 $datarray['guid'] = $guid;
1558 $datarray['uri'] = self::getUriFromGuid($guid, $author);
1559 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1561 $datarray['verb'] = Activity::POST;
1562 $datarray['gravity'] = Item::GRAVITY_COMMENT;
1564 $datarray['thr-parent'] = $thr_parent ?: $toplevel_parent_item['uri'];
1566 $datarray['object-type'] = Activity\ObjectType::COMMENT;
1567 $datarray['post-type'] = Item::PT_NOTE;
1569 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1570 $datarray['source'] = $xml;
1572 $datarray = self::setDirection($datarray, $direction);
1574 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
1576 $datarray['plink'] = self::plink($author, $guid, $toplevel_parent_item['guid']);
1577 $body = Markdown::toBBCode($text);
1579 $datarray['body'] = self::replacePeopleGuid($body, $author_url);
1581 self::storeMentions($datarray['uri-id'], $text);
1582 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
1584 self::fetchGuid($datarray);
1586 // If we are the origin of the parent we store the original data.
1587 // We notify our followers during the item storage.
1588 if ($toplevel_parent_item['origin']) {
1589 $datarray['diaspora_signed_text'] = json_encode($data);
1592 if (Item::isTooOld($datarray)) {
1593 Logger::info('Comment is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1597 $message_id = Item::insert($datarray);
1599 if ($message_id <= 0) {
1604 Logger::info('Stored comment ' . $datarray['guid'] . ' with message id ' . $message_id);
1605 if ($datarray['uid'] == 0) {
1606 Item::distribute($message_id, json_encode($data));
1614 * processes and stores private messages
1616 * @param array $importer Array of the importer user
1617 * @param array $contact The contact of the message
1618 * @param SimpleXMLElement $data The message object
1619 * @param array $msg Array of the processed message, author handle and key
1620 * @param object $mesg The private message
1621 * @param array $conversation The conversation record to which this message belongs
1623 * @return bool "true" if it was successful
1624 * @throws \Exception
1625 * @todo Find type-hint for $mesg and update documentation
1627 private static function receiveConversationMessage(array $importer, array $contact, SimpleXMLElement $data, array $msg, $mesg, array $conversation): bool
1629 $author_handle = XML::unescape($data->author);
1630 $guid = XML::unescape($data->guid);
1631 $subject = XML::unescape($data->subject);
1633 // "diaspora_handle" is the element name from the old version
1634 // "author" is the element name from the new version
1635 if ($mesg->author) {
1636 $msg_author_handle = XML::unescape($mesg->author);
1637 } elseif ($mesg->diaspora_handle) {
1638 $msg_author_handle = XML::unescape($mesg->diaspora_handle);
1644 $msg_author_uri = WebFingerUri::fromString($msg_author_handle);
1645 } catch (\InvalidArgumentException $e) {
1649 $msg_guid = XML::unescape($mesg->guid);
1650 $msg_conversation_guid = XML::unescape($mesg->conversation_guid);
1651 $msg_text = XML::unescape($mesg->text);
1652 $msg_created_at = DateTimeFormat::utc(XML::unescape($mesg->created_at));
1654 if ($msg_conversation_guid != $guid) {
1655 Logger::notice('Message conversation guid does not belong to the current conversation.', ['guid' => $guid]);
1659 $msg_author = DI::dsprContact()->getByAddr($msg_author_uri);
1661 return Mail::insert([
1662 'uid' => $importer['uid'],
1663 'guid' => $msg_guid,
1664 'convid' => $conversation['id'],
1665 'from-name' => $msg_author->name,
1666 'from-photo' => (string)$msg_author->photo,
1667 'from-url' => (string)$msg_author->url,
1668 'contact-id' => $contact['id'],
1669 'title' => $subject,
1670 'body' => Markdown::toBBCode($msg_text),
1671 'uri' => $msg_author_handle . ':' . $msg_guid,
1672 'parent-uri' => $author_handle . ':' . $guid,
1673 'created' => $msg_created_at
1678 * Processes new private messages (answers to private messages are processed elsewhere)
1680 * @param array $importer Array of the importer user
1681 * @param array $msg Array of the processed message, author handle and key
1682 * @param SimpleXMLElement $data The message object
1684 * @return bool Success
1685 * @throws \Exception
1687 private static function receiveConversation(array $importer, array $msg, SimpleXMLElement $data)
1689 $author_handle = XML::unescape($data->author);
1690 $guid = XML::unescape($data->guid);
1691 $subject = XML::unescape($data->subject);
1692 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1693 $participants = XML::unescape($data->participants);
1695 $messages = $data->message;
1697 if (!count($messages)) {
1698 Logger::notice('Empty conversation');
1702 $contact = self::allowedContactByHandle($importer, WebFingerUri::fromString($msg['author']), true);
1707 if (!empty($contact['gsid'])) {
1708 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1711 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1712 if (!DBA::isResult($conversation)) {
1713 $r = DBA::insert('conv', [
1714 'uid' => $importer['uid'],
1716 'creator' => $author_handle,
1717 'created' => $created_at,
1718 'updated' => DateTimeFormat::utcNow(),
1719 'subject' => $subject,
1720 'recips' => $participants
1724 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1727 if (!$conversation) {
1728 Logger::warning('Unable to create conversation.');
1732 foreach ($messages as $mesg) {
1733 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1740 * Processes "like" messages
1742 * @param array $importer Array of the importer user
1743 * @param WebFingerUri $sender The sender of the message
1744 * @param SimpleXMLElement $data The message object
1745 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1747 * @return bool Success or failure
1748 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1749 * @throws \ImagickException
1751 private static function receiveLike(array $importer, WebFingerUri $sender, SimpleXMLElement $data, int $direction): bool
1753 $author = WebFingerUri::fromString(XML::unescape($data->author));
1754 $guid = XML::unescape($data->guid);
1755 $parent_guid = XML::unescape($data->parent_guid);
1756 $parent_type = XML::unescape($data->parent_type);
1757 $positive = XML::unescape($data->positive);
1759 // likes on comments aren't supported by Diaspora - only on posts
1760 // But maybe this will be supported in the future, so we will accept it.
1761 if (!in_array($parent_type, ['Post', 'Comment'])) {
1765 $contact = self::allowedContactByHandle($importer, $sender, true);
1770 if (!empty($contact['gsid'])) {
1771 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1774 $message_id = self::messageExists($importer['uid'], $guid);
1779 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1780 if (!$toplevel_parent_item) {
1785 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
1786 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
1787 Logger::notice('Unable to find author details', ['author' => $author->getAddr()]);
1791 // Fetch the contact id - if we know this contact
1792 $author_contact = self::authorContactByUrl($contact, $author_url, $importer['uid']);
1794 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1795 // We would accept this anyhow.
1796 if ($positive == 'true') {
1797 $verb = Activity::LIKE;
1799 $verb = Activity::DISLIKE;
1804 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1806 $datarray['uid'] = $importer['uid'];
1807 $datarray['contact-id'] = $author_contact['cid'];
1808 $datarray['network'] = $author_contact['network'];
1810 $datarray = self::setDirection($datarray, $direction);
1812 $datarray['owner-link'] = $datarray['author-link'] = $author_url;
1813 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($author_url);
1815 $datarray['guid'] = $guid;
1816 $datarray['uri'] = self::getUriFromGuid($guid, $author);
1818 $datarray['verb'] = $verb;
1819 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
1820 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1822 $datarray['object-type'] = Activity\ObjectType::NOTE;
1824 $datarray['body'] = $verb;
1826 // Diaspora doesn't provide a date for likes
1827 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
1829 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1830 if ($toplevel_parent_item['gravity'] != Item::GRAVITY_PARENT) {
1831 $toplevel = Post::selectFirst(['origin'], ['id' => $toplevel_parent_item['parent']]);
1832 $origin = $toplevel['origin'];
1834 $origin = $toplevel_parent_item['origin'];
1837 // If we are the origin of the parent we store the original data.
1838 // We notify our followers during the item storage.
1840 $datarray['diaspora_signed_text'] = json_encode($data);
1843 if (Item::isTooOld($datarray)) {
1844 Logger::info('Like is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1848 $message_id = Item::insert($datarray);
1850 if ($message_id <= 0) {
1855 Logger::info('Stored like ' . $datarray['guid'] . ' with message id ' . $message_id);
1856 if ($datarray['uid'] == 0) {
1857 Item::distribute($message_id, json_encode($data));
1865 * Processes private messages
1867 * @param array $importer Array of the importer user
1868 * @param SimpleXMLElement $data The message object
1870 * @return bool Success?
1871 * @throws \Exception
1873 private static function receiveMessage(array $importer, SimpleXMLElement $data): bool
1875 $author_uri = WebFingerUri::fromString(XML::unescape($data->author));
1876 $guid = XML::unescape($data->guid);
1877 $conversation_guid = XML::unescape($data->conversation_guid);
1878 $text = XML::unescape($data->text);
1879 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1881 $contact = self::allowedContactByHandle($importer, $author_uri, true);
1886 if (!empty($contact['gsid'])) {
1887 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1890 $condition = ['uid' => $importer['uid'], 'guid' => $conversation_guid];
1891 $conversation = DBA::selectFirst('conv', [], $condition);
1892 if (!DBA::isResult($conversation)) {
1893 Logger::notice('Conversation not available.');
1898 $author = DI::dsprContact()->getByAddr($author_uri);
1899 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
1900 Logger::notice('Unable to find author details', ['author' => $author_uri->getAddr()]);
1904 $body = Markdown::toBBCode($text);
1906 $body = self::replacePeopleGuid($body, $author->url);
1908 return Mail::insert([
1909 'uid' => $importer['uid'],
1911 'convid' => $conversation['id'],
1912 'from-name' => $author->name,
1913 'from-photo' => (string)$author->photo,
1914 'from-url' => (string)$author->url,
1915 'contact-id' => $contact['id'],
1916 'title' => $conversation['subject'],
1919 'uri' => $author_uri . ':' . $guid,
1920 'parent-uri' => $author_uri . ':' . $conversation['guid'],
1921 'created' => $created_at
1926 * Processes participations - unsupported by now
1928 * @param array $importer Array of the importer user
1929 * @param SimpleXMLElement $data The message object
1930 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1932 * @return bool success
1933 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1934 * @throws \ImagickException
1936 private static function receiveParticipation(array $importer, SimpleXMLElement $data, int $direction): bool
1938 $author = WebFingerUri::fromString(strtolower(XML::unescape($data->author)));
1939 $guid = XML::unescape($data->guid);
1940 $parent_guid = XML::unescape($data->parent_guid);
1942 $contact = self::allowedContactByHandle($importer, $author, true);
1947 if (!empty($contact['gsid'])) {
1948 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1951 if (self::messageExists($importer['uid'], $guid)) {
1955 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1956 if (!$toplevel_parent_item) {
1960 if (!$toplevel_parent_item['origin']) {
1961 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1964 if (!in_array($toplevel_parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
1965 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1970 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
1971 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
1972 Logger::notice('unable to find author details', ['author' => $author->getAddr()]);
1976 $author_contact = self::authorContactByUrl($contact, $author_url, $importer['uid']);
1978 // Store participation
1981 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1983 $datarray['uid'] = $importer['uid'];
1984 $datarray['contact-id'] = $author_contact['cid'];
1985 $datarray['network'] = $author_contact['network'];
1987 $datarray = self::setDirection($datarray, $direction);
1989 $datarray['owner-link'] = $datarray['author-link'] = $author_url;
1990 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($author_url);
1992 $datarray['guid'] = $guid;
1993 $datarray['uri'] = self::getUriFromGuid($guid, $author);
1995 $datarray['verb'] = Activity::FOLLOW;
1996 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
1997 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1999 $datarray['object-type'] = Activity\ObjectType::NOTE;
2001 $datarray['body'] = Activity::FOLLOW;
2003 // Diaspora doesn't provide a date for a participation
2004 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
2006 if (Item::isTooOld($datarray)) {
2007 Logger::info('Participation is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2011 $message_id = Item::insert($datarray);
2013 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
2015 // Send all existing comments and likes to the requesting server
2016 $comments = Post::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb', 'gravity'],
2017 ['parent' => $toplevel_parent_item['id'], 'gravity' => [Item::GRAVITY_COMMENT, Item::GRAVITY_ACTIVITY]]);
2018 while ($comment = Post::fetch($comments)) {
2019 if (($comment['gravity'] == Item::GRAVITY_ACTIVITY) && !in_array($comment['verb'], [Activity::LIKE, Activity::DISLIKE])) {
2020 Logger::info('Unsupported activities are not relayed', ['item' => $comment['id'], 'verb' => $comment['verb']]);
2024 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
2025 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2029 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
2030 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2034 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact['cid']]);
2035 if (Worker::add(Worker::PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['uri-id'], $author_contact['cid'], $datarray['uid'])) {
2036 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2039 DBA::close($comments);
2045 * Processes photos - unneeded
2047 * @param array $importer Array of the importer user
2048 * @param SimpleXMLElement $data The message object
2050 * @return bool always true
2052 private static function receivePhoto(array $importer, $data)
2054 // There doesn't seem to be a reason for this function,
2055 // since the photo data is transmitted in the status message as well
2060 * Processes poll participations - unssupported
2062 * @param array $importer Array of the importer user
2063 * @param object $data The message object
2065 * @return bool always true
2067 private static function receivePollParticipation(array $importer, $data)
2069 // We don't support polls by now
2074 * Processes incoming profile updates
2076 * @param array $importer Array of the importer user
2077 * @param SimpleXMLElement $data The message object
2079 * @return bool Success
2080 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2081 * @throws \ImagickException
2083 private static function receiveProfile(array $importer, SimpleXMLElement $data): bool
2085 $author = WebFingerUri::fromString(strtolower(XML::unescape($data->author)));
2087 $contact = self::contactByHandle($importer['uid'], $author);
2092 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? ' ' . XML::unescape($data->last_name) : '');
2093 $image_url = XML::unescape($data->image_url);
2094 $birthday = XML::unescape($data->birthday);
2095 $about = Markdown::toBBCode(XML::unescape($data->bio));
2096 $location = Markdown::toBBCode(XML::unescape($data->location));
2097 $searchable = (XML::unescape($data->searchable) == 'true');
2098 $nsfw = (XML::unescape($data->nsfw) == 'true');
2099 $tags = XML::unescape($data->tag_string);
2101 $tags = explode('#', $tags);
2104 foreach ($tags as $tag) {
2105 $tag = trim(strtolower($tag));
2111 $keywords = implode(', ', $keywords);
2114 $name = $author->getUser();
2117 if (preg_match('|^https?://|', $image_url) === 0) {
2118 // @TODO No HTTPS here?
2119 $image_url = 'http://' . $author->getFullHost() . $image_url;
2122 Contact::updateAvatar($contact['id'], $image_url);
2124 // Generic birthday. We don't know the timezone. The year is irrelevant.
2126 $birthday = str_replace('1000', '1901', $birthday);
2128 if ($birthday != '') {
2129 $birthday = DateTimeFormat::utc($birthday, 'Y-m-d');
2132 // this is to prevent multiple birthday notifications in a single year
2133 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2135 if (substr($birthday, 5) === substr($contact['bd'], 5)) {
2136 $birthday = $contact['bd'];
2139 $fields = ['name' => $name, 'location' => $location,
2140 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2141 'addr' => $author->getAddr(), 'nick' => $author->getUser(), 'keywords' => $keywords,
2142 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2144 if (!empty($birthday)) {
2145 $fields['bd'] = $birthday;
2148 Contact::update($fields, ['id' => $contact['id']]);
2150 Logger::info('Profile of contact ' . $contact['id'] . ' stored for user ' . $importer['uid']);
2156 * Processes incoming friend requests
2158 * @param array $importer Array of the importer user
2159 * @param array $contact The contact that send the request
2161 * @throws \Exception
2163 private static function receiveRequestMakeFriend(array $importer, array $contact)
2165 if ($contact['rel'] == Contact::SHARING) {
2167 ['rel' => Contact::FRIEND, 'writable' => true],
2168 ['id' => $contact['id'], 'uid' => $importer['uid']]
2174 * Processes incoming sharing notification
2176 * @param array $importer Array of the importer user
2177 * @param SimpleXMLElement $data The message object
2179 * @return bool Success
2180 * @throws \Exception
2182 private static function receiveContactRequest(array $importer, SimpleXMLElement $data): bool
2184 $author_handle = XML::unescape($data->author);
2185 $recipient = XML::unescape($data->recipient);
2187 if (!$author_handle || !$recipient) {
2191 $author = WebFingerUri::fromString($author_handle);
2193 // the current protocol version doesn't know these fields
2194 // That means that we will assume their existance
2195 if (isset($data->following)) {
2196 $following = (XML::unescape($data->following) == 'true');
2201 if (isset($data->sharing)) {
2202 $sharing = (XML::unescape($data->sharing) == 'true');
2207 $contact = self::contactByHandle($importer['uid'], $author);
2209 // perhaps we were already sharing with this person. Now they're sharing with us.
2210 // That makes us friends.
2213 Logger::info('Author ' . $author . ' (Contact ' . $contact['id'] . ') wants to follow us.');
2214 self::receiveRequestMakeFriend($importer, $contact);
2216 // refetch the contact array
2217 $contact = self::contactByHandle($importer['uid'], $author);
2219 // If we are now friends, we are sending a share message.
2220 // Normally we needn't to do so, but the first message could have been vanished.
2221 if (in_array($contact['rel'], [Contact::FRIEND])) {
2222 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2223 if (DBA::isResult($user)) {
2224 Logger::info('Sending share message to author ' . $author . ' - Contact: ' . $contact['id'] . ' - User: ' . $importer['uid']);
2225 self::sendShare($user, $contact);
2230 Logger::info("Author " . $author . " doesn't want to follow us anymore.");
2231 Contact::removeFollower($contact);
2236 if (!$following && $sharing && in_array($importer['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2237 Logger::info("Author " . $author . " wants to share with us - but doesn't want to listen. Request is ignored.");
2239 } elseif (!$following && !$sharing) {
2240 Logger::info("Author " . $author . " doesn't want anything - and we don't know the author. Request is ignored.");
2242 } elseif (!$following && $sharing) {
2243 Logger::info("Author " . $author . " wants to share with us.");
2244 } elseif ($following && $sharing) {
2245 Logger::info("Author " . $author . " wants to have a bidirectional conection.");
2246 } elseif ($following && !$sharing) {
2247 Logger::info("Author " . $author . " wants to listen to us.");
2251 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
2252 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
2253 Logger::notice('Cannot resolve diaspora handle for recipient', ['author' => $author->getAddr(), 'recipient' => $recipient]);
2257 $cid = Contact::getIdForURL($author_url, $importer['uid']);
2259 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2265 'author-id' => Contact::getIdForURL($author_url),
2266 'author-link' => $author_url
2269 $result = Contact::addRelationship($importer, $contact, $item, false);
2270 if ($result === true) {
2271 $contact_record = self::contactByHandle($importer['uid'], $author);
2272 if (!$contact_record) {
2273 Logger::info('unable to locate newly created contact record.');
2277 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2278 if (DBA::isResult($user)) {
2279 self::sendShare($user, $contact_record);
2281 // Send the profile data, maybe it weren't transmitted before
2282 self::sendProfile($importer['uid'], [$contact_record]);
2290 * Processes a reshare message
2292 * @param array $importer Array of the importer user
2293 * @param SimpleXMLElement $data The message object
2294 * @param string $xml The original XML of the message
2295 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2297 * @return bool Success or failure
2298 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2299 * @throws \ImagickException
2301 private static function receiveReshare(array $importer, SimpleXMLElement $data, string $xml, int $direction): bool
2303 $author = WebFingerUri::fromString(XML::unescape($data->author));
2304 $guid = XML::unescape($data->guid);
2305 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2307 $root_author = WebFingerUri::fromString(XML::unescape($data->root_author));
2308 } catch (\InvalidArgumentException $e) {
2312 $root_guid = XML::unescape($data->root_guid);
2313 /// @todo handle unprocessed property "provider_display_name"
2314 $public = XML::unescape($data->public);
2316 $contact = self::allowedContactByHandle($importer, $author);
2321 if (!empty($contact['gsid'])) {
2322 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2325 $message_id = self::messageExists($importer['uid'], $guid);
2331 $original_person = DI::dsprContact()->getByAddr($root_author);
2332 } catch (HTTPException\NotFoundException $e) {
2338 $datarray['uid'] = $importer['uid'];
2339 $datarray['contact-id'] = $contact['id'];
2340 $datarray['network'] = Protocol::DIASPORA;
2342 $datarray['author-link'] = $contact['url'];
2343 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2345 $datarray['owner-link'] = $datarray['author-link'];
2346 $datarray['owner-id'] = $datarray['author-id'];
2348 $datarray['guid'] = $guid;
2349 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($guid, $author);
2350 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2352 $datarray['verb'] = Activity::POST;
2353 $datarray['gravity'] = Item::GRAVITY_PARENT;
2355 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2356 $datarray['source'] = $xml;
2358 $datarray = self::setDirection($datarray, $direction);
2360 $datarray['quote-uri-id'] = self::getQuoteUriId($root_guid, $importer['uid'], $original_person->url);
2361 if (empty($datarray['quote-uri-id'])) {
2365 $datarray['body'] = '';
2366 $datarray['plink'] = self::plink($author, $guid);
2367 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2368 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2370 self::fetchGuid($datarray);
2372 if (Item::isTooOld($datarray)) {
2373 Logger::info('Reshare is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2377 $message_id = Item::insert($datarray);
2379 self::sendParticipation($contact, $datarray);
2382 Logger::info('Stored reshare ' . $datarray['guid'] . ' with message id ' . $message_id);
2383 if ($datarray['uid'] == 0) {
2384 Item::distribute($message_id);
2392 private static function getQuoteUriId(string $guid, int $uid, string $host): int
2394 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2396 if (!DBA::isResult($shared_item) && !empty($host) && Diaspora::storeByGuid($guid, $host, true)) {
2397 Logger::debug('Fetched post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2398 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2399 } elseif (DBA::isResult($shared_item)) {
2400 Logger::debug('Found existing post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2403 if (!DBA::isResult($shared_item)) {
2404 Logger::notice('Post does not exist.', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2408 return $shared_item['uri-id'];
2412 * Processes retractions
2414 * @param array $importer Array of the importer user
2415 * @param array $contact The contact of the item owner
2416 * @param SimpleXMLElement $data The message object
2418 * @return bool success
2419 * @throws \Exception
2421 private static function itemRetraction(array $importer, array $contact, SimpleXMLElement $data): bool
2423 $author_uri = WebFingerUri::fromString(XML::unescape($data->author));
2424 $target_guid = XML::unescape($data->target_guid);
2425 $target_type = XML::unescape($data->target_type);
2428 $author = DI::dsprContact()->getByAddr($author_uri);
2429 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
2430 Logger::notice('Unable to find details for author', ['author' => $author_uri->getAddr()]);
2434 $contact_url = $contact['url'] ?? '' ?: (string)$author->url;
2436 // Fetch items that are about to be deleted
2437 $fields = ['uid', 'id', 'parent', 'author-link', 'uri-id'];
2439 // When we receive a public retraction, we delete every item that we find.
2440 if ($importer['uid'] == 0) {
2441 $condition = ['guid' => $target_guid, 'deleted' => false];
2443 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2446 $r = Post::select($fields, $condition);
2447 if (!DBA::isResult($r)) {
2448 Logger::notice('Target guid ' . $target_guid . ' was not found on this system for user ' . $importer['uid'] . '.');
2452 while ($item = Post::fetch($r)) {
2453 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2454 Logger::info("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.");
2458 // Fetch the parent item
2459 $parent = Post::selectFirst(['author-link'], ['id' => $item['parent']]);
2461 // Only delete it if the parent author really fits
2462 if (!Strings::compareLink($parent['author-link'], $contact_url) && !Strings::compareLink($item['author-link'], $contact_url)) {
2463 Logger::info("Thread author " . $parent['author-link'] . " and item author " . $item['author-link'] . " don't fit to expected contact " . $contact_url);
2467 Item::markForDeletion(['id' => $item['id']]);
2469 Logger::info('Deleted target ' . $target_guid . ' (' . $item['id'] . ') from user ' . $item['uid'] . ' parent: ' . $item['parent']);
2477 * Receives retraction messages
2479 * @param array $importer Array of the importer user
2480 * @param WebFingerUri $sender The sender of the message
2481 * @param SimpleXMLElement $data The message object
2483 * @return bool Success
2484 * @throws \Exception
2486 private static function receiveRetraction(array $importer, WebFingerUri $sender, SimpleXMLElement $data)
2488 $target_type = XML::unescape($data->target_type);
2490 $contact = self::contactByHandle($importer['uid'], $sender);
2491 if (!$contact && (in_array($target_type, ['Contact', 'Person']))) {
2492 Logger::notice('Cannot find contact for sender: ' . $sender . ' and user ' . $importer['uid']);
2500 Logger::info('Got retraction for ' . $target_type . ', sender ' . $sender . ' and user ' . $importer['uid']);
2502 switch ($target_type) {
2507 case 'StatusMessage':
2508 return self::itemRetraction($importer, $contact, $data);
2510 case 'PollParticipation':
2512 // Currently unsupported
2516 Logger::notice('Unknown target type ' . $target_type);
2523 * Checks if an incoming message is wanted
2525 * @param array $item
2526 * @param string $author
2527 * @param string $body
2528 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2530 * @return boolean Is the message wanted?
2532 private static function isSolicitedMessage(array $item, string $author, string $body, int $direction): bool
2534 $contact = Contact::getByURL($author);
2535 if (DBA::exists('contact', ['`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)', $contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) {
2536 Logger::debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2540 if ($direction == self::FORCED_FETCH) {
2541 Logger::debug('Post is a forced fetch - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2545 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
2546 if (Relay::isSolicitedPost($tags, $body, $contact['id'], $item['uri'], Protocol::DIASPORA)) {
2547 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2555 * Store an attached photo in the post-media table
2558 * @param object $photo
2561 private static function storePhotoAsMedia(int $uriid, $photo)
2563 // @TODO Need to find object type, roland@f.haeder.net
2564 Logger::debug('photo='.get_class($photo));
2566 $data['uri-id'] = $uriid;
2567 $data['type'] = Post\Media::IMAGE;
2568 $data['url'] = XML::unescape($photo->remote_photo_path) . XML::unescape($photo->remote_photo_name);
2569 $data['height'] = (int)XML::unescape($photo->height ?? 0);
2570 $data['width'] = (int)XML::unescape($photo->width ?? 0);
2571 $data['description'] = XML::unescape($photo->text ?? '');
2573 Post\Media::insert($data);
2577 * Set direction and post reason
2579 * @param array $datarray
2580 * @param integer $direction
2584 public static function setDirection(array $datarray, int $direction): array
2586 $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
2588 if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
2589 $datarray['post-reason'] = Item::PR_FETCHED;
2590 } elseif ($datarray['uid'] == 0) {
2591 $datarray['post-reason'] = Item::PR_GLOBAL;
2593 $datarray['post-reason'] = Item::PR_PUSHED;
2600 * Receives status messages
2602 * @param array $importer Array of the importer user
2603 * @param SimpleXMLElement $data The message object
2604 * @param string $xml The original XML of the message
2605 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2607 * @return int|bool The message id of the newly created item or false on error
2608 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2609 * @throws \ImagickException
2611 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, string $xml, int $direction)
2613 $author = WebFingerUri::fromString(XML::unescape($data->author));
2614 $guid = XML::unescape($data->guid);
2615 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2616 $public = XML::unescape($data->public);
2617 $text = XML::unescape($data->text);
2618 $provider_display_name = XML::unescape($data->provider_display_name);
2620 $contact = self::allowedContactByHandle($importer, $author);
2625 if (!empty($contact['gsid'])) {
2626 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2629 $message_id = self::messageExists($importer['uid'], $guid);
2635 if ($data->location) {
2636 foreach ($data->location->children() as $fieldname => $data) {
2637 $address[$fieldname] = XML::unescape($data);
2641 $raw_body = $body = Markdown::toBBCode($text);
2645 $datarray['guid'] = $guid;
2646 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($guid, $author);
2647 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2649 // Attach embedded pictures to the body
2651 foreach ($data->photo as $photo) {
2652 self::storePhotoAsMedia($datarray['uri-id'], $photo);
2655 $datarray['object-type'] = Activity\ObjectType::IMAGE;
2656 $datarray['post-type'] = Item::PT_IMAGE;
2657 } elseif ($data->poll) {
2658 $datarray['object-type'] = Activity\ObjectType::NOTE;
2659 $datarray['post-type'] = Item::PT_POLL;
2661 $datarray['object-type'] = Activity\ObjectType::NOTE;
2662 $datarray['post-type'] = Item::PT_NOTE;
2665 /// @todo enable support for polls
2666 //if ($data->poll) {
2667 // foreach ($data->poll as $poll)
2672 /// @todo enable support for events
2674 $datarray['uid'] = $importer['uid'];
2675 $datarray['contact-id'] = $contact['id'];
2676 $datarray['network'] = Protocol::DIASPORA;
2678 $datarray['author-link'] = $contact['url'];
2679 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2681 $datarray['owner-link'] = $datarray['author-link'];
2682 $datarray['owner-id'] = $datarray['author-id'];
2684 $datarray['verb'] = Activity::POST;
2685 $datarray['gravity'] = Item::GRAVITY_PARENT;
2687 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2688 $datarray['source'] = $xml;
2690 $datarray = self::setDirection($datarray, $direction);
2692 $datarray['body'] = self::replacePeopleGuid($body, $contact['url']);
2693 $datarray['raw-body'] = self::replacePeopleGuid($raw_body, $contact['url']);
2695 self::storeMentions($datarray['uri-id'], $text);
2696 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
2698 if (!self::isSolicitedMessage($datarray, $author, $body, $direction)) {
2699 DBA::delete('item-uri', ['uri' => $datarray['uri']]);
2703 if ($provider_display_name != '') {
2704 $datarray['app'] = $provider_display_name;
2707 $datarray['plink'] = self::plink($author, $guid);
2708 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2709 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2711 if (isset($address['address'])) {
2712 $datarray['location'] = $address['address'];
2715 if (isset($address['lat']) && isset($address['lng'])) {
2716 $datarray['coord'] = $address['lat'] . ' ' . $address['lng'];
2719 self::fetchGuid($datarray);
2721 if (Item::isTooOld($datarray)) {
2722 Logger::info('Status is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2726 $message_id = Item::insert($datarray);
2728 self::sendParticipation($contact, $datarray);
2731 Logger::info('Stored item ' . $datarray['guid'] . ' with message id ' . $message_id);
2732 if ($datarray['uid'] == 0) {
2733 Item::distribute($message_id);
2741 /* ************************************************************************************** *
2742 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2743 * ************************************************************************************** */
2746 * returnes the handle of a contact
2748 * @param array $contact contact array
2750 * @return string the handle in the format user@domain.tld
2751 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2753 private static function myHandle(array $contact): string
2755 if (!empty($contact['addr'])) {
2756 return $contact['addr'];
2759 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2760 // So - just in case - we build the the address here.
2761 if ($contact['nickname'] != '') {
2762 $nick = $contact['nickname'];
2764 $nick = $contact['nick'];
2767 return $nick . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
2772 * Creates the data for a private message in the new format
2774 * @param string $msg The message that is to be transmitted
2775 * @param array $user The record of the sender
2776 * @param array $contact Target of the communication
2777 * @param string $prvkey The private key of the sender
2778 * @param string $pubkey The public key of the receiver
2780 * @return string The encrypted data
2781 * @throws \Exception
2783 public static function encodePrivateData(string $msg, array $user, array $contact, string $prvkey, string $pubkey): string
2785 Logger::debug('Message: ' . $msg);
2787 // without a public key nothing will work
2789 Logger::notice('pubkey missing: contact id: ' . $contact['id']);
2793 $aes_key = random_bytes(32);
2794 $b_aes_key = base64_encode($aes_key);
2795 $iv = random_bytes(16);
2796 $b_iv = base64_encode($iv);
2798 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2800 $json = json_encode(['iv' => $b_iv, 'key' => $b_aes_key]);
2802 $encrypted_key_bundle = '';
2803 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
2807 $json_object = json_encode(
2809 'aes_key' => base64_encode($encrypted_key_bundle),
2810 'encrypted_magic_envelope' => base64_encode($ciphertext)
2814 return $json_object;
2818 * Creates the envelope for the "fetch" endpoint and for the new format
2820 * @param string $msg The message that is to be transmitted
2821 * @param array $user The record of the sender
2823 * @return string The envelope
2824 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2826 public static function buildMagicEnvelope(string $msg, array $user): string
2828 $b64url_data = Strings::base64UrlEncode($msg);
2829 $data = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
2831 $key_id = Strings::base64UrlEncode(self::myHandle($user));
2832 $type = 'application/xml';
2833 $encoding = 'base64url';
2834 $alg = 'RSA-SHA256';
2835 $signable_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
2837 // Fallback if the private key wasn't transmitted in the expected field
2838 if ($user['uprvkey'] == '') {
2839 $user['uprvkey'] = $user['prvkey'];
2842 $signature = Crypto::rsaSign($signable_data, $user['uprvkey']);
2843 $sig = Strings::base64UrlEncode($signature);
2848 '@attributes' => ['type' => $type],
2849 'me:encoding' => $encoding,
2852 '@attributes2' => ['key_id' => $key_id]
2856 $namespaces = ['me' => ActivityNamespace::SALMON_ME];
2858 return XML::fromArray($xmldata, $dummy, false, $namespaces);
2862 * Create the envelope for a message
2864 * @param string $msg The message that is to be transmitted
2865 * @param array $user The record of the sender
2866 * @param array $contact Target of the communication
2867 * @param string $prvkey The private key of the sender
2868 * @param string $pubkey The public key of the receiver
2869 * @param bool $public Is the message public?
2871 * @return string The message that will be transmitted to other servers
2872 * @throws \Exception
2874 public static function buildMessage(string $msg, array $user, array $contact, string $prvkey, string $pubkey, bool $public = false): string
2876 // The message is put into an envelope with the sender's signature
2877 $envelope = self::buildMagicEnvelope($msg, $user);
2879 // Private messages are put into a second envelope, encrypted with the receivers public key
2881 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
2888 * Creates a signature for a message
2890 * @param array $owner the array of the owner of the message
2891 * @param array $message The message that is to be signed
2893 * @return string The signature
2895 private static function signature(array $owner, array $message): string
2898 unset($sigmsg['author_signature']);
2899 unset($sigmsg['parent_author_signature']);
2901 $signed_text = implode(';', $sigmsg);
2903 return base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
2907 * Transmit a message to a target server
2909 * @param array $owner the array of the item owner
2910 * @param array $contact Target of the communication
2911 * @param string $envelope The message that is to be transmitted
2912 * @param bool $public_batch Is it a public post?
2913 * @param string $guid message guid
2915 * @return int Result of the transmission
2916 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2917 * @throws \ImagickException
2919 private static function transmit(array $owner, array $contact, string $envelope, bool $public_batch, string $guid = ''): int
2921 $enabled = intval(DI::config()->get('system', 'diaspora_enabled'));
2926 $logid = Strings::getRandomHex(4);
2928 // We always try to use the data from the diaspora-contact table.
2929 // This is important for transmitting data to Friendica servers.
2931 $target = DI::dsprContact()->getByAddr(WebFingerUri::fromString($contact['addr']));
2932 $dest_url = $public_batch ? $target->batch : $target->notify;
2933 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
2937 if (empty($dest_url)) {
2938 $dest_url = ($public_batch ? $contact['batch'] : $contact['notify']);
2942 Logger::notice('No URL for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2946 Logger::notice('transmit: ' . $logid . '-' . $guid . ' ' . $dest_url);
2948 if (!intval(DI::config()->get('system', 'diaspora_test'))) {
2949 $content_type = (($public_batch) ? 'application/magic-envelope+xml' : 'application/json');
2951 $postResult = DI::httpClient()->post($dest_url . '/', $envelope, ['Content-Type' => $content_type]);
2952 $return_code = $postResult->getReturnCode();
2954 Logger::notice('test_mode');
2958 if (!empty($contact['gsid']) && (empty($return_code) || $postResult->isTimeout())) {
2959 GServer::setFailureById($contact['gsid']);
2960 } elseif (!empty($contact['gsid']) && ($return_code >= 200) && ($return_code <= 299)) {
2961 GServer::setReachableById($contact['gsid'], Protocol::DIASPORA);
2964 Logger::notice('transmit: ' . $logid . '-' . $guid . ' to ' . $dest_url . ' returns: ' . $return_code);
2966 return $return_code ? $return_code : -1;
2971 * Build the post xml
2973 * @param string $type The message type
2974 * @param array $message The message data
2976 * @return string The post XML
2977 * @throws \Exception
2979 public static function buildPostXml(string $type, array $message): string
2981 return XML::fromArray([$type => $message]);
2985 * Builds and transmit messages
2987 * @param array $owner the array of the item owner
2988 * @param array $contact Target of the communication
2989 * @param string $type The message type
2990 * @param array $message The message data
2991 * @param bool $public_batch Is it a public post?
2992 * @param string $guid message guid
2994 * @return int Result of the transmission
2995 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2996 * @throws \ImagickException
2998 private static function buildAndTransmit(array $owner, array $contact, string $type, array $message, bool $public_batch = false, string $guid = '')
3000 $msg = self::buildPostXml($type, $message);
3002 // Fallback if the private key wasn't transmitted in the expected field
3003 if (empty($owner['uprvkey'])) {
3004 $owner['uprvkey'] = $owner['prvkey'];
3007 // When sending content to Friendica contacts using the Diaspora protocol
3008 // we have to fetch the public key from the diaspora-contact.
3009 // This is due to the fact that legacy DFRN had unique keys for every contact.
3010 $pubkey = $contact['pubkey'];
3011 if (!empty($contact['addr'])) {
3013 $pubkey = DI::dsprContact()->getByAddr(WebFingerUri::fromString($contact['addr']))->pubKey;
3014 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
3018 // The "addr" field should always be filled.
3019 // If this isn't the case, it will raise a notice some lines later.
3020 // And in the log we will see where it came from, and we can handle it there.
3021 Logger::notice('Empty addr', ['contact' => $contact ?? [], 'callstack' => System::callstack(20)]);
3024 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $pubkey ?? '', $public_batch);
3026 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3028 Logger::info('Transmitted message', ['owner' => $owner['uid'], 'target' => $contact['addr'], 'type' => $type, 'guid' => $guid, 'result' => $return_code]);
3030 return $return_code;
3034 * sends a participation (Used to get all further updates)
3036 * @param array $contact Target of the communication
3037 * @param array $item Item array
3039 * @return int The result of the transmission
3040 * @throws \Exception
3042 private static function sendParticipation(array $contact, array $item): int
3044 // Don't send notifications for private postings
3045 if ($item['private'] == Item::PRIVATE) {
3049 $cachekey = 'diaspora:sendParticipation:' . $item['guid'];
3051 $result = DI::cache()->get($cachekey);
3052 if (!is_null($result)) {
3056 // Fetch some user id to have a valid handle to transmit the participation.
3057 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3058 // If the item belongs to a user, we take this user id.
3059 if ($item['uid'] == 0) {
3060 // @todo Possibly use an administrator account?
3061 $condition = ['verified' => true, 'blocked' => false,
3062 'account_removed' => false, 'account_expired' => false, 'account-type' => User::ACCOUNT_TYPE_PERSON];
3063 $first_user = DBA::selectFirst('user', ['uid'], $condition, ['order' => ['uid']]);
3064 $owner = User::getOwnerDataById($first_user['uid']);
3066 $owner = User::getOwnerDataById($item['uid']);
3069 $author_handle = self::myHandle($owner);
3072 'author' => $author_handle,
3073 'guid' => System::createUUID(),
3074 'parent_type' => 'Post',
3075 'parent_guid' => $item['guid']
3078 Logger::info('Send participation for ' . $item['guid'] . ' by ' . $author_handle);
3080 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3081 DI::cache()->set($cachekey, $item['guid'], Duration::QUARTER_HOUR);
3083 return self::buildAndTransmit($owner, $contact, 'participation', $message);
3087 * sends an account migration
3089 * @param array $owner the array of the item owner
3090 * @param array $contact Target of the communication
3091 * @param int $uid User ID
3093 * @return int The result of the transmission
3094 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3095 * @throws \ImagickException
3097 public static function sendAccountMigration(array $owner, array $contact, int $uid): int
3099 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3100 $profile = self::createProfileData($uid);
3102 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3103 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
3106 'author' => $old_handle,
3107 'profile' => $profile,
3108 'signature' => $signature
3111 Logger::info('Send account migration', ['msg' => $message]);
3113 return self::buildAndTransmit($owner, $contact, 'account_migration', $message);
3117 * Sends a "share" message
3119 * @param array $owner the array of the item owner
3120 * @param array $contact Target of the communication
3122 * @return int The result of the transmission
3123 * @throws \Exception
3125 public static function sendShare(array $owner, array $contact): int
3128 * @todo support the different possible combinations of "following" and "sharing"
3129 * Currently, Diaspora only interprets the "sharing" field
3131 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3135 switch ($contact["rel"]) {
3136 case Contact::FRIEND:
3140 case Contact::SHARING:
3144 case Contact::FOLLOWER:
3151 'author' => self::myHandle($owner),
3152 'recipient' => $contact['addr'],
3153 'following' => 'true',
3157 Logger::info('Send share', ['msg' => $message]);
3159 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3163 * sends an "unshare"
3165 * @param array $owner the array of the item owner
3166 * @param array $contact Target of the communication
3168 * @return int The result of the transmission
3169 * @throws \Exception
3171 public static function sendUnshare(array $owner, array $contact): int
3174 'author' => self::myHandle($owner),
3175 'recipient' => $contact['addr'],
3176 'following' => 'false',
3177 'sharing' => 'false'
3180 Logger::info('Send unshare', ['msg' => $message]);
3182 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3186 * Fetch reshare details
3188 * @param array $item The message body that is to be check
3190 * @return array Reshare details (empty if the item is no reshare)
3191 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3192 * @throws \ImagickException
3194 public static function getReshareDetails(array $item): array
3196 $reshared = DI::contentItem()->getSharedPost($item, ['guid', 'network', 'author-addr']);
3197 if (empty($reshared)) {
3201 // Skip if it isn't a pure repeated messages or not a real reshare
3202 if (!empty($reshared['comment']) || !in_array($reshared['post']['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
3207 'root_handle' => strtolower($reshared['post']['author-addr']),
3208 'root_guid' => $reshared['post']['guid'],
3213 * Create an event array
3215 * @param integer $event_id The id of the event
3217 * @return array with event data
3218 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3220 private static function buildEvent(string $event_id): array
3222 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
3223 if (!DBA::isResult($event)) {
3229 $owner = User::getOwnerDataById($event['uid']);
3234 $eventdata['author'] = self::myHandle($owner);
3236 if ($event['guid']) {
3237 $eventdata['guid'] = $event['guid'];
3240 $mask = DateTimeFormat::ATOM;
3242 /// @todo - establish "all day" events in Friendica
3243 $eventdata['all_day'] = 'false';
3245 $eventdata['timezone'] = 'UTC';
3247 if ($event['start']) {
3248 $eventdata['start'] = DateTimeFormat::utc($event['start'], $mask);
3250 if ($event['finish'] && !$event['nofinish']) {
3251 $eventdata['end'] = DateTimeFormat::utc($event['finish'], $mask);
3253 if ($event['summary']) {
3254 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3256 if ($event['desc']) {
3257 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3259 if ($event['location']) {
3260 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3261 $coord = Map::getCoordinates($event['location']);
3264 $location['address'] = html_entity_decode(BBCode::toMarkdown($event['location']));
3265 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3266 $location['lat'] = $coord['lat'];
3267 $location['lng'] = $coord['lon'];
3269 $location['lat'] = 0;
3270 $location['lng'] = 0;
3272 $eventdata['location'] = $location;
3279 * Create a post (status message or reshare)
3281 * @param array $item The item that will be exported
3282 * @param array $owner the array of the item owner
3285 * 'type' -> Message type ("status_message" or "reshare")
3286 * 'message' -> Array of XML elements of the status
3287 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3288 * @throws \ImagickException
3290 public static function buildStatus(array $item, array $owner)
3292 $cachekey = 'diaspora:buildStatus:' . $item['guid'];
3294 $result = DI::cache()->get($cachekey);
3295 if (!is_null($result)) {
3299 $myaddr = self::myHandle($owner);
3301 $public = ($item['private'] == Item::PRIVATE ? 'false' : 'true');
3302 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3303 $edited = DateTimeFormat::utc($item['edited'] ?? $item['created'], DateTimeFormat::ATOM);
3305 // Detect a share element and do a reshare
3306 if (($item['private'] != Item::PRIVATE) && ($ret = self::getReshareDetails($item))) {
3308 'author' => $myaddr,
3309 'guid' => $item['guid'],
3310 'created_at' => $created,
3311 'root_author' => $ret['root_handle'],
3312 'root_guid' => $ret['root_guid'],
3313 'provider_display_name' => $item['app'],
3319 $native_photos = DI::config()->get('diaspora', 'native_photos');
3320 if ($native_photos) {
3321 $item['body'] = Post\Media::removeFromEndOfBody($item['body']);
3322 $attach_media = [Post\Media::AUDIO, Post\Media::VIDEO];
3324 $attach_media = [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO];
3327 $title = $item['title'];
3328 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item), $attach_media);
3330 // Fetch the title from an attached link - if there is one
3331 if (empty($item['title']) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3332 $page_data = BBCode::getAttachmentData($item['body']);
3333 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3334 $title = $page_data['title'];
3338 // convert to markdown
3339 $body = html_entity_decode(BBCode::toMarkdown($body));
3342 if (strlen($title)) {
3343 $body = '### ' . html_entity_decode($title) . "\n\n" . $body;
3346 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT]);
3347 if (!empty($attachments)) {
3348 $body .= "\n[hr]\n";
3349 foreach ($attachments as $attachment) {
3350 $body .= "[" . $attachment['description'] . "](" . $attachment['url'] . ")\n";
3356 if ($item['location'] != '')
3357 $location['address'] = $item['location'];
3359 if ($item['coord'] != '') {
3360 $coord = explode(' ', $item['coord']);
3361 $location['lat'] = $coord[0];
3362 $location['lng'] = $coord[1];
3366 'author' => $myaddr,
3367 'guid' => $item['guid'],
3368 'created_at' => $created,
3369 'edited_at' => $edited,
3370 'public' => $public,
3372 'provider_display_name' => $item['app'],
3373 'location' => $location
3376 if ($native_photos) {
3377 $message = self::addPhotos($item, $message);
3380 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3381 if (!isset($location['lat']) || !isset($location['lng'])) {
3382 unset($message['location']);
3385 if ($item['event-id'] > 0) {
3386 $event = self::buildEvent($item['event-id']);
3387 if (count($event)) {
3388 $message['event'] = $event;
3390 if (!empty($event['location']['address']) &&
3391 !empty($event['location']['lat']) &&
3392 !empty($event['location']['lng'])) {
3393 $message['location'] = $event['location'];
3396 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3397 // $message['text'] = '';
3401 $type = 'status_message';
3406 'message' => $message
3409 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3415 * Add photo elements to the message array
3417 * @param array $item
3418 * @param array $message
3421 private static function addPhotos(array $item, array $message): array
3423 $medias = Post\Media::getByURIId($item['uri-id'], [Post\Media::IMAGE]);
3424 $public = ($item['private'] == Item::PRIVATE ? 'false' : 'true');
3427 foreach ($medias as $media) {
3428 if (Item::containsLink($item['body'], $media['preview'] ?? $media['url'], $media['type'])) {
3432 $name = basename($media['url']);
3433 $path = str_replace($name, '', $media['url']);
3435 $message[++$counter . ':photo'] = [
3436 'guid' => Item::guid(['uri' => $media['url']], false),
3437 'author' => $item['author-addr'],
3438 'public' => $public,
3439 'created_at' => $item['created'],
3440 'remote_photo_path' => $path,
3441 'remote_photo_name' => $name,
3442 'status_message_guid' => $item['guid'],
3443 'height' => $media['height'],
3444 'width' => $media['width'],
3445 'text' => $media['description'],
3452 private static function prependParentAuthorMention(string $body, string $profile_url): string
3454 $profile = Contact::getByURL($profile_url, false, ['addr', 'name']);
3455 if (!empty($profile['addr'])
3456 && !strstr($body, $profile['addr'])
3457 && !strstr($body, $profile_url)
3459 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3468 * @param array $item The item that will be exported
3469 * @param array $owner the array of the item owner
3470 * @param array $contact Target of the communication
3471 * @param bool $public_batch Is it a public post?
3473 * @return int The result of the transmission
3474 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3475 * @throws \ImagickException
3477 public static function sendStatus(array $item, array $owner, array $contact, bool $public_batch = false): int
3479 $status = self::buildStatus($item, $owner);
3481 return self::buildAndTransmit($owner, $contact, $status['type'], $status['message'], $public_batch, $item['guid']);
3485 * Creates a "like" object
3487 * @param array $item The item that will be exported
3488 * @param array $owner the array of the item owner
3490 * @return array|bool The data for a "like" or false on error
3491 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3493 private static function constructLike(array $item, array $owner)
3495 $parent = Post::selectFirst(['guid', 'uri', 'thr-parent'], ['uri' => $item['thr-parent']]);
3496 if (!DBA::isResult($parent)) {
3500 $target_type = ($parent['uri'] === $parent['thr-parent'] ? 'Post' : 'Comment');
3502 if ($item['verb'] === Activity::LIKE) {
3504 } elseif ($item['verb'] === Activity::DISLIKE) {
3505 $positive = 'false';
3509 'author' => self::myHandle($owner),
3510 'guid' => $item['guid'],
3511 'parent_guid' => $parent['guid'],
3512 'parent_type' => $target_type,
3513 'positive' => $positive,
3514 'author_signature' => '',
3519 * Creates an "EventParticipation" object
3521 * @param array $item The item that will be exported
3522 * @param array $owner the array of the item owner
3524 * @return array|bool The data for an "EventParticipation" or false on error
3525 * @throws \Exception
3527 private static function constructAttend(array $item, array $owner)
3529 $parent = Post::selectFirst(['guid'], ['uri' => $item['thr-parent']]);
3530 if (!DBA::isResult($parent)) {
3534 switch ($item['verb']) {
3535 case Activity::ATTEND:
3536 $attend_answer = 'accepted';
3538 case Activity::ATTENDNO:
3539 $attend_answer = 'declined';
3541 case Activity::ATTENDMAYBE:
3542 $attend_answer = 'tentative';
3545 Logger::warning('Unknown verb ' . $item['verb'] . ' in item ' . $item['guid']);
3550 'author' => self::myHandle($owner),
3551 'guid' => $item['guid'],
3552 'parent_guid' => $parent['guid'],
3553 'status' => $attend_answer,
3554 'author_signature' => ''
3559 * Creates the object for a comment
3561 * @param array $item The item that will be exported
3562 * @param array $owner the array of the item owner
3564 * @return array|false The data for a comment
3565 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3567 private static function constructComment(array $item, array $owner)
3569 $cachekey = 'diaspora:constructComment:' . $item['guid'];
3571 $result = DI::cache()->get($cachekey);
3572 if (!is_null($result)) {
3576 $toplevel_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3577 if (!DBA::isResult($toplevel_item)) {
3578 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3582 $thread_parent_item = $toplevel_item;
3583 if ($item['thr-parent'] != $item['parent-uri']) {
3584 $thread_parent_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3587 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
3589 // The replied to autor mention is prepended for clarity if:
3590 // - Item replied isn't yours
3591 // - Item is public or explicit mentions are disabled
3592 // - Implicit mentions are enabled
3594 $item['author-id'] != $thread_parent_item['author-id']
3595 && ($thread_parent_item['gravity'] != Item::GRAVITY_PARENT)
3596 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3597 && !DI::config()->get('system', 'disable_implicit_mentions')
3599 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3602 $text = html_entity_decode(BBCode::toMarkdown($body));
3603 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3604 $edited = DateTimeFormat::utc($item['edited'], DateTimeFormat::ATOM);
3607 'author' => self::myHandle($owner),
3608 'guid' => $item['guid'],
3609 'created_at' => $created,
3610 'edited_at' => $edited,
3611 'parent_guid' => $toplevel_item['guid'],
3613 'author_signature' => '',
3616 // Send the thread parent guid only if it is a threaded comment
3617 if ($item['thr-parent'] != $item['parent-uri']) {
3618 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3621 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3627 * Send a like or a comment
3629 * @param array $item The item that will be exported
3630 * @param array $owner the array of the item owner
3631 * @param array $contact Target of the communication
3632 * @param bool $public_batch Is it a public post?
3634 * @return int The result of the transmission
3635 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3636 * @throws \ImagickException
3638 public static function sendFollowup(array $item, array $owner, array $contact, bool $public_batch = false): int
3640 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3641 $message = self::constructAttend($item, $owner);
3642 $type = 'event_participation';
3643 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3644 $message = self::constructLike($item, $owner);
3646 } elseif (!in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
3647 $message = self::constructComment($item, $owner);
3651 if (empty($message)) {
3655 $message['author_signature'] = self::signature($owner, $message);
3657 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3661 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3663 * @param array $item The item that will be exported
3664 * @param array $owner the array of the item owner
3665 * @param array $contact Target of the communication
3666 * @param bool $public_batch Is it a public post?
3668 * @return int The result of the transmission
3669 * @throws \Exception
3671 public static function sendRelay(array $item, array $owner, array $contact, bool $public_batch = false): int
3673 if ($item['deleted']) {
3674 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3675 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3681 Logger::info('Got relayable data ' . $type . ' for item ' . $item['guid'] . ' (' . $item['id'] . ')');
3683 $msg = json_decode($item['signed_text'] ?? '', true);
3686 if (is_array($msg)) {
3687 foreach ($msg as $field => $data) {
3688 if (!$item['deleted']) {
3689 if ($field == 'diaspora_handle') {
3692 if ($field == 'target_type') {
3693 $field = 'parent_type';
3697 $message[$field] = $data;
3700 Logger::info('Signature text for item ' . $item['guid'] . ' (' . $item['id'] . ') could not be extracted: ' . $item['signed_text']);
3703 $message['parent_author_signature'] = self::signature($owner, $message);
3705 Logger::info('Relayed data', ['msg' => $message]);
3707 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3711 * Sends a retraction (deletion) of a message, like or comment
3713 * @param array $item The item that will be exported
3714 * @param array $owner the array of the item owner
3715 * @param array $contact Target of the communication
3716 * @param bool $public_batch Is it a public post?
3717 * @param bool $relay Is the retraction transmitted from a relay?
3719 * @return int The result of the transmission
3720 * @throws \Exception
3722 public static function sendRetraction(array $item, array $owner, array $contact, bool $public_batch = false, bool $relay = false): int
3724 $itemaddr = strtolower($item['author-addr']);
3726 $msg_type = 'retraction';
3728 if ($item['gravity'] == Item::GRAVITY_PARENT) {
3729 $target_type = 'Post';
3730 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3731 $target_type = 'Like';
3733 $target_type = 'Comment';
3737 'author' => $itemaddr,
3738 'target_guid' => $item['guid'],
3739 'target_type' => $target_type
3742 Logger::info('Got message', ['msg' => $message]);
3744 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item['guid']);
3750 * @param array $item The item that will be exported
3751 * @param array $owner The owner
3752 * @param array $contact Target of the communication
3754 * @return int The result of the transmission
3755 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3756 * @throws \ImagickException
3758 public static function sendMail(array $item, array $owner, array $contact): int
3760 $myaddr = self::myHandle($owner);
3762 $cnv = DBA::selectFirst('conv', [], ['id' => $item['convid'], 'uid' => $item['uid']]);
3763 if (!DBA::isResult($cnv)) {
3764 Logger::notice('Conversation not found.');
3768 $body = BBCode::toMarkdown($item['body']);
3769 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3772 'author' => $myaddr,
3773 'guid' => $item['guid'],
3774 'conversation_guid' => $cnv['guid'],
3776 'created_at' => $created,
3779 if ($item['reply']) {
3784 'author' => $cnv['creator'],
3785 'guid' => $cnv['guid'],
3786 'subject' => $cnv['subject'],
3787 'created_at' => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3788 'participants' => $cnv['recips'],
3792 $type = 'conversation';
3795 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item['guid']);
3799 * Split a name into first name and last name
3801 * @param string $name The name
3803 * @return array The array with "first" and "last"
3805 public static function splitName(string $name): array
3807 $name = trim($name);
3809 // Is the name longer than 64 characters? Then cut the rest of it.
3810 if (strlen($name) > 64) {
3811 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3812 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3814 $name = substr($name, 0, 64);
3818 // Take the first word as first name
3819 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3820 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3821 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3822 return ['first' => $first, 'last' => $last];
3825 // Take the last word as last name
3826 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3827 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3829 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3830 return ['first' => $first, 'last' => $last];
3833 // Take the first 32 characters if there is no space in the first 32 characters
3834 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3835 $first = substr($name, 0, 32);
3836 $last = substr($name, 32);
3837 return ['first' => $first, 'last' => $last];
3840 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3841 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3843 // Check if the last name is longer than 32 characters
3844 if (strlen($last) > 32) {
3845 if (strpos($last, ' ') <= 32) {
3846 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
3848 $last = substr($last, 0, 32);
3852 return ['first' => $first, 'last' => $last];
3856 * Create profile data
3858 * @param int $uid The user id
3860 * @return array The profile data
3861 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3863 private static function createProfileData(int $uid): array
3865 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
3867 if (!DBA::isResult($profile)) {
3871 $split_name = self::splitName($profile['name']);
3874 'author' => $profile['addr'],
3875 'first_name' => $split_name['first'],
3876 'last_name' => $split_name['last'],
3877 'image_url' => DI::baseUrl() . '/photo/custom/300/' . $profile['uid'] . '.jpg',
3878 'image_url_medium' => DI::baseUrl() . '/photo/custom/100/' . $profile['uid'] . '.jpg',
3879 'image_url_small' => DI::baseUrl() . '/photo/custom/50/' . $profile['uid'] . '.jpg',
3880 'searchable' => ($profile['net-publish'] ? 'true' : 'false'),
3884 'tag_string' => null,
3888 if ($data['searchable'] === 'true') {
3889 $data['birthday'] = '';
3891 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
3892 [$year, $month, $day] = sscanf($profile['dob'], '%4d-%2d-%2d');
3896 $data['birthday'] = DateTimeFormat::utc($year . '-' . $month . '-' . $day, 'Y-m-d');
3899 $data['about'] = BBCode::toMarkdown($profile['about'] ?? '');
3901 $data['location'] = $profile['location'];
3902 $data['tag_string'] = '';
3904 if ($profile['pub_keywords']) {
3905 $kw = str_replace(',', ' ', $profile['pub_keywords']);
3906 $kw = str_replace(' ', ' ', $kw);
3907 $arr = explode(' ', $kw);
3909 for ($x = 0; $x < 5; $x ++) {
3910 if (!empty($arr[$x])) {
3911 $data['tag_string'] .= '#'. trim($arr[$x]) .' ';
3916 $data['tag_string'] = trim($data['tag_string']);
3923 * Sends profile data
3925 * @param int $uid The user id
3926 * @param array $recipients optional, default empty array
3929 * @throws \Exception
3931 public static function sendProfile(int $uid, array $recipients = [])
3934 Logger::warning('Parameter "uid" is empty');
3938 $owner = User::getOwnerDataById($uid);
3939 if (empty($owner)) {
3940 Logger::warning('Cannot fetch User record', ['uid' => $uid]);
3944 if (empty($recipients)) {
3945 Logger::debug('No recipients provided, fetching for user', ['uid' => $uid]);
3946 $recipients = DBA::selectToArray('contact', [], ['network' => Protocol::DIASPORA, 'uid' => $uid, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
3949 if (empty($recipients)) {
3950 Logger::warning('Cannot fetch recipients', ['uid' => $uid]);
3954 $message = self::createProfileData($uid);
3956 // @todo Split this into single worker jobs
3957 foreach ($recipients as $recipient) {
3958 Logger::info('Send updated profile data for user ' . $uid . ' to contact ' . $recipient['id']);
3959 self::buildAndTransmit($owner, $recipient, 'profile', $message);
3964 * Creates the signature for likes that are created on our system
3966 * @param integer $uid The user of that comment
3967 * @param array $item Item array
3969 * @return array|bool Signed content or false on error
3970 * @throws \Exception
3972 public static function createLikeSignature(int $uid, array $item)
3974 $owner = User::getOwnerDataById($uid);
3975 if (empty($owner)) {
3976 Logger::info('No owner post, so not storing signature', ['uid' => $uid]);
3980 if (!in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3981 Logger::warning('Item is neither a like nor a dislike', ['uid' => $uid, 'item[verb]' => $item['verb']]);;
3985 $message = self::constructLike($item, $owner);
3986 if ($message === false) {
3990 $message['author_signature'] = self::signature($owner, $message);
3996 * Creates the signature for Comments that are created on our system
3998 * @param array $item Item array
4000 * @return array|bool Signed content or false on error
4001 * @throws \Exception
4003 public static function createCommentSignature(array $item)
4006 if (!empty($item['author-link'])) {
4007 $url = $item['author-link'];
4009 $contact = Contact::getById($item['author-id'], ['url']);
4010 if (empty($contact['url'])) {
4011 Logger::warning('Author Contact not found', ['author-id' => $item['author-id']]);
4014 $url = $contact['url'];
4017 $uid = User::getIdForURL($url);
4019 Logger::info('No owner post, so not storing signature', ['url' => $contact['url'] ?? 'No contact loaded']);
4023 $owner = User::getOwnerDataById($uid);
4024 if (empty($owner)) {
4025 Logger::info('No owner post, so not storing signature');
4029 // This is only needed for the automated tests
4030 if (empty($owner['uprvkey'])) {
4034 if (!self::parentSupportDiaspora($item['thr-parent-id'])) {
4035 Logger::info('One of the parents does not support Diaspora. A signature will not be created.', ['uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
4039 $message = self::constructComment($item, $owner);
4040 if ($message === false) {
4044 $message['author_signature'] = self::signature($owner, $message);
4050 * Check if the parent and their parents support Diaspora
4052 * @param integer $parent_id
4054 * @throws InternalServerErrorException
4055 * @throws \ImagickException
4057 private static function parentSupportDiaspora(int $parent_id): bool
4059 $parent_post = Post::selectFirstPost(['gravity', 'signed_text', 'author-link', 'thr-parent-id'], ['uri-id' => $parent_id]);
4060 if (empty($parent_post['thr-parent-id'])) {
4061 Logger::warning('Parent post does not exist.', ['parent-id' => $parent_id]);
4065 if (!self::isSupportedByContactUrl($parent_post['author-link'])) {
4066 Logger::info('Parent author is no Diaspora contact.', ['parent-id' => $parent_id]);
4070 if (($parent_post['gravity'] == Item::GRAVITY_COMMENT) && empty($parent_post['signed_text'])) {
4071 Logger::info('Parent comment has got no Diaspora signature.', ['parent-id' => $parent_id]);
4075 if ($parent_post['gravity'] == Item::GRAVITY_COMMENT) {
4076 return self::parentSupportDiaspora($parent_post['thr-parent-id']);
4082 public static function performReshare(int $UriId, int $uid): int
4084 $owner = User::getOwnerDataById($uid);
4085 $author = Contact::getPublicIdByUserId($uid);
4089 'verb' => Activity::POST,
4090 'contact-id' => $owner['id'],
4091 'author-id' => $author,
4092 'owner-id' => $author,
4094 'quote-uri-id' => $UriId,
4095 'allow_cid' => $owner['allow_cid'] ?? '',
4096 'allow_gid' => $owner['allow_gid']?? '',
4097 'deny_cid' => $owner['deny_cid'] ?? '',
4098 'deny_gid' => $owner['deny_gid'] ?? '',
4101 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
4102 $item['private'] = Item::PRIVATE;
4103 } elseif (DI::pConfig()->get($uid, 'system', 'unlisted')) {
4104 $item['private'] = Item::UNLISTED;
4106 $item['private'] = Item::PUBLIC;
4109 // Don't trigger the addons
4110 $item['api_source'] = false;
4112 return Item::insert($item, true);