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 contains functions to communicate via the Diaspora protocol
58 * @see https://diaspora.github.io/diaspora_federation/
64 const FORCED_FETCH = 2;
67 * Return a list of participating contacts for a thread
69 * This is used for the participation feature.
70 * One of the parameters is a contact array.
71 * This is done to avoid duplicates.
73 * @param array $item Item that is about to be delivered
74 * @param array $contacts The previously fetched contacts
76 * @return array of relay servers
79 public static function participantsForThread(array $item, array $contacts): array
81 if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
82 Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]);
86 $items = Post::select(['author-id', 'author-link', 'parent-author-link', 'parent-guid', 'guid'],
87 ['parent' => $item['parent'], 'gravity' => [Item::GRAVITY_COMMENT, Item::GRAVITY_ACTIVITY]]);
88 while ($item = Post::fetch($items)) {
89 $contact = DBA::selectFirst('contact', ['id', 'url', 'name', 'protocol', 'batch', 'network'],
90 ['id' => $item['author-id']]);
91 if (!DBA::isResult($contact) || empty($contact['batch']) ||
92 ($contact['network'] != Protocol::DIASPORA) ||
93 Strings::compareLink($item['parent-author-link'], $item['author-link'])) {
98 foreach ($contacts as $entry) {
99 if ($entry['batch'] == $contact['batch']) {
105 Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]);
106 $contacts[] = $contact;
115 * verify the envelope and return the verified data
117 * @param string $envelope The magic envelope
119 * @return string|bool verified data or false on error
120 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
121 * @throws \ImagickException
123 private static function verifyMagicEnvelope(string $envelope)
125 $basedom = XML::parseString($envelope, true);
127 if (!is_object($basedom)) {
128 Logger::notice('Envelope is no XML file');
132 $children = $basedom->children(ActivityNamespace::SALMON_ME);
134 if (sizeof($children) == 0) {
135 Logger::notice('XML has no children');
141 $data = Strings::base64UrlDecode($children->data);
142 $type = $children->data->attributes()->type[0];
144 $encoding = $children->encoding;
146 $alg = $children->alg;
148 $sig = Strings::base64UrlDecode($children->sig);
149 $key_id = $children->sig->attributes()->key_id[0];
151 $handle = Strings::base64UrlDecode($key_id);
154 $b64url_data = Strings::base64UrlEncode($data);
155 $msg = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
157 $signable_data = $msg . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
160 Logger::notice('No author could be decoded. Discarding. Message: ' . $envelope);
164 $key = self::key($handle);
166 Logger::notice("Couldn't get a key for handle " . $handle . ". Discarding.");
170 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
172 Logger::notice('Message from ' . $handle . ' did not verify. Discarding.');
180 * encrypts data via AES
182 * @param string $key The AES key
183 * @param string $iv The IV (is used for CBC encoding)
184 * @param string $data The data that is to be encrypted
186 * @return string encrypted data
188 private static function aesEncrypt(string $key, string $iv, string $data): string
190 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
194 * decrypts data via AES
196 * @param string $key The AES key
197 * @param string $iv The IV (is used for CBC encoding)
198 * @param string $encrypted The encrypted data
200 * @return string decrypted data
202 private static function aesDecrypt(string $key, string $iv, string $encrypted): string
204 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
208 * Decodes incoming Diaspora message in the new format. This method returns false on an error.
210 * @param string $raw raw post message
211 * @param string $privKey The private key of the importer
212 * @param boolean $no_exit Don't do an http exit on error
215 * 'message' -> decoded Diaspora XML message
216 * 'author' -> author diaspora handle
217 * 'key' -> author public key (converted to pkcs#8)
218 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
219 * @throws \ImagickException
221 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
223 $data = json_decode($raw);
225 // Is it a private post? Then decrypt the outer Salmon
226 if (is_object($data)) {
227 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
228 $ciphertext = base64_decode($data->encrypted_magic_envelope);
230 $outer_key_bundle = '';
231 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
232 $j_outer_key_bundle = json_decode($outer_key_bundle);
234 if (!is_object($j_outer_key_bundle)) {
235 Logger::notice('Outer Salmon did not verify. Discarding.');
239 throw new \Friendica\Network\HTTPException\BadRequestException();
243 $outer_iv = base64_decode($j_outer_key_bundle->iv);
244 $outer_key = base64_decode($j_outer_key_bundle->key);
246 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
251 $basedom = XML::parseString($xml, true);
253 if (!is_object($basedom)) {
254 Logger::notice('Received data does not seem to be an XML. Discarding. '.$xml);
258 throw new \Friendica\Network\HTTPException\BadRequestException();
262 $base = $basedom->children(ActivityNamespace::SALMON_ME);
264 // Not sure if this cleaning is needed
265 $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
267 // Build the signed data
268 $type = $base->data[0]->attributes()->type[0];
269 $encoding = $base->encoding;
271 $signed_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
273 // This is the signature
274 $signature = Strings::base64UrlDecode($base->sig);
276 // Get the senders' public key
277 $key_id = $base->sig[0]->attributes()->key_id[0];
278 $author_addr = base64_decode($key_id);
279 if ($author_addr == '') {
280 Logger::notice('No author could be decoded. Discarding. Message: ' . $xml);
284 throw new \Friendica\Network\HTTPException\BadRequestException();
288 $key = self::key($author_addr);
290 Logger::notice("Couldn't get a key for handle " . $author_addr . ". Discarding.");
294 throw new \Friendica\Network\HTTPException\BadRequestException();
298 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
300 Logger::notice('Message did not verify. Discarding.');
304 throw new \Friendica\Network\HTTPException\BadRequestException();
309 'message' => (string)Strings::base64UrlDecode($base->data),
310 'author' => XML::unescape($author_addr),
311 'key' => (string)$key
316 * Decodes incoming Diaspora message in the deprecated format
318 * @param string $xml urldecoded Diaspora salmon
319 * @param string $privKey The private key of the importer
322 * 'message' -> decoded Diaspora XML message
323 * 'author' -> author diaspora handle
324 * 'key' -> author public key (converted to pkcs#8)
325 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
326 * @throws \ImagickException
328 public static function decode(string $xml, string $privKey = '')
331 $basedom = XML::parseString($xml);
333 if (!is_object($basedom)) {
334 Logger::notice('XML is not parseable.');
337 $children = $basedom->children('https://joindiaspora.com/protocol');
339 $inner_aes_key = null;
342 if ($children->header) {
344 $author_link = str_replace('acct:', '', $children->header->author_id);
346 // This happens with posts from a relais
347 if (empty($privKey)) {
348 Logger::info('This is no private post in the old format');
352 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
354 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
355 $ciphertext = base64_decode($encrypted_header->ciphertext);
357 $outer_key_bundle = '';
358 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
360 $j_outer_key_bundle = json_decode($outer_key_bundle);
362 $outer_iv = base64_decode($j_outer_key_bundle->iv);
363 $outer_key = base64_decode($j_outer_key_bundle->key);
365 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
367 Logger::info('decrypted', ['data' => $decrypted]);
368 $idom = XML::parseString($decrypted);
370 $inner_iv = base64_decode($idom->iv);
371 $inner_aes_key = base64_decode($idom->aes_key);
373 $author_link = str_replace('acct:', '', $idom->author_id);
376 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
378 // figure out where in the DOM tree our data is hiding
381 if ($dom->provenance->data) {
382 $base = $dom->provenance;
383 } elseif ($dom->env->data) {
385 } elseif ($dom->data) {
390 Logger::notice('unable to locate salmon data in xml');
391 throw new \Friendica\Network\HTTPException\BadRequestException();
395 // Stash the signature away for now. We have to find their key or it won't be good for anything.
396 $signature = Strings::base64UrlDecode($base->sig);
400 // strip whitespace so our data element will return to one big base64 blob
401 $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
404 // stash away some other stuff for later
406 $type = $base->data[0]->attributes()->type[0];
407 $keyhash = $base->sig[0]->attributes()->keyhash[0];
408 $encoding = $base->encoding;
412 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
416 $data = Strings::base64UrlDecode($data);
420 $inner_decrypted = $data;
422 // Decode the encrypted blob
423 $inner_encrypted = base64_decode($data);
424 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
428 Logger::notice('Could not retrieve author URI.');
429 throw new \Friendica\Network\HTTPException\BadRequestException();
431 // Once we have the author URI, go to the web and try to find their public key
432 // (first this will look it up locally if it is in the fcontact cache)
433 // This will also convert diaspora public key from pkcs#1 to pkcs#8
435 Logger::notice('Fetching key for '.$author_link);
436 $key = self::key($author_link);
439 Logger::notice('Could not retrieve author key.');
440 throw new \Friendica\Network\HTTPException\BadRequestException();
443 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
446 Logger::notice('Message did not verify. Discarding.');
447 throw new \Friendica\Network\HTTPException\BadRequestException();
450 Logger::notice('Message verified.');
453 'message' => (string)$inner_decrypted,
454 'author' => XML::unescape($author_link),
455 'key' => (string)$key
461 * Dispatches public messages and find the fitting receivers
463 * @param array $msg The post that will be dispatched
464 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
466 * @return int|bool The message id of the generated message, "true" or "false" if there was an error
467 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
468 * @throws \ImagickException
470 public static function dispatchPublic(array $msg, int $direction)
472 $enabled = intval(DI::config()->get('system', 'diaspora_enabled'));
474 Logger::notice('Diaspora is disabled');
478 if (!($fields = self::validPosting($msg))) {
479 Logger::warning('Invalid posting');
485 'page-flags' => User::PAGE_FLAGS_FREELOVE
487 $success = self::dispatch($importer, $msg, $fields, $direction);
493 * Dispatches the different message types to the different functions
495 * @param array $importer Array of the importer user
496 * @param array $msg The post that will be dispatched
497 * @param SimpleXMLElement $fields SimpleXML object that contains the message
498 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
500 * @return int|bool The message id of the generated message, "true" or "false" if there was an error
501 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
502 * @throws \ImagickException
504 public static function dispatch(array $importer, array $msg, SimpleXMLElement $fields = null, int $direction = self::PUSHED)
506 // The sender is the handle of the contact that sent the message.
507 // This will often be different with relayed messages (for example "like" and "comment")
508 $sender = $msg['author'];
510 // This is only needed for private postings since this is already done for public ones before
511 if (is_null($fields)) {
513 if (!($fields = self::validPosting($msg))) {
514 Logger::warning('Invalid posting');
521 $type = $fields->getName();
523 Logger::info('Received message', ['type' => $type, 'sender' => $sender, 'user' => $importer['uid']]);
526 case 'account_migration':
528 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
531 return self::receiveAccountMigration($importer, $fields);
533 case 'account_deletion':
534 return self::receiveAccountDeletion($fields);
537 return self::receiveComment($importer, $sender, $fields, $msg['message'], $direction);
541 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
544 return self::receiveContactRequest($importer, $fields);
548 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
551 return self::receiveConversation($importer, $msg, $fields);
554 return self::receiveLike($importer, $sender, $fields, $direction);
558 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
561 return self::receiveMessage($importer, $fields);
563 case 'participation':
565 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
568 return self::receiveParticipation($importer, $fields, $direction);
570 case 'photo': // Not implemented
571 return self::receivePhoto($importer, $fields);
573 case 'poll_participation': // Not implemented
574 return self::receivePollParticipation($importer, $fields);
578 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
581 return self::receiveProfile($importer, $fields);
584 return self::receiveReshare($importer, $fields, $msg['message'], $direction);
587 return self::receiveRetraction($importer, $sender, $fields);
589 case 'status_message':
590 return self::receiveStatusMessage($importer, $fields, $msg['message'], $direction);
593 Logger::notice('Unknown message type ' . $type);
599 * Checks if a posting is valid and fetches the data fields.
601 * This function does not only check the signature.
602 * It also does the conversion between the old and the new diaspora format.
604 * @param array $msg Array with the XML, the sender handle and the sender signature
606 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
607 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
608 * @throws \ImagickException
610 private static function validPosting(array $msg)
612 $data = XML::parseString($msg['message']);
614 if (!is_object($data)) {
615 Logger::info('No valid XML', ['message' => $msg['message']]);
619 // Is this the new or the old version?
620 if ($data->getName() == 'XML') {
622 foreach ($data->post->children() as $child) {
630 $type = $element->getName();
633 Logger::debug('Got message', ['type' => $type, 'message' => $msg['message']]);
635 // All retractions are handled identically from now on.
636 // In the new version there will only be "retraction".
637 if (in_array($type, ['signed_retraction', 'relayable_retraction']))
638 $type = 'retraction';
640 if ($type == 'request') {
644 $fields = new SimpleXMLElement('<' . $type . '/>');
647 $author_signature = null;
648 $parent_author_signature = null;
650 foreach ($element->children() as $fieldname => $entry) {
652 // Translation for the old XML structure
653 if ($fieldname == 'diaspora_handle') {
654 $fieldname = 'author';
656 if ($fieldname == 'participant_handles') {
657 $fieldname = 'participants';
659 if (in_array($type, ['like', 'participation'])) {
660 if ($fieldname == 'target_type') {
661 $fieldname = 'parent_type';
664 if ($fieldname == 'sender_handle') {
665 $fieldname = 'author';
667 if ($fieldname == 'recipient_handle') {
668 $fieldname = 'recipient';
670 if ($fieldname == 'root_diaspora_id') {
671 $fieldname = 'root_author';
673 if ($type == 'status_message') {
674 if ($fieldname == 'raw_message') {
678 if ($type == 'retraction') {
679 if ($fieldname == 'post_guid') {
680 $fieldname = 'target_guid';
682 if ($fieldname == 'type') {
683 $fieldname = 'target_type';
688 if (($fieldname == 'author_signature') && ($entry != '')) {
689 $author_signature = base64_decode($entry);
690 } elseif (($fieldname == 'parent_author_signature') && ($entry != '')) {
691 $parent_author_signature = base64_decode($entry);
692 } elseif (!in_array($fieldname, ['author_signature', 'parent_author_signature', 'target_author_signature'])) {
693 if ($signed_data != '') {
697 $signed_data .= $entry;
699 if (!in_array($fieldname, ['parent_author_signature', 'target_author_signature'])
700 || ($orig_type == 'relayable_retraction')
702 XML::copy($entry, $fields, $fieldname);
706 // This is something that shouldn't happen at all.
707 if (in_array($type, ['status_message', 'reshare', 'profile'])) {
708 if ($msg['author'] != $fields->author) {
709 Logger::notice('Message handle is not the same as envelope sender. Quitting this message.', ['author1' => $msg['author'], 'author2' => $fields->author]);
714 // Only some message types have signatures. So we quit here for the other types.
715 if (!in_array($type, ['comment', 'like'])) {
719 if (!isset($author_signature) && ($msg['author'] == $fields->author)) {
720 Logger::debug('No author signature, but the sender matches the author', ['type' => $type, 'msg-author' => $msg['author'], 'message' => $msg['message']]);
724 // No author_signature? This is a must, so we quit.
725 if (!isset($author_signature)) {
726 Logger::info('No author signature', ['type' => $type, 'msg-author' => $msg['author'], 'fields-author' => $fields->author, 'message' => $msg['message']]);
730 if (isset($parent_author_signature)) {
731 $key = self::key($msg['author']);
733 Logger::info('No key found for parent', ['author' => $msg['author']]);
737 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, 'sha256')) {
738 Logger::info('No valid parent author signature', ['author' => $msg['author'], 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $parent_author_signature]);
743 $key = self::key($fields->author);
745 Logger::info('No key found', ['author' => $fields->author]);
749 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, 'sha256')) {
750 Logger::info('No valid author signature for author', ['author' => $fields->author, 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $author_signature]);
758 * Fetches the public key for a given handle
760 * @param string $handle The handle
762 * @return string The public key
763 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
764 * @throws \ImagickException
766 private static function key(string $handle = null): string
768 $handle = strval($handle);
770 Logger::notice('Fetching diaspora key', ['handle' => $handle, 'callstack' => System::callstack(20)]);
772 $fcontact = FContact::getByURL($handle);
773 if (!empty($fcontact['pubkey'])) {
774 return $fcontact['pubkey'];
781 * Get a contact id for a given handle
783 * @todo Move to Friendica\Model\Contact
785 * @param int $uid The user id
786 * @param string $handle The handle in the format user@domain.tld
788 * @return array Contact data
789 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
790 * @throws \ImagickException
792 private static function contactByHandle(int $uid, string $handle): array
794 return Contact::getByURL($handle, null, [], $uid);
798 * Checks if the given contact url does support ActivityPub
800 * @param string $url profile url
801 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
803 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
804 * @throws \ImagickException
806 public static function isSupportedByContactUrl(string $url, $update = null)
808 return !empty(FContact::getByURL($url, $update));
812 * Check if posting is allowed for this contact
814 * @param array $importer Array of the importer user
815 * @param array $contact The contact that is checked
816 * @param bool $is_comment Is the check for a comment?
818 * @return bool is the contact allowed to post?
820 private static function postAllow(array $importer, array $contact, bool $is_comment = false): bool
823 * Perhaps we were already sharing with this person. Now they're sharing with us.
824 * That makes us friends.
825 * Normally this should have handled by getting a request - but this could get lost
827 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
828 // It is not removed by now. Possibly the code is needed?
829 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
831 // array('rel' => Contact::FRIEND, 'writable' => true),
832 // array('id' => $contact["id"], 'uid' => $contact["uid"])
835 // $contact["rel"] = Contact::FRIEND;
836 // Logger::notice("defining user ".$contact["nick"]." as friend");
839 // Contact server is blocked
840 if (Network::isUrlBlocked($contact['url'])) {
842 // We don't seem to like that person
843 } elseif ($contact['blocked']) {
844 // Maybe blocked, don't accept.
846 // We are following this person?
847 } elseif (($contact['rel'] == Contact::SHARING) || ($contact['rel'] == Contact::FRIEND)) {
848 // Yes, then it is fine.
850 // Is the message a global user or a comment?
851 } elseif (($importer['uid'] == 0) || $is_comment) {
852 // Messages for the global users and comments are always accepted
860 * Fetches the contact id for a handle and checks if posting is allowed
862 * @param array $importer Array of the importer user
863 * @param string $handle The checked handle in the format user@domain.tld
864 * @param bool $is_comment Is the check for a comment?
866 * @return array|bool The contact data or false on error
869 private static function allowedContactByHandle(array $importer, string $handle, bool $is_comment = false)
871 $contact = self::contactByHandle($importer['uid'], $handle);
873 Logger::notice('A Contact for handle ' . $handle . ' and user ' . $importer['uid'] . ' was not found');
874 // If a contact isn't found, we accept it anyway if it is a comment
875 if ($is_comment && ($importer['uid'] != 0)) {
876 return self::contactByHandle(0, $handle);
877 } elseif ($is_comment) {
884 if (!self::postAllow($importer, $contact, $is_comment)) {
885 Logger::notice('The handle: ' . $handle . ' is not allowed to post to user ' . $importer['uid']);
892 * Does the message already exists on the system?
894 * @param int $uid The user id
895 * @param string $guid The guid of the message
897 * @return int|bool message id if the message already was stored into the system - or false.
900 private static function messageExists(int $uid, string $guid)
902 $item = Post::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
903 if (DBA::isResult($item)) {
904 Logger::notice('Message ' . $guid . ' already exists for user ' . $uid);
912 * Checks for links to posts in a message
914 * @param array $item The item array
917 private static function fetchGuid(array $item)
919 preg_replace_callback(
920 "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism",
921 function ($match) use ($item) {
922 self::fetchGuidSub($match, $item);
927 preg_replace_callback(
928 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
929 function ($match) use ($item) {
930 self::fetchGuidSub($match, $item);
937 * Checks for relative /people/* links in an item body to match local
938 * contacts or prepends the remote host taken from the author link.
940 * @param string $body The item body to replace links from
941 * @param string $author_link The author link for missing local contact fallback
943 * @return string the replaced string
945 public static function replacePeopleGuid(string $body, string $author_link): string
947 $return = preg_replace_callback(
948 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
949 function ($match) use ($author_link) {
951 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
952 // 1 => '0123456789abcdef'
954 $handle = FContact::getUrlByGuid($match[1]);
957 $return = '@[url=' . $handle . ']' . $match[2] . '[/url]';
959 // No local match, restoring absolute remote URL from author scheme and host
960 $author_url = parse_url($author_link);
961 $return = '[url=' . $author_url['scheme'] . '://' . $author_url['host'] . '/people/' . $match[1] . ']' . $match[2] . '[/url]';
973 * sub function of "fetchGuid" which checks for links in messages
975 * @param array $match array containing a link that has to be checked for a message link
976 * @param array $item The item array
978 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
979 * @throws \ImagickException
981 private static function fetchGuidSub(array $match, array $item)
983 if (!self::storeByGuid($match[1], $item['author-link'], true)) {
984 self::storeByGuid($match[1], $item['owner-link'], true);
989 * Fetches an item with a given guid from a given server
991 * @param string $guid the message guid
992 * @param string $server The server address
993 * @param bool $force Forced fetch
995 * @return int|bool the message id of the stored message or false
996 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
997 * @throws \ImagickException
999 public static function storeByGuid(string $guid, string $server, bool $force)
1001 $serverparts = parse_url($server);
1003 if (empty($serverparts['host']) || empty($serverparts['scheme'])) {
1007 $server = $serverparts['scheme'] . '://' . $serverparts['host'];
1009 Logger::info('Trying to fetch item ' . $guid . ' from ' . $server);
1011 $msg = self::message($guid, $server);
1017 Logger::info('Successfully fetched item ' . $guid . ' from ' . $server);
1019 // Now call the dispatcher
1020 return self::dispatchPublic($msg, $force ? self::FORCED_FETCH : self::FETCHED);
1024 * Fetches a message from a server
1026 * @param string $guid message guid
1027 * @param string $server The url of the server
1028 * @param int $level Endless loop prevention
1031 * 'message' => The message XML
1032 * 'author' => The author handle
1033 * 'key' => The public key of the author
1034 * @throws \Exception
1036 public static function message(string $guid, string $server, int $level = 0)
1042 // This will work for new Diaspora servers and Friendica servers from 3.5
1043 $source_url = $server . '/fetch/post/' . urlencode($guid);
1045 Logger::info('Fetch post from ' . $source_url);
1047 $envelope = DI::httpClient()->fetch($source_url, HttpClientAccept::MAGIC);
1049 Logger::info('Envelope was fetched.');
1050 $x = self::verifyMagicEnvelope($envelope);
1052 Logger::info('Envelope could not be verified.');
1054 Logger::info('Envelope was verified.');
1064 $source_xml = XML::parseString($x);
1066 if (!is_object($source_xml)) {
1070 if ($source_xml->post->reshare) {
1071 // Reshare of a reshare - old Diaspora version
1072 Logger::info('Message is a reshare');
1073 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1074 } elseif ($source_xml->getName() == 'reshare') {
1075 // Reshare of a reshare - new Diaspora version
1076 Logger::info('Message is a new reshare');
1077 return self::message($source_xml->root_guid, $server, ++$level);
1082 // Fetch the author - for the old and the new Diaspora version
1083 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1084 $author = (string)$source_xml->post->status_message->diaspora_handle;
1085 } elseif ($source_xml->author && ($source_xml->getName() == 'status_message')) {
1086 $author = (string)$source_xml->author;
1089 // If this isn't a "status_message" then quit
1091 Logger::info("Message doesn't seem to be a status message");
1097 'author' => $author,
1098 'key' => self::key($author)
1103 * Fetches an item with a given URL
1105 * @param string $url the message url
1106 * @param int $uid User id
1108 * @return int|bool the message id of the stored message or false
1109 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1110 * @throws \ImagickException
1112 public static function fetchByURL(string $url, int $uid = 0)
1114 // Check for Diaspora (and Friendica) typical paths
1115 if (!preg_match('=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i', $url, $matches)) {
1116 Logger::info('Invalid url', ['url' => $url]);
1120 $guid = urldecode($matches[2]);
1122 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1123 if (DBA::isResult($item)) {
1124 Logger::info('Found', ['id' => $item['id']]);
1128 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1129 $ret = self::storeByGuid($guid, $matches[1], true);
1130 Logger::info('Result', ['ret' => $ret]);
1132 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1133 if (DBA::isResult($item)) {
1134 Logger::info('Found', ['id' => $item['id']]);
1137 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1143 * Fetches the item record of a given guid
1145 * @param int $uid The user id
1146 * @param string $guid message guid
1147 * @param string $author The handle of the item
1148 * @param array $contact The contact of the item owner
1150 * @return array|bool the item record or false on failure
1151 * @throws \Exception
1153 private static function parentItem(int $uid, string $guid, string $author, array $contact)
1155 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1156 'author-name', 'author-link', 'author-avatar', 'gravity',
1157 'owner-name', 'owner-link', 'owner-avatar'];
1159 $condition = ['uid' => $uid, 'guid' => $guid];
1160 $item = Post::selectFirst($fields, $condition);
1162 if (!DBA::isResult($item)) {
1163 $person = FContact::getByURL($author);
1164 $result = self::storeByGuid($guid, $person['url'], false);
1166 // We don't have an url for items that arrived at the public dispatcher
1167 if (!$result && !empty($contact['url'])) {
1168 $result = self::storeByGuid($guid, $contact['url'], false);
1172 Logger::info('Fetched missing item ' . $guid . ' - result: ' . $result);
1174 $item = Post::selectFirst($fields, $condition);
1178 if (!DBA::isResult($item)) {
1179 Logger::notice('Parent item not found: parent: ' . $guid . ' - user: ' . $uid);
1182 Logger::notice('Parent item found: parent: ' . $guid . ' - user: ' . $uid);
1188 * returns contact details
1190 * @param array $def_contact The default contact if the person isn't found
1191 * @param array $person The record of the person
1192 * @param int $uid The user id
1195 * 'cid' => contact id
1196 * 'network' => network type
1197 * @throws \Exception
1199 private static function authorContactByUrl(array $def_contact, array $person, int $uid): array
1201 $condition = ['nurl' => Strings::normaliseLink($person['url']), 'uid' => $uid];
1202 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1203 if (DBA::isResult($contact)) {
1204 $cid = $contact['id'];
1205 $network = $contact['network'];
1207 $cid = $def_contact['id'];
1208 $network = Protocol::DIASPORA;
1213 'network' => $network
1218 * Is the profile a hubzilla profile?
1220 * @param string $url The profile link
1222 * @return bool is it a hubzilla server?
1224 private static function isHubzilla(string $url): bool
1226 return strstr($url, '/channel/');
1230 * Generate a post link with a given handle and message guid
1232 * @param string $addr The user handle
1233 * @param string $guid message guid
1234 * @param string $parent_guid optional parent guid
1236 * @return string the post link
1237 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1238 * @throws \ImagickException
1240 private static function plink(string $addr, string $guid, string $parent_guid = ''): string
1242 $contact = Contact::getByURL($addr);
1243 if (empty($contact)) {
1244 Logger::info('No contact data for address', ['addr' => $addr]);
1248 if (empty($contact['baseurl'])) {
1249 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1250 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1254 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1255 if (!empty($gserver['platform'])) {
1256 $platform = strtolower($gserver['platform']);
1257 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1260 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1261 if (self::isHubzilla($contact['url'])) {
1262 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1263 $platform = 'hubzilla';
1264 } elseif ($contact['network'] == Protocol::DFRN) {
1265 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1266 $platform = 'friendica';
1270 if ($platform == 'friendica') {
1271 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1274 if ($platform == 'hubzilla') {
1275 return $contact['baseurl'] . '/item/' . $guid;
1278 if ($platform == 'socialhome') {
1279 return $contact['baseurl'] . '/content/' . $guid;
1282 if ($platform != 'diaspora') {
1283 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1287 if ($parent_guid != '') {
1288 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1290 return $contact['baseurl'] . '/posts/' . $guid;
1295 * Receives account migration
1297 * @param array $importer Array of the importer user
1298 * @param SimpleXMLElement $data The message object
1300 * @return bool Success
1301 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1302 * @throws \ImagickException
1304 private static function receiveAccountMigration(array $importer, SimpleXMLElement $data): bool
1306 $old_handle = XML::unescape($data->author);
1307 $new_handle = XML::unescape($data->profile->author);
1308 $signature = XML::unescape($data->signature);
1310 $contact = self::contactByHandle($importer['uid'], $old_handle);
1312 Logger::notice('Cannot find contact for sender: ' . $old_handle . ' and user ' . $importer['uid']);
1316 Logger::notice('Got migration for ' . $old_handle . ', to ' . $new_handle . ' with user ' . $importer['uid']);
1319 $signed_text = 'AccountMigration:' . $old_handle . ':' . $new_handle;
1320 $key = self::key($old_handle);
1321 if (!Crypto::rsaVerify($signed_text, $signature, $key, 'sha256')) {
1322 Logger::notice('No valid signature for migration.');
1326 // Update the profile
1327 self::receiveProfile($importer, $data->profile);
1329 // change the technical stuff in contact
1330 $data = Probe::uri($new_handle);
1331 if ($data['network'] == Protocol::PHANTOM) {
1332 Logger::notice("Account for " . $new_handle . " couldn't be probed.");
1337 'url' => $data['url'],
1338 'nurl' => Strings::normaliseLink($data['url']),
1339 'name' => $data['name'],
1340 'nick' => $data['nick'],
1341 'addr' => $data['addr'],
1342 'batch' => $data['batch'],
1343 'notify' => $data['notify'],
1344 'poll' => $data['poll'],
1345 'network' => $data['network'],
1348 Contact::update($fields, ['addr' => $old_handle]);
1350 Logger::notice('Contacts are updated.');
1356 * Processes an account deletion
1358 * @param SimpleXMLElement $data The message object
1360 * @return bool Success
1361 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1363 private static function receiveAccountDeletion(SimpleXMLElement $data): bool
1365 $author = XML::unescape($data->author);
1367 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1368 while ($contact = DBA::fetch($contacts)) {
1369 Contact::remove($contact['id']);
1371 DBA::close($contacts);
1373 Logger::notice('Removed contacts for ' . $author);
1379 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1381 * @param string $author Author handle
1382 * @param string $guid Message guid
1383 * @param boolean $onlyfound Only return uri when found in the database
1385 * @return string The constructed uri or the one from our database or empty string on if $onlyfound is true
1386 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1387 * @throws \ImagickException
1389 private static function getUriFromGuid(string $author, string $guid, bool $onlyfound = false): string
1391 $item = Post::selectFirst(['uri'], ['guid' => $guid]);
1392 if (DBA::isResult($item)) {
1393 return $item['uri'];
1394 } elseif (!$onlyfound) {
1395 $person = FContact::getByURL($author);
1397 $parts = parse_url($person['url']);
1398 unset($parts['path']);
1399 $host_url = (string)Uri::fromParts($parts);
1401 return $host_url . '/objects/' . $guid;
1408 * Store the mentions in the tag table
1410 * @param integer $uriid
1411 * @param string $text
1413 private static function storeMentions(int $uriid, string $text)
1415 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1416 if (empty($matches)) {
1421 * Matching values for the preg match
1422 * [1] = mention type (@ or !)
1423 * [2] = name (optional)
1427 foreach ($matches as $match) {
1428 if (empty($match)) {
1432 $person = FContact::getByURL($match[3]);
1433 if (empty($person)) {
1437 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1442 * Processes an incoming comment
1444 * @param array $importer Array of the importer user
1445 * @param string $sender The sender of the message
1446 * @param SimpleXMLElement $data The message object
1447 * @param string $xml The original XML of the message
1448 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1450 * @return int The message id of the generated comment or "false" if there was an error
1451 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1452 * @throws \ImagickException
1454 private static function receiveComment(array $importer, string $sender, SimpleXMLElement $data, string $xml, int $direction): bool
1456 $author = XML::unescape($data->author);
1457 $guid = XML::unescape($data->guid);
1458 $parent_guid = XML::unescape($data->parent_guid);
1459 $text = XML::unescape($data->text);
1461 if (isset($data->created_at)) {
1462 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1464 $created_at = DateTimeFormat::utcNow();
1467 if (isset($data->thread_parent_guid)) {
1468 $thread_parent_guid = XML::unescape($data->thread_parent_guid);
1469 $thr_parent = self::getUriFromGuid('', $thread_parent_guid, true);
1474 $contact = self::allowedContactByHandle($importer, $sender, true);
1479 if (!empty($contact['gsid'])) {
1480 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1483 $message_id = self::messageExists($importer['uid'], $guid);
1488 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1489 if (!$toplevel_parent_item) {
1493 $person = FContact::getByURL($author);
1494 if (!is_array($person)) {
1495 Logger::notice('Unable to find author details');
1499 // Fetch the contact id - if we know this contact
1500 $author_contact = self::authorContactByUrl($contact, $person, $importer['uid']);
1504 $datarray['uid'] = $importer['uid'];
1505 $datarray['contact-id'] = $author_contact['cid'];
1506 $datarray['network'] = $author_contact['network'];
1508 $datarray['author-link'] = $person['url'];
1509 $datarray['author-id'] = Contact::getIdForURL($person['url'], 0);
1511 $datarray['owner-link'] = $contact['url'];
1512 $datarray['owner-id'] = Contact::getIdForURL($contact['url'], 0);
1514 // Will be overwritten for sharing accounts in Item::insert
1515 $datarray = self::setDirection($datarray, $direction);
1517 $datarray['guid'] = $guid;
1518 $datarray['uri'] = self::getUriFromGuid($author, $guid);
1519 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1521 $datarray['verb'] = Activity::POST;
1522 $datarray['gravity'] = Item::GRAVITY_COMMENT;
1524 $datarray['thr-parent'] = $thr_parent ?: $toplevel_parent_item['uri'];
1526 $datarray['object-type'] = Activity\ObjectType::COMMENT;
1527 $datarray['post-type'] = Item::PT_NOTE;
1529 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1530 $datarray['source'] = $xml;
1532 $datarray = self::setDirection($datarray, $direction);
1534 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
1536 $datarray['plink'] = self::plink($author, $guid, $toplevel_parent_item['guid']);
1537 $body = Markdown::toBBCode($text);
1539 $datarray['body'] = self::replacePeopleGuid($body, $person['url']);
1541 self::storeMentions($datarray['uri-id'], $text);
1542 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
1544 self::fetchGuid($datarray);
1546 // If we are the origin of the parent we store the original data.
1547 // We notify our followers during the item storage.
1548 if ($toplevel_parent_item['origin']) {
1549 $datarray['diaspora_signed_text'] = json_encode($data);
1552 if (Item::isTooOld($datarray)) {
1553 Logger::info('Comment is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1557 $message_id = Item::insert($datarray);
1559 if ($message_id <= 0) {
1564 Logger::info('Stored comment ' . $datarray['guid'] . ' with message id ' . $message_id);
1565 if ($datarray['uid'] == 0) {
1566 Item::distribute($message_id, json_encode($data));
1574 * processes and stores private messages
1576 * @param array $importer Array of the importer user
1577 * @param array $contact The contact of the message
1578 * @param SimpleXMLElement $data The message object
1579 * @param array $msg Array of the processed message, author handle and key
1580 * @param object $mesg The private message
1581 * @param array $conversation The conversation record to which this message belongs
1583 * @return bool "true" if it was successful
1584 * @throws \Exception
1585 * @todo Find type-hint for $mesg and update documentation
1587 private static function receiveConversationMessage(array $importer, array $contact, SimpleXMLElement $data, array $msg, $mesg, array $conversation): bool
1589 $author = XML::unescape($data->author);
1590 $guid = XML::unescape($data->guid);
1591 $subject = XML::unescape($data->subject);
1593 // "diaspora_handle" is the element name from the old version
1594 // "author" is the element name from the new version
1595 if ($mesg->author) {
1596 $msg_author = XML::unescape($mesg->author);
1597 } elseif ($mesg->diaspora_handle) {
1598 $msg_author = XML::unescape($mesg->diaspora_handle);
1603 $msg_guid = XML::unescape($mesg->guid);
1604 $msg_conversation_guid = XML::unescape($mesg->conversation_guid);
1605 $msg_text = XML::unescape($mesg->text);
1606 $msg_created_at = DateTimeFormat::utc(XML::unescape($mesg->created_at));
1608 if ($msg_conversation_guid != $guid) {
1609 Logger::notice('Message conversation guid does not belong to the current conversation.', ['guid' => $guid]);
1613 $body = Markdown::toBBCode($msg_text);
1614 $message_uri = $msg_author . ':' . $msg_guid;
1616 $person = FContact::getByURL($msg_author);
1618 return Mail::insert([
1619 'uid' => $importer['uid'],
1620 'guid' => $msg_guid,
1621 'convid' => $conversation['id'],
1622 'from-name' => $person['name'],
1623 'from-photo' => $person['photo'],
1624 'from-url' => $person['url'],
1625 'contact-id' => $contact['id'],
1626 'title' => $subject,
1628 'uri' => $message_uri,
1629 'parent-uri' => $author . ':' . $guid,
1630 'created' => $msg_created_at
1635 * Processes new private messages (answers to private messages are processed elsewhere)
1637 * @param array $importer Array of the importer user
1638 * @param array $msg Array of the processed message, author handle and key
1639 * @param SimpleXMLElement $data The message object
1641 * @return bool Success
1642 * @throws \Exception
1644 private static function receiveConversation(array $importer, array $msg, SimpleXMLElement $data)
1646 $author = XML::unescape($data->author);
1647 $guid = XML::unescape($data->guid);
1648 $subject = XML::unescape($data->subject);
1649 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1650 $participants = XML::unescape($data->participants);
1652 $messages = $data->message;
1654 if (!count($messages)) {
1655 Logger::notice('Empty conversation');
1659 $contact = self::allowedContactByHandle($importer, $msg['author'], true);
1664 if (!empty($contact['gsid'])) {
1665 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1668 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1669 if (!DBA::isResult($conversation)) {
1670 $r = DBA::insert('conv', [
1671 'uid' => $importer['uid'],
1673 'creator' => $author,
1674 'created' => $created_at,
1675 'updated' => DateTimeFormat::utcNow(),
1676 'subject' => $subject,
1677 'recips' => $participants
1681 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1684 if (!$conversation) {
1685 Logger::warning('Unable to create conversation.');
1689 foreach ($messages as $mesg) {
1690 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1697 * Processes "like" messages
1699 * @param array $importer Array of the importer user
1700 * @param string $sender The sender of the message
1701 * @param SimpleXMLElement $data The message object
1702 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1704 * @return bool Success or failure
1705 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1706 * @throws \ImagickException
1708 private static function receiveLike(array $importer, string $sender, SimpleXMLElement $data, int $direction): bool
1710 $author = XML::unescape($data->author);
1711 $guid = XML::unescape($data->guid);
1712 $parent_guid = XML::unescape($data->parent_guid);
1713 $parent_type = XML::unescape($data->parent_type);
1714 $positive = XML::unescape($data->positive);
1716 // likes on comments aren't supported by Diaspora - only on posts
1717 // But maybe this will be supported in the future, so we will accept it.
1718 if (!in_array($parent_type, ['Post', 'Comment'])) {
1722 $contact = self::allowedContactByHandle($importer, $sender, true);
1727 if (!empty($contact['gsid'])) {
1728 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1731 $message_id = self::messageExists($importer['uid'], $guid);
1736 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1737 if (!$toplevel_parent_item) {
1741 $person = FContact::getByURL($author);
1742 if (!is_array($person)) {
1743 Logger::notice('Unable to find author details');
1747 // Fetch the contact id - if we know this contact
1748 $author_contact = self::authorContactByUrl($contact, $person, $importer['uid']);
1750 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1751 // We would accept this anyhow.
1752 if ($positive == 'true') {
1753 $verb = Activity::LIKE;
1755 $verb = Activity::DISLIKE;
1760 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1762 $datarray['uid'] = $importer['uid'];
1763 $datarray['contact-id'] = $author_contact['cid'];
1764 $datarray['network'] = $author_contact['network'];
1766 $datarray = self::setDirection($datarray, $direction);
1768 $datarray['owner-link'] = $datarray['author-link'] = $person['url'];
1769 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($person['url'], 0);
1771 $datarray['guid'] = $guid;
1772 $datarray['uri'] = self::getUriFromGuid($author, $guid);
1774 $datarray['verb'] = $verb;
1775 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
1776 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1778 $datarray['object-type'] = Activity\ObjectType::NOTE;
1780 $datarray['body'] = $verb;
1782 // Diaspora doesn't provide a date for likes
1783 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
1785 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1786 if ($toplevel_parent_item['gravity'] != Item::GRAVITY_PARENT) {
1787 $toplevel = Post::selectFirst(['origin'], ['id' => $toplevel_parent_item['parent']]);
1788 $origin = $toplevel['origin'];
1790 $origin = $toplevel_parent_item['origin'];
1793 // If we are the origin of the parent we store the original data.
1794 // We notify our followers during the item storage.
1796 $datarray['diaspora_signed_text'] = json_encode($data);
1799 if (Item::isTooOld($datarray)) {
1800 Logger::info('Like is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1804 $message_id = Item::insert($datarray);
1806 if ($message_id <= 0) {
1811 Logger::info('Stored like ' . $datarray['guid'] . ' with message id ' . $message_id);
1812 if ($datarray['uid'] == 0) {
1813 Item::distribute($message_id, json_encode($data));
1821 * Processes private messages
1823 * @param array $importer Array of the importer user
1824 * @param SimpleXMLElement $data The message object
1826 * @return bool Success?
1827 * @throws \Exception
1829 private static function receiveMessage(array $importer, SimpleXMLElement $data): bool
1831 $author = XML::unescape($data->author);
1832 $guid = XML::unescape($data->guid);
1833 $conversation_guid = XML::unescape($data->conversation_guid);
1834 $text = XML::unescape($data->text);
1835 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1837 $contact = self::allowedContactByHandle($importer, $author, true);
1842 if (!empty($contact['gsid'])) {
1843 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1846 $conversation = null;
1848 $condition = ['uid' => $importer['uid'], 'guid' => $conversation_guid];
1849 $conversation = DBA::selectFirst('conv', [], $condition);
1851 if (!DBA::isResult($conversation)) {
1852 Logger::notice('Conversation not available.');
1856 $message_uri = $author . ':' . $guid;
1858 $person = FContact::getByURL($author);
1860 Logger::notice('Unable to find author details');
1864 $body = Markdown::toBBCode($text);
1866 $body = self::replacePeopleGuid($body, $person['url']);
1868 return Mail::insert([
1869 'uid' => $importer['uid'],
1871 'convid' => $conversation['id'],
1872 'from-name' => $person['name'],
1873 'from-photo' => $person['photo'],
1874 'from-url' => $person['url'],
1875 'contact-id' => $contact['id'],
1876 'title' => $conversation['subject'],
1879 'uri' => $message_uri,
1880 'parent-uri' => $author . ':' . $conversation['guid'],
1881 'created' => $created_at
1886 * Processes participations - unsupported by now
1888 * @param array $importer Array of the importer user
1889 * @param SimpleXMLElement $data The message object
1890 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1892 * @return bool success
1893 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1894 * @throws \ImagickException
1896 private static function receiveParticipation(array $importer, SimpleXMLElement $data, int $direction): bool
1898 $author = strtolower(XML::unescape($data->author));
1899 $guid = XML::unescape($data->guid);
1900 $parent_guid = XML::unescape($data->parent_guid);
1902 $contact = self::allowedContactByHandle($importer, $author, true);
1907 if (!empty($contact['gsid'])) {
1908 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1911 if (self::messageExists($importer['uid'], $guid)) {
1915 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1916 if (!$toplevel_parent_item) {
1920 if (!$toplevel_parent_item['origin']) {
1921 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1924 if (!in_array($toplevel_parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
1925 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1929 $person = FContact::getByURL($author);
1930 if (!is_array($person)) {
1931 Logger::notice('Person not found: ' . $author);
1935 $author_contact = self::authorContactByUrl($contact, $person, $importer['uid']);
1937 // Store participation
1940 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1942 $datarray['uid'] = $importer['uid'];
1943 $datarray['contact-id'] = $author_contact['cid'];
1944 $datarray['network'] = $author_contact['network'];
1946 $datarray = self::setDirection($datarray, $direction);
1948 $datarray['owner-link'] = $datarray['author-link'] = $person['url'];
1949 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($person['url'], 0);
1951 $datarray['guid'] = $guid;
1952 $datarray['uri'] = self::getUriFromGuid($author, $guid);
1954 $datarray['verb'] = Activity::FOLLOW;
1955 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
1956 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1958 $datarray['object-type'] = Activity\ObjectType::NOTE;
1960 $datarray['body'] = Activity::FOLLOW;
1962 // Diaspora doesn't provide a date for a participation
1963 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
1965 if (Item::isTooOld($datarray)) {
1966 Logger::info('Participation is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1970 $message_id = Item::insert($datarray);
1972 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
1974 // Send all existing comments and likes to the requesting server
1975 $comments = Post::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb', 'gravity'],
1976 ['parent' => $toplevel_parent_item['id'], 'gravity' => [Item::GRAVITY_COMMENT, Item::GRAVITY_ACTIVITY]]);
1977 while ($comment = Post::fetch($comments)) {
1978 if (($comment['gravity'] == Item::GRAVITY_ACTIVITY) && !in_array($comment['verb'], [Activity::LIKE, Activity::DISLIKE])) {
1979 Logger::info('Unsupported activities are not relayed', ['item' => $comment['id'], 'verb' => $comment['verb']]);
1983 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
1984 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
1988 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
1989 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
1993 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact['cid']]);
1994 if (Worker::add(Worker::PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['uri-id'], $author_contact['cid'], $datarray['uid'])) {
1995 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
1998 DBA::close($comments);
2004 * Processes photos - unneeded
2006 * @param array $importer Array of the importer user
2007 * @param SimpleXMLElement $data The message object
2009 * @return bool always true
2011 private static function receivePhoto(array $importer, $data)
2013 // There doesn't seem to be a reason for this function,
2014 // since the photo data is transmitted in the status message as well
2019 * Processes poll participations - unssupported
2021 * @param array $importer Array of the importer user
2022 * @param object $data The message object
2024 * @return bool always true
2026 private static function receivePollParticipation(array $importer, $data)
2028 // We don't support polls by now
2033 * Processes incoming profile updates
2035 * @param array $importer Array of the importer user
2036 * @param SimpleXMLElement $data The message object
2038 * @return bool Success
2039 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2040 * @throws \ImagickException
2042 private static function receiveProfile(array $importer, SimpleXMLElement $data): bool
2044 $author = strtolower(XML::unescape($data->author));
2046 $contact = self::contactByHandle($importer['uid'], $author);
2051 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? ' ' . XML::unescape($data->last_name) : '');
2052 $image_url = XML::unescape($data->image_url);
2053 $birthday = XML::unescape($data->birthday);
2054 $about = Markdown::toBBCode(XML::unescape($data->bio));
2055 $location = Markdown::toBBCode(XML::unescape($data->location));
2056 $searchable = (XML::unescape($data->searchable) == 'true');
2057 $nsfw = (XML::unescape($data->nsfw) == 'true');
2058 $tags = XML::unescape($data->tag_string);
2060 $tags = explode('#', $tags);
2063 foreach ($tags as $tag) {
2064 $tag = trim(strtolower($tag));
2070 $keywords = implode(', ', $keywords);
2072 $handle_parts = explode('@', $author);
2073 $nick = $handle_parts[0];
2076 $name = $handle_parts[0];
2079 if (preg_match('|^https?://|', $image_url) === 0) {
2080 // @TODO No HTTPS here?
2081 $image_url = 'http://' . $handle_parts[1] . $image_url;
2084 Contact::updateAvatar($contact['id'], $image_url);
2086 // Generic birthday. We don't know the timezone. The year is irrelevant.
2088 $birthday = str_replace('1000', '1901', $birthday);
2090 if ($birthday != '') {
2091 $birthday = DateTimeFormat::utc($birthday, 'Y-m-d');
2094 // this is to prevent multiple birthday notifications in a single year
2095 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2097 if (substr($birthday, 5) === substr($contact['bd'], 5)) {
2098 $birthday = $contact['bd'];
2101 $fields = ['name' => $name, 'location' => $location,
2102 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2103 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2104 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2106 if (!empty($birthday)) {
2107 $fields['bd'] = $birthday;
2110 Contact::update($fields, ['id' => $contact['id']]);
2112 Logger::info('Profile of contact ' . $contact['id'] . ' stored for user ' . $importer['uid']);
2118 * Processes incoming friend requests
2120 * @param array $importer Array of the importer user
2121 * @param array $contact The contact that send the request
2123 * @throws \Exception
2125 private static function receiveRequestMakeFriend(array $importer, array $contact)
2127 if ($contact['rel'] == Contact::SHARING) {
2129 ['rel' => Contact::FRIEND, 'writable' => true],
2130 ['id' => $contact['id'], 'uid' => $importer['uid']]
2136 * Processes incoming sharing notification
2138 * @param array $importer Array of the importer user
2139 * @param SimpleXMLElement $data The message object
2141 * @return bool Success
2142 * @throws \Exception
2144 private static function receiveContactRequest(array $importer, SimpleXMLElement $data): bool
2146 $author = XML::unescape($data->author);
2147 $recipient = XML::unescape($data->recipient);
2149 if (!$author || !$recipient) {
2153 // the current protocol version doesn't know these fields
2154 // That means that we will assume their existance
2155 if (isset($data->following)) {
2156 $following = (XML::unescape($data->following) == 'true');
2161 if (isset($data->sharing)) {
2162 $sharing = (XML::unescape($data->sharing) == 'true');
2167 $contact = self::contactByHandle($importer['uid'], $author);
2169 // perhaps we were already sharing with this person. Now they're sharing with us.
2170 // That makes us friends.
2173 Logger::info('Author ' . $author . ' (Contact ' . $contact['id'] . ') wants to follow us.');
2174 self::receiveRequestMakeFriend($importer, $contact);
2176 // refetch the contact array
2177 $contact = self::contactByHandle($importer['uid'], $author);
2179 // If we are now friends, we are sending a share message.
2180 // Normally we needn't to do so, but the first message could have been vanished.
2181 if (in_array($contact['rel'], [Contact::FRIEND])) {
2182 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2183 if (DBA::isResult($user)) {
2184 Logger::info('Sending share message to author ' . $author . ' - Contact: ' . $contact['id'] . ' - User: ' . $importer['uid']);
2185 self::sendShare($user, $contact);
2190 Logger::info("Author " . $author . " doesn't want to follow us anymore.");
2191 Contact::removeFollower($contact);
2196 if (!$following && $sharing && in_array($importer['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2197 Logger::info("Author " . $author . " wants to share with us - but doesn't want to listen. Request is ignored.");
2199 } elseif (!$following && !$sharing) {
2200 Logger::info("Author " . $author . " doesn't want anything - and we don't know the author. Request is ignored.");
2202 } elseif (!$following && $sharing) {
2203 Logger::info("Author " . $author . " wants to share with us.");
2204 } elseif ($following && $sharing) {
2205 Logger::info("Author " . $author . " wants to have a bidirectional conection.");
2206 } elseif ($following && !$sharing) {
2207 Logger::info("Author " . $author . " wants to listen to us.");
2210 $ret = FContact::getByURL($author);
2212 if (!$ret || ($ret['network'] != Protocol::DIASPORA)) {
2213 Logger::notice("Cannot resolve diaspora handle " . $author . " for ".$recipient);
2217 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2219 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2224 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2225 'author-link' => $ret['url']];
2227 $result = Contact::addRelationship($importer, $contact, $item, false);
2228 if ($result === true) {
2229 $contact_record = self::contactByHandle($importer['uid'], $author);
2230 if (!$contact_record) {
2231 Logger::info('unable to locate newly created contact record.');
2235 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2236 if (DBA::isResult($user)) {
2237 self::sendShare($user, $contact_record);
2239 // Send the profile data, maybe it weren't transmitted before
2240 self::sendProfile($importer['uid'], [$contact_record]);
2248 * Stores a reshare activity
2250 * @param array $item Array of reshare post
2251 * @param integer $parent_message_id Id of the parent post
2252 * @param string $guid GUID string of reshare action
2253 * @param string $author Author handle
2255 private static function addReshareActivity(array $item, int $parent_message_id, string $guid, string $author)
2257 $parent = Post::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2261 $datarray['uid'] = $item['uid'];
2262 $datarray['contact-id'] = $item['contact-id'];
2263 $datarray['network'] = $item['network'];
2265 $datarray['author-link'] = $item['author-link'];
2266 $datarray['author-id'] = $item['author-id'];
2268 $datarray['owner-link'] = $datarray['author-link'];
2269 $datarray['owner-id'] = $datarray['author-id'];
2271 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2272 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2273 $datarray['thr-parent'] = $parent['uri'];
2275 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2276 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
2277 $datarray['object-type'] = Activity\ObjectType::NOTE;
2279 $datarray['protocol'] = $item['protocol'];
2280 $datarray['source'] = $item['source'];
2281 $datarray['direction'] = $item['direction'];
2282 $datarray['post-reason'] = $item['post-reason'];
2284 $datarray['plink'] = self::plink($author, $datarray['guid']);
2285 $datarray['private'] = $item['private'];
2286 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2288 if (Item::isTooOld($datarray)) {
2289 Logger::info('Reshare activity is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2293 $message_id = Item::insert($datarray);
2296 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2297 if ($datarray['uid'] == 0) {
2298 Item::distribute($message_id);
2304 * Processes a reshare message
2306 * @param array $importer Array of the importer user
2307 * @param SimpleXMLElement $data The message object
2308 * @param string $xml The original XML of the message
2309 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2311 * @return bool Success or failure
2312 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2313 * @throws \ImagickException
2315 private static function receiveReshare(array $importer, SimpleXMLElement $data, string $xml, int $direction): bool
2317 $author = XML::unescape($data->author);
2318 $guid = XML::unescape($data->guid);
2319 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2320 $root_author = XML::unescape($data->root_author);
2321 $root_guid = XML::unescape($data->root_guid);
2322 /// @todo handle unprocessed property "provider_display_name"
2323 $public = XML::unescape($data->public);
2325 $contact = self::allowedContactByHandle($importer, $author, false);
2330 if (!empty($contact['gsid'])) {
2331 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2334 $message_id = self::messageExists($importer['uid'], $guid);
2339 $original_person = FContact::getByURL($root_author);
2340 if (!$original_person) {
2346 $datarray['uid'] = $importer['uid'];
2347 $datarray['contact-id'] = $contact['id'];
2348 $datarray['network'] = Protocol::DIASPORA;
2350 $datarray['author-link'] = $contact['url'];
2351 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2353 $datarray['owner-link'] = $datarray['author-link'];
2354 $datarray['owner-id'] = $datarray['author-id'];
2356 $datarray['guid'] = $guid;
2357 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($author, $guid);
2358 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2360 $datarray['verb'] = Activity::POST;
2361 $datarray['gravity'] = Item::GRAVITY_PARENT;
2363 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2364 $datarray['source'] = $xml;
2366 $datarray = self::setDirection($datarray, $direction);
2368 $datarray['quote-uri-id'] = self::getQuoteUriId($root_guid, $importer['uid'], $original_person['url']);
2369 if (empty($datarray['quote-uri-id'])) {
2373 $datarray['body'] = '';
2374 $datarray['plink'] = self::plink($author, $guid);
2375 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2376 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2378 self::fetchGuid($datarray);
2380 if (Item::isTooOld($datarray)) {
2381 Logger::info('Reshare is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2385 $message_id = Item::insert($datarray);
2387 self::sendParticipation($contact, $datarray);
2389 $root_message_id = self::messageExists($importer['uid'], $root_guid);
2390 if ($root_message_id) {
2391 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2395 Logger::info('Stored reshare ' . $datarray['guid'] . ' with message id ' . $message_id);
2396 if ($datarray['uid'] == 0) {
2397 Item::distribute($message_id);
2405 private static function getQuoteUriId(string $guid, int $uid, string $host): int
2407 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2409 if (!DBA::isResult($shared_item) && !empty($host) && Diaspora::storeByGuid($guid, $host, true)) {
2410 Logger::debug('Fetched post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2411 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2412 } elseif (DBA::isResult($shared_item)) {
2413 Logger::debug('Found existing post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2416 if (!DBA::isResult($shared_item)) {
2417 Logger::notice('Post does not exist.', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2421 return $shared_item['uri-id'];
2425 * Processes retractions
2427 * @param array $importer Array of the importer user
2428 * @param array $contact The contact of the item owner
2429 * @param SimpleXMLElement $data The message object
2431 * @return bool success
2432 * @throws \Exception
2434 private static function itemRetraction(array $importer, array $contact, SimpleXMLElement $data): bool
2436 $author = XML::unescape($data->author);
2437 $target_guid = XML::unescape($data->target_guid);
2438 $target_type = XML::unescape($data->target_type);
2440 $person = FContact::getByURL($author);
2441 if (!is_array($person)) {
2442 Logger::notice('Unable to find author detail for ' . $author);
2446 if (empty($contact['url'])) {
2447 $contact['url'] = $person['url'];
2450 // Fetch items that are about to be deleted
2451 $fields = ['uid', 'id', 'parent', 'author-link', 'uri-id'];
2453 // When we receive a public retraction, we delete every item that we find.
2454 if ($importer['uid'] == 0) {
2455 $condition = ['guid' => $target_guid, 'deleted' => false];
2457 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2460 $r = Post::select($fields, $condition);
2461 if (!DBA::isResult($r)) {
2462 Logger::notice('Target guid ' . $target_guid . ' was not found on this system for user ' . $importer['uid'] . '.');
2466 while ($item = Post::fetch($r)) {
2467 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2468 Logger::info("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.");
2472 // Fetch the parent item
2473 $parent = Post::selectFirst(['author-link'], ['id' => $item['parent']]);
2475 // Only delete it if the parent author really fits
2476 if (!Strings::compareLink($parent['author-link'], $contact['url']) && !Strings::compareLink($item['author-link'], $contact['url'])) {
2477 Logger::info("Thread author " . $parent['author-link'] . " and item author " . $item['author-link'] . " don't fit to expected contact " . $contact['url']);
2481 Item::markForDeletion(['id' => $item['id']]);
2483 Logger::info('Deleted target ' . $target_guid . ' (' . $item['id'] . ') from user ' . $item['uid'] . ' parent: ' . $item['parent']);
2491 * Receives retraction messages
2493 * @param array $importer Array of the importer user
2494 * @param string $sender The sender of the message
2495 * @param SimpleXMLElement $data The message object
2497 * @return bool Success
2498 * @throws \Exception
2500 private static function receiveRetraction(array $importer, string $sender, SimpleXMLElement $data)
2502 $target_type = XML::unescape($data->target_type);
2504 $contact = self::contactByHandle($importer['uid'], $sender);
2505 if (!$contact && (in_array($target_type, ['Contact', 'Person']))) {
2506 Logger::notice('Cannot find contact for sender: ' . $sender . ' and user ' . $importer['uid']);
2514 Logger::info('Got retraction for ' . $target_type . ', sender ' . $sender . ' and user ' . $importer['uid']);
2516 switch ($target_type) {
2521 case 'StatusMessage':
2522 return self::itemRetraction($importer, $contact, $data);
2524 case 'PollParticipation':
2526 // Currently unsupported
2530 Logger::notice('Unknown target type ' . $target_type);
2537 * Checks if an incoming message is wanted
2539 * @param array $item
2540 * @param string $author
2541 * @param string $body
2542 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2544 * @return boolean Is the message wanted?
2546 private static function isSolicitedMessage(array $item, string $author, string $body, int $direction): bool
2548 $contact = Contact::getByURL($author);
2549 if (DBA::exists('contact', ['`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)', $contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) {
2550 Logger::debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2554 if ($direction == self::FORCED_FETCH) {
2555 Logger::debug('Post is a forced fetch - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2559 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
2560 if (Relay::isSolicitedPost($tags, $body, $contact['id'], $item['uri'], Protocol::DIASPORA)) {
2561 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2569 * Store an attached photo in the post-media table
2572 * @param object $photo
2575 private static function storePhotoAsMedia(int $uriid, $photo)
2577 // @TODO Need to find object type, roland@f.haeder.net
2578 Logger::debug('photo='.get_class($photo));
2580 $data['uri-id'] = $uriid;
2581 $data['type'] = Post\Media::IMAGE;
2582 $data['url'] = XML::unescape($photo->remote_photo_path) . XML::unescape($photo->remote_photo_name);
2583 $data['height'] = (int)XML::unescape($photo->height ?? 0);
2584 $data['width'] = (int)XML::unescape($photo->width ?? 0);
2585 $data['description'] = XML::unescape($photo->text ?? '');
2587 Post\Media::insert($data);
2591 * Set direction and post reason
2593 * @param array $datarray
2594 * @param integer $direction
2598 public static function setDirection(array $datarray, int $direction): array
2600 $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
2602 if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
2603 $datarray['post-reason'] = Item::PR_FETCHED;
2604 } elseif ($datarray['uid'] == 0) {
2605 $datarray['post-reason'] = Item::PR_GLOBAL;
2607 $datarray['post-reason'] = Item::PR_PUSHED;
2614 * Receives status messages
2616 * @param array $importer Array of the importer user
2617 * @param SimpleXMLElement $data The message object
2618 * @param string $xml The original XML of the message
2619 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2621 * @return int|bool The message id of the newly created item or false on error
2622 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2623 * @throws \ImagickException
2625 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, string $xml, int $direction)
2627 $author = XML::unescape($data->author);
2628 $guid = XML::unescape($data->guid);
2629 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2630 $public = XML::unescape($data->public);
2631 $text = XML::unescape($data->text);
2632 $provider_display_name = XML::unescape($data->provider_display_name);
2634 $contact = self::allowedContactByHandle($importer, $author, false);
2639 if (!empty($contact['gsid'])) {
2640 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2643 $message_id = self::messageExists($importer['uid'], $guid);
2649 if ($data->location) {
2650 foreach ($data->location->children() as $fieldname => $data) {
2651 $address[$fieldname] = XML::unescape($data);
2655 $raw_body = $body = Markdown::toBBCode($text);
2659 $datarray['guid'] = $guid;
2660 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($author, $guid);
2661 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2663 // Attach embedded pictures to the body
2665 foreach ($data->photo as $photo) {
2666 self::storePhotoAsMedia($datarray['uri-id'], $photo);
2669 $datarray['object-type'] = Activity\ObjectType::IMAGE;
2670 $datarray['post-type'] = Item::PT_IMAGE;
2671 } elseif ($data->poll) {
2672 $datarray['object-type'] = Activity\ObjectType::NOTE;
2673 $datarray['post-type'] = Item::PT_POLL;
2675 $datarray['object-type'] = Activity\ObjectType::NOTE;
2676 $datarray['post-type'] = Item::PT_NOTE;
2679 /// @todo enable support for polls
2680 //if ($data->poll) {
2681 // foreach ($data->poll as $poll)
2686 /// @todo enable support for events
2688 $datarray['uid'] = $importer['uid'];
2689 $datarray['contact-id'] = $contact['id'];
2690 $datarray['network'] = Protocol::DIASPORA;
2692 $datarray['author-link'] = $contact['url'];
2693 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2695 $datarray['owner-link'] = $datarray['author-link'];
2696 $datarray['owner-id'] = $datarray['author-id'];
2698 $datarray['verb'] = Activity::POST;
2699 $datarray['gravity'] = Item::GRAVITY_PARENT;
2701 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2702 $datarray['source'] = $xml;
2704 $datarray = self::setDirection($datarray, $direction);
2706 $datarray['body'] = self::replacePeopleGuid($body, $contact['url']);
2707 $datarray['raw-body'] = self::replacePeopleGuid($raw_body, $contact['url']);
2709 self::storeMentions($datarray['uri-id'], $text);
2710 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
2712 if (!self::isSolicitedMessage($datarray, $author, $body, $direction)) {
2713 DBA::delete('item-uri', ['uri' => $datarray['uri']]);
2717 if ($provider_display_name != '') {
2718 $datarray['app'] = $provider_display_name;
2721 $datarray['plink'] = self::plink($author, $guid);
2722 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2723 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2725 if (isset($address['address'])) {
2726 $datarray['location'] = $address['address'];
2729 if (isset($address['lat']) && isset($address['lng'])) {
2730 $datarray['coord'] = $address['lat'] . ' ' . $address['lng'];
2733 self::fetchGuid($datarray);
2735 if (Item::isTooOld($datarray)) {
2736 Logger::info('Status is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2740 $message_id = Item::insert($datarray);
2742 self::sendParticipation($contact, $datarray);
2745 Logger::info('Stored item ' . $datarray['guid'] . ' with message id ' . $message_id);
2746 if ($datarray['uid'] == 0) {
2747 Item::distribute($message_id);
2755 /* ************************************************************************************** *
2756 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2757 * ************************************************************************************** */
2760 * returnes the handle of a contact
2762 * @param array $contact contact array
2764 * @return string the handle in the format user@domain.tld
2765 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2767 private static function myHandle(array $contact): string
2769 if (!empty($contact['addr'])) {
2770 return $contact['addr'];
2773 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2774 // So - just in case - we build the the address here.
2775 if ($contact['nickname'] != '') {
2776 $nick = $contact['nickname'];
2778 $nick = $contact['nick'];
2781 return $nick . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
2786 * Creates the data for a private message in the new format
2788 * @param string $msg The message that is to be transmitted
2789 * @param array $user The record of the sender
2790 * @param array $contact Target of the communication
2791 * @param string $prvkey The private key of the sender
2792 * @param string $pubkey The public key of the receiver
2794 * @return string The encrypted data
2795 * @throws \Exception
2797 public static function encodePrivateData(string $msg, array $user, array $contact, string $prvkey, string $pubkey): string
2799 Logger::debug('Message: ' . $msg);
2801 // without a public key nothing will work
2803 Logger::notice('pubkey missing: contact id: ' . $contact['id']);
2807 $aes_key = random_bytes(32);
2808 $b_aes_key = base64_encode($aes_key);
2809 $iv = random_bytes(16);
2810 $b_iv = base64_encode($iv);
2812 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2814 $json = json_encode(['iv' => $b_iv, 'key' => $b_aes_key]);
2816 $encrypted_key_bundle = '';
2817 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
2821 $json_object = json_encode(
2823 'aes_key' => base64_encode($encrypted_key_bundle),
2824 'encrypted_magic_envelope' => base64_encode($ciphertext)
2828 return $json_object;
2832 * Creates the envelope for the "fetch" endpoint and for the new format
2834 * @param string $msg The message that is to be transmitted
2835 * @param array $user The record of the sender
2837 * @return string The envelope
2838 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2840 public static function buildMagicEnvelope(string $msg, array $user): string
2842 $b64url_data = Strings::base64UrlEncode($msg);
2843 $data = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
2845 $key_id = Strings::base64UrlEncode(self::myHandle($user));
2846 $type = 'application/xml';
2847 $encoding = 'base64url';
2848 $alg = 'RSA-SHA256';
2849 $signable_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
2851 // Fallback if the private key wasn't transmitted in the expected field
2852 if ($user['uprvkey'] == '') {
2853 $user['uprvkey'] = $user['prvkey'];
2856 $signature = Crypto::rsaSign($signable_data, $user['uprvkey']);
2857 $sig = Strings::base64UrlEncode($signature);
2862 '@attributes' => ['type' => $type],
2863 'me:encoding' => $encoding,
2866 '@attributes2' => ['key_id' => $key_id]
2870 $namespaces = ['me' => ActivityNamespace::SALMON_ME];
2872 return XML::fromArray($xmldata, $xml, false, $namespaces);
2876 * Create the envelope for a message
2878 * @param string $msg The message that is to be transmitted
2879 * @param array $user The record of the sender
2880 * @param array $contact Target of the communication
2881 * @param string $prvkey The private key of the sender
2882 * @param string $pubkey The public key of the receiver
2883 * @param bool $public Is the message public?
2885 * @return string The message that will be transmitted to other servers
2886 * @throws \Exception
2888 public static function buildMessage(string $msg, array $user, array $contact, string $prvkey, string $pubkey, bool $public = false): string
2890 // The message is put into an envelope with the sender's signature
2891 $envelope = self::buildMagicEnvelope($msg, $user);
2893 // Private messages are put into a second envelope, encrypted with the receivers public key
2895 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
2902 * Creates a signature for a message
2904 * @param array $owner the array of the owner of the message
2905 * @param array $message The message that is to be signed
2907 * @return string The signature
2909 private static function signature(array $owner, array $message): string
2912 unset($sigmsg['author_signature']);
2913 unset($sigmsg['parent_author_signature']);
2915 $signed_text = implode(';', $sigmsg);
2917 return base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
2921 * Transmit a message to a target server
2923 * @param array $owner the array of the item owner
2924 * @param array $contact Target of the communication
2925 * @param string $envelope The message that is to be transmitted
2926 * @param bool $public_batch Is it a public post?
2927 * @param string $guid message guid
2929 * @return int Result of the transmission
2930 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2931 * @throws \ImagickException
2933 private static function transmit(array $owner, array $contact, string $envelope, bool $public_batch, string $guid = ''): int
2935 $enabled = intval(DI::config()->get('system', 'diaspora_enabled'));
2940 $logid = Strings::getRandomHex(4);
2942 // We always try to use the data from the fcontact table.
2943 // This is important for transmitting data to Friendica servers.
2944 if (!empty($contact['addr'])) {
2945 $fcontact = FContact::getByURL($contact['addr']);
2946 if (!empty($fcontact)) {
2947 $dest_url = ($public_batch ? $fcontact['batch'] : $fcontact['notify']);
2951 if (empty($dest_url)) {
2952 $dest_url = ($public_batch ? $contact['batch'] : $contact['notify']);
2956 Logger::notice('No URL for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2960 Logger::notice('transmit: ' . $logid . '-' . $guid . ' ' . $dest_url);
2962 if (!intval(DI::config()->get('system', 'diaspora_test'))) {
2963 $content_type = (($public_batch) ? 'application/magic-envelope+xml' : 'application/json');
2965 $postResult = DI::httpClient()->post($dest_url . '/', $envelope, ['Content-Type' => $content_type]);
2966 $return_code = $postResult->getReturnCode();
2968 Logger::notice('test_mode');
2972 Logger::notice('transmit: ' . $logid . '-' . $guid . ' to ' . $dest_url . ' returns: ' . $return_code);
2974 return $return_code ? $return_code : -1;
2979 * Build the post xml
2981 * @param string $type The message type
2982 * @param array $message The message data
2984 * @return string The post XML
2986 public static function buildPostXml(string $type, array $message): string
2988 $data = [$type => $message];
2990 return XML::fromArray($data, $xml);
2994 * Builds and transmit messages
2996 * @param array $owner the array of the item owner
2997 * @param array $contact Target of the communication
2998 * @param string $type The message type
2999 * @param array $message The message data
3000 * @param bool $public_batch Is it a public post?
3001 * @param string $guid message guid
3003 * @return int Result of the transmission
3004 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3005 * @throws \ImagickException
3007 private static function buildAndTransmit(array $owner, array $contact, string $type, array $message, bool $public_batch = false, string $guid = '')
3009 $msg = self::buildPostXml($type, $message);
3011 // Fallback if the private key wasn't transmitted in the expected field
3012 if (empty($owner['uprvkey'])) {
3013 $owner['uprvkey'] = $owner['prvkey'];
3016 // When sending content to Friendica contacts using the Diaspora protocol
3017 // we have to fetch the public key from the fcontact.
3018 // This is due to the fact that legacy DFRN had unique keys for every contact.
3019 $pubkey = $contact['pubkey'];
3020 if (!empty($contact['addr'])) {
3021 $fcontact = FContact::getByURL($contact['addr']);
3022 if (!empty($fcontact)) {
3023 $pubkey = $fcontact['pubkey'];
3026 // The "addr" field should always be filled.
3027 // If this isn't the case, it will raise a notice some lines later.
3028 // And in the log we will see where it came from and we can handle it there.
3029 Logger::notice('Empty addr', ['contact' => $contact ?? [], 'callstack' => System::callstack(20)]);
3032 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $pubkey ?? '', $public_batch);
3034 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3036 Logger::info('Transmitted message', ['owner' => $owner['uid'], 'target' => $contact['addr'], 'type' => $type, 'guid' => $guid, 'result' => $return_code]);
3038 return $return_code;
3042 * sends a participation (Used to get all further updates)
3044 * @param array $contact Target of the communication
3045 * @param array $item Item array
3047 * @return int The result of the transmission
3048 * @throws \Exception
3050 private static function sendParticipation(array $contact, array $item): int
3052 // Don't send notifications for private postings
3053 if ($item['private'] == Item::PRIVATE) {
3057 $cachekey = 'diaspora:sendParticipation:' . $item['guid'];
3059 $result = DI::cache()->get($cachekey);
3060 if (!is_null($result)) {
3064 // Fetch some user id to have a valid handle to transmit the participation.
3065 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3066 // If the item belongs to a user, we take this user id.
3067 if ($item['uid'] == 0) {
3068 // @todo Possibly use an administrator account?
3069 $condition = ['verified' => true, 'blocked' => false,
3070 'account_removed' => false, 'account_expired' => false, 'account-type' => User::ACCOUNT_TYPE_PERSON];
3071 $first_user = DBA::selectFirst('user', ['uid'], $condition, ['order' => ['uid']]);
3072 $owner = User::getOwnerDataById($first_user['uid']);
3074 $owner = User::getOwnerDataById($item['uid']);
3077 $author = self::myHandle($owner);
3080 'author' => $author,
3081 'guid' => System::createUUID(),
3082 'parent_type' => 'Post',
3083 'parent_guid' => $item['guid']
3086 Logger::info('Send participation for ' . $item['guid'] . ' by ' . $author);
3088 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3089 DI::cache()->set($cachekey, $item['guid'], Duration::QUARTER_HOUR);
3091 return self::buildAndTransmit($owner, $contact, 'participation', $message);
3095 * sends an account migration
3097 * @param array $owner the array of the item owner
3098 * @param array $contact Target of the communication
3099 * @param int $uid User ID
3101 * @return int The result of the transmission
3102 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3103 * @throws \ImagickException
3105 public static function sendAccountMigration(array $owner, array $contact, int $uid): int
3107 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3108 $profile = self::createProfileData($uid);
3110 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3111 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
3114 'author' => $old_handle,
3115 'profile' => $profile,
3116 'signature' => $signature
3119 Logger::info('Send account migration', ['msg' => $message]);
3121 return self::buildAndTransmit($owner, $contact, 'account_migration', $message);
3125 * Sends a "share" message
3127 * @param array $owner the array of the item owner
3128 * @param array $contact Target of the communication
3130 * @return int The result of the transmission
3131 * @throws \Exception
3133 public static function sendShare(array $owner, array $contact): int
3136 * @todo support the different possible combinations of "following" and "sharing"
3137 * Currently, Diaspora only interprets the "sharing" field
3139 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3143 switch ($contact["rel"]) {
3144 case Contact::FRIEND:
3148 case Contact::SHARING:
3152 case Contact::FOLLOWER:
3159 'author' => self::myHandle($owner),
3160 'recipient' => $contact['addr'],
3161 'following' => 'true',
3165 Logger::info('Send share', ['msg' => $message]);
3167 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3171 * sends an "unshare"
3173 * @param array $owner the array of the item owner
3174 * @param array $contact Target of the communication
3176 * @return int The result of the transmission
3177 * @throws \Exception
3179 public static function sendUnshare(array $owner, array $contact): int
3182 'author' => self::myHandle($owner),
3183 'recipient' => $contact['addr'],
3184 'following' => 'false',
3185 'sharing' => 'false'
3188 Logger::info('Send unshare', ['msg' => $message]);
3190 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3194 * Fetch reshare details
3196 * @param array $item The message body that is to be check
3198 * @return array Reshare details (empty if the item is no reshare)
3199 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3200 * @throws \ImagickException
3202 public static function getReshareDetails(array $item): array
3204 $reshared = DI::contentItem()->getSharedPost($item, ['network', 'author-addr']);
3205 if (empty($reshared)) {
3209 // Skip if it isn't a pure repeated messages or not a real reshare
3210 if (!empty($reshared['comment']) || !in_array($reshared['post']['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
3215 'root_handle' => strtolower($reshared['post']['author-addr']),
3216 'root_guid' => $reshared['guid']
3221 * Create an event array
3223 * @param integer $event_id The id of the event
3225 * @return array with event data
3226 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3228 private static function buildEvent(string $event_id): array
3230 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
3231 if (!DBA::isResult($event)) {
3237 $owner = User::getOwnerDataById($event['uid']);
3242 $eventdata['author'] = self::myHandle($owner);
3244 if ($event['guid']) {
3245 $eventdata['guid'] = $event['guid'];
3248 $mask = DateTimeFormat::ATOM;
3250 /// @todo - establish "all day" events in Friendica
3251 $eventdata['all_day'] = 'false';
3253 $eventdata['timezone'] = 'UTC';
3255 if ($event['start']) {
3256 $eventdata['start'] = DateTimeFormat::utc($event['start'], $mask);
3258 if ($event['finish'] && !$event['nofinish']) {
3259 $eventdata['end'] = DateTimeFormat::utc($event['finish'], $mask);
3261 if ($event['summary']) {
3262 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3264 if ($event['desc']) {
3265 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3267 if ($event['location']) {
3268 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3269 $coord = Map::getCoordinates($event['location']);
3272 $location['address'] = html_entity_decode(BBCode::toMarkdown($event['location']));
3273 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3274 $location['lat'] = $coord['lat'];
3275 $location['lng'] = $coord['lon'];
3277 $location['lat'] = 0;
3278 $location['lng'] = 0;
3280 $eventdata['location'] = $location;
3287 * Create a post (status message or reshare)
3289 * @param array $item The item that will be exported
3290 * @param array $owner the array of the item owner
3293 * 'type' -> Message type ("status_message" or "reshare")
3294 * 'message' -> Array of XML elements of the status
3295 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3296 * @throws \ImagickException
3298 public static function buildStatus(array $item, array $owner)
3300 $cachekey = 'diaspora:buildStatus:' . $item['guid'];
3302 $result = DI::cache()->get($cachekey);
3303 if (!is_null($result)) {
3307 $myaddr = self::myHandle($owner);
3309 $public = ($item['private'] == Item::PRIVATE ? 'false' : 'true');
3310 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3311 $edited = DateTimeFormat::utc($item['edited'] ?? $item['created'], DateTimeFormat::ATOM);
3313 // Detect a share element and do a reshare
3314 if (($item['private'] != Item::PRIVATE) && ($ret = self::getReshareDetails($item))) {
3316 'author' => $myaddr,
3317 'guid' => $item['guid'],
3318 'created_at' => $created,
3319 'root_author' => $ret['root_handle'],
3320 'root_guid' => $ret['root_guid'],
3321 'provider_display_name' => $item['app'],
3327 $title = $item['title'];
3328 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
3330 // Fetch the title from an attached link - if there is one
3331 if (empty($item['title']) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3332 $page_data = BBCode::getAttachmentData($item['body']);
3333 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3334 $title = $page_data['title'];
3338 // convert to markdown
3339 $body = html_entity_decode(BBCode::toMarkdown($body));
3342 if (strlen($title)) {
3343 $body = '### ' . html_entity_decode($title) . "\n\n" . $body;
3346 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]);
3347 if (!empty($attachments)) {
3348 $body .= "\n[hr]\n";
3349 foreach ($attachments as $attachment) {
3350 $body .= "[" . $attachment['description'] . "](" . $attachment['url'] . ")\n";
3356 if ($item['location'] != '')
3357 $location['address'] = $item['location'];
3359 if ($item['coord'] != '') {
3360 $coord = explode(' ', $item['coord']);
3361 $location['lat'] = $coord[0];
3362 $location['lng'] = $coord[1];
3366 'author' => $myaddr,
3367 'guid' => $item['guid'],
3368 'created_at' => $created,
3369 'edited_at' => $edited,
3370 'public' => $public,
3372 'provider_display_name' => $item['app'],
3373 'location' => $location
3376 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3377 if (!isset($location['lat']) || !isset($location['lng'])) {
3378 unset($message['location']);
3381 if ($item['event-id'] > 0) {
3382 $event = self::buildEvent($item['event-id']);
3383 if (count($event)) {
3384 $message['event'] = $event;
3386 if (!empty($event['location']['address']) &&
3387 !empty($event['location']['lat']) &&
3388 !empty($event['location']['lng'])) {
3389 $message['location'] = $event['location'];
3392 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3393 // $message['text'] = '';
3397 $type = 'status_message';
3402 'message' => $message
3405 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3410 private static function prependParentAuthorMention(string $body, string $profile_url): string
3412 $profile = Contact::getByURL($profile_url, false, ['addr', 'name']);
3413 if (!empty($profile['addr'])
3414 && !strstr($body, $profile['addr'])
3415 && !strstr($body, $profile_url)
3417 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3426 * @param array $item The item that will be exported
3427 * @param array $owner the array of the item owner
3428 * @param array $contact Target of the communication
3429 * @param bool $public_batch Is it a public post?
3431 * @return int The result of the transmission
3432 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3433 * @throws \ImagickException
3435 public static function sendStatus(array $item, array $owner, array $contact, bool $public_batch = false): int
3437 $status = self::buildStatus($item, $owner);
3439 return self::buildAndTransmit($owner, $contact, $status['type'], $status['message'], $public_batch, $item['guid']);
3443 * Creates a "like" object
3445 * @param array $item The item that will be exported
3446 * @param array $owner the array of the item owner
3448 * @return array|bool The data for a "like" or false on error
3449 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3451 private static function constructLike(array $item, array $owner)
3453 $parent = Post::selectFirst(['guid', 'uri', 'thr-parent'], ['uri' => $item['thr-parent']]);
3454 if (!DBA::isResult($parent)) {
3458 $target_type = ($parent['uri'] === $parent['thr-parent'] ? 'Post' : 'Comment');
3460 if ($item['verb'] === Activity::LIKE) {
3462 } elseif ($item['verb'] === Activity::DISLIKE) {
3463 $positive = 'false';
3467 'author' => self::myHandle($owner),
3468 'guid' => $item['guid'],
3469 'parent_guid' => $parent['guid'],
3470 'parent_type' => $target_type,
3471 'positive' => $positive,
3472 'author_signature' => '',
3477 * Creates an "EventParticipation" object
3479 * @param array $item The item that will be exported
3480 * @param array $owner the array of the item owner
3482 * @return array|bool The data for an "EventParticipation" or false on error
3483 * @throws \Exception
3485 private static function constructAttend(array $item, array $owner)
3487 $parent = Post::selectFirst(['guid'], ['uri' => $item['thr-parent']]);
3488 if (!DBA::isResult($parent)) {
3492 switch ($item['verb']) {
3493 case Activity::ATTEND:
3494 $attend_answer = 'accepted';
3496 case Activity::ATTENDNO:
3497 $attend_answer = 'declined';
3499 case Activity::ATTENDMAYBE:
3500 $attend_answer = 'tentative';
3503 Logger::warning('Unknown verb ' . $item['verb'] . ' in item ' . $item['guid']);
3508 'author' => self::myHandle($owner),
3509 'guid' => $item['guid'],
3510 'parent_guid' => $parent['guid'],
3511 'status' => $attend_answer,
3512 'author_signature' => ''
3517 * Creates the object for a comment
3519 * @param array $item The item that will be exported
3520 * @param array $owner the array of the item owner
3522 * @return array|false The data for a comment
3523 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3525 private static function constructComment(array $item, array $owner)
3527 $cachekey = 'diaspora:constructComment:' . $item['guid'];
3529 $result = DI::cache()->get($cachekey);
3530 if (!is_null($result)) {
3534 $toplevel_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3535 if (!DBA::isResult($toplevel_item)) {
3536 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3540 $thread_parent_item = $toplevel_item;
3541 if ($item['thr-parent'] != $item['parent-uri']) {
3542 $thread_parent_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3545 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
3547 // The replied to autor mention is prepended for clarity if:
3548 // - Item replied isn't yours
3549 // - Item is public or explicit mentions are disabled
3550 // - Implicit mentions are enabled
3552 $item['author-id'] != $thread_parent_item['author-id']
3553 && ($thread_parent_item['gravity'] != Item::GRAVITY_PARENT)
3554 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3555 && !DI::config()->get('system', 'disable_implicit_mentions')
3557 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3560 $text = html_entity_decode(BBCode::toMarkdown($body));
3561 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3562 $edited = DateTimeFormat::utc($item['edited'], DateTimeFormat::ATOM);
3565 'author' => self::myHandle($owner),
3566 'guid' => $item['guid'],
3567 'created_at' => $created,
3568 'edited_at' => $edited,
3569 'parent_guid' => $toplevel_item['guid'],
3571 'author_signature' => '',
3574 // Send the thread parent guid only if it is a threaded comment
3575 if ($item['thr-parent'] != $item['parent-uri']) {
3576 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3579 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3585 * Send a like or a comment
3587 * @param array $item The item that will be exported
3588 * @param array $owner the array of the item owner
3589 * @param array $contact Target of the communication
3590 * @param bool $public_batch Is it a public post?
3592 * @return int The result of the transmission
3593 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3594 * @throws \ImagickException
3596 public static function sendFollowup(array $item, array $owner, array $contact, bool $public_batch = false): int
3598 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3599 $message = self::constructAttend($item, $owner);
3600 $type = 'event_participation';
3601 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3602 $message = self::constructLike($item, $owner);
3604 } elseif (!in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
3605 $message = self::constructComment($item, $owner);
3609 if (empty($message)) {
3613 $message['author_signature'] = self::signature($owner, $message);
3615 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3619 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3621 * @param array $item The item that will be exported
3622 * @param array $owner the array of the item owner
3623 * @param array $contact Target of the communication
3624 * @param bool $public_batch Is it a public post?
3626 * @return int The result of the transmission
3627 * @throws \Exception
3629 public static function sendRelay(array $item, array $owner, array $contact, bool $public_batch = false): int
3631 if ($item['deleted']) {
3632 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3633 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3639 Logger::info('Got relayable data ' . $type . ' for item ' . $item['guid'] . ' (' . $item['id'] . ')');
3641 $msg = json_decode($item['signed_text'], true);
3644 if (is_array($msg)) {
3645 foreach ($msg as $field => $data) {
3646 if (!$item['deleted']) {
3647 if ($field == 'diaspora_handle') {
3650 if ($field == 'target_type') {
3651 $field = 'parent_type';
3655 $message[$field] = $data;
3658 Logger::info('Signature text for item ' . $item['guid'] . ' (' . $item['id'] . ') could not be extracted: ' . $item['signed_text']);
3661 $message['parent_author_signature'] = self::signature($owner, $message);
3663 Logger::info('Relayed data', ['msg' => $message]);
3665 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3669 * Sends a retraction (deletion) of a message, like or comment
3671 * @param array $item The item that will be exported
3672 * @param array $owner the array of the item owner
3673 * @param array $contact Target of the communication
3674 * @param bool $public_batch Is it a public post?
3675 * @param bool $relay Is the retraction transmitted from a relay?
3677 * @return int The result of the transmission
3678 * @throws \Exception
3680 public static function sendRetraction(array $item, array $owner, array $contact, bool $public_batch = false, bool $relay = false): int
3682 $itemaddr = strtolower($item['author-addr']);
3684 $msg_type = 'retraction';
3686 if ($item['gravity'] == Item::GRAVITY_PARENT) {
3687 $target_type = 'Post';
3688 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3689 $target_type = 'Like';
3691 $target_type = 'Comment';
3695 'author' => $itemaddr,
3696 'target_guid' => $item['guid'],
3697 'target_type' => $target_type
3700 Logger::info('Got message', ['msg' => $message]);
3702 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item['guid']);
3708 * @param array $item The item that will be exported
3709 * @param array $owner The owner
3710 * @param array $contact Target of the communication
3712 * @return int The result of the transmission
3713 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3714 * @throws \ImagickException
3716 public static function sendMail(array $item, array $owner, array $contact): int
3718 $myaddr = self::myHandle($owner);
3720 $cnv = DBA::selectFirst('conv', [], ['id' => $item['convid'], 'uid' => $item['uid']]);
3721 if (!DBA::isResult($cnv)) {
3722 Logger::notice('Conversation not found.');
3726 $body = BBCode::toMarkdown($item['body']);
3727 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3730 'author' => $myaddr,
3731 'guid' => $item['guid'],
3732 'conversation_guid' => $cnv['guid'],
3734 'created_at' => $created,
3737 if ($item['reply']) {
3742 'author' => $cnv['creator'],
3743 'guid' => $cnv['guid'],
3744 'subject' => $cnv['subject'],
3745 'created_at' => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3746 'participants' => $cnv['recips'],
3750 $type = 'conversation';
3753 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item['guid']);
3757 * Split a name into first name and last name
3759 * @param string $name The name
3761 * @return array The array with "first" and "last"
3763 public static function splitName(string $name): array
3765 $name = trim($name);
3767 // Is the name longer than 64 characters? Then cut the rest of it.
3768 if (strlen($name) > 64) {
3769 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3770 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3772 $name = substr($name, 0, 64);
3776 // Take the first word as first name
3777 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3778 $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 last word as last name
3784 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3785 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3787 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3788 return ['first' => $first, 'last' => $last];
3791 // Take the first 32 characters if there is no space in the first 32 characters
3792 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3793 $first = substr($name, 0, 32);
3794 $last = substr($name, 32);
3795 return ['first' => $first, 'last' => $last];
3798 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3799 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3801 // Check if the last name is longer than 32 characters
3802 if (strlen($last) > 32) {
3803 if (strpos($last, ' ') <= 32) {
3804 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
3806 $last = substr($last, 0, 32);
3810 return ['first' => $first, 'last' => $last];
3814 * Create profile data
3816 * @param int $uid The user id
3818 * @return array The profile data
3819 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3821 private static function createProfileData(int $uid): array
3823 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
3825 if (!DBA::isResult($profile)) {
3829 $split_name = self::splitName($profile['name']);
3832 'author' => $profile['addr'],
3833 'first_name' => $split_name['first'],
3834 'last_name' => $split_name['last'],
3835 'image_url' => DI::baseUrl() . '/photo/custom/300/' . $profile['uid'] . '.jpg',
3836 'image_url_medium' => DI::baseUrl() . '/photo/custom/100/' . $profile['uid'] . '.jpg',
3837 'image_url_small' => DI::baseUrl() . '/photo/custom/50/' . $profile['uid'] . '.jpg',
3838 'searchable' => ($profile['net-publish'] ? 'true' : 'false'),
3842 'tag_string' => null,
3846 if ($data['searchable'] === 'true') {
3847 $data['birthday'] = '';
3849 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
3850 [$year, $month, $day] = sscanf($profile['dob'], '%4d-%2d-%2d');
3854 $data['birthday'] = DateTimeFormat::utc($year . '-' . $month . '-' . $day, 'Y-m-d');
3857 $data['about'] = BBCode::toMarkdown($profile['about'] ?? '');
3859 $data['location'] = $profile['location'];
3860 $data['tag_string'] = '';
3862 if ($profile['pub_keywords']) {
3863 $kw = str_replace(',', ' ', $profile['pub_keywords']);
3864 $kw = str_replace(' ', ' ', $kw);
3865 $arr = explode(' ', $kw);
3867 for ($x = 0; $x < 5; $x ++) {
3868 if (!empty($arr[$x])) {
3869 $data['tag_string'] .= '#'. trim($arr[$x]) .' ';
3874 $data['tag_string'] = trim($data['tag_string']);
3881 * Sends profile data
3883 * @param int $uid The user id
3884 * @param array $recipients optional, default empty array
3887 * @throws \Exception
3889 public static function sendProfile(int $uid, array $recipients = [])
3892 Logger::warning('Parameter "uid" is empty');
3896 $owner = User::getOwnerDataById($uid);
3897 if (empty($owner)) {
3898 Logger::warning('Cannot fetch User record', ['uid' => $uid]);
3902 if (empty($recipients)) {
3903 Logger::debug('No recipients provided, fetching for user', ['uid' => $uid]);
3904 $recipients = DBA::selectToArray('contact', [], ['network' => Protocol::DIASPORA, 'uid' => $uid, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
3907 if (empty($recipients)) {
3908 Logger::warning('Cannot fetch recipients', ['uid' => $uid]);
3912 $message = self::createProfileData($uid);
3914 // @todo Split this into single worker jobs
3915 foreach ($recipients as $recipient) {
3916 Logger::info('Send updated profile data for user ' . $uid . ' to contact ' . $recipient['id']);
3917 self::buildAndTransmit($owner, $recipient, 'profile', $message);
3922 * Creates the signature for likes that are created on our system
3924 * @param integer $uid The user of that comment
3925 * @param array $item Item array
3927 * @return array|bool Signed content or false on error
3928 * @throws \Exception
3930 public static function createLikeSignature(int $uid, array $item)
3932 $owner = User::getOwnerDataById($uid);
3933 if (empty($owner)) {
3934 Logger::info('No owner post, so not storing signature', ['uid' => $uid]);
3938 if (!in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3939 Logger::warning('Item is neither a like nor a dislike', ['uid' => $uid, 'item[verb]' => $item['verb']]);;
3943 $message = self::constructLike($item, $owner);
3944 if ($message === false) {
3948 $message['author_signature'] = self::signature($owner, $message);
3954 * Creates the signature for Comments that are created on our system
3956 * @param array $item Item array
3958 * @return array|bool Signed content or false on error
3959 * @throws \Exception
3961 public static function createCommentSignature(array $item)
3964 if (!empty($item['author-link'])) {
3965 $url = $item['author-link'];
3967 $contact = Contact::getById($item['author-id'], ['url']);
3968 if (empty($contact['url'])) {
3969 Logger::warning('Author Contact not found', ['author-id' => $item['author-id']]);
3972 $url = $contact['url'];
3975 $uid = User::getIdForURL($url);
3977 Logger::info('No owner post, so not storing signature', ['url' => $contact['url'] ?? 'No contact loaded']);
3981 $owner = User::getOwnerDataById($uid);
3982 if (empty($owner)) {
3983 Logger::info('No owner post, so not storing signature');
3987 // This is only needed for the automated tests
3988 if (empty($owner['uprvkey'])) {
3992 if (!self::parentSupportDiaspora($item['thr-parent-id'])) {
3993 Logger::info('One of the parents does not support Diaspora. A signature will not be created.', ['uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
3997 $message = self::constructComment($item, $owner);
3998 if ($message === false) {
4002 $message['author_signature'] = self::signature($owner, $message);
4008 * Check if the parent and their parents support Diaspora
4010 * @param integer $parent_id
4013 private static function parentSupportDiaspora(int $parent_id): bool
4015 $parent_post = Post::selectFirstPost(['gravity', 'signed_text', 'author-link', 'thr-parent-id'], ['uri-id' => $parent_id]);
4016 if (empty($parent_post['thr-parent-id'])) {
4017 Logger::warning('Parent post does not exist.', ['parent-id' => $parent_id]);
4021 if (empty(FContact::getByURL($parent_post['author-link'], false))) {
4022 Logger::info('Parent author is no Diaspora contact.', ['parent-id' => $parent_id]);
4026 if (($parent_post['gravity'] == Item::GRAVITY_COMMENT) && empty($parent_post['signed_text'])) {
4027 Logger::info('Parent comment has got no Diaspora signature.', ['parent-id' => $parent_id]);
4031 if ($parent_post['gravity'] == Item::GRAVITY_COMMENT) {
4032 return self::parentSupportDiaspora($parent_post['thr-parent-id']);
4038 public static function performReshare(int $UriId, int $uid): int
4040 $owner = User::getOwnerDataById($uid);
4041 $author = Contact::getPublicIdByUserId($uid);
4045 'verb' => Activity::POST,
4046 'contact-id' => $owner['id'],
4047 'author-id' => $author,
4048 'owner-id' => $author,
4050 'quote-uri-id' => $UriId,
4051 'allow_cid' => $owner['allow_cid'] ?? '',
4052 'allow_gid' => $owner['allow_gid']?? '',
4053 'deny_cid' => $owner['deny_cid'] ?? '',
4054 'deny_gid' => $owner['deny_gid'] ?? '',
4057 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
4058 $item['private'] = Item::PRIVATE;
4059 } elseif (DI::pConfig()->get($uid, 'system', 'unlisted')) {
4060 $item['private'] = Item::UNLISTED;
4062 $item['private'] = Item::PUBLIC;
4065 // Don't trigger the addons
4066 $item['api_source'] = false;
4068 return Item::insert($item, true);