3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol;
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\Markdown;
27 use Friendica\Core\Cache\Enum\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\FContact;
37 use Friendica\Model\GServer;
38 use Friendica\Model\Item;
39 use Friendica\Model\ItemURI;
40 use Friendica\Model\Mail;
41 use Friendica\Model\Post;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
45 use Friendica\Network\Probe;
46 use Friendica\Util\Crypto;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Map;
49 use Friendica\Util\Network;
50 use Friendica\Util\Strings;
51 use Friendica\Util\XML;
52 use Friendica\Worker\Delivery;
53 use GuzzleHttp\Psr7\Uri;
57 * This class contain functions to create and send Diaspora XML files
63 const FORCED_FETCH = 2;
66 * Return a list of participating contacts for a thread
68 * This is used for the participation feature.
69 * One of the parameters is a contact array.
70 * This is done to avoid duplicates.
72 * @param array $item Item that is about to be delivered
73 * @param array $contacts The previously fetched contacts
75 * @return array of relay servers
78 public static function participantsForThread(array $item, array $contacts): array
80 if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
81 Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]);
85 $items = Post::select(['author-id', 'author-link', 'parent-author-link', 'parent-guid', 'guid'],
86 ['parent' => $item['parent'], 'gravity' => [Item::GRAVITY_COMMENT, Item::GRAVITY_ACTIVITY]]);
87 while ($item = Post::fetch($items)) {
88 $contact = DBA::selectFirst('contact', ['id', 'url', 'name', 'protocol', 'batch', 'network'],
89 ['id' => $item['author-id']]);
90 if (!DBA::isResult($contact) || empty($contact['batch']) ||
91 ($contact['network'] != Protocol::DIASPORA) ||
92 Strings::compareLink($item['parent-author-link'], $item['author-link'])) {
97 foreach ($contacts as $entry) {
98 if ($entry['batch'] == $contact['batch']) {
104 Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]);
105 $contacts[] = $contact;
114 * verify the envelope and return the verified data
116 * @param string $envelope The magic envelope
118 * @return string|bool verified data or false on error
119 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
120 * @throws \ImagickException
122 private static function verifyMagicEnvelope(string $envelope)
124 $basedom = XML::parseString($envelope, true);
126 if (!is_object($basedom)) {
127 Logger::notice('Envelope is no XML file');
131 $children = $basedom->children(ActivityNamespace::SALMON_ME);
133 if (sizeof($children) == 0) {
134 Logger::notice('XML has no children');
140 $data = Strings::base64UrlDecode($children->data);
141 $type = $children->data->attributes()->type[0];
143 $encoding = $children->encoding;
145 $alg = $children->alg;
147 $sig = Strings::base64UrlDecode($children->sig);
148 $key_id = $children->sig->attributes()->key_id[0];
150 $handle = Strings::base64UrlDecode($key_id);
153 $b64url_data = Strings::base64UrlEncode($data);
154 $msg = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
156 $signable_data = $msg . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
159 Logger::notice('No author could be decoded. Discarding. Message: ' . $envelope);
163 $key = self::key($handle);
165 Logger::notice("Couldn't get a key for handle " . $handle . ". Discarding.");
169 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
171 Logger::notice('Message from ' . $handle . ' did not verify. Discarding.');
179 * encrypts data via AES
181 * @param string $key The AES key
182 * @param string $iv The IV (is used for CBC encoding)
183 * @param string $data The data that is to be encrypted
185 * @return string encrypted data
187 private static function aesEncrypt(string $key, string $iv, string $data): string
189 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
193 * decrypts data via AES
195 * @param string $key The AES key
196 * @param string $iv The IV (is used for CBC encoding)
197 * @param string $encrypted The encrypted data
199 * @return string decrypted data
201 private static function aesDecrypt(string $key, string $iv, string $encrypted): string
203 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
207 * Decodes incoming Diaspora message in the new format. This method returns false on an error.
209 * @param string $raw raw post message
210 * @param string $privKey The private key of the importer
211 * @param boolean $no_exit Don't do an http exit on error
214 * 'message' -> decoded Diaspora XML message
215 * 'author' -> author diaspora handle
216 * 'key' -> author public key (converted to pkcs#8)
217 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
218 * @throws \ImagickException
220 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
222 $data = json_decode($raw);
224 // Is it a private post? Then decrypt the outer Salmon
225 if (is_object($data)) {
226 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
227 $ciphertext = base64_decode($data->encrypted_magic_envelope);
229 $outer_key_bundle = '';
230 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
231 $j_outer_key_bundle = json_decode($outer_key_bundle);
233 if (!is_object($j_outer_key_bundle)) {
234 Logger::notice('Outer Salmon did not verify. Discarding.');
238 throw new \Friendica\Network\HTTPException\BadRequestException();
242 $outer_iv = base64_decode($j_outer_key_bundle->iv);
243 $outer_key = base64_decode($j_outer_key_bundle->key);
245 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
250 $basedom = XML::parseString($xml, true);
252 if (!is_object($basedom)) {
253 Logger::notice('Received data does not seem to be an XML. Discarding. '.$xml);
257 throw new \Friendica\Network\HTTPException\BadRequestException();
261 $base = $basedom->children(ActivityNamespace::SALMON_ME);
263 // Not sure if this cleaning is needed
264 $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
266 // Build the signed data
267 $type = $base->data[0]->attributes()->type[0];
268 $encoding = $base->encoding;
270 $signed_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
272 // This is the signature
273 $signature = Strings::base64UrlDecode($base->sig);
275 // Get the senders' public key
276 $key_id = $base->sig[0]->attributes()->key_id[0];
277 $author_addr = base64_decode($key_id);
278 if ($author_addr == '') {
279 Logger::notice('No author could be decoded. Discarding. Message: ' . $xml);
283 throw new \Friendica\Network\HTTPException\BadRequestException();
287 $key = self::key($author_addr);
289 Logger::notice("Couldn't get a key for handle " . $author_addr . ". Discarding.");
293 throw new \Friendica\Network\HTTPException\BadRequestException();
297 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
299 Logger::notice('Message did not verify. Discarding.');
303 throw new \Friendica\Network\HTTPException\BadRequestException();
308 'message' => (string)Strings::base64UrlDecode($base->data),
309 'author' => XML::unescape($author_addr),
310 'key' => (string)$key
315 * Decodes incoming Diaspora message in the deprecated format
317 * @param string $xml urldecoded Diaspora salmon
318 * @param string $privKey The private key of the importer
321 * 'message' -> decoded Diaspora XML message
322 * 'author' -> author diaspora handle
323 * 'key' -> author public key (converted to pkcs#8)
324 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
325 * @throws \ImagickException
327 public static function decode(string $xml, string $privKey = '')
330 $basedom = XML::parseString($xml);
332 if (!is_object($basedom)) {
333 Logger::notice('XML is not parseable.');
336 $children = $basedom->children('https://joindiaspora.com/protocol');
338 $inner_aes_key = null;
341 if ($children->header) {
343 $author_link = str_replace('acct:', '', $children->header->author_id);
345 // This happens with posts from a relais
346 if (empty($privKey)) {
347 Logger::info('This is no private post in the old format');
351 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
353 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
354 $ciphertext = base64_decode($encrypted_header->ciphertext);
356 $outer_key_bundle = '';
357 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
359 $j_outer_key_bundle = json_decode($outer_key_bundle);
361 $outer_iv = base64_decode($j_outer_key_bundle->iv);
362 $outer_key = base64_decode($j_outer_key_bundle->key);
364 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
366 Logger::info('decrypted', ['data' => $decrypted]);
367 $idom = XML::parseString($decrypted);
369 $inner_iv = base64_decode($idom->iv);
370 $inner_aes_key = base64_decode($idom->aes_key);
372 $author_link = str_replace('acct:', '', $idom->author_id);
375 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
377 // figure out where in the DOM tree our data is hiding
380 if ($dom->provenance->data) {
381 $base = $dom->provenance;
382 } elseif ($dom->env->data) {
384 } elseif ($dom->data) {
389 Logger::notice('unable to locate salmon data in xml');
390 throw new \Friendica\Network\HTTPException\BadRequestException();
394 // Stash the signature away for now. We have to find their key or it won't be good for anything.
395 $signature = Strings::base64UrlDecode($base->sig);
399 // strip whitespace so our data element will return to one big base64 blob
400 $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
403 // stash away some other stuff for later
405 $type = $base->data[0]->attributes()->type[0];
406 $keyhash = $base->sig[0]->attributes()->keyhash[0];
407 $encoding = $base->encoding;
411 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
415 $data = Strings::base64UrlDecode($data);
419 $inner_decrypted = $data;
421 // Decode the encrypted blob
422 $inner_encrypted = base64_decode($data);
423 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
427 Logger::notice('Could not retrieve author URI.');
428 throw new \Friendica\Network\HTTPException\BadRequestException();
430 // Once we have the author URI, go to the web and try to find their public key
431 // (first this will look it up locally if it is in the fcontact cache)
432 // This will also convert diaspora public key from pkcs#1 to pkcs#8
434 Logger::notice('Fetching key for '.$author_link);
435 $key = self::key($author_link);
438 Logger::notice('Could not retrieve author key.');
439 throw new \Friendica\Network\HTTPException\BadRequestException();
442 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
445 Logger::notice('Message did not verify. Discarding.');
446 throw new \Friendica\Network\HTTPException\BadRequestException();
449 Logger::notice('Message verified.');
452 'message' => (string)$inner_decrypted,
453 'author' => XML::unescape($author_link),
454 'key' => (string)$key
460 * Dispatches public messages and find the fitting receivers
462 * @param array $msg The post that will be dispatched
463 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
465 * @return int|bool The message id of the generated message, "true" or "false" if there was an error
466 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
467 * @throws \ImagickException
469 public static function dispatchPublic(array $msg, int $direction)
471 $enabled = intval(DI::config()->get('system', 'diaspora_enabled'));
473 Logger::notice('Diaspora is disabled');
477 if (!($fields = self::validPosting($msg))) {
478 Logger::warning('Invalid posting');
484 'page-flags' => User::PAGE_FLAGS_FREELOVE
486 $success = self::dispatch($importer, $msg, $fields, $direction);
492 * Dispatches the different message types to the different functions
494 * @param array $importer Array of the importer user
495 * @param array $msg The post that will be dispatched
496 * @param SimpleXMLElement $fields SimpleXML object that contains the message
497 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
499 * @return int|bool The message id of the generated message, "true" or "false" if there was an error
500 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
501 * @throws \ImagickException
503 public static function dispatch(array $importer, array $msg, SimpleXMLElement $fields = null, int $direction = self::PUSHED)
505 // The sender is the handle of the contact that sent the message.
506 // This will often be different with relayed messages (for example "like" and "comment")
507 $sender = $msg['author'];
509 // This is only needed for private postings since this is already done for public ones before
510 if (is_null($fields)) {
512 if (!($fields = self::validPosting($msg))) {
513 Logger::warning('Invalid posting');
520 $type = $fields->getName();
522 Logger::info('Received message', ['type' => $type, 'sender' => $sender, 'user' => $importer['uid']]);
525 case 'account_migration':
527 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
530 return self::receiveAccountMigration($importer, $fields);
532 case 'account_deletion':
533 return self::receiveAccountDeletion($fields);
536 return self::receiveComment($importer, $sender, $fields, $msg['message'], $direction);
540 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
543 return self::receiveContactRequest($importer, $fields);
547 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
550 return self::receiveConversation($importer, $msg, $fields);
553 return self::receiveLike($importer, $sender, $fields, $direction);
557 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
560 return self::receiveMessage($importer, $fields);
562 case 'participation':
564 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
567 return self::receiveParticipation($importer, $fields, $direction);
569 case 'photo': // Not implemented
570 return self::receivePhoto($importer, $fields);
572 case 'poll_participation': // Not implemented
573 return self::receivePollParticipation($importer, $fields);
577 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
580 return self::receiveProfile($importer, $fields);
583 return self::receiveReshare($importer, $fields, $msg['message'], $direction);
586 return self::receiveRetraction($importer, $sender, $fields);
588 case 'status_message':
589 return self::receiveStatusMessage($importer, $fields, $msg['message'], $direction);
592 Logger::notice('Unknown message type ' . $type);
598 * Checks if a posting is valid and fetches the data fields.
600 * This function does not only check the signature.
601 * It also does the conversion between the old and the new diaspora format.
603 * @param array $msg Array with the XML, the sender handle and the sender signature
605 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
606 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
607 * @throws \ImagickException
609 private static function validPosting(array $msg)
611 $data = XML::parseString($msg['message']);
613 if (!is_object($data)) {
614 Logger::info('No valid XML', ['message' => $msg['message']]);
618 // Is this the new or the old version?
619 if ($data->getName() == 'XML') {
621 foreach ($data->post->children() as $child) {
629 $type = $element->getName();
632 Logger::debug('Got message', ['type' => $type, 'message' => $msg['message']]);
634 // All retractions are handled identically from now on.
635 // In the new version there will only be "retraction".
636 if (in_array($type, ['signed_retraction', 'relayable_retraction']))
637 $type = 'retraction';
639 if ($type == 'request') {
643 $fields = new SimpleXMLElement('<' . $type . '/>');
646 $author_signature = null;
647 $parent_author_signature = null;
649 foreach ($element->children() as $fieldname => $entry) {
651 // Translation for the old XML structure
652 if ($fieldname == 'diaspora_handle') {
653 $fieldname = 'author';
655 if ($fieldname == 'participant_handles') {
656 $fieldname = 'participants';
658 if (in_array($type, ['like', 'participation'])) {
659 if ($fieldname == 'target_type') {
660 $fieldname = 'parent_type';
663 if ($fieldname == 'sender_handle') {
664 $fieldname = 'author';
666 if ($fieldname == 'recipient_handle') {
667 $fieldname = 'recipient';
669 if ($fieldname == 'root_diaspora_id') {
670 $fieldname = 'root_author';
672 if ($type == 'status_message') {
673 if ($fieldname == 'raw_message') {
677 if ($type == 'retraction') {
678 if ($fieldname == 'post_guid') {
679 $fieldname = 'target_guid';
681 if ($fieldname == 'type') {
682 $fieldname = 'target_type';
687 if (($fieldname == 'author_signature') && ($entry != '')) {
688 $author_signature = base64_decode($entry);
689 } elseif (($fieldname == 'parent_author_signature') && ($entry != '')) {
690 $parent_author_signature = base64_decode($entry);
691 } elseif (!in_array($fieldname, ['author_signature', 'parent_author_signature', 'target_author_signature'])) {
692 if ($signed_data != '') {
696 $signed_data .= $entry;
698 if (!in_array($fieldname, ['parent_author_signature', 'target_author_signature'])
699 || ($orig_type == 'relayable_retraction')
701 XML::copy($entry, $fields, $fieldname);
705 // This is something that shouldn't happen at all.
706 if (in_array($type, ['status_message', 'reshare', 'profile'])) {
707 if ($msg['author'] != $fields->author) {
708 Logger::notice('Message handle is not the same as envelope sender. Quitting this message.', ['author1' => $msg['author'], 'author2' => $fields->author]);
713 // Only some message types have signatures. So we quit here for the other types.
714 if (!in_array($type, ['comment', 'like'])) {
718 if (!isset($author_signature) && ($msg['author'] == $fields->author)) {
719 Logger::debug('No author signature, but the sender matches the author', ['type' => $type, 'msg-author' => $msg['author'], 'message' => $msg['message']]);
723 // No author_signature? This is a must, so we quit.
724 if (!isset($author_signature)) {
725 Logger::info('No author signature', ['type' => $type, 'msg-author' => $msg['author'], 'fields-author' => $fields->author, 'message' => $msg['message']]);
729 if (isset($parent_author_signature)) {
730 $key = self::key($msg['author']);
732 Logger::info('No key found for parent', ['author' => $msg['author']]);
736 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, 'sha256')) {
737 Logger::info('No valid parent author signature', ['author' => $msg['author'], 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $parent_author_signature]);
742 $key = self::key($fields->author);
744 Logger::info('No key found', ['author' => $fields->author]);
748 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, 'sha256')) {
749 Logger::info('No valid author signature for author', ['author' => $fields->author, 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $author_signature]);
757 * Fetches the public key for a given handle
759 * @param string $handle The handle
761 * @return string The public key
762 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
763 * @throws \ImagickException
765 private static function key(string $handle = null): string
767 $handle = strval($handle);
769 Logger::notice('Fetching diaspora key', ['handle' => $handle, 'callstack' => System::callstack(20)]);
771 $fcontact = FContact::getByURL($handle);
772 if (!empty($fcontact['pubkey'])) {
773 return $fcontact['pubkey'];
780 * Get a contact id for a given handle
782 * @todo Move to Friendica\Model\Contact
784 * @param int $uid The user id
785 * @param string $handle The handle in the format user@domain.tld
787 * @return array Contact data
788 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
789 * @throws \ImagickException
791 private static function contactByHandle(int $uid, string $handle): array
793 return Contact::getByURL($handle, null, [], $uid);
797 * Checks if the given contact url does support ActivityPub
799 * @param string $url profile url
800 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
802 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
803 * @throws \ImagickException
805 public static function isSupportedByContactUrl(string $url, $update = null)
807 return !empty(FContact::getByURL($url, $update));
811 * Check if posting is allowed for this contact
813 * @param array $importer Array of the importer user
814 * @param array $contact The contact that is checked
815 * @param bool $is_comment Is the check for a comment?
817 * @return bool is the contact allowed to post?
819 private static function postAllow(array $importer, array $contact, bool $is_comment = false): bool
822 * Perhaps we were already sharing with this person. Now they're sharing with us.
823 * That makes us friends.
824 * Normally this should have handled by getting a request - but this could get lost
826 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
827 // It is not removed by now. Possibly the code is needed?
828 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
830 // array('rel' => Contact::FRIEND, 'writable' => true),
831 // array('id' => $contact["id"], 'uid' => $contact["uid"])
834 // $contact["rel"] = Contact::FRIEND;
835 // Logger::notice("defining user ".$contact["nick"]." as friend");
838 // Contact server is blocked
839 if (Network::isUrlBlocked($contact['url'])) {
841 // We don't seem to like that person
842 } elseif ($contact['blocked']) {
843 // Maybe blocked, don't accept.
845 // We are following this person?
846 } elseif (($contact['rel'] == Contact::SHARING) || ($contact['rel'] == Contact::FRIEND)) {
847 // Yes, then it is fine.
849 // Is the message a global user or a comment?
850 } elseif (($importer['uid'] == 0) || $is_comment) {
851 // Messages for the global users and comments are always accepted
859 * Fetches the contact id for a handle and checks if posting is allowed
861 * @param array $importer Array of the importer user
862 * @param string $handle The checked handle in the format user@domain.tld
863 * @param bool $is_comment Is the check for a comment?
865 * @return array|bool The contact data or false on error
868 private static function allowedContactByHandle(array $importer, string $handle, bool $is_comment = false)
870 $contact = self::contactByHandle($importer['uid'], $handle);
872 Logger::notice('A Contact for handle ' . $handle . ' and user ' . $importer['uid'] . ' was not found');
873 // If a contact isn't found, we accept it anyway if it is a comment
874 if ($is_comment && ($importer['uid'] != 0)) {
875 return self::contactByHandle(0, $handle);
876 } elseif ($is_comment) {
883 if (!self::postAllow($importer, $contact, $is_comment)) {
884 Logger::notice('The handle: ' . $handle . ' is not allowed to post to user ' . $importer['uid']);
891 * Does the message already exists on the system?
893 * @param int $uid The user id
894 * @param string $guid The guid of the message
896 * @return int|bool message id if the message already was stored into the system - or false.
899 private static function messageExists(int $uid, string $guid)
901 $item = Post::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
902 if (DBA::isResult($item)) {
903 Logger::notice('Message ' . $guid . ' already exists for user ' . $uid);
911 * Checks for links to posts in a message
913 * @param array $item The item array
916 private static function fetchGuid(array $item)
918 preg_replace_callback(
919 "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism",
920 function ($match) use ($item) {
921 self::fetchGuidSub($match, $item);
926 preg_replace_callback(
927 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
928 function ($match) use ($item) {
929 self::fetchGuidSub($match, $item);
936 * Checks for relative /people/* links in an item body to match local
937 * contacts or prepends the remote host taken from the author link.
939 * @param string $body The item body to replace links from
940 * @param string $author_link The author link for missing local contact fallback
942 * @return string the replaced string
944 public static function replacePeopleGuid(string $body, string $author_link): string
946 $return = preg_replace_callback(
947 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
948 function ($match) use ($author_link) {
950 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
951 // 1 => '0123456789abcdef'
953 $handle = FContact::getUrlByGuid($match[1]);
956 $return = '@[url=' . $handle . ']' . $match[2] . '[/url]';
958 // No local match, restoring absolute remote URL from author scheme and host
959 $author_url = parse_url($author_link);
960 $return = '[url=' . $author_url['scheme'] . '://' . $author_url['host'] . '/people/' . $match[1] . ']' . $match[2] . '[/url]';
972 * sub function of "fetchGuid" which checks for links in messages
974 * @param array $match array containing a link that has to be checked for a message link
975 * @param array $item The item array
977 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
978 * @throws \ImagickException
980 private static function fetchGuidSub(array $match, array $item)
982 if (!self::storeByGuid($match[1], $item['author-link'], true)) {
983 self::storeByGuid($match[1], $item['owner-link'], true);
988 * Fetches an item with a given guid from a given server
990 * @param string $guid the message guid
991 * @param string $server The server address
992 * @param bool $force Forced fetch
994 * @return int|bool the message id of the stored message or false
995 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
996 * @throws \ImagickException
998 public static function storeByGuid(string $guid, string $server, bool $force)
1000 $serverparts = parse_url($server);
1002 if (empty($serverparts['host']) || empty($serverparts['scheme'])) {
1006 $server = $serverparts['scheme'] . '://' . $serverparts['host'];
1008 Logger::info('Trying to fetch item ' . $guid . ' from ' . $server);
1010 $msg = self::message($guid, $server);
1016 Logger::info('Successfully fetched item ' . $guid . ' from ' . $server);
1018 // Now call the dispatcher
1019 return self::dispatchPublic($msg, $force ? self::FORCED_FETCH : self::FETCHED);
1023 * Fetches a message from a server
1025 * @param string $guid message guid
1026 * @param string $server The url of the server
1027 * @param int $level Endless loop prevention
1030 * 'message' => The message XML
1031 * 'author' => The author handle
1032 * 'key' => The public key of the author
1033 * @throws \Exception
1035 public static function message(string $guid, string $server, int $level = 0)
1041 // This will work for new Diaspora servers and Friendica servers from 3.5
1042 $source_url = $server . '/fetch/post/' . urlencode($guid);
1044 Logger::info('Fetch post from ' . $source_url);
1046 $envelope = DI::httpClient()->fetch($source_url, HttpClientAccept::MAGIC);
1048 Logger::info('Envelope was fetched.');
1049 $x = self::verifyMagicEnvelope($envelope);
1051 Logger::info('Envelope could not be verified.');
1053 Logger::info('Envelope was verified.');
1063 $source_xml = XML::parseString($x);
1065 if (!is_object($source_xml)) {
1069 if ($source_xml->post->reshare) {
1070 // Reshare of a reshare - old Diaspora version
1071 Logger::info('Message is a reshare');
1072 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1073 } elseif ($source_xml->getName() == 'reshare') {
1074 // Reshare of a reshare - new Diaspora version
1075 Logger::info('Message is a new reshare');
1076 return self::message($source_xml->root_guid, $server, ++$level);
1081 // Fetch the author - for the old and the new Diaspora version
1082 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1083 $author = (string)$source_xml->post->status_message->diaspora_handle;
1084 } elseif ($source_xml->author && ($source_xml->getName() == 'status_message')) {
1085 $author = (string)$source_xml->author;
1088 // If this isn't a "status_message" then quit
1090 Logger::info("Message doesn't seem to be a status message");
1096 'author' => $author,
1097 'key' => self::key($author)
1102 * Fetches an item with a given URL
1104 * @param string $url the message url
1105 * @param int $uid User id
1107 * @return int|bool the message id of the stored message or false
1108 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1109 * @throws \ImagickException
1111 public static function fetchByURL(string $url, int $uid = 0)
1113 // Check for Diaspora (and Friendica) typical paths
1114 if (!preg_match('=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i', $url, $matches)) {
1115 Logger::info('Invalid url', ['url' => $url]);
1119 $guid = urldecode($matches[2]);
1121 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1122 if (DBA::isResult($item)) {
1123 Logger::info('Found', ['id' => $item['id']]);
1127 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1128 $ret = self::storeByGuid($guid, $matches[1], true);
1129 Logger::info('Result', ['ret' => $ret]);
1131 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1132 if (DBA::isResult($item)) {
1133 Logger::info('Found', ['id' => $item['id']]);
1136 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1142 * Fetches the item record of a given guid
1144 * @param int $uid The user id
1145 * @param string $guid message guid
1146 * @param string $author The handle of the item
1147 * @param array $contact The contact of the item owner
1149 * @return array|bool the item record or false on failure
1150 * @throws \Exception
1152 private static function parentItem(int $uid, string $guid, string $author, array $contact)
1154 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1155 'author-name', 'author-link', 'author-avatar', 'gravity',
1156 'owner-name', 'owner-link', 'owner-avatar'];
1158 $condition = ['uid' => $uid, 'guid' => $guid];
1159 $item = Post::selectFirst($fields, $condition);
1161 if (!DBA::isResult($item)) {
1162 $person = FContact::getByURL($author);
1163 $result = self::storeByGuid($guid, $person['url'], false);
1165 // We don't have an url for items that arrived at the public dispatcher
1166 if (!$result && !empty($contact['url'])) {
1167 $result = self::storeByGuid($guid, $contact['url'], false);
1171 Logger::info('Fetched missing item ' . $guid . ' - result: ' . $result);
1173 $item = Post::selectFirst($fields, $condition);
1177 if (!DBA::isResult($item)) {
1178 Logger::notice('Parent item not found: parent: ' . $guid . ' - user: ' . $uid);
1181 Logger::notice('Parent item found: parent: ' . $guid . ' - user: ' . $uid);
1187 * returns contact details
1189 * @param array $def_contact The default contact if the person isn't found
1190 * @param array $person The record of the person
1191 * @param int $uid The user id
1194 * 'cid' => contact id
1195 * 'network' => network type
1196 * @throws \Exception
1198 private static function authorContactByUrl(array $def_contact, array $person, int $uid): array
1200 $condition = ['nurl' => Strings::normaliseLink($person['url']), 'uid' => $uid];
1201 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1202 if (DBA::isResult($contact)) {
1203 $cid = $contact['id'];
1204 $network = $contact['network'];
1206 $cid = $def_contact['id'];
1207 $network = Protocol::DIASPORA;
1212 'network' => $network
1217 * Is the profile a hubzilla profile?
1219 * @param string $url The profile link
1221 * @return bool is it a hubzilla server?
1223 private static function isHubzilla(string $url): bool
1225 return strstr($url, '/channel/');
1229 * Generate a post link with a given handle and message guid
1231 * @param string $addr The user handle
1232 * @param string $guid message guid
1233 * @param string $parent_guid optional parent guid
1235 * @return string the post link
1236 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1237 * @throws \ImagickException
1239 private static function plink(string $addr, string $guid, string $parent_guid = ''): string
1241 $contact = Contact::getByURL($addr);
1242 if (empty($contact)) {
1243 Logger::info('No contact data for address', ['addr' => $addr]);
1247 if (empty($contact['baseurl'])) {
1248 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1249 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1253 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1254 if (!empty($gserver['platform'])) {
1255 $platform = strtolower($gserver['platform']);
1256 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1259 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1260 if (self::isHubzilla($contact['url'])) {
1261 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1262 $platform = 'hubzilla';
1263 } elseif ($contact['network'] == Protocol::DFRN) {
1264 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1265 $platform = 'friendica';
1269 if ($platform == 'friendica') {
1270 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1273 if ($platform == 'hubzilla') {
1274 return $contact['baseurl'] . '/item/' . $guid;
1277 if ($platform == 'socialhome') {
1278 return $contact['baseurl'] . '/content/' . $guid;
1281 if ($platform != 'diaspora') {
1282 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1286 if ($parent_guid != '') {
1287 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1289 return $contact['baseurl'] . '/posts/' . $guid;
1294 * Receives account migration
1296 * @param array $importer Array of the importer user
1297 * @param SimpleXMLElement $data The message object
1299 * @return bool Success
1300 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1301 * @throws \ImagickException
1303 private static function receiveAccountMigration(array $importer, SimpleXMLElement $data): bool
1305 $old_handle = XML::unescape($data->author);
1306 $new_handle = XML::unescape($data->profile->author);
1307 $signature = XML::unescape($data->signature);
1309 $contact = self::contactByHandle($importer['uid'], $old_handle);
1311 Logger::notice('Cannot find contact for sender: ' . $old_handle . ' and user ' . $importer['uid']);
1315 Logger::notice('Got migration for ' . $old_handle . ', to ' . $new_handle . ' with user ' . $importer['uid']);
1318 $signed_text = 'AccountMigration:' . $old_handle . ':' . $new_handle;
1319 $key = self::key($old_handle);
1320 if (!Crypto::rsaVerify($signed_text, $signature, $key, 'sha256')) {
1321 Logger::notice('No valid signature for migration.');
1325 // Update the profile
1326 self::receiveProfile($importer, $data->profile);
1328 // change the technical stuff in contact
1329 $data = Probe::uri($new_handle);
1330 if ($data['network'] == Protocol::PHANTOM) {
1331 Logger::notice("Account for " . $new_handle . " couldn't be probed.");
1336 'url' => $data['url'],
1337 'nurl' => Strings::normaliseLink($data['url']),
1338 'name' => $data['name'],
1339 'nick' => $data['nick'],
1340 'addr' => $data['addr'],
1341 'batch' => $data['batch'],
1342 'notify' => $data['notify'],
1343 'poll' => $data['poll'],
1344 'network' => $data['network'],
1347 Contact::update($fields, ['addr' => $old_handle]);
1349 Logger::notice('Contacts are updated.');
1355 * Processes an account deletion
1357 * @param SimpleXMLElement $data The message object
1359 * @return bool Success
1360 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1362 private static function receiveAccountDeletion(SimpleXMLElement $data): bool
1364 $author = XML::unescape($data->author);
1366 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1367 while ($contact = DBA::fetch($contacts)) {
1368 Contact::remove($contact['id']);
1370 DBA::close($contacts);
1372 Logger::notice('Removed contacts for ' . $author);
1378 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1380 * @param string $author Author handle
1381 * @param string $guid Message guid
1382 * @param boolean $onlyfound Only return uri when found in the database
1384 * @return string The constructed uri or the one from our database or empty string on if $onlyfound is true
1385 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1386 * @throws \ImagickException
1388 private static function getUriFromGuid(string $author, string $guid, bool $onlyfound = false): string
1390 $item = Post::selectFirst(['uri'], ['guid' => $guid]);
1391 if (DBA::isResult($item)) {
1392 return $item['uri'];
1393 } elseif (!$onlyfound) {
1394 $person = FContact::getByURL($author);
1396 $parts = parse_url($person['url']);
1397 unset($parts['path']);
1398 $host_url = (string)Uri::fromParts($parts);
1400 return $host_url . '/objects/' . $guid;
1407 * Store the mentions in the tag table
1409 * @param integer $uriid
1410 * @param string $text
1412 private static function storeMentions(int $uriid, string $text)
1414 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1415 if (empty($matches)) {
1420 * Matching values for the preg match
1421 * [1] = mention type (@ or !)
1422 * [2] = name (optional)
1426 foreach ($matches as $match) {
1427 if (empty($match)) {
1431 $person = FContact::getByURL($match[3]);
1432 if (empty($person)) {
1436 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1441 * Processes an incoming comment
1443 * @param array $importer Array of the importer user
1444 * @param string $sender The sender of the message
1445 * @param SimpleXMLElement $data The message object
1446 * @param string $xml The original XML of the message
1447 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1449 * @return int The message id of the generated comment or "false" if there was an error
1450 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1451 * @throws \ImagickException
1453 private static function receiveComment(array $importer, string $sender, SimpleXMLElement $data, string $xml, int $direction): bool
1455 $author = XML::unescape($data->author);
1456 $guid = XML::unescape($data->guid);
1457 $parent_guid = XML::unescape($data->parent_guid);
1458 $text = XML::unescape($data->text);
1460 if (isset($data->created_at)) {
1461 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1463 $created_at = DateTimeFormat::utcNow();
1466 if (isset($data->thread_parent_guid)) {
1467 $thread_parent_guid = XML::unescape($data->thread_parent_guid);
1468 $thr_parent = self::getUriFromGuid('', $thread_parent_guid, true);
1473 $contact = self::allowedContactByHandle($importer, $sender, true);
1478 if (!empty($contact['gsid'])) {
1479 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1482 $message_id = self::messageExists($importer['uid'], $guid);
1487 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1488 if (!$toplevel_parent_item) {
1492 $person = FContact::getByURL($author);
1493 if (!is_array($person)) {
1494 Logger::notice('Unable to find author details');
1498 // Fetch the contact id - if we know this contact
1499 $author_contact = self::authorContactByUrl($contact, $person, $importer['uid']);
1503 $datarray['uid'] = $importer['uid'];
1504 $datarray['contact-id'] = $author_contact['cid'];
1505 $datarray['network'] = $author_contact['network'];
1507 $datarray['author-link'] = $person['url'];
1508 $datarray['author-id'] = Contact::getIdForURL($person['url'], 0);
1510 $datarray['owner-link'] = $contact['url'];
1511 $datarray['owner-id'] = Contact::getIdForURL($contact['url'], 0);
1513 // Will be overwritten for sharing accounts in Item::insert
1514 $datarray = self::setDirection($datarray, $direction);
1516 $datarray['guid'] = $guid;
1517 $datarray['uri'] = self::getUriFromGuid($author, $guid);
1518 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1520 $datarray['verb'] = Activity::POST;
1521 $datarray['gravity'] = Item::GRAVITY_COMMENT;
1523 $datarray['thr-parent'] = $thr_parent ?: $toplevel_parent_item['uri'];
1525 $datarray['object-type'] = Activity\ObjectType::COMMENT;
1526 $datarray['post-type'] = Item::PT_NOTE;
1528 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1529 $datarray['source'] = $xml;
1531 $datarray = self::setDirection($datarray, $direction);
1533 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
1535 $datarray['plink'] = self::plink($author, $guid, $toplevel_parent_item['guid']);
1536 $body = Markdown::toBBCode($text);
1538 $datarray['body'] = self::replacePeopleGuid($body, $person['url']);
1540 self::storeMentions($datarray['uri-id'], $text);
1541 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
1543 self::fetchGuid($datarray);
1545 // If we are the origin of the parent we store the original data.
1546 // We notify our followers during the item storage.
1547 if ($toplevel_parent_item['origin']) {
1548 $datarray['diaspora_signed_text'] = json_encode($data);
1551 if (Item::isTooOld($datarray)) {
1552 Logger::info('Comment is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1556 $message_id = Item::insert($datarray);
1558 if ($message_id <= 0) {
1563 Logger::info('Stored comment ' . $datarray['guid'] . ' with message id ' . $message_id);
1564 if ($datarray['uid'] == 0) {
1565 Item::distribute($message_id, json_encode($data));
1573 * processes and stores private messages
1575 * @param array $importer Array of the importer user
1576 * @param array $contact The contact of the message
1577 * @param SimpleXMLElement $data The message object
1578 * @param array $msg Array of the processed message, author handle and key
1579 * @param object $mesg The private message
1580 * @param array $conversation The conversation record to which this message belongs
1582 * @return bool "true" if it was successful
1583 * @throws \Exception
1584 * @todo Find type-hint for $mesg and update documentation
1586 private static function receiveConversationMessage(array $importer, array $contact, SimpleXMLElement $data, array $msg, $mesg, array $conversation): bool
1588 $author = XML::unescape($data->author);
1589 $guid = XML::unescape($data->guid);
1590 $subject = XML::unescape($data->subject);
1592 // "diaspora_handle" is the element name from the old version
1593 // "author" is the element name from the new version
1594 if ($mesg->author) {
1595 $msg_author = XML::unescape($mesg->author);
1596 } elseif ($mesg->diaspora_handle) {
1597 $msg_author = XML::unescape($mesg->diaspora_handle);
1602 $msg_guid = XML::unescape($mesg->guid);
1603 $msg_conversation_guid = XML::unescape($mesg->conversation_guid);
1604 $msg_text = XML::unescape($mesg->text);
1605 $msg_created_at = DateTimeFormat::utc(XML::unescape($mesg->created_at));
1607 if ($msg_conversation_guid != $guid) {
1608 Logger::notice('Message conversation guid does not belong to the current conversation.', ['guid' => $guid]);
1612 $body = Markdown::toBBCode($msg_text);
1613 $message_uri = $msg_author . ':' . $msg_guid;
1615 $person = FContact::getByURL($msg_author);
1617 return Mail::insert([
1618 'uid' => $importer['uid'],
1619 'guid' => $msg_guid,
1620 'convid' => $conversation['id'],
1621 'from-name' => $person['name'],
1622 'from-photo' => $person['photo'],
1623 'from-url' => $person['url'],
1624 'contact-id' => $contact['id'],
1625 'title' => $subject,
1627 'uri' => $message_uri,
1628 'parent-uri' => $author . ':' . $guid,
1629 'created' => $msg_created_at
1634 * Processes new private messages (answers to private messages are processed elsewhere)
1636 * @param array $importer Array of the importer user
1637 * @param array $msg Array of the processed message, author handle and key
1638 * @param SimpleXMLElement $data The message object
1640 * @return bool Success
1641 * @throws \Exception
1643 private static function receiveConversation(array $importer, array $msg, SimpleXMLElement $data)
1645 $author = XML::unescape($data->author);
1646 $guid = XML::unescape($data->guid);
1647 $subject = XML::unescape($data->subject);
1648 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1649 $participants = XML::unescape($data->participants);
1651 $messages = $data->message;
1653 if (!count($messages)) {
1654 Logger::notice('Empty conversation');
1658 $contact = self::allowedContactByHandle($importer, $msg['author'], true);
1663 if (!empty($contact['gsid'])) {
1664 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1667 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1668 if (!DBA::isResult($conversation)) {
1669 $r = DBA::insert('conv', [
1670 'uid' => $importer['uid'],
1672 'creator' => $author,
1673 'created' => $created_at,
1674 'updated' => DateTimeFormat::utcNow(),
1675 'subject' => $subject,
1676 'recips' => $participants
1680 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1683 if (!$conversation) {
1684 Logger::warning('Unable to create conversation.');
1688 foreach ($messages as $mesg) {
1689 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1696 * Processes "like" messages
1698 * @param array $importer Array of the importer user
1699 * @param string $sender The sender of the message
1700 * @param SimpleXMLElement $data The message object
1701 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1703 * @return bool Success or failure
1704 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1705 * @throws \ImagickException
1707 private static function receiveLike(array $importer, string $sender, SimpleXMLElement $data, int $direction): bool
1709 $author = XML::unescape($data->author);
1710 $guid = XML::unescape($data->guid);
1711 $parent_guid = XML::unescape($data->parent_guid);
1712 $parent_type = XML::unescape($data->parent_type);
1713 $positive = XML::unescape($data->positive);
1715 // likes on comments aren't supported by Diaspora - only on posts
1716 // But maybe this will be supported in the future, so we will accept it.
1717 if (!in_array($parent_type, ['Post', 'Comment'])) {
1721 $contact = self::allowedContactByHandle($importer, $sender, true);
1726 if (!empty($contact['gsid'])) {
1727 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1730 $message_id = self::messageExists($importer['uid'], $guid);
1735 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1736 if (!$toplevel_parent_item) {
1740 $person = FContact::getByURL($author);
1741 if (!is_array($person)) {
1742 Logger::notice('Unable to find author details');
1746 // Fetch the contact id - if we know this contact
1747 $author_contact = self::authorContactByUrl($contact, $person, $importer['uid']);
1749 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1750 // We would accept this anyhow.
1751 if ($positive == 'true') {
1752 $verb = Activity::LIKE;
1754 $verb = Activity::DISLIKE;
1759 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1761 $datarray['uid'] = $importer['uid'];
1762 $datarray['contact-id'] = $author_contact['cid'];
1763 $datarray['network'] = $author_contact['network'];
1765 $datarray = self::setDirection($datarray, $direction);
1767 $datarray['owner-link'] = $datarray['author-link'] = $person['url'];
1768 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($person['url'], 0);
1770 $datarray['guid'] = $guid;
1771 $datarray['uri'] = self::getUriFromGuid($author, $guid);
1773 $datarray['verb'] = $verb;
1774 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
1775 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1777 $datarray['object-type'] = Activity\ObjectType::NOTE;
1779 $datarray['body'] = $verb;
1781 // Diaspora doesn't provide a date for likes
1782 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
1784 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1785 if ($toplevel_parent_item['gravity'] != Item::GRAVITY_PARENT) {
1786 $toplevel = Post::selectFirst(['origin'], ['id' => $toplevel_parent_item['parent']]);
1787 $origin = $toplevel['origin'];
1789 $origin = $toplevel_parent_item['origin'];
1792 // If we are the origin of the parent we store the original data.
1793 // We notify our followers during the item storage.
1795 $datarray['diaspora_signed_text'] = json_encode($data);
1798 if (Item::isTooOld($datarray)) {
1799 Logger::info('Like is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1803 $message_id = Item::insert($datarray);
1805 if ($message_id <= 0) {
1810 Logger::info('Stored like ' . $datarray['guid'] . ' with message id ' . $message_id);
1811 if ($datarray['uid'] == 0) {
1812 Item::distribute($message_id, json_encode($data));
1820 * Processes private messages
1822 * @param array $importer Array of the importer user
1823 * @param SimpleXMLElement $data The message object
1825 * @return bool Success?
1826 * @throws \Exception
1828 private static function receiveMessage(array $importer, SimpleXMLElement $data): bool
1830 $author = XML::unescape($data->author);
1831 $guid = XML::unescape($data->guid);
1832 $conversation_guid = XML::unescape($data->conversation_guid);
1833 $text = XML::unescape($data->text);
1834 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1836 $contact = self::allowedContactByHandle($importer, $author, true);
1841 if (!empty($contact['gsid'])) {
1842 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1845 $conversation = null;
1847 $condition = ['uid' => $importer['uid'], 'guid' => $conversation_guid];
1848 $conversation = DBA::selectFirst('conv', [], $condition);
1850 if (!DBA::isResult($conversation)) {
1851 Logger::notice('Conversation not available.');
1855 $message_uri = $author . ':' . $guid;
1857 $person = FContact::getByURL($author);
1859 Logger::notice('Unable to find author details');
1863 $body = Markdown::toBBCode($text);
1865 $body = self::replacePeopleGuid($body, $person['url']);
1867 return Mail::insert([
1868 'uid' => $importer['uid'],
1870 'convid' => $conversation['id'],
1871 'from-name' => $person['name'],
1872 'from-photo' => $person['photo'],
1873 'from-url' => $person['url'],
1874 'contact-id' => $contact['id'],
1875 'title' => $conversation['subject'],
1878 'uri' => $message_uri,
1879 'parent-uri' => $author . ':' . $conversation['guid'],
1880 'created' => $created_at
1885 * Processes participations - unsupported by now
1887 * @param array $importer Array of the importer user
1888 * @param SimpleXMLElement $data The message object
1889 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1891 * @return bool success
1892 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1893 * @throws \ImagickException
1895 private static function receiveParticipation(array $importer, SimpleXMLElement $data, int $direction): bool
1897 $author = strtolower(XML::unescape($data->author));
1898 $guid = XML::unescape($data->guid);
1899 $parent_guid = XML::unescape($data->parent_guid);
1901 $contact = self::allowedContactByHandle($importer, $author, true);
1906 if (!empty($contact['gsid'])) {
1907 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1910 if (self::messageExists($importer['uid'], $guid)) {
1914 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1915 if (!$toplevel_parent_item) {
1919 if (!$toplevel_parent_item['origin']) {
1920 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1923 if (!in_array($toplevel_parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
1924 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1928 $person = FContact::getByURL($author);
1929 if (!is_array($person)) {
1930 Logger::notice('Person not found: ' . $author);
1934 $author_contact = self::authorContactByUrl($contact, $person, $importer['uid']);
1936 // Store participation
1939 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1941 $datarray['uid'] = $importer['uid'];
1942 $datarray['contact-id'] = $author_contact['cid'];
1943 $datarray['network'] = $author_contact['network'];
1945 $datarray = self::setDirection($datarray, $direction);
1947 $datarray['owner-link'] = $datarray['author-link'] = $person['url'];
1948 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($person['url'], 0);
1950 $datarray['guid'] = $guid;
1951 $datarray['uri'] = self::getUriFromGuid($author, $guid);
1953 $datarray['verb'] = Activity::FOLLOW;
1954 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
1955 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1957 $datarray['object-type'] = Activity\ObjectType::NOTE;
1959 $datarray['body'] = Activity::FOLLOW;
1961 // Diaspora doesn't provide a date for a participation
1962 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
1964 if (Item::isTooOld($datarray)) {
1965 Logger::info('Participation is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1969 $message_id = Item::insert($datarray);
1971 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
1973 // Send all existing comments and likes to the requesting server
1974 $comments = Post::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb', 'gravity'],
1975 ['parent' => $toplevel_parent_item['id'], 'gravity' => [Item::GRAVITY_COMMENT, Item::GRAVITY_ACTIVITY]]);
1976 while ($comment = Post::fetch($comments)) {
1977 if (($comment['gravity'] == Item::GRAVITY_ACTIVITY) && !in_array($comment['verb'], [Activity::LIKE, Activity::DISLIKE])) {
1978 Logger::info('Unsupported activities are not relayed', ['item' => $comment['id'], 'verb' => $comment['verb']]);
1982 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
1983 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
1987 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
1988 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
1992 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact['cid']]);
1993 if (Worker::add(Worker::PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['uri-id'], $author_contact['cid'], $datarray['uid'])) {
1994 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
1997 DBA::close($comments);
2003 * Processes photos - unneeded
2005 * @param array $importer Array of the importer user
2006 * @param SimpleXMLElement $data The message object
2008 * @return bool always true
2010 private static function receivePhoto(array $importer, $data)
2012 // There doesn't seem to be a reason for this function,
2013 // since the photo data is transmitted in the status message as well
2018 * Processes poll participations - unssupported
2020 * @param array $importer Array of the importer user
2021 * @param object $data The message object
2023 * @return bool always true
2025 private static function receivePollParticipation(array $importer, $data)
2027 // We don't support polls by now
2032 * Processes incoming profile updates
2034 * @param array $importer Array of the importer user
2035 * @param SimpleXMLElement $data The message object
2037 * @return bool Success
2038 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2039 * @throws \ImagickException
2041 private static function receiveProfile(array $importer, SimpleXMLElement $data): bool
2043 $author = strtolower(XML::unescape($data->author));
2045 $contact = self::contactByHandle($importer['uid'], $author);
2050 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? ' ' . XML::unescape($data->last_name) : '');
2051 $image_url = XML::unescape($data->image_url);
2052 $birthday = XML::unescape($data->birthday);
2053 $about = Markdown::toBBCode(XML::unescape($data->bio));
2054 $location = Markdown::toBBCode(XML::unescape($data->location));
2055 $searchable = (XML::unescape($data->searchable) == 'true');
2056 $nsfw = (XML::unescape($data->nsfw) == 'true');
2057 $tags = XML::unescape($data->tag_string);
2059 $tags = explode('#', $tags);
2062 foreach ($tags as $tag) {
2063 $tag = trim(strtolower($tag));
2069 $keywords = implode(', ', $keywords);
2071 $handle_parts = explode('@', $author);
2072 $nick = $handle_parts[0];
2075 $name = $handle_parts[0];
2078 if (preg_match('|^https?://|', $image_url) === 0) {
2079 // @TODO No HTTPS here?
2080 $image_url = 'http://' . $handle_parts[1] . $image_url;
2083 Contact::updateAvatar($contact['id'], $image_url);
2085 // Generic birthday. We don't know the timezone. The year is irrelevant.
2087 $birthday = str_replace('1000', '1901', $birthday);
2089 if ($birthday != '') {
2090 $birthday = DateTimeFormat::utc($birthday, 'Y-m-d');
2093 // this is to prevent multiple birthday notifications in a single year
2094 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2096 if (substr($birthday, 5) === substr($contact['bd'], 5)) {
2097 $birthday = $contact['bd'];
2100 $fields = ['name' => $name, 'location' => $location,
2101 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2102 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2103 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2105 if (!empty($birthday)) {
2106 $fields['bd'] = $birthday;
2109 Contact::update($fields, ['id' => $contact['id']]);
2111 Logger::info('Profile of contact ' . $contact['id'] . ' stored for user ' . $importer['uid']);
2117 * Processes incoming friend requests
2119 * @param array $importer Array of the importer user
2120 * @param array $contact The contact that send the request
2122 * @throws \Exception
2124 private static function receiveRequestMakeFriend(array $importer, array $contact)
2126 if ($contact['rel'] == Contact::SHARING) {
2128 ['rel' => Contact::FRIEND, 'writable' => true],
2129 ['id' => $contact['id'], 'uid' => $importer['uid']]
2135 * Processes incoming sharing notification
2137 * @param array $importer Array of the importer user
2138 * @param SimpleXMLElement $data The message object
2140 * @return bool Success
2141 * @throws \Exception
2143 private static function receiveContactRequest(array $importer, SimpleXMLElement $data): bool
2145 $author = XML::unescape($data->author);
2146 $recipient = XML::unescape($data->recipient);
2148 if (!$author || !$recipient) {
2152 // the current protocol version doesn't know these fields
2153 // That means that we will assume their existance
2154 if (isset($data->following)) {
2155 $following = (XML::unescape($data->following) == 'true');
2160 if (isset($data->sharing)) {
2161 $sharing = (XML::unescape($data->sharing) == 'true');
2166 $contact = self::contactByHandle($importer['uid'], $author);
2168 // perhaps we were already sharing with this person. Now they're sharing with us.
2169 // That makes us friends.
2172 Logger::info('Author ' . $author . ' (Contact ' . $contact['id'] . ') wants to follow us.');
2173 self::receiveRequestMakeFriend($importer, $contact);
2175 // refetch the contact array
2176 $contact = self::contactByHandle($importer['uid'], $author);
2178 // If we are now friends, we are sending a share message.
2179 // Normally we needn't to do so, but the first message could have been vanished.
2180 if (in_array($contact['rel'], [Contact::FRIEND])) {
2181 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2182 if (DBA::isResult($user)) {
2183 Logger::info('Sending share message to author ' . $author . ' - Contact: ' . $contact['id'] . ' - User: ' . $importer['uid']);
2184 self::sendShare($user, $contact);
2189 Logger::info("Author " . $author . " doesn't want to follow us anymore.");
2190 Contact::removeFollower($contact);
2195 if (!$following && $sharing && in_array($importer['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2196 Logger::info("Author " . $author . " wants to share with us - but doesn't want to listen. Request is ignored.");
2198 } elseif (!$following && !$sharing) {
2199 Logger::info("Author " . $author . " doesn't want anything - and we don't know the author. Request is ignored.");
2201 } elseif (!$following && $sharing) {
2202 Logger::info("Author " . $author . " wants to share with us.");
2203 } elseif ($following && $sharing) {
2204 Logger::info("Author " . $author . " wants to have a bidirectional conection.");
2205 } elseif ($following && !$sharing) {
2206 Logger::info("Author " . $author . " wants to listen to us.");
2209 $ret = FContact::getByURL($author);
2211 if (!$ret || ($ret['network'] != Protocol::DIASPORA)) {
2212 Logger::notice("Cannot resolve diaspora handle " . $author . " for ".$recipient);
2216 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2218 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2223 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2224 'author-link' => $ret['url']];
2226 $result = Contact::addRelationship($importer, $contact, $item, false);
2227 if ($result === true) {
2228 $contact_record = self::contactByHandle($importer['uid'], $author);
2229 if (!$contact_record) {
2230 Logger::info('unable to locate newly created contact record.');
2234 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2235 if (DBA::isResult($user)) {
2236 self::sendShare($user, $contact_record);
2238 // Send the profile data, maybe it weren't transmitted before
2239 self::sendProfile($importer['uid'], [$contact_record]);
2247 * Stores a reshare activity
2249 * @param array $item Array of reshare post
2250 * @param integer $parent_message_id Id of the parent post
2251 * @param string $guid GUID string of reshare action
2252 * @param string $author Author handle
2254 private static function addReshareActivity(array $item, int $parent_message_id, string $guid, string $author)
2256 $parent = Post::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2260 $datarray['uid'] = $item['uid'];
2261 $datarray['contact-id'] = $item['contact-id'];
2262 $datarray['network'] = $item['network'];
2264 $datarray['author-link'] = $item['author-link'];
2265 $datarray['author-id'] = $item['author-id'];
2267 $datarray['owner-link'] = $datarray['author-link'];
2268 $datarray['owner-id'] = $datarray['author-id'];
2270 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2271 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2272 $datarray['thr-parent'] = $parent['uri'];
2274 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2275 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
2276 $datarray['object-type'] = Activity\ObjectType::NOTE;
2278 $datarray['protocol'] = $item['protocol'];
2279 $datarray['source'] = $item['source'];
2280 $datarray['direction'] = $item['direction'];
2281 $datarray['post-reason'] = $item['post-reason'];
2283 $datarray['plink'] = self::plink($author, $datarray['guid']);
2284 $datarray['private'] = $item['private'];
2285 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2287 if (Item::isTooOld($datarray)) {
2288 Logger::info('Reshare activity is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2292 $message_id = Item::insert($datarray);
2295 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2296 if ($datarray['uid'] == 0) {
2297 Item::distribute($message_id);
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 = XML::unescape($data->author);
2317 $guid = XML::unescape($data->guid);
2318 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2319 $root_author = XML::unescape($data->root_author);
2320 $root_guid = XML::unescape($data->root_guid);
2321 /// @todo handle unprocessed property "provider_display_name"
2322 $public = XML::unescape($data->public);
2324 $contact = self::allowedContactByHandle($importer, $author, false);
2329 if (!empty($contact['gsid'])) {
2330 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2333 $message_id = self::messageExists($importer['uid'], $guid);
2338 $original_person = FContact::getByURL($root_author);
2339 if (!$original_person) {
2345 $datarray['uid'] = $importer['uid'];
2346 $datarray['contact-id'] = $contact['id'];
2347 $datarray['network'] = Protocol::DIASPORA;
2349 $datarray['author-link'] = $contact['url'];
2350 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2352 $datarray['owner-link'] = $datarray['author-link'];
2353 $datarray['owner-id'] = $datarray['author-id'];
2355 $datarray['guid'] = $guid;
2356 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($author, $guid);
2357 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2359 $datarray['verb'] = Activity::POST;
2360 $datarray['gravity'] = Item::GRAVITY_PARENT;
2362 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2363 $datarray['source'] = $xml;
2365 $datarray = self::setDirection($datarray, $direction);
2367 $datarray['quote-uri-id'] = self::getQuoteUriId($root_guid, $importer['uid'], $original_person['url']);
2368 if (empty($datarray['quote-uri-id'])) {
2372 $datarray['body'] = '';
2373 $datarray['plink'] = self::plink($author, $guid);
2374 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2375 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2377 self::fetchGuid($datarray);
2379 if (Item::isTooOld($datarray)) {
2380 Logger::info('Reshare is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2384 $message_id = Item::insert($datarray);
2386 self::sendParticipation($contact, $datarray);
2388 $root_message_id = self::messageExists($importer['uid'], $root_guid);
2389 if ($root_message_id) {
2390 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2394 Logger::info('Stored reshare ' . $datarray['guid'] . ' with message id ' . $message_id);
2395 if ($datarray['uid'] == 0) {
2396 Item::distribute($message_id);
2404 private static function getQuoteUriId(string $guid, int $uid, string $host): int
2406 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2408 if (!DBA::isResult($shared_item) && !empty($host) && Diaspora::storeByGuid($guid, $host, true)) {
2409 Logger::debug('Fetched post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2410 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2411 } elseif (DBA::isResult($shared_item)) {
2412 Logger::debug('Found existing post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2415 if (!DBA::isResult($shared_item)) {
2416 Logger::notice('Post does not exist.', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2420 return $shared_item['uri-id'];
2424 * Processes retractions
2426 * @param array $importer Array of the importer user
2427 * @param array $contact The contact of the item owner
2428 * @param SimpleXMLElement $data The message object
2430 * @return bool success
2431 * @throws \Exception
2433 private static function itemRetraction(array $importer, array $contact, SimpleXMLElement $data): bool
2435 $author = XML::unescape($data->author);
2436 $target_guid = XML::unescape($data->target_guid);
2437 $target_type = XML::unescape($data->target_type);
2439 $person = FContact::getByURL($author);
2440 if (!is_array($person)) {
2441 Logger::notice('Unable to find author detail for ' . $author);
2445 if (empty($contact['url'])) {
2446 $contact['url'] = $person['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 string $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, string $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 = 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, false);
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($author, $guid);
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, $xml, 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 fcontact table.
2942 // This is important for transmitting data to Friendica servers.
2943 if (!empty($contact['addr'])) {
2944 $fcontact = FContact::getByURL($contact['addr']);
2945 if (!empty($fcontact)) {
2946 $dest_url = ($public_batch ? $fcontact['batch'] : $fcontact['notify']);
2950 if (empty($dest_url)) {
2951 $dest_url = ($public_batch ? $contact['batch'] : $contact['notify']);
2955 Logger::notice('No URL for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2959 Logger::notice('transmit: ' . $logid . '-' . $guid . ' ' . $dest_url);
2961 if (!intval(DI::config()->get('system', 'diaspora_test'))) {
2962 $content_type = (($public_batch) ? 'application/magic-envelope+xml' : 'application/json');
2964 $postResult = DI::httpClient()->post($dest_url . '/', $envelope, ['Content-Type' => $content_type]);
2965 $return_code = $postResult->getReturnCode();
2967 Logger::notice('test_mode');
2971 Logger::notice('transmit: ' . $logid . '-' . $guid . ' to ' . $dest_url . ' returns: ' . $return_code);
2973 return $return_code ? $return_code : -1;
2978 * Build the post xml
2980 * @param string $type The message type
2981 * @param array $message The message data
2983 * @return string The post XML
2985 public static function buildPostXml(string $type, array $message): string
2987 $data = [$type => $message];
2989 return XML::fromArray($data, $xml);
2993 * Builds and transmit messages
2995 * @param array $owner the array of the item owner
2996 * @param array $contact Target of the communication
2997 * @param string $type The message type
2998 * @param array $message The message data
2999 * @param bool $public_batch Is it a public post?
3000 * @param string $guid message guid
3002 * @return int Result of the transmission
3003 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3004 * @throws \ImagickException
3006 private static function buildAndTransmit(array $owner, array $contact, string $type, array $message, bool $public_batch = false, string $guid = '')
3008 $msg = self::buildPostXml($type, $message);
3010 // Fallback if the private key wasn't transmitted in the expected field
3011 if (empty($owner['uprvkey'])) {
3012 $owner['uprvkey'] = $owner['prvkey'];
3015 // When sending content to Friendica contacts using the Diaspora protocol
3016 // we have to fetch the public key from the fcontact.
3017 // This is due to the fact that legacy DFRN had unique keys for every contact.
3018 $pubkey = $contact['pubkey'];
3019 if (!empty($contact['addr'])) {
3020 $fcontact = FContact::getByURL($contact['addr']);
3021 if (!empty($fcontact)) {
3022 $pubkey = $fcontact['pubkey'];
3025 // The "addr" field should always be filled.
3026 // If this isn't the case, it will raise a notice some lines later.
3027 // And in the log we will see where it came from and we can handle it there.
3028 Logger::notice('Empty addr', ['contact' => $contact ?? [], 'callstack' => System::callstack(20)]);
3031 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $pubkey ?? '', $public_batch);
3033 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3035 Logger::info('Transmitted message', ['owner' => $owner['uid'], 'target' => $contact['addr'], 'type' => $type, 'guid' => $guid, 'result' => $return_code]);
3037 return $return_code;
3041 * sends a participation (Used to get all further updates)
3043 * @param array $contact Target of the communication
3044 * @param array $item Item array
3046 * @return int The result of the transmission
3047 * @throws \Exception
3049 private static function sendParticipation(array $contact, array $item): int
3051 // Don't send notifications for private postings
3052 if ($item['private'] == Item::PRIVATE) {
3056 $cachekey = 'diaspora:sendParticipation:' . $item['guid'];
3058 $result = DI::cache()->get($cachekey);
3059 if (!is_null($result)) {
3063 // Fetch some user id to have a valid handle to transmit the participation.
3064 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3065 // If the item belongs to a user, we take this user id.
3066 if ($item['uid'] == 0) {
3067 // @todo Possibly use an administrator account?
3068 $condition = ['verified' => true, 'blocked' => false,
3069 'account_removed' => false, 'account_expired' => false, 'account-type' => User::ACCOUNT_TYPE_PERSON];
3070 $first_user = DBA::selectFirst('user', ['uid'], $condition, ['order' => ['uid']]);
3071 $owner = User::getOwnerDataById($first_user['uid']);
3073 $owner = User::getOwnerDataById($item['uid']);
3076 $author = self::myHandle($owner);
3079 'author' => $author,
3080 'guid' => System::createUUID(),
3081 'parent_type' => 'Post',
3082 'parent_guid' => $item['guid']
3085 Logger::info('Send participation for ' . $item['guid'] . ' by ' . $author);
3087 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3088 DI::cache()->set($cachekey, $item['guid'], Duration::QUARTER_HOUR);
3090 return self::buildAndTransmit($owner, $contact, 'participation', $message);
3094 * sends an account migration
3096 * @param array $owner the array of the item owner
3097 * @param array $contact Target of the communication
3098 * @param int $uid User ID
3100 * @return int The result of the transmission
3101 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3102 * @throws \ImagickException
3104 public static function sendAccountMigration(array $owner, array $contact, int $uid): int
3106 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3107 $profile = self::createProfileData($uid);
3109 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3110 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
3113 'author' => $old_handle,
3114 'profile' => $profile,
3115 'signature' => $signature
3118 Logger::info('Send account migration', ['msg' => $message]);
3120 return self::buildAndTransmit($owner, $contact, 'account_migration', $message);
3124 * Sends a "share" message
3126 * @param array $owner the array of the item owner
3127 * @param array $contact Target of the communication
3129 * @return int The result of the transmission
3130 * @throws \Exception
3132 public static function sendShare(array $owner, array $contact): int
3135 * @todo support the different possible combinations of "following" and "sharing"
3136 * Currently, Diaspora only interprets the "sharing" field
3138 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3142 switch ($contact["rel"]) {
3143 case Contact::FRIEND:
3147 case Contact::SHARING:
3151 case Contact::FOLLOWER:
3158 'author' => self::myHandle($owner),
3159 'recipient' => $contact['addr'],
3160 'following' => 'true',
3164 Logger::info('Send share', ['msg' => $message]);
3166 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3170 * sends an "unshare"
3172 * @param array $owner the array of the item owner
3173 * @param array $contact Target of the communication
3175 * @return int The result of the transmission
3176 * @throws \Exception
3178 public static function sendUnshare(array $owner, array $contact): int
3181 'author' => self::myHandle($owner),
3182 'recipient' => $contact['addr'],
3183 'following' => 'false',
3184 'sharing' => 'false'
3187 Logger::info('Send unshare', ['msg' => $message]);
3189 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3193 * Fetch reshare details
3195 * @param array $item The message body that is to be check
3197 * @return array Reshare details (empty if the item is no reshare)
3198 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3199 * @throws \ImagickException
3201 public static function getReshareDetails(array $item): array
3203 $reshared = DI::contentItem()->getSharedPost($item, ['network', 'author-addr']);
3204 if (empty($reshared)) {
3208 // Skip if it isn't a pure repeated messages or not a real reshare
3209 if (!empty($reshared['comment']) || !in_array($reshared['post']['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
3214 'root_handle' => strtolower($reshared['post']['author-addr']),
3215 'root_guid' => $reshared['guid']
3220 * Create an event array
3222 * @param integer $event_id The id of the event
3224 * @return array with event data
3225 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3227 private static function buildEvent(string $event_id): array
3229 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
3230 if (!DBA::isResult($event)) {
3236 $owner = User::getOwnerDataById($event['uid']);
3241 $eventdata['author'] = self::myHandle($owner);
3243 if ($event['guid']) {
3244 $eventdata['guid'] = $event['guid'];
3247 $mask = DateTimeFormat::ATOM;
3249 /// @todo - establish "all day" events in Friendica
3250 $eventdata['all_day'] = 'false';
3252 $eventdata['timezone'] = 'UTC';
3254 if ($event['start']) {
3255 $eventdata['start'] = DateTimeFormat::utc($event['start'], $mask);
3257 if ($event['finish'] && !$event['nofinish']) {
3258 $eventdata['end'] = DateTimeFormat::utc($event['finish'], $mask);
3260 if ($event['summary']) {
3261 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3263 if ($event['desc']) {
3264 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3266 if ($event['location']) {
3267 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3268 $coord = Map::getCoordinates($event['location']);
3271 $location['address'] = html_entity_decode(BBCode::toMarkdown($event['location']));
3272 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3273 $location['lat'] = $coord['lat'];
3274 $location['lng'] = $coord['lon'];
3276 $location['lat'] = 0;
3277 $location['lng'] = 0;
3279 $eventdata['location'] = $location;
3286 * Create a post (status message or reshare)
3288 * @param array $item The item that will be exported
3289 * @param array $owner the array of the item owner
3292 * 'type' -> Message type ("status_message" or "reshare")
3293 * 'message' -> Array of XML elements of the status
3294 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3295 * @throws \ImagickException
3297 public static function buildStatus(array $item, array $owner)
3299 $cachekey = 'diaspora:buildStatus:' . $item['guid'];
3301 $result = DI::cache()->get($cachekey);
3302 if (!is_null($result)) {
3306 $myaddr = self::myHandle($owner);
3308 $public = ($item['private'] == Item::PRIVATE ? 'false' : 'true');
3309 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3310 $edited = DateTimeFormat::utc($item['edited'] ?? $item['created'], DateTimeFormat::ATOM);
3312 // Detect a share element and do a reshare
3313 if (($item['private'] != Item::PRIVATE) && ($ret = self::getReshareDetails($item))) {
3315 'author' => $myaddr,
3316 'guid' => $item['guid'],
3317 'created_at' => $created,
3318 'root_author' => $ret['root_handle'],
3319 'root_guid' => $ret['root_guid'],
3320 'provider_display_name' => $item['app'],
3326 $title = $item['title'];
3327 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
3329 // Fetch the title from an attached link - if there is one
3330 if (empty($item['title']) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3331 $page_data = BBCode::getAttachmentData($item['body']);
3332 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3333 $title = $page_data['title'];
3337 // convert to markdown
3338 $body = html_entity_decode(BBCode::toMarkdown($body));
3341 if (strlen($title)) {
3342 $body = '### ' . html_entity_decode($title) . "\n\n" . $body;
3345 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]);
3346 if (!empty($attachments)) {
3347 $body .= "\n[hr]\n";
3348 foreach ($attachments as $attachment) {
3349 $body .= "[" . $attachment['description'] . "](" . $attachment['url'] . ")\n";
3355 if ($item['location'] != '')
3356 $location['address'] = $item['location'];
3358 if ($item['coord'] != '') {
3359 $coord = explode(' ', $item['coord']);
3360 $location['lat'] = $coord[0];
3361 $location['lng'] = $coord[1];
3365 'author' => $myaddr,
3366 'guid' => $item['guid'],
3367 'created_at' => $created,
3368 'edited_at' => $edited,
3369 'public' => $public,
3371 'provider_display_name' => $item['app'],
3372 'location' => $location
3375 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3376 if (!isset($location['lat']) || !isset($location['lng'])) {
3377 unset($message['location']);
3380 if ($item['event-id'] > 0) {
3381 $event = self::buildEvent($item['event-id']);
3382 if (count($event)) {
3383 $message['event'] = $event;
3385 if (!empty($event['location']['address']) &&
3386 !empty($event['location']['lat']) &&
3387 !empty($event['location']['lng'])) {
3388 $message['location'] = $event['location'];
3391 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3392 // $message['text'] = '';
3396 $type = 'status_message';
3401 'message' => $message
3404 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3409 private static function prependParentAuthorMention(string $body, string $profile_url): string
3411 $profile = Contact::getByURL($profile_url, false, ['addr', 'name']);
3412 if (!empty($profile['addr'])
3413 && !strstr($body, $profile['addr'])
3414 && !strstr($body, $profile_url)
3416 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3425 * @param array $item The item that will be exported
3426 * @param array $owner the array of the item owner
3427 * @param array $contact Target of the communication
3428 * @param bool $public_batch Is it a public post?
3430 * @return int The result of the transmission
3431 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3432 * @throws \ImagickException
3434 public static function sendStatus(array $item, array $owner, array $contact, bool $public_batch = false): int
3436 $status = self::buildStatus($item, $owner);
3438 return self::buildAndTransmit($owner, $contact, $status['type'], $status['message'], $public_batch, $item['guid']);
3442 * Creates a "like" object
3444 * @param array $item The item that will be exported
3445 * @param array $owner the array of the item owner
3447 * @return array|bool The data for a "like" or false on error
3448 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3450 private static function constructLike(array $item, array $owner)
3452 $parent = Post::selectFirst(['guid', 'uri', 'thr-parent'], ['uri' => $item['thr-parent']]);
3453 if (!DBA::isResult($parent)) {
3457 $target_type = ($parent['uri'] === $parent['thr-parent'] ? 'Post' : 'Comment');
3459 if ($item['verb'] === Activity::LIKE) {
3461 } elseif ($item['verb'] === Activity::DISLIKE) {
3462 $positive = 'false';
3466 'author' => self::myHandle($owner),
3467 'guid' => $item['guid'],
3468 'parent_guid' => $parent['guid'],
3469 'parent_type' => $target_type,
3470 'positive' => $positive,
3471 'author_signature' => '',
3476 * Creates an "EventParticipation" object
3478 * @param array $item The item that will be exported
3479 * @param array $owner the array of the item owner
3481 * @return array|bool The data for an "EventParticipation" or false on error
3482 * @throws \Exception
3484 private static function constructAttend(array $item, array $owner)
3486 $parent = Post::selectFirst(['guid'], ['uri' => $item['thr-parent']]);
3487 if (!DBA::isResult($parent)) {
3491 switch ($item['verb']) {
3492 case Activity::ATTEND:
3493 $attend_answer = 'accepted';
3495 case Activity::ATTENDNO:
3496 $attend_answer = 'declined';
3498 case Activity::ATTENDMAYBE:
3499 $attend_answer = 'tentative';
3502 Logger::warning('Unknown verb ' . $item['verb'] . ' in item ' . $item['guid']);
3507 'author' => self::myHandle($owner),
3508 'guid' => $item['guid'],
3509 'parent_guid' => $parent['guid'],
3510 'status' => $attend_answer,
3511 'author_signature' => ''
3516 * Creates the object for a comment
3518 * @param array $item The item that will be exported
3519 * @param array $owner the array of the item owner
3521 * @return array|false The data for a comment
3522 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3524 private static function constructComment(array $item, array $owner)
3526 $cachekey = 'diaspora:constructComment:' . $item['guid'];
3528 $result = DI::cache()->get($cachekey);
3529 if (!is_null($result)) {
3533 $toplevel_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3534 if (!DBA::isResult($toplevel_item)) {
3535 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3539 $thread_parent_item = $toplevel_item;
3540 if ($item['thr-parent'] != $item['parent-uri']) {
3541 $thread_parent_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3544 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
3546 // The replied to autor mention is prepended for clarity if:
3547 // - Item replied isn't yours
3548 // - Item is public or explicit mentions are disabled
3549 // - Implicit mentions are enabled
3551 $item['author-id'] != $thread_parent_item['author-id']
3552 && ($thread_parent_item['gravity'] != Item::GRAVITY_PARENT)
3553 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3554 && !DI::config()->get('system', 'disable_implicit_mentions')
3556 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3559 $text = html_entity_decode(BBCode::toMarkdown($body));
3560 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3561 $edited = DateTimeFormat::utc($item['edited'], DateTimeFormat::ATOM);
3564 'author' => self::myHandle($owner),
3565 'guid' => $item['guid'],
3566 'created_at' => $created,
3567 'edited_at' => $edited,
3568 'parent_guid' => $toplevel_item['guid'],
3570 'author_signature' => '',
3573 // Send the thread parent guid only if it is a threaded comment
3574 if ($item['thr-parent'] != $item['parent-uri']) {
3575 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3578 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3584 * Send a like or a comment
3586 * @param array $item The item that will be exported
3587 * @param array $owner the array of the item owner
3588 * @param array $contact Target of the communication
3589 * @param bool $public_batch Is it a public post?
3591 * @return int The result of the transmission
3592 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3593 * @throws \ImagickException
3595 public static function sendFollowup(array $item, array $owner, array $contact, bool $public_batch = false): int
3597 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3598 $message = self::constructAttend($item, $owner);
3599 $type = 'event_participation';
3600 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3601 $message = self::constructLike($item, $owner);
3603 } elseif (!in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
3604 $message = self::constructComment($item, $owner);
3608 if (empty($message)) {
3612 $message['author_signature'] = self::signature($owner, $message);
3614 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3618 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3620 * @param array $item The item that will be exported
3621 * @param array $owner the array of the item owner
3622 * @param array $contact Target of the communication
3623 * @param bool $public_batch Is it a public post?
3625 * @return int The result of the transmission
3626 * @throws \Exception
3628 public static function sendRelay(array $item, array $owner, array $contact, bool $public_batch = false): int
3630 if ($item['deleted']) {
3631 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3632 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3638 Logger::info('Got relayable data ' . $type . ' for item ' . $item['guid'] . ' (' . $item['id'] . ')');
3640 $msg = json_decode($item['signed_text'], true);
3643 if (is_array($msg)) {
3644 foreach ($msg as $field => $data) {
3645 if (!$item['deleted']) {
3646 if ($field == 'diaspora_handle') {
3649 if ($field == 'target_type') {
3650 $field = 'parent_type';
3654 $message[$field] = $data;
3657 Logger::info('Signature text for item ' . $item['guid'] . ' (' . $item['id'] . ') could not be extracted: ' . $item['signed_text']);
3660 $message['parent_author_signature'] = self::signature($owner, $message);
3662 Logger::info('Relayed data', ['msg' => $message]);
3664 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3668 * Sends a retraction (deletion) of a message, like or comment
3670 * @param array $item The item that will be exported
3671 * @param array $owner the array of the item owner
3672 * @param array $contact Target of the communication
3673 * @param bool $public_batch Is it a public post?
3674 * @param bool $relay Is the retraction transmitted from a relay?
3676 * @return int The result of the transmission
3677 * @throws \Exception
3679 public static function sendRetraction(array $item, array $owner, array $contact, bool $public_batch = false, bool $relay = false): int
3681 $itemaddr = strtolower($item['author-addr']);
3683 $msg_type = 'retraction';
3685 if ($item['gravity'] == Item::GRAVITY_PARENT) {
3686 $target_type = 'Post';
3687 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3688 $target_type = 'Like';
3690 $target_type = 'Comment';
3694 'author' => $itemaddr,
3695 'target_guid' => $item['guid'],
3696 'target_type' => $target_type
3699 Logger::info('Got message', ['msg' => $message]);
3701 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item['guid']);
3707 * @param array $item The item that will be exported
3708 * @param array $owner The owner
3709 * @param array $contact Target of the communication
3711 * @return int The result of the transmission
3712 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3713 * @throws \ImagickException
3715 public static function sendMail(array $item, array $owner, array $contact): int
3717 $myaddr = self::myHandle($owner);
3719 $cnv = DBA::selectFirst('conv', [], ['id' => $item['convid'], 'uid' => $item['uid']]);
3720 if (!DBA::isResult($cnv)) {
3721 Logger::notice('Conversation not found.');
3725 $body = BBCode::toMarkdown($item['body']);
3726 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3729 'author' => $myaddr,
3730 'guid' => $item['guid'],
3731 'conversation_guid' => $cnv['guid'],
3733 'created_at' => $created,
3736 if ($item['reply']) {
3741 'author' => $cnv['creator'],
3742 'guid' => $cnv['guid'],
3743 'subject' => $cnv['subject'],
3744 'created_at' => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3745 'participants' => $cnv['recips'],
3749 $type = 'conversation';
3752 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item['guid']);
3756 * Split a name into first name and last name
3758 * @param string $name The name
3760 * @return array The array with "first" and "last"
3762 public static function splitName(string $name): array
3764 $name = trim($name);
3766 // Is the name longer than 64 characters? Then cut the rest of it.
3767 if (strlen($name) > 64) {
3768 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3769 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3771 $name = substr($name, 0, 64);
3775 // Take the first word as first name
3776 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3777 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3778 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3779 return ['first' => $first, 'last' => $last];
3782 // Take the last word as last name
3783 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3784 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3786 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3787 return ['first' => $first, 'last' => $last];
3790 // Take the first 32 characters if there is no space in the first 32 characters
3791 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3792 $first = substr($name, 0, 32);
3793 $last = substr($name, 32);
3794 return ['first' => $first, 'last' => $last];
3797 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3798 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3800 // Check if the last name is longer than 32 characters
3801 if (strlen($last) > 32) {
3802 if (strpos($last, ' ') <= 32) {
3803 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
3805 $last = substr($last, 0, 32);
3809 return ['first' => $first, 'last' => $last];
3813 * Create profile data
3815 * @param int $uid The user id
3817 * @return array The profile data
3818 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3820 private static function createProfileData(int $uid): array
3822 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
3824 if (!DBA::isResult($profile)) {
3828 $split_name = self::splitName($profile['name']);
3831 'author' => $profile['addr'],
3832 'first_name' => $split_name['first'],
3833 'last_name' => $split_name['last'],
3834 'image_url' => DI::baseUrl() . '/photo/custom/300/' . $profile['uid'] . '.jpg',
3835 'image_url_medium' => DI::baseUrl() . '/photo/custom/100/' . $profile['uid'] . '.jpg',
3836 'image_url_small' => DI::baseUrl() . '/photo/custom/50/' . $profile['uid'] . '.jpg',
3837 'searchable' => ($profile['net-publish'] ? 'true' : 'false'),
3841 'tag_string' => null,
3845 if ($data['searchable'] === 'true') {
3846 $data['birthday'] = '';
3848 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
3849 [$year, $month, $day] = sscanf($profile['dob'], '%4d-%2d-%2d');
3853 $data['birthday'] = DateTimeFormat::utc($year . '-' . $month . '-' . $day, 'Y-m-d');
3856 $data['about'] = BBCode::toMarkdown($profile['about'] ?? '');
3858 $data['location'] = $profile['location'];
3859 $data['tag_string'] = '';
3861 if ($profile['pub_keywords']) {
3862 $kw = str_replace(',', ' ', $profile['pub_keywords']);
3863 $kw = str_replace(' ', ' ', $kw);
3864 $arr = explode(' ', $kw);
3866 for ($x = 0; $x < 5; $x ++) {
3867 if (!empty($arr[$x])) {
3868 $data['tag_string'] .= '#'. trim($arr[$x]) .' ';
3873 $data['tag_string'] = trim($data['tag_string']);
3880 * Sends profile data
3882 * @param int $uid The user id
3883 * @param array $recipients optional, default empty array
3886 * @throws \Exception
3888 public static function sendProfile(int $uid, array $recipients = [])
3891 Logger::warning('Parameter "uid" is empty');
3895 $owner = User::getOwnerDataById($uid);
3896 if (empty($owner)) {
3897 Logger::warning('Cannot fetch User record', ['uid' => $uid]);
3901 if (empty($recipients)) {
3902 Logger::debug('No recipients provided, fetching for user', ['uid' => $uid]);
3903 $recipients = DBA::selectToArray('contact', [], ['network' => Protocol::DIASPORA, 'uid' => $uid, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
3906 if (empty($recipients)) {
3907 Logger::warning('Cannot fetch recipients', ['uid' => $uid]);
3911 $message = self::createProfileData($uid);
3913 // @todo Split this into single worker jobs
3914 foreach ($recipients as $recipient) {
3915 Logger::info('Send updated profile data for user ' . $uid . ' to contact ' . $recipient['id']);
3916 self::buildAndTransmit($owner, $recipient, 'profile', $message);
3921 * Creates the signature for likes that are created on our system
3923 * @param integer $uid The user of that comment
3924 * @param array $item Item array
3926 * @return array|bool Signed content or false on error
3927 * @throws \Exception
3929 public static function createLikeSignature(int $uid, array $item)
3931 $owner = User::getOwnerDataById($uid);
3932 if (empty($owner)) {
3933 Logger::info('No owner post, so not storing signature', ['uid' => $uid]);
3937 if (!in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3938 Logger::warning('Item is neither a like nor a dislike', ['uid' => $uid, 'item[verb]' => $item['verb']]);;
3942 $message = self::constructLike($item, $owner);
3943 if ($message === false) {
3947 $message['author_signature'] = self::signature($owner, $message);
3953 * Creates the signature for Comments that are created on our system
3955 * @param array $item Item array
3957 * @return array|bool Signed content or false on error
3958 * @throws \Exception
3960 public static function createCommentSignature(array $item)
3963 if (!empty($item['author-link'])) {
3964 $url = $item['author-link'];
3966 $contact = Contact::getById($item['author-id'], ['url']);
3967 if (empty($contact['url'])) {
3968 Logger::warning('Author Contact not found', ['author-id' => $item['author-id']]);
3971 $url = $contact['url'];
3974 $uid = User::getIdForURL($url);
3976 Logger::info('No owner post, so not storing signature', ['url' => $contact['url'] ?? 'No contact loaded']);
3980 $owner = User::getOwnerDataById($uid);
3981 if (empty($owner)) {
3982 Logger::info('No owner post, so not storing signature');
3986 // This is only needed for the automated tests
3987 if (empty($owner['uprvkey'])) {
3991 if (!self::parentSupportDiaspora($item['thr-parent-id'])) {
3992 Logger::info('One of the parents does not support Diaspora. A signature will not be created.', ['uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
3996 $message = self::constructComment($item, $owner);
3997 if ($message === false) {
4001 $message['author_signature'] = self::signature($owner, $message);
4007 * Check if the parent and their parents support Diaspora
4009 * @param integer $parent_id
4012 private static function parentSupportDiaspora(int $parent_id): bool
4014 $parent_post = Post::selectFirstPost(['gravity', 'signed_text', 'author-link', 'thr-parent-id'], ['uri-id' => $parent_id]);
4015 if (empty($parent_post['thr-parent-id'])) {
4016 Logger::warning('Parent post does not exist.', ['parent-id' => $parent_id]);
4020 if (empty(FContact::getByURL($parent_post['author-link'], false))) {
4021 Logger::info('Parent author is no Diaspora contact.', ['parent-id' => $parent_id]);
4025 if (($parent_post['gravity'] == Item::GRAVITY_COMMENT) && empty($parent_post['signed_text'])) {
4026 Logger::info('Parent comment has got no Diaspora signature.', ['parent-id' => $parent_id]);
4030 if ($parent_post['gravity'] == Item::GRAVITY_COMMENT) {
4031 return self::parentSupportDiaspora($parent_post['thr-parent-id']);
4037 public static function performReshare(int $UriId, int $uid): int
4039 $owner = User::getOwnerDataById($uid);
4040 $author = Contact::getPublicIdByUserId($uid);
4044 'verb' => Activity::POST,
4045 'contact-id' => $owner['id'],
4046 'author-id' => $author,
4047 'owner-id' => $author,
4049 'quote-uri-id' => $UriId,
4050 'allow_cid' => $owner['allow_cid'] ?? '',
4051 'allow_gid' => $owner['allow_gid']?? '',
4052 'deny_cid' => $owner['deny_cid'] ?? '',
4053 'deny_gid' => $owner['deny_gid'] ?? '',
4056 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
4057 $item['private'] = Item::PRIVATE;
4058 } elseif (DI::pConfig()->get($uid, 'system', 'unlisted')) {
4059 $item['private'] = Item::UNLISTED;
4061 $item['private'] = Item::PUBLIC;
4064 // Don't trigger the addons
4065 $item['api_source'] = false;
4067 return Item::insert($item, true);