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['body'] = DI::contentItem()->createSharedPostByGuid($root_guid, $importer['uid'], $original_person['url']);
2368 $datarray['body'] = Diaspora::replacePeopleGuid($datarray['body'], $datarray['author-link']);
2370 /// @todo Copy tag data from original post
2371 Tag::storeFromBody($datarray['uri-id'], $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);
2405 * Processes retractions
2407 * @param array $importer Array of the importer user
2408 * @param array $contact The contact of the item owner
2409 * @param SimpleXMLElement $data The message object
2411 * @return bool success
2412 * @throws \Exception
2414 private static function itemRetraction(array $importer, array $contact, SimpleXMLElement $data): bool
2416 $author = XML::unescape($data->author);
2417 $target_guid = XML::unescape($data->target_guid);
2418 $target_type = XML::unescape($data->target_type);
2420 $person = FContact::getByURL($author);
2421 if (!is_array($person)) {
2422 Logger::notice('Unable to find author detail for ' . $author);
2426 if (empty($contact['url'])) {
2427 $contact['url'] = $person['url'];
2430 // Fetch items that are about to be deleted
2431 $fields = ['uid', 'id', 'parent', 'author-link', 'uri-id'];
2433 // When we receive a public retraction, we delete every item that we find.
2434 if ($importer['uid'] == 0) {
2435 $condition = ['guid' => $target_guid, 'deleted' => false];
2437 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2440 $r = Post::select($fields, $condition);
2441 if (!DBA::isResult($r)) {
2442 Logger::notice('Target guid ' . $target_guid . ' was not found on this system for user ' . $importer['uid'] . '.');
2446 while ($item = Post::fetch($r)) {
2447 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2448 Logger::info("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.");
2452 // Fetch the parent item
2453 $parent = Post::selectFirst(['author-link'], ['id' => $item['parent']]);
2455 // Only delete it if the parent author really fits
2456 if (!Strings::compareLink($parent['author-link'], $contact['url']) && !Strings::compareLink($item['author-link'], $contact['url'])) {
2457 Logger::info("Thread author " . $parent['author-link'] . " and item author " . $item['author-link'] . " don't fit to expected contact " . $contact['url']);
2461 Item::markForDeletion(['id' => $item['id']]);
2463 Logger::info('Deleted target ' . $target_guid . ' (' . $item['id'] . ') from user ' . $item['uid'] . ' parent: ' . $item['parent']);
2471 * Receives retraction messages
2473 * @param array $importer Array of the importer user
2474 * @param string $sender The sender of the message
2475 * @param SimpleXMLElement $data The message object
2477 * @return bool Success
2478 * @throws \Exception
2480 private static function receiveRetraction(array $importer, string $sender, SimpleXMLElement $data)
2482 $target_type = XML::unescape($data->target_type);
2484 $contact = self::contactByHandle($importer['uid'], $sender);
2485 if (!$contact && (in_array($target_type, ['Contact', 'Person']))) {
2486 Logger::notice('Cannot find contact for sender: ' . $sender . ' and user ' . $importer['uid']);
2494 Logger::info('Got retraction for ' . $target_type . ', sender ' . $sender . ' and user ' . $importer['uid']);
2496 switch ($target_type) {
2501 case 'StatusMessage':
2502 return self::itemRetraction($importer, $contact, $data);
2504 case 'PollParticipation':
2506 // Currently unsupported
2510 Logger::notice('Unknown target type ' . $target_type);
2517 * Checks if an incoming message is wanted
2519 * @param array $item
2520 * @param string $author
2521 * @param string $body
2522 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2524 * @return boolean Is the message wanted?
2526 private static function isSolicitedMessage(array $item, string $author, string $body, int $direction): bool
2528 $contact = Contact::getByURL($author);
2529 if (DBA::exists('contact', ['`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)', $contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) {
2530 Logger::debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2534 if ($direction == self::FORCED_FETCH) {
2535 Logger::debug('Post is a forced fetch - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2539 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
2540 if (Relay::isSolicitedPost($tags, $body, $contact['id'], $item['uri'], Protocol::DIASPORA)) {
2541 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2549 * Store an attached photo in the post-media table
2552 * @param object $photo
2555 private static function storePhotoAsMedia(int $uriid, $photo)
2557 // @TODO Need to find object type, roland@f.haeder.net
2558 Logger::debug('photo='.get_class($photo));
2560 $data['uri-id'] = $uriid;
2561 $data['type'] = Post\Media::IMAGE;
2562 $data['url'] = XML::unescape($photo->remote_photo_path) . XML::unescape($photo->remote_photo_name);
2563 $data['height'] = (int)XML::unescape($photo->height ?? 0);
2564 $data['width'] = (int)XML::unescape($photo->width ?? 0);
2565 $data['description'] = XML::unescape($photo->text ?? '');
2567 Post\Media::insert($data);
2571 * Set direction and post reason
2573 * @param array $datarray
2574 * @param integer $direction
2578 public static function setDirection(array $datarray, int $direction): array
2580 $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
2582 if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
2583 $datarray['post-reason'] = Item::PR_FETCHED;
2584 } elseif ($datarray['uid'] == 0) {
2585 $datarray['post-reason'] = Item::PR_GLOBAL;
2587 $datarray['post-reason'] = Item::PR_PUSHED;
2594 * Receives status messages
2596 * @param array $importer Array of the importer user
2597 * @param SimpleXMLElement $data The message object
2598 * @param string $xml The original XML of the message
2599 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2601 * @return int|bool The message id of the newly created item or false on error
2602 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2603 * @throws \ImagickException
2605 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, string $xml, int $direction)
2607 $author = XML::unescape($data->author);
2608 $guid = XML::unescape($data->guid);
2609 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2610 $public = XML::unescape($data->public);
2611 $text = XML::unescape($data->text);
2612 $provider_display_name = XML::unescape($data->provider_display_name);
2614 $contact = self::allowedContactByHandle($importer, $author, false);
2619 if (!empty($contact['gsid'])) {
2620 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2623 $message_id = self::messageExists($importer['uid'], $guid);
2629 if ($data->location) {
2630 foreach ($data->location->children() as $fieldname => $data) {
2631 $address[$fieldname] = XML::unescape($data);
2635 $raw_body = $body = Markdown::toBBCode($text);
2639 $datarray['guid'] = $guid;
2640 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($author, $guid);
2641 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2643 // Attach embedded pictures to the body
2645 foreach ($data->photo as $photo) {
2646 self::storePhotoAsMedia($datarray['uri-id'], $photo);
2649 $datarray['object-type'] = Activity\ObjectType::IMAGE;
2650 $datarray['post-type'] = Item::PT_IMAGE;
2651 } elseif ($data->poll) {
2652 $datarray['object-type'] = Activity\ObjectType::NOTE;
2653 $datarray['post-type'] = Item::PT_POLL;
2655 $datarray['object-type'] = Activity\ObjectType::NOTE;
2656 $datarray['post-type'] = Item::PT_NOTE;
2659 /// @todo enable support for polls
2660 //if ($data->poll) {
2661 // foreach ($data->poll as $poll)
2666 /// @todo enable support for events
2668 $datarray['uid'] = $importer['uid'];
2669 $datarray['contact-id'] = $contact['id'];
2670 $datarray['network'] = Protocol::DIASPORA;
2672 $datarray['author-link'] = $contact['url'];
2673 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2675 $datarray['owner-link'] = $datarray['author-link'];
2676 $datarray['owner-id'] = $datarray['author-id'];
2678 $datarray['verb'] = Activity::POST;
2679 $datarray['gravity'] = Item::GRAVITY_PARENT;
2681 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2682 $datarray['source'] = $xml;
2684 $datarray = self::setDirection($datarray, $direction);
2686 $datarray['body'] = self::replacePeopleGuid($body, $contact['url']);
2687 $datarray['raw-body'] = self::replacePeopleGuid($raw_body, $contact['url']);
2689 self::storeMentions($datarray['uri-id'], $text);
2690 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
2692 if (!self::isSolicitedMessage($datarray, $author, $body, $direction)) {
2693 DBA::delete('item-uri', ['uri' => $datarray['uri']]);
2697 if ($provider_display_name != '') {
2698 $datarray['app'] = $provider_display_name;
2701 $datarray['plink'] = self::plink($author, $guid);
2702 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2703 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2705 if (isset($address['address'])) {
2706 $datarray['location'] = $address['address'];
2709 if (isset($address['lat']) && isset($address['lng'])) {
2710 $datarray['coord'] = $address['lat'] . ' ' . $address['lng'];
2713 self::fetchGuid($datarray);
2715 if (Item::isTooOld($datarray)) {
2716 Logger::info('Status is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2720 $message_id = Item::insert($datarray);
2722 self::sendParticipation($contact, $datarray);
2725 Logger::info('Stored item ' . $datarray['guid'] . ' with message id ' . $message_id);
2726 if ($datarray['uid'] == 0) {
2727 Item::distribute($message_id);
2735 /* ************************************************************************************** *
2736 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2737 * ************************************************************************************** */
2740 * returnes the handle of a contact
2742 * @param array $contact contact array
2744 * @return string the handle in the format user@domain.tld
2745 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2747 private static function myHandle(array $contact): string
2749 if (!empty($contact['addr'])) {
2750 return $contact['addr'];
2753 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2754 // So - just in case - we build the the address here.
2755 if ($contact['nickname'] != '') {
2756 $nick = $contact['nickname'];
2758 $nick = $contact['nick'];
2761 return $nick . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
2766 * Creates the data for a private message in the new format
2768 * @param string $msg The message that is to be transmitted
2769 * @param array $user The record of the sender
2770 * @param array $contact Target of the communication
2771 * @param string $prvkey The private key of the sender
2772 * @param string $pubkey The public key of the receiver
2774 * @return string The encrypted data
2775 * @throws \Exception
2777 public static function encodePrivateData(string $msg, array $user, array $contact, string $prvkey, string $pubkey): string
2779 Logger::debug('Message: ' . $msg);
2781 // without a public key nothing will work
2783 Logger::notice('pubkey missing: contact id: ' . $contact['id']);
2787 $aes_key = random_bytes(32);
2788 $b_aes_key = base64_encode($aes_key);
2789 $iv = random_bytes(16);
2790 $b_iv = base64_encode($iv);
2792 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2794 $json = json_encode(['iv' => $b_iv, 'key' => $b_aes_key]);
2796 $encrypted_key_bundle = '';
2797 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
2801 $json_object = json_encode(
2803 'aes_key' => base64_encode($encrypted_key_bundle),
2804 'encrypted_magic_envelope' => base64_encode($ciphertext)
2808 return $json_object;
2812 * Creates the envelope for the "fetch" endpoint and for the new format
2814 * @param string $msg The message that is to be transmitted
2815 * @param array $user The record of the sender
2817 * @return string The envelope
2818 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2820 public static function buildMagicEnvelope(string $msg, array $user): string
2822 $b64url_data = Strings::base64UrlEncode($msg);
2823 $data = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
2825 $key_id = Strings::base64UrlEncode(self::myHandle($user));
2826 $type = 'application/xml';
2827 $encoding = 'base64url';
2828 $alg = 'RSA-SHA256';
2829 $signable_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
2831 // Fallback if the private key wasn't transmitted in the expected field
2832 if ($user['uprvkey'] == '') {
2833 $user['uprvkey'] = $user['prvkey'];
2836 $signature = Crypto::rsaSign($signable_data, $user['uprvkey']);
2837 $sig = Strings::base64UrlEncode($signature);
2842 '@attributes' => ['type' => $type],
2843 'me:encoding' => $encoding,
2846 '@attributes2' => ['key_id' => $key_id]
2850 $namespaces = ['me' => ActivityNamespace::SALMON_ME];
2852 return XML::fromArray($xmldata, $xml, false, $namespaces);
2856 * Create the envelope for a message
2858 * @param string $msg The message that is to be transmitted
2859 * @param array $user The record of the sender
2860 * @param array $contact Target of the communication
2861 * @param string $prvkey The private key of the sender
2862 * @param string $pubkey The public key of the receiver
2863 * @param bool $public Is the message public?
2865 * @return string The message that will be transmitted to other servers
2866 * @throws \Exception
2868 public static function buildMessage(string $msg, array $user, array $contact, string $prvkey, string $pubkey, bool $public = false): string
2870 // The message is put into an envelope with the sender's signature
2871 $envelope = self::buildMagicEnvelope($msg, $user);
2873 // Private messages are put into a second envelope, encrypted with the receivers public key
2875 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
2882 * Creates a signature for a message
2884 * @param array $owner the array of the owner of the message
2885 * @param array $message The message that is to be signed
2887 * @return string The signature
2889 private static function signature(array $owner, array $message): string
2892 unset($sigmsg['author_signature']);
2893 unset($sigmsg['parent_author_signature']);
2895 $signed_text = implode(';', $sigmsg);
2897 return base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
2901 * Transmit a message to a target server
2903 * @param array $owner the array of the item owner
2904 * @param array $contact Target of the communication
2905 * @param string $envelope The message that is to be transmitted
2906 * @param bool $public_batch Is it a public post?
2907 * @param string $guid message guid
2909 * @return int Result of the transmission
2910 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2911 * @throws \ImagickException
2913 private static function transmit(array $owner, array $contact, string $envelope, bool $public_batch, string $guid = ''): int
2915 $enabled = intval(DI::config()->get('system', 'diaspora_enabled'));
2920 $logid = Strings::getRandomHex(4);
2922 // We always try to use the data from the fcontact table.
2923 // This is important for transmitting data to Friendica servers.
2924 if (!empty($contact['addr'])) {
2925 $fcontact = FContact::getByURL($contact['addr']);
2926 if (!empty($fcontact)) {
2927 $dest_url = ($public_batch ? $fcontact['batch'] : $fcontact['notify']);
2931 if (empty($dest_url)) {
2932 $dest_url = ($public_batch ? $contact['batch'] : $contact['notify']);
2936 Logger::notice('No URL for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2940 Logger::notice('transmit: ' . $logid . '-' . $guid . ' ' . $dest_url);
2942 if (!intval(DI::config()->get('system', 'diaspora_test'))) {
2943 $content_type = (($public_batch) ? 'application/magic-envelope+xml' : 'application/json');
2945 $postResult = DI::httpClient()->post($dest_url . '/', $envelope, ['Content-Type' => $content_type]);
2946 $return_code = $postResult->getReturnCode();
2948 Logger::notice('test_mode');
2952 Logger::notice('transmit: ' . $logid . '-' . $guid . ' to ' . $dest_url . ' returns: ' . $return_code);
2954 return $return_code ? $return_code : -1;
2959 * Build the post xml
2961 * @param string $type The message type
2962 * @param array $message The message data
2964 * @return string The post XML
2966 public static function buildPostXml(string $type, array $message): string
2968 $data = [$type => $message];
2970 return XML::fromArray($data, $xml);
2974 * Builds and transmit messages
2976 * @param array $owner the array of the item owner
2977 * @param array $contact Target of the communication
2978 * @param string $type The message type
2979 * @param array $message The message data
2980 * @param bool $public_batch Is it a public post?
2981 * @param string $guid message guid
2983 * @return int Result of the transmission
2984 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2985 * @throws \ImagickException
2987 private static function buildAndTransmit(array $owner, array $contact, string $type, array $message, bool $public_batch = false, string $guid = '')
2989 $msg = self::buildPostXml($type, $message);
2991 // Fallback if the private key wasn't transmitted in the expected field
2992 if (empty($owner['uprvkey'])) {
2993 $owner['uprvkey'] = $owner['prvkey'];
2996 // When sending content to Friendica contacts using the Diaspora protocol
2997 // we have to fetch the public key from the fcontact.
2998 // This is due to the fact that legacy DFRN had unique keys for every contact.
2999 $pubkey = $contact['pubkey'];
3000 if (!empty($contact['addr'])) {
3001 $fcontact = FContact::getByURL($contact['addr']);
3002 if (!empty($fcontact)) {
3003 $pubkey = $fcontact['pubkey'];
3006 // The "addr" field should always be filled.
3007 // If this isn't the case, it will raise a notice some lines later.
3008 // And in the log we will see where it came from and we can handle it there.
3009 Logger::notice('Empty addr', ['contact' => $contact ?? [], 'callstack' => System::callstack(20)]);
3012 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $pubkey ?? '', $public_batch);
3014 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3016 Logger::info('Transmitted message', ['owner' => $owner['uid'], 'target' => $contact['addr'], 'type' => $type, 'guid' => $guid, 'result' => $return_code]);
3018 return $return_code;
3022 * sends a participation (Used to get all further updates)
3024 * @param array $contact Target of the communication
3025 * @param array $item Item array
3027 * @return int The result of the transmission
3028 * @throws \Exception
3030 private static function sendParticipation(array $contact, array $item): int
3032 // Don't send notifications for private postings
3033 if ($item['private'] == Item::PRIVATE) {
3037 $cachekey = 'diaspora:sendParticipation:' . $item['guid'];
3039 $result = DI::cache()->get($cachekey);
3040 if (!is_null($result)) {
3044 // Fetch some user id to have a valid handle to transmit the participation.
3045 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3046 // If the item belongs to a user, we take this user id.
3047 if ($item['uid'] == 0) {
3048 // @todo Possibly use an administrator account?
3049 $condition = ['verified' => true, 'blocked' => false,
3050 'account_removed' => false, 'account_expired' => false, 'account-type' => User::ACCOUNT_TYPE_PERSON];
3051 $first_user = DBA::selectFirst('user', ['uid'], $condition, ['order' => ['uid']]);
3052 $owner = User::getOwnerDataById($first_user['uid']);
3054 $owner = User::getOwnerDataById($item['uid']);
3057 $author = self::myHandle($owner);
3060 'author' => $author,
3061 'guid' => System::createUUID(),
3062 'parent_type' => 'Post',
3063 'parent_guid' => $item['guid']
3066 Logger::info('Send participation for ' . $item['guid'] . ' by ' . $author);
3068 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3069 DI::cache()->set($cachekey, $item['guid'], Duration::QUARTER_HOUR);
3071 return self::buildAndTransmit($owner, $contact, 'participation', $message);
3075 * sends an account migration
3077 * @param array $owner the array of the item owner
3078 * @param array $contact Target of the communication
3079 * @param int $uid User ID
3081 * @return int The result of the transmission
3082 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3083 * @throws \ImagickException
3085 public static function sendAccountMigration(array $owner, array $contact, int $uid): int
3087 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3088 $profile = self::createProfileData($uid);
3090 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3091 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
3094 'author' => $old_handle,
3095 'profile' => $profile,
3096 'signature' => $signature
3099 Logger::info('Send account migration', ['msg' => $message]);
3101 return self::buildAndTransmit($owner, $contact, 'account_migration', $message);
3105 * Sends a "share" message
3107 * @param array $owner the array of the item owner
3108 * @param array $contact Target of the communication
3110 * @return int The result of the transmission
3111 * @throws \Exception
3113 public static function sendShare(array $owner, array $contact): int
3116 * @todo support the different possible combinations of "following" and "sharing"
3117 * Currently, Diaspora only interprets the "sharing" field
3119 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3123 switch ($contact["rel"]) {
3124 case Contact::FRIEND:
3128 case Contact::SHARING:
3132 case Contact::FOLLOWER:
3139 'author' => self::myHandle($owner),
3140 'recipient' => $contact['addr'],
3141 'following' => 'true',
3145 Logger::info('Send share', ['msg' => $message]);
3147 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3151 * sends an "unshare"
3153 * @param array $owner the array of the item owner
3154 * @param array $contact Target of the communication
3156 * @return int The result of the transmission
3157 * @throws \Exception
3159 public static function sendUnshare(array $owner, array $contact): int
3162 'author' => self::myHandle($owner),
3163 'recipient' => $contact['addr'],
3164 'following' => 'false',
3165 'sharing' => 'false'
3168 Logger::info('Send unshare', ['msg' => $message]);
3170 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3174 * Checks a message body if it is a reshare
3176 * @param array $item The message body that is to be check
3178 * @return array Reshare details or "false" if no reshare
3179 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3180 * @throws \ImagickException
3182 public static function isReshare(array $item): array
3184 $reshared = Item::getShareArray($item);
3185 if (empty($reshared)) {
3189 // Skip if it isn't a pure repeated messages or not a real reshare
3190 if (!empty($reshared['comment']) || empty($reshared['guid'])) {
3194 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3195 $item = Post::selectFirst(['author-addr'], $condition);
3196 if (DBA::isResult($item)) {
3198 'root_handle' => strtolower($item['author-addr']),
3199 'root_guid' => $reshared['guid']
3203 // We are resharing something that isn't a DFRN or Diaspora post.
3208 * Create an event array
3210 * @param integer $event_id The id of the event
3212 * @return array with event data
3213 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3215 private static function buildEvent(string $event_id): array
3217 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
3218 if (!DBA::isResult($event)) {
3224 $owner = User::getOwnerDataById($event['uid']);
3229 $eventdata['author'] = self::myHandle($owner);
3231 if ($event['guid']) {
3232 $eventdata['guid'] = $event['guid'];
3235 $mask = DateTimeFormat::ATOM;
3237 /// @todo - establish "all day" events in Friendica
3238 $eventdata['all_day'] = 'false';
3240 $eventdata['timezone'] = 'UTC';
3242 if ($event['start']) {
3243 $eventdata['start'] = DateTimeFormat::utc($event['start'], $mask);
3245 if ($event['finish'] && !$event['nofinish']) {
3246 $eventdata['end'] = DateTimeFormat::utc($event['finish'], $mask);
3248 if ($event['summary']) {
3249 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3251 if ($event['desc']) {
3252 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3254 if ($event['location']) {
3255 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3256 $coord = Map::getCoordinates($event['location']);
3259 $location['address'] = html_entity_decode(BBCode::toMarkdown($event['location']));
3260 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3261 $location['lat'] = $coord['lat'];
3262 $location['lng'] = $coord['lon'];
3264 $location['lat'] = 0;
3265 $location['lng'] = 0;
3267 $eventdata['location'] = $location;
3274 * Create a post (status message or reshare)
3276 * @param array $item The item that will be exported
3277 * @param array $owner the array of the item owner
3280 * 'type' -> Message type ("status_message" or "reshare")
3281 * 'message' -> Array of XML elements of the status
3282 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3283 * @throws \ImagickException
3285 public static function buildStatus(array $item, array $owner)
3287 $cachekey = 'diaspora:buildStatus:' . $item['guid'];
3289 $result = DI::cache()->get($cachekey);
3290 if (!is_null($result)) {
3294 $myaddr = self::myHandle($owner);
3296 $public = ($item['private'] == Item::PRIVATE ? 'false' : 'true');
3297 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3298 $edited = DateTimeFormat::utc($item['edited'] ?? $item['created'], DateTimeFormat::ATOM);
3300 // Detect a share element and do a reshare
3301 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item))) {
3303 'author' => $myaddr,
3304 'guid' => $item['guid'],
3305 'created_at' => $created,
3306 'root_author' => $ret['root_handle'],
3307 'root_guid' => $ret['root_guid'],
3308 'provider_display_name' => $item['app'],
3314 $title = $item['title'];
3315 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
3317 // Fetch the title from an attached link - if there is one
3318 if (empty($item['title']) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3319 $page_data = BBCode::getAttachmentData($item['body']);
3320 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3321 $title = $page_data['title'];
3325 // @todo Check if this is obsolete and if we are still using different owners. (Possibly a fragment from the forum functionality)
3326 if ($item['author-link'] != $item['owner-link']) {
3327 $body = DI::contentItem()->createSharedBlockByArray($item);
3330 // convert to markdown
3331 $body = html_entity_decode(BBCode::toMarkdown($body));
3334 if (strlen($title)) {
3335 $body = '### ' . html_entity_decode($title) . "\n\n" . $body;
3338 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]);
3339 if (!empty($attachments)) {
3340 $body .= "\n[hr]\n";
3341 foreach ($attachments as $attachment) {
3342 $body .= "[" . $attachment['description'] . "](" . $attachment['url'] . ")\n";
3348 if ($item['location'] != '')
3349 $location['address'] = $item['location'];
3351 if ($item['coord'] != '') {
3352 $coord = explode(' ', $item['coord']);
3353 $location['lat'] = $coord[0];
3354 $location['lng'] = $coord[1];
3358 'author' => $myaddr,
3359 'guid' => $item['guid'],
3360 'created_at' => $created,
3361 'edited_at' => $edited,
3362 'public' => $public,
3364 'provider_display_name' => $item['app'],
3365 'location' => $location
3368 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3369 if (!isset($location['lat']) || !isset($location['lng'])) {
3370 unset($message['location']);
3373 if ($item['event-id'] > 0) {
3374 $event = self::buildEvent($item['event-id']);
3375 if (count($event)) {
3376 $message['event'] = $event;
3378 if (!empty($event['location']['address']) &&
3379 !empty($event['location']['lat']) &&
3380 !empty($event['location']['lng'])) {
3381 $message['location'] = $event['location'];
3384 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3385 // $message['text'] = '';
3389 $type = 'status_message';
3394 'message' => $message
3397 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3402 private static function prependParentAuthorMention(string $body, string $profile_url): string
3404 $profile = Contact::getByURL($profile_url, false, ['addr', 'name']);
3405 if (!empty($profile['addr'])
3406 && !strstr($body, $profile['addr'])
3407 && !strstr($body, $profile_url)
3409 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3418 * @param array $item The item that will be exported
3419 * @param array $owner the array of the item owner
3420 * @param array $contact Target of the communication
3421 * @param bool $public_batch Is it a public post?
3423 * @return int The result of the transmission
3424 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3425 * @throws \ImagickException
3427 public static function sendStatus(array $item, array $owner, array $contact, bool $public_batch = false): int
3429 $status = self::buildStatus($item, $owner);
3431 return self::buildAndTransmit($owner, $contact, $status['type'], $status['message'], $public_batch, $item['guid']);
3435 * Creates a "like" object
3437 * @param array $item The item that will be exported
3438 * @param array $owner the array of the item owner
3440 * @return array|bool The data for a "like" or false on error
3441 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3443 private static function constructLike(array $item, array $owner)
3445 $parent = Post::selectFirst(['guid', 'uri', 'thr-parent'], ['uri' => $item['thr-parent']]);
3446 if (!DBA::isResult($parent)) {
3450 $target_type = ($parent['uri'] === $parent['thr-parent'] ? 'Post' : 'Comment');
3452 if ($item['verb'] === Activity::LIKE) {
3454 } elseif ($item['verb'] === Activity::DISLIKE) {
3455 $positive = 'false';
3459 'author' => self::myHandle($owner),
3460 'guid' => $item['guid'],
3461 'parent_guid' => $parent['guid'],
3462 'parent_type' => $target_type,
3463 'positive' => $positive,
3464 'author_signature' => '',
3469 * Creates an "EventParticipation" object
3471 * @param array $item The item that will be exported
3472 * @param array $owner the array of the item owner
3474 * @return array|bool The data for an "EventParticipation" or false on error
3475 * @throws \Exception
3477 private static function constructAttend(array $item, array $owner)
3479 $parent = Post::selectFirst(['guid'], ['uri' => $item['thr-parent']]);
3480 if (!DBA::isResult($parent)) {
3484 switch ($item['verb']) {
3485 case Activity::ATTEND:
3486 $attend_answer = 'accepted';
3488 case Activity::ATTENDNO:
3489 $attend_answer = 'declined';
3491 case Activity::ATTENDMAYBE:
3492 $attend_answer = 'tentative';
3495 Logger::warning('Unknown verb ' . $item['verb'] . ' in item ' . $item['guid']);
3500 'author' => self::myHandle($owner),
3501 'guid' => $item['guid'],
3502 'parent_guid' => $parent['guid'],
3503 'status' => $attend_answer,
3504 'author_signature' => ''
3509 * Creates the object for a comment
3511 * @param array $item The item that will be exported
3512 * @param array $owner the array of the item owner
3514 * @return array|false The data for a comment
3515 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3517 private static function constructComment(array $item, array $owner)
3519 $cachekey = 'diaspora:constructComment:' . $item['guid'];
3521 $result = DI::cache()->get($cachekey);
3522 if (!is_null($result)) {
3526 $toplevel_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3527 if (!DBA::isResult($toplevel_item)) {
3528 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3532 $thread_parent_item = $toplevel_item;
3533 if ($item['thr-parent'] != $item['parent-uri']) {
3534 $thread_parent_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3537 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
3539 // The replied to autor mention is prepended for clarity if:
3540 // - Item replied isn't yours
3541 // - Item is public or explicit mentions are disabled
3542 // - Implicit mentions are enabled
3544 $item['author-id'] != $thread_parent_item['author-id']
3545 && ($thread_parent_item['gravity'] != Item::GRAVITY_PARENT)
3546 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3547 && !DI::config()->get('system', 'disable_implicit_mentions')
3549 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3552 $text = html_entity_decode(BBCode::toMarkdown($body));
3553 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3554 $edited = DateTimeFormat::utc($item['edited'], DateTimeFormat::ATOM);
3557 'author' => self::myHandle($owner),
3558 'guid' => $item['guid'],
3559 'created_at' => $created,
3560 'edited_at' => $edited,
3561 'parent_guid' => $toplevel_item['guid'],
3563 'author_signature' => '',
3566 // Send the thread parent guid only if it is a threaded comment
3567 if ($item['thr-parent'] != $item['parent-uri']) {
3568 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3571 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3577 * Send a like or a comment
3579 * @param array $item The item that will be exported
3580 * @param array $owner the array of the item owner
3581 * @param array $contact Target of the communication
3582 * @param bool $public_batch Is it a public post?
3584 * @return int The result of the transmission
3585 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3586 * @throws \ImagickException
3588 public static function sendFollowup(array $item, array $owner, array $contact, bool $public_batch = false): int
3590 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3591 $message = self::constructAttend($item, $owner);
3592 $type = 'event_participation';
3593 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3594 $message = self::constructLike($item, $owner);
3596 } elseif (!in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
3597 $message = self::constructComment($item, $owner);
3601 if (empty($message)) {
3605 $message['author_signature'] = self::signature($owner, $message);
3607 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3611 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3613 * @param array $item The item that will be exported
3614 * @param array $owner the array of the item owner
3615 * @param array $contact Target of the communication
3616 * @param bool $public_batch Is it a public post?
3618 * @return int The result of the transmission
3619 * @throws \Exception
3621 public static function sendRelay(array $item, array $owner, array $contact, bool $public_batch = false): int
3623 if ($item['deleted']) {
3624 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3625 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3631 Logger::info('Got relayable data ' . $type . ' for item ' . $item['guid'] . ' (' . $item['id'] . ')');
3633 $msg = json_decode($item['signed_text'], true);
3636 if (is_array($msg)) {
3637 foreach ($msg as $field => $data) {
3638 if (!$item['deleted']) {
3639 if ($field == 'diaspora_handle') {
3642 if ($field == 'target_type') {
3643 $field = 'parent_type';
3647 $message[$field] = $data;
3650 Logger::info('Signature text for item ' . $item['guid'] . ' (' . $item['id'] . ') could not be extracted: ' . $item['signed_text']);
3653 $message['parent_author_signature'] = self::signature($owner, $message);
3655 Logger::info('Relayed data', ['msg' => $message]);
3657 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3661 * Sends a retraction (deletion) of a message, like or comment
3663 * @param array $item The item that will be exported
3664 * @param array $owner the array of the item owner
3665 * @param array $contact Target of the communication
3666 * @param bool $public_batch Is it a public post?
3667 * @param bool $relay Is the retraction transmitted from a relay?
3669 * @return int The result of the transmission
3670 * @throws \Exception
3672 public static function sendRetraction(array $item, array $owner, array $contact, bool $public_batch = false, bool $relay = false): int
3674 $itemaddr = strtolower($item['author-addr']);
3676 $msg_type = 'retraction';
3678 if ($item['gravity'] == Item::GRAVITY_PARENT) {
3679 $target_type = 'Post';
3680 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3681 $target_type = 'Like';
3683 $target_type = 'Comment';
3687 'author' => $itemaddr,
3688 'target_guid' => $item['guid'],
3689 'target_type' => $target_type
3692 Logger::info('Got message', ['msg' => $message]);
3694 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item['guid']);
3700 * @param array $item The item that will be exported
3701 * @param array $owner The owner
3702 * @param array $contact Target of the communication
3704 * @return int The result of the transmission
3705 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3706 * @throws \ImagickException
3708 public static function sendMail(array $item, array $owner, array $contact): int
3710 $myaddr = self::myHandle($owner);
3712 $cnv = DBA::selectFirst('conv', [], ['id' => $item['convid'], 'uid' => $item['uid']]);
3713 if (!DBA::isResult($cnv)) {
3714 Logger::notice('Conversation not found.');
3718 $body = BBCode::toMarkdown($item['body']);
3719 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3722 'author' => $myaddr,
3723 'guid' => $item['guid'],
3724 'conversation_guid' => $cnv['guid'],
3726 'created_at' => $created,
3729 if ($item['reply']) {
3734 'author' => $cnv['creator'],
3735 'guid' => $cnv['guid'],
3736 'subject' => $cnv['subject'],
3737 'created_at' => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3738 'participants' => $cnv['recips'],
3742 $type = 'conversation';
3745 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item['guid']);
3749 * Split a name into first name and last name
3751 * @param string $name The name
3753 * @return array The array with "first" and "last"
3755 public static function splitName(string $name): array
3757 $name = trim($name);
3759 // Is the name longer than 64 characters? Then cut the rest of it.
3760 if (strlen($name) > 64) {
3761 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3762 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3764 $name = substr($name, 0, 64);
3768 // Take the first word as first name
3769 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3770 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3771 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3772 return ['first' => $first, 'last' => $last];
3775 // Take the last word as last name
3776 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3777 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3779 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3780 return ['first' => $first, 'last' => $last];
3783 // Take the first 32 characters if there is no space in the first 32 characters
3784 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3785 $first = substr($name, 0, 32);
3786 $last = substr($name, 32);
3787 return ['first' => $first, 'last' => $last];
3790 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3791 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3793 // Check if the last name is longer than 32 characters
3794 if (strlen($last) > 32) {
3795 if (strpos($last, ' ') <= 32) {
3796 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
3798 $last = substr($last, 0, 32);
3802 return ['first' => $first, 'last' => $last];
3806 * Create profile data
3808 * @param int $uid The user id
3810 * @return array The profile data
3811 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3813 private static function createProfileData(int $uid): array
3815 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
3817 if (!DBA::isResult($profile)) {
3821 $split_name = self::splitName($profile['name']);
3824 'author' => $profile['addr'],
3825 'first_name' => $split_name['first'],
3826 'last_name' => $split_name['last'],
3827 'image_url' => DI::baseUrl() . '/photo/custom/300/' . $profile['uid'] . '.jpg',
3828 'image_url_medium' => DI::baseUrl() . '/photo/custom/100/' . $profile['uid'] . '.jpg',
3829 'image_url_small' => DI::baseUrl() . '/photo/custom/50/' . $profile['uid'] . '.jpg',
3830 'searchable' => ($profile['net-publish'] ? 'true' : 'false'),
3834 'tag_string' => null,
3838 if ($data['searchable'] === 'true') {
3839 $data['birthday'] = '';
3841 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
3842 [$year, $month, $day] = sscanf($profile['dob'], '%4d-%2d-%2d');
3846 $data['birthday'] = DateTimeFormat::utc($year . '-' . $month . '-' . $day, 'Y-m-d');
3849 $data['about'] = BBCode::toMarkdown($profile['about'] ?? '');
3851 $data['location'] = $profile['location'];
3852 $data['tag_string'] = '';
3854 if ($profile['pub_keywords']) {
3855 $kw = str_replace(',', ' ', $profile['pub_keywords']);
3856 $kw = str_replace(' ', ' ', $kw);
3857 $arr = explode(' ', $kw);
3859 for ($x = 0; $x < 5; $x ++) {
3860 if (!empty($arr[$x])) {
3861 $data['tag_string'] .= '#'. trim($arr[$x]) .' ';
3866 $data['tag_string'] = trim($data['tag_string']);
3873 * Sends profile data
3875 * @param int $uid The user id
3876 * @param array $recipients optional, default empty array
3879 * @throws \Exception
3881 public static function sendProfile(int $uid, array $recipients = [])
3884 Logger::warning('Parameter "uid" is empty');
3888 $owner = User::getOwnerDataById($uid);
3889 if (empty($owner)) {
3890 Logger::warning('Cannot fetch User record', ['uid' => $uid]);
3894 if (empty($recipients)) {
3895 Logger::debug('No recipients provided, fetching for user', ['uid' => $uid]);
3896 $recipients = DBA::selectToArray('contact', [], ['network' => Protocol::DIASPORA, 'uid' => $uid, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
3899 if (empty($recipients)) {
3900 Logger::warning('Cannot fetch recipients', ['uid' => $uid]);
3904 $message = self::createProfileData($uid);
3906 // @todo Split this into single worker jobs
3907 foreach ($recipients as $recipient) {
3908 Logger::info('Send updated profile data for user ' . $uid . ' to contact ' . $recipient['id']);
3909 self::buildAndTransmit($owner, $recipient, 'profile', $message);
3914 * Creates the signature for likes that are created on our system
3916 * @param integer $uid The user of that comment
3917 * @param array $item Item array
3919 * @return array|bool Signed content or false on error
3920 * @throws \Exception
3922 public static function createLikeSignature(int $uid, array $item)
3924 $owner = User::getOwnerDataById($uid);
3925 if (empty($owner)) {
3926 Logger::info('No owner post, so not storing signature', ['uid' => $uid]);
3930 if (!in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3931 Logger::warning('Item is neither a like nor a dislike', ['uid' => $uid, 'item[verb]' => $item['verb']]);;
3935 $message = self::constructLike($item, $owner);
3936 if ($message === false) {
3940 $message['author_signature'] = self::signature($owner, $message);
3946 * Creates the signature for Comments that are created on our system
3948 * @param array $item Item array
3950 * @return array|bool Signed content or false on error
3951 * @throws \Exception
3953 public static function createCommentSignature(array $item)
3956 if (!empty($item['author-link'])) {
3957 $url = $item['author-link'];
3959 $contact = Contact::getById($item['author-id'], ['url']);
3960 if (empty($contact['url'])) {
3961 Logger::warning('Author Contact not found', ['author-id' => $item['author-id']]);
3964 $url = $contact['url'];
3967 $uid = User::getIdForURL($url);
3969 Logger::info('No owner post, so not storing signature', ['url' => $contact['url'] ?? 'No contact loaded']);
3973 $owner = User::getOwnerDataById($uid);
3974 if (empty($owner)) {
3975 Logger::info('No owner post, so not storing signature');
3979 // This is only needed for the automated tests
3980 if (empty($owner['uprvkey'])) {
3984 if (!self::parentSupportDiaspora($item['thr-parent-id'])) {
3985 Logger::info('One of the parents does not support Diaspora. A signature will not be created.', ['uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
3989 $message = self::constructComment($item, $owner);
3990 if ($message === false) {
3994 $message['author_signature'] = self::signature($owner, $message);
4000 * Check if the parent and their parents support Diaspora
4002 * @param integer $parent_id
4005 private static function parentSupportDiaspora(int $parent_id): bool
4007 $parent_post = Post::selectFirstPost(['gravity', 'signed_text', 'author-link', 'thr-parent-id'], ['uri-id' => $parent_id]);
4008 if (empty($parent_post['thr-parent-id'])) {
4009 Logger::warning('Parent post does not exist.', ['parent-id' => $parent_id]);
4013 if (empty(FContact::getByURL($parent_post['author-link'], false))) {
4014 Logger::info('Parent author is no Diaspora contact.', ['parent-id' => $parent_id]);
4018 if (($parent_post['gravity'] == Item::GRAVITY_COMMENT) && empty($parent_post['signed_text'])) {
4019 Logger::info('Parent comment has got no Diaspora signature.', ['parent-id' => $parent_id]);
4023 if ($parent_post['gravity'] == Item::GRAVITY_COMMENT) {
4024 return self::parentSupportDiaspora($parent_post['thr-parent-id']);
4030 public static function performReshare(int $UriId, int $uid): int
4032 $post = DI::contentItem()->createSharedPostByUriId($UriId, $uid);
4037 $owner = User::getOwnerDataById($uid);
4038 $author = Contact::getPublicIdByUserId($uid);
4042 'verb' => Activity::POST,
4043 'contact-id' => $owner['id'],
4044 'author-id' => $author,
4045 'owner-id' => $author,
4047 'allow_cid' => $owner['allow_cid'] ?? '',
4048 'allow_gid' => $owner['allow_gid']?? '',
4049 'deny_cid' => $owner['deny_cid'] ?? '',
4050 'deny_gid' => $owner['deny_gid'] ?? '',
4053 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
4054 $item['private'] = Item::PRIVATE;
4055 } elseif (DI::pConfig()->get($uid, 'system', 'unlisted')) {
4056 $item['private'] = Item::UNLISTED;
4058 $item['private'] = Item::PUBLIC;
4061 // Don't trigger the addons
4062 $item['api_source'] = false;
4064 return Item::insert($item, true);