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(
87 ['author-id', 'author-link', 'parent-author-link', 'parent-guid', 'guid'],
88 ['parent' => $item['parent'], 'gravity' => [Item::GRAVITY_COMMENT, Item::GRAVITY_ACTIVITY]]
90 while ($item = Post::fetch($items)) {
91 $contact = DBA::selectFirst(
93 ['id', 'url', 'name', 'protocol', 'batch', 'network'],
94 ['id' => $item['author-id']]
97 !DBA::isResult($contact) || empty($contact['batch']) ||
98 ($contact['network'] != Protocol::DIASPORA) ||
99 Strings::compareLink($item['parent-author-link'], $item['author-link'])
105 foreach ($contacts as $entry) {
106 if ($entry['batch'] == $contact['batch']) {
112 Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]);
113 $contacts[] = $contact;
122 * verify the envelope and return the verified data
124 * @param string $envelope The magic envelope
126 * @return string|bool verified data or false on error
127 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
128 * @throws \ImagickException
130 private static function verifyMagicEnvelope(string $envelope)
132 $basedom = XML::parseString($envelope, true);
134 if (!is_object($basedom)) {
135 Logger::notice('Envelope is no XML file');
139 $children = $basedom->children(ActivityNamespace::SALMON_ME);
141 if (sizeof($children) == 0) {
142 Logger::notice('XML has no children');
148 $data = Strings::base64UrlDecode($children->data);
149 $type = $children->data->attributes()->type[0];
151 $encoding = $children->encoding;
153 $alg = $children->alg;
155 $sig = Strings::base64UrlDecode($children->sig);
156 $key_id = $children->sig->attributes()->key_id[0];
158 $handle = Strings::base64UrlDecode($key_id);
161 $b64url_data = Strings::base64UrlEncode($data);
162 $msg = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
164 $signable_data = $msg . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
167 Logger::notice('No author could be decoded. Discarding. Message: ' . $envelope);
172 $key = self::key(WebFingerUri::fromString($handle));
174 throw new \InvalidArgumentException();
176 } catch (\InvalidArgumentException $e) {
177 Logger::notice("Couldn't get a key for handle " . $handle . ". Discarding.");
181 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
183 Logger::notice('Message from ' . $handle . ' did not verify. Discarding.');
191 * encrypts data via AES
193 * @param string $key The AES key
194 * @param string $iv The IV (is used for CBC encoding)
195 * @param string $data The data that is to be encrypted
197 * @return string encrypted data
199 private static function aesEncrypt(string $key, string $iv, string $data): string
201 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
205 * decrypts data via AES
207 * @param string $key The AES key
208 * @param string $iv The IV (is used for CBC encoding)
209 * @param string $encrypted The encrypted data
211 * @return string decrypted data
213 private static function aesDecrypt(string $key, string $iv, string $encrypted): string
215 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
219 * Decodes incoming Diaspora message in the new format. This method returns false on an error.
221 * @param string $raw raw post message
222 * @param string $privKey The private key of the importer
223 * @param boolean $no_exit Don't do an http exit on error
226 * 'message' -> decoded Diaspora XML message
227 * 'author' -> author diaspora handle
228 * 'key' -> author public key (converted to pkcs#8)
229 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
230 * @throws \ImagickException
232 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
234 $data = json_decode($raw);
236 // Is it a private post? Then decrypt the outer Salmon
237 if (is_object($data)) {
239 if (!isset($data->aes_key) || !isset($data->encrypted_magic_envelope)) {
240 Logger::info('Missing keys "aes_key" and/or "encrypted_magic_envelope"', ['data' => $data]);
241 throw new \RuntimeException('Missing keys "aes_key" and/or "encrypted_magic_envelope"');
244 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
245 $ciphertext = base64_decode($data->encrypted_magic_envelope);
247 $outer_key_bundle = '';
248 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
249 $j_outer_key_bundle = json_decode($outer_key_bundle);
251 if (!is_object($j_outer_key_bundle)) {
252 Logger::info('Unable to decode outer key bundle', ['outer_key_bundle' => $outer_key_bundle]);
253 throw new \RuntimeException('Unable to decode outer key bundle');
256 if (!isset($j_outer_key_bundle->iv) || !isset($j_outer_key_bundle->key)) {
257 Logger::info('Missing keys "iv" and/or "key" from outer Salmon', ['j_outer_key_bundle' => $j_outer_key_bundle]);
258 throw new \RuntimeException('Missing keys "iv" and/or "key" from outer Salmon');
261 $outer_iv = base64_decode($j_outer_key_bundle->iv);
262 $outer_key = base64_decode($j_outer_key_bundle->key);
264 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
265 } catch (\Throwable $e) {
266 Logger::notice('Outer Salmon did not verify. Discarding.');
270 throw new \Friendica\Network\HTTPException\BadRequestException();
277 $basedom = XML::parseString($xml, true);
279 if (!is_object($basedom)) {
280 Logger::notice('Received data does not seem to be an XML. Discarding. ' . $xml);
284 throw new \Friendica\Network\HTTPException\BadRequestException();
288 $base = $basedom->children(ActivityNamespace::SALMON_ME);
290 // Not sure if this cleaning is needed
291 $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
293 // Build the signed data
294 $type = $base->data[0]->attributes()->type[0];
295 $encoding = $base->encoding;
297 $signed_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
299 // This is the signature
300 $signature = Strings::base64UrlDecode($base->sig);
302 // Get the senders' public key
303 $key_id = $base->sig[0]->attributes()->key_id[0];
304 $author_addr = base64_decode($key_id);
305 if ($author_addr == '') {
306 Logger::notice('No author could be decoded. Discarding. Message: ' . $xml);
310 throw new \Friendica\Network\HTTPException\BadRequestException();
315 $author = WebFingerUri::fromString($author_addr);
316 $key = self::key($author);
318 throw new \InvalidArgumentException();
320 } catch (\InvalidArgumentException $e) {
321 Logger::notice("Couldn't get a key for handle " . $author_addr . ". Discarding.");
325 throw new \Friendica\Network\HTTPException\BadRequestException();
329 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
331 Logger::notice('Message did not verify. Discarding.');
335 throw new \Friendica\Network\HTTPException\BadRequestException();
340 'message' => (string)Strings::base64UrlDecode($base->data),
341 'author' => $author->getAddr(),
342 'key' => (string)$key
347 * Decodes incoming Diaspora message in the deprecated format
349 * @param string $xml urldecoded Diaspora salmon
350 * @param string $privKey The private key of the importer
353 * 'message' -> decoded Diaspora XML message
354 * 'author' -> author diaspora handle
355 * 'key' -> author public key (converted to pkcs#8)
356 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
357 * @throws \ImagickException
359 public static function decode(string $xml, string $privKey = '')
362 $basedom = XML::parseString($xml);
364 if (!is_object($basedom)) {
365 Logger::notice('XML is not parseable.');
368 $children = $basedom->children('https://joindiaspora.com/protocol');
370 $inner_aes_key = null;
373 if ($children->header) {
375 $idom = $children->header;
377 // This happens with posts from a relais
378 if (empty($privKey)) {
379 Logger::info('This is no private post in the old format');
383 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
385 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
386 $ciphertext = base64_decode($encrypted_header->ciphertext);
388 $outer_key_bundle = '';
389 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
391 $j_outer_key_bundle = json_decode($outer_key_bundle);
393 $outer_iv = base64_decode($j_outer_key_bundle->iv);
394 $outer_key = base64_decode($j_outer_key_bundle->key);
396 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
398 Logger::info('decrypted', ['data' => $decrypted]);
399 $idom = XML::parseString($decrypted);
401 $inner_iv = base64_decode($idom->iv);
402 $inner_aes_key = base64_decode($idom->aes_key);
406 $author = WebFingerUri::fromString($idom->author_id);
407 } catch (\Throwable $e) {
408 Logger::notice('Could not retrieve author URI.', ['idom' => $idom]);
409 throw new \Friendica\Network\HTTPException\BadRequestException();
412 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
414 // figure out where in the DOM tree our data is hiding
417 if ($dom->provenance->data) {
418 $base = $dom->provenance;
419 } elseif ($dom->env->data) {
421 } elseif ($dom->data) {
426 Logger::notice('unable to locate salmon data in xml');
427 throw new \Friendica\Network\HTTPException\BadRequestException();
431 // Stash the signature away for now. We have to find their key or it won't be good for anything.
432 $signature = Strings::base64UrlDecode($base->sig);
436 // strip whitespace so our data element will return to one big base64 blob
437 $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
440 // stash away some other stuff for later
442 $type = $base->data[0]->attributes()->type[0];
443 $keyhash = $base->sig[0]->attributes()->keyhash[0];
444 $encoding = $base->encoding;
448 $signed_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
452 $data = Strings::base64UrlDecode($data);
456 $inner_decrypted = $data;
458 // Decode the encrypted blob
459 $inner_encrypted = base64_decode($data);
460 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
463 // Once we have the author URI, go to the web and try to find their public key
464 // (first this will look it up locally if it is in the diaspora-contact cache)
465 // This will also convert diaspora public key from pkcs#1 to pkcs#8
466 Logger::info('Fetching key for ' . $author);
467 $key = self::key($author);
469 Logger::notice('Could not retrieve author key.');
470 throw new \Friendica\Network\HTTPException\BadRequestException();
473 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
476 Logger::notice('Message did not verify. Discarding.');
477 throw new \Friendica\Network\HTTPException\BadRequestException();
480 Logger::info('Message verified.');
483 'message' => $inner_decrypted,
484 'author' => $author->getAddr(),
491 * Dispatches public messages and find the fitting receivers
493 * @param array $msg The post that will be dispatched
494 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
496 * @return int|bool The message id of the generated message, "true" or "false" if there was an error
497 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
498 * @throws \ImagickException
500 public static function dispatchPublic(array $msg, int $direction)
502 $enabled = intval(DI::config()->get('system', 'diaspora_enabled'));
504 Logger::notice('Diaspora is disabled');
508 if (!($fields = self::validPosting($msg))) {
509 Logger::notice('Invalid posting', ['msg' => $msg]);
515 'page-flags' => User::PAGE_FLAGS_FREELOVE
517 $success = self::dispatch($importer, $msg, $fields, $direction);
523 * Dispatches the different message types to the different functions
525 * @param array $importer Array of the importer user
526 * @param array $msg The post that will be dispatched
527 * @param SimpleXMLElement $fields SimpleXML object that contains the message
528 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
530 * @return int|bool The message id of the generated message, "true" or "false" if there was an error
531 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
532 * @throws \ImagickException
534 public static function dispatch(array $importer, array $msg, SimpleXMLElement $fields = null, int $direction = self::PUSHED)
536 // The sender is the handle of the contact that sent the message.
537 // This will often be different with relayed messages (for example "like" and "comment")
538 $sender = WebFingerUri::fromString($msg['author']);
540 // This is only needed for private postings since this is already done for public ones before
541 if (is_null($fields)) {
543 if (!($fields = self::validPosting($msg))) {
544 Logger::notice('Invalid posting', ['msg' => $msg]);
551 $type = $fields->getName();
553 Logger::info('Received message', ['type' => $type, 'sender' => $sender->getAddr(), 'user' => $importer['uid']]);
556 case 'account_migration':
558 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
561 return self::receiveAccountMigration($importer, $fields);
563 case 'account_deletion':
564 return self::receiveAccountDeletion($fields);
567 return self::receiveComment($importer, $sender, $fields, $msg['message'], $direction);
571 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
574 return self::receiveContactRequest($importer, $fields);
578 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
581 return self::receiveConversation($importer, $msg, $fields);
584 return self::receiveLike($importer, $sender, $fields, $direction);
588 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
591 return self::receiveMessage($importer, $fields);
593 case 'participation':
595 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
598 return self::receiveParticipation($importer, $fields, $direction);
600 case 'photo': // Not implemented
601 return self::receivePhoto($importer, $fields);
603 case 'poll_participation': // Not implemented
604 return self::receivePollParticipation($importer, $fields);
608 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
611 return self::receiveProfile($importer, $fields);
614 return self::receiveReshare($importer, $fields, $msg['message'], $direction);
617 return self::receiveRetraction($importer, $sender, $fields);
619 case 'status_message':
620 return self::receiveStatusMessage($importer, $fields, $msg['message'], $direction);
623 Logger::notice('Unknown message type ' . $type);
629 * Checks if a posting is valid and fetches the data fields.
631 * This function does not only check the signature.
632 * It also does the conversion between the old and the new diaspora format.
634 * @param array $msg Array with the XML, the sender handle and the sender signature
636 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
637 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
638 * @throws \ImagickException
640 private static function validPosting(array $msg)
642 $data = XML::parseString($msg['message']);
644 if (!is_object($data)) {
645 Logger::info('No valid XML', ['message' => $msg['message']]);
649 // Is this the new or the old version?
650 if ($data->getName() == 'XML') {
652 foreach ($data->post->children() as $child) {
660 $type = $element->getName();
663 Logger::debug('Got message', ['type' => $type, 'message' => $msg['message']]);
665 // All retractions are handled identically from now on.
666 // In the new version there will only be "retraction".
667 if (in_array($type, ['signed_retraction', 'relayable_retraction']))
668 $type = 'retraction';
670 if ($type == 'request') {
674 $fields = new SimpleXMLElement('<' . $type . '/>');
677 $author_signature = null;
678 $parent_author_signature = null;
680 foreach ($element->children() as $fieldname => $entry) {
682 // Translation for the old XML structure
683 if ($fieldname == 'diaspora_handle') {
684 $fieldname = 'author';
686 if ($fieldname == 'participant_handles') {
687 $fieldname = 'participants';
689 if (in_array($type, ['like', 'participation'])) {
690 if ($fieldname == 'target_type') {
691 $fieldname = 'parent_type';
694 if ($fieldname == 'sender_handle') {
695 $fieldname = 'author';
697 if ($fieldname == 'recipient_handle') {
698 $fieldname = 'recipient';
700 if ($fieldname == 'root_diaspora_id') {
701 $fieldname = 'root_author';
703 if ($type == 'status_message') {
704 if ($fieldname == 'raw_message') {
708 if ($type == 'retraction') {
709 if ($fieldname == 'post_guid') {
710 $fieldname = 'target_guid';
712 if ($fieldname == 'type') {
713 $fieldname = 'target_type';
718 if (($fieldname == 'author_signature') && ($entry != '')) {
719 $author_signature = base64_decode($entry);
720 } elseif (($fieldname == 'parent_author_signature') && ($entry != '')) {
721 $parent_author_signature = base64_decode($entry);
722 } elseif (!in_array($fieldname, ['author_signature', 'parent_author_signature', 'target_author_signature'])) {
723 if ($signed_data != '') {
727 $signed_data .= $entry;
730 !in_array($fieldname, ['parent_author_signature', 'target_author_signature'])
731 || ($orig_type == 'relayable_retraction')
733 XML::copy($entry, $fields, $fieldname);
737 // This is something that shouldn't happen at all.
738 if (in_array($type, ['status_message', 'reshare', 'profile'])) {
739 if ($msg['author'] != $fields->author) {
740 Logger::notice('Message handle is not the same as envelope sender. Quitting this message.', ['author1' => $msg['author'], 'author2' => $fields->author]);
745 // Only some message types have signatures. So we quit here for the other types.
746 if (!in_array($type, ['comment', 'like'])) {
750 if (!isset($author_signature) && ($msg['author'] == $fields->author)) {
751 Logger::debug('No author signature, but the sender matches the author', ['type' => $type, 'msg-author' => $msg['author'], 'message' => $msg['message']]);
755 // No author_signature? This is a must, so we quit.
756 if (!isset($author_signature)) {
757 Logger::info('No author signature', ['type' => $type, 'msg-author' => $msg['author'], 'fields-author' => $fields->author, 'message' => $msg['message']]);
761 if (isset($parent_author_signature)) {
762 $key = self::key(WebFingerUri::fromString($msg['author']));
764 Logger::info('No key found for parent', ['author' => $msg['author']]);
768 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, 'sha256')) {
769 Logger::info('No valid parent author signature', ['author' => $msg['author'], 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $parent_author_signature]);
775 $key = self::key(WebFingerUri::fromString($fields->author));
777 throw new \InvalidArgumentException();
779 } catch (\Throwable $e) {
780 Logger::info('No key found', ['author' => $fields->author]);
784 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, 'sha256')) {
785 Logger::info('No valid author signature for author', ['author' => $fields->author, 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $author_signature]);
793 * Fetches the public key for a given handle
795 * @param WebFingerUri $uri The handle
797 * @return string The public key
798 * @throws InternalServerErrorException
799 * @throws \ImagickException
801 private static function key(WebFingerUri $uri): string
803 Logger::info('Fetching diaspora key', ['handle' => $uri->getAddr(), 'callstack' => System::callstack(20)]);
805 return DI::dsprContact()->getByAddr($uri)->pubKey;
806 } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) {
812 * Get a contact id for a given handle
814 * @param int $uid The user id
815 * @param WebFingerUri $uri
817 * @return array Contact data
818 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
819 * @throws \ImagickException
821 private static function contactByHandle(int $uid, WebFingerUri $uri): array
823 Contact::updateByUrlIfNeeded($uri->getAddr());
824 return Contact::getByURL($uri->getAddr(), null, [], $uid);
828 * Checks if the given contact url does support ActivityPub
830 * @param string $url profile url or WebFinger address
831 * @param boolean|null $update true = always update, false = never update, null = update when not found or outdated
833 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
834 * @throws \ImagickException
836 public static function isSupportedByContactUrl(string $url, ?bool $update = null): bool
838 $contact = Contact::getByURL($url, $update, ['uri-id', 'network']);
840 $supported = DI::dsprContact()->existsByUriId($contact['uri-id'] ?? 0);
842 if (!$supported && is_null($update) && ($contact['network'] == Protocol::DFRN)) {
843 $supported = self::isSupportedByContactUrl($url, true);
850 * Check if posting is allowed for this contact
852 * @param array $importer Array of the importer user
853 * @param array $contact The contact that is checked
854 * @param bool $is_comment Is the check for a comment?
856 * @return bool is the contact allowed to post?
858 private static function postAllow(array $importer, array $contact, bool $is_comment = false): bool
861 * Perhaps we were already sharing with this person. Now they're sharing with us.
862 * That makes us friends.
863 * Normally this should have handled by getting a request - but this could get lost
865 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
866 // It is not removed by now. Possibly the code is needed?
867 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
869 // array('rel' => Contact::FRIEND, 'writable' => true),
870 // array('id' => $contact["id"], 'uid' => $contact["uid"])
873 // $contact["rel"] = Contact::FRIEND;
874 // Logger::notice("defining user ".$contact["nick"]." as friend");
877 // Contact server is blocked
878 if (Network::isUrlBlocked($contact['url'])) {
880 // We don't seem to like that person
881 } elseif ($contact['blocked']) {
882 // Maybe blocked, don't accept.
884 // We are following this person?
885 } elseif (($contact['rel'] == Contact::SHARING) || ($contact['rel'] == Contact::FRIEND)) {
886 // Yes, then it is fine.
888 // Is the message a global user or a comment?
889 } elseif (($importer['uid'] == 0) || $is_comment) {
890 // Messages for the global users and comments are always accepted
898 * Fetches the contact id for a handle and checks if posting is allowed
900 * @param array $importer Array of the importer user
901 * @param WebFingerUri $contact_uri The checked contact
902 * @param bool $is_comment Is the check for a comment?
904 * @return array|bool The contact data or false on error
905 * @throws InternalServerErrorException
906 * @throws \ImagickException
908 private static function allowedContactByHandle(array $importer, WebFingerUri $contact_uri, bool $is_comment = false)
910 $contact = self::contactByHandle($importer['uid'], $contact_uri);
912 Logger::notice('A Contact for handle ' . $contact_uri . ' and user ' . $importer['uid'] . ' was not found');
913 // If a contact isn't found, we accept it anyway if it is a comment
914 if ($is_comment && ($importer['uid'] != 0)) {
915 return self::contactByHandle(0, $contact_uri);
916 } elseif ($is_comment) {
923 if (!self::postAllow($importer, $contact, $is_comment)) {
924 Logger::notice('The handle: ' . $contact_uri . ' is not allowed to post to user ' . $importer['uid']);
931 * Does the message already exists on the system?
933 * @param int $uid The user id
934 * @param string $guid The guid of the message
936 * @return int|bool message id if the message already was stored into the system - or false.
939 private static function messageExists(int $uid, string $guid)
941 $item = Post::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
942 if (DBA::isResult($item)) {
943 Logger::notice('Message ' . $guid . ' already exists for user ' . $uid);
951 * Checks for links to posts in a message
953 * @param array $item The item array
956 private static function fetchGuid(array $item)
958 preg_replace_callback(
959 "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism",
960 function ($match) use ($item) {
961 self::fetchGuidSub($match, $item);
966 preg_replace_callback(
967 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
968 function ($match) use ($item) {
969 self::fetchGuidSub($match, $item);
976 * Checks for relative /people/* links in an item body to match local
977 * contacts or prepends the remote host taken from the author link.
979 * @param string $body The item body to replace links from
980 * @param string $author_link The author link for missing local contact fallback
982 * @return string the replaced string
984 public static function replacePeopleGuid(string $body, string $author_link): string
986 $return = preg_replace_callback(
987 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
988 function ($match) use ($author_link) {
990 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
991 // 1 => '0123456789abcdef'
993 $handle = DI::dsprContact()->getUrlByGuid($match[1]);
996 $return = '@[url=' . $handle . ']' . $match[2] . '[/url]';
998 // No local match, restoring absolute remote URL from author scheme and host
999 $author_url = parse_url($author_link);
1000 $return = '[url=' . $author_url['scheme'] . '://' . $author_url['host'] . '/people/' . $match[1] . ']' . $match[2] . '[/url]';
1012 * sub function of "fetchGuid" which checks for links in messages
1014 * @param array $match array containing a link that has to be checked for a message link
1015 * @param array $item The item array
1017 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1018 * @throws \ImagickException
1020 private static function fetchGuidSub(array $match, array $item)
1022 if (!self::storeByGuid($match[1], $item['author-link'], true)) {
1023 self::storeByGuid($match[1], $item['owner-link'], true);
1028 * Fetches an item with a given guid from a given server
1030 * @param string $guid the message guid
1031 * @param string $server The server address
1032 * @param bool $force Forced fetch
1034 * @return int|bool the message id of the stored message or false
1035 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1036 * @throws \ImagickException
1038 private static function storeByGuid(string $guid, string $server, bool $force)
1040 $serverparts = parse_url($server);
1042 if (empty($serverparts['host']) || empty($serverparts['scheme'])) {
1046 $server = $serverparts['scheme'] . '://' . $serverparts['host'];
1048 Logger::info('Trying to fetch item ' . $guid . ' from ' . $server);
1050 $msg = self::message($guid, $server);
1056 Logger::info('Successfully fetched item ' . $guid . ' from ' . $server);
1058 // Now call the dispatcher
1059 return self::dispatchPublic($msg, $force ? self::FORCED_FETCH : self::FETCHED);
1063 * Fetches a message from a server
1065 * @param string $guid message guid
1066 * @param string $server The url of the server
1067 * @param int $level Endless loop prevention
1070 * 'message' => The message XML
1071 * 'author' => The author handle
1072 * 'key' => The public key of the author
1073 * @throws \Exception
1075 public static function message(string $guid, string $server, int $level = 0)
1081 // This will work for new Diaspora servers and Friendica servers from 3.5
1082 $source_url = $server . '/fetch/post/' . urlencode($guid);
1084 Logger::info('Fetch post from ' . $source_url);
1086 $envelope = DI::httpClient()->fetch($source_url, HttpClientAccept::MAGIC);
1088 Logger::info('Envelope was fetched.');
1089 $x = self::verifyMagicEnvelope($envelope);
1091 Logger::info('Envelope could not be verified.');
1093 Logger::info('Envelope was verified.');
1103 $source_xml = XML::parseString($x);
1105 if (!is_object($source_xml)) {
1109 if ($source_xml->post->reshare) {
1110 // Reshare of a reshare - old Diaspora version
1111 Logger::info('Message is a reshare');
1112 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1113 } elseif ($source_xml->getName() == 'reshare') {
1114 // Reshare of a reshare - new Diaspora version
1115 Logger::info('Message is a new reshare');
1116 return self::message($source_xml->root_guid, $server, ++$level);
1119 $author_handle = '';
1121 // Fetch the author - for the old and the new Diaspora version
1122 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1123 $author_handle = (string)$source_xml->post->status_message->diaspora_handle;
1124 } elseif ($source_xml->author && ($source_xml->getName() == 'status_message')) {
1125 $author_handle = (string)$source_xml->author;
1129 $author = WebFingerUri::fromString($author_handle);
1130 } catch (\InvalidArgumentException $e) {
1131 // If this isn't a "status_message" then quit
1132 Logger::info("Message doesn't seem to be a status message");
1138 'author' => $author->getAddr(),
1139 'key' => self::key($author)
1144 * Fetches an item with a given URL
1146 * @param string $url the message url
1147 * @param int $uid User id
1149 * @return int|bool the message id of the stored message or false
1150 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1151 * @throws \ImagickException
1153 public static function fetchByURL(string $url, int $uid = 0)
1155 // Check for Diaspora (and Friendica) typical paths
1156 if (!preg_match('=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i', $url, $matches)) {
1157 Logger::notice('Invalid url', ['url' => $url]);
1161 $guid = urldecode($matches[2]);
1163 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1164 if (DBA::isResult($item)) {
1165 Logger::info('Found', ['id' => $item['id']]);
1169 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1170 $ret = self::storeByGuid($guid, $matches[1], true);
1171 Logger::info('Result', ['ret' => $ret]);
1173 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1174 if (DBA::isResult($item)) {
1175 Logger::info('Found', ['id' => $item['id']]);
1178 Logger::notice('Not found', ['guid' => $guid, 'uid' => $uid]);
1184 * Fetches the item record of a given guid
1186 * @param int $uid The user id
1187 * @param string $guid message guid
1188 * @param WebFingerUri $author
1189 * @param array $contact The contact of the item owner
1191 * @return array|bool the item record or false on failure
1192 * @throws \Exception
1194 private static function parentItem(int $uid, string $guid, WebFingerUri $author, array $contact)
1197 'id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1198 'author-name', 'author-link', 'author-avatar', 'gravity',
1199 'owner-name', 'owner-link', 'owner-avatar'
1202 $condition = ['uid' => $uid, 'guid' => $guid];
1203 $item = Post::selectFirst($fields, $condition);
1205 if (!DBA::isResult($item)) {
1207 $result = self::storeByGuid($guid, DI::dsprContact()->getByAddr($author)->url, false);
1209 // We don't have an url for items that arrived at the public dispatcher
1210 if (!$result && !empty($contact['url'])) {
1211 $result = self::storeByGuid($guid, $contact['url'], false);
1215 Logger::info('Fetched missing item ' . $guid . ' - result: ' . $result);
1217 $item = Post::selectFirst($fields, $condition);
1219 } catch (HTTPException\NotFoundException $e) {
1220 Logger::notice('Unable to retrieve author details', ['author' => $author->getAddr()]);
1224 if (!DBA::isResult($item)) {
1225 Logger::notice('Parent item not found: parent: ' . $guid . ' - user: ' . $uid);
1228 Logger::info('Parent item found: parent: ' . $guid . ' - user: ' . $uid);
1234 * returns contact details for the given user
1236 * @param array $def_contact The default details if the contact isn't found
1237 * @param string $contact_url The url of the contact
1238 * @param int $uid The user id
1241 * 'cid' => contact id
1242 * 'network' => network type
1243 * @throws \Exception
1245 private static function authorContactByUrl(array $def_contact, string $contact_url, int $uid): array
1247 $condition = ['nurl' => Strings::normaliseLink($contact_url), 'uid' => $uid];
1248 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1249 if (DBA::isResult($contact)) {
1250 $cid = $contact['id'];
1251 $network = $contact['network'];
1253 $cid = $def_contact['id'];
1254 $network = Protocol::DIASPORA;
1259 'network' => $network
1264 * Is the profile a hubzilla profile?
1266 * @param string $url The profile link
1268 * @return bool is it a hubzilla server?
1270 private static function isHubzilla(string $url): bool
1272 return strstr($url, '/channel/');
1276 * Generate a post link with a given handle and message guid
1278 * @param string $addr The user handle
1279 * @param string $guid message guid
1280 * @param string $parent_guid optional parent guid
1282 * @return string the post link
1283 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1284 * @throws \ImagickException
1286 private static function plink(string $addr, string $guid, string $parent_guid = ''): string
1288 $contact = Contact::getByURL($addr);
1289 if (empty($contact)) {
1290 Logger::info('No contact data for address', ['addr' => $addr]);
1294 if (empty($contact['baseurl'])) {
1295 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1296 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1300 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1301 if (!empty($gserver['platform'])) {
1302 $platform = strtolower($gserver['platform']);
1303 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1306 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1307 if (self::isHubzilla($contact['url'])) {
1308 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1309 $platform = 'hubzilla';
1310 } elseif ($contact['network'] == Protocol::DFRN) {
1311 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1312 $platform = 'friendica';
1316 if ($platform == 'friendica') {
1317 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1320 if ($platform == 'hubzilla') {
1321 return $contact['baseurl'] . '/item/' . $guid;
1324 if ($platform == 'socialhome') {
1325 return $contact['baseurl'] . '/content/' . $guid;
1328 if ($platform != 'diaspora') {
1329 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1333 if ($parent_guid != '') {
1334 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1336 return $contact['baseurl'] . '/posts/' . $guid;
1341 * Receives account migration
1343 * @param array $importer Array of the importer user
1344 * @param SimpleXMLElement $data The message object
1346 * @return bool Success
1347 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1348 * @throws \ImagickException
1350 private static function receiveAccountMigration(array $importer, SimpleXMLElement $data): bool
1353 $old_author = WebFingerUri::fromString(XML::unescape($data->author));
1354 $new_author = WebFingerUri::fromString(XML::unescape($data->profile->author));
1355 } catch (\Throwable $e) {
1356 Logger::notice('Cannot find handles for sender and user', ['data' => $data]);
1360 $signature = XML::unescape($data->signature);
1362 $contact = self::contactByHandle($importer['uid'], $old_author);
1364 Logger::notice('Cannot find contact for sender: ' . $old_author . ' and user ' . $importer['uid']);
1368 Logger::info('Got migration for ' . $old_author . ', to ' . $new_author . ' with user ' . $importer['uid']);
1371 $signed_text = 'AccountMigration:' . $old_author . ':' . $new_author;
1372 $key = self::key($old_author);
1373 if (!Crypto::rsaVerify($signed_text, $signature, $key, 'sha256')) {
1374 Logger::notice('No valid signature for migration.');
1378 // Update the profile
1379 self::receiveProfile($importer, $data->profile);
1381 // change the technical stuff in contact
1382 $data = Probe::uri($new_author);
1383 if ($data['network'] == Protocol::PHANTOM) {
1384 Logger::notice("Account for " . $new_author . " couldn't be probed.");
1389 'url' => $data['url'],
1390 'nurl' => Strings::normaliseLink($data['url']),
1391 'name' => $data['name'],
1392 'nick' => $data['nick'],
1393 'addr' => $data['addr'],
1394 'batch' => $data['batch'],
1395 'notify' => $data['notify'],
1396 'poll' => $data['poll'],
1397 'network' => $data['network'],
1400 Contact::update($fields, ['addr' => $old_author->getAddr()]);
1402 Logger::info('Contacts are updated.');
1408 * Processes an account deletion
1410 * @param SimpleXMLElement $data The message object
1412 * @return bool Success
1413 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1415 private static function receiveAccountDeletion(SimpleXMLElement $data): bool
1417 $author_handle = XML::unescape($data->author);
1419 $contacts = DBA::select('contact', ['id'], ['addr' => $author_handle]);
1420 while ($contact = DBA::fetch($contacts)) {
1421 Contact::remove($contact['id']);
1423 DBA::close($contacts);
1425 Logger::info('Removed contacts for ' . $author_handle);
1431 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1433 * @param string $guid Message guid
1434 * @param WebFingerUri|null $person_uri Optional person to derive the base URL from
1436 * @return string The constructed uri or the one from our database or empty string
1437 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1438 * @throws \ImagickException
1440 private static function getUriFromGuid(string $guid, WebFingerUri $person_uri = null): string
1442 $item = Post::selectFirst(['uri'], ['guid' => $guid]);
1444 return $item['uri'];
1445 } elseif ($person_uri) {
1447 return DI::dsprContact()->selectOneByAddr($person_uri)->baseurl . '/objects/' . $guid;
1448 } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) {
1457 * Store the mentions in the tag table
1459 * @param integer $uriid
1460 * @param string $text
1462 private static function storeMentions(int $uriid, string $text)
1464 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1465 if (empty($matches)) {
1470 * Matching values for the preg match
1471 * [1] = mention type (@ or !)
1472 * [2] = name (optional)
1476 foreach ($matches as $match) {
1477 if (empty($match)) {
1482 $contact = DI::dsprContact()->getByUrl(new Uri($match[3]));
1483 Tag::storeByHash($uriid, $match[1], $contact->name ?: $contact->nick, $contact->url);
1484 } catch (\Throwable $e) {
1490 * Processes an incoming comment
1492 * @param array $importer Array of the importer user
1493 * @param WebFingerUri $sender The sender of the message
1494 * @param SimpleXMLElement $data The message object
1495 * @param string $xml The original XML of the message
1496 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1498 * @return bool The message id of the generated comment or "false" if there was an error
1499 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1500 * @throws \ImagickException
1502 private static function receiveComment(array $importer, WebFingerUri $sender, SimpleXMLElement $data, string $xml, int $direction): bool
1504 $author = WebFingerUri::fromString(XML::unescape($data->author));
1505 $guid = XML::unescape($data->guid);
1506 $parent_guid = XML::unescape($data->parent_guid);
1507 $text = XML::unescape($data->text);
1509 if (isset($data->created_at)) {
1510 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1512 $created_at = DateTimeFormat::utcNow();
1515 if (isset($data->thread_parent_guid)) {
1516 $thread_parent_guid = XML::unescape($data->thread_parent_guid);
1517 $thr_parent = self::getUriFromGuid($thread_parent_guid);
1522 $contact = self::allowedContactByHandle($importer, $sender, true);
1527 if (!empty($contact['gsid'])) {
1528 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1531 $message_id = self::messageExists($importer['uid'], $guid);
1536 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1537 if (!$toplevel_parent_item) {
1542 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
1543 } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) {
1544 Logger::notice('Unable to find author details', ['author' => $author->getAddr()]);
1548 // Fetch the contact id - if we know this contact
1549 $author_contact = self::authorContactByUrl($contact, $author_url, $importer['uid']);
1553 $datarray['uid'] = $importer['uid'];
1554 $datarray['contact-id'] = $author_contact['cid'];
1555 $datarray['network'] = $author_contact['network'];
1557 $datarray['author-link'] = $author_url;
1558 $datarray['author-id'] = Contact::getIdForURL($author_url);
1560 $datarray['owner-link'] = $contact['url'];
1561 $datarray['owner-id'] = Contact::getIdForURL($contact['url']);
1563 // Will be overwritten for sharing accounts in Item::insert
1564 $datarray = self::setDirection($datarray, $direction);
1566 $datarray['guid'] = $guid;
1567 $datarray['uri'] = self::getUriFromGuid($guid, $author);
1568 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1570 $datarray['verb'] = Activity::POST;
1571 $datarray['gravity'] = Item::GRAVITY_COMMENT;
1573 $datarray['thr-parent'] = $thr_parent ?: $toplevel_parent_item['uri'];
1575 $datarray['object-type'] = Activity\ObjectType::COMMENT;
1576 $datarray['post-type'] = Item::PT_NOTE;
1578 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1579 $datarray['source'] = $xml;
1581 $datarray = self::setDirection($datarray, $direction);
1583 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
1585 $datarray['plink'] = self::plink($author, $guid, $toplevel_parent_item['guid']);
1586 $body = Markdown::toBBCode($text);
1588 $datarray['body'] = self::replacePeopleGuid($body, $author_url);
1590 self::storeMentions($datarray['uri-id'], $text);
1591 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
1593 self::fetchGuid($datarray);
1595 // If we are the origin of the parent we store the original data.
1596 // We notify our followers during the item storage.
1597 if ($toplevel_parent_item['origin']) {
1598 $datarray['diaspora_signed_text'] = json_encode($data);
1601 if (Item::isTooOld($datarray)) {
1602 Logger::info('Comment is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1606 $message_id = Item::insert($datarray);
1608 if ($message_id <= 0) {
1613 Logger::info('Stored comment ' . $datarray['guid'] . ' with message id ' . $message_id);
1614 if ($datarray['uid'] == 0) {
1615 Item::distribute($message_id, json_encode($data));
1623 * processes and stores private messages
1625 * @param array $importer Array of the importer user
1626 * @param array $contact The contact of the message
1627 * @param SimpleXMLElement $data The message object
1628 * @param array $msg Array of the processed message, author handle and key
1629 * @param object $mesg The private message
1630 * @param array $conversation The conversation record to which this message belongs
1632 * @return bool "true" if it was successful
1633 * @throws \Exception
1634 * @todo Find type-hint for $mesg and update documentation
1636 private static function receiveConversationMessage(array $importer, array $contact, SimpleXMLElement $data, array $msg, $mesg, array $conversation): bool
1638 $author_handle = XML::unescape($data->author);
1639 $guid = XML::unescape($data->guid);
1640 $subject = XML::unescape($data->subject);
1642 // "diaspora_handle" is the element name from the old version
1643 // "author" is the element name from the new version
1644 if ($mesg->author) {
1645 $msg_author_handle = XML::unescape($mesg->author);
1646 } elseif ($mesg->diaspora_handle) {
1647 $msg_author_handle = XML::unescape($mesg->diaspora_handle);
1653 $msg_author_uri = WebFingerUri::fromString($msg_author_handle);
1654 } catch (\InvalidArgumentException $e) {
1658 $msg_guid = XML::unescape($mesg->guid);
1659 $msg_conversation_guid = XML::unescape($mesg->conversation_guid);
1660 $msg_text = XML::unescape($mesg->text);
1661 $msg_created_at = DateTimeFormat::utc(XML::unescape($mesg->created_at));
1663 if ($msg_conversation_guid != $guid) {
1664 Logger::notice('Message conversation guid does not belong to the current conversation.', ['guid' => $guid]);
1668 $msg_author = DI::dsprContact()->getByAddr($msg_author_uri);
1670 return Mail::insert([
1671 'uid' => $importer['uid'],
1672 'guid' => $msg_guid,
1673 'convid' => $conversation['id'],
1674 'from-name' => $msg_author->name,
1675 'from-photo' => (string)$msg_author->photo,
1676 'from-url' => (string)$msg_author->url,
1677 'contact-id' => $contact['id'],
1678 'title' => $subject,
1679 'body' => Markdown::toBBCode($msg_text),
1680 'uri' => $msg_author_handle . ':' . $msg_guid,
1681 'parent-uri' => $author_handle . ':' . $guid,
1682 'created' => $msg_created_at
1687 * Processes new private messages (answers to private messages are processed elsewhere)
1689 * @param array $importer Array of the importer user
1690 * @param array $msg Array of the processed message, author handle and key
1691 * @param SimpleXMLElement $data The message object
1693 * @return bool Success
1694 * @throws \Exception
1696 private static function receiveConversation(array $importer, array $msg, SimpleXMLElement $data)
1698 $author_handle = XML::unescape($data->author);
1699 $guid = XML::unescape($data->guid);
1700 $subject = XML::unescape($data->subject);
1701 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1702 $participants = XML::unescape($data->participants);
1704 $messages = $data->message;
1706 if (!count($messages)) {
1707 Logger::notice('Empty conversation');
1711 $contact = self::allowedContactByHandle($importer, WebFingerUri::fromString($msg['author']), true);
1716 if (!empty($contact['gsid'])) {
1717 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1720 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1721 if (!DBA::isResult($conversation)) {
1722 $r = DBA::insert('conv', [
1723 'uid' => $importer['uid'],
1725 'creator' => $author_handle,
1726 'created' => $created_at,
1727 'updated' => DateTimeFormat::utcNow(),
1728 'subject' => $subject,
1729 'recips' => $participants
1733 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1736 if (!$conversation) {
1737 Logger::warning('Unable to create conversation.');
1741 foreach ($messages as $mesg) {
1742 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1749 * Processes "like" messages
1751 * @param array $importer Array of the importer user
1752 * @param WebFingerUri $sender The sender of the message
1753 * @param SimpleXMLElement $data The message object
1754 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1756 * @return bool Success or failure
1757 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1758 * @throws \ImagickException
1760 private static function receiveLike(array $importer, WebFingerUri $sender, SimpleXMLElement $data, int $direction): bool
1762 $author = WebFingerUri::fromString(XML::unescape($data->author));
1763 $guid = XML::unescape($data->guid);
1764 $parent_guid = XML::unescape($data->parent_guid);
1765 $parent_type = XML::unescape($data->parent_type);
1766 $positive = XML::unescape($data->positive);
1768 // likes on comments aren't supported by Diaspora - only on posts
1769 // But maybe this will be supported in the future, so we will accept it.
1770 if (!in_array($parent_type, ['Post', 'Comment'])) {
1774 $contact = self::allowedContactByHandle($importer, $sender, true);
1779 if (!empty($contact['gsid'])) {
1780 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1783 $message_id = self::messageExists($importer['uid'], $guid);
1788 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1789 if (!$toplevel_parent_item) {
1794 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
1795 } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) {
1796 Logger::notice('Unable to find author details', ['author' => $author->getAddr()]);
1800 // Fetch the contact id - if we know this contact
1801 $author_contact = self::authorContactByUrl($contact, $author_url, $importer['uid']);
1803 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1804 // We would accept this anyhow.
1805 if ($positive == 'true') {
1806 $verb = Activity::LIKE;
1808 $verb = Activity::DISLIKE;
1813 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1815 $datarray['uid'] = $importer['uid'];
1816 $datarray['contact-id'] = $author_contact['cid'];
1817 $datarray['network'] = $author_contact['network'];
1819 $datarray = self::setDirection($datarray, $direction);
1821 $datarray['owner-link'] = $datarray['author-link'] = $author_url;
1822 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($author_url);
1824 $datarray['guid'] = $guid;
1825 $datarray['uri'] = self::getUriFromGuid($guid, $author);
1827 $datarray['verb'] = $verb;
1828 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
1829 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1831 $datarray['object-type'] = Activity\ObjectType::NOTE;
1833 $datarray['body'] = $verb;
1835 // Diaspora doesn't provide a date for likes
1836 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
1838 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1839 if ($toplevel_parent_item['gravity'] != Item::GRAVITY_PARENT) {
1840 $toplevel = Post::selectFirst(['origin'], ['id' => $toplevel_parent_item['parent']]);
1841 $origin = $toplevel['origin'];
1843 $origin = $toplevel_parent_item['origin'];
1846 // If we are the origin of the parent we store the original data.
1847 // We notify our followers during the item storage.
1849 $datarray['diaspora_signed_text'] = json_encode($data);
1852 if (Item::isTooOld($datarray)) {
1853 Logger::info('Like is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1857 $message_id = Item::insert($datarray);
1859 if ($message_id <= 0) {
1864 Logger::info('Stored like ' . $datarray['guid'] . ' with message id ' . $message_id);
1865 if ($datarray['uid'] == 0) {
1866 Item::distribute($message_id, json_encode($data));
1874 * Processes private messages
1876 * @param array $importer Array of the importer user
1877 * @param SimpleXMLElement $data The message object
1879 * @return bool Success?
1880 * @throws \Exception
1882 private static function receiveMessage(array $importer, SimpleXMLElement $data): bool
1884 $author_uri = WebFingerUri::fromString(XML::unescape($data->author));
1885 $guid = XML::unescape($data->guid);
1886 $conversation_guid = XML::unescape($data->conversation_guid);
1887 $text = XML::unescape($data->text);
1888 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1890 $contact = self::allowedContactByHandle($importer, $author_uri, true);
1895 if (!empty($contact['gsid'])) {
1896 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1899 $condition = ['uid' => $importer['uid'], 'guid' => $conversation_guid];
1900 $conversation = DBA::selectFirst('conv', [], $condition);
1901 if (!DBA::isResult($conversation)) {
1902 Logger::notice('Conversation not available.');
1907 $author = DI::dsprContact()->getByAddr($author_uri);
1908 } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) {
1909 Logger::notice('Unable to find author details', ['author' => $author_uri->getAddr()]);
1913 $body = Markdown::toBBCode($text);
1915 $body = self::replacePeopleGuid($body, $author->url);
1917 return Mail::insert([
1918 'uid' => $importer['uid'],
1920 'convid' => $conversation['id'],
1921 'from-name' => $author->name,
1922 'from-photo' => (string)$author->photo,
1923 'from-url' => (string)$author->url,
1924 'contact-id' => $contact['id'],
1925 'title' => $conversation['subject'],
1928 'uri' => $author_uri . ':' . $guid,
1929 'parent-uri' => $author_uri . ':' . $conversation['guid'],
1930 'created' => $created_at
1935 * Processes participations - unsupported by now
1937 * @param array $importer Array of the importer user
1938 * @param SimpleXMLElement $data The message object
1939 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1941 * @return bool success
1942 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1943 * @throws \ImagickException
1945 private static function receiveParticipation(array $importer, SimpleXMLElement $data, int $direction): bool
1947 $author = WebFingerUri::fromString(strtolower(XML::unescape($data->author)));
1948 $guid = XML::unescape($data->guid);
1949 $parent_guid = XML::unescape($data->parent_guid);
1951 $contact = self::allowedContactByHandle($importer, $author, true);
1956 if (!empty($contact['gsid'])) {
1957 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1960 if (self::messageExists($importer['uid'], $guid)) {
1964 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1965 if (!$toplevel_parent_item) {
1969 if (!$toplevel_parent_item['origin']) {
1970 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1973 if (!in_array($toplevel_parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
1974 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1979 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
1980 } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) {
1981 Logger::notice('unable to find author details', ['author' => $author->getAddr()]);
1985 $author_contact = self::authorContactByUrl($contact, $author_url, $importer['uid']);
1987 // Store participation
1990 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1992 $datarray['uid'] = $importer['uid'];
1993 $datarray['contact-id'] = $author_contact['cid'];
1994 $datarray['network'] = $author_contact['network'];
1996 $datarray = self::setDirection($datarray, $direction);
1998 $datarray['owner-link'] = $datarray['author-link'] = $author_url;
1999 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($author_url);
2001 $datarray['guid'] = $guid;
2002 $datarray['uri'] = self::getUriFromGuid($guid, $author);
2004 $datarray['verb'] = Activity::FOLLOW;
2005 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
2006 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
2008 $datarray['object-type'] = Activity\ObjectType::NOTE;
2010 $datarray['body'] = Activity::FOLLOW;
2012 // Diaspora doesn't provide a date for a participation
2013 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
2015 if (Item::isTooOld($datarray)) {
2016 Logger::info('Participation is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2020 $message_id = Item::insert($datarray);
2022 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
2024 // Send all existing comments and likes to the requesting server
2025 $comments = Post::select(
2026 ['id', 'uri-id', 'parent-author-network', 'author-network', 'verb', 'gravity'],
2027 ['parent' => $toplevel_parent_item['id'], 'gravity' => [Item::GRAVITY_COMMENT, Item::GRAVITY_ACTIVITY]]
2029 while ($comment = Post::fetch($comments)) {
2030 if (($comment['gravity'] == Item::GRAVITY_ACTIVITY) && !in_array($comment['verb'], [Activity::LIKE, Activity::DISLIKE])) {
2031 Logger::info('Unsupported activities are not relayed', ['item' => $comment['id'], 'verb' => $comment['verb']]);
2035 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
2036 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2040 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
2041 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2045 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact['cid']]);
2046 if (Worker::add(Worker::PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['uri-id'], $author_contact['cid'], $datarray['uid'])) {
2047 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2050 DBA::close($comments);
2056 * Processes photos - unneeded
2058 * @param array $importer Array of the importer user
2059 * @param SimpleXMLElement $data The message object
2061 * @return bool always true
2063 private static function receivePhoto(array $importer, $data)
2065 // There doesn't seem to be a reason for this function,
2066 // since the photo data is transmitted in the status message as well
2071 * Processes poll participations - unssupported
2073 * @param array $importer Array of the importer user
2074 * @param object $data The message object
2076 * @return bool always true
2078 private static function receivePollParticipation(array $importer, $data)
2080 // We don't support polls by now
2085 * Processes incoming profile updates
2087 * @param array $importer Array of the importer user
2088 * @param SimpleXMLElement $data The message object
2090 * @return bool Success
2091 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2092 * @throws \ImagickException
2094 private static function receiveProfile(array $importer, SimpleXMLElement $data): bool
2096 $author = WebFingerUri::fromString(strtolower(XML::unescape($data->author)));
2098 $contact = self::contactByHandle($importer['uid'], $author);
2103 $name = XML::unescape($data->first_name) . ((strlen($data->last_name)) ? ' ' . XML::unescape($data->last_name) : '');
2104 $image_url = XML::unescape($data->image_url);
2105 $birthday = XML::unescape($data->birthday);
2106 $about = Markdown::toBBCode(XML::unescape($data->bio));
2107 $location = Markdown::toBBCode(XML::unescape($data->location));
2108 $searchable = (XML::unescape($data->searchable) == 'true');
2109 $nsfw = (XML::unescape($data->nsfw) == 'true');
2110 $tags = XML::unescape($data->tag_string);
2112 $tags = explode('#', $tags);
2115 foreach ($tags as $tag) {
2116 $tag = trim(strtolower($tag));
2122 $keywords = implode(', ', $keywords);
2125 $name = $author->getUser();
2128 if (preg_match('|^https?://|', $image_url) === 0) {
2129 // @TODO No HTTPS here?
2130 $image_url = 'http://' . $author->getFullHost() . $image_url;
2133 Contact::updateAvatar($contact['id'], $image_url);
2135 // Generic birthday. We don't know the timezone. The year is irrelevant.
2137 $birthday = str_replace('1000', '1901', $birthday);
2139 if ($birthday != '') {
2140 $birthday = DateTimeFormat::utc($birthday, 'Y-m-d');
2143 // this is to prevent multiple birthday notifications in a single year
2144 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2146 if (substr($birthday, 5) === substr($contact['bd'], 5)) {
2147 $birthday = $contact['bd'];
2151 'name' => $name, 'location' => $location,
2152 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2153 'addr' => $author->getAddr(), 'nick' => $author->getUser(), 'keywords' => $keywords,
2154 'unsearchable' => !$searchable, 'sensitive' => $nsfw
2157 if (!empty($birthday)) {
2158 $fields['bd'] = $birthday;
2161 Contact::update($fields, ['id' => $contact['id']]);
2163 Logger::info('Profile of contact ' . $contact['id'] . ' stored for user ' . $importer['uid']);
2169 * Processes incoming friend requests
2171 * @param array $importer Array of the importer user
2172 * @param array $contact The contact that send the request
2174 * @throws \Exception
2176 private static function receiveRequestMakeFriend(array $importer, array $contact)
2178 if ($contact['rel'] == Contact::SHARING) {
2180 ['rel' => Contact::FRIEND, 'writable' => true],
2181 ['id' => $contact['id'], 'uid' => $importer['uid']]
2187 * Processes incoming sharing notification
2189 * @param array $importer Array of the importer user
2190 * @param SimpleXMLElement $data The message object
2192 * @return bool Success
2193 * @throws \Exception
2195 private static function receiveContactRequest(array $importer, SimpleXMLElement $data): bool
2197 $author_handle = XML::unescape($data->author);
2198 $recipient = XML::unescape($data->recipient);
2200 if (!$author_handle || !$recipient) {
2204 $author = WebFingerUri::fromString($author_handle);
2206 // the current protocol version doesn't know these fields
2207 // That means that we will assume their existence
2208 if (isset($data->following)) {
2209 $following = (XML::unescape($data->following) == 'true');
2214 if (isset($data->sharing)) {
2215 $sharing = (XML::unescape($data->sharing) == 'true');
2220 $contact = self::contactByHandle($importer['uid'], $author);
2222 // perhaps we were already sharing with this person. Now they're sharing with us.
2223 // That makes us friends.
2226 Logger::info('Author ' . $author . ' (Contact ' . $contact['id'] . ') wants to follow us.');
2227 self::receiveRequestMakeFriend($importer, $contact);
2229 // refetch the contact array
2230 $contact = self::contactByHandle($importer['uid'], $author);
2232 // If we are now friends, we are sending a share message.
2233 // Normally we needn't to do so, but the first message could have been vanished.
2234 if (in_array($contact['rel'], [Contact::FRIEND])) {
2235 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2236 if (DBA::isResult($user)) {
2237 Logger::info('Sending share message to author ' . $author . ' - Contact: ' . $contact['id'] . ' - User: ' . $importer['uid']);
2238 self::sendShare($user, $contact);
2243 Logger::info("Author " . $author . " doesn't want to follow us anymore.");
2244 Contact::removeFollower($contact);
2249 if (!$following && $sharing && in_array($importer['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2250 Logger::info("Author " . $author . " wants to share with us - but doesn't want to listen. Request is ignored.");
2252 } elseif (!$following && !$sharing) {
2253 Logger::info("Author " . $author . " doesn't want anything - and we don't know the author. Request is ignored.");
2255 } elseif (!$following && $sharing) {
2256 Logger::info("Author " . $author . " wants to share with us.");
2257 } elseif ($following && $sharing) {
2258 Logger::info("Author " . $author . " wants to have a bidirectional connection.");
2259 } elseif ($following && !$sharing) {
2260 Logger::info("Author " . $author . " wants to listen to us.");
2264 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
2265 } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) {
2266 Logger::notice('Cannot resolve diaspora handle for recipient', ['author' => $author->getAddr(), 'recipient' => $recipient]);
2270 $cid = Contact::getIdForURL($author_url, $importer['uid']);
2272 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2278 'author-id' => Contact::getIdForURL($author_url),
2279 'author-link' => $author_url
2282 $result = Contact::addRelationship($importer, $contact, $item, false);
2283 if ($result === true) {
2284 $contact_record = self::contactByHandle($importer['uid'], $author);
2285 if (!$contact_record) {
2286 Logger::info('unable to locate newly created contact record.');
2290 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2291 if (DBA::isResult($user)) {
2292 self::sendShare($user, $contact_record);
2294 // Send the profile data, maybe it weren't transmitted before
2295 self::sendProfile($importer['uid'], [$contact_record]);
2303 * Processes a reshare message
2305 * @param array $importer Array of the importer user
2306 * @param SimpleXMLElement $data The message object
2307 * @param string $xml The original XML of the message
2308 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2310 * @return bool Success or failure
2311 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2312 * @throws \ImagickException
2314 private static function receiveReshare(array $importer, SimpleXMLElement $data, string $xml, int $direction): bool
2316 $author = WebFingerUri::fromString(XML::unescape($data->author));
2317 $guid = XML::unescape($data->guid);
2318 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2320 $root_author = WebFingerUri::fromString(XML::unescape($data->root_author));
2321 } catch (\InvalidArgumentException $e) {
2325 $root_guid = XML::unescape($data->root_guid);
2326 /// @todo handle unprocessed property "provider_display_name"
2327 $public = XML::unescape($data->public);
2329 $contact = self::allowedContactByHandle($importer, $author);
2334 if (!empty($contact['gsid'])) {
2335 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2338 $message_id = self::messageExists($importer['uid'], $guid);
2344 $original_person = DI::dsprContact()->getByAddr($root_author);
2345 } catch (HTTPException\NotFoundException $e) {
2351 $datarray['uid'] = $importer['uid'];
2352 $datarray['contact-id'] = $contact['id'];
2353 $datarray['network'] = Protocol::DIASPORA;
2355 $datarray['author-link'] = $contact['url'];
2356 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2358 $datarray['owner-link'] = $datarray['author-link'];
2359 $datarray['owner-id'] = $datarray['author-id'];
2361 $datarray['guid'] = $guid;
2362 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($guid, $author);
2363 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2365 $datarray['verb'] = Activity::POST;
2366 $datarray['gravity'] = Item::GRAVITY_PARENT;
2368 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2369 $datarray['source'] = $xml;
2371 $datarray = self::setDirection($datarray, $direction);
2373 $datarray['quote-uri-id'] = self::getQuoteUriId($root_guid, $importer['uid'], $original_person->url);
2374 if (empty($datarray['quote-uri-id'])) {
2378 $datarray['body'] = '';
2379 $datarray['plink'] = self::plink($author, $guid);
2380 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2381 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2383 self::fetchGuid($datarray);
2385 if (Item::isTooOld($datarray)) {
2386 Logger::info('Reshare is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2390 $message_id = Item::insert($datarray);
2392 self::sendParticipation($contact, $datarray);
2395 Logger::info('Stored reshare ' . $datarray['guid'] . ' with message id ' . $message_id);
2396 if ($datarray['uid'] == 0) {
2397 Item::distribute($message_id);
2405 private static function getQuoteUriId(string $guid, int $uid, string $host): int
2407 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2409 if (!DBA::isResult($shared_item) && !empty($host) && Diaspora::storeByGuid($guid, $host, true)) {
2410 Logger::debug('Fetched post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2411 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2412 } elseif (DBA::isResult($shared_item)) {
2413 Logger::debug('Found existing post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2416 if (!DBA::isResult($shared_item)) {
2417 Logger::notice('Post does not exist.', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2421 return $shared_item['uri-id'];
2425 * Processes retractions
2427 * @param array $importer Array of the importer user
2428 * @param array $contact The contact of the item owner
2429 * @param SimpleXMLElement $data The message object
2431 * @return bool success
2432 * @throws \Exception
2434 private static function itemRetraction(array $importer, array $contact, SimpleXMLElement $data): bool
2436 $author_uri = WebFingerUri::fromString(XML::unescape($data->author));
2437 $target_guid = XML::unescape($data->target_guid);
2438 $target_type = XML::unescape($data->target_type);
2441 $author = DI::dsprContact()->getByAddr($author_uri);
2442 } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) {
2443 Logger::notice('Unable to find details for author', ['author' => $author_uri->getAddr()]);
2447 $contact_url = $contact['url'] ?? '' ?: (string)$author->url;
2449 // Fetch items that are about to be deleted
2450 $fields = ['uid', 'id', 'parent', 'author-link', 'uri-id'];
2452 // When we receive a public retraction, we delete every item that we find.
2453 if ($importer['uid'] == 0) {
2454 $condition = ['guid' => $target_guid, 'deleted' => false];
2456 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2459 $r = Post::select($fields, $condition);
2460 if (!DBA::isResult($r)) {
2461 Logger::notice('Target guid ' . $target_guid . ' was not found on this system for user ' . $importer['uid'] . '.');
2465 while ($item = Post::fetch($r)) {
2466 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2467 Logger::info("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.");
2471 // Fetch the parent item
2472 $parent = Post::selectFirst(['author-link'], ['id' => $item['parent']]);
2474 // Only delete it if the parent author really fits
2475 if (!Strings::compareLink($parent['author-link'], $contact_url) && !Strings::compareLink($item['author-link'], $contact_url)) {
2476 Logger::info("Thread author " . $parent['author-link'] . " and item author " . $item['author-link'] . " don't fit to expected contact " . $contact_url);
2480 Item::markForDeletion(['id' => $item['id']]);
2482 Logger::info('Deleted target ' . $target_guid . ' (' . $item['id'] . ') from user ' . $item['uid'] . ' parent: ' . $item['parent']);
2490 * Receives retraction messages
2492 * @param array $importer Array of the importer user
2493 * @param WebFingerUri $sender The sender of the message
2494 * @param SimpleXMLElement $data The message object
2496 * @return bool Success
2497 * @throws \Exception
2499 private static function receiveRetraction(array $importer, WebFingerUri $sender, SimpleXMLElement $data)
2501 $target_type = XML::unescape($data->target_type);
2503 $contact = self::contactByHandle($importer['uid'], $sender);
2504 if (!$contact && (in_array($target_type, ['Contact', 'Person']))) {
2505 Logger::notice('Cannot find contact for sender: ' . $sender . ' and user ' . $importer['uid']);
2513 Logger::info('Got retraction for ' . $target_type . ', sender ' . $sender . ' and user ' . $importer['uid']);
2515 switch ($target_type) {
2520 case 'StatusMessage':
2521 return self::itemRetraction($importer, $contact, $data);
2523 case 'PollParticipation':
2525 // Currently unsupported
2529 Logger::notice('Unknown target type ' . $target_type);
2536 * Checks if an incoming message is wanted
2538 * @param array $item
2539 * @param string $author
2540 * @param string $body
2541 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2543 * @return boolean Is the message wanted?
2545 private static function isSolicitedMessage(array $item, string $author, string $body, int $direction): bool
2547 $contact = Contact::getByURL($author);
2548 if (DBA::exists('contact', ['`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)', $contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) {
2549 Logger::debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2553 if ($direction == self::FORCED_FETCH) {
2554 Logger::debug('Post is a forced fetch - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2558 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
2559 if (Relay::isSolicitedPost($tags, $body, $contact['id'], $item['uri'], Protocol::DIASPORA)) {
2560 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2568 * Store an attached photo in the post-media table
2571 * @param object $photo
2574 private static function storePhotoAsMedia(int $uriid, $photo)
2576 // @TODO Need to find object type, roland@f.haeder.net
2577 Logger::debug('photo=' . get_class($photo));
2579 $data['uri-id'] = $uriid;
2580 $data['type'] = Post\Media::IMAGE;
2581 $data['url'] = XML::unescape($photo->remote_photo_path) . XML::unescape($photo->remote_photo_name);
2582 $data['height'] = (int)XML::unescape($photo->height ?? 0);
2583 $data['width'] = (int)XML::unescape($photo->width ?? 0);
2584 $data['description'] = XML::unescape($photo->text ?? '');
2586 Post\Media::insert($data);
2590 * Set direction and post reason
2592 * @param array $datarray
2593 * @param integer $direction
2597 public static function setDirection(array $datarray, int $direction): array
2599 $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
2601 if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
2602 $datarray['post-reason'] = Item::PR_FETCHED;
2603 } elseif ($datarray['uid'] == 0) {
2604 $datarray['post-reason'] = Item::PR_GLOBAL;
2606 $datarray['post-reason'] = Item::PR_PUSHED;
2613 * Receives status messages
2615 * @param array $importer Array of the importer user
2616 * @param SimpleXMLElement $data The message object
2617 * @param string $xml The original XML of the message
2618 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2620 * @return int|bool The message id of the newly created item or false on error
2621 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2622 * @throws \ImagickException
2624 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, string $xml, int $direction)
2626 $author = WebFingerUri::fromString(XML::unescape($data->author));
2627 $guid = XML::unescape($data->guid);
2628 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2629 $public = XML::unescape($data->public);
2630 $text = XML::unescape($data->text);
2631 $provider_display_name = XML::unescape($data->provider_display_name);
2633 $contact = self::allowedContactByHandle($importer, $author);
2638 if (!empty($contact['gsid'])) {
2639 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2642 $message_id = self::messageExists($importer['uid'], $guid);
2648 if ($data->location) {
2649 foreach ($data->location->children() as $fieldname => $data) {
2650 $address[$fieldname] = XML::unescape($data);
2654 $raw_body = $body = Markdown::toBBCode($text);
2658 $datarray['guid'] = $guid;
2659 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($guid, $author);
2660 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2662 // Attach embedded pictures to the body
2664 foreach ($data->photo as $photo) {
2665 self::storePhotoAsMedia($datarray['uri-id'], $photo);
2668 $datarray['object-type'] = Activity\ObjectType::IMAGE;
2669 $datarray['post-type'] = Item::PT_IMAGE;
2670 } elseif ($data->poll) {
2671 $datarray['object-type'] = Activity\ObjectType::NOTE;
2672 $datarray['post-type'] = Item::PT_POLL;
2674 $datarray['object-type'] = Activity\ObjectType::NOTE;
2675 $datarray['post-type'] = Item::PT_NOTE;
2678 /// @todo enable support for polls
2679 //if ($data->poll) {
2680 // foreach ($data->poll as $poll)
2685 /// @todo enable support for events
2687 $datarray['uid'] = $importer['uid'];
2688 $datarray['contact-id'] = $contact['id'];
2689 $datarray['network'] = Protocol::DIASPORA;
2691 $datarray['author-link'] = $contact['url'];
2692 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2694 $datarray['owner-link'] = $datarray['author-link'];
2695 $datarray['owner-id'] = $datarray['author-id'];
2697 $datarray['verb'] = Activity::POST;
2698 $datarray['gravity'] = Item::GRAVITY_PARENT;
2700 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2701 $datarray['source'] = $xml;
2703 $datarray = self::setDirection($datarray, $direction);
2705 $datarray['body'] = self::replacePeopleGuid($body, $contact['url']);
2706 $datarray['raw-body'] = self::replacePeopleGuid($raw_body, $contact['url']);
2708 self::storeMentions($datarray['uri-id'], $text);
2709 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
2711 if (!self::isSolicitedMessage($datarray, $author, $body, $direction)) {
2712 DBA::delete('item-uri', ['uri' => $datarray['uri']]);
2716 if ($provider_display_name != '') {
2717 $datarray['app'] = $provider_display_name;
2720 $datarray['plink'] = self::plink($author, $guid);
2721 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2722 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2724 if (isset($address['address'])) {
2725 $datarray['location'] = $address['address'];
2728 if (isset($address['lat']) && isset($address['lng'])) {
2729 $datarray['coord'] = $address['lat'] . ' ' . $address['lng'];
2732 self::fetchGuid($datarray);
2734 if (Item::isTooOld($datarray)) {
2735 Logger::info('Status is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2739 $message_id = Item::insert($datarray);
2741 self::sendParticipation($contact, $datarray);
2744 Logger::info('Stored item ' . $datarray['guid'] . ' with message id ' . $message_id);
2745 if ($datarray['uid'] == 0) {
2746 Item::distribute($message_id);
2754 /* ************************************************************************************** *
2755 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2756 * ************************************************************************************** */
2759 * returnes the handle of a contact
2761 * @param array $contact contact array
2763 * @return string the handle in the format user@domain.tld
2764 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2766 private static function myHandle(array $contact): string
2768 if (!empty($contact['addr'])) {
2769 return $contact['addr'];
2772 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2773 // So - just in case - we build the the address here.
2774 if ($contact['nickname'] != '') {
2775 $nick = $contact['nickname'];
2777 $nick = $contact['nick'];
2780 return $nick . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
2785 * Creates the data for a private message in the new format
2787 * @param string $msg The message that is to be transmitted
2788 * @param array $user The record of the sender
2789 * @param array $contact Target of the communication
2790 * @param string $prvkey The private key of the sender
2791 * @param string $pubkey The public key of the receiver
2793 * @return string The encrypted data
2794 * @throws \Exception
2796 public static function encodePrivateData(string $msg, array $user, array $contact, string $prvkey, string $pubkey): string
2798 Logger::debug('Message: ' . $msg);
2800 // without a public key nothing will work
2802 Logger::notice('pubkey missing: contact id: ' . $contact['id']);
2806 $aes_key = random_bytes(32);
2807 $b_aes_key = base64_encode($aes_key);
2808 $iv = random_bytes(16);
2809 $b_iv = base64_encode($iv);
2811 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2813 $json = json_encode(['iv' => $b_iv, 'key' => $b_aes_key]);
2815 $encrypted_key_bundle = '';
2816 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
2820 $json_object = json_encode(
2822 'aes_key' => base64_encode($encrypted_key_bundle),
2823 'encrypted_magic_envelope' => base64_encode($ciphertext)
2827 return $json_object;
2831 * Creates the envelope for the "fetch" endpoint and for the new format
2833 * @param string $msg The message that is to be transmitted
2834 * @param array $user The record of the sender
2836 * @return string The envelope
2837 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2839 public static function buildMagicEnvelope(string $msg, array $user): string
2841 $b64url_data = Strings::base64UrlEncode($msg);
2842 $data = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
2844 $key_id = Strings::base64UrlEncode(self::myHandle($user));
2845 $type = 'application/xml';
2846 $encoding = 'base64url';
2847 $alg = 'RSA-SHA256';
2848 $signable_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
2850 // Fallback if the private key wasn't transmitted in the expected field
2851 if ($user['uprvkey'] == '') {
2852 $user['uprvkey'] = $user['prvkey'];
2855 $signature = Crypto::rsaSign($signable_data, $user['uprvkey']);
2856 $sig = Strings::base64UrlEncode($signature);
2861 '@attributes' => ['type' => $type],
2862 'me:encoding' => $encoding,
2865 '@attributes2' => ['key_id' => $key_id]
2869 $namespaces = ['me' => ActivityNamespace::SALMON_ME];
2871 return XML::fromArray($xmldata, $dummy, false, $namespaces);
2875 * Create the envelope for a message
2877 * @param string $msg The message that is to be transmitted
2878 * @param array $user The record of the sender
2879 * @param array $contact Target of the communication
2880 * @param string $prvkey The private key of the sender
2881 * @param string $pubkey The public key of the receiver
2882 * @param bool $public Is the message public?
2884 * @return string The message that will be transmitted to other servers
2885 * @throws \Exception
2887 public static function buildMessage(string $msg, array $user, array $contact, string $prvkey, string $pubkey, bool $public = false): string
2889 // The message is put into an envelope with the sender's signature
2890 $envelope = self::buildMagicEnvelope($msg, $user);
2892 // Private messages are put into a second envelope, encrypted with the receivers public key
2894 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
2901 * Creates a signature for a message
2903 * @param array $owner the array of the owner of the message
2904 * @param array $message The message that is to be signed
2906 * @return string The signature
2908 private static function signature(array $owner, array $message): string
2911 unset($sigmsg['author_signature']);
2912 unset($sigmsg['parent_author_signature']);
2914 $signed_text = implode(';', $sigmsg);
2916 return base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
2920 * Transmit a message to a target server
2922 * @param array $owner the array of the item owner
2923 * @param array $contact Target of the communication
2924 * @param string $envelope The message that is to be transmitted
2925 * @param bool $public_batch Is it a public post?
2926 * @param string $guid message guid
2928 * @return int Result of the transmission
2929 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2930 * @throws \ImagickException
2932 private static function transmit(array $owner, array $contact, string $envelope, bool $public_batch, string $guid = ''): int
2934 $enabled = intval(DI::config()->get('system', 'diaspora_enabled'));
2939 $logid = Strings::getRandomHex(4);
2941 // We always try to use the data from the diaspora-contact table.
2942 // This is important for transmitting data to Friendica servers.
2944 $target = DI::dsprContact()->getByAddr(WebFingerUri::fromString($contact['addr']));
2945 $dest_url = $public_batch ? $target->batch : $target->notify;
2946 } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) {
2949 if (empty($dest_url)) {
2950 $dest_url = ($public_batch ? $contact['batch'] : $contact['notify']);
2954 Logger::notice('No URL for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2958 Logger::info('transmit: ' . $logid . '-' . $guid . ' ' . $dest_url);
2960 if (!intval(DI::config()->get('system', 'diaspora_test'))) {
2961 $content_type = (($public_batch) ? 'application/magic-envelope+xml' : 'application/json');
2963 $postResult = DI::httpClient()->post($dest_url . '/', $envelope, ['Content-Type' => $content_type]);
2964 $return_code = $postResult->getReturnCode();
2966 Logger::notice('test_mode');
2970 if (!empty($contact['gsid']) && (empty($return_code) || $postResult->isTimeout())) {
2971 GServer::setFailureById($contact['gsid']);
2972 } elseif (!empty($contact['gsid']) && ($return_code >= 200) && ($return_code <= 299)) {
2973 GServer::setReachableById($contact['gsid'], Protocol::DIASPORA);
2976 Logger::info('transmit: ' . $logid . '-' . $guid . ' to ' . $dest_url . ' returns: ' . $return_code);
2978 return $return_code ? $return_code : -1;
2983 * Build the post xml
2985 * @param string $type The message type
2986 * @param array $message The message data
2988 * @return string The post XML
2989 * @throws \Exception
2991 public static function buildPostXml(string $type, array $message): string
2993 return XML::fromArray([$type => $message]);
2997 * Builds and transmit messages
2999 * @param array $owner the array of the item owner
3000 * @param array $contact Target of the communication
3001 * @param string $type The message type
3002 * @param array $message The message data
3003 * @param bool $public_batch Is it a public post?
3004 * @param string $guid message guid
3006 * @return int Result of the transmission
3007 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3008 * @throws \ImagickException
3010 private static function buildAndTransmit(array $owner, array $contact, string $type, array $message, bool $public_batch = false, string $guid = '')
3012 $msg = self::buildPostXml($type, $message);
3014 // Fallback if the private key wasn't transmitted in the expected field
3015 if (empty($owner['uprvkey'])) {
3016 $owner['uprvkey'] = $owner['prvkey'];
3019 // When sending content to Friendica contacts using the Diaspora protocol
3020 // we have to fetch the public key from the diaspora-contact.
3021 // This is due to the fact that legacy DFRN had unique keys for every contact.
3022 $pubkey = $contact['pubkey'];
3023 if (!empty($contact['addr'])) {
3025 $pubkey = DI::dsprContact()->getByAddr(WebFingerUri::fromString($contact['addr']))->pubKey;
3026 } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) {
3029 // The "addr" field should always be filled.
3030 // If this isn't the case, it will raise a notice some lines later.
3031 // And in the log we will see where it came from, and we can handle it there.
3032 Logger::notice('Empty addr', ['contact' => $contact ?? [], 'callstack' => System::callstack(20)]);
3035 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $pubkey ?? '', $public_batch);
3037 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3039 Logger::info('Transmitted message', ['owner' => $owner['uid'], 'target' => $contact['addr'], 'type' => $type, 'guid' => $guid, 'result' => $return_code]);
3041 return $return_code;
3045 * sends a participation (Used to get all further updates)
3047 * @param array $contact Target of the communication
3048 * @param array $item Item array
3050 * @return int The result of the transmission
3051 * @throws \Exception
3053 private static function sendParticipation(array $contact, array $item): int
3055 // Don't send notifications for private postings
3056 if ($item['private'] == Item::PRIVATE) {
3060 $cachekey = 'diaspora:sendParticipation:' . $item['guid'];
3062 $result = DI::cache()->get($cachekey);
3063 if (!is_null($result)) {
3067 // Fetch some user id to have a valid handle to transmit the participation.
3068 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3069 // If the item belongs to a user, we take this user id.
3070 if ($item['uid'] == 0) {
3071 // @todo Possibly use an administrator account?
3073 'verified' => true, 'blocked' => false,
3074 'account_removed' => false, 'account_expired' => false, 'account-type' => User::ACCOUNT_TYPE_PERSON
3076 $first_user = DBA::selectFirst('user', ['uid'], $condition, ['order' => ['uid']]);
3077 $owner = User::getOwnerDataById($first_user['uid']);
3079 $owner = User::getOwnerDataById($item['uid']);
3082 $author_handle = self::myHandle($owner);
3085 'author' => $author_handle,
3086 'guid' => System::createUUID(),
3087 'parent_type' => 'Post',
3088 'parent_guid' => $item['guid']
3091 Logger::info('Send participation for ' . $item['guid'] . ' by ' . $author_handle);
3093 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3094 DI::cache()->set($cachekey, $item['guid'], Duration::QUARTER_HOUR);
3096 return self::buildAndTransmit($owner, $contact, 'participation', $message);
3100 * sends an account migration
3102 * @param array $owner the array of the item owner
3103 * @param array $contact Target of the communication
3104 * @param int $uid User ID
3106 * @return int The result of the transmission
3107 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3108 * @throws \ImagickException
3110 public static function sendAccountMigration(array $owner, array $contact, int $uid): int
3112 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3113 $profile = self::createProfileData($uid);
3115 $signed_text = 'AccountMigration:' . $old_handle . ':' . $profile['author'];
3116 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
3119 'author' => $old_handle,
3120 'profile' => $profile,
3121 'signature' => $signature
3124 Logger::info('Send account migration', ['msg' => $message]);
3126 return self::buildAndTransmit($owner, $contact, 'account_migration', $message);
3130 * Sends a "share" message
3132 * @param array $owner the array of the item owner
3133 * @param array $contact Target of the communication
3135 * @return int The result of the transmission
3136 * @throws \Exception
3138 public static function sendShare(array $owner, array $contact): int
3141 * @todo support the different possible combinations of "following" and "sharing"
3142 * Currently, Diaspora only interprets the "sharing" field
3144 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3148 switch ($contact["rel"]) {
3149 case Contact::FRIEND:
3153 case Contact::SHARING:
3157 case Contact::FOLLOWER:
3164 'author' => self::myHandle($owner),
3165 'recipient' => $contact['addr'],
3166 'following' => 'true',
3170 Logger::info('Send share', ['msg' => $message]);
3172 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3176 * sends an "unshare"
3178 * @param array $owner the array of the item owner
3179 * @param array $contact Target of the communication
3181 * @return int The result of the transmission
3182 * @throws \Exception
3184 public static function sendUnshare(array $owner, array $contact): int
3187 'author' => self::myHandle($owner),
3188 'recipient' => $contact['addr'],
3189 'following' => 'false',
3190 'sharing' => 'false'
3193 Logger::info('Send unshare', ['msg' => $message]);
3195 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3199 * Fetch reshare details
3201 * @param array $item The message body that is to be check
3203 * @return array Reshare details (empty if the item is no reshare)
3204 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3205 * @throws \ImagickException
3207 public static function getReshareDetails(array $item): array
3209 $reshared = DI::contentItem()->getSharedPost($item, ['guid', 'network', 'author-addr']);
3210 if (empty($reshared)) {
3214 // Skip if it isn't a pure repeated messages or not a real reshare
3215 if (!empty($reshared['comment']) || !in_array($reshared['post']['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
3220 'root_handle' => strtolower($reshared['post']['author-addr']),
3221 'root_guid' => $reshared['post']['guid'],
3226 * Create an event array
3228 * @param integer $event_id The id of the event
3230 * @return array with event data
3231 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3233 private static function buildEvent(string $event_id): array
3235 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
3236 if (!DBA::isResult($event)) {
3242 $owner = User::getOwnerDataById($event['uid']);
3247 $eventdata['author'] = self::myHandle($owner);
3249 if ($event['guid']) {
3250 $eventdata['guid'] = $event['guid'];
3253 $mask = DateTimeFormat::ATOM;
3255 /// @todo - establish "all day" events in Friendica
3256 $eventdata['all_day'] = 'false';
3258 $eventdata['timezone'] = 'UTC';
3260 if ($event['start']) {
3261 $eventdata['start'] = DateTimeFormat::utc($event['start'], $mask);
3263 if ($event['finish'] && !$event['nofinish']) {
3264 $eventdata['end'] = DateTimeFormat::utc($event['finish'], $mask);
3266 if ($event['summary']) {
3267 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3269 if ($event['desc']) {
3270 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3272 if ($event['location']) {
3273 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3274 $coord = Map::getCoordinates($event['location']);
3277 $location['address'] = html_entity_decode(BBCode::toMarkdown($event['location']));
3278 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3279 $location['lat'] = $coord['lat'];
3280 $location['lng'] = $coord['lon'];
3282 $location['lat'] = 0;
3283 $location['lng'] = 0;
3285 $eventdata['location'] = $location;
3292 * Create a post (status message or reshare)
3294 * @param array $item The item that will be exported
3295 * @param array $owner the array of the item owner
3298 * 'type' -> Message type ("status_message" or "reshare")
3299 * 'message' -> Array of XML elements of the status
3300 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3301 * @throws \ImagickException
3303 public static function buildStatus(array $item, array $owner)
3305 $cachekey = 'diaspora:buildStatus:' . $item['guid'];
3307 $result = DI::cache()->get($cachekey);
3308 if (!is_null($result)) {
3312 $myaddr = self::myHandle($owner);
3314 $public = ($item['private'] == Item::PRIVATE ? 'false' : 'true');
3315 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3316 $edited = DateTimeFormat::utc($item['edited'] ?? $item['created'], DateTimeFormat::ATOM);
3318 // Detect a share element and do a reshare
3319 if (($item['private'] != Item::PRIVATE) && ($ret = self::getReshareDetails($item))) {
3321 'author' => $myaddr,
3322 'guid' => $item['guid'],
3323 'created_at' => $created,
3324 'root_author' => $ret['root_handle'],
3325 'root_guid' => $ret['root_guid'],
3326 'provider_display_name' => $item['app'],
3332 $native_photos = DI::config()->get('diaspora', 'native_photos');
3333 if ($native_photos) {
3334 $item['body'] = Post\Media::removeFromEndOfBody($item['body']);
3335 $attach_media = [Post\Media::AUDIO, Post\Media::VIDEO];
3337 $attach_media = [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO];
3340 $title = $item['title'];
3341 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item), $attach_media);
3342 $body = Post\Media::addHTMLLinkToBody($item['uri-id'], $body);
3344 // Fetch the title from an attached link - if there is one
3345 if (empty($item['title']) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3346 $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
3347 if (!empty($media) && !empty($media[0]['name']) && ($media[0]['name'] != $media[0]['url'])) {
3348 $title = $media[0]['name'];
3352 // convert to markdown
3353 $body = html_entity_decode(BBCode::toMarkdown($body));
3356 if (strlen($title)) {
3357 $body = '### ' . html_entity_decode($title) . "\n\n" . $body;
3360 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT]);
3361 if (!empty($attachments)) {
3362 $body .= "\n[hr]\n";
3363 foreach ($attachments as $attachment) {
3364 $body .= "[" . $attachment['description'] . "](" . $attachment['url'] . ")\n";
3370 if ($item['location'] != '')
3371 $location['address'] = $item['location'];
3373 if ($item['coord'] != '') {
3374 $coord = explode(' ', $item['coord']);
3375 $location['lat'] = $coord[0];
3376 $location['lng'] = $coord[1];
3380 'author' => $myaddr,
3381 'guid' => $item['guid'],
3382 'created_at' => $created,
3383 'edited_at' => $edited,
3384 'public' => $public,
3386 'provider_display_name' => $item['app'],
3387 'location' => $location
3390 if ($native_photos) {
3391 $message = self::addPhotos($item, $message);
3394 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3395 if (!isset($location['lat']) || !isset($location['lng'])) {
3396 unset($message['location']);
3399 if ($item['event-id'] > 0) {
3400 $event = self::buildEvent($item['event-id']);
3401 if (count($event)) {
3402 $message['event'] = $event;
3405 !empty($event['location']['address']) &&
3406 !empty($event['location']['lat']) &&
3407 !empty($event['location']['lng'])
3409 $message['location'] = $event['location'];
3412 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3413 // $message['text'] = '';
3417 $type = 'status_message';
3422 'message' => $message
3425 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3431 * Add photo elements to the message array
3433 * @param array $item
3434 * @param array $message
3437 private static function addPhotos(array $item, array $message): array
3439 $medias = Post\Media::getByURIId($item['uri-id'], [Post\Media::IMAGE]);
3440 $public = ($item['private'] == Item::PRIVATE ? 'false' : 'true');
3443 foreach ($medias as $media) {
3444 if (Item::containsLink($item['body'], $media['preview'] ?? $media['url'], $media['type'])) {
3448 $name = basename($media['url']);
3449 $path = str_replace($name, '', $media['url']);
3451 $message[++$counter . ':photo'] = [
3452 'guid' => Item::guid(['uri' => $media['url']], false),
3453 'author' => $item['author-addr'],
3454 'public' => $public,
3455 'created_at' => $item['created'],
3456 'remote_photo_path' => $path,
3457 'remote_photo_name' => $name,
3458 'status_message_guid' => $item['guid'],
3459 'height' => $media['height'],
3460 'width' => $media['width'],
3461 'text' => $media['description'],
3468 private static function prependParentAuthorMention(string $body, string $profile_url): string
3470 $profile = Contact::getByURL($profile_url, false, ['addr', 'name']);
3472 !empty($profile['addr'])
3473 && !strstr($body, $profile['addr'])
3474 && !strstr($body, $profile_url)
3476 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3485 * @param array $item The item that will be exported
3486 * @param array $owner the array of the item owner
3487 * @param array $contact Target of the communication
3488 * @param bool $public_batch Is it a public post?
3490 * @return int The result of the transmission
3491 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3492 * @throws \ImagickException
3494 public static function sendStatus(array $item, array $owner, array $contact, bool $public_batch = false): int
3496 $status = self::buildStatus($item, $owner);
3498 return self::buildAndTransmit($owner, $contact, $status['type'], $status['message'], $public_batch, $item['guid']);
3502 * Creates a "like" object
3504 * @param array $item The item that will be exported
3505 * @param array $owner the array of the item owner
3507 * @return array|bool The data for a "like" or false on error
3508 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3510 private static function constructLike(array $item, array $owner)
3512 $parent = Post::selectFirst(['guid', 'uri', 'thr-parent'], ['uri' => $item['thr-parent']]);
3513 if (!DBA::isResult($parent)) {
3517 $target_type = ($parent['uri'] === $parent['thr-parent'] ? 'Post' : 'Comment');
3519 if ($item['verb'] === Activity::LIKE) {
3521 } elseif ($item['verb'] === Activity::DISLIKE) {
3522 $positive = 'false';
3526 'author' => self::myHandle($owner),
3527 'guid' => $item['guid'],
3528 'parent_guid' => $parent['guid'],
3529 'parent_type' => $target_type,
3530 'positive' => $positive,
3531 'author_signature' => '',
3536 * Creates an "EventParticipation" object
3538 * @param array $item The item that will be exported
3539 * @param array $owner the array of the item owner
3541 * @return array|bool The data for an "EventParticipation" or false on error
3542 * @throws \Exception
3544 private static function constructAttend(array $item, array $owner)
3546 $parent = Post::selectFirst(['guid'], ['uri' => $item['thr-parent']]);
3547 if (!DBA::isResult($parent)) {
3551 switch ($item['verb']) {
3552 case Activity::ATTEND:
3553 $attend_answer = 'accepted';
3555 case Activity::ATTENDNO:
3556 $attend_answer = 'declined';
3558 case Activity::ATTENDMAYBE:
3559 $attend_answer = 'tentative';
3562 Logger::warning('Unknown verb ' . $item['verb'] . ' in item ' . $item['guid']);
3567 'author' => self::myHandle($owner),
3568 'guid' => $item['guid'],
3569 'parent_guid' => $parent['guid'],
3570 'status' => $attend_answer,
3571 'author_signature' => ''
3576 * Creates the object for a comment
3578 * @param array $item The item that will be exported
3579 * @param array $owner the array of the item owner
3581 * @return array|false The data for a comment
3582 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3584 private static function constructComment(array $item, array $owner)
3586 $cachekey = 'diaspora:constructComment:' . $item['guid'];
3588 $result = DI::cache()->get($cachekey);
3589 if (!is_null($result)) {
3593 $toplevel_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3594 if (!DBA::isResult($toplevel_item)) {
3595 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3599 $thread_parent_item = $toplevel_item;
3600 if ($item['thr-parent'] != $item['parent-uri']) {
3601 $thread_parent_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3604 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
3605 $body = Post\Media::addHTMLLinkToBody($item['uri-id'], $body);
3607 // The replied to autor mention is prepended for clarity if:
3608 // - Item replied isn't yours
3609 // - Item is public or explicit mentions are disabled
3610 // - Implicit mentions are enabled
3612 $item['author-id'] != $thread_parent_item['author-id']
3613 && ($thread_parent_item['gravity'] != Item::GRAVITY_PARENT)
3614 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3615 && !DI::config()->get('system', 'disable_implicit_mentions')
3617 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3620 $text = html_entity_decode(BBCode::toMarkdown($body));
3621 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3622 $edited = DateTimeFormat::utc($item['edited'], DateTimeFormat::ATOM);
3625 'author' => self::myHandle($owner),
3626 'guid' => $item['guid'],
3627 'created_at' => $created,
3628 'edited_at' => $edited,
3629 'parent_guid' => $toplevel_item['guid'],
3631 'author_signature' => '',
3634 // Send the thread parent guid only if it is a threaded comment
3635 if ($item['thr-parent'] != $item['parent-uri']) {
3636 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3639 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3645 * Send a like or a comment
3647 * @param array $item The item that will be exported
3648 * @param array $owner the array of the item owner
3649 * @param array $contact Target of the communication
3650 * @param bool $public_batch Is it a public post?
3652 * @return int The result of the transmission
3653 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3654 * @throws \ImagickException
3656 public static function sendFollowup(array $item, array $owner, array $contact, bool $public_batch = false): int
3658 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3659 $message = self::constructAttend($item, $owner);
3660 $type = 'event_participation';
3661 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3662 $message = self::constructLike($item, $owner);
3664 } elseif (!in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
3665 $message = self::constructComment($item, $owner);
3669 if (empty($message)) {
3673 $message['author_signature'] = self::signature($owner, $message);
3675 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3679 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3681 * @param array $item The item that will be exported
3682 * @param array $owner the array of the item owner
3683 * @param array $contact Target of the communication
3684 * @param bool $public_batch Is it a public post?
3686 * @return int The result of the transmission
3687 * @throws \Exception
3689 public static function sendRelay(array $item, array $owner, array $contact, bool $public_batch = false): int
3691 if ($item['deleted']) {
3692 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3693 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3699 Logger::info('Got relayable data ' . $type . ' for item ' . $item['guid'] . ' (' . $item['id'] . ')');
3701 $msg = json_decode($item['signed_text'] ?? '', true);
3704 if (is_array($msg)) {
3705 foreach ($msg as $field => $data) {
3706 if (!$item['deleted']) {
3707 if ($field == 'diaspora_handle') {
3710 if ($field == 'target_type') {
3711 $field = 'parent_type';
3715 $message[$field] = $data;
3718 Logger::info('Signature text for item ' . $item['guid'] . ' (' . $item['id'] . ') could not be extracted: ' . $item['signed_text']);
3721 $message['parent_author_signature'] = self::signature($owner, $message);
3723 Logger::info('Relayed data', ['msg' => $message]);
3725 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3729 * Sends a retraction (deletion) of a message, like or comment
3731 * @param array $item The item that will be exported
3732 * @param array $owner the array of the item owner
3733 * @param array $contact Target of the communication
3734 * @param bool $public_batch Is it a public post?
3735 * @param bool $relay Is the retraction transmitted from a relay?
3737 * @return int The result of the transmission
3738 * @throws \Exception
3740 public static function sendRetraction(array $item, array $owner, array $contact, bool $public_batch = false, bool $relay = false): int
3742 $itemaddr = strtolower($item['author-addr']);
3744 $msg_type = 'retraction';
3746 if ($item['gravity'] == Item::GRAVITY_PARENT) {
3747 $target_type = 'Post';
3748 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3749 $target_type = 'Like';
3751 $target_type = 'Comment';
3755 'author' => $itemaddr,
3756 'target_guid' => $item['guid'],
3757 'target_type' => $target_type
3760 Logger::info('Got message', ['msg' => $message]);
3762 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item['guid']);
3768 * @param array $item The item that will be exported
3769 * @param array $owner The owner
3770 * @param array $contact Target of the communication
3772 * @return int The result of the transmission
3773 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3774 * @throws \ImagickException
3776 public static function sendMail(array $item, array $owner, array $contact): int
3778 $myaddr = self::myHandle($owner);
3780 $cnv = DBA::selectFirst('conv', [], ['id' => $item['convid'], 'uid' => $item['uid']]);
3781 if (!DBA::isResult($cnv)) {
3782 Logger::notice('Conversation not found.');
3786 $body = BBCode::toMarkdown($item['body']);
3787 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3790 'author' => $myaddr,
3791 'guid' => $item['guid'],
3792 'conversation_guid' => $cnv['guid'],
3794 'created_at' => $created,
3797 if ($item['reply']) {
3802 'author' => $cnv['creator'],
3803 'guid' => $cnv['guid'],
3804 'subject' => $cnv['subject'],
3805 'created_at' => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3806 'participants' => $cnv['recips'],
3810 $type = 'conversation';
3813 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item['guid']);
3817 * Split a name into first name and last name
3819 * @param string $name The name
3821 * @return array The array with "first" and "last"
3823 public static function splitName(string $name): array
3825 $name = trim($name);
3827 // Is the name longer than 64 characters? Then cut the rest of it.
3828 if (strlen($name) > 64) {
3829 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3830 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3832 $name = substr($name, 0, 64);
3836 // Take the first word as first name
3837 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3838 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3839 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3840 return ['first' => $first, 'last' => $last];
3843 // Take the last word as last name
3844 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3845 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3847 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3848 return ['first' => $first, 'last' => $last];
3851 // Take the first 32 characters if there is no space in the first 32 characters
3852 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3853 $first = substr($name, 0, 32);
3854 $last = substr($name, 32);
3855 return ['first' => $first, 'last' => $last];
3858 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3859 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3861 // Check if the last name is longer than 32 characters
3862 if (strlen($last) > 32) {
3863 if (strpos($last, ' ') <= 32) {
3864 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
3866 $last = substr($last, 0, 32);
3870 return ['first' => $first, 'last' => $last];
3874 * Create profile data
3876 * @param int $uid The user id
3878 * @return array The profile data
3879 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3881 private static function createProfileData(int $uid): array
3883 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
3885 if (!DBA::isResult($profile)) {
3889 $split_name = self::splitName($profile['name']);
3892 'author' => $profile['addr'],
3893 'first_name' => $split_name['first'],
3894 'last_name' => $split_name['last'],
3895 'image_url' => DI::baseUrl() . '/photo/custom/300/' . $profile['uid'] . '.jpg',
3896 'image_url_medium' => DI::baseUrl() . '/photo/custom/100/' . $profile['uid'] . '.jpg',
3897 'image_url_small' => DI::baseUrl() . '/photo/custom/50/' . $profile['uid'] . '.jpg',
3898 'searchable' => ($profile['net-publish'] ? 'true' : 'false'),
3902 'tag_string' => null,
3906 if ($data['searchable'] === 'true') {
3907 $data['birthday'] = '';
3909 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
3910 [$year, $month, $day] = sscanf($profile['dob'], '%4d-%2d-%2d');
3914 $data['birthday'] = DateTimeFormat::utc($year . '-' . $month . '-' . $day, 'Y-m-d');
3917 $data['about'] = BBCode::toMarkdown($profile['about'] ?? '');
3919 $data['location'] = $profile['location'];
3920 $data['tag_string'] = '';
3922 if ($profile['pub_keywords']) {
3923 $kw = str_replace(',', ' ', $profile['pub_keywords']);
3924 $kw = str_replace(' ', ' ', $kw);
3925 $arr = explode(' ', $kw);
3927 for ($x = 0; $x < 5; $x++) {
3928 if (!empty($arr[$x])) {
3929 $data['tag_string'] .= '#' . trim($arr[$x]) . ' ';
3934 $data['tag_string'] = trim($data['tag_string']);
3941 * Sends profile data
3943 * @param int $uid The user id
3944 * @param array $recipients optional, default empty array
3947 * @throws \Exception
3949 public static function sendProfile(int $uid, array $recipients = [])
3952 Logger::warning('Parameter "uid" is empty');
3956 $owner = User::getOwnerDataById($uid);
3957 if (empty($owner)) {
3958 Logger::warning('Cannot fetch User record', ['uid' => $uid]);
3962 if (empty($recipients)) {
3963 Logger::debug('No recipients provided, fetching for user', ['uid' => $uid]);
3964 $recipients = DBA::selectToArray('contact', [], ['network' => Protocol::DIASPORA, 'uid' => $uid, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
3967 if (empty($recipients)) {
3968 Logger::warning('Cannot fetch recipients', ['uid' => $uid]);
3972 $message = self::createProfileData($uid);
3974 // @todo Split this into single worker jobs
3975 foreach ($recipients as $recipient) {
3976 Logger::info('Send updated profile data for user ' . $uid . ' to contact ' . $recipient['id']);
3977 self::buildAndTransmit($owner, $recipient, 'profile', $message);
3982 * Creates the signature for likes that are created on our system
3984 * @param integer $uid The user of that comment
3985 * @param array $item Item array
3987 * @return array|bool Signed content or false on error
3988 * @throws \Exception
3990 public static function createLikeSignature(int $uid, array $item)
3992 $owner = User::getOwnerDataById($uid);
3993 if (empty($owner)) {
3994 Logger::info('No owner post, so not storing signature', ['uid' => $uid]);
3998 if (!in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3999 Logger::warning('Item is neither a like nor a dislike', ['uid' => $uid, 'item[verb]' => $item['verb']]);;
4003 $message = self::constructLike($item, $owner);
4004 if ($message === false) {
4008 $message['author_signature'] = self::signature($owner, $message);
4014 * Creates the signature for Comments that are created on our system
4016 * @param array $item Item array
4018 * @return array|bool Signed content or false on error
4019 * @throws \Exception
4021 public static function createCommentSignature(array $item)
4024 if (!empty($item['author-link'])) {
4025 $url = $item['author-link'];
4027 $contact = Contact::getById($item['author-id'], ['url']);
4028 if (empty($contact['url'])) {
4029 Logger::warning('Author Contact not found', ['author-id' => $item['author-id']]);
4032 $url = $contact['url'];
4035 $uid = User::getIdForURL($url);
4037 Logger::info('No owner post, so not storing signature', ['url' => $contact['url'] ?? 'No contact loaded']);
4041 $owner = User::getOwnerDataById($uid);
4042 if (empty($owner)) {
4043 Logger::info('No owner post, so not storing signature');
4047 // This is only needed for the automated tests
4048 if (empty($owner['uprvkey'])) {
4052 if (!self::parentSupportDiaspora($item['thr-parent-id'])) {
4053 Logger::info('One of the parents does not support Diaspora. A signature will not be created.', ['uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
4057 $message = self::constructComment($item, $owner);
4058 if ($message === false) {
4062 $message['author_signature'] = self::signature($owner, $message);
4068 * Check if the parent and their parents support Diaspora
4070 * @param integer $parent_id
4072 * @throws InternalServerErrorException
4073 * @throws \ImagickException
4075 private static function parentSupportDiaspora(int $parent_id): bool
4077 $parent_post = Post::selectFirstPost(['gravity', 'signed_text', 'author-link', 'thr-parent-id'], ['uri-id' => $parent_id]);
4078 if (empty($parent_post['thr-parent-id'])) {
4079 Logger::warning('Parent post does not exist.', ['parent-id' => $parent_id]);
4083 if (!self::isSupportedByContactUrl($parent_post['author-link'])) {
4084 Logger::info('Parent author is no Diaspora contact.', ['parent-id' => $parent_id]);
4088 if (($parent_post['gravity'] == Item::GRAVITY_COMMENT) && empty($parent_post['signed_text'])) {
4089 Logger::info('Parent comment has got no Diaspora signature.', ['parent-id' => $parent_id]);
4093 if ($parent_post['gravity'] == Item::GRAVITY_COMMENT) {
4094 return self::parentSupportDiaspora($parent_post['thr-parent-id']);
4100 public static function performReshare(int $UriId, int $uid): int
4102 $owner = User::getOwnerDataById($uid);
4103 $author = Contact::getPublicIdByUserId($uid);
4107 'verb' => Activity::POST,
4108 'contact-id' => $owner['id'],
4109 'author-id' => $author,
4110 'owner-id' => $author,
4112 'quote-uri-id' => $UriId,
4113 'allow_cid' => $owner['allow_cid'] ?? '',
4114 'allow_gid' => $owner['allow_gid'] ?? '',
4115 'deny_cid' => $owner['deny_cid'] ?? '',
4116 'deny_gid' => $owner['deny_gid'] ?? '',
4119 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
4120 $item['private'] = Item::PRIVATE;
4121 } elseif (DI::pConfig()->get($uid, 'system', 'unlisted')) {
4122 $item['private'] = Item::UNLISTED;
4124 $item['private'] = Item::PUBLIC;
4127 // Don't trigger the addons
4128 $item['api_source'] = false;
4130 return Item::insert($item, true);