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');
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');
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);
831 return DI::dsprContact()->existsByUriId($contact['uri-id'] ?? 0);
835 * Check if posting is allowed for this contact
837 * @param array $importer Array of the importer user
838 * @param array $contact The contact that is checked
839 * @param bool $is_comment Is the check for a comment?
841 * @return bool is the contact allowed to post?
843 private static function postAllow(array $importer, array $contact, bool $is_comment = false): bool
846 * Perhaps we were already sharing with this person. Now they're sharing with us.
847 * That makes us friends.
848 * Normally this should have handled by getting a request - but this could get lost
850 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
851 // It is not removed by now. Possibly the code is needed?
852 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
854 // array('rel' => Contact::FRIEND, 'writable' => true),
855 // array('id' => $contact["id"], 'uid' => $contact["uid"])
858 // $contact["rel"] = Contact::FRIEND;
859 // Logger::notice("defining user ".$contact["nick"]." as friend");
862 // Contact server is blocked
863 if (Network::isUrlBlocked($contact['url'])) {
865 // We don't seem to like that person
866 } elseif ($contact['blocked']) {
867 // Maybe blocked, don't accept.
869 // We are following this person?
870 } elseif (($contact['rel'] == Contact::SHARING) || ($contact['rel'] == Contact::FRIEND)) {
871 // Yes, then it is fine.
873 // Is the message a global user or a comment?
874 } elseif (($importer['uid'] == 0) || $is_comment) {
875 // Messages for the global users and comments are always accepted
883 * Fetches the contact id for a handle and checks if posting is allowed
885 * @param array $importer Array of the importer user
886 * @param WebFingerUri $contact_uri The checked contact
887 * @param bool $is_comment Is the check for a comment?
889 * @return array|bool The contact data or false on error
890 * @throws InternalServerErrorException
891 * @throws \ImagickException
893 private static function allowedContactByHandle(array $importer, WebFingerUri $contact_uri, bool $is_comment = false)
895 $contact = self::contactByHandle($importer['uid'], $contact_uri);
897 Logger::notice('A Contact for handle ' . $contact_uri . ' and user ' . $importer['uid'] . ' was not found');
898 // If a contact isn't found, we accept it anyway if it is a comment
899 if ($is_comment && ($importer['uid'] != 0)) {
900 return self::contactByHandle(0, $contact_uri);
901 } elseif ($is_comment) {
908 if (!self::postAllow($importer, $contact, $is_comment)) {
909 Logger::notice('The handle: ' . $contact_uri . ' is not allowed to post to user ' . $importer['uid']);
916 * Does the message already exists on the system?
918 * @param int $uid The user id
919 * @param string $guid The guid of the message
921 * @return int|bool message id if the message already was stored into the system - or false.
924 private static function messageExists(int $uid, string $guid)
926 $item = Post::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
927 if (DBA::isResult($item)) {
928 Logger::notice('Message ' . $guid . ' already exists for user ' . $uid);
936 * Checks for links to posts in a message
938 * @param array $item The item array
941 private static function fetchGuid(array $item)
943 preg_replace_callback(
944 "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism",
945 function ($match) use ($item) {
946 self::fetchGuidSub($match, $item);
951 preg_replace_callback(
952 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
953 function ($match) use ($item) {
954 self::fetchGuidSub($match, $item);
961 * Checks for relative /people/* links in an item body to match local
962 * contacts or prepends the remote host taken from the author link.
964 * @param string $body The item body to replace links from
965 * @param string $author_link The author link for missing local contact fallback
967 * @return string the replaced string
969 public static function replacePeopleGuid(string $body, string $author_link): string
971 $return = preg_replace_callback(
972 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
973 function ($match) use ($author_link) {
975 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
976 // 1 => '0123456789abcdef'
978 $handle = DI::dsprContact()->getUrlByGuid($match[1]);
981 $return = '@[url=' . $handle . ']' . $match[2] . '[/url]';
983 // No local match, restoring absolute remote URL from author scheme and host
984 $author_url = parse_url($author_link);
985 $return = '[url=' . $author_url['scheme'] . '://' . $author_url['host'] . '/people/' . $match[1] . ']' . $match[2] . '[/url]';
997 * sub function of "fetchGuid" which checks for links in messages
999 * @param array $match array containing a link that has to be checked for a message link
1000 * @param array $item The item array
1002 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1003 * @throws \ImagickException
1005 private static function fetchGuidSub(array $match, array $item)
1007 if (!self::storeByGuid($match[1], $item['author-link'], true)) {
1008 self::storeByGuid($match[1], $item['owner-link'], true);
1013 * Fetches an item with a given guid from a given server
1015 * @param string $guid the message guid
1016 * @param string $server The server address
1017 * @param bool $force Forced fetch
1019 * @return int|bool the message id of the stored message or false
1020 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1021 * @throws \ImagickException
1023 private static function storeByGuid(string $guid, string $server, bool $force)
1025 $serverparts = parse_url($server);
1027 if (empty($serverparts['host']) || empty($serverparts['scheme'])) {
1031 $server = $serverparts['scheme'] . '://' . $serverparts['host'];
1033 Logger::info('Trying to fetch item ' . $guid . ' from ' . $server);
1035 $msg = self::message($guid, $server);
1041 Logger::info('Successfully fetched item ' . $guid . ' from ' . $server);
1043 // Now call the dispatcher
1044 return self::dispatchPublic($msg, $force ? self::FORCED_FETCH : self::FETCHED);
1048 * Fetches a message from a server
1050 * @param string $guid message guid
1051 * @param string $server The url of the server
1052 * @param int $level Endless loop prevention
1055 * 'message' => The message XML
1056 * 'author' => The author handle
1057 * 'key' => The public key of the author
1058 * @throws \Exception
1060 public static function message(string $guid, string $server, int $level = 0)
1066 // This will work for new Diaspora servers and Friendica servers from 3.5
1067 $source_url = $server . '/fetch/post/' . urlencode($guid);
1069 Logger::info('Fetch post from ' . $source_url);
1071 $envelope = DI::httpClient()->fetch($source_url, HttpClientAccept::MAGIC);
1073 Logger::info('Envelope was fetched.');
1074 $x = self::verifyMagicEnvelope($envelope);
1076 Logger::info('Envelope could not be verified.');
1078 Logger::info('Envelope was verified.');
1088 $source_xml = XML::parseString($x);
1090 if (!is_object($source_xml)) {
1094 if ($source_xml->post->reshare) {
1095 // Reshare of a reshare - old Diaspora version
1096 Logger::info('Message is a reshare');
1097 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1098 } elseif ($source_xml->getName() == 'reshare') {
1099 // Reshare of a reshare - new Diaspora version
1100 Logger::info('Message is a new reshare');
1101 return self::message($source_xml->root_guid, $server, ++$level);
1104 $author_handle = '';
1106 // Fetch the author - for the old and the new Diaspora version
1107 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1108 $author_handle = (string)$source_xml->post->status_message->diaspora_handle;
1109 } elseif ($source_xml->author && ($source_xml->getName() == 'status_message')) {
1110 $author_handle = (string)$source_xml->author;
1114 $author = WebFingerUri::fromString($author_handle);
1115 } catch (\InvalidArgumentException $e) {
1116 // If this isn't a "status_message" then quit
1117 Logger::info("Message doesn't seem to be a status message");
1123 'author' => $author->getAddr(),
1124 'key' => self::key($author)
1129 * Fetches an item with a given URL
1131 * @param string $url the message url
1132 * @param int $uid User id
1134 * @return int|bool the message id of the stored message or false
1135 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1136 * @throws \ImagickException
1138 public static function fetchByURL(string $url, int $uid = 0)
1140 // Check for Diaspora (and Friendica) typical paths
1141 if (!preg_match('=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i', $url, $matches)) {
1142 Logger::info('Invalid url', ['url' => $url]);
1146 $guid = urldecode($matches[2]);
1148 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1149 if (DBA::isResult($item)) {
1150 Logger::info('Found', ['id' => $item['id']]);
1154 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1155 $ret = self::storeByGuid($guid, $matches[1], true);
1156 Logger::info('Result', ['ret' => $ret]);
1158 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1159 if (DBA::isResult($item)) {
1160 Logger::info('Found', ['id' => $item['id']]);
1163 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1169 * Fetches the item record of a given guid
1171 * @param int $uid The user id
1172 * @param string $guid message guid
1173 * @param WebFingerUri $author
1174 * @param array $contact The contact of the item owner
1176 * @return array|bool the item record or false on failure
1177 * @throws \Exception
1179 private static function parentItem(int $uid, string $guid, WebFingerUri $author, array $contact)
1181 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1182 'author-name', 'author-link', 'author-avatar', 'gravity',
1183 'owner-name', 'owner-link', 'owner-avatar'];
1185 $condition = ['uid' => $uid, 'guid' => $guid];
1186 $item = Post::selectFirst($fields, $condition);
1188 if (!DBA::isResult($item)) {
1190 $result = self::storeByGuid($guid, DI::dsprContact()->getByAddr($author)->url, false);
1192 // We don't have an url for items that arrived at the public dispatcher
1193 if (!$result && !empty($contact['url'])) {
1194 $result = self::storeByGuid($guid, $contact['url'], false);
1198 Logger::info('Fetched missing item ' . $guid . ' - result: ' . $result);
1200 $item = Post::selectFirst($fields, $condition);
1202 } catch (HTTPException\NotFoundException $e) {
1203 Logger::notice('Unable to retrieve author details', ['author' => $author->getAddr()]);
1207 if (!DBA::isResult($item)) {
1208 Logger::notice('Parent item not found: parent: ' . $guid . ' - user: ' . $uid);
1211 Logger::notice('Parent item found: parent: ' . $guid . ' - user: ' . $uid);
1217 * returns contact details for the given user
1219 * @param array $def_contact The default details if the contact isn't found
1220 * @param string $contact_url The url of the contact
1221 * @param int $uid The user id
1224 * 'cid' => contact id
1225 * 'network' => network type
1226 * @throws \Exception
1228 private static function authorContactByUrl(array $def_contact, string $contact_url, int $uid): array
1230 $condition = ['nurl' => Strings::normaliseLink($contact_url), 'uid' => $uid];
1231 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1232 if (DBA::isResult($contact)) {
1233 $cid = $contact['id'];
1234 $network = $contact['network'];
1236 $cid = $def_contact['id'];
1237 $network = Protocol::DIASPORA;
1242 'network' => $network
1247 * Is the profile a hubzilla profile?
1249 * @param string $url The profile link
1251 * @return bool is it a hubzilla server?
1253 private static function isHubzilla(string $url): bool
1255 return strstr($url, '/channel/');
1259 * Generate a post link with a given handle and message guid
1261 * @param string $addr The user handle
1262 * @param string $guid message guid
1263 * @param string $parent_guid optional parent guid
1265 * @return string the post link
1266 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1267 * @throws \ImagickException
1269 private static function plink(string $addr, string $guid, string $parent_guid = ''): string
1271 $contact = Contact::getByURL($addr);
1272 if (empty($contact)) {
1273 Logger::info('No contact data for address', ['addr' => $addr]);
1277 if (empty($contact['baseurl'])) {
1278 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1279 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1283 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1284 if (!empty($gserver['platform'])) {
1285 $platform = strtolower($gserver['platform']);
1286 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1289 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1290 if (self::isHubzilla($contact['url'])) {
1291 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1292 $platform = 'hubzilla';
1293 } elseif ($contact['network'] == Protocol::DFRN) {
1294 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1295 $platform = 'friendica';
1299 if ($platform == 'friendica') {
1300 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1303 if ($platform == 'hubzilla') {
1304 return $contact['baseurl'] . '/item/' . $guid;
1307 if ($platform == 'socialhome') {
1308 return $contact['baseurl'] . '/content/' . $guid;
1311 if ($platform != 'diaspora') {
1312 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1316 if ($parent_guid != '') {
1317 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1319 return $contact['baseurl'] . '/posts/' . $guid;
1324 * Receives account migration
1326 * @param array $importer Array of the importer user
1327 * @param SimpleXMLElement $data The message object
1329 * @return bool Success
1330 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1331 * @throws \ImagickException
1333 private static function receiveAccountMigration(array $importer, SimpleXMLElement $data): bool
1336 $old_author = WebFingerUri::fromString(XML::unescape($data->author));
1337 $new_author = WebFingerUri::fromString(XML::unescape($data->profile->author));
1338 } catch (\Throwable $e) {
1339 Logger::notice('Cannot find handles for sender and user', ['data' => $data]);
1343 $signature = XML::unescape($data->signature);
1345 $contact = self::contactByHandle($importer['uid'], $old_author);
1347 Logger::notice('Cannot find contact for sender: ' . $old_author . ' and user ' . $importer['uid']);
1351 Logger::notice('Got migration for ' . $old_author . ', to ' . $new_author . ' with user ' . $importer['uid']);
1354 $signed_text = 'AccountMigration:' . $old_author . ':' . $new_author;
1355 $key = self::key($old_author);
1356 if (!Crypto::rsaVerify($signed_text, $signature, $key, 'sha256')) {
1357 Logger::notice('No valid signature for migration.');
1361 // Update the profile
1362 self::receiveProfile($importer, $data->profile);
1364 // change the technical stuff in contact
1365 $data = Probe::uri($new_author);
1366 if ($data['network'] == Protocol::PHANTOM) {
1367 Logger::notice("Account for " . $new_author . " couldn't be probed.");
1372 'url' => $data['url'],
1373 'nurl' => Strings::normaliseLink($data['url']),
1374 'name' => $data['name'],
1375 'nick' => $data['nick'],
1376 'addr' => $data['addr'],
1377 'batch' => $data['batch'],
1378 'notify' => $data['notify'],
1379 'poll' => $data['poll'],
1380 'network' => $data['network'],
1383 Contact::update($fields, ['addr' => $old_author->getAddr()]);
1385 Logger::notice('Contacts are updated.');
1391 * Processes an account deletion
1393 * @param SimpleXMLElement $data The message object
1395 * @return bool Success
1396 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1398 private static function receiveAccountDeletion(SimpleXMLElement $data): bool
1400 $author_handle = XML::unescape($data->author);
1402 $contacts = DBA::select('contact', ['id'], ['addr' => $author_handle]);
1403 while ($contact = DBA::fetch($contacts)) {
1404 Contact::remove($contact['id']);
1406 DBA::close($contacts);
1408 Logger::notice('Removed contacts for ' . $author_handle);
1414 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1416 * @param string $guid Message guid
1417 * @param WebFingerUri|null $person_uri Optional person to derive the base URL from
1419 * @return string The constructed uri or the one from our database or empty string
1420 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1421 * @throws \ImagickException
1423 private static function getUriFromGuid(string $guid, WebFingerUri $person_uri = null): string
1425 $item = Post::selectFirst(['uri'], ['guid' => $guid]);
1427 return $item['uri'];
1428 } elseif ($person_uri) {
1430 return DI::dsprContact()->selectOneByAddr($person_uri)->baseurl . '/objects/' . $guid;
1431 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
1440 * Store the mentions in the tag table
1442 * @param integer $uriid
1443 * @param string $text
1445 private static function storeMentions(int $uriid, string $text)
1447 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1448 if (empty($matches)) {
1453 * Matching values for the preg match
1454 * [1] = mention type (@ or !)
1455 * [2] = name (optional)
1459 foreach ($matches as $match) {
1460 if (empty($match)) {
1465 $contact = DI::dsprContact()->getByUrl(new Uri($match[3]));
1466 Tag::storeByHash($uriid, $match[1], $contact->name ?: $contact->nick, $contact->url);
1467 } catch (\Throwable $e) {
1474 * Processes an incoming comment
1476 * @param array $importer Array of the importer user
1477 * @param WebFingerUri $sender The sender of the message
1478 * @param SimpleXMLElement $data The message object
1479 * @param string $xml The original XML of the message
1480 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1482 * @return bool The message id of the generated comment or "false" if there was an error
1483 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1484 * @throws \ImagickException
1486 private static function receiveComment(array $importer, WebFingerUri $sender, SimpleXMLElement $data, string $xml, int $direction): bool
1488 $author = WebFingerUri::fromString(XML::unescape($data->author));
1489 $guid = XML::unescape($data->guid);
1490 $parent_guid = XML::unescape($data->parent_guid);
1491 $text = XML::unescape($data->text);
1493 if (isset($data->created_at)) {
1494 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1496 $created_at = DateTimeFormat::utcNow();
1499 if (isset($data->thread_parent_guid)) {
1500 $thread_parent_guid = XML::unescape($data->thread_parent_guid);
1501 $thr_parent = self::getUriFromGuid($thread_parent_guid);
1506 $contact = self::allowedContactByHandle($importer, $sender, true);
1511 if (!empty($contact['gsid'])) {
1512 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1515 $message_id = self::messageExists($importer['uid'], $guid);
1520 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1521 if (!$toplevel_parent_item) {
1526 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
1527 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
1528 Logger::notice('Unable to find author details', ['author' => $author->getAddr()]);
1532 // Fetch the contact id - if we know this contact
1533 $author_contact = self::authorContactByUrl($contact, $author_url, $importer['uid']);
1537 $datarray['uid'] = $importer['uid'];
1538 $datarray['contact-id'] = $author_contact['cid'];
1539 $datarray['network'] = $author_contact['network'];
1541 $datarray['author-link'] = $author_url;
1542 $datarray['author-id'] = Contact::getIdForURL($author_url);
1544 $datarray['owner-link'] = $contact['url'];
1545 $datarray['owner-id'] = Contact::getIdForURL($contact['url']);
1547 // Will be overwritten for sharing accounts in Item::insert
1548 $datarray = self::setDirection($datarray, $direction);
1550 $datarray['guid'] = $guid;
1551 $datarray['uri'] = self::getUriFromGuid($guid, $author);
1552 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1554 $datarray['verb'] = Activity::POST;
1555 $datarray['gravity'] = Item::GRAVITY_COMMENT;
1557 $datarray['thr-parent'] = $thr_parent ?: $toplevel_parent_item['uri'];
1559 $datarray['object-type'] = Activity\ObjectType::COMMENT;
1560 $datarray['post-type'] = Item::PT_NOTE;
1562 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1563 $datarray['source'] = $xml;
1565 $datarray = self::setDirection($datarray, $direction);
1567 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
1569 $datarray['plink'] = self::plink($author, $guid, $toplevel_parent_item['guid']);
1570 $body = Markdown::toBBCode($text);
1572 $datarray['body'] = self::replacePeopleGuid($body, $author_url);
1574 self::storeMentions($datarray['uri-id'], $text);
1575 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
1577 self::fetchGuid($datarray);
1579 // If we are the origin of the parent we store the original data.
1580 // We notify our followers during the item storage.
1581 if ($toplevel_parent_item['origin']) {
1582 $datarray['diaspora_signed_text'] = json_encode($data);
1585 if (Item::isTooOld($datarray)) {
1586 Logger::info('Comment is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1590 $message_id = Item::insert($datarray);
1592 if ($message_id <= 0) {
1597 Logger::info('Stored comment ' . $datarray['guid'] . ' with message id ' . $message_id);
1598 if ($datarray['uid'] == 0) {
1599 Item::distribute($message_id, json_encode($data));
1607 * processes and stores private messages
1609 * @param array $importer Array of the importer user
1610 * @param array $contact The contact of the message
1611 * @param SimpleXMLElement $data The message object
1612 * @param array $msg Array of the processed message, author handle and key
1613 * @param object $mesg The private message
1614 * @param array $conversation The conversation record to which this message belongs
1616 * @return bool "true" if it was successful
1617 * @throws \Exception
1618 * @todo Find type-hint for $mesg and update documentation
1620 private static function receiveConversationMessage(array $importer, array $contact, SimpleXMLElement $data, array $msg, $mesg, array $conversation): bool
1622 $author_handle = XML::unescape($data->author);
1623 $guid = XML::unescape($data->guid);
1624 $subject = XML::unescape($data->subject);
1626 // "diaspora_handle" is the element name from the old version
1627 // "author" is the element name from the new version
1628 if ($mesg->author) {
1629 $msg_author_handle = XML::unescape($mesg->author);
1630 } elseif ($mesg->diaspora_handle) {
1631 $msg_author_handle = XML::unescape($mesg->diaspora_handle);
1637 $msg_author_uri = WebFingerUri::fromString($msg_author_handle);
1638 } catch (\InvalidArgumentException $e) {
1642 $msg_guid = XML::unescape($mesg->guid);
1643 $msg_conversation_guid = XML::unescape($mesg->conversation_guid);
1644 $msg_text = XML::unescape($mesg->text);
1645 $msg_created_at = DateTimeFormat::utc(XML::unescape($mesg->created_at));
1647 if ($msg_conversation_guid != $guid) {
1648 Logger::notice('Message conversation guid does not belong to the current conversation.', ['guid' => $guid]);
1652 $msg_author = DI::dsprContact()->getByAddr($msg_author_uri);
1654 return Mail::insert([
1655 'uid' => $importer['uid'],
1656 'guid' => $msg_guid,
1657 'convid' => $conversation['id'],
1658 'from-name' => $msg_author->name,
1659 'from-photo' => (string)$msg_author->photo,
1660 'from-url' => (string)$msg_author->url,
1661 'contact-id' => $contact['id'],
1662 'title' => $subject,
1663 'body' => Markdown::toBBCode($msg_text),
1664 'uri' => $msg_author_handle . ':' . $msg_guid,
1665 'parent-uri' => $author_handle . ':' . $guid,
1666 'created' => $msg_created_at
1671 * Processes new private messages (answers to private messages are processed elsewhere)
1673 * @param array $importer Array of the importer user
1674 * @param array $msg Array of the processed message, author handle and key
1675 * @param SimpleXMLElement $data The message object
1677 * @return bool Success
1678 * @throws \Exception
1680 private static function receiveConversation(array $importer, array $msg, SimpleXMLElement $data)
1682 $author_handle = XML::unescape($data->author);
1683 $guid = XML::unescape($data->guid);
1684 $subject = XML::unescape($data->subject);
1685 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1686 $participants = XML::unescape($data->participants);
1688 $messages = $data->message;
1690 if (!count($messages)) {
1691 Logger::notice('Empty conversation');
1695 $contact = self::allowedContactByHandle($importer, WebFingerUri::fromString($msg['author']), true);
1700 if (!empty($contact['gsid'])) {
1701 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1704 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1705 if (!DBA::isResult($conversation)) {
1706 $r = DBA::insert('conv', [
1707 'uid' => $importer['uid'],
1709 'creator' => $author_handle,
1710 'created' => $created_at,
1711 'updated' => DateTimeFormat::utcNow(),
1712 'subject' => $subject,
1713 'recips' => $participants
1717 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
1720 if (!$conversation) {
1721 Logger::warning('Unable to create conversation.');
1725 foreach ($messages as $mesg) {
1726 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1733 * Processes "like" messages
1735 * @param array $importer Array of the importer user
1736 * @param WebFingerUri $sender The sender of the message
1737 * @param SimpleXMLElement $data The message object
1738 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1740 * @return bool Success or failure
1741 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1742 * @throws \ImagickException
1744 private static function receiveLike(array $importer, WebFingerUri $sender, SimpleXMLElement $data, int $direction): bool
1746 $author = WebFingerUri::fromString(XML::unescape($data->author));
1747 $guid = XML::unescape($data->guid);
1748 $parent_guid = XML::unescape($data->parent_guid);
1749 $parent_type = XML::unescape($data->parent_type);
1750 $positive = XML::unescape($data->positive);
1752 // likes on comments aren't supported by Diaspora - only on posts
1753 // But maybe this will be supported in the future, so we will accept it.
1754 if (!in_array($parent_type, ['Post', 'Comment'])) {
1758 $contact = self::allowedContactByHandle($importer, $sender, true);
1763 if (!empty($contact['gsid'])) {
1764 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1767 $message_id = self::messageExists($importer['uid'], $guid);
1772 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1773 if (!$toplevel_parent_item) {
1778 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
1779 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
1780 Logger::notice('Unable to find author details', ['author' => $author->getAddr()]);
1784 // Fetch the contact id - if we know this contact
1785 $author_contact = self::authorContactByUrl($contact, $author_url, $importer['uid']);
1787 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1788 // We would accept this anyhow.
1789 if ($positive == 'true') {
1790 $verb = Activity::LIKE;
1792 $verb = Activity::DISLIKE;
1797 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1799 $datarray['uid'] = $importer['uid'];
1800 $datarray['contact-id'] = $author_contact['cid'];
1801 $datarray['network'] = $author_contact['network'];
1803 $datarray = self::setDirection($datarray, $direction);
1805 $datarray['owner-link'] = $datarray['author-link'] = $author_url;
1806 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($author_url);
1808 $datarray['guid'] = $guid;
1809 $datarray['uri'] = self::getUriFromGuid($guid, $author);
1811 $datarray['verb'] = $verb;
1812 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
1813 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1815 $datarray['object-type'] = Activity\ObjectType::NOTE;
1817 $datarray['body'] = $verb;
1819 // Diaspora doesn't provide a date for likes
1820 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
1822 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1823 if ($toplevel_parent_item['gravity'] != Item::GRAVITY_PARENT) {
1824 $toplevel = Post::selectFirst(['origin'], ['id' => $toplevel_parent_item['parent']]);
1825 $origin = $toplevel['origin'];
1827 $origin = $toplevel_parent_item['origin'];
1830 // If we are the origin of the parent we store the original data.
1831 // We notify our followers during the item storage.
1833 $datarray['diaspora_signed_text'] = json_encode($data);
1836 if (Item::isTooOld($datarray)) {
1837 Logger::info('Like is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1841 $message_id = Item::insert($datarray);
1843 if ($message_id <= 0) {
1848 Logger::info('Stored like ' . $datarray['guid'] . ' with message id ' . $message_id);
1849 if ($datarray['uid'] == 0) {
1850 Item::distribute($message_id, json_encode($data));
1858 * Processes private messages
1860 * @param array $importer Array of the importer user
1861 * @param SimpleXMLElement $data The message object
1863 * @return bool Success?
1864 * @throws \Exception
1866 private static function receiveMessage(array $importer, SimpleXMLElement $data): bool
1868 $author_uri = WebFingerUri::fromString(XML::unescape($data->author));
1869 $guid = XML::unescape($data->guid);
1870 $conversation_guid = XML::unescape($data->conversation_guid);
1871 $text = XML::unescape($data->text);
1872 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1874 $contact = self::allowedContactByHandle($importer, $author_uri, true);
1879 if (!empty($contact['gsid'])) {
1880 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1883 $condition = ['uid' => $importer['uid'], 'guid' => $conversation_guid];
1884 $conversation = DBA::selectFirst('conv', [], $condition);
1885 if (!DBA::isResult($conversation)) {
1886 Logger::notice('Conversation not available.');
1891 $author = DI::dsprContact()->getByAddr($author_uri);
1892 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
1893 Logger::notice('Unable to find author details', ['author' => $author_uri->getAddr()]);
1897 $body = Markdown::toBBCode($text);
1899 $body = self::replacePeopleGuid($body, $author->url);
1901 return Mail::insert([
1902 'uid' => $importer['uid'],
1904 'convid' => $conversation['id'],
1905 'from-name' => $author->name,
1906 'from-photo' => (string)$author->photo,
1907 'from-url' => (string)$author->url,
1908 'contact-id' => $contact['id'],
1909 'title' => $conversation['subject'],
1912 'uri' => $author_uri . ':' . $guid,
1913 'parent-uri' => $author_uri . ':' . $conversation['guid'],
1914 'created' => $created_at
1919 * Processes participations - unsupported by now
1921 * @param array $importer Array of the importer user
1922 * @param SimpleXMLElement $data The message object
1923 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1925 * @return bool success
1926 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1927 * @throws \ImagickException
1929 private static function receiveParticipation(array $importer, SimpleXMLElement $data, int $direction): bool
1931 $author = WebFingerUri::fromString(strtolower(XML::unescape($data->author)));
1932 $guid = XML::unescape($data->guid);
1933 $parent_guid = XML::unescape($data->parent_guid);
1935 $contact = self::allowedContactByHandle($importer, $author, true);
1940 if (!empty($contact['gsid'])) {
1941 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1944 if (self::messageExists($importer['uid'], $guid)) {
1948 $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
1949 if (!$toplevel_parent_item) {
1953 if (!$toplevel_parent_item['origin']) {
1954 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1957 if (!in_array($toplevel_parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
1958 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1963 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
1964 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
1965 Logger::notice('unable to find author details', ['author' => $author->getAddr()]);
1969 $author_contact = self::authorContactByUrl($contact, $author_url, $importer['uid']);
1971 // Store participation
1974 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
1976 $datarray['uid'] = $importer['uid'];
1977 $datarray['contact-id'] = $author_contact['cid'];
1978 $datarray['network'] = $author_contact['network'];
1980 $datarray = self::setDirection($datarray, $direction);
1982 $datarray['owner-link'] = $datarray['author-link'] = $author_url;
1983 $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($author_url);
1985 $datarray['guid'] = $guid;
1986 $datarray['uri'] = self::getUriFromGuid($guid, $author);
1988 $datarray['verb'] = Activity::FOLLOW;
1989 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
1990 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1992 $datarray['object-type'] = Activity\ObjectType::NOTE;
1994 $datarray['body'] = Activity::FOLLOW;
1996 // Diaspora doesn't provide a date for a participation
1997 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
1999 if (Item::isTooOld($datarray)) {
2000 Logger::info('Participation is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2004 $message_id = Item::insert($datarray);
2006 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
2008 // Send all existing comments and likes to the requesting server
2009 $comments = Post::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb', 'gravity'],
2010 ['parent' => $toplevel_parent_item['id'], 'gravity' => [Item::GRAVITY_COMMENT, Item::GRAVITY_ACTIVITY]]);
2011 while ($comment = Post::fetch($comments)) {
2012 if (($comment['gravity'] == Item::GRAVITY_ACTIVITY) && !in_array($comment['verb'], [Activity::LIKE, Activity::DISLIKE])) {
2013 Logger::info('Unsupported activities are not relayed', ['item' => $comment['id'], 'verb' => $comment['verb']]);
2017 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
2018 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2022 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
2023 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2027 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact['cid']]);
2028 if (Worker::add(Worker::PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['uri-id'], $author_contact['cid'], $datarray['uid'])) {
2029 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2032 DBA::close($comments);
2038 * Processes photos - unneeded
2040 * @param array $importer Array of the importer user
2041 * @param SimpleXMLElement $data The message object
2043 * @return bool always true
2045 private static function receivePhoto(array $importer, $data)
2047 // There doesn't seem to be a reason for this function,
2048 // since the photo data is transmitted in the status message as well
2053 * Processes poll participations - unssupported
2055 * @param array $importer Array of the importer user
2056 * @param object $data The message object
2058 * @return bool always true
2060 private static function receivePollParticipation(array $importer, $data)
2062 // We don't support polls by now
2067 * Processes incoming profile updates
2069 * @param array $importer Array of the importer user
2070 * @param SimpleXMLElement $data The message object
2072 * @return bool Success
2073 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2074 * @throws \ImagickException
2076 private static function receiveProfile(array $importer, SimpleXMLElement $data): bool
2078 $author = WebFingerUri::fromString(strtolower(XML::unescape($data->author)));
2080 $contact = self::contactByHandle($importer['uid'], $author);
2085 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? ' ' . XML::unescape($data->last_name) : '');
2086 $image_url = XML::unescape($data->image_url);
2087 $birthday = XML::unescape($data->birthday);
2088 $about = Markdown::toBBCode(XML::unescape($data->bio));
2089 $location = Markdown::toBBCode(XML::unescape($data->location));
2090 $searchable = (XML::unescape($data->searchable) == 'true');
2091 $nsfw = (XML::unescape($data->nsfw) == 'true');
2092 $tags = XML::unescape($data->tag_string);
2094 $tags = explode('#', $tags);
2097 foreach ($tags as $tag) {
2098 $tag = trim(strtolower($tag));
2104 $keywords = implode(', ', $keywords);
2107 $name = $author->getUser();
2110 if (preg_match('|^https?://|', $image_url) === 0) {
2111 // @TODO No HTTPS here?
2112 $image_url = 'http://' . $author->getFullHost() . $image_url;
2115 Contact::updateAvatar($contact['id'], $image_url);
2117 // Generic birthday. We don't know the timezone. The year is irrelevant.
2119 $birthday = str_replace('1000', '1901', $birthday);
2121 if ($birthday != '') {
2122 $birthday = DateTimeFormat::utc($birthday, 'Y-m-d');
2125 // this is to prevent multiple birthday notifications in a single year
2126 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2128 if (substr($birthday, 5) === substr($contact['bd'], 5)) {
2129 $birthday = $contact['bd'];
2132 $fields = ['name' => $name, 'location' => $location,
2133 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2134 'addr' => $author->getAddr(), 'nick' => $author->getUser(), 'keywords' => $keywords,
2135 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2137 if (!empty($birthday)) {
2138 $fields['bd'] = $birthday;
2141 Contact::update($fields, ['id' => $contact['id']]);
2143 Logger::info('Profile of contact ' . $contact['id'] . ' stored for user ' . $importer['uid']);
2149 * Processes incoming friend requests
2151 * @param array $importer Array of the importer user
2152 * @param array $contact The contact that send the request
2154 * @throws \Exception
2156 private static function receiveRequestMakeFriend(array $importer, array $contact)
2158 if ($contact['rel'] == Contact::SHARING) {
2160 ['rel' => Contact::FRIEND, 'writable' => true],
2161 ['id' => $contact['id'], 'uid' => $importer['uid']]
2167 * Processes incoming sharing notification
2169 * @param array $importer Array of the importer user
2170 * @param SimpleXMLElement $data The message object
2172 * @return bool Success
2173 * @throws \Exception
2175 private static function receiveContactRequest(array $importer, SimpleXMLElement $data): bool
2177 $author_handle = XML::unescape($data->author);
2178 $recipient = XML::unescape($data->recipient);
2180 if (!$author_handle || !$recipient) {
2184 $author = WebFingerUri::fromString($author_handle);
2186 // the current protocol version doesn't know these fields
2187 // That means that we will assume their existance
2188 if (isset($data->following)) {
2189 $following = (XML::unescape($data->following) == 'true');
2194 if (isset($data->sharing)) {
2195 $sharing = (XML::unescape($data->sharing) == 'true');
2200 $contact = self::contactByHandle($importer['uid'], $author);
2202 // perhaps we were already sharing with this person. Now they're sharing with us.
2203 // That makes us friends.
2206 Logger::info('Author ' . $author . ' (Contact ' . $contact['id'] . ') wants to follow us.');
2207 self::receiveRequestMakeFriend($importer, $contact);
2209 // refetch the contact array
2210 $contact = self::contactByHandle($importer['uid'], $author);
2212 // If we are now friends, we are sending a share message.
2213 // Normally we needn't to do so, but the first message could have been vanished.
2214 if (in_array($contact['rel'], [Contact::FRIEND])) {
2215 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2216 if (DBA::isResult($user)) {
2217 Logger::info('Sending share message to author ' . $author . ' - Contact: ' . $contact['id'] . ' - User: ' . $importer['uid']);
2218 self::sendShare($user, $contact);
2223 Logger::info("Author " . $author . " doesn't want to follow us anymore.");
2224 Contact::removeFollower($contact);
2229 if (!$following && $sharing && in_array($importer['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2230 Logger::info("Author " . $author . " wants to share with us - but doesn't want to listen. Request is ignored.");
2232 } elseif (!$following && !$sharing) {
2233 Logger::info("Author " . $author . " doesn't want anything - and we don't know the author. Request is ignored.");
2235 } elseif (!$following && $sharing) {
2236 Logger::info("Author " . $author . " wants to share with us.");
2237 } elseif ($following && $sharing) {
2238 Logger::info("Author " . $author . " wants to have a bidirectional conection.");
2239 } elseif ($following && !$sharing) {
2240 Logger::info("Author " . $author . " wants to listen to us.");
2244 $author_url = (string)DI::dsprContact()->getByAddr($author)->url;
2245 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
2246 Logger::notice('Cannot resolve diaspora handle for recipient', ['author' => $author->getAddr(), 'recipient' => $recipient]);
2250 $cid = Contact::getIdForURL($author_url, $importer['uid']);
2252 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2258 'author-id' => Contact::getIdForURL($author_url),
2259 'author-link' => $author_url
2262 $result = Contact::addRelationship($importer, $contact, $item, false);
2263 if ($result === true) {
2264 $contact_record = self::contactByHandle($importer['uid'], $author);
2265 if (!$contact_record) {
2266 Logger::info('unable to locate newly created contact record.');
2270 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2271 if (DBA::isResult($user)) {
2272 self::sendShare($user, $contact_record);
2274 // Send the profile data, maybe it weren't transmitted before
2275 self::sendProfile($importer['uid'], [$contact_record]);
2283 * Stores a reshare activity
2285 * @param array $item Array of reshare post
2286 * @param integer $parent_message_id Id of the parent post
2287 * @param string $guid GUID string of reshare action
2288 * @param WebFingerUri $author Author handle
2289 * @return false|void
2290 * @throws InternalServerErrorException
2291 * @throws \ImagickException
2293 private static function addReshareActivity(array $item, int $parent_message_id, string $guid, WebFingerUri $author)
2295 $parent = Post::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2299 $datarray['uid'] = $item['uid'];
2300 $datarray['contact-id'] = $item['contact-id'];
2301 $datarray['network'] = $item['network'];
2303 $datarray['author-link'] = $item['author-link'];
2304 $datarray['author-id'] = $item['author-id'];
2306 $datarray['owner-link'] = $datarray['author-link'];
2307 $datarray['owner-id'] = $datarray['author-id'];
2309 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2310 $datarray['uri'] = self::getUriFromGuid($datarray['guid'], $author);
2311 $datarray['thr-parent'] = $parent['uri'];
2313 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2314 $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
2315 $datarray['object-type'] = Activity\ObjectType::NOTE;
2317 $datarray['protocol'] = $item['protocol'];
2318 $datarray['source'] = $item['source'];
2319 $datarray['direction'] = $item['direction'];
2320 $datarray['post-reason'] = $item['post-reason'];
2322 $datarray['plink'] = self::plink($author, $datarray['guid']);
2323 $datarray['private'] = $item['private'];
2324 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2326 if (Item::isTooOld($datarray)) {
2327 Logger::info('Reshare activity is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2331 $message_id = Item::insert($datarray);
2334 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2335 if ($datarray['uid'] == 0) {
2336 Item::distribute($message_id);
2342 * Processes a reshare message
2344 * @param array $importer Array of the importer user
2345 * @param SimpleXMLElement $data The message object
2346 * @param string $xml The original XML of the message
2347 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2349 * @return bool Success or failure
2350 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2351 * @throws \ImagickException
2353 private static function receiveReshare(array $importer, SimpleXMLElement $data, string $xml, int $direction): bool
2355 $author = WebFingerUri::fromString(XML::unescape($data->author));
2356 $guid = XML::unescape($data->guid);
2357 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2359 $root_author = WebFingerUri::fromString(XML::unescape($data->root_author));
2360 } catch (\InvalidArgumentException $e) {
2364 $root_guid = XML::unescape($data->root_guid);
2365 /// @todo handle unprocessed property "provider_display_name"
2366 $public = XML::unescape($data->public);
2368 $contact = self::allowedContactByHandle($importer, $author);
2373 if (!empty($contact['gsid'])) {
2374 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2377 $message_id = self::messageExists($importer['uid'], $guid);
2383 $original_person = DI::dsprContact()->getByAddr($root_author);
2384 } catch (HTTPException\NotFoundException $e) {
2390 $datarray['uid'] = $importer['uid'];
2391 $datarray['contact-id'] = $contact['id'];
2392 $datarray['network'] = Protocol::DIASPORA;
2394 $datarray['author-link'] = $contact['url'];
2395 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2397 $datarray['owner-link'] = $datarray['author-link'];
2398 $datarray['owner-id'] = $datarray['author-id'];
2400 $datarray['guid'] = $guid;
2401 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($guid, $author);
2402 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2404 $datarray['verb'] = Activity::POST;
2405 $datarray['gravity'] = Item::GRAVITY_PARENT;
2407 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2408 $datarray['source'] = $xml;
2410 $datarray = self::setDirection($datarray, $direction);
2412 $datarray['quote-uri-id'] = self::getQuoteUriId($root_guid, $importer['uid'], $original_person->url);
2413 if (empty($datarray['quote-uri-id'])) {
2417 $datarray['body'] = '';
2418 $datarray['plink'] = self::plink($author, $guid);
2419 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2420 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2422 self::fetchGuid($datarray);
2424 if (Item::isTooOld($datarray)) {
2425 Logger::info('Reshare is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2429 $message_id = Item::insert($datarray);
2431 self::sendParticipation($contact, $datarray);
2433 $root_message_id = self::messageExists($importer['uid'], $root_guid);
2434 if ($root_message_id) {
2435 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2439 Logger::info('Stored reshare ' . $datarray['guid'] . ' with message id ' . $message_id);
2440 if ($datarray['uid'] == 0) {
2441 Item::distribute($message_id);
2449 private static function getQuoteUriId(string $guid, int $uid, string $host): int
2451 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2453 if (!DBA::isResult($shared_item) && !empty($host) && Diaspora::storeByGuid($guid, $host, true)) {
2454 Logger::debug('Fetched post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2455 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2456 } elseif (DBA::isResult($shared_item)) {
2457 Logger::debug('Found existing post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2460 if (!DBA::isResult($shared_item)) {
2461 Logger::notice('Post does not exist.', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
2465 return $shared_item['uri-id'];
2469 * Processes retractions
2471 * @param array $importer Array of the importer user
2472 * @param array $contact The contact of the item owner
2473 * @param SimpleXMLElement $data The message object
2475 * @return bool success
2476 * @throws \Exception
2478 private static function itemRetraction(array $importer, array $contact, SimpleXMLElement $data): bool
2480 $author_uri = WebFingerUri::fromString(XML::unescape($data->author));
2481 $target_guid = XML::unescape($data->target_guid);
2482 $target_type = XML::unescape($data->target_type);
2485 $author = DI::dsprContact()->getByAddr($author_uri);
2486 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
2487 Logger::notice('Unable to find details for author', ['author' => $author_uri->getAddr()]);
2491 $contact_url = $contact['url'] ?? '' ?: (string)$author->url;
2493 // Fetch items that are about to be deleted
2494 $fields = ['uid', 'id', 'parent', 'author-link', 'uri-id'];
2496 // When we receive a public retraction, we delete every item that we find.
2497 if ($importer['uid'] == 0) {
2498 $condition = ['guid' => $target_guid, 'deleted' => false];
2500 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2503 $r = Post::select($fields, $condition);
2504 if (!DBA::isResult($r)) {
2505 Logger::notice('Target guid ' . $target_guid . ' was not found on this system for user ' . $importer['uid'] . '.');
2509 while ($item = Post::fetch($r)) {
2510 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2511 Logger::info("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.");
2515 // Fetch the parent item
2516 $parent = Post::selectFirst(['author-link'], ['id' => $item['parent']]);
2518 // Only delete it if the parent author really fits
2519 if (!Strings::compareLink($parent['author-link'], $contact_url) && !Strings::compareLink($item['author-link'], $contact_url)) {
2520 Logger::info("Thread author " . $parent['author-link'] . " and item author " . $item['author-link'] . " don't fit to expected contact " . $contact_url);
2524 Item::markForDeletion(['id' => $item['id']]);
2526 Logger::info('Deleted target ' . $target_guid . ' (' . $item['id'] . ') from user ' . $item['uid'] . ' parent: ' . $item['parent']);
2534 * Receives retraction messages
2536 * @param array $importer Array of the importer user
2537 * @param WebFingerUri $sender The sender of the message
2538 * @param SimpleXMLElement $data The message object
2540 * @return bool Success
2541 * @throws \Exception
2543 private static function receiveRetraction(array $importer, WebFingerUri $sender, SimpleXMLElement $data)
2545 $target_type = XML::unescape($data->target_type);
2547 $contact = self::contactByHandle($importer['uid'], $sender);
2548 if (!$contact && (in_array($target_type, ['Contact', 'Person']))) {
2549 Logger::notice('Cannot find contact for sender: ' . $sender . ' and user ' . $importer['uid']);
2557 Logger::info('Got retraction for ' . $target_type . ', sender ' . $sender . ' and user ' . $importer['uid']);
2559 switch ($target_type) {
2564 case 'StatusMessage':
2565 return self::itemRetraction($importer, $contact, $data);
2567 case 'PollParticipation':
2569 // Currently unsupported
2573 Logger::notice('Unknown target type ' . $target_type);
2580 * Checks if an incoming message is wanted
2582 * @param array $item
2583 * @param string $author
2584 * @param string $body
2585 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2587 * @return boolean Is the message wanted?
2589 private static function isSolicitedMessage(array $item, string $author, string $body, int $direction): bool
2591 $contact = Contact::getByURL($author);
2592 if (DBA::exists('contact', ['`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)', $contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) {
2593 Logger::debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2597 if ($direction == self::FORCED_FETCH) {
2598 Logger::debug('Post is a forced fetch - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2602 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
2603 if (Relay::isSolicitedPost($tags, $body, $contact['id'], $item['uri'], Protocol::DIASPORA)) {
2604 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2612 * Store an attached photo in the post-media table
2615 * @param object $photo
2618 private static function storePhotoAsMedia(int $uriid, $photo)
2620 // @TODO Need to find object type, roland@f.haeder.net
2621 Logger::debug('photo='.get_class($photo));
2623 $data['uri-id'] = $uriid;
2624 $data['type'] = Post\Media::IMAGE;
2625 $data['url'] = XML::unescape($photo->remote_photo_path) . XML::unescape($photo->remote_photo_name);
2626 $data['height'] = (int)XML::unescape($photo->height ?? 0);
2627 $data['width'] = (int)XML::unescape($photo->width ?? 0);
2628 $data['description'] = XML::unescape($photo->text ?? '');
2630 Post\Media::insert($data);
2634 * Set direction and post reason
2636 * @param array $datarray
2637 * @param integer $direction
2641 public static function setDirection(array $datarray, int $direction): array
2643 $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
2645 if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
2646 $datarray['post-reason'] = Item::PR_FETCHED;
2647 } elseif ($datarray['uid'] == 0) {
2648 $datarray['post-reason'] = Item::PR_GLOBAL;
2650 $datarray['post-reason'] = Item::PR_PUSHED;
2657 * Receives status messages
2659 * @param array $importer Array of the importer user
2660 * @param SimpleXMLElement $data The message object
2661 * @param string $xml The original XML of the message
2662 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2664 * @return int|bool The message id of the newly created item or false on error
2665 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2666 * @throws \ImagickException
2668 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, string $xml, int $direction)
2670 $author = WebFingerUri::fromString(XML::unescape($data->author));
2671 $guid = XML::unescape($data->guid);
2672 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2673 $public = XML::unescape($data->public);
2674 $text = XML::unescape($data->text);
2675 $provider_display_name = XML::unescape($data->provider_display_name);
2677 $contact = self::allowedContactByHandle($importer, $author);
2682 if (!empty($contact['gsid'])) {
2683 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2686 $message_id = self::messageExists($importer['uid'], $guid);
2692 if ($data->location) {
2693 foreach ($data->location->children() as $fieldname => $data) {
2694 $address[$fieldname] = XML::unescape($data);
2698 $raw_body = $body = Markdown::toBBCode($text);
2702 $datarray['guid'] = $guid;
2703 $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($guid, $author);
2704 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2706 // Attach embedded pictures to the body
2708 foreach ($data->photo as $photo) {
2709 self::storePhotoAsMedia($datarray['uri-id'], $photo);
2712 $datarray['object-type'] = Activity\ObjectType::IMAGE;
2713 $datarray['post-type'] = Item::PT_IMAGE;
2714 } elseif ($data->poll) {
2715 $datarray['object-type'] = Activity\ObjectType::NOTE;
2716 $datarray['post-type'] = Item::PT_POLL;
2718 $datarray['object-type'] = Activity\ObjectType::NOTE;
2719 $datarray['post-type'] = Item::PT_NOTE;
2722 /// @todo enable support for polls
2723 //if ($data->poll) {
2724 // foreach ($data->poll as $poll)
2729 /// @todo enable support for events
2731 $datarray['uid'] = $importer['uid'];
2732 $datarray['contact-id'] = $contact['id'];
2733 $datarray['network'] = Protocol::DIASPORA;
2735 $datarray['author-link'] = $contact['url'];
2736 $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
2738 $datarray['owner-link'] = $datarray['author-link'];
2739 $datarray['owner-id'] = $datarray['author-id'];
2741 $datarray['verb'] = Activity::POST;
2742 $datarray['gravity'] = Item::GRAVITY_PARENT;
2744 $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
2745 $datarray['source'] = $xml;
2747 $datarray = self::setDirection($datarray, $direction);
2749 $datarray['body'] = self::replacePeopleGuid($body, $contact['url']);
2750 $datarray['raw-body'] = self::replacePeopleGuid($raw_body, $contact['url']);
2752 self::storeMentions($datarray['uri-id'], $text);
2753 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
2755 if (!self::isSolicitedMessage($datarray, $author, $body, $direction)) {
2756 DBA::delete('item-uri', ['uri' => $datarray['uri']]);
2760 if ($provider_display_name != '') {
2761 $datarray['app'] = $provider_display_name;
2764 $datarray['plink'] = self::plink($author, $guid);
2765 $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
2766 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
2768 if (isset($address['address'])) {
2769 $datarray['location'] = $address['address'];
2772 if (isset($address['lat']) && isset($address['lng'])) {
2773 $datarray['coord'] = $address['lat'] . ' ' . $address['lng'];
2776 self::fetchGuid($datarray);
2778 if (Item::isTooOld($datarray)) {
2779 Logger::info('Status is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2783 $message_id = Item::insert($datarray);
2785 self::sendParticipation($contact, $datarray);
2788 Logger::info('Stored item ' . $datarray['guid'] . ' with message id ' . $message_id);
2789 if ($datarray['uid'] == 0) {
2790 Item::distribute($message_id);
2798 /* ************************************************************************************** *
2799 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2800 * ************************************************************************************** */
2803 * returnes the handle of a contact
2805 * @param array $contact contact array
2807 * @return string the handle in the format user@domain.tld
2808 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2810 private static function myHandle(array $contact): string
2812 if (!empty($contact['addr'])) {
2813 return $contact['addr'];
2816 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2817 // So - just in case - we build the the address here.
2818 if ($contact['nickname'] != '') {
2819 $nick = $contact['nickname'];
2821 $nick = $contact['nick'];
2824 return $nick . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
2829 * Creates the data for a private message in the new format
2831 * @param string $msg The message that is to be transmitted
2832 * @param array $user The record of the sender
2833 * @param array $contact Target of the communication
2834 * @param string $prvkey The private key of the sender
2835 * @param string $pubkey The public key of the receiver
2837 * @return string The encrypted data
2838 * @throws \Exception
2840 public static function encodePrivateData(string $msg, array $user, array $contact, string $prvkey, string $pubkey): string
2842 Logger::debug('Message: ' . $msg);
2844 // without a public key nothing will work
2846 Logger::notice('pubkey missing: contact id: ' . $contact['id']);
2850 $aes_key = random_bytes(32);
2851 $b_aes_key = base64_encode($aes_key);
2852 $iv = random_bytes(16);
2853 $b_iv = base64_encode($iv);
2855 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2857 $json = json_encode(['iv' => $b_iv, 'key' => $b_aes_key]);
2859 $encrypted_key_bundle = '';
2860 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
2864 $json_object = json_encode(
2866 'aes_key' => base64_encode($encrypted_key_bundle),
2867 'encrypted_magic_envelope' => base64_encode($ciphertext)
2871 return $json_object;
2875 * Creates the envelope for the "fetch" endpoint and for the new format
2877 * @param string $msg The message that is to be transmitted
2878 * @param array $user The record of the sender
2880 * @return string The envelope
2881 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2883 public static function buildMagicEnvelope(string $msg, array $user): string
2885 $b64url_data = Strings::base64UrlEncode($msg);
2886 $data = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
2888 $key_id = Strings::base64UrlEncode(self::myHandle($user));
2889 $type = 'application/xml';
2890 $encoding = 'base64url';
2891 $alg = 'RSA-SHA256';
2892 $signable_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
2894 // Fallback if the private key wasn't transmitted in the expected field
2895 if ($user['uprvkey'] == '') {
2896 $user['uprvkey'] = $user['prvkey'];
2899 $signature = Crypto::rsaSign($signable_data, $user['uprvkey']);
2900 $sig = Strings::base64UrlEncode($signature);
2905 '@attributes' => ['type' => $type],
2906 'me:encoding' => $encoding,
2909 '@attributes2' => ['key_id' => $key_id]
2913 $namespaces = ['me' => ActivityNamespace::SALMON_ME];
2915 return XML::fromArray($xmldata, $xml, false, $namespaces);
2919 * Create the envelope for a message
2921 * @param string $msg The message that is to be transmitted
2922 * @param array $user The record of the sender
2923 * @param array $contact Target of the communication
2924 * @param string $prvkey The private key of the sender
2925 * @param string $pubkey The public key of the receiver
2926 * @param bool $public Is the message public?
2928 * @return string The message that will be transmitted to other servers
2929 * @throws \Exception
2931 public static function buildMessage(string $msg, array $user, array $contact, string $prvkey, string $pubkey, bool $public = false): string
2933 // The message is put into an envelope with the sender's signature
2934 $envelope = self::buildMagicEnvelope($msg, $user);
2936 // Private messages are put into a second envelope, encrypted with the receivers public key
2938 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
2945 * Creates a signature for a message
2947 * @param array $owner the array of the owner of the message
2948 * @param array $message The message that is to be signed
2950 * @return string The signature
2952 private static function signature(array $owner, array $message): string
2955 unset($sigmsg['author_signature']);
2956 unset($sigmsg['parent_author_signature']);
2958 $signed_text = implode(';', $sigmsg);
2960 return base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
2964 * Transmit a message to a target server
2966 * @param array $owner the array of the item owner
2967 * @param array $contact Target of the communication
2968 * @param string $envelope The message that is to be transmitted
2969 * @param bool $public_batch Is it a public post?
2970 * @param string $guid message guid
2972 * @return int Result of the transmission
2973 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2974 * @throws \ImagickException
2976 private static function transmit(array $owner, array $contact, string $envelope, bool $public_batch, string $guid = ''): int
2978 $enabled = intval(DI::config()->get('system', 'diaspora_enabled'));
2983 $logid = Strings::getRandomHex(4);
2985 // We always try to use the data from the diaspora-contact table.
2986 // This is important for transmitting data to Friendica servers.
2988 $target = DI::dsprContact()->getByAddr(WebFingerUri::fromString($contact['addr']));
2989 $dest_url = $public_batch ? $target->batch : $target->notify;
2990 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
2994 if (empty($dest_url)) {
2995 $dest_url = ($public_batch ? $contact['batch'] : $contact['notify']);
2999 Logger::notice('No URL for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
3003 Logger::notice('transmit: ' . $logid . '-' . $guid . ' ' . $dest_url);
3005 if (!intval(DI::config()->get('system', 'diaspora_test'))) {
3006 $content_type = (($public_batch) ? 'application/magic-envelope+xml' : 'application/json');
3008 $postResult = DI::httpClient()->post($dest_url . '/', $envelope, ['Content-Type' => $content_type]);
3009 $return_code = $postResult->getReturnCode();
3011 Logger::notice('test_mode');
3015 Logger::notice('transmit: ' . $logid . '-' . $guid . ' to ' . $dest_url . ' returns: ' . $return_code);
3017 return $return_code ? $return_code : -1;
3022 * Build the post xml
3024 * @param string $type The message type
3025 * @param array $message The message data
3027 * @return string The post XML
3029 public static function buildPostXml(string $type, array $message): string
3031 $data = [$type => $message];
3033 return XML::fromArray($data, $xml);
3037 * Builds and transmit messages
3039 * @param array $owner the array of the item owner
3040 * @param array $contact Target of the communication
3041 * @param string $type The message type
3042 * @param array $message The message data
3043 * @param bool $public_batch Is it a public post?
3044 * @param string $guid message guid
3046 * @return int Result of the transmission
3047 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3048 * @throws \ImagickException
3050 private static function buildAndTransmit(array $owner, array $contact, string $type, array $message, bool $public_batch = false, string $guid = '')
3052 $msg = self::buildPostXml($type, $message);
3054 // Fallback if the private key wasn't transmitted in the expected field
3055 if (empty($owner['uprvkey'])) {
3056 $owner['uprvkey'] = $owner['prvkey'];
3059 // When sending content to Friendica contacts using the Diaspora protocol
3060 // we have to fetch the public key from the diaspora-contact.
3061 // This is due to the fact that legacy DFRN had unique keys for every contact.
3062 $pubkey = $contact['pubkey'];
3063 if (!empty($contact['addr'])) {
3065 $pubkey = DI::dsprContact()->getByAddr(WebFingerUri::fromString($contact['addr']))->pubKey;
3066 } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
3070 // The "addr" field should always be filled.
3071 // If this isn't the case, it will raise a notice some lines later.
3072 // And in the log we will see where it came from, and we can handle it there.
3073 Logger::notice('Empty addr', ['contact' => $contact ?? [], 'callstack' => System::callstack(20)]);
3076 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $pubkey ?? '', $public_batch);
3078 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3080 Logger::info('Transmitted message', ['owner' => $owner['uid'], 'target' => $contact['addr'], 'type' => $type, 'guid' => $guid, 'result' => $return_code]);
3082 return $return_code;
3086 * sends a participation (Used to get all further updates)
3088 * @param array $contact Target of the communication
3089 * @param array $item Item array
3091 * @return int The result of the transmission
3092 * @throws \Exception
3094 private static function sendParticipation(array $contact, array $item): int
3096 // Don't send notifications for private postings
3097 if ($item['private'] == Item::PRIVATE) {
3101 $cachekey = 'diaspora:sendParticipation:' . $item['guid'];
3103 $result = DI::cache()->get($cachekey);
3104 if (!is_null($result)) {
3108 // Fetch some user id to have a valid handle to transmit the participation.
3109 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3110 // If the item belongs to a user, we take this user id.
3111 if ($item['uid'] == 0) {
3112 // @todo Possibly use an administrator account?
3113 $condition = ['verified' => true, 'blocked' => false,
3114 'account_removed' => false, 'account_expired' => false, 'account-type' => User::ACCOUNT_TYPE_PERSON];
3115 $first_user = DBA::selectFirst('user', ['uid'], $condition, ['order' => ['uid']]);
3116 $owner = User::getOwnerDataById($first_user['uid']);
3118 $owner = User::getOwnerDataById($item['uid']);
3121 $author_handle = self::myHandle($owner);
3124 'author' => $author_handle,
3125 'guid' => System::createUUID(),
3126 'parent_type' => 'Post',
3127 'parent_guid' => $item['guid']
3130 Logger::info('Send participation for ' . $item['guid'] . ' by ' . $author_handle);
3132 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3133 DI::cache()->set($cachekey, $item['guid'], Duration::QUARTER_HOUR);
3135 return self::buildAndTransmit($owner, $contact, 'participation', $message);
3139 * sends an account migration
3141 * @param array $owner the array of the item owner
3142 * @param array $contact Target of the communication
3143 * @param int $uid User ID
3145 * @return int The result of the transmission
3146 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3147 * @throws \ImagickException
3149 public static function sendAccountMigration(array $owner, array $contact, int $uid): int
3151 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3152 $profile = self::createProfileData($uid);
3154 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3155 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
3158 'author' => $old_handle,
3159 'profile' => $profile,
3160 'signature' => $signature
3163 Logger::info('Send account migration', ['msg' => $message]);
3165 return self::buildAndTransmit($owner, $contact, 'account_migration', $message);
3169 * Sends a "share" message
3171 * @param array $owner the array of the item owner
3172 * @param array $contact Target of the communication
3174 * @return int The result of the transmission
3175 * @throws \Exception
3177 public static function sendShare(array $owner, array $contact): int
3180 * @todo support the different possible combinations of "following" and "sharing"
3181 * Currently, Diaspora only interprets the "sharing" field
3183 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3187 switch ($contact["rel"]) {
3188 case Contact::FRIEND:
3192 case Contact::SHARING:
3196 case Contact::FOLLOWER:
3203 'author' => self::myHandle($owner),
3204 'recipient' => $contact['addr'],
3205 'following' => 'true',
3209 Logger::info('Send share', ['msg' => $message]);
3211 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3215 * sends an "unshare"
3217 * @param array $owner the array of the item owner
3218 * @param array $contact Target of the communication
3220 * @return int The result of the transmission
3221 * @throws \Exception
3223 public static function sendUnshare(array $owner, array $contact): int
3226 'author' => self::myHandle($owner),
3227 'recipient' => $contact['addr'],
3228 'following' => 'false',
3229 'sharing' => 'false'
3232 Logger::info('Send unshare', ['msg' => $message]);
3234 return self::buildAndTransmit($owner, $contact, 'contact', $message);
3238 * Fetch reshare details
3240 * @param array $item The message body that is to be check
3242 * @return array Reshare details (empty if the item is no reshare)
3243 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3244 * @throws \ImagickException
3246 public static function getReshareDetails(array $item): array
3248 $reshared = DI::contentItem()->getSharedPost($item, ['guid', 'network', 'author-addr']);
3249 if (empty($reshared)) {
3253 // Skip if it isn't a pure repeated messages or not a real reshare
3254 if (!empty($reshared['comment']) || !in_array($reshared['post']['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
3259 'root_handle' => strtolower($reshared['post']['author-addr']),
3260 'root_guid' => $reshared['post']['guid'],
3265 * Create an event array
3267 * @param integer $event_id The id of the event
3269 * @return array with event data
3270 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3272 private static function buildEvent(string $event_id): array
3274 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
3275 if (!DBA::isResult($event)) {
3281 $owner = User::getOwnerDataById($event['uid']);
3286 $eventdata['author'] = self::myHandle($owner);
3288 if ($event['guid']) {
3289 $eventdata['guid'] = $event['guid'];
3292 $mask = DateTimeFormat::ATOM;
3294 /// @todo - establish "all day" events in Friendica
3295 $eventdata['all_day'] = 'false';
3297 $eventdata['timezone'] = 'UTC';
3299 if ($event['start']) {
3300 $eventdata['start'] = DateTimeFormat::utc($event['start'], $mask);
3302 if ($event['finish'] && !$event['nofinish']) {
3303 $eventdata['end'] = DateTimeFormat::utc($event['finish'], $mask);
3305 if ($event['summary']) {
3306 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3308 if ($event['desc']) {
3309 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3311 if ($event['location']) {
3312 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3313 $coord = Map::getCoordinates($event['location']);
3316 $location['address'] = html_entity_decode(BBCode::toMarkdown($event['location']));
3317 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3318 $location['lat'] = $coord['lat'];
3319 $location['lng'] = $coord['lon'];
3321 $location['lat'] = 0;
3322 $location['lng'] = 0;
3324 $eventdata['location'] = $location;
3331 * Create a post (status message or reshare)
3333 * @param array $item The item that will be exported
3334 * @param array $owner the array of the item owner
3337 * 'type' -> Message type ("status_message" or "reshare")
3338 * 'message' -> Array of XML elements of the status
3339 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3340 * @throws \ImagickException
3342 public static function buildStatus(array $item, array $owner)
3344 $cachekey = 'diaspora:buildStatus:' . $item['guid'];
3346 $result = DI::cache()->get($cachekey);
3347 if (!is_null($result)) {
3351 $myaddr = self::myHandle($owner);
3353 $public = ($item['private'] == Item::PRIVATE ? 'false' : 'true');
3354 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3355 $edited = DateTimeFormat::utc($item['edited'] ?? $item['created'], DateTimeFormat::ATOM);
3357 // Detect a share element and do a reshare
3358 if (($item['private'] != Item::PRIVATE) && ($ret = self::getReshareDetails($item))) {
3360 'author' => $myaddr,
3361 'guid' => $item['guid'],
3362 'created_at' => $created,
3363 'root_author' => $ret['root_handle'],
3364 'root_guid' => $ret['root_guid'],
3365 'provider_display_name' => $item['app'],
3371 $title = $item['title'];
3372 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
3374 // Fetch the title from an attached link - if there is one
3375 if (empty($item['title']) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3376 $page_data = BBCode::getAttachmentData($item['body']);
3377 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3378 $title = $page_data['title'];
3382 // convert to markdown
3383 $body = html_entity_decode(BBCode::toMarkdown($body));
3386 if (strlen($title)) {
3387 $body = '### ' . html_entity_decode($title) . "\n\n" . $body;
3390 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]);
3391 if (!empty($attachments)) {
3392 $body .= "\n[hr]\n";
3393 foreach ($attachments as $attachment) {
3394 $body .= "[" . $attachment['description'] . "](" . $attachment['url'] . ")\n";
3400 if ($item['location'] != '')
3401 $location['address'] = $item['location'];
3403 if ($item['coord'] != '') {
3404 $coord = explode(' ', $item['coord']);
3405 $location['lat'] = $coord[0];
3406 $location['lng'] = $coord[1];
3410 'author' => $myaddr,
3411 'guid' => $item['guid'],
3412 'created_at' => $created,
3413 'edited_at' => $edited,
3414 'public' => $public,
3416 'provider_display_name' => $item['app'],
3417 'location' => $location
3420 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3421 if (!isset($location['lat']) || !isset($location['lng'])) {
3422 unset($message['location']);
3425 if ($item['event-id'] > 0) {
3426 $event = self::buildEvent($item['event-id']);
3427 if (count($event)) {
3428 $message['event'] = $event;
3430 if (!empty($event['location']['address']) &&
3431 !empty($event['location']['lat']) &&
3432 !empty($event['location']['lng'])) {
3433 $message['location'] = $event['location'];
3436 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3437 // $message['text'] = '';
3441 $type = 'status_message';
3446 'message' => $message
3449 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3454 private static function prependParentAuthorMention(string $body, string $profile_url): string
3456 $profile = Contact::getByURL($profile_url, false, ['addr', 'name']);
3457 if (!empty($profile['addr'])
3458 && !strstr($body, $profile['addr'])
3459 && !strstr($body, $profile_url)
3461 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3470 * @param array $item The item that will be exported
3471 * @param array $owner the array of the item owner
3472 * @param array $contact Target of the communication
3473 * @param bool $public_batch Is it a public post?
3475 * @return int The result of the transmission
3476 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3477 * @throws \ImagickException
3479 public static function sendStatus(array $item, array $owner, array $contact, bool $public_batch = false): int
3481 $status = self::buildStatus($item, $owner);
3483 return self::buildAndTransmit($owner, $contact, $status['type'], $status['message'], $public_batch, $item['guid']);
3487 * Creates a "like" object
3489 * @param array $item The item that will be exported
3490 * @param array $owner the array of the item owner
3492 * @return array|bool The data for a "like" or false on error
3493 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3495 private static function constructLike(array $item, array $owner)
3497 $parent = Post::selectFirst(['guid', 'uri', 'thr-parent'], ['uri' => $item['thr-parent']]);
3498 if (!DBA::isResult($parent)) {
3502 $target_type = ($parent['uri'] === $parent['thr-parent'] ? 'Post' : 'Comment');
3504 if ($item['verb'] === Activity::LIKE) {
3506 } elseif ($item['verb'] === Activity::DISLIKE) {
3507 $positive = 'false';
3511 'author' => self::myHandle($owner),
3512 'guid' => $item['guid'],
3513 'parent_guid' => $parent['guid'],
3514 'parent_type' => $target_type,
3515 'positive' => $positive,
3516 'author_signature' => '',
3521 * Creates an "EventParticipation" object
3523 * @param array $item The item that will be exported
3524 * @param array $owner the array of the item owner
3526 * @return array|bool The data for an "EventParticipation" or false on error
3527 * @throws \Exception
3529 private static function constructAttend(array $item, array $owner)
3531 $parent = Post::selectFirst(['guid'], ['uri' => $item['thr-parent']]);
3532 if (!DBA::isResult($parent)) {
3536 switch ($item['verb']) {
3537 case Activity::ATTEND:
3538 $attend_answer = 'accepted';
3540 case Activity::ATTENDNO:
3541 $attend_answer = 'declined';
3543 case Activity::ATTENDMAYBE:
3544 $attend_answer = 'tentative';
3547 Logger::warning('Unknown verb ' . $item['verb'] . ' in item ' . $item['guid']);
3552 'author' => self::myHandle($owner),
3553 'guid' => $item['guid'],
3554 'parent_guid' => $parent['guid'],
3555 'status' => $attend_answer,
3556 'author_signature' => ''
3561 * Creates the object for a comment
3563 * @param array $item The item that will be exported
3564 * @param array $owner the array of the item owner
3566 * @return array|false The data for a comment
3567 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3569 private static function constructComment(array $item, array $owner)
3571 $cachekey = 'diaspora:constructComment:' . $item['guid'];
3573 $result = DI::cache()->get($cachekey);
3574 if (!is_null($result)) {
3578 $toplevel_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3579 if (!DBA::isResult($toplevel_item)) {
3580 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3584 $thread_parent_item = $toplevel_item;
3585 if ($item['thr-parent'] != $item['parent-uri']) {
3586 $thread_parent_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3589 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
3591 // The replied to autor mention is prepended for clarity if:
3592 // - Item replied isn't yours
3593 // - Item is public or explicit mentions are disabled
3594 // - Implicit mentions are enabled
3596 $item['author-id'] != $thread_parent_item['author-id']
3597 && ($thread_parent_item['gravity'] != Item::GRAVITY_PARENT)
3598 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3599 && !DI::config()->get('system', 'disable_implicit_mentions')
3601 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3604 $text = html_entity_decode(BBCode::toMarkdown($body));
3605 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3606 $edited = DateTimeFormat::utc($item['edited'], DateTimeFormat::ATOM);
3609 'author' => self::myHandle($owner),
3610 'guid' => $item['guid'],
3611 'created_at' => $created,
3612 'edited_at' => $edited,
3613 'parent_guid' => $toplevel_item['guid'],
3615 'author_signature' => '',
3618 // Send the thread parent guid only if it is a threaded comment
3619 if ($item['thr-parent'] != $item['parent-uri']) {
3620 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3623 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3629 * Send a like or a comment
3631 * @param array $item The item that will be exported
3632 * @param array $owner the array of the item owner
3633 * @param array $contact Target of the communication
3634 * @param bool $public_batch Is it a public post?
3636 * @return int The result of the transmission
3637 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3638 * @throws \ImagickException
3640 public static function sendFollowup(array $item, array $owner, array $contact, bool $public_batch = false): int
3642 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3643 $message = self::constructAttend($item, $owner);
3644 $type = 'event_participation';
3645 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3646 $message = self::constructLike($item, $owner);
3648 } elseif (!in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
3649 $message = self::constructComment($item, $owner);
3653 if (empty($message)) {
3657 $message['author_signature'] = self::signature($owner, $message);
3659 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3663 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3665 * @param array $item The item that will be exported
3666 * @param array $owner the array of the item owner
3667 * @param array $contact Target of the communication
3668 * @param bool $public_batch Is it a public post?
3670 * @return int The result of the transmission
3671 * @throws \Exception
3673 public static function sendRelay(array $item, array $owner, array $contact, bool $public_batch = false): int
3675 if ($item['deleted']) {
3676 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3677 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3683 Logger::info('Got relayable data ' . $type . ' for item ' . $item['guid'] . ' (' . $item['id'] . ')');
3685 $msg = json_decode($item['signed_text'] ?? '', true);
3688 if (is_array($msg)) {
3689 foreach ($msg as $field => $data) {
3690 if (!$item['deleted']) {
3691 if ($field == 'diaspora_handle') {
3694 if ($field == 'target_type') {
3695 $field = 'parent_type';
3699 $message[$field] = $data;
3702 Logger::info('Signature text for item ' . $item['guid'] . ' (' . $item['id'] . ') could not be extracted: ' . $item['signed_text']);
3705 $message['parent_author_signature'] = self::signature($owner, $message);
3707 Logger::info('Relayed data', ['msg' => $message]);
3709 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
3713 * Sends a retraction (deletion) of a message, like or comment
3715 * @param array $item The item that will be exported
3716 * @param array $owner the array of the item owner
3717 * @param array $contact Target of the communication
3718 * @param bool $public_batch Is it a public post?
3719 * @param bool $relay Is the retraction transmitted from a relay?
3721 * @return int The result of the transmission
3722 * @throws \Exception
3724 public static function sendRetraction(array $item, array $owner, array $contact, bool $public_batch = false, bool $relay = false): int
3726 $itemaddr = strtolower($item['author-addr']);
3728 $msg_type = 'retraction';
3730 if ($item['gravity'] == Item::GRAVITY_PARENT) {
3731 $target_type = 'Post';
3732 } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3733 $target_type = 'Like';
3735 $target_type = 'Comment';
3739 'author' => $itemaddr,
3740 'target_guid' => $item['guid'],
3741 'target_type' => $target_type
3744 Logger::info('Got message', ['msg' => $message]);
3746 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item['guid']);
3752 * @param array $item The item that will be exported
3753 * @param array $owner The owner
3754 * @param array $contact Target of the communication
3756 * @return int The result of the transmission
3757 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3758 * @throws \ImagickException
3760 public static function sendMail(array $item, array $owner, array $contact): int
3762 $myaddr = self::myHandle($owner);
3764 $cnv = DBA::selectFirst('conv', [], ['id' => $item['convid'], 'uid' => $item['uid']]);
3765 if (!DBA::isResult($cnv)) {
3766 Logger::notice('Conversation not found.');
3770 $body = BBCode::toMarkdown($item['body']);
3771 $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
3774 'author' => $myaddr,
3775 'guid' => $item['guid'],
3776 'conversation_guid' => $cnv['guid'],
3778 'created_at' => $created,
3781 if ($item['reply']) {
3786 'author' => $cnv['creator'],
3787 'guid' => $cnv['guid'],
3788 'subject' => $cnv['subject'],
3789 'created_at' => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3790 'participants' => $cnv['recips'],
3794 $type = 'conversation';
3797 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item['guid']);
3801 * Split a name into first name and last name
3803 * @param string $name The name
3805 * @return array The array with "first" and "last"
3807 public static function splitName(string $name): array
3809 $name = trim($name);
3811 // Is the name longer than 64 characters? Then cut the rest of it.
3812 if (strlen($name) > 64) {
3813 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3814 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3816 $name = substr($name, 0, 64);
3820 // Take the first word as first name
3821 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3822 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3823 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3824 return ['first' => $first, 'last' => $last];
3827 // Take the last word as last name
3828 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3829 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3831 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3832 return ['first' => $first, 'last' => $last];
3835 // Take the first 32 characters if there is no space in the first 32 characters
3836 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3837 $first = substr($name, 0, 32);
3838 $last = substr($name, 32);
3839 return ['first' => $first, 'last' => $last];
3842 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3843 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3845 // Check if the last name is longer than 32 characters
3846 if (strlen($last) > 32) {
3847 if (strpos($last, ' ') <= 32) {
3848 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
3850 $last = substr($last, 0, 32);
3854 return ['first' => $first, 'last' => $last];
3858 * Create profile data
3860 * @param int $uid The user id
3862 * @return array The profile data
3863 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3865 private static function createProfileData(int $uid): array
3867 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
3869 if (!DBA::isResult($profile)) {
3873 $split_name = self::splitName($profile['name']);
3876 'author' => $profile['addr'],
3877 'first_name' => $split_name['first'],
3878 'last_name' => $split_name['last'],
3879 'image_url' => DI::baseUrl() . '/photo/custom/300/' . $profile['uid'] . '.jpg',
3880 'image_url_medium' => DI::baseUrl() . '/photo/custom/100/' . $profile['uid'] . '.jpg',
3881 'image_url_small' => DI::baseUrl() . '/photo/custom/50/' . $profile['uid'] . '.jpg',
3882 'searchable' => ($profile['net-publish'] ? 'true' : 'false'),
3886 'tag_string' => null,
3890 if ($data['searchable'] === 'true') {
3891 $data['birthday'] = '';
3893 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
3894 [$year, $month, $day] = sscanf($profile['dob'], '%4d-%2d-%2d');
3898 $data['birthday'] = DateTimeFormat::utc($year . '-' . $month . '-' . $day, 'Y-m-d');
3901 $data['about'] = BBCode::toMarkdown($profile['about'] ?? '');
3903 $data['location'] = $profile['location'];
3904 $data['tag_string'] = '';
3906 if ($profile['pub_keywords']) {
3907 $kw = str_replace(',', ' ', $profile['pub_keywords']);
3908 $kw = str_replace(' ', ' ', $kw);
3909 $arr = explode(' ', $kw);
3911 for ($x = 0; $x < 5; $x ++) {
3912 if (!empty($arr[$x])) {
3913 $data['tag_string'] .= '#'. trim($arr[$x]) .' ';
3918 $data['tag_string'] = trim($data['tag_string']);
3925 * Sends profile data
3927 * @param int $uid The user id
3928 * @param array $recipients optional, default empty array
3931 * @throws \Exception
3933 public static function sendProfile(int $uid, array $recipients = [])
3936 Logger::warning('Parameter "uid" is empty');
3940 $owner = User::getOwnerDataById($uid);
3941 if (empty($owner)) {
3942 Logger::warning('Cannot fetch User record', ['uid' => $uid]);
3946 if (empty($recipients)) {
3947 Logger::debug('No recipients provided, fetching for user', ['uid' => $uid]);
3948 $recipients = DBA::selectToArray('contact', [], ['network' => Protocol::DIASPORA, 'uid' => $uid, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
3951 if (empty($recipients)) {
3952 Logger::warning('Cannot fetch recipients', ['uid' => $uid]);
3956 $message = self::createProfileData($uid);
3958 // @todo Split this into single worker jobs
3959 foreach ($recipients as $recipient) {
3960 Logger::info('Send updated profile data for user ' . $uid . ' to contact ' . $recipient['id']);
3961 self::buildAndTransmit($owner, $recipient, 'profile', $message);
3966 * Creates the signature for likes that are created on our system
3968 * @param integer $uid The user of that comment
3969 * @param array $item Item array
3971 * @return array|bool Signed content or false on error
3972 * @throws \Exception
3974 public static function createLikeSignature(int $uid, array $item)
3976 $owner = User::getOwnerDataById($uid);
3977 if (empty($owner)) {
3978 Logger::info('No owner post, so not storing signature', ['uid' => $uid]);
3982 if (!in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
3983 Logger::warning('Item is neither a like nor a dislike', ['uid' => $uid, 'item[verb]' => $item['verb']]);;
3987 $message = self::constructLike($item, $owner);
3988 if ($message === false) {
3992 $message['author_signature'] = self::signature($owner, $message);
3998 * Creates the signature for Comments that are created on our system
4000 * @param array $item Item array
4002 * @return array|bool Signed content or false on error
4003 * @throws \Exception
4005 public static function createCommentSignature(array $item)
4008 if (!empty($item['author-link'])) {
4009 $url = $item['author-link'];
4011 $contact = Contact::getById($item['author-id'], ['url']);
4012 if (empty($contact['url'])) {
4013 Logger::warning('Author Contact not found', ['author-id' => $item['author-id']]);
4016 $url = $contact['url'];
4019 $uid = User::getIdForURL($url);
4021 Logger::info('No owner post, so not storing signature', ['url' => $contact['url'] ?? 'No contact loaded']);
4025 $owner = User::getOwnerDataById($uid);
4026 if (empty($owner)) {
4027 Logger::info('No owner post, so not storing signature');
4031 // This is only needed for the automated tests
4032 if (empty($owner['uprvkey'])) {
4036 if (!self::parentSupportDiaspora($item['thr-parent-id'])) {
4037 Logger::info('One of the parents does not support Diaspora. A signature will not be created.', ['uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
4041 $message = self::constructComment($item, $owner);
4042 if ($message === false) {
4046 $message['author_signature'] = self::signature($owner, $message);
4052 * Check if the parent and their parents support Diaspora
4054 * @param integer $parent_id
4056 * @throws InternalServerErrorException
4057 * @throws \ImagickException
4059 private static function parentSupportDiaspora(int $parent_id): bool
4061 $parent_post = Post::selectFirstPost(['gravity', 'signed_text', 'author-link', 'thr-parent-id'], ['uri-id' => $parent_id]);
4062 if (empty($parent_post['thr-parent-id'])) {
4063 Logger::warning('Parent post does not exist.', ['parent-id' => $parent_id]);
4067 if (!self::isSupportedByContactUrl($parent_post['author-link'], false)) {
4068 Logger::info('Parent author is no Diaspora contact.', ['parent-id' => $parent_id]);
4072 if (($parent_post['gravity'] == Item::GRAVITY_COMMENT) && empty($parent_post['signed_text'])) {
4073 Logger::info('Parent comment has got no Diaspora signature.', ['parent-id' => $parent_id]);
4077 if ($parent_post['gravity'] == Item::GRAVITY_COMMENT) {
4078 return self::parentSupportDiaspora($parent_post['thr-parent-id']);
4084 public static function performReshare(int $UriId, int $uid): int
4086 $owner = User::getOwnerDataById($uid);
4087 $author = Contact::getPublicIdByUserId($uid);
4091 'verb' => Activity::POST,
4092 'contact-id' => $owner['id'],
4093 'author-id' => $author,
4094 'owner-id' => $author,
4096 'quote-uri-id' => $UriId,
4097 'allow_cid' => $owner['allow_cid'] ?? '',
4098 'allow_gid' => $owner['allow_gid']?? '',
4099 'deny_cid' => $owner['deny_cid'] ?? '',
4100 'deny_gid' => $owner['deny_gid'] ?? '',
4103 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
4104 $item['private'] = Item::PRIVATE;
4105 } elseif (DI::pConfig()->get($uid, 'system', 'unlisted')) {
4106 $item['private'] = Item::UNLISTED;
4108 $item['private'] = Item::PUBLIC;
4111 // Don't trigger the addons
4112 $item['api_source'] = false;
4114 return Item::insert($item, true);