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\GServer;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\Mail;
40 use Friendica\Model\Post;
41 use Friendica\Model\Tag;
42 use Friendica\Model\User;
43 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
44 use Friendica\Network\HTTPException;
45 use Friendica\Network\Probe;
46 use Friendica\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);
165 $key = self::key(WebFingerUri::fromString($handle));
167 throw new \InvalidArgumentException();
169 } catch (\InvalidArgumentException $e) {
170 Logger::notice("Couldn't get a key for handle " . $handle . ". Discarding.");
174 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
176 Logger::notice('Message from ' . $handle . ' did not verify. Discarding.');
184 * encrypts data via AES
186 * @param string $key The AES key
187 * @param string $iv The IV (is used for CBC encoding)
188 * @param string $data The data that is to be encrypted
190 * @return string encrypted data
192 private static function aesEncrypt(string $key, string $iv, string $data): string
194 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
198 * decrypts data via AES
200 * @param string $key The AES key
201 * @param string $iv The IV (is used for CBC encoding)
202 * @param string $encrypted The encrypted data
204 * @return string decrypted data
206 private static function aesDecrypt(string $key, string $iv, string $encrypted): string
208 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
212 * Decodes incoming Diaspora message in the new format. This method returns false on an error.
214 * @param string $raw raw post message
215 * @param string $privKey The private key of the importer
216 * @param boolean $no_exit Don't do an http exit on error
219 * 'message' -> decoded Diaspora XML message
220 * 'author' -> author diaspora handle
221 * 'key' -> author public key (converted to pkcs#8)
222 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
223 * @throws \ImagickException
225 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
227 $data = json_decode($raw);
229 // Is it a private post? Then decrypt the outer Salmon
230 if (is_object($data)) {
232 if (!isset($data->aes_key) || !isset($data->encrypted_magic_envelope)) {
233 Logger::info('Missing keys "aes_key" and/or "encrypted_magic_envelope"', ['data' => $data]);
234 throw new \RuntimeException('Missing keys "aes_key" and/or "encrypted_magic_envelope"');
237 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
238 $ciphertext = base64_decode($data->encrypted_magic_envelope);
240 $outer_key_bundle = '';
241 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
242 $j_outer_key_bundle = json_decode($outer_key_bundle);
244 if (!is_object($j_outer_key_bundle)) {
245 Logger::info('Unable to decode outer key bundle', ['outer_key_bundle' => $outer_key_bundle]);
246 throw new \RuntimeException('Unable to decode outer key bundle');
249 if (!isset($j_outer_key_bundle->iv) || !isset($j_outer_key_bundle->key)) {
250 Logger::info('Missing keys "iv" and/or "key" from outer Salmon', ['j_outer_key_bundle' => $j_outer_key_bundle]);
251 throw new \RuntimeException('Missing keys "iv" and/or "key" from outer Salmon');
254 $outer_iv = base64_decode($j_outer_key_bundle->iv);
255 $outer_key = base64_decode($j_outer_key_bundle->key);
257 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
258 } catch (\Throwable $e) {
259 Logger::notice('Outer Salmon did not verify. Discarding.');
263 throw new \Friendica\Network\HTTPException\BadRequestException();
270 $basedom = XML::parseString($xml, true);
272 if (!is_object($basedom)) {
273 Logger::notice('Received data does not seem to be an XML. Discarding. '.$xml);
277 throw new \Friendica\Network\HTTPException\BadRequestException();
281 $base = $basedom->children(ActivityNamespace::SALMON_ME);
283 // Not sure if this cleaning is needed
284 $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
286 // Build the signed data
287 $type = $base->data[0]->attributes()->type[0];
288 $encoding = $base->encoding;
290 $signed_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
292 // This is the signature
293 $signature = Strings::base64UrlDecode($base->sig);
295 // Get the senders' public key
296 $key_id = $base->sig[0]->attributes()->key_id[0];
297 $author_addr = base64_decode($key_id);
298 if ($author_addr == '') {
299 Logger::notice('No author could be decoded. Discarding. Message: ' . $xml);
303 throw new \Friendica\Network\HTTPException\BadRequestException();
308 $author = WebFingerUri::fromString($author_addr);
309 $key = self::key($author);
311 throw new \InvalidArgumentException();
313 } catch (\InvalidArgumentException $e) {
314 Logger::notice("Couldn't get a key for handle " . $author_addr . ". Discarding.");
318 throw new \Friendica\Network\HTTPException\BadRequestException();
322 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
324 Logger::notice('Message did not verify. Discarding.');
328 throw new \Friendica\Network\HTTPException\BadRequestException();
333 'message' => (string)Strings::base64UrlDecode($base->data),
334 'author' => $author->getAddr(),
335 'key' => (string)$key
340 * Decodes incoming Diaspora message in the deprecated format
342 * @param string $xml urldecoded Diaspora salmon
343 * @param string $privKey The private key of the importer
346 * 'message' -> decoded Diaspora XML message
347 * 'author' -> author diaspora handle
348 * 'key' -> author public key (converted to pkcs#8)
349 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
350 * @throws \ImagickException
352 public static function decode(string $xml, string $privKey = '')
355 $basedom = XML::parseString($xml);
357 if (!is_object($basedom)) {
358 Logger::notice('XML is not parseable.');
361 $children = $basedom->children('https://joindiaspora.com/protocol');
363 $inner_aes_key = null;
366 if ($children->header) {
368 $idom = $children->header;
370 // This happens with posts from a relais
371 if (empty($privKey)) {
372 Logger::info('This is no private post in the old format');
376 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
378 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
379 $ciphertext = base64_decode($encrypted_header->ciphertext);
381 $outer_key_bundle = '';
382 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
384 $j_outer_key_bundle = json_decode($outer_key_bundle);
386 $outer_iv = base64_decode($j_outer_key_bundle->iv);
387 $outer_key = base64_decode($j_outer_key_bundle->key);
389 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
391 Logger::info('decrypted', ['data' => $decrypted]);
392 $idom = XML::parseString($decrypted);
394 $inner_iv = base64_decode($idom->iv);
395 $inner_aes_key = base64_decode($idom->aes_key);
399 $author = WebFingerUri::fromString($idom->author_id);
400 } catch (\Throwable $e) {
401 Logger::notice('Could not retrieve author URI.', ['idom' => $idom]);
402 throw new \Friendica\Network\HTTPException\BadRequestException();
405 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
407 // figure out where in the DOM tree our data is hiding
410 if ($dom->provenance->data) {
411 $base = $dom->provenance;
412 } elseif ($dom->env->data) {
414 } elseif ($dom->data) {
419 Logger::notice('unable to locate salmon data in xml');
420 throw new \Friendica\Network\HTTPException\BadRequestException();
424 // Stash the signature away for now. We have to find their key or it won't be good for anything.
425 $signature = Strings::base64UrlDecode($base->sig);
429 // strip whitespace so our data element will return to one big base64 blob
430 $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
433 // stash away some other stuff for later
435 $type = $base->data[0]->attributes()->type[0];
436 $keyhash = $base->sig[0]->attributes()->keyhash[0];
437 $encoding = $base->encoding;
441 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
445 $data = Strings::base64UrlDecode($data);
449 $inner_decrypted = $data;
451 // Decode the encrypted blob
452 $inner_encrypted = base64_decode($data);
453 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
456 // Once we have the author URI, go to the web and try to find their public key
457 // (first this will look it up locally if it is in the diaspora-contact cache)
458 // This will also convert diaspora public key from pkcs#1 to pkcs#8
459 Logger::notice('Fetching key for ' . $author);
460 $key = self::key($author);
462 Logger::notice('Could not retrieve author key.');
463 throw new \Friendica\Network\HTTPException\BadRequestException();
466 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
469 Logger::notice('Message did not verify. Discarding.');
470 throw new \Friendica\Network\HTTPException\BadRequestException();
473 Logger::notice('Message verified.');
476 'message' => $inner_decrypted,
477 'author' => $author->getAddr(),
484 * Dispatches public messages and find the fitting receivers
486 * @param array $msg The post that will be dispatched
487 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
489 * @return int|bool The message id of the generated message, "true" or "false" if there was an error
490 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
491 * @throws \ImagickException
493 public static function dispatchPublic(array $msg, int $direction)
495 $enabled = intval(DI::config()->get('system', 'diaspora_enabled'));
497 Logger::notice('Diaspora is disabled');
501 if (!($fields = self::validPosting($msg))) {
502 Logger::warning('Invalid posting', ['msg' => $msg]);
508 'page-flags' => User::PAGE_FLAGS_FREELOVE
510 $success = self::dispatch($importer, $msg, $fields, $direction);
516 * Dispatches the different message types to the different functions
518 * @param array $importer Array of the importer user
519 * @param array $msg The post that will be dispatched
520 * @param SimpleXMLElement $fields SimpleXML object that contains the message
521 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
523 * @return int|bool The message id of the generated message, "true" or "false" if there was an error
524 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
525 * @throws \ImagickException
527 public static function dispatch(array $importer, array $msg, SimpleXMLElement $fields = null, int $direction = self::PUSHED)
529 // The sender is the handle of the contact that sent the message.
530 // This will often be different with relayed messages (for example "like" and "comment")
531 $sender = WebFingerUri::fromString($msg['author']);
533 // This is only needed for private postings since this is already done for public ones before
534 if (is_null($fields)) {
536 if (!($fields = self::validPosting($msg))) {
537 Logger::warning('Invalid posting', ['msg' => $msg]);
544 $type = $fields->getName();
546 Logger::info('Received message', ['type' => $type, 'sender' => $sender->getAddr(), 'user' => $importer['uid']]);
549 case 'account_migration':
551 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
554 return self::receiveAccountMigration($importer, $fields);
556 case 'account_deletion':
557 return self::receiveAccountDeletion($fields);
560 return self::receiveComment($importer, $sender, $fields, $msg['message'], $direction);
564 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
567 return self::receiveContactRequest($importer, $fields);
571 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
574 return self::receiveConversation($importer, $msg, $fields);
577 return self::receiveLike($importer, $sender, $fields, $direction);
581 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
584 return self::receiveMessage($importer, $fields);
586 case 'participation':
588 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
591 return self::receiveParticipation($importer, $fields, $direction);
593 case 'photo': // Not implemented
594 return self::receivePhoto($importer, $fields);
596 case 'poll_participation': // Not implemented
597 return self::receivePollParticipation($importer, $fields);
601 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
604 return self::receiveProfile($importer, $fields);
607 return self::receiveReshare($importer, $fields, $msg['message'], $direction);
610 return self::receiveRetraction($importer, $sender, $fields);
612 case 'status_message':
613 return self::receiveStatusMessage($importer, $fields, $msg['message'], $direction);
616 Logger::notice('Unknown message type ' . $type);
622 * Checks if a posting is valid and fetches the data fields.
624 * This function does not only check the signature.
625 * It also does the conversion between the old and the new diaspora format.
627 * @param array $msg Array with the XML, the sender handle and the sender signature
629 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
630 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
631 * @throws \ImagickException
633 private static function validPosting(array $msg)
635 $data = XML::parseString($msg['message']);
637 if (!is_object($data)) {
638 Logger::info('No valid XML', ['message' => $msg['message']]);
642 // Is this the new or the old version?
643 if ($data->getName() == 'XML') {
645 foreach ($data->post->children() as $child) {
653 $type = $element->getName();
656 Logger::debug('Got message', ['type' => $type, 'message' => $msg['message']]);
658 // All retractions are handled identically from now on.
659 // In the new version there will only be "retraction".
660 if (in_array($type, ['signed_retraction', 'relayable_retraction']))
661 $type = 'retraction';
663 if ($type == 'request') {
667 $fields = new SimpleXMLElement('<' . $type . '/>');
670 $author_signature = null;
671 $parent_author_signature = null;
673 foreach ($element->children() as $fieldname => $entry) {
675 // Translation for the old XML structure
676 if ($fieldname == 'diaspora_handle') {
677 $fieldname = 'author';
679 if ($fieldname == 'participant_handles') {
680 $fieldname = 'participants';
682 if (in_array($type, ['like', 'participation'])) {
683 if ($fieldname == 'target_type') {
684 $fieldname = 'parent_type';
687 if ($fieldname == 'sender_handle') {
688 $fieldname = 'author';
690 if ($fieldname == 'recipient_handle') {
691 $fieldname = 'recipient';
693 if ($fieldname == 'root_diaspora_id') {
694 $fieldname = 'root_author';
696 if ($type == 'status_message') {
697 if ($fieldname == 'raw_message') {
701 if ($type == 'retraction') {
702 if ($fieldname == 'post_guid') {
703 $fieldname = 'target_guid';
705 if ($fieldname == 'type') {
706 $fieldname = 'target_type';
711 if (($fieldname == 'author_signature') && ($entry != '')) {
712 $author_signature = base64_decode($entry);
713 } elseif (($fieldname == 'parent_author_signature') && ($entry != '')) {
714 $parent_author_signature = base64_decode($entry);
715 } elseif (!in_array($fieldname, ['author_signature', 'parent_author_signature', 'target_author_signature'])) {
716 if ($signed_data != '') {
720 $signed_data .= $entry;
722 if (!in_array($fieldname, ['parent_author_signature', 'target_author_signature'])
723 || ($orig_type == 'relayable_retraction')
725 XML::copy($entry, $fields, $fieldname);
729 // This is something that shouldn't happen at all.
730 if (in_array($type, ['status_message', 'reshare', 'profile'])) {
731 if ($msg['author'] != $fields->author) {
732 Logger::notice('Message handle is not the same as envelope sender. Quitting this message.', ['author1' => $msg['author'], 'author2' => $fields->author]);
737 // Only some message types have signatures. So we quit here for the other types.
738 if (!in_array($type, ['comment', 'like'])) {
742 if (!isset($author_signature) && ($msg['author'] == $fields->author)) {
743 Logger::debug('No author signature, but the sender matches the author', ['type' => $type, 'msg-author' => $msg['author'], 'message' => $msg['message']]);
747 // No author_signature? This is a must, so we quit.
748 if (!isset($author_signature)) {
749 Logger::info('No author signature', ['type' => $type, 'msg-author' => $msg['author'], 'fields-author' => $fields->author, 'message' => $msg['message']]);
753 if (isset($parent_author_signature)) {
754 $key = self::key(WebFingerUri::fromString($msg['author']));
756 Logger::info('No key found for parent', ['author' => $msg['author']]);
760 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, 'sha256')) {
761 Logger::info('No valid parent author signature', ['author' => $msg['author'], 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $parent_author_signature]);
767 $key = self::key(WebFingerUri::fromString($fields->author));
769 throw new \InvalidArgumentException();
771 } catch (\Throwable $e) {
772 Logger::info('No key found', ['author' => $fields->author]);
776 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, 'sha256')) {
777 Logger::info('No valid author signature for author', ['author' => $fields->author, 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $author_signature]);
785 * Fetches the public key for a given handle
787 * @param WebFingerUri $uri The handle
789 * @return string The public key
790 * @throws InternalServerErrorException
791 * @throws \ImagickException
793 private static function key(WebFingerUri $uri): string
795 Logger::notice('Fetching diaspora key', ['handle' => $uri->getAddr(), 'callstack' => System::callstack(20)]);
797 return DI::dsprContact()->getByAddr($uri)->pubKey;
798 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
804 * Get a contact id for a given handle
806 * @param int $uid The user id
807 * @param WebFingerUri $uri
809 * @return array Contact data
810 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
811 * @throws \ImagickException
813 private static function contactByHandle(int $uid, WebFingerUri $uri): array
815 return Contact::getByURL($uri->getAddr(), null, [], $uid);
819 * Checks if the given contact url does support ActivityPub
821 * @param string $url profile url or WebFinger address
822 * @param boolean|null $update true = always update, false = never update, null = update when not found or outdated
824 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
825 * @throws \ImagickException
827 public static function isSupportedByContactUrl(string $url, ?bool $update = null): bool
829 $contact = Contact::getByURL($url, $update, ['uri-id', 'network']);
831 $supported = DI::dsprContact()->existsByUriId($contact['uri-id'] ?? 0);
833 if (!$supported && is_null($update) && ($contact['network'] == Protocol::DFRN)) {
834 $supported = self::isSupportedByContactUrl($url, true);
841 * Check if posting is allowed for this contact
843 * @param array $importer Array of the importer user
844 * @param array $contact The contact that is checked
845 * @param bool $is_comment Is the check for a comment?
847 * @return bool is the contact allowed to post?
849 private static function postAllow(array $importer, array $contact, bool $is_comment = false): bool
852 * Perhaps we were already sharing with this person. Now they're sharing with us.
853 * That makes us friends.
854 * Normally this should have handled by getting a request - but this could get lost
856 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
857 // It is not removed by now. Possibly the code is needed?
858 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
860 // array('rel' => Contact::FRIEND, 'writable' => true),
861 // array('id' => $contact["id"], 'uid' => $contact["uid"])
864 // $contact["rel"] = Contact::FRIEND;
865 // Logger::notice("defining user ".$contact["nick"]." as friend");
868 // Contact server is blocked
869 if (Network::isUrlBlocked($contact['url'])) {
871 // We don't seem to like that person
872 } elseif ($contact['blocked']) {
873 // Maybe blocked, don't accept.
875 // We are following this person?
876 } elseif (($contact['rel'] == Contact::SHARING) || ($contact['rel'] == Contact::FRIEND)) {
877 // Yes, then it is fine.
879 // Is the message a global user or a comment?
880 } elseif (($importer['uid'] == 0) || $is_comment) {
881 // Messages for the global users and comments are always accepted
889 * Fetches the contact id for a handle and checks if posting is allowed
891 * @param array $importer Array of the importer user
892 * @param WebFingerUri $contact_uri The checked contact
893 * @param bool $is_comment Is the check for a comment?
895 * @return array|bool The contact data or false on error
896 * @throws InternalServerErrorException
897 * @throws \ImagickException
899 private static function allowedContactByHandle(array $importer, WebFingerUri $contact_uri, bool $is_comment = false)
901 $contact = self::contactByHandle($importer['uid'], $contact_uri);
903 Logger::notice('A Contact for handle ' . $contact_uri . ' and user ' . $importer['uid'] . ' was not found');
904 // If a contact isn't found, we accept it anyway if it is a comment
905 if ($is_comment && ($importer['uid'] != 0)) {
906 return self::contactByHandle(0, $contact_uri);
907 } elseif ($is_comment) {
914 if (!self::postAllow($importer, $contact, $is_comment)) {
915 Logger::notice('The handle: ' . $contact_uri . ' is not allowed to post to user ' . $importer['uid']);
922 * Does the message already exists on the system?
924 * @param int $uid The user id
925 * @param string $guid The guid of the message
927 * @return int|bool message id if the message already was stored into the system - or false.
930 private static function messageExists(int $uid, string $guid)
932 $item = Post::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
933 if (DBA::isResult($item)) {
934 Logger::notice('Message ' . $guid . ' already exists for user ' . $uid);
942 * Checks for links to posts in a message
944 * @param array $item The item array
947 private static function fetchGuid(array $item)
949 preg_replace_callback(
950 "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism",
951 function ($match) use ($item) {
952 self::fetchGuidSub($match, $item);
957 preg_replace_callback(
958 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
959 function ($match) use ($item) {
960 self::fetchGuidSub($match, $item);
967 * Checks for relative /people/* links in an item body to match local
968 * contacts or prepends the remote host taken from the author link.
970 * @param string $body The item body to replace links from
971 * @param string $author_link The author link for missing local contact fallback
973 * @return string the replaced string
975 public static function replacePeopleGuid(string $body, string $author_link): string
977 $return = preg_replace_callback(
978 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
979 function ($match) use ($author_link) {
981 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
982 // 1 => '0123456789abcdef'
984 $handle = DI::dsprContact()->getUrlByGuid($match[1]);
987 $return = '@[url=' . $handle . ']' . $match[2] . '[/url]';
989 // No local match, restoring absolute remote URL from author scheme and host
990 $author_url = parse_url($author_link);
991 $return = '[url=' . $author_url['scheme'] . '://' . $author_url['host'] . '/people/' . $match[1] . ']' . $match[2] . '[/url]';
1003 * sub function of "fetchGuid" which checks for links in messages
1005 * @param array $match array containing a link that has to be checked for a message link
1006 * @param array $item The item array
1008 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1009 * @throws \ImagickException
1011 private static function fetchGuidSub(array $match, array $item)
1013 if (!self::storeByGuid($match[1], $item['author-link'], true)) {
1014 self::storeByGuid($match[1], $item['owner-link'], true);
1019 * Fetches an item with a given guid from a given server
1021 * @param string $guid the message guid
1022 * @param string $server The server address
1023 * @param bool $force Forced fetch
1025 * @return int|bool the message id of the stored message or false
1026 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1027 * @throws \ImagickException
1029 private static function storeByGuid(string $guid, string $server, bool $force)
1031 $serverparts = parse_url($server);
1033 if (empty($serverparts['host']) || empty($serverparts['scheme'])) {
1037 $server = $serverparts['scheme'] . '://' . $serverparts['host'];
1039 Logger::info('Trying to fetch item ' . $guid . ' from ' . $server);
1041 $msg = self::message($guid, $server);
1047 Logger::info('Successfully fetched item ' . $guid . ' from ' . $server);
1049 // Now call the dispatcher
1050 return self::dispatchPublic($msg, $force ? self::FORCED_FETCH : self::FETCHED);
1054 * Fetches a message from a server
1056 * @param string $guid message guid
1057 * @param string $server The url of the server
1058 * @param int $level Endless loop prevention
1061 * 'message' => The message XML
1062 * 'author' => The author handle
1063 * 'key' => The public key of the author
1064 * @throws \Exception
1066 public static function message(string $guid, string $server, int $level = 0)
1072 // This will work for new Diaspora servers and Friendica servers from 3.5
1073 $source_url = $server . '/fetch/post/' . urlencode($guid);
1075 Logger::info('Fetch post from ' . $source_url);
1077 $envelope = DI::httpClient()->fetch($source_url, HttpClientAccept::MAGIC);
1079 Logger::info('Envelope was fetched.');
1080 $x = self::verifyMagicEnvelope($envelope);
1082 Logger::info('Envelope could not be verified.');
1084 Logger::info('Envelope was verified.');
1094 $source_xml = XML::parseString($x);
1096 if (!is_object($source_xml)) {
1100 if ($source_xml->post->reshare) {
1101 // Reshare of a reshare - old Diaspora version
1102 Logger::info('Message is a reshare');
1103 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1104 } elseif ($source_xml->getName() == 'reshare') {
1105 // Reshare of a reshare - new Diaspora version
1106 Logger::info('Message is a new reshare');
1107 return self::message($source_xml->root_guid, $server, ++$level);
1110 $author_handle = '';
1112 // Fetch the author - for the old and the new Diaspora version
1113 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1114 $author_handle = (string)$source_xml->post->status_message->diaspora_handle;
1115 } elseif ($source_xml->author && ($source_xml->getName() == 'status_message')) {
1116 $author_handle = (string)$source_xml->author;
1120 $author = WebFingerUri::fromString($author_handle);
1121 } catch (\InvalidArgumentException $e) {
1122 // If this isn't a "status_message" then quit
1123 Logger::info("Message doesn't seem to be a status message");
1129 'author' => $author->getAddr(),
1130 'key' => self::key($author)
1135 * Fetches an item with a given URL
1137 * @param string $url the message url
1138 * @param int $uid User id
1140 * @return int|bool the message id of the stored message or false
1141 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1142 * @throws \ImagickException
1144 public static function fetchByURL(string $url, int $uid = 0)
1146 // Check for Diaspora (and Friendica) typical paths
1147 if (!preg_match('=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i', $url, $matches)) {
1148 Logger::info('Invalid url', ['url' => $url]);
1152 $guid = urldecode($matches[2]);
1154 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1155 if (DBA::isResult($item)) {
1156 Logger::info('Found', ['id' => $item['id']]);
1160 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1161 $ret = self::storeByGuid($guid, $matches[1], true);
1162 Logger::info('Result', ['ret' => $ret]);
1164 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1165 if (DBA::isResult($item)) {
1166 Logger::info('Found', ['id' => $item['id']]);
1169 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1175 * Fetches the item record of a given guid
1177 * @param int $uid The user id
1178 * @param string $guid message guid
1179 * @param WebFingerUri $author
1180 * @param array $contact The contact of the item owner
1182 * @return array|bool the item record or false on failure
1183 * @throws \Exception
1185 private static function parentItem(int $uid, string $guid, WebFingerUri $author, array $contact)
1187 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1188 'author-name', 'author-link', 'author-avatar', 'gravity',
1189 'owner-name', 'owner-link', 'owner-avatar'];
1191 $condition = ['uid' => $uid, 'guid' => $guid];
1192 $item = Post::selectFirst($fields, $condition);
1194 if (!DBA::isResult($item)) {
1196 $result = self::storeByGuid($guid, DI::dsprContact()->getByAddr($author)->url, false);
1198 // We don't have an url for items that arrived at the public dispatcher
1199 if (!$result && !empty($contact['url'])) {
1200 $result = self::storeByGuid($guid, $contact['url'], false);
1204 Logger::info('Fetched missing item ' . $guid . ' - result: ' . $result);
1206 $item = Post::selectFirst($fields, $condition);
1208 } catch (HTTPException\NotFoundException $e) {
1209 Logger::notice('Unable to retrieve author details', ['author' => $author->getAddr()]);
1213 if (!DBA::isResult($item)) {
1214 Logger::notice('Parent item not found: parent: ' . $guid . ' - user: ' . $uid);
1217 Logger::notice('Parent item found: parent: ' . $guid . ' - user: ' . $uid);
1223 * returns contact details for the given user
1225 * @param array $def_contact The default details if the contact isn't found
1226 * @param string $contact_url The url of the contact
1227 * @param int $uid The user id
1230 * 'cid' => contact id
1231 * 'network' => network type
1232 * @throws \Exception
1234 private static function authorContactByUrl(array $def_contact, string $contact_url, int $uid): array
1236 $condition = ['nurl' => Strings::normaliseLink($contact_url), 'uid' => $uid];
1237 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1238 if (DBA::isResult($contact)) {
1239 $cid = $contact['id'];
1240 $network = $contact['network'];
1242 $cid = $def_contact['id'];
1243 $network = Protocol::DIASPORA;
1248 'network' => $network
1253 * Is the profile a hubzilla profile?
1255 * @param string $url The profile link
1257 * @return bool is it a hubzilla server?
1259 private static function isHubzilla(string $url): bool
1261 return strstr($url, '/channel/');
1265 * Generate a post link with a given handle and message guid
1267 * @param string $addr The user handle
1268 * @param string $guid message guid
1269 * @param string $parent_guid optional parent guid
1271 * @return string the post link
1272 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1273 * @throws \ImagickException
1275 private static function plink(string $addr, string $guid, string $parent_guid = ''): string
1277 $contact = Contact::getByURL($addr);
1278 if (empty($contact)) {
1279 Logger::info('No contact data for address', ['addr' => $addr]);
1283 if (empty($contact['baseurl'])) {
1284 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1285 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1289 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1290 if (!empty($gserver['platform'])) {
1291 $platform = strtolower($gserver['platform']);
1292 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1295 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1296 if (self::isHubzilla($contact['url'])) {
1297 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1298 $platform = 'hubzilla';
1299 } elseif ($contact['network'] == Protocol::DFRN) {
1300 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1301 $platform = 'friendica';
1305 if ($platform == 'friendica') {
1306 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1309 if ($platform == 'hubzilla') {
1310 return $contact['baseurl'] . '/item/' . $guid;
1313 if ($platform == 'socialhome') {
1314 return $contact['baseurl'] . '/content/' . $guid;
1317 if ($platform != 'diaspora') {
1318 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1322 if ($parent_guid != '') {
1323 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1325 return $contact['baseurl'] . '/posts/' . $guid;
1330 * Receives account migration
1332 * @param array $importer Array of the importer user
1333 * @param SimpleXMLElement $data The message object
1335 * @return bool Success
1336 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1337 * @throws \ImagickException
1339 private static function receiveAccountMigration(array $importer, SimpleXMLElement $data): bool
1342 $old_author = WebFingerUri::fromString(XML::unescape($data->author));
1343 $new_author = WebFingerUri::fromString(XML::unescape($data->profile->author));
1344 } catch (\Throwable $e) {
1345 Logger::notice('Cannot find handles for sender and user', ['data' => $data]);
1349 $signature = XML::unescape($data->signature);
1351 $contact = self::contactByHandle($importer['uid'], $old_author);
1353 Logger::notice('Cannot find contact for sender: ' . $old_author . ' and user ' . $importer['uid']);
1357 Logger::notice('Got migration for ' . $old_author . ', to ' . $new_author . ' with user ' . $importer['uid']);
1360 $signed_text = 'AccountMigration:' . $old_author . ':' . $new_author;
1361 $key = self::key($old_author);
1362 if (!Crypto::rsaVerify($signed_text, $signature, $key, 'sha256')) {
1363 Logger::notice('No valid signature for migration.');
1367 // Update the profile
1368 self::receiveProfile($importer, $data->profile);
1370 // change the technical stuff in contact
1371 $data = Probe::uri($new_author);
1372 if ($data['network'] == Protocol::PHANTOM) {
1373 Logger::notice("Account for " . $new_author . " couldn't be probed.");
1378 'url' => $data['url'],
1379 'nurl' => Strings::normaliseLink($data['url']),
1380 'name' => $data['name'],
1381 'nick' => $data['nick'],
1382 'addr' => $data['addr'],
1383 'batch' => $data['batch'],
1384 'notify' => $data['notify'],
1385 'poll' => $data['poll'],
1386 'network' => $data['network'],
1389 Contact::update($fields, ['addr' => $old_author->getAddr()]);
1391 Logger::notice('Contacts are updated.');
1397 * Processes an account deletion
1399 * @param SimpleXMLElement $data The message object
1401 * @return bool Success
1402 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1404 private static function receiveAccountDeletion(SimpleXMLElement $data): bool
1406 $author_handle = XML::unescape($data->author);
1408 $contacts = DBA::select('contact', ['id'], ['addr' => $author_handle]);
1409 while ($contact = DBA::fetch($contacts)) {
1410 Contact::remove($contact['id']);
1412 DBA::close($contacts);
1414 Logger::notice('Removed contacts for ' . $author_handle);
1420 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1422 * @param string $guid Message guid
1423 * @param WebFingerUri|null $person_uri Optional person to derive the base URL from
1425 * @return string The constructed uri or the one from our database or empty string
1426 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1427 * @throws \ImagickException
1429 private static function getUriFromGuid(string $guid, WebFingerUri $person_uri = null): string
1431 $item = Post::selectFirst(['uri'], ['guid' => $guid]);
1433 return $item['uri'];
1434 } elseif ($person_uri) {
1436 return DI::dsprContact()->selectOneByAddr($person_uri)->baseurl . '/objects/' . $guid;
1437 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
1446 * Store the mentions in the tag table
1448 * @param integer $uriid
1449 * @param string $text
1451 private static function storeMentions(int $uriid, string $text)
1453 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1454 if (empty($matches)) {
1459 * Matching values for the preg match
1460 * [1] = mention type (@ or !)
1461 * [2] = name (optional)
1465 foreach ($matches as $match) {
1466 if (empty($match)) {
1471 $contact = DI::dsprContact()->getByUrl(new Uri($match[3]));
1472 Tag::storeByHash($uriid, $match[1], $contact->name ?: $contact->nick, $contact->url);
1473 } catch (\Throwable $e) {
1480 * Processes an incoming comment
1482 * @param array $importer Array of the importer user
1483 * @param WebFingerUri $sender The sender of the message
1484 * @param SimpleXMLElement $data The message object
1485 * @param string $xml The original XML of the message
1486 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1488 * @return bool The message id of the generated comment or "false" if there was an error
1489 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1490 * @throws \ImagickException
1492 private static function receiveComment(array $importer, WebFingerUri $sender, SimpleXMLElement $data, string $xml, int $direction): bool
1494 $author = WebFingerUri::fromString(XML::unescape($data->author));
1495 $guid = XML::unescape($data->guid);
1496 $parent_guid = XML::unescape($data->parent_guid);
1497 $text = XML::unescape($data->text);
1499 if (isset($data->created_at)) {
1500 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1502 $created_at = DateTimeFormat::utcNow();
1505 if (isset($data->thread_parent_guid)) {
1506 $thread_parent_guid = XML::unescape($data->thread_parent_guid);
1507 $thr_parent = self::getUriFromGuid($thread_parent_guid);
1512 $contact = self::allowedContactByHandle($importer, $sender, true);
1517 if (!empty($contact['gsid'])) {
1518 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1521 $message_id = self::messageExists($importer['uid'], $guid);
1526 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1527 if (!$toplevel_parent_item) {
1532 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
1533 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
1534 Logger::notice('Unable to find author details', ['author' => $author->getAddr()]);
1538 // Fetch the contact id - if we know this contact
1539 $author_contact = self::authorContactByUrl($contact, $author_url, $importer['uid']);
1543 $datarray['uid'] = $importer['uid'];
1544 $datarray['contact-id'] = $author_contact['cid'];
1545 $datarray['network'] = $author_contact['network'];
1547 $datarray['author-link'] = $author_url;
1548 $datarray['author-id'] = Contact::getIdForURL($author_url);
1550 $datarray['owner-link'] = $contact['url'];
1551 $datarray['owner-id'] = Contact::getIdForURL($contact['url']);
1553 // Will be overwritten for sharing accounts in Item::insert
1554 $datarray = self::setDirection($datarray, $direction);
1556 $datarray['guid'] = $guid;
1557 $datarray['uri'] = self::getUriFromGuid($guid, $author);
1558 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1560 $datarray['verb'] = Activity::POST;
1561 $datarray['gravity'] = Item::GRAVITY_COMMENT;
1563 $datarray['thr-parent'] = $thr_parent ?: $toplevel_parent_item['uri'];
1565 $datarray['object-type'] = Activity\ObjectType::COMMENT;
1566 $datarray['post-type'] = Item::PT_NOTE;
1568 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1569 $datarray['source'] = $xml;
1571 $datarray = self::setDirection($datarray, $direction);
1573 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
1575 $datarray['plink'] = self::plink($author, $guid, $toplevel_parent_item['guid']);
1576 $body = Markdown::toBBCode($text);
1578 $datarray['body'] = self::replacePeopleGuid($body, $author_url);
1580 self::storeMentions($datarray['uri-id'], $text);
1581 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
1583 self::fetchGuid($datarray);
1585 // If we are the origin of the parent we store the original data.
1586 // We notify our followers during the item storage.
1587 if ($toplevel_parent_item['origin']) {
1588 $datarray['diaspora_signed_text'] = json_encode($data);
1591 if (Item::isTooOld($datarray)) {
1592 Logger::info('Comment is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1596 $message_id = Item::insert($datarray);
1598 if ($message_id <= 0) {
1603 Logger::info('Stored comment ' . $datarray['guid'] . ' with message id ' . $message_id);
1604 if ($datarray['uid'] == 0) {
1605 Item::distribute($message_id, json_encode($data));
1613 * processes and stores private messages
1615 * @param array $importer Array of the importer user
1616 * @param array $contact The contact of the message
1617 * @param SimpleXMLElement $data The message object
1618 * @param array $msg Array of the processed message, author handle and key
1619 * @param object $mesg The private message
1620 * @param array $conversation The conversation record to which this message belongs
1622 * @return bool "true" if it was successful
1623 * @throws \Exception
1624 * @todo Find type-hint for $mesg and update documentation
1626 private static function receiveConversationMessage(array $importer, array $contact, SimpleXMLElement $data, array $msg, $mesg, array $conversation): bool
1628 $author_handle = XML::unescape($data->author);
1629 $guid = XML::unescape($data->guid);
1630 $subject = XML::unescape($data->subject);
1632 // "diaspora_handle" is the element name from the old version
1633 // "author" is the element name from the new version
1634 if ($mesg->author) {
1635 $msg_author_handle = XML::unescape($mesg->author);
1636 } elseif ($mesg->diaspora_handle) {
1637 $msg_author_handle = XML::unescape($mesg->diaspora_handle);
1643 $msg_author_uri = WebFingerUri::fromString($msg_author_handle);
1644 } catch (\InvalidArgumentException $e) {
1648 $msg_guid = XML::unescape($mesg->guid);
1649 $msg_conversation_guid = XML::unescape($mesg->conversation_guid);
1650 $msg_text = XML::unescape($mesg->text);
1651 $msg_created_at = DateTimeFormat::utc(XML::unescape($mesg->created_at));
1653 if ($msg_conversation_guid != $guid) {
1654 Logger::notice('Message conversation guid does not belong to the current conversation.', ['guid' => $guid]);
1658 $msg_author = DI::dsprContact()->getByAddr($msg_author_uri);
1660 return Mail::insert([
1661 'uid' => $importer['uid'],
1662 'guid' => $msg_guid,
1663 'convid' => $conversation['id'],
1664 'from-name' => $msg_author->name,
1665 'from-photo' => (string)$msg_author->photo,
1666 'from-url' => (string)$msg_author->url,
1667 'contact-id' => $contact['id'],
1668 'title' => $subject,
1669 'body' => Markdown::toBBCode($msg_text),
1670 'uri' => $msg_author_handle . ':' . $msg_guid,
1671 'parent-uri' => $author_handle . ':' . $guid,
1672 'created' => $msg_created_at
1677 * Processes new private messages (answers to private messages are processed elsewhere)
1679 * @param array $importer Array of the importer user
1680 * @param array $msg Array of the processed message, author handle and key
1681 * @param SimpleXMLElement $data The message object
1683 * @return bool Success
1684 * @throws \Exception
1686 private static function receiveConversation(array $importer, array $msg, SimpleXMLElement $data)
1688 $author_handle = XML::unescape($data->author);
1689 $guid = XML::unescape($data->guid);
1690 $subject = XML::unescape($data->subject);
1691 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1692 $participants = XML::unescape($data->participants);
1694 $messages = $data->message;
1696 if (!count($messages)) {
1697 Logger::notice('Empty conversation');
1701 $contact = self::allowedContactByHandle($importer, WebFingerUri::fromString($msg['author']), true);
1706 if (!empty($contact['gsid'])) {
1707 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1710 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1711 if (!DBA::isResult($conversation)) {
1712 $r = DBA::insert('conv', [
1713 'uid' => $importer['uid'],
1715 'creator' => $author_handle,
1716 'created' => $created_at,
1717 'updated' => DateTimeFormat::utcNow(),
1718 'subject' => $subject,
1719 'recips' => $participants
1723 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1726 if (!$conversation) {
1727 Logger::warning('Unable to create conversation.');
1731 foreach ($messages as $mesg) {
1732 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1739 * Processes "like" messages
1741 * @param array $importer Array of the importer user
1742 * @param WebFingerUri $sender The sender of the message
1743 * @param SimpleXMLElement $data The message object
1744 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1746 * @return bool Success or failure
1747 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1748 * @throws \ImagickException
1750 private static function receiveLike(array $importer, WebFingerUri $sender, SimpleXMLElement $data, int $direction): bool
1752 $author = WebFingerUri::fromString(XML::unescape($data->author));
1753 $guid = XML::unescape($data->guid);
1754 $parent_guid = XML::unescape($data->parent_guid);
1755 $parent_type = XML::unescape($data->parent_type);
1756 $positive = XML::unescape($data->positive);
1758 // likes on comments aren't supported by Diaspora - only on posts
1759 // But maybe this will be supported in the future, so we will accept it.
1760 if (!in_array($parent_type, ['Post', 'Comment'])) {
1764 $contact = self::allowedContactByHandle($importer, $sender, true);
1769 if (!empty($contact['gsid'])) {
1770 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1773 $message_id = self::messageExists($importer['uid'], $guid);
1778 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1779 if (!$toplevel_parent_item) {
1784 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
1785 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
1786 Logger::notice('Unable to find author details', ['author' => $author->getAddr()]);
1790 // Fetch the contact id - if we know this contact
1791 $author_contact = self::authorContactByUrl($contact, $author_url, $importer['uid']);
1793 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1794 // We would accept this anyhow.
1795 if ($positive == 'true') {
1796 $verb = Activity::LIKE;
1798 $verb = Activity::DISLIKE;
1803 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1805 $datarray['uid'] = $importer['uid'];
1806 $datarray['contact-id'] = $author_contact['cid'];
1807 $datarray['network'] = $author_contact['network'];
1809 $datarray = self::setDirection($datarray, $direction);
1811 $datarray['owner-link'] = $datarray['author-link'] = $author_url;
1812 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($author_url);
1814 $datarray['guid'] = $guid;
1815 $datarray['uri'] = self::getUriFromGuid($guid, $author);
1817 $datarray['verb'] = $verb;
1818 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
1819 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1821 $datarray['object-type'] = Activity\ObjectType::NOTE;
1823 $datarray['body'] = $verb;
1825 // Diaspora doesn't provide a date for likes
1826 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
1828 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1829 if ($toplevel_parent_item['gravity'] != Item::GRAVITY_PARENT) {
1830 $toplevel = Post::selectFirst(['origin'], ['id' => $toplevel_parent_item['parent']]);
1831 $origin = $toplevel['origin'];
1833 $origin = $toplevel_parent_item['origin'];
1836 // If we are the origin of the parent we store the original data.
1837 // We notify our followers during the item storage.
1839 $datarray['diaspora_signed_text'] = json_encode($data);
1842 if (Item::isTooOld($datarray)) {
1843 Logger::info('Like is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1847 $message_id = Item::insert($datarray);
1849 if ($message_id <= 0) {
1854 Logger::info('Stored like ' . $datarray['guid'] . ' with message id ' . $message_id);
1855 if ($datarray['uid'] == 0) {
1856 Item::distribute($message_id, json_encode($data));
1864 * Processes private messages
1866 * @param array $importer Array of the importer user
1867 * @param SimpleXMLElement $data The message object
1869 * @return bool Success?
1870 * @throws \Exception
1872 private static function receiveMessage(array $importer, SimpleXMLElement $data): bool
1874 $author_uri = WebFingerUri::fromString(XML::unescape($data->author));
1875 $guid = XML::unescape($data->guid);
1876 $conversation_guid = XML::unescape($data->conversation_guid);
1877 $text = XML::unescape($data->text);
1878 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1880 $contact = self::allowedContactByHandle($importer, $author_uri, true);
1885 if (!empty($contact['gsid'])) {
1886 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1889 $condition = ['uid' => $importer['uid'], 'guid' => $conversation_guid];
1890 $conversation = DBA::selectFirst('conv', [], $condition);
1891 if (!DBA::isResult($conversation)) {
1892 Logger::notice('Conversation not available.');
1897 $author = DI::dsprContact()->getByAddr($author_uri);
1898 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
1899 Logger::notice('Unable to find author details', ['author' => $author_uri->getAddr()]);
1903 $body = Markdown::toBBCode($text);
1905 $body = self::replacePeopleGuid($body, $author->url);
1907 return Mail::insert([
1908 'uid' => $importer['uid'],
1910 'convid' => $conversation['id'],
1911 'from-name' => $author->name,
1912 'from-photo' => (string)$author->photo,
1913 'from-url' => (string)$author->url,
1914 'contact-id' => $contact['id'],
1915 'title' => $conversation['subject'],
1918 'uri' => $author_uri . ':' . $guid,
1919 'parent-uri' => $author_uri . ':' . $conversation['guid'],
1920 'created' => $created_at
1925 * Processes participations - unsupported by now
1927 * @param array $importer Array of the importer user
1928 * @param SimpleXMLElement $data The message object
1929 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1931 * @return bool success
1932 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1933 * @throws \ImagickException
1935 private static function receiveParticipation(array $importer, SimpleXMLElement $data, int $direction): bool
1937 $author = WebFingerUri::fromString(strtolower(XML::unescape($data->author)));
1938 $guid = XML::unescape($data->guid);
1939 $parent_guid = XML::unescape($data->parent_guid);
1941 $contact = self::allowedContactByHandle($importer, $author, true);
1946 if (!empty($contact['gsid'])) {
1947 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1950 if (self::messageExists($importer['uid'], $guid)) {
1954 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1955 if (!$toplevel_parent_item) {
1959 if (!$toplevel_parent_item['origin']) {
1960 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1963 if (!in_array($toplevel_parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
1964 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1969 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
1970 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
1971 Logger::notice('unable to find author details', ['author' => $author->getAddr()]);
1975 $author_contact = self::authorContactByUrl($contact, $author_url, $importer['uid']);
1977 // Store participation
1980 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1982 $datarray['uid'] = $importer['uid'];
1983 $datarray['contact-id'] = $author_contact['cid'];
1984 $datarray['network'] = $author_contact['network'];
1986 $datarray = self::setDirection($datarray, $direction);
1988 $datarray['owner-link'] = $datarray['author-link'] = $author_url;
1989 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($author_url);
1991 $datarray['guid'] = $guid;
1992 $datarray['uri'] = self::getUriFromGuid($guid, $author);
1994 $datarray['verb'] = Activity::FOLLOW;
1995 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
1996 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1998 $datarray['object-type'] = Activity\ObjectType::NOTE;
2000 $datarray['body'] = Activity::FOLLOW;
2002 // Diaspora doesn't provide a date for a participation
2003 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
2005 if (Item::isTooOld($datarray)) {
2006 Logger::info('Participation is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2010 $message_id = Item::insert($datarray);
2012 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
2014 // Send all existing comments and likes to the requesting server
2015 $comments = Post::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb', 'gravity'],
2016 ['parent' => $toplevel_parent_item['id'], 'gravity' => [Item::GRAVITY_COMMENT, Item::GRAVITY_ACTIVITY]]);
2017 while ($comment = Post::fetch($comments)) {
2018 if (($comment['gravity'] == Item::GRAVITY_ACTIVITY) && !in_array($comment['verb'], [Activity::LIKE, Activity::DISLIKE])) {
2019 Logger::info('Unsupported activities are not relayed', ['item' => $comment['id'], 'verb' => $comment['verb']]);
2023 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
2024 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2028 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
2029 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2033 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact['cid']]);
2034 if (Worker::add(Worker::PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['uri-id'], $author_contact['cid'], $datarray['uid'])) {
2035 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2038 DBA::close($comments);
2044 * Processes photos - unneeded
2046 * @param array $importer Array of the importer user
2047 * @param SimpleXMLElement $data The message object
2049 * @return bool always true
2051 private static function receivePhoto(array $importer, $data)
2053 // There doesn't seem to be a reason for this function,
2054 // since the photo data is transmitted in the status message as well
2059 * Processes poll participations - unssupported
2061 * @param array $importer Array of the importer user
2062 * @param object $data The message object
2064 * @return bool always true
2066 private static function receivePollParticipation(array $importer, $data)
2068 // We don't support polls by now
2073 * Processes incoming profile updates
2075 * @param array $importer Array of the importer user
2076 * @param SimpleXMLElement $data The message object
2078 * @return bool Success
2079 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2080 * @throws \ImagickException
2082 private static function receiveProfile(array $importer, SimpleXMLElement $data): bool
2084 $author = WebFingerUri::fromString(strtolower(XML::unescape($data->author)));
2086 $contact = self::contactByHandle($importer['uid'], $author);
2091 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? ' ' . XML::unescape($data->last_name) : '');
2092 $image_url = XML::unescape($data->image_url);
2093 $birthday = XML::unescape($data->birthday);
2094 $about = Markdown::toBBCode(XML::unescape($data->bio));
2095 $location = Markdown::toBBCode(XML::unescape($data->location));
2096 $searchable = (XML::unescape($data->searchable) == 'true');
2097 $nsfw = (XML::unescape($data->nsfw) == 'true');
2098 $tags = XML::unescape($data->tag_string);
2100 $tags = explode('#', $tags);
2103 foreach ($tags as $tag) {
2104 $tag = trim(strtolower($tag));
2110 $keywords = implode(', ', $keywords);
2113 $name = $author->getUser();
2116 if (preg_match('|^https?://|', $image_url) === 0) {
2117 // @TODO No HTTPS here?
2118 $image_url = 'http://' . $author->getFullHost() . $image_url;
2121 Contact::updateAvatar($contact['id'], $image_url);
2123 // Generic birthday. We don't know the timezone. The year is irrelevant.
2125 $birthday = str_replace('1000', '1901', $birthday);
2127 if ($birthday != '') {
2128 $birthday = DateTimeFormat::utc($birthday, 'Y-m-d');
2131 // this is to prevent multiple birthday notifications in a single year
2132 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2134 if (substr($birthday, 5) === substr($contact['bd'], 5)) {
2135 $birthday = $contact['bd'];
2138 $fields = ['name' => $name, 'location' => $location,
2139 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2140 'addr' => $author->getAddr(), 'nick' => $author->getUser(), 'keywords' => $keywords,
2141 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2143 if (!empty($birthday)) {
2144 $fields['bd'] = $birthday;
2147 Contact::update($fields, ['id' => $contact['id']]);
2149 Logger::info('Profile of contact ' . $contact['id'] . ' stored for user ' . $importer['uid']);
2155 * Processes incoming friend requests
2157 * @param array $importer Array of the importer user
2158 * @param array $contact The contact that send the request
2160 * @throws \Exception
2162 private static function receiveRequestMakeFriend(array $importer, array $contact)
2164 if ($contact['rel'] == Contact::SHARING) {
2166 ['rel' => Contact::FRIEND, 'writable' => true],
2167 ['id' => $contact['id'], 'uid' => $importer['uid']]
2173 * Processes incoming sharing notification
2175 * @param array $importer Array of the importer user
2176 * @param SimpleXMLElement $data The message object
2178 * @return bool Success
2179 * @throws \Exception
2181 private static function receiveContactRequest(array $importer, SimpleXMLElement $data): bool
2183 $author_handle = XML::unescape($data->author);
2184 $recipient = XML::unescape($data->recipient);
2186 if (!$author_handle || !$recipient) {
2190 $author = WebFingerUri::fromString($author_handle);
2192 // the current protocol version doesn't know these fields
2193 // That means that we will assume their existance
2194 if (isset($data->following)) {
2195 $following = (XML::unescape($data->following) == 'true');
2200 if (isset($data->sharing)) {
2201 $sharing = (XML::unescape($data->sharing) == 'true');
2206 $contact = self::contactByHandle($importer['uid'], $author);
2208 // perhaps we were already sharing with this person. Now they're sharing with us.
2209 // That makes us friends.
2212 Logger::info('Author ' . $author . ' (Contact ' . $contact['id'] . ') wants to follow us.');
2213 self::receiveRequestMakeFriend($importer, $contact);
2215 // refetch the contact array
2216 $contact = self::contactByHandle($importer['uid'], $author);
2218 // If we are now friends, we are sending a share message.
2219 // Normally we needn't to do so, but the first message could have been vanished.
2220 if (in_array($contact['rel'], [Contact::FRIEND])) {
2221 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2222 if (DBA::isResult($user)) {
2223 Logger::info('Sending share message to author ' . $author . ' - Contact: ' . $contact['id'] . ' - User: ' . $importer['uid']);
2224 self::sendShare($user, $contact);
2229 Logger::info("Author " . $author . " doesn't want to follow us anymore.");
2230 Contact::removeFollower($contact);
2235 if (!$following && $sharing && in_array($importer['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2236 Logger::info("Author " . $author . " wants to share with us - but doesn't want to listen. Request is ignored.");
2238 } elseif (!$following && !$sharing) {
2239 Logger::info("Author " . $author . " doesn't want anything - and we don't know the author. Request is ignored.");
2241 } elseif (!$following && $sharing) {
2242 Logger::info("Author " . $author . " wants to share with us.");
2243 } elseif ($following && $sharing) {
2244 Logger::info("Author " . $author . " wants to have a bidirectional conection.");
2245 } elseif ($following && !$sharing) {
2246 Logger::info("Author " . $author . " wants to listen to us.");
2250 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
2251 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
2252 Logger::notice('Cannot resolve diaspora handle for recipient', ['author' => $author->getAddr(), 'recipient' => $recipient]);
2256 $cid = Contact::getIdForURL($author_url, $importer['uid']);
2258 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2264 'author-id' => Contact::getIdForURL($author_url),
2265 'author-link' => $author_url
2268 $result = Contact::addRelationship($importer, $contact, $item, false);
2269 if ($result === true) {
2270 $contact_record = self::contactByHandle($importer['uid'], $author);
2271 if (!$contact_record) {
2272 Logger::info('unable to locate newly created contact record.');
2276 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2277 if (DBA::isResult($user)) {
2278 self::sendShare($user, $contact_record);
2280 // Send the profile data, maybe it weren't transmitted before
2281 self::sendProfile($importer['uid'], [$contact_record]);
2289 * Stores a reshare activity
2291 * @param array $item Array of reshare post
2292 * @param integer $parent_message_id Id of the parent post
2293 * @param string $guid GUID string of reshare action
2294 * @param WebFingerUri $author Author handle
2295 * @return false|void
2296 * @throws InternalServerErrorException
2297 * @throws \ImagickException
2299 private static function addReshareActivity(array $item, int $parent_message_id, string $guid, WebFingerUri $author)
2301 $parent = Post::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2305 $datarray['uid'] = $item['uid'];
2306 $datarray['contact-id'] = $item['contact-id'];
2307 $datarray['network'] = $item['network'];
2309 $datarray['author-link'] = $item['author-link'];
2310 $datarray['author-id'] = $item['author-id'];
2312 $datarray['owner-link'] = $datarray['author-link'];
2313 $datarray['owner-id'] = $datarray['author-id'];
2315 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2316 $datarray['uri'] = self::getUriFromGuid($datarray['guid'], $author);
2317 $datarray['thr-parent'] = $parent['uri'];
2319 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2320 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
2321 $datarray['object-type'] = Activity\ObjectType::NOTE;
2323 $datarray['protocol'] = $item['protocol'];
2324 $datarray['source'] = $item['source'];
2325 $datarray['direction'] = $item['direction'];
2326 $datarray['post-reason'] = $item['post-reason'];
2328 $datarray['plink'] = self::plink($author, $datarray['guid']);
2329 $datarray['private'] = $item['private'];
2330 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2332 if (Item::isTooOld($datarray)) {
2333 Logger::info('Reshare activity is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2337 $message_id = Item::insert($datarray);
2340 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2341 if ($datarray['uid'] == 0) {
2342 Item::distribute($message_id);
2348 * Processes a reshare message
2350 * @param array $importer Array of the importer user
2351 * @param SimpleXMLElement $data The message object
2352 * @param string $xml The original XML of the message
2353 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2355 * @return bool Success or failure
2356 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2357 * @throws \ImagickException
2359 private static function receiveReshare(array $importer, SimpleXMLElement $data, string $xml, int $direction): bool
2361 $author = WebFingerUri::fromString(XML::unescape($data->author));
2362 $guid = XML::unescape($data->guid);
2363 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2365 $root_author = WebFingerUri::fromString(XML::unescape($data->root_author));
2366 } catch (\InvalidArgumentException $e) {
2370 $root_guid = XML::unescape($data->root_guid);
2371 /// @todo handle unprocessed property "provider_display_name"
2372 $public = XML::unescape($data->public);
2374 $contact = self::allowedContactByHandle($importer, $author);
2379 if (!empty($contact['gsid'])) {
2380 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2383 $message_id = self::messageExists($importer['uid'], $guid);
2389 $original_person = DI::dsprContact()->getByAddr($root_author);
2390 } catch (HTTPException\NotFoundException $e) {
2396 $datarray['uid'] = $importer['uid'];
2397 $datarray['contact-id'] = $contact['id'];
2398 $datarray['network'] = Protocol::DIASPORA;
2400 $datarray['author-link'] = $contact['url'];
2401 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2403 $datarray['owner-link'] = $datarray['author-link'];
2404 $datarray['owner-id'] = $datarray['author-id'];
2406 $datarray['guid'] = $guid;
2407 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($guid, $author);
2408 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2410 $datarray['verb'] = Activity::POST;
2411 $datarray['gravity'] = Item::GRAVITY_PARENT;
2413 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2414 $datarray['source'] = $xml;
2416 $datarray = self::setDirection($datarray, $direction);
2418 $datarray['quote-uri-id'] = self::getQuoteUriId($root_guid, $importer['uid'], $original_person->url);
2419 if (empty($datarray['quote-uri-id'])) {
2423 $datarray['body'] = '';
2424 $datarray['plink'] = self::plink($author, $guid);
2425 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2426 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2428 self::fetchGuid($datarray);
2430 if (Item::isTooOld($datarray)) {
2431 Logger::info('Reshare is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2435 $message_id = Item::insert($datarray);
2437 self::sendParticipation($contact, $datarray);
2439 $root_message_id = self::messageExists($importer['uid'], $root_guid);
2440 if ($root_message_id) {
2441 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2445 Logger::info('Stored reshare ' . $datarray['guid'] . ' with message id ' . $message_id);
2446 if ($datarray['uid'] == 0) {
2447 Item::distribute($message_id);
2455 private static function getQuoteUriId(string $guid, int $uid, string $host): int
2457 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2459 if (!DBA::isResult($shared_item) && !empty($host) && Diaspora::storeByGuid($guid, $host, true)) {
2460 Logger::debug('Fetched post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2461 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2462 } elseif (DBA::isResult($shared_item)) {
2463 Logger::debug('Found existing post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2466 if (!DBA::isResult($shared_item)) {
2467 Logger::notice('Post does not exist.', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2471 return $shared_item['uri-id'];
2475 * Processes retractions
2477 * @param array $importer Array of the importer user
2478 * @param array $contact The contact of the item owner
2479 * @param SimpleXMLElement $data The message object
2481 * @return bool success
2482 * @throws \Exception
2484 private static function itemRetraction(array $importer, array $contact, SimpleXMLElement $data): bool
2486 $author_uri = WebFingerUri::fromString(XML::unescape($data->author));
2487 $target_guid = XML::unescape($data->target_guid);
2488 $target_type = XML::unescape($data->target_type);
2491 $author = DI::dsprContact()->getByAddr($author_uri);
2492 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
2493 Logger::notice('Unable to find details for author', ['author' => $author_uri->getAddr()]);
2497 $contact_url = $contact['url'] ?? '' ?: (string)$author->url;
2499 // Fetch items that are about to be deleted
2500 $fields = ['uid', 'id', 'parent', 'author-link', 'uri-id'];
2502 // When we receive a public retraction, we delete every item that we find.
2503 if ($importer['uid'] == 0) {
2504 $condition = ['guid' => $target_guid, 'deleted' => false];
2506 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2509 $r = Post::select($fields, $condition);
2510 if (!DBA::isResult($r)) {
2511 Logger::notice('Target guid ' . $target_guid . ' was not found on this system for user ' . $importer['uid'] . '.');
2515 while ($item = Post::fetch($r)) {
2516 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2517 Logger::info("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.");
2521 // Fetch the parent item
2522 $parent = Post::selectFirst(['author-link'], ['id' => $item['parent']]);
2524 // Only delete it if the parent author really fits
2525 if (!Strings::compareLink($parent['author-link'], $contact_url) && !Strings::compareLink($item['author-link'], $contact_url)) {
2526 Logger::info("Thread author " . $parent['author-link'] . " and item author " . $item['author-link'] . " don't fit to expected contact " . $contact_url);
2530 Item::markForDeletion(['id' => $item['id']]);
2532 Logger::info('Deleted target ' . $target_guid . ' (' . $item['id'] . ') from user ' . $item['uid'] . ' parent: ' . $item['parent']);
2540 * Receives retraction messages
2542 * @param array $importer Array of the importer user
2543 * @param WebFingerUri $sender The sender of the message
2544 * @param SimpleXMLElement $data The message object
2546 * @return bool Success
2547 * @throws \Exception
2549 private static function receiveRetraction(array $importer, WebFingerUri $sender, SimpleXMLElement $data)
2551 $target_type = XML::unescape($data->target_type);
2553 $contact = self::contactByHandle($importer['uid'], $sender);
2554 if (!$contact && (in_array($target_type, ['Contact', 'Person']))) {
2555 Logger::notice('Cannot find contact for sender: ' . $sender . ' and user ' . $importer['uid']);
2563 Logger::info('Got retraction for ' . $target_type . ', sender ' . $sender . ' and user ' . $importer['uid']);
2565 switch ($target_type) {
2570 case 'StatusMessage':
2571 return self::itemRetraction($importer, $contact, $data);
2573 case 'PollParticipation':
2575 // Currently unsupported
2579 Logger::notice('Unknown target type ' . $target_type);
2586 * Checks if an incoming message is wanted
2588 * @param array $item
2589 * @param string $author
2590 * @param string $body
2591 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2593 * @return boolean Is the message wanted?
2595 private static function isSolicitedMessage(array $item, string $author, string $body, int $direction): bool
2597 $contact = Contact::getByURL($author);
2598 if (DBA::exists('contact', ['`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)', $contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) {
2599 Logger::debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2603 if ($direction == self::FORCED_FETCH) {
2604 Logger::debug('Post is a forced fetch - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2608 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
2609 if (Relay::isSolicitedPost($tags, $body, $contact['id'], $item['uri'], Protocol::DIASPORA)) {
2610 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2618 * Store an attached photo in the post-media table
2621 * @param object $photo
2624 private static function storePhotoAsMedia(int $uriid, $photo)
2626 // @TODO Need to find object type, roland@f.haeder.net
2627 Logger::debug('photo='.get_class($photo));
2629 $data['uri-id'] = $uriid;
2630 $data['type'] = Post\Media::IMAGE;
2631 $data['url'] = XML::unescape($photo->remote_photo_path) . XML::unescape($photo->remote_photo_name);
2632 $data['height'] = (int)XML::unescape($photo->height ?? 0);
2633 $data['width'] = (int)XML::unescape($photo->width ?? 0);
2634 $data['description'] = XML::unescape($photo->text ?? '');
2636 Post\Media::insert($data);
2640 * Set direction and post reason
2642 * @param array $datarray
2643 * @param integer $direction
2647 public static function setDirection(array $datarray, int $direction): array
2649 $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
2651 if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
2652 $datarray['post-reason'] = Item::PR_FETCHED;
2653 } elseif ($datarray['uid'] == 0) {
2654 $datarray['post-reason'] = Item::PR_GLOBAL;
2656 $datarray['post-reason'] = Item::PR_PUSHED;
2663 * Receives status messages
2665 * @param array $importer Array of the importer user
2666 * @param SimpleXMLElement $data The message object
2667 * @param string $xml The original XML of the message
2668 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2670 * @return int|bool The message id of the newly created item or false on error
2671 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2672 * @throws \ImagickException
2674 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, string $xml, int $direction)
2676 $author = WebFingerUri::fromString(XML::unescape($data->author));
2677 $guid = XML::unescape($data->guid);
2678 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2679 $public = XML::unescape($data->public);
2680 $text = XML::unescape($data->text);
2681 $provider_display_name = XML::unescape($data->provider_display_name);
2683 $contact = self::allowedContactByHandle($importer, $author);
2688 if (!empty($contact['gsid'])) {
2689 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2692 $message_id = self::messageExists($importer['uid'], $guid);
2698 if ($data->location) {
2699 foreach ($data->location->children() as $fieldname => $data) {
2700 $address[$fieldname] = XML::unescape($data);
2704 $raw_body = $body = Markdown::toBBCode($text);
2708 $datarray['guid'] = $guid;
2709 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($guid, $author);
2710 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2712 // Attach embedded pictures to the body
2714 foreach ($data->photo as $photo) {
2715 self::storePhotoAsMedia($datarray['uri-id'], $photo);
2718 $datarray['object-type'] = Activity\ObjectType::IMAGE;
2719 $datarray['post-type'] = Item::PT_IMAGE;
2720 } elseif ($data->poll) {
2721 $datarray['object-type'] = Activity\ObjectType::NOTE;
2722 $datarray['post-type'] = Item::PT_POLL;
2724 $datarray['object-type'] = Activity\ObjectType::NOTE;
2725 $datarray['post-type'] = Item::PT_NOTE;
2728 /// @todo enable support for polls
2729 //if ($data->poll) {
2730 // foreach ($data->poll as $poll)
2735 /// @todo enable support for events
2737 $datarray['uid'] = $importer['uid'];
2738 $datarray['contact-id'] = $contact['id'];
2739 $datarray['network'] = Protocol::DIASPORA;
2741 $datarray['author-link'] = $contact['url'];
2742 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2744 $datarray['owner-link'] = $datarray['author-link'];
2745 $datarray['owner-id'] = $datarray['author-id'];
2747 $datarray['verb'] = Activity::POST;
2748 $datarray['gravity'] = Item::GRAVITY_PARENT;
2750 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2751 $datarray['source'] = $xml;
2753 $datarray = self::setDirection($datarray, $direction);
2755 $datarray['body'] = self::replacePeopleGuid($body, $contact['url']);
2756 $datarray['raw-body'] = self::replacePeopleGuid($raw_body, $contact['url']);
2758 self::storeMentions($datarray['uri-id'], $text);
2759 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
2761 if (!self::isSolicitedMessage($datarray, $author, $body, $direction)) {
2762 DBA::delete('item-uri', ['uri' => $datarray['uri']]);
2766 if ($provider_display_name != '') {
2767 $datarray['app'] = $provider_display_name;
2770 $datarray['plink'] = self::plink($author, $guid);
2771 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2772 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2774 if (isset($address['address'])) {
2775 $datarray['location'] = $address['address'];
2778 if (isset($address['lat']) && isset($address['lng'])) {
2779 $datarray['coord'] = $address['lat'] . ' ' . $address['lng'];
2782 self::fetchGuid($datarray);
2784 if (Item::isTooOld($datarray)) {
2785 Logger::info('Status is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2789 $message_id = Item::insert($datarray);
2791 self::sendParticipation($contact, $datarray);
2794 Logger::info('Stored item ' . $datarray['guid'] . ' with message id ' . $message_id);
2795 if ($datarray['uid'] == 0) {
2796 Item::distribute($message_id);
2804 /* ************************************************************************************** *
2805 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2806 * ************************************************************************************** */
2809 * returnes the handle of a contact
2811 * @param array $contact contact array
2813 * @return string the handle in the format user@domain.tld
2814 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2816 private static function myHandle(array $contact): string
2818 if (!empty($contact['addr'])) {
2819 return $contact['addr'];
2822 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2823 // So - just in case - we build the the address here.
2824 if ($contact['nickname'] != '') {
2825 $nick = $contact['nickname'];
2827 $nick = $contact['nick'];
2830 return $nick . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
2835 * Creates the data for a private message in the new format
2837 * @param string $msg The message that is to be transmitted
2838 * @param array $user The record of the sender
2839 * @param array $contact Target of the communication
2840 * @param string $prvkey The private key of the sender
2841 * @param string $pubkey The public key of the receiver
2843 * @return string The encrypted data
2844 * @throws \Exception
2846 public static function encodePrivateData(string $msg, array $user, array $contact, string $prvkey, string $pubkey): string
2848 Logger::debug('Message: ' . $msg);
2850 // without a public key nothing will work
2852 Logger::notice('pubkey missing: contact id: ' . $contact['id']);
2856 $aes_key = random_bytes(32);
2857 $b_aes_key = base64_encode($aes_key);
2858 $iv = random_bytes(16);
2859 $b_iv = base64_encode($iv);
2861 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2863 $json = json_encode(['iv' => $b_iv, 'key' => $b_aes_key]);
2865 $encrypted_key_bundle = '';
2866 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
2870 $json_object = json_encode(
2872 'aes_key' => base64_encode($encrypted_key_bundle),
2873 'encrypted_magic_envelope' => base64_encode($ciphertext)
2877 return $json_object;
2881 * Creates the envelope for the "fetch" endpoint and for the new format
2883 * @param string $msg The message that is to be transmitted
2884 * @param array $user The record of the sender
2886 * @return string The envelope
2887 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2889 public static function buildMagicEnvelope(string $msg, array $user): string
2891 $b64url_data = Strings::base64UrlEncode($msg);
2892 $data = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
2894 $key_id = Strings::base64UrlEncode(self::myHandle($user));
2895 $type = 'application/xml';
2896 $encoding = 'base64url';
2897 $alg = 'RSA-SHA256';
2898 $signable_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
2900 // Fallback if the private key wasn't transmitted in the expected field
2901 if ($user['uprvkey'] == '') {
2902 $user['uprvkey'] = $user['prvkey'];
2905 $signature = Crypto::rsaSign($signable_data, $user['uprvkey']);
2906 $sig = Strings::base64UrlEncode($signature);
2911 '@attributes' => ['type' => $type],
2912 'me:encoding' => $encoding,
2915 '@attributes2' => ['key_id' => $key_id]
2919 $namespaces = ['me' => ActivityNamespace::SALMON_ME];
2921 return XML::fromArray($xmldata, $xml, false, $namespaces);
2925 * Create the envelope for a message
2927 * @param string $msg The message that is to be transmitted
2928 * @param array $user The record of the sender
2929 * @param array $contact Target of the communication
2930 * @param string $prvkey The private key of the sender
2931 * @param string $pubkey The public key of the receiver
2932 * @param bool $public Is the message public?
2934 * @return string The message that will be transmitted to other servers
2935 * @throws \Exception
2937 public static function buildMessage(string $msg, array $user, array $contact, string $prvkey, string $pubkey, bool $public = false): string
2939 // The message is put into an envelope with the sender's signature
2940 $envelope = self::buildMagicEnvelope($msg, $user);
2942 // Private messages are put into a second envelope, encrypted with the receivers public key
2944 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
2951 * Creates a signature for a message
2953 * @param array $owner the array of the owner of the message
2954 * @param array $message The message that is to be signed
2956 * @return string The signature
2958 private static function signature(array $owner, array $message): string
2961 unset($sigmsg['author_signature']);
2962 unset($sigmsg['parent_author_signature']);
2964 $signed_text = implode(';', $sigmsg);
2966 return base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
2970 * Transmit a message to a target server
2972 * @param array $owner the array of the item owner
2973 * @param array $contact Target of the communication
2974 * @param string $envelope The message that is to be transmitted
2975 * @param bool $public_batch Is it a public post?
2976 * @param string $guid message guid
2978 * @return int Result of the transmission
2979 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2980 * @throws \ImagickException
2982 private static function transmit(array $owner, array $contact, string $envelope, bool $public_batch, string $guid = ''): int
2984 $enabled = intval(DI::config()->get('system', 'diaspora_enabled'));
2989 $logid = Strings::getRandomHex(4);
2991 // We always try to use the data from the diaspora-contact table.
2992 // This is important for transmitting data to Friendica servers.
2994 $target = DI::dsprContact()->getByAddr(WebFingerUri::fromString($contact['addr']));
2995 $dest_url = $public_batch ? $target->batch : $target->notify;
2996 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
3000 if (empty($dest_url)) {
3001 $dest_url = ($public_batch ? $contact['batch'] : $contact['notify']);
3005 Logger::notice('No URL for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
3009 Logger::notice('transmit: ' . $logid . '-' . $guid . ' ' . $dest_url);
3011 if (!intval(DI::config()->get('system', 'diaspora_test'))) {
3012 $content_type = (($public_batch) ? 'application/magic-envelope+xml' : 'application/json');
3014 $postResult = DI::httpClient()->post($dest_url . '/', $envelope, ['Content-Type' => $content_type]);
3015 $return_code = $postResult->getReturnCode();
3017 Logger::notice('test_mode');
3021 Logger::notice('transmit: ' . $logid . '-' . $guid . ' to ' . $dest_url . ' returns: ' . $return_code);
3023 return $return_code ? $return_code : -1;
3028 * Build the post xml
3030 * @param string $type The message type
3031 * @param array $message The message data
3033 * @return string The post XML
3035 public static function buildPostXml(string $type, array $message): string
3037 $data = [$type => $message];
3039 return XML::fromArray($data, $xml);
3043 * Builds and transmit messages
3045 * @param array $owner the array of the item owner
3046 * @param array $contact Target of the communication
3047 * @param string $type The message type
3048 * @param array $message The message data
3049 * @param bool $public_batch Is it a public post?
3050 * @param string $guid message guid
3052 * @return int Result of the transmission
3053 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3054 * @throws \ImagickException
3056 private static function buildAndTransmit(array $owner, array $contact, string $type, array $message, bool $public_batch = false, string $guid = '')
3058 $msg = self::buildPostXml($type, $message);
3060 // Fallback if the private key wasn't transmitted in the expected field
3061 if (empty($owner['uprvkey'])) {
3062 $owner['uprvkey'] = $owner['prvkey'];
3065 // When sending content to Friendica contacts using the Diaspora protocol
3066 // we have to fetch the public key from the diaspora-contact.
3067 // This is due to the fact that legacy DFRN had unique keys for every contact.
3068 $pubkey = $contact['pubkey'];
3069 if (!empty($contact['addr'])) {
3071 $pubkey = DI::dsprContact()->getByAddr(WebFingerUri::fromString($contact['addr']))->pubKey;
3072 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
3076 // The "addr" field should always be filled.
3077 // If this isn't the case, it will raise a notice some lines later.
3078 // And in the log we will see where it came from, and we can handle it there.
3079 Logger::notice('Empty addr', ['contact' => $contact ?? [], 'callstack' => System::callstack(20)]);
3082 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $pubkey ?? '', $public_batch);
3084 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3086 Logger::info('Transmitted message', ['owner' => $owner['uid'], 'target' => $contact['addr'], 'type' => $type, 'guid' => $guid, 'result' => $return_code]);
3088 return $return_code;
3092 * sends a participation (Used to get all further updates)
3094 * @param array $contact Target of the communication
3095 * @param array $item Item array
3097 * @return int The result of the transmission
3098 * @throws \Exception
3100 private static function sendParticipation(array $contact, array $item): int
3102 // Don't send notifications for private postings
3103 if ($item['private'] == Item::PRIVATE) {
3107 $cachekey = 'diaspora:sendParticipation:' . $item['guid'];
3109 $result = DI::cache()->get($cachekey);
3110 if (!is_null($result)) {
3114 // Fetch some user id to have a valid handle to transmit the participation.
3115 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3116 // If the item belongs to a user, we take this user id.
3117 if ($item['uid'] == 0) {
3118 // @todo Possibly use an administrator account?
3119 $condition = ['verified' => true, 'blocked' => false,
3120 'account_removed' => false, 'account_expired' => false, 'account-type' => User::ACCOUNT_TYPE_PERSON];
3121 $first_user = DBA::selectFirst('user', ['uid'], $condition, ['order' => ['uid']]);
3122 $owner = User::getOwnerDataById($first_user['uid']);
3124 $owner = User::getOwnerDataById($item['uid']);
3127 $author_handle = self::myHandle($owner);
3130 'author' => $author_handle,
3131 'guid' => System::createUUID(),
3132 'parent_type' => 'Post',
3133 'parent_guid' => $item['guid']
3136 Logger::info('Send participation for ' . $item['guid'] . ' by ' . $author_handle);
3138 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3139 DI::cache()->set($cachekey, $item['guid'], Duration::QUARTER_HOUR);
3141 return self::buildAndTransmit($owner, $contact, 'participation', $message);
3145 * sends an account migration
3147 * @param array $owner the array of the item owner
3148 * @param array $contact Target of the communication
3149 * @param int $uid User ID
3151 * @return int The result of the transmission
3152 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3153 * @throws \ImagickException
3155 public static function sendAccountMigration(array $owner, array $contact, int $uid): int
3157 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3158 $profile = self::createProfileData($uid);
3160 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3161 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
3164 'author' => $old_handle,
3165 'profile' => $profile,
3166 'signature' => $signature
3169 Logger::info('Send account migration', ['msg' => $message]);
3171 return self::buildAndTransmit($owner, $contact, 'account_migration', $message);
3175 * Sends a "share" message
3177 * @param array $owner the array of the item owner
3178 * @param array $contact Target of the communication
3180 * @return int The result of the transmission
3181 * @throws \Exception
3183 public static function sendShare(array $owner, array $contact): int
3186 * @todo support the different possible combinations of "following" and "sharing"
3187 * Currently, Diaspora only interprets the "sharing" field
3189 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3193 switch ($contact["rel"]) {
3194 case Contact::FRIEND:
3198 case Contact::SHARING:
3202 case Contact::FOLLOWER:
3209 'author' => self::myHandle($owner),
3210 'recipient' => $contact['addr'],
3211 'following' => 'true',
3215 Logger::info('Send share', ['msg' => $message]);
3217 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3221 * sends an "unshare"
3223 * @param array $owner the array of the item owner
3224 * @param array $contact Target of the communication
3226 * @return int The result of the transmission
3227 * @throws \Exception
3229 public static function sendUnshare(array $owner, array $contact): int
3232 'author' => self::myHandle($owner),
3233 'recipient' => $contact['addr'],
3234 'following' => 'false',
3235 'sharing' => 'false'
3238 Logger::info('Send unshare', ['msg' => $message]);
3240 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3244 * Fetch reshare details
3246 * @param array $item The message body that is to be check
3248 * @return array Reshare details (empty if the item is no reshare)
3249 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3250 * @throws \ImagickException
3252 public static function getReshareDetails(array $item): array
3254 $reshared = DI::contentItem()->getSharedPost($item, ['guid', 'network', 'author-addr']);
3255 if (empty($reshared)) {
3259 // Skip if it isn't a pure repeated messages or not a real reshare
3260 if (!empty($reshared['comment']) || !in_array($reshared['post']['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
3265 'root_handle' => strtolower($reshared['post']['author-addr']),
3266 'root_guid' => $reshared['post']['guid'],
3271 * Create an event array
3273 * @param integer $event_id The id of the event
3275 * @return array with event data
3276 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3278 private static function buildEvent(string $event_id): array
3280 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
3281 if (!DBA::isResult($event)) {
3287 $owner = User::getOwnerDataById($event['uid']);
3292 $eventdata['author'] = self::myHandle($owner);
3294 if ($event['guid']) {
3295 $eventdata['guid'] = $event['guid'];
3298 $mask = DateTimeFormat::ATOM;
3300 /// @todo - establish "all day" events in Friendica
3301 $eventdata['all_day'] = 'false';
3303 $eventdata['timezone'] = 'UTC';
3305 if ($event['start']) {
3306 $eventdata['start'] = DateTimeFormat::utc($event['start'], $mask);
3308 if ($event['finish'] && !$event['nofinish']) {
3309 $eventdata['end'] = DateTimeFormat::utc($event['finish'], $mask);
3311 if ($event['summary']) {
3312 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3314 if ($event['desc']) {
3315 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3317 if ($event['location']) {
3318 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3319 $coord = Map::getCoordinates($event['location']);
3322 $location['address'] = html_entity_decode(BBCode::toMarkdown($event['location']));
3323 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3324 $location['lat'] = $coord['lat'];
3325 $location['lng'] = $coord['lon'];
3327 $location['lat'] = 0;
3328 $location['lng'] = 0;
3330 $eventdata['location'] = $location;
3337 * Create a post (status message or reshare)
3339 * @param array $item The item that will be exported
3340 * @param array $owner the array of the item owner
3343 * 'type' -> Message type ("status_message" or "reshare")
3344 * 'message' -> Array of XML elements of the status
3345 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3346 * @throws \ImagickException
3348 public static function buildStatus(array $item, array $owner)
3350 $cachekey = 'diaspora:buildStatus:' . $item['guid'];
3352 $result = DI::cache()->get($cachekey);
3353 if (!is_null($result)) {
3357 $myaddr = self::myHandle($owner);
3359 $public = ($item['private'] == Item::PRIVATE ? 'false' : 'true');
3360 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3361 $edited = DateTimeFormat::utc($item['edited'] ?? $item['created'], DateTimeFormat::ATOM);
3363 // Detect a share element and do a reshare
3364 if (($item['private'] != Item::PRIVATE) && ($ret = self::getReshareDetails($item))) {
3366 'author' => $myaddr,
3367 'guid' => $item['guid'],
3368 'created_at' => $created,
3369 'root_author' => $ret['root_handle'],
3370 'root_guid' => $ret['root_guid'],
3371 'provider_display_name' => $item['app'],
3377 $title = $item['title'];
3378 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
3380 // Fetch the title from an attached link - if there is one
3381 if (empty($item['title']) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3382 $page_data = BBCode::getAttachmentData($item['body']);
3383 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3384 $title = $page_data['title'];
3388 // convert to markdown
3389 $body = html_entity_decode(BBCode::toMarkdown($body));
3392 if (strlen($title)) {
3393 $body = '### ' . html_entity_decode($title) . "\n\n" . $body;
3396 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT]);
3397 if (!empty($attachments)) {
3398 $body .= "\n[hr]\n";
3399 foreach ($attachments as $attachment) {
3400 $body .= "[" . $attachment['description'] . "](" . $attachment['url'] . ")\n";
3406 if ($item['location'] != '')
3407 $location['address'] = $item['location'];
3409 if ($item['coord'] != '') {
3410 $coord = explode(' ', $item['coord']);
3411 $location['lat'] = $coord[0];
3412 $location['lng'] = $coord[1];
3416 'author' => $myaddr,
3417 'guid' => $item['guid'],
3418 'created_at' => $created,
3419 'edited_at' => $edited,
3420 'public' => $public,
3422 'provider_display_name' => $item['app'],
3423 'location' => $location
3426 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3427 if (!isset($location['lat']) || !isset($location['lng'])) {
3428 unset($message['location']);
3431 if ($item['event-id'] > 0) {
3432 $event = self::buildEvent($item['event-id']);
3433 if (count($event)) {
3434 $message['event'] = $event;
3436 if (!empty($event['location']['address']) &&
3437 !empty($event['location']['lat']) &&
3438 !empty($event['location']['lng'])) {
3439 $message['location'] = $event['location'];
3442 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3443 // $message['text'] = '';
3447 $type = 'status_message';
3452 'message' => $message
3455 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3460 private static function prependParentAuthorMention(string $body, string $profile_url): string
3462 $profile = Contact::getByURL($profile_url, false, ['addr', 'name']);
3463 if (!empty($profile['addr'])
3464 && !strstr($body, $profile['addr'])
3465 && !strstr($body, $profile_url)
3467 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3476 * @param array $item The item that will be exported
3477 * @param array $owner the array of the item owner
3478 * @param array $contact Target of the communication
3479 * @param bool $public_batch Is it a public post?
3481 * @return int The result of the transmission
3482 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3483 * @throws \ImagickException
3485 public static function sendStatus(array $item, array $owner, array $contact, bool $public_batch = false): int
3487 $status = self::buildStatus($item, $owner);
3489 return self::buildAndTransmit($owner, $contact, $status['type'], $status['message'], $public_batch, $item['guid']);
3493 * Creates a "like" object
3495 * @param array $item The item that will be exported
3496 * @param array $owner the array of the item owner
3498 * @return array|bool The data for a "like" or false on error
3499 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3501 private static function constructLike(array $item, array $owner)
3503 $parent = Post::selectFirst(['guid', 'uri', 'thr-parent'], ['uri' => $item['thr-parent']]);
3504 if (!DBA::isResult($parent)) {
3508 $target_type = ($parent['uri'] === $parent['thr-parent'] ? 'Post' : 'Comment');
3510 if ($item['verb'] === Activity::LIKE) {
3512 } elseif ($item['verb'] === Activity::DISLIKE) {
3513 $positive = 'false';
3517 'author' => self::myHandle($owner),
3518 'guid' => $item['guid'],
3519 'parent_guid' => $parent['guid'],
3520 'parent_type' => $target_type,
3521 'positive' => $positive,
3522 'author_signature' => '',
3527 * Creates an "EventParticipation" object
3529 * @param array $item The item that will be exported
3530 * @param array $owner the array of the item owner
3532 * @return array|bool The data for an "EventParticipation" or false on error
3533 * @throws \Exception
3535 private static function constructAttend(array $item, array $owner)
3537 $parent = Post::selectFirst(['guid'], ['uri' => $item['thr-parent']]);
3538 if (!DBA::isResult($parent)) {
3542 switch ($item['verb']) {
3543 case Activity::ATTEND:
3544 $attend_answer = 'accepted';
3546 case Activity::ATTENDNO:
3547 $attend_answer = 'declined';
3549 case Activity::ATTENDMAYBE:
3550 $attend_answer = 'tentative';
3553 Logger::warning('Unknown verb ' . $item['verb'] . ' in item ' . $item['guid']);
3558 'author' => self::myHandle($owner),
3559 'guid' => $item['guid'],
3560 'parent_guid' => $parent['guid'],
3561 'status' => $attend_answer,
3562 'author_signature' => ''
3567 * Creates the object for a comment
3569 * @param array $item The item that will be exported
3570 * @param array $owner the array of the item owner
3572 * @return array|false The data for a comment
3573 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3575 private static function constructComment(array $item, array $owner)
3577 $cachekey = 'diaspora:constructComment:' . $item['guid'];
3579 $result = DI::cache()->get($cachekey);
3580 if (!is_null($result)) {
3584 $toplevel_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3585 if (!DBA::isResult($toplevel_item)) {
3586 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3590 $thread_parent_item = $toplevel_item;
3591 if ($item['thr-parent'] != $item['parent-uri']) {
3592 $thread_parent_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3595 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
3597 // The replied to autor mention is prepended for clarity if:
3598 // - Item replied isn't yours
3599 // - Item is public or explicit mentions are disabled
3600 // - Implicit mentions are enabled
3602 $item['author-id'] != $thread_parent_item['author-id']
3603 && ($thread_parent_item['gravity'] != Item::GRAVITY_PARENT)
3604 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3605 && !DI::config()->get('system', 'disable_implicit_mentions')
3607 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3610 $text = html_entity_decode(BBCode::toMarkdown($body));
3611 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3612 $edited = DateTimeFormat::utc($item['edited'], DateTimeFormat::ATOM);
3615 'author' => self::myHandle($owner),
3616 'guid' => $item['guid'],
3617 'created_at' => $created,
3618 'edited_at' => $edited,
3619 'parent_guid' => $toplevel_item['guid'],
3621 'author_signature' => '',
3624 // Send the thread parent guid only if it is a threaded comment
3625 if ($item['thr-parent'] != $item['parent-uri']) {
3626 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3629 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3635 * Send a like or a comment
3637 * @param array $item The item that will be exported
3638 * @param array $owner the array of the item owner
3639 * @param array $contact Target of the communication
3640 * @param bool $public_batch Is it a public post?
3642 * @return int The result of the transmission
3643 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3644 * @throws \ImagickException
3646 public static function sendFollowup(array $item, array $owner, array $contact, bool $public_batch = false): int
3648 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3649 $message = self::constructAttend($item, $owner);
3650 $type = 'event_participation';
3651 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3652 $message = self::constructLike($item, $owner);
3654 } elseif (!in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
3655 $message = self::constructComment($item, $owner);
3659 if (empty($message)) {
3663 $message['author_signature'] = self::signature($owner, $message);
3665 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3669 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
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?
3676 * @return int The result of the transmission
3677 * @throws \Exception
3679 public static function sendRelay(array $item, array $owner, array $contact, bool $public_batch = false): int
3681 if ($item['deleted']) {
3682 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3683 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3689 Logger::info('Got relayable data ' . $type . ' for item ' . $item['guid'] . ' (' . $item['id'] . ')');
3691 $msg = json_decode($item['signed_text'] ?? '', true);
3694 if (is_array($msg)) {
3695 foreach ($msg as $field => $data) {
3696 if (!$item['deleted']) {
3697 if ($field == 'diaspora_handle') {
3700 if ($field == 'target_type') {
3701 $field = 'parent_type';
3705 $message[$field] = $data;
3708 Logger::info('Signature text for item ' . $item['guid'] . ' (' . $item['id'] . ') could not be extracted: ' . $item['signed_text']);
3711 $message['parent_author_signature'] = self::signature($owner, $message);
3713 Logger::info('Relayed data', ['msg' => $message]);
3715 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3719 * Sends a retraction (deletion) of a message, like or comment
3721 * @param array $item The item that will be exported
3722 * @param array $owner the array of the item owner
3723 * @param array $contact Target of the communication
3724 * @param bool $public_batch Is it a public post?
3725 * @param bool $relay Is the retraction transmitted from a relay?
3727 * @return int The result of the transmission
3728 * @throws \Exception
3730 public static function sendRetraction(array $item, array $owner, array $contact, bool $public_batch = false, bool $relay = false): int
3732 $itemaddr = strtolower($item['author-addr']);
3734 $msg_type = 'retraction';
3736 if ($item['gravity'] == Item::GRAVITY_PARENT) {
3737 $target_type = 'Post';
3738 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3739 $target_type = 'Like';
3741 $target_type = 'Comment';
3745 'author' => $itemaddr,
3746 'target_guid' => $item['guid'],
3747 'target_type' => $target_type
3750 Logger::info('Got message', ['msg' => $message]);
3752 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item['guid']);
3758 * @param array $item The item that will be exported
3759 * @param array $owner The owner
3760 * @param array $contact Target of the communication
3762 * @return int The result of the transmission
3763 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3764 * @throws \ImagickException
3766 public static function sendMail(array $item, array $owner, array $contact): int
3768 $myaddr = self::myHandle($owner);
3770 $cnv = DBA::selectFirst('conv', [], ['id' => $item['convid'], 'uid' => $item['uid']]);
3771 if (!DBA::isResult($cnv)) {
3772 Logger::notice('Conversation not found.');
3776 $body = BBCode::toMarkdown($item['body']);
3777 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3780 'author' => $myaddr,
3781 'guid' => $item['guid'],
3782 'conversation_guid' => $cnv['guid'],
3784 'created_at' => $created,
3787 if ($item['reply']) {
3792 'author' => $cnv['creator'],
3793 'guid' => $cnv['guid'],
3794 'subject' => $cnv['subject'],
3795 'created_at' => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3796 'participants' => $cnv['recips'],
3800 $type = 'conversation';
3803 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item['guid']);
3807 * Split a name into first name and last name
3809 * @param string $name The name
3811 * @return array The array with "first" and "last"
3813 public static function splitName(string $name): array
3815 $name = trim($name);
3817 // Is the name longer than 64 characters? Then cut the rest of it.
3818 if (strlen($name) > 64) {
3819 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3820 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3822 $name = substr($name, 0, 64);
3826 // Take the first word as first name
3827 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3828 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3829 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3830 return ['first' => $first, 'last' => $last];
3833 // Take the last word as last name
3834 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3835 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3837 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3838 return ['first' => $first, 'last' => $last];
3841 // Take the first 32 characters if there is no space in the first 32 characters
3842 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3843 $first = substr($name, 0, 32);
3844 $last = substr($name, 32);
3845 return ['first' => $first, 'last' => $last];
3848 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3849 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3851 // Check if the last name is longer than 32 characters
3852 if (strlen($last) > 32) {
3853 if (strpos($last, ' ') <= 32) {
3854 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
3856 $last = substr($last, 0, 32);
3860 return ['first' => $first, 'last' => $last];
3864 * Create profile data
3866 * @param int $uid The user id
3868 * @return array The profile data
3869 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3871 private static function createProfileData(int $uid): array
3873 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
3875 if (!DBA::isResult($profile)) {
3879 $split_name = self::splitName($profile['name']);
3882 'author' => $profile['addr'],
3883 'first_name' => $split_name['first'],
3884 'last_name' => $split_name['last'],
3885 'image_url' => DI::baseUrl() . '/photo/custom/300/' . $profile['uid'] . '.jpg',
3886 'image_url_medium' => DI::baseUrl() . '/photo/custom/100/' . $profile['uid'] . '.jpg',
3887 'image_url_small' => DI::baseUrl() . '/photo/custom/50/' . $profile['uid'] . '.jpg',
3888 'searchable' => ($profile['net-publish'] ? 'true' : 'false'),
3892 'tag_string' => null,
3896 if ($data['searchable'] === 'true') {
3897 $data['birthday'] = '';
3899 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
3900 [$year, $month, $day] = sscanf($profile['dob'], '%4d-%2d-%2d');
3904 $data['birthday'] = DateTimeFormat::utc($year . '-' . $month . '-' . $day, 'Y-m-d');
3907 $data['about'] = BBCode::toMarkdown($profile['about'] ?? '');
3909 $data['location'] = $profile['location'];
3910 $data['tag_string'] = '';
3912 if ($profile['pub_keywords']) {
3913 $kw = str_replace(',', ' ', $profile['pub_keywords']);
3914 $kw = str_replace(' ', ' ', $kw);
3915 $arr = explode(' ', $kw);
3917 for ($x = 0; $x < 5; $x ++) {
3918 if (!empty($arr[$x])) {
3919 $data['tag_string'] .= '#'. trim($arr[$x]) .' ';
3924 $data['tag_string'] = trim($data['tag_string']);
3931 * Sends profile data
3933 * @param int $uid The user id
3934 * @param array $recipients optional, default empty array
3937 * @throws \Exception
3939 public static function sendProfile(int $uid, array $recipients = [])
3942 Logger::warning('Parameter "uid" is empty');
3946 $owner = User::getOwnerDataById($uid);
3947 if (empty($owner)) {
3948 Logger::warning('Cannot fetch User record', ['uid' => $uid]);
3952 if (empty($recipients)) {
3953 Logger::debug('No recipients provided, fetching for user', ['uid' => $uid]);
3954 $recipients = DBA::selectToArray('contact', [], ['network' => Protocol::DIASPORA, 'uid' => $uid, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
3957 if (empty($recipients)) {
3958 Logger::warning('Cannot fetch recipients', ['uid' => $uid]);
3962 $message = self::createProfileData($uid);
3964 // @todo Split this into single worker jobs
3965 foreach ($recipients as $recipient) {
3966 Logger::info('Send updated profile data for user ' . $uid . ' to contact ' . $recipient['id']);
3967 self::buildAndTransmit($owner, $recipient, 'profile', $message);
3972 * Creates the signature for likes that are created on our system
3974 * @param integer $uid The user of that comment
3975 * @param array $item Item array
3977 * @return array|bool Signed content or false on error
3978 * @throws \Exception
3980 public static function createLikeSignature(int $uid, array $item)
3982 $owner = User::getOwnerDataById($uid);
3983 if (empty($owner)) {
3984 Logger::info('No owner post, so not storing signature', ['uid' => $uid]);
3988 if (!in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3989 Logger::warning('Item is neither a like nor a dislike', ['uid' => $uid, 'item[verb]' => $item['verb']]);;
3993 $message = self::constructLike($item, $owner);
3994 if ($message === false) {
3998 $message['author_signature'] = self::signature($owner, $message);
4004 * Creates the signature for Comments that are created on our system
4006 * @param array $item Item array
4008 * @return array|bool Signed content or false on error
4009 * @throws \Exception
4011 public static function createCommentSignature(array $item)
4014 if (!empty($item['author-link'])) {
4015 $url = $item['author-link'];
4017 $contact = Contact::getById($item['author-id'], ['url']);
4018 if (empty($contact['url'])) {
4019 Logger::warning('Author Contact not found', ['author-id' => $item['author-id']]);
4022 $url = $contact['url'];
4025 $uid = User::getIdForURL($url);
4027 Logger::info('No owner post, so not storing signature', ['url' => $contact['url'] ?? 'No contact loaded']);
4031 $owner = User::getOwnerDataById($uid);
4032 if (empty($owner)) {
4033 Logger::info('No owner post, so not storing signature');
4037 // This is only needed for the automated tests
4038 if (empty($owner['uprvkey'])) {
4042 if (!self::parentSupportDiaspora($item['thr-parent-id'])) {
4043 Logger::info('One of the parents does not support Diaspora. A signature will not be created.', ['uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
4047 $message = self::constructComment($item, $owner);
4048 if ($message === false) {
4052 $message['author_signature'] = self::signature($owner, $message);
4058 * Check if the parent and their parents support Diaspora
4060 * @param integer $parent_id
4062 * @throws InternalServerErrorException
4063 * @throws \ImagickException
4065 private static function parentSupportDiaspora(int $parent_id): bool
4067 $parent_post = Post::selectFirstPost(['gravity', 'signed_text', 'author-link', 'thr-parent-id'], ['uri-id' => $parent_id]);
4068 if (empty($parent_post['thr-parent-id'])) {
4069 Logger::warning('Parent post does not exist.', ['parent-id' => $parent_id]);
4073 if (!self::isSupportedByContactUrl($parent_post['author-link'])) {
4074 Logger::info('Parent author is no Diaspora contact.', ['parent-id' => $parent_id]);
4078 if (($parent_post['gravity'] == Item::GRAVITY_COMMENT) && empty($parent_post['signed_text'])) {
4079 Logger::info('Parent comment has got no Diaspora signature.', ['parent-id' => $parent_id]);
4083 if ($parent_post['gravity'] == Item::GRAVITY_COMMENT) {
4084 return self::parentSupportDiaspora($parent_post['thr-parent-id']);
4090 public static function performReshare(int $UriId, int $uid): int
4092 $owner = User::getOwnerDataById($uid);
4093 $author = Contact::getPublicIdByUserId($uid);
4097 'verb' => Activity::POST,
4098 'contact-id' => $owner['id'],
4099 'author-id' => $author,
4100 'owner-id' => $author,
4102 'quote-uri-id' => $UriId,
4103 'allow_cid' => $owner['allow_cid'] ?? '',
4104 'allow_gid' => $owner['allow_gid']?? '',
4105 'deny_cid' => $owner['deny_cid'] ?? '',
4106 'deny_gid' => $owner['deny_gid'] ?? '',
4109 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
4110 $item['private'] = Item::PRIVATE;
4111 } elseif (DI::pConfig()->get($uid, 'system', 'unlisted')) {
4112 $item['private'] = Item::UNLISTED;
4114 $item['private'] = Item::PUBLIC;
4117 // Don't trigger the addons
4118 $item['api_source'] = false;
4120 return Item::insert($item, true);