3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol;
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\Markdown;
27 use Friendica\Core\Cache\Enum\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\FContact;
37 use Friendica\Model\GServer;
38 use Friendica\Model\Item;
39 use Friendica\Model\ItemURI;
40 use Friendica\Model\Mail;
41 use Friendica\Model\Post;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
45 use Friendica\Network\Probe;
46 use Friendica\Util\Crypto;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Map;
49 use Friendica\Util\Network;
50 use Friendica\Util\Strings;
51 use Friendica\Util\XML;
52 use Friendica\Worker\Delivery;
56 * This class contain functions to create and send Diaspora XML files
62 const FORCED_FETCH = 2;
65 * Return a list of participating contacts for a thread
67 * This is used for the participation feature.
68 * One of the parameters is a contact array.
69 * This is done to avoid duplicates.
71 * @param array $item Item that is about to be delivered
72 * @param array $contacts The previously fetched contacts
74 * @return array of relay servers
77 public static function participantsForThread(array $item, array $contacts): array
79 if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
80 Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]);
84 $items = Post::select(['author-id', 'author-link', 'parent-author-link', 'parent-guid', 'guid'],
85 ['parent' => $item['parent'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
86 while ($item = Post::fetch($items)) {
87 $contact = DBA::selectFirst('contact', ['id', 'url', 'name', 'protocol', 'batch', 'network'],
88 ['id' => $item['author-id']]);
89 if (!DBA::isResult($contact) || empty($contact['batch']) ||
90 ($contact['network'] != Protocol::DIASPORA) ||
91 Strings::compareLink($item['parent-author-link'], $item['author-link'])) {
96 foreach ($contacts as $entry) {
97 if ($entry['batch'] == $contact['batch']) {
103 Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]);
104 $contacts[] = $contact;
113 * verify the envelope and return the verified data
115 * @param string $envelope The magic envelope
117 * @return string|bool verified data or false on error
118 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
119 * @throws \ImagickException
121 private static function verifyMagicEnvelope(string $envelope)
123 $basedom = XML::parseString($envelope, true);
125 if (!is_object($basedom)) {
126 Logger::notice("Envelope is no XML file");
130 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
132 if (sizeof($children) == 0) {
133 Logger::notice("XML has no children");
139 $data = Strings::base64UrlDecode($children->data);
140 $type = $children->data->attributes()->type[0];
142 $encoding = $children->encoding;
144 $alg = $children->alg;
146 $sig = Strings::base64UrlDecode($children->sig);
147 $key_id = $children->sig->attributes()->key_id[0];
149 $handle = Strings::base64UrlDecode($key_id);
152 $b64url_data = Strings::base64UrlEncode($data);
153 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
155 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
158 Logger::notice('No author could be decoded. Discarding. Message: ' . $envelope);
162 $key = self::key($handle);
164 Logger::notice("Couldn't get a key for handle " . $handle . ". Discarding.");
168 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
170 Logger::notice('Message from ' . $handle . ' did not verify. Discarding.');
178 * encrypts data via AES
180 * @param string $key The AES key
181 * @param string $iv The IV (is used for CBC encoding)
182 * @param string $data The data that is to be encrypted
184 * @return string encrypted data
186 private static function aesEncrypt(string $key, string $iv, string $data): string
188 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
192 * decrypts data via AES
194 * @param string $key The AES key
195 * @param string $iv The IV (is used for CBC encoding)
196 * @param string $encrypted The encrypted data
198 * @return string decrypted data
200 private static function aesDecrypt(string $key, string $iv, string $encrypted): string
202 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
206 * Decodes incoming Diaspora message in the new format. This method returns false on an error.
208 * @param string $raw raw post message
209 * @param string $privKey The private key of the importer
210 * @param boolean $no_exit Don't do an http exit on error
213 * 'message' -> decoded Diaspora XML message
214 * 'author' -> author diaspora handle
215 * 'key' -> author public key (converted to pkcs#8)
216 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
217 * @throws \ImagickException
219 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
221 $data = json_decode($raw);
223 // Is it a private post? Then decrypt the outer Salmon
224 if (is_object($data)) {
225 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
226 $ciphertext = base64_decode($data->encrypted_magic_envelope);
228 $outer_key_bundle = '';
229 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
230 $j_outer_key_bundle = json_decode($outer_key_bundle);
232 if (!is_object($j_outer_key_bundle)) {
233 Logger::notice('Outer Salmon did not verify. Discarding.');
237 throw new \Friendica\Network\HTTPException\BadRequestException();
241 $outer_iv = base64_decode($j_outer_key_bundle->iv);
242 $outer_key = base64_decode($j_outer_key_bundle->key);
244 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
249 $basedom = XML::parseString($xml, true);
251 if (!is_object($basedom)) {
252 Logger::notice('Received data does not seem to be an XML. Discarding. '.$xml);
256 throw new \Friendica\Network\HTTPException\BadRequestException();
260 $base = $basedom->children(ActivityNamespace::SALMON_ME);
262 // Not sure if this cleaning is needed
263 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
265 // Build the signed data
266 $type = $base->data[0]->attributes()->type[0];
267 $encoding = $base->encoding;
269 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
271 // This is the signature
272 $signature = Strings::base64UrlDecode($base->sig);
274 // Get the senders' public key
275 $key_id = $base->sig[0]->attributes()->key_id[0];
276 $author_addr = base64_decode($key_id);
277 if ($author_addr == '') {
278 Logger::notice('No author could be decoded. Discarding. Message: ' . $xml);
282 throw new \Friendica\Network\HTTPException\BadRequestException();
286 $key = self::key($author_addr);
288 Logger::notice("Couldn't get a key for handle " . $author_addr . ". Discarding.");
292 throw new \Friendica\Network\HTTPException\BadRequestException();
296 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
298 Logger::notice('Message did not verify. Discarding.');
302 throw new \Friendica\Network\HTTPException\BadRequestException();
306 return ['message' => (string)Strings::base64UrlDecode($base->data),
307 'author' => XML::unescape($author_addr),
308 'key' => (string)$key];
312 * Decodes incoming Diaspora message in the deprecated format
314 * @param string $xml urldecoded Diaspora salmon
315 * @param string $privKey The private key of the importer
318 * 'message' -> decoded Diaspora XML message
319 * 'author' -> author diaspora handle
320 * 'key' -> author public key (converted to pkcs#8)
321 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
322 * @throws \ImagickException
324 public static function decode(string $xml, string $privKey = ''): array
327 $basedom = XML::parseString($xml);
329 if (!is_object($basedom)) {
330 Logger::notice('XML is not parseable.');
333 $children = $basedom->children('https://joindiaspora.com/protocol');
335 $inner_aes_key = null;
338 if ($children->header) {
340 $author_link = str_replace('acct:', '', $children->header->author_id);
342 // This happens with posts from a relais
343 if (empty($privKey)) {
344 Logger::info('This is no private post in the old format');
348 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
350 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
351 $ciphertext = base64_decode($encrypted_header->ciphertext);
353 $outer_key_bundle = '';
354 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
356 $j_outer_key_bundle = json_decode($outer_key_bundle);
358 $outer_iv = base64_decode($j_outer_key_bundle->iv);
359 $outer_key = base64_decode($j_outer_key_bundle->key);
361 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
363 Logger::info('decrypted', ['data' => $decrypted]);
364 $idom = XML::parseString($decrypted);
366 $inner_iv = base64_decode($idom->iv);
367 $inner_aes_key = base64_decode($idom->aes_key);
369 $author_link = str_replace('acct:', '', $idom->author_id);
372 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
374 // figure out where in the DOM tree our data is hiding
377 if ($dom->provenance->data) {
378 $base = $dom->provenance;
379 } elseif ($dom->env->data) {
381 } elseif ($dom->data) {
386 Logger::notice('unable to locate salmon data in xml');
387 throw new \Friendica\Network\HTTPException\BadRequestException();
391 // Stash the signature away for now. We have to find their key or it won't be good for anything.
392 $signature = Strings::base64UrlDecode($base->sig);
396 // strip whitespace so our data element will return to one big base64 blob
397 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
400 // stash away some other stuff for later
402 $type = $base->data[0]->attributes()->type[0];
403 $keyhash = $base->sig[0]->attributes()->keyhash[0];
404 $encoding = $base->encoding;
408 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
412 $data = Strings::base64UrlDecode($data);
416 $inner_decrypted = $data;
418 // Decode the encrypted blob
419 $inner_encrypted = base64_decode($data);
420 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
424 Logger::notice('Could not retrieve author URI.');
425 throw new \Friendica\Network\HTTPException\BadRequestException();
427 // Once we have the author URI, go to the web and try to find their public key
428 // (first this will look it up locally if it is in the fcontact cache)
429 // This will also convert diaspora public key from pkcs#1 to pkcs#8
431 Logger::notice('Fetching key for '.$author_link);
432 $key = self::key($author_link);
435 Logger::notice('Could not retrieve author key.');
436 throw new \Friendica\Network\HTTPException\BadRequestException();
439 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
442 Logger::notice('Message did not verify. Discarding.');
443 throw new \Friendica\Network\HTTPException\BadRequestException();
446 Logger::notice('Message verified.');
448 return ['message' => (string)$inner_decrypted,
449 'author' => XML::unescape($author_link),
450 'key' => (string)$key];
455 * Dispatches public messages and find the fitting receivers
457 * @param array $msg The post that will be dispatched
458 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
460 * @return int|bool The message id of the generated message, "true" or "false" if there was an error
461 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
462 * @throws \ImagickException
464 public static function dispatchPublic(array $msg, int $direction)
466 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
468 Logger::notice("diaspora is disabled");
472 if (!($fields = self::validPosting($msg))) {
473 Logger::notice("Invalid posting");
477 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
478 $success = self::dispatch($importer, $msg, $fields, $direction);
484 * Dispatches the different message types to the different functions
486 * @param array $importer Array of the importer user
487 * @param array $msg The post that will be dispatched
488 * @param SimpleXMLElement $fields SimpleXML object that contains the message
489 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
491 * @return int|bool The message id of the generated message, "true" or "false" if there was an error
492 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
493 * @throws \ImagickException
495 public static function dispatch(array $importer, array $msg, SimpleXMLElement $fields = null, int $direction = self::PUSHED)
497 // The sender is the handle of the contact that sent the message.
498 // This will often be different with relayed messages (for example "like" and "comment")
499 $sender = $msg["author"];
501 // This is only needed for private postings since this is already done for public ones before
502 if (is_null($fields)) {
504 if (!($fields = self::validPosting($msg))) {
505 Logger::notice("Invalid posting");
512 $type = $fields->getName();
514 Logger::info('Received message', ['type' => $type, 'sender' => $sender, 'user' => $importer["uid"]]);
517 case "account_migration":
519 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
522 return self::receiveAccountMigration($importer, $fields);
524 case "account_deletion":
525 return self::receiveAccountDeletion($fields);
528 return self::receiveComment($importer, $sender, $fields, $msg["message"], $direction);
532 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
535 return self::receiveContactRequest($importer, $fields);
539 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
542 return self::receiveConversation($importer, $msg, $fields);
545 return self::receiveLike($importer, $sender, $fields, $direction);
549 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
552 return self::receiveMessage($importer, $fields);
554 case "participation":
556 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
559 return self::receiveParticipation($importer, $fields, $direction);
561 case "photo": // Not implemented
562 return self::receivePhoto($importer, $fields);
564 case "poll_participation": // Not implemented
565 return self::receivePollParticipation($importer, $fields);
569 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
572 return self::receiveProfile($importer, $fields);
575 return self::receiveReshare($importer, $fields, $msg["message"], $direction);
578 return self::receiveRetraction($importer, $sender, $fields);
580 case "status_message":
581 return self::receiveStatusMessage($importer, $fields, $msg["message"], $direction);
584 Logger::notice("Unknown message type ".$type);
590 * Checks if a posting is valid and fetches the data fields.
592 * This function does not only check the signature.
593 * It also does the conversion between the old and the new diaspora format.
595 * @param array $msg Array with the XML, the sender handle and the sender signature
597 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
598 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
599 * @throws \ImagickException
601 private static function validPosting(array $msg)
603 $data = XML::parseString($msg["message"]);
605 if (!is_object($data)) {
606 Logger::info('No valid XML', ['message' => $msg['message']]);
610 // Is this the new or the old version?
611 if ($data->getName() == "XML") {
613 foreach ($data->post->children() as $child) {
621 $type = $element->getName();
624 Logger::debug("Got message type ".$type.": ".$msg["message"]);
626 // All retractions are handled identically from now on.
627 // In the new version there will only be "retraction".
628 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
629 $type = "retraction";
631 if ($type == "request") {
635 $fields = new SimpleXMLElement("<".$type."/>");
638 $author_signature = null;
639 $parent_author_signature = null;
641 foreach ($element->children() as $fieldname => $entry) {
643 // Translation for the old XML structure
644 if ($fieldname == "diaspora_handle") {
645 $fieldname = "author";
647 if ($fieldname == "participant_handles") {
648 $fieldname = "participants";
650 if (in_array($type, ["like", "participation"])) {
651 if ($fieldname == "target_type") {
652 $fieldname = "parent_type";
655 if ($fieldname == "sender_handle") {
656 $fieldname = "author";
658 if ($fieldname == "recipient_handle") {
659 $fieldname = "recipient";
661 if ($fieldname == "root_diaspora_id") {
662 $fieldname = "root_author";
664 if ($type == "status_message") {
665 if ($fieldname == "raw_message") {
669 if ($type == "retraction") {
670 if ($fieldname == "post_guid") {
671 $fieldname = "target_guid";
673 if ($fieldname == "type") {
674 $fieldname = "target_type";
679 if (($fieldname == "author_signature") && ($entry != "")) {
680 $author_signature = base64_decode($entry);
681 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
682 $parent_author_signature = base64_decode($entry);
683 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
684 if ($signed_data != "") {
688 $signed_data .= $entry;
690 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
691 || ($orig_type == "relayable_retraction")
693 XML::copy($entry, $fields, $fieldname);
697 // This is something that shouldn't happen at all.
698 if (in_array($type, ["status_message", "reshare", "profile"])) {
699 if ($msg["author"] != $fields->author) {
700 Logger::notice("Message handle is not the same as envelope sender. Quitting this message.");
705 // Only some message types have signatures. So we quit here for the other types.
706 if (!in_array($type, ["comment", "like"])) {
709 // No author_signature? This is a must, so we quit.
710 if (!isset($author_signature)) {
711 Logger::info("No author signature for type ".$type." - Message: ".$msg["message"]);
715 if (isset($parent_author_signature)) {
716 $key = self::key($msg["author"]);
718 Logger::info('No key found for parent', ['author' => $msg["author"]]);
722 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
723 Logger::info("No valid parent author signature for parent author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$parent_author_signature);
728 $key = self::key($fields->author);
730 Logger::info('No key found', ['author' => $fields->author]);
734 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
735 Logger::info("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature);
743 * Fetches the public key for a given handle
745 * @param string $handle The handle
747 * @return string The public key
748 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
749 * @throws \ImagickException
751 private static function key(string $handle): string
753 $handle = strval($handle);
755 Logger::notice("Fetching diaspora key for: ".$handle);
757 $fcontact = FContact::getByURL($handle);
759 return $fcontact["pubkey"];
766 * get a handle (user@domain.tld) from a given contact id
768 * @param int $contact_id The id in the contact table
769 * @param int $pcontact_id The id in the contact table (Used for the public contact)
771 * @return string the handle
774 private static function handleFromContact(int $contact_id, int $pcontact_id = 0): string
778 if ($pcontact_id != 0) {
779 $contact = Contact::getById($pcontact_id, ['addr']);
780 if (DBA::isResult($contact)) {
781 $handle = $contact['addr'];
785 if (empty($handle)) {
786 $contact = Contact::getById($contact_id, ['addr']);
787 if (DBA::isResult($contact)) {
788 $handle = $contact['addr'];
792 return strtolower($handle);
796 * Get a contact id for a given handle
798 * @todo Move to Friendica\Model\Contact
800 * @param int $uid The user id
801 * @param string $handle The handle in the format user@domain.tld
803 * @return array Contact data
804 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
805 * @throws \ImagickException
807 private static function contactByHandle(int $uid, string $handle): array
809 return Contact::getByURL($handle, null, [], $uid);
813 * Checks if the given contact url does support ActivityPub
815 * @param string $url profile url
816 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
818 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
819 * @throws \ImagickException
821 public static function isSupportedByContactUrl(string $url, $update = null)
823 return !empty(FContact::getByURL($url, $update));
827 * Check if posting is allowed for this contact
829 * @param array $importer Array of the importer user
830 * @param array $contact The contact that is checked
831 * @param bool $is_comment Is the check for a comment?
833 * @return bool is the contact allowed to post?
835 private static function postAllow(array $importer, array $contact, bool $is_comment = false): bool
838 * Perhaps we were already sharing with this person. Now they're sharing with us.
839 * That makes us friends.
840 * Normally this should have handled by getting a request - but this could get lost
842 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
843 // It is not removed by now. Possibly the code is needed?
844 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
846 // array('rel' => Contact::FRIEND, 'writable' => true),
847 // array('id' => $contact["id"], 'uid' => $contact["uid"])
850 // $contact["rel"] = Contact::FRIEND;
851 // Logger::notice("defining user ".$contact["nick"]." as friend");
854 // Contact server is blocked
855 if (Network::isUrlBlocked($contact['url'])) {
857 // We don't seem to like that person
858 } elseif ($contact["blocked"]) {
859 // Maybe blocked, don't accept.
861 // We are following this person?
862 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
863 // Yes, then it is fine.
865 // Is the message a global user or a comment?
866 } elseif (($importer["uid"] == 0) || $is_comment) {
867 // Messages for the global users and comments are always accepted
875 * Fetches the contact id for a handle and checks if posting is allowed
877 * @param array $importer Array of the importer user
878 * @param string $handle The checked handle in the format user@domain.tld
879 * @param bool $is_comment Is the check for a comment?
881 * @return array|bool The contact data or false on error
884 private static function allowedContactByHandle(array $importer, string $handle, bool $is_comment = false)
886 $contact = self::contactByHandle($importer["uid"], $handle);
888 Logger::notice("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
889 // If a contact isn't found, we accept it anyway if it is a comment
890 if ($is_comment && ($importer["uid"] != 0)) {
891 return self::contactByHandle(0, $handle);
892 } elseif ($is_comment) {
899 if (!self::postAllow($importer, $contact, $is_comment)) {
900 Logger::notice("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
907 * Does the message already exists on the system?
909 * @param int $uid The user id
910 * @param string $guid The guid of the message
912 * @return int|bool message id if the message already was stored into the system - or false.
915 private static function messageExists(int $uid, string $guid)
917 $item = Post::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
918 if (DBA::isResult($item)) {
919 Logger::notice("message ".$guid." already exists for user ".$uid);
927 * Checks for links to posts in a message
929 * @param array $item The item array
932 private static function fetchGuid(array $item)
934 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
935 preg_replace_callback(
937 function ($match) use ($item) {
938 self::fetchGuidSub($match, $item);
943 preg_replace_callback(
944 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
945 function ($match) use ($item) {
946 self::fetchGuidSub($match, $item);
953 * Checks for relative /people/* links in an item body to match local
954 * contacts or prepends the remote host taken from the author link.
956 * @param string $body The item body to replace links from
957 * @param string $author_link The author link for missing local contact fallback
959 * @return string the replaced string
961 public static function replacePeopleGuid(string $body, string $author_link): string
963 $return = preg_replace_callback(
964 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
965 function ($match) use ($author_link) {
967 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
968 // 1 => '0123456789abcdef'
970 $handle = FContact::getUrlByGuid($match[1]);
973 $return = '@[url='.$handle.']'.$match[2].'[/url]';
975 // No local match, restoring absolute remote URL from author scheme and host
976 $author_url = parse_url($author_link);
977 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
989 * sub function of "fetchGuid" which checks for links in messages
991 * @param array $match array containing a link that has to be checked for a message link
992 * @param array $item The item array
994 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
995 * @throws \ImagickException
997 private static function fetchGuidSub(array $match, array $item)
999 if (!self::storeByGuid($match[1], $item["author-link"], true)) {
1000 self::storeByGuid($match[1], $item["owner-link"], true);
1005 * Fetches an item with a given guid from a given server
1007 * @param string $guid the message guid
1008 * @param string $server The server address
1009 * @param bool $force Forced fetch
1011 * @return int|bool the message id of the stored message or false
1012 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1013 * @throws \ImagickException
1015 private static function storeByGuid(string $guid, string $server, bool $force)
1017 $serverparts = parse_url($server);
1019 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1023 $server = $serverparts["scheme"]."://".$serverparts["host"];
1025 Logger::info("Trying to fetch item ".$guid." from ".$server);
1027 $msg = self::message($guid, $server);
1033 Logger::info("Successfully fetched item ".$guid." from ".$server);
1035 // Now call the dispatcher
1036 return self::dispatchPublic($msg, $force ? self::FORCED_FETCH : self::FETCHED);
1040 * Fetches a message from a server
1042 * @param string $guid message guid
1043 * @param string $server The url of the server
1044 * @param int $level Endless loop prevention
1047 * 'message' => The message XML
1048 * 'author' => The author handle
1049 * 'key' => The public key of the author
1050 * @throws \Exception
1052 public static function message(string $guid, string $server, int $level = 0)
1058 // This will work for new Diaspora servers and Friendica servers from 3.5
1059 $source_url = $server."/fetch/post/".urlencode($guid);
1061 Logger::info("Fetch post from ".$source_url);
1063 $envelope = DI::httpClient()->fetch($source_url, HttpClientAccept::MAGIC);
1065 Logger::info("Envelope was fetched.");
1066 $x = self::verifyMagicEnvelope($envelope);
1068 Logger::info("Envelope could not be verified.");
1070 Logger::info("Envelope was verified.");
1080 $source_xml = XML::parseString($x);
1082 if (!is_object($source_xml)) {
1086 if ($source_xml->post->reshare) {
1087 // Reshare of a reshare - old Diaspora version
1088 Logger::info("Message is a reshare");
1089 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1090 } elseif ($source_xml->getName() == "reshare") {
1091 // Reshare of a reshare - new Diaspora version
1092 Logger::info("Message is a new reshare");
1093 return self::message($source_xml->root_guid, $server, ++$level);
1098 // Fetch the author - for the old and the new Diaspora version
1099 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1100 $author = (string)$source_xml->post->status_message->diaspora_handle;
1101 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1102 $author = (string)$source_xml->author;
1105 // If this isn't a "status_message" then quit
1107 Logger::info("Message doesn't seem to be a status message");
1111 $msg = ["message" => $x, "author" => $author];
1113 $msg["key"] = self::key($msg["author"]);
1119 * Fetches an item with a given URL
1121 * @param string $url the message url
1122 * @param int $uid User id
1124 * @return int|bool the message id of the stored message or false
1125 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1126 * @throws \ImagickException
1128 public static function fetchByURL(string $url, int $uid = 0)
1130 // Check for Diaspora (and Friendica) typical paths
1131 if (!preg_match("=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1132 Logger::info('Invalid url', ['url' => $url]);
1136 $guid = urldecode($matches[2]);
1138 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1139 if (DBA::isResult($item)) {
1140 Logger::info('Found', ['id' => $item['id']]);
1144 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1145 $ret = self::storeByGuid($guid, $matches[1], true);
1146 Logger::info('Result', ['ret' => $ret]);
1148 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1149 if (DBA::isResult($item)) {
1150 Logger::info('Found', ['id' => $item['id']]);
1153 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1159 * Fetches the item record of a given guid
1161 * @param int $uid The user id
1162 * @param string $guid message guid
1163 * @param string $author The handle of the item
1164 * @param array $contact The contact of the item owner
1166 * @return array|bool the item record or false on failure
1167 * @throws \Exception
1169 private static function parentItem(int $uid, string $guid, string $author, array $contact)
1171 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1172 'author-name', 'author-link', 'author-avatar', 'gravity',
1173 'owner-name', 'owner-link', 'owner-avatar'];
1174 $condition = ['uid' => $uid, 'guid' => $guid];
1175 $item = Post::selectFirst($fields, $condition);
1177 if (!DBA::isResult($item)) {
1178 $person = FContact::getByURL($author);
1179 $result = self::storeByGuid($guid, $person["url"], false);
1181 // We don't have an url for items that arrived at the public dispatcher
1182 if (!$result && !empty($contact["url"])) {
1183 $result = self::storeByGuid($guid, $contact["url"], false);
1187 Logger::info("Fetched missing item ".$guid." - result: ".$result);
1189 $item = Post::selectFirst($fields, $condition);
1193 if (!DBA::isResult($item)) {
1194 Logger::notice("parent item not found: parent: ".$guid." - user: ".$uid);
1197 Logger::notice("parent item found: parent: ".$guid." - user: ".$uid);
1203 * returns contact details
1205 * @param array $def_contact The default contact if the person isn't found
1206 * @param array $person The record of the person
1207 * @param int $uid The user id
1210 * 'cid' => contact id
1211 * 'network' => network type
1212 * @throws \Exception
1214 private static function authorContactByUrl(array $def_contact, array $person, int $uid): array
1216 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1217 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1218 if (DBA::isResult($contact)) {
1219 $cid = $contact["id"];
1220 $network = $contact["network"];
1222 $cid = $def_contact["id"];
1223 $network = Protocol::DIASPORA;
1226 return ["cid" => $cid, "network" => $network];
1230 * Is the profile a hubzilla profile?
1232 * @param string $url The profile link
1234 * @return bool is it a hubzilla server?
1236 private static function isHubzilla(string $url): bool
1238 return strstr($url, '/channel/');
1242 * Generate a post link with a given handle and message guid
1244 * @param string $addr The user handle
1245 * @param string $guid message guid
1246 * @param string $parent_guid optional parent guid
1248 * @return string the post link
1249 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1250 * @throws \ImagickException
1252 private static function plink(string $addr, string $guid, string $parent_guid = ''): string
1254 $contact = Contact::getByURL($addr);
1255 if (empty($contact)) {
1256 Logger::info('No contact data for address', ['addr' => $addr]);
1260 if (empty($contact['baseurl'])) {
1261 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1262 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1266 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1267 if (!empty($gserver['platform'])) {
1268 $platform = strtolower($gserver['platform']);
1269 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1272 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1273 if (self::isHubzilla($contact['url'])) {
1274 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1275 $platform = 'hubzilla';
1276 } elseif ($contact['network'] == Protocol::DFRN) {
1277 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1278 $platform = 'friendica';
1282 if ($platform == 'friendica') {
1283 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1286 if ($platform == 'hubzilla') {
1287 return $contact['baseurl'] . '/item/' . $guid;
1290 if ($platform == 'socialhome') {
1291 return $contact['baseurl'] . '/content/' . $guid;
1294 if ($platform != 'diaspora') {
1295 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1299 if ($parent_guid != '') {
1300 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1302 return $contact['baseurl'] . '/posts/' . $guid;
1307 * Receives account migration
1309 * @param array $importer Array of the importer user
1310 * @param object $data The message object
1312 * @return bool Success
1313 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1314 * @throws \ImagickException
1316 private static function receiveAccountMigration(array $importer, $data): bool
1318 // @TODO Need to find object type, roland@f.haeder.net
1319 Logger::debug('data='.get_class($data));
1320 $old_handle = XML::unescape($data->author);
1321 $new_handle = XML::unescape($data->profile->author);
1322 $signature = XML::unescape($data->signature);
1324 $contact = self::contactByHandle($importer["uid"], $old_handle);
1326 Logger::notice("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1330 Logger::notice("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1333 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1334 $key = self::key($old_handle);
1335 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1336 Logger::notice('No valid signature for migration.');
1340 // Update the profile
1341 self::receiveProfile($importer, $data->profile);
1343 // change the technical stuff in contact
1344 $data = Probe::uri($new_handle);
1345 if ($data['network'] == Protocol::PHANTOM) {
1346 Logger::notice('Account for '.$new_handle." couldn't be probed.");
1350 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1351 'name' => $data['name'], 'nick' => $data['nick'],
1352 'addr' => $data['addr'], 'batch' => $data['batch'],
1353 'notify' => $data['notify'], 'poll' => $data['poll'],
1354 'network' => $data['network']];
1356 Contact::update($fields, ['addr' => $old_handle]);
1358 Logger::notice('Contacts are updated.');
1364 * Processes an account deletion
1366 * @param object $data The message object
1368 * @return bool Success
1369 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1371 private static function receiveAccountDeletion($data): bool
1373 // @TODO Need to find object type, roland@f.haeder.net
1374 Logger::debug('data='.get_class($data));
1375 $author = XML::unescape($data->author);
1377 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1378 while ($contact = DBA::fetch($contacts)) {
1379 Contact::remove($contact["id"]);
1381 DBA::close($contacts);
1383 Logger::notice('Removed contacts for ' . $author);
1389 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1391 * @param string $author Author handle
1392 * @param string $guid Message guid
1393 * @param boolean $onlyfound Only return uri when found in the database
1395 * @return string The constructed uri or the one from our database or empty string on if $onlyfound is true
1396 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1397 * @throws \ImagickException
1399 private static function getUriFromGuid(string $author, string $guid, bool $onlyfound = false): string
1401 $item = Post::selectFirst(['uri'], ['guid' => $guid]);
1402 if (DBA::isResult($item)) {
1403 return $item["uri"];
1404 } elseif (!$onlyfound) {
1405 $person = FContact::getByURL($author);
1407 $parts = parse_url($person['url']);
1408 unset($parts['path']);
1409 $host_url = Network::unparseURL($parts);
1411 return $host_url . '/objects/' . $guid;
1418 * Store the mentions in the tag table
1420 * @param integer $uriid
1421 * @param string $text
1423 private static function storeMentions(int $uriid, string $text)
1425 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1426 if (empty($matches)) {
1431 * Matching values for the preg match
1432 * [1] = mention type (@ or !)
1433 * [2] = name (optional)
1437 foreach ($matches as $match) {
1438 if (empty($match)) {
1442 $person = FContact::getByURL($match[3]);
1443 if (empty($person)) {
1447 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1452 * Processes an incoming comment
1454 * @param array $importer Array of the importer user
1455 * @param string $sender The sender of the message
1456 * @param object $data The message object
1457 * @param string $xml The original XML of the message
1458 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1460 * @return int The message id of the generated comment or "false" if there was an error
1461 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1462 * @throws \ImagickException
1464 private static function receiveComment(array $importer, string $sender, $data, string $xml, int $direction): bool
1466 // @TODO Need to find object type, roland@f.haeder.net
1467 Logger::debug('data='.get_class($data));
1468 $author = XML::unescape($data->author);
1469 $guid = XML::unescape($data->guid);
1470 $parent_guid = XML::unescape($data->parent_guid);
1471 $text = XML::unescape($data->text);
1473 if (isset($data->created_at)) {
1474 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1476 $created_at = DateTimeFormat::utcNow();
1479 if (isset($data->thread_parent_guid)) {
1480 $thread_parent_guid = XML::unescape($data->thread_parent_guid);
1481 $thr_parent = self::getUriFromGuid("", $thread_parent_guid, true);
1486 $contact = self::allowedContactByHandle($importer, $sender, true);
1491 if (!empty($contact['gsid'])) {
1492 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1495 $message_id = self::messageExists($importer["uid"], $guid);
1500 $toplevel_parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1501 if (!$toplevel_parent_item) {
1505 $person = FContact::getByURL($author);
1506 if (!is_array($person)) {
1507 Logger::notice("unable to find author details");
1511 // Fetch the contact id - if we know this contact
1512 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1516 $datarray["uid"] = $importer["uid"];
1517 $datarray["contact-id"] = $author_contact["cid"];
1518 $datarray["network"] = $author_contact["network"];
1520 $datarray["author-link"] = $person["url"];
1521 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1523 $datarray["owner-link"] = $contact["url"];
1524 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1526 // Will be overwritten for sharing accounts in Item::insert
1527 if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
1528 $datarray["post-reason"] = Item::PR_FETCHED;
1529 } elseif ($datarray["uid"] == 0) {
1530 $datarray["post-reason"] = Item::PR_GLOBAL;
1532 $datarray["post-reason"] = Item::PR_COMMENT;
1535 $datarray["guid"] = $guid;
1536 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1537 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1539 $datarray["verb"] = Activity::POST;
1540 $datarray["gravity"] = GRAVITY_COMMENT;
1542 $datarray['thr-parent'] = $thr_parent ?: $toplevel_parent_item['uri'];
1544 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1545 $datarray["post-type"] = Item::PT_NOTE;
1547 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1548 $datarray["source"] = $xml;
1549 $datarray["direction"] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
1551 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1553 $datarray["plink"] = self::plink($author, $guid, $toplevel_parent_item['guid']);
1554 $body = Markdown::toBBCode($text);
1556 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1558 self::storeMentions($datarray['uri-id'], $text);
1559 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
1561 self::fetchGuid($datarray);
1563 // If we are the origin of the parent we store the original data.
1564 // We notify our followers during the item storage.
1565 if ($toplevel_parent_item["origin"]) {
1566 $datarray['diaspora_signed_text'] = json_encode($data);
1569 if (Item::isTooOld($datarray)) {
1570 Logger::info('Comment is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1574 $message_id = Item::insert($datarray);
1576 if ($message_id <= 0) {
1581 Logger::info("Stored comment ".$datarray["guid"]." with message id ".$message_id);
1582 if ($datarray['uid'] == 0) {
1583 Item::distribute($message_id, json_encode($data));
1591 * processes and stores private messages
1593 * @param array $importer Array of the importer user
1594 * @param array $contact The contact of the message
1595 * @param object $data The message object
1596 * @param array $msg Array of the processed message, author handle and key
1597 * @param object $mesg The private message
1598 * @param array $conversation The conversation record to which this message belongs
1600 * @return bool "true" if it was successful
1601 * @throws \Exception
1603 private static function receiveConversationMessage(array $importer, array $contact, $data, array $msg, $mesg, array $conversation): bool
1605 // @TODO Need to find object type, roland@f.haeder.net
1606 Logger::debug('data='.get_class($data).',mesg='.get_class($mesg));
1607 $author = XML::unescape($data->author);
1608 $guid = XML::unescape($data->guid);
1609 $subject = XML::unescape($data->subject);
1611 // "diaspora_handle" is the element name from the old version
1612 // "author" is the element name from the new version
1613 if ($mesg->author) {
1614 $msg_author = XML::unescape($mesg->author);
1615 } elseif ($mesg->diaspora_handle) {
1616 $msg_author = XML::unescape($mesg->diaspora_handle);
1621 $msg_guid = XML::unescape($mesg->guid);
1622 $msg_conversation_guid = XML::unescape($mesg->conversation_guid);
1623 $msg_text = XML::unescape($mesg->text);
1624 $msg_created_at = DateTimeFormat::utc(XML::unescape($mesg->created_at));
1626 if ($msg_conversation_guid != $guid) {
1627 Logger::notice("message conversation guid does not belong to the current conversation.");
1631 $body = Markdown::toBBCode($msg_text);
1632 $message_uri = $msg_author.":".$msg_guid;
1634 $person = FContact::getByURL($msg_author);
1636 return Mail::insert([
1637 'uid' => $importer['uid'],
1638 'guid' => $msg_guid,
1639 'convid' => $conversation['id'],
1640 'from-name' => $person['name'],
1641 'from-photo' => $person['photo'],
1642 'from-url' => $person['url'],
1643 'contact-id' => $contact['id'],
1644 'title' => $subject,
1646 'uri' => $message_uri,
1647 'parent-uri' => $author . ':' . $guid,
1648 'created' => $msg_created_at
1653 * Processes new private messages (answers to private messages are processed elsewhere)
1655 * @param array $importer Array of the importer user
1656 * @param array $msg Array of the processed message, author handle and key
1657 * @param object $data The message object
1659 * @return bool Success
1660 * @throws \Exception
1662 private static function receiveConversation(array $importer, array $msg, $data)
1664 // @TODO Need to find object type, roland@f.haeder.net
1665 Logger::debug('data='.get_class($data));
1666 $author = XML::unescape($data->author);
1667 $guid = XML::unescape($data->guid);
1668 $subject = XML::unescape($data->subject);
1669 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1670 $participants = XML::unescape($data->participants);
1672 $messages = $data->message;
1674 if (!count($messages)) {
1675 Logger::notice("empty conversation");
1679 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1684 if (!empty($contact['gsid'])) {
1685 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1688 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1689 if (!DBA::isResult($conversation)) {
1690 $r = DBA::insert('conv', [
1691 'uid' => $importer['uid'],
1693 'creator' => $author,
1694 'created' => $created_at,
1695 'updated' => DateTimeFormat::utcNow(),
1696 'subject' => $subject,
1697 'recips' => $participants]);
1699 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1702 if (!$conversation) {
1703 Logger::notice("unable to create conversation.");
1707 foreach ($messages as $mesg) {
1708 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1715 * Processes "like" messages
1717 * @param array $importer Array of the importer user
1718 * @param string $sender The sender of the message
1719 * @param object $data The message object
1720 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1722 * @return bool Success or failure
1723 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1724 * @throws \ImagickException
1726 private static function receiveLike(array $importer, string $sender, $data, int $direction): bool
1728 // @TODO Need to find object type, roland@f.haeder.net
1729 Logger::debug('data='.get_class($data));
1730 $author = XML::unescape($data->author);
1731 $guid = XML::unescape($data->guid);
1732 $parent_guid = XML::unescape($data->parent_guid);
1733 $parent_type = XML::unescape($data->parent_type);
1734 $positive = XML::unescape($data->positive);
1736 // likes on comments aren't supported by Diaspora - only on posts
1737 // But maybe this will be supported in the future, so we will accept it.
1738 if (!in_array($parent_type, ["Post", "Comment"])) {
1742 $contact = self::allowedContactByHandle($importer, $sender, true);
1747 if (!empty($contact['gsid'])) {
1748 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1751 $message_id = self::messageExists($importer["uid"], $guid);
1756 $toplevel_parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1757 if (!$toplevel_parent_item) {
1761 $person = FContact::getByURL($author);
1762 if (!is_array($person)) {
1763 Logger::notice("unable to find author details");
1767 // Fetch the contact id - if we know this contact
1768 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1770 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1771 // We would accept this anyhow.
1772 if ($positive == "true") {
1773 $verb = Activity::LIKE;
1775 $verb = Activity::DISLIKE;
1780 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1781 $datarray["direction"] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
1783 $datarray["uid"] = $importer["uid"];
1784 $datarray["contact-id"] = $author_contact["cid"];
1785 $datarray["network"] = $author_contact["network"];
1787 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
1788 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1790 $datarray["guid"] = $guid;
1791 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1793 $datarray["verb"] = $verb;
1794 $datarray["gravity"] = GRAVITY_ACTIVITY;
1795 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1797 $datarray["object-type"] = Activity\ObjectType::NOTE;
1799 $datarray["body"] = $verb;
1801 // Diaspora doesn't provide a date for likes
1802 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
1804 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1805 if ($toplevel_parent_item['gravity'] != GRAVITY_PARENT) {
1806 $toplevel = Post::selectFirst(['origin'], ['id' => $toplevel_parent_item['parent']]);
1807 $origin = $toplevel["origin"];
1809 $origin = $toplevel_parent_item["origin"];
1812 // If we are the origin of the parent we store the original data.
1813 // We notify our followers during the item storage.
1815 $datarray['diaspora_signed_text'] = json_encode($data);
1818 if (Item::isTooOld($datarray)) {
1819 Logger::info('Like is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1823 $message_id = Item::insert($datarray);
1825 if ($message_id <= 0) {
1830 Logger::info("Stored like ".$datarray["guid"]." with message id ".$message_id);
1831 if ($datarray['uid'] == 0) {
1832 Item::distribute($message_id, json_encode($data));
1840 * Processes private messages
1842 * @param array $importer Array of the importer user
1843 * @param object $data The message object
1845 * @return bool Success?
1846 * @throws \Exception
1848 private static function receiveMessage(array $importer, $data): bool
1850 // @TODO Need to find object type, roland@f.haeder.net
1851 Logger::debug('data='.get_class($data));
1852 $author = XML::unescape($data->author);
1853 $guid = XML::unescape($data->guid);
1854 $conversation_guid = XML::unescape($data->conversation_guid);
1855 $text = XML::unescape($data->text);
1856 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1858 $contact = self::allowedContactByHandle($importer, $author, true);
1863 if (!empty($contact['gsid'])) {
1864 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1867 $conversation = null;
1869 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
1870 $conversation = DBA::selectFirst('conv', [], $condition);
1872 if (!DBA::isResult($conversation)) {
1873 Logger::notice("conversation not available.");
1877 $message_uri = $author.":".$guid;
1879 $person = FContact::getByURL($author);
1881 Logger::notice("unable to find author details");
1885 $body = Markdown::toBBCode($text);
1887 $body = self::replacePeopleGuid($body, $person["url"]);
1889 return Mail::insert([
1890 'uid' => $importer['uid'],
1892 'convid' => $conversation['id'],
1893 'from-name' => $person['name'],
1894 'from-photo' => $person['photo'],
1895 'from-url' => $person['url'],
1896 'contact-id' => $contact['id'],
1897 'title' => $conversation['subject'],
1900 'uri' => $message_uri,
1901 'parent-uri' => $author.":".$conversation['guid'],
1902 'created' => $created_at
1907 * Processes participations - unsupported by now
1909 * @param array $importer Array of the importer user
1910 * @param object $data The message object
1911 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1913 * @return bool success
1914 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1915 * @throws \ImagickException
1917 private static function receiveParticipation(array $importer, $data, int $direction): bool
1919 // @TODO Need to find object type, roland@f.haeder.net
1920 Logger::debug('data='.get_class($data));
1921 $author = strtolower(XML::unescape($data->author));
1922 $guid = XML::unescape($data->guid);
1923 $parent_guid = XML::unescape($data->parent_guid);
1925 $contact = self::allowedContactByHandle($importer, $author, true);
1930 if (!empty($contact['gsid'])) {
1931 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1934 if (self::messageExists($importer["uid"], $guid)) {
1938 $toplevel_parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1939 if (!$toplevel_parent_item) {
1943 if (!$toplevel_parent_item['origin']) {
1944 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1947 if (!in_array($toplevel_parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
1948 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1952 $person = FContact::getByURL($author);
1953 if (!is_array($person)) {
1954 Logger::notice("Person not found: ".$author);
1958 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1960 // Store participation
1963 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1964 $datarray["direction"] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
1966 $datarray["uid"] = $importer["uid"];
1967 $datarray["contact-id"] = $author_contact["cid"];
1968 $datarray["network"] = $author_contact["network"];
1970 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
1971 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1973 $datarray["guid"] = $guid;
1974 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1976 $datarray["verb"] = Activity::FOLLOW;
1977 $datarray["gravity"] = GRAVITY_ACTIVITY;
1978 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1980 $datarray["object-type"] = Activity\ObjectType::NOTE;
1982 $datarray["body"] = Activity::FOLLOW;
1984 // Diaspora doesn't provide a date for a participation
1985 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
1987 if (Item::isTooOld($datarray)) {
1988 Logger::info('Participation is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1992 $message_id = Item::insert($datarray);
1994 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
1996 // Send all existing comments and likes to the requesting server
1997 $comments = Post::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb'],
1998 ['parent' => $toplevel_parent_item['id'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
1999 while ($comment = Post::fetch($comments)) {
2000 if (in_array($comment['verb'], [Activity::FOLLOW, Activity::TAG])) {
2001 Logger::info('participation messages are not relayed', ['item' => $comment['id']]);
2005 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
2006 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2010 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
2011 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2015 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact["cid"]]);
2016 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $author_contact["cid"])) {
2017 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2020 DBA::close($comments);
2026 * Processes photos - unneeded
2028 * @param array $importer Array of the importer user
2029 * @param object $data The message object
2031 * @return bool always true
2033 private static function receivePhoto(array $importer, $data)
2035 // There doesn't seem to be a reason for this function,
2036 // since the photo data is transmitted in the status message as well
2041 * Processes poll participations - unssupported
2043 * @param array $importer Array of the importer user
2044 * @param object $data The message object
2046 * @return bool always true
2048 private static function receivePollParticipation(array $importer, $data)
2050 // We don't support polls by now
2055 * Processes incoming profile updates
2057 * @param array $importer Array of the importer user
2058 * @param object $data The message object
2060 * @return bool Success
2061 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2062 * @throws \ImagickException
2064 private static function receiveProfile(array $importer, $data): bool
2066 // @TODO Need to find object type, roland@f.haeder.net
2067 Logger::debug('data='.get_class($data));
2068 $author = strtolower(XML::unescape($data->author));
2070 $contact = self::contactByHandle($importer["uid"], $author);
2075 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2076 $image_url = XML::unescape($data->image_url);
2077 $birthday = XML::unescape($data->birthday);
2078 $about = Markdown::toBBCode(XML::unescape($data->bio));
2079 $location = Markdown::toBBCode(XML::unescape($data->location));
2080 $searchable = (XML::unescape($data->searchable) == "true");
2081 $nsfw = (XML::unescape($data->nsfw) == "true");
2082 $tags = XML::unescape($data->tag_string);
2084 $tags = explode("#", $tags);
2087 foreach ($tags as $tag) {
2088 $tag = trim(strtolower($tag));
2094 $keywords = implode(", ", $keywords);
2096 $handle_parts = explode("@", $author);
2097 $nick = $handle_parts[0];
2100 $name = $handle_parts[0];
2103 if (preg_match("|^https?://|", $image_url) === 0) {
2104 $image_url = "http://".$handle_parts[1].$image_url;
2107 Contact::updateAvatar($contact["id"], $image_url);
2109 // Generic birthday. We don't know the timezone. The year is irrelevant.
2111 $birthday = str_replace("1000", "1901", $birthday);
2113 if ($birthday != "") {
2114 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2117 // this is to prevent multiple birthday notifications in a single year
2118 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2120 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2121 $birthday = $contact["bd"];
2124 $fields = ['name' => $name, 'location' => $location,
2125 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2126 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2127 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2129 if (!empty($birthday)) {
2130 $fields['bd'] = $birthday;
2133 Contact::update($fields, ['id' => $contact['id']]);
2135 Logger::info("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"]);
2141 * Processes incoming friend requests
2143 * @param array $importer Array of the importer user
2144 * @param array $contact The contact that send the request
2146 * @throws \Exception
2148 private static function receiveRequestMakeFriend(array $importer, array $contact)
2150 if ($contact["rel"] == Contact::SHARING) {
2152 ['rel' => Contact::FRIEND, 'writable' => true],
2153 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2159 * Processes incoming sharing notification
2161 * @param array $importer Array of the importer user
2162 * @param object $data The message object
2164 * @return bool Success
2165 * @throws \Exception
2167 private static function receiveContactRequest(array $importer, $data): bool
2169 // @TODO Need to find object type, roland@f.haeder.net
2170 Logger::debug('data='.get_class($data));
2171 $author = XML::unescape($data->author);
2172 $recipient = XML::unescape($data->recipient);
2174 if (!$author || !$recipient) {
2178 // the current protocol version doesn't know these fields
2179 // That means that we will assume their existance
2180 if (isset($data->following)) {
2181 $following = (XML::unescape($data->following) == "true");
2186 if (isset($data->sharing)) {
2187 $sharing = (XML::unescape($data->sharing) == "true");
2192 $contact = self::contactByHandle($importer["uid"], $author);
2194 // perhaps we were already sharing with this person. Now they're sharing with us.
2195 // That makes us friends.
2198 Logger::info("Author ".$author." (Contact ".$contact["id"].") wants to follow us.");
2199 self::receiveRequestMakeFriend($importer, $contact);
2201 // refetch the contact array
2202 $contact = self::contactByHandle($importer["uid"], $author);
2204 // If we are now friends, we are sending a share message.
2205 // Normally we needn't to do so, but the first message could have been vanished.
2206 if (in_array($contact["rel"], [Contact::FRIEND])) {
2207 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2208 if (DBA::isResult($user)) {
2209 Logger::info("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"]);
2210 self::sendShare($user, $contact);
2215 Logger::info("Author ".$author." doesn't want to follow us anymore.");
2216 Contact::removeFollower($contact);
2221 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2222 Logger::info("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.");
2224 } elseif (!$following && !$sharing) {
2225 Logger::info("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.");
2227 } elseif (!$following && $sharing) {
2228 Logger::info("Author ".$author." wants to share with us.");
2229 } elseif ($following && $sharing) {
2230 Logger::info("Author ".$author." wants to have a bidirectional conection.");
2231 } elseif ($following && !$sharing) {
2232 Logger::info("Author ".$author." wants to listen to us.");
2235 $ret = FContact::getByURL($author);
2237 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2238 Logger::notice("Cannot resolve diaspora handle ".$author." for ".$recipient);
2242 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2244 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2249 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2250 'author-link' => $ret['url']];
2252 $result = Contact::addRelationship($importer, $contact, $item, false);
2253 if ($result === true) {
2254 $contact_record = self::contactByHandle($importer['uid'], $author);
2255 if (!$contact_record) {
2256 Logger::info('unable to locate newly created contact record.');
2260 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2261 if (DBA::isResult($user)) {
2262 self::sendShare($user, $contact_record);
2264 // Send the profile data, maybe it weren't transmitted before
2265 self::sendProfile($importer['uid'], [$contact_record]);
2273 * Fetches a message with a given guid
2275 * @param string $guid message guid
2276 * @param string $orig_author handle of the original post
2277 * @return array|bool The fetched item or false on failure
2278 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2279 * @throws \ImagickException
2281 public static function originalItem(string $guid, string $orig_author)
2284 Logger::notice('Empty guid. Quitting.');
2288 // Do we already have this item?
2289 $fields = ['body', 'title', 'app', 'created', 'object-type', 'uri', 'guid',
2290 'author-name', 'author-link', 'author-avatar', 'plink', 'uri-id'];
2291 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2292 $item = Post::selectFirst($fields, $condition);
2294 if (DBA::isResult($item)) {
2295 Logger::notice("reshared message ".$guid." already exists on system.");
2297 // Maybe it is already a reshared item?
2298 // Then refetch the content, if it is a reshare from a reshare.
2299 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2300 if (self::isReshare($item["body"], true)) {
2302 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2303 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2305 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2313 if (!DBA::isResult($item)) {
2314 if (empty($orig_author)) {
2315 Logger::notice('Empty author for guid ' . $guid . '. Quitting.');
2319 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2320 Logger::notice("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2321 $stored = self::storeByGuid($guid, $server, true);
2324 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2325 Logger::notice("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2326 $stored = self::storeByGuid($guid, $server, true);
2330 $fields = ['body', 'title', 'app', 'created', 'object-type', 'uri', 'guid',
2331 'author-name', 'author-link', 'author-avatar', 'plink', 'uri-id'];
2332 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2333 $item = Post::selectFirst($fields, $condition);
2335 if (DBA::isResult($item)) {
2336 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2337 if (self::isReshare($item["body"], false)) {
2338 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2339 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2350 * Stores a reshare activity
2352 * @param array $item Array of reshare post
2353 * @param integer $parent_message_id Id of the parent post
2354 * @param string $guid GUID string of reshare action
2355 * @param string $author Author handle
2357 private static function addReshareActivity(array $item, int $parent_message_id, string $guid, string $author)
2359 $parent = Post::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2363 $datarray['uid'] = $item['uid'];
2364 $datarray['contact-id'] = $item['contact-id'];
2365 $datarray['network'] = $item['network'];
2367 $datarray['author-link'] = $item['author-link'];
2368 $datarray['author-id'] = $item['author-id'];
2370 $datarray['owner-link'] = $datarray['author-link'];
2371 $datarray['owner-id'] = $datarray['author-id'];
2373 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2374 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2375 $datarray['thr-parent'] = $parent['uri'];
2377 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2378 $datarray['gravity'] = GRAVITY_ACTIVITY;
2379 $datarray['object-type'] = Activity\ObjectType::NOTE;
2381 $datarray['protocol'] = $item['protocol'];
2382 $datarray['source'] = $item['source'];
2383 $datarray['direction'] = $item['direction'];
2385 $datarray['plink'] = self::plink($author, $datarray['guid']);
2386 $datarray['private'] = $item['private'];
2387 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2389 if (Item::isTooOld($datarray)) {
2390 Logger::info('Reshare activity is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2394 $message_id = Item::insert($datarray);
2397 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2398 if ($datarray['uid'] == 0) {
2399 Item::distribute($message_id);
2405 * Processes a reshare message
2407 * @param array $importer Array of the importer user
2408 * @param object $data The message object
2409 * @param string $xml The original XML of the message
2410 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2412 * @return bool Success or failure
2413 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2414 * @throws \ImagickException
2416 private static function receiveReshare(array $importer, $data, string $xml, int $direction): bool
2418 // @TODO Need to find object type, roland@f.haeder.net
2419 Logger::debug('data='.get_class($data));
2420 $author = XML::unescape($data->author);
2421 $guid = XML::unescape($data->guid);
2422 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2423 $root_author = XML::unescape($data->root_author);
2424 $root_guid = XML::unescape($data->root_guid);
2425 /// @todo handle unprocessed property "provider_display_name"
2426 $public = XML::unescape($data->public);
2428 $contact = self::allowedContactByHandle($importer, $author, false);
2433 if (!empty($contact['gsid'])) {
2434 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2437 $message_id = self::messageExists($importer["uid"], $guid);
2442 $original_item = self::originalItem($root_guid, $root_author);
2443 if (!$original_item) {
2447 if (empty($original_item['plink'])) {
2448 $original_item['plink'] = self::plink($root_author, $root_guid);
2453 $datarray["uid"] = $importer["uid"];
2454 $datarray["contact-id"] = $contact["id"];
2455 $datarray["network"] = Protocol::DIASPORA;
2457 $datarray["author-link"] = $contact["url"];
2458 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2460 $datarray["owner-link"] = $datarray["author-link"];
2461 $datarray["owner-id"] = $datarray["author-id"];
2463 $datarray["guid"] = $guid;
2464 $datarray["uri"] = $datarray["thr-parent"] = self::getUriFromGuid($author, $guid);
2465 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2467 $datarray["verb"] = Activity::POST;
2468 $datarray["gravity"] = GRAVITY_PARENT;
2470 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2471 $datarray["source"] = $xml;
2472 $datarray["direction"] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
2474 /// @todo Copy tag data from original post
2476 $prefix = BBCode::getShareOpeningTag(
2477 $original_item["author-name"],
2478 $original_item["author-link"],
2479 $original_item["author-avatar"],
2480 $original_item["plink"],
2481 $original_item["created"],
2482 $original_item["guid"]
2485 if (!empty($original_item['title'])) {
2486 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2489 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2491 Tag::storeFromBody($datarray['uri-id'], $datarray["body"]);
2493 $datarray["app"] = $original_item["app"];
2495 $datarray["plink"] = self::plink($author, $guid);
2496 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2497 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2499 $datarray["object-type"] = $original_item["object-type"];
2501 self::fetchGuid($datarray);
2503 if (Item::isTooOld($datarray)) {
2504 Logger::info('Reshare is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2508 $message_id = Item::insert($datarray);
2510 self::sendParticipation($contact, $datarray);
2512 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2513 if ($root_message_id) {
2514 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2518 Logger::info("Stored reshare ".$datarray["guid"]." with message id ".$message_id);
2519 if ($datarray['uid'] == 0) {
2520 Item::distribute($message_id);
2529 * Processes retractions
2531 * @param array $importer Array of the importer user
2532 * @param array $contact The contact of the item owner
2533 * @param object $data The message object
2535 * @return bool success
2536 * @throws \Exception
2538 private static function itemRetraction(array $importer, array $contact, $data): bool
2540 // @TODO Need to find object type, roland@f.haeder.net
2541 Logger::debug('data='.get_class($data));
2542 $author = XML::unescape($data->author);
2543 $target_guid = XML::unescape($data->target_guid);
2544 $target_type = XML::unescape($data->target_type);
2546 $person = FContact::getByURL($author);
2547 if (!is_array($person)) {
2548 Logger::notice("unable to find author detail for ".$author);
2552 if (empty($contact["url"])) {
2553 $contact["url"] = $person["url"];
2556 // Fetch items that are about to be deleted
2557 $fields = ['uid', 'id', 'parent', 'author-link', 'uri-id'];
2559 // When we receive a public retraction, we delete every item that we find.
2560 if ($importer['uid'] == 0) {
2561 $condition = ['guid' => $target_guid, 'deleted' => false];
2563 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2566 $r = Post::select($fields, $condition);
2567 if (!DBA::isResult($r)) {
2568 Logger::notice("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2572 while ($item = Post::fetch($r)) {
2573 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2574 Logger::info("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.");
2578 // Fetch the parent item
2579 $parent = Post::selectFirst(['author-link'], ['id' => $item['parent']]);
2581 // Only delete it if the parent author really fits
2582 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2583 Logger::info("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"]);
2587 Item::markForDeletion(['id' => $item['id']]);
2589 Logger::info("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item['parent']);
2597 * Receives retraction messages
2599 * @param array $importer Array of the importer user
2600 * @param string $sender The sender of the message
2601 * @param object $data The message object
2603 * @return bool Success
2604 * @throws \Exception
2606 private static function receiveRetraction(array $importer, string $sender, $data)
2608 // @TODO Need to find object type, roland@f.haeder.net
2609 Logger::debug('data='.get_class($data));
2610 $target_type = XML::unescape($data->target_type);
2612 $contact = self::contactByHandle($importer["uid"], $sender);
2613 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2614 Logger::notice("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2622 Logger::info("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"]);
2624 switch ($target_type) {
2629 case "StatusMessage":
2630 return self::itemRetraction($importer, $contact, $data);
2632 case "PollParticipation":
2634 // Currently unsupported
2638 Logger::notice("Unknown target type ".$target_type);
2645 * Checks if an incoming message is wanted
2647 * @param array $item
2648 * @param string $author
2649 * @param string $body
2650 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2652 * @return boolean Is the message wanted?
2654 private static function isSolicitedMessage(array $item, string $author, string $body, int $direction): bool
2656 $contact = Contact::getByURL($author);
2657 if (DBA::exists('contact', ["`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)",
2658 $contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) {
2659 Logger::debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2663 if ($direction == self::FORCED_FETCH) {
2664 Logger::debug('Post is a forced fetch - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2668 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
2669 if (Relay::isSolicitedPost($tags, $body, $contact['id'], $item['uri'], Protocol::DIASPORA)) {
2670 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2678 * Store an attached photo in the post-media table
2681 * @param object $photo
2684 private static function storePhotoAsMedia(int $uriid, $photo)
2686 // @TODO Need to find object type, roland@f.haeder.net
2687 Logger::debug('photo='.get_class($photo));
2689 $data['uri-id'] = $uriid;
2690 $data['type'] = Post\Media::IMAGE;
2691 $data['url'] = XML::unescape($photo->remote_photo_path) . XML::unescape($photo->remote_photo_name);
2692 $data['height'] = (int)XML::unescape($photo->height ?? 0);
2693 $data['width'] = (int)XML::unescape($photo->width ?? 0);
2694 $data['description'] = XML::unescape($photo->text ?? '');
2696 Post\Media::insert($data);
2700 * Receives status messages
2702 * @param array $importer Array of the importer user
2703 * @param SimpleXMLElement $data The message object
2704 * @param string $xml The original XML of the message
2705 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2707 * @return int|bool The message id of the newly created item or false on error
2708 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2709 * @throws \ImagickException
2711 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, string $xml, int $direction)
2713 $author = XML::unescape($data->author);
2714 $guid = XML::unescape($data->guid);
2715 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2716 $public = XML::unescape($data->public);
2717 $text = XML::unescape($data->text);
2718 $provider_display_name = XML::unescape($data->provider_display_name);
2720 $contact = self::allowedContactByHandle($importer, $author, false);
2725 if (!empty($contact['gsid'])) {
2726 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2729 $message_id = self::messageExists($importer["uid"], $guid);
2735 if ($data->location) {
2736 foreach ($data->location->children() as $fieldname => $data) {
2737 $address[$fieldname] = XML::unescape($data);
2741 $raw_body = $body = Markdown::toBBCode($text);
2745 $datarray["guid"] = $guid;
2746 $datarray["uri"] = $datarray["thr-parent"] = self::getUriFromGuid($author, $guid);
2747 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2749 // Attach embedded pictures to the body
2751 foreach ($data->photo as $photo) {
2752 self::storePhotoAsMedia($datarray['uri-id'], $photo);
2755 $datarray["object-type"] = Activity\ObjectType::IMAGE;
2756 $datarray["post-type"] = Item::PT_IMAGE;
2757 } elseif ($data->poll) {
2758 $datarray["object-type"] = Activity\ObjectType::NOTE;
2759 $datarray["post-type"] = Item::PT_POLL;
2761 $datarray["object-type"] = Activity\ObjectType::NOTE;
2762 $datarray["post-type"] = Item::PT_NOTE;
2765 /// @todo enable support for polls
2766 //if ($data->poll) {
2767 // foreach ($data->poll as $poll)
2772 /// @todo enable support for events
2774 $datarray["uid"] = $importer["uid"];
2775 $datarray["contact-id"] = $contact["id"];
2776 $datarray["network"] = Protocol::DIASPORA;
2778 $datarray["author-link"] = $contact["url"];
2779 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2781 $datarray["owner-link"] = $datarray["author-link"];
2782 $datarray["owner-id"] = $datarray["author-id"];
2784 $datarray["verb"] = Activity::POST;
2785 $datarray["gravity"] = GRAVITY_PARENT;
2787 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2788 $datarray["source"] = $xml;
2789 $datarray["direction"] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
2791 if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
2792 $datarray["post-reason"] = Item::PR_FETCHED;
2793 } elseif ($datarray["uid"] == 0) {
2794 $datarray["post-reason"] = Item::PR_GLOBAL;
2797 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2798 $datarray["raw-body"] = self::replacePeopleGuid($raw_body, $contact["url"]);
2800 self::storeMentions($datarray['uri-id'], $text);
2801 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
2803 if (!self::isSolicitedMessage($datarray, $author, $body, $direction)) {
2804 DBA::delete('item-uri', ['uri' => $datarray['uri']]);
2808 if ($provider_display_name != "") {
2809 $datarray["app"] = $provider_display_name;
2812 $datarray["plink"] = self::plink($author, $guid);
2813 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2814 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2816 if (isset($address["address"])) {
2817 $datarray["location"] = $address["address"];
2820 if (isset($address["lat"]) && isset($address["lng"])) {
2821 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2824 self::fetchGuid($datarray);
2826 if (Item::isTooOld($datarray)) {
2827 Logger::info('Status is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2831 $message_id = Item::insert($datarray);
2833 self::sendParticipation($contact, $datarray);
2836 Logger::info("Stored item ".$datarray["guid"]." with message id ".$message_id);
2837 if ($datarray['uid'] == 0) {
2838 Item::distribute($message_id);
2846 /* ************************************************************************************** *
2847 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2848 * ************************************************************************************** */
2851 * returnes the handle of a contact
2853 * @param array $contact contact array
2855 * @return string the handle in the format user@domain.tld
2856 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2858 private static function myHandle(array $contact): string
2860 if (!empty($contact["addr"])) {
2861 return $contact["addr"];
2864 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2865 // So - just in case - we build the the address here.
2866 if ($contact["nickname"] != "") {
2867 $nick = $contact["nickname"];
2869 $nick = $contact["nick"];
2872 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
2877 * Creates the data for a private message in the new format
2879 * @param string $msg The message that is to be transmitted
2880 * @param array $user The record of the sender
2881 * @param array $contact Target of the communication
2882 * @param string $prvkey The private key of the sender
2883 * @param string $pubkey The public key of the receiver
2885 * @return string The encrypted data
2886 * @throws \Exception
2888 public static function encodePrivateData(string $msg, array $user, array $contact, string $prvkey, string $pubkey): string
2890 Logger::debug("Message: ".$msg);
2892 // without a public key nothing will work
2894 Logger::notice("pubkey missing: contact id: ".$contact["id"]);
2898 $aes_key = random_bytes(32);
2899 $b_aes_key = base64_encode($aes_key);
2900 $iv = random_bytes(16);
2901 $b_iv = base64_encode($iv);
2903 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2905 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
2907 $encrypted_key_bundle = "";
2908 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
2912 $json_object = json_encode(
2913 ["aes_key" => base64_encode($encrypted_key_bundle),
2914 "encrypted_magic_envelope" => base64_encode($ciphertext)]
2917 return $json_object;
2921 * Creates the envelope for the "fetch" endpoint and for the new format
2923 * @param string $msg The message that is to be transmitted
2924 * @param array $user The record of the sender
2926 * @return string The envelope
2927 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2929 public static function buildMagicEnvelope(string $msg, array $user): string
2931 $b64url_data = Strings::base64UrlEncode($msg);
2932 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
2934 $key_id = Strings::base64UrlEncode(self::myHandle($user));
2935 $type = "application/xml";
2936 $encoding = "base64url";
2937 $alg = "RSA-SHA256";
2938 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
2940 // Fallback if the private key wasn't transmitted in the expected field
2941 if ($user['uprvkey'] == "") {
2942 $user['uprvkey'] = $user['prvkey'];
2945 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
2946 $sig = Strings::base64UrlEncode($signature);
2948 $xmldata = ["me:env" => ["me:data" => $data,
2949 "@attributes" => ["type" => $type],
2950 "me:encoding" => $encoding,
2953 "@attributes2" => ["key_id" => $key_id]]];
2955 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
2957 return XML::fromArray($xmldata, $xml, false, $namespaces);
2961 * Create the envelope for a message
2963 * @param string $msg The message that is to be transmitted
2964 * @param array $user The record of the sender
2965 * @param array $contact Target of the communication
2966 * @param string $prvkey The private key of the sender
2967 * @param string $pubkey The public key of the receiver
2968 * @param bool $public Is the message public?
2970 * @return string The message that will be transmitted to other servers
2971 * @throws \Exception
2973 public static function buildMessage(string $msg, array $user, array $contact, string $prvkey, string $pubkey, bool $public = false): string
2975 // The message is put into an envelope with the sender's signature
2976 $envelope = self::buildMagicEnvelope($msg, $user);
2978 // Private messages are put into a second envelope, encrypted with the receivers public key
2980 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
2987 * Creates a signature for a message
2989 * @param array $owner the array of the owner of the message
2990 * @param array $message The message that is to be signed
2992 * @return string The signature
2994 private static function signature(array $owner, array $message): string
2997 unset($sigmsg["author_signature"]);
2998 unset($sigmsg["parent_author_signature"]);
3000 $signed_text = implode(";", $sigmsg);
3002 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3006 * Transmit a message to a target server
3008 * @param array $owner the array of the item owner
3009 * @param array $contact Target of the communication
3010 * @param string $envelope The message that is to be transmitted
3011 * @param bool $public_batch Is it a public post?
3012 * @param string $guid message guid
3014 * @return int Result of the transmission
3015 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3016 * @throws \ImagickException
3018 private static function transmit(array $owner, array $contact, string $envelope, bool $public_batch, string $guid = ""): int
3020 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
3025 $logid = Strings::getRandomHex(4);
3027 // We always try to use the data from the fcontact table.
3028 // This is important for transmitting data to Friendica servers.
3029 if (!empty($contact['addr'])) {
3030 $fcontact = FContact::getByURL($contact['addr']);
3031 if (!empty($fcontact)) {
3032 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3036 if (empty($dest_url)) {
3037 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3041 Logger::notice("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3045 Logger::notice("transmit: ".$logid."-".$guid." ".$dest_url);
3047 if (!intval(DI::config()->get("system", "diaspora_test"))) {
3048 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3050 $postResult = DI::httpClient()->post($dest_url . "/", $envelope, ['Content-Type' => $content_type]);
3051 $return_code = $postResult->getReturnCode();
3053 Logger::notice("test_mode");
3057 Logger::notice("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3059 return $return_code ? $return_code : -1;
3064 * Build the post xml
3066 * @param string $type The message type
3067 * @param array $message The message data
3069 * @return string The post XML
3071 public static function buildPostXml(string $type, array $message): string
3073 $data = [$type => $message];
3075 return XML::fromArray($data, $xml);
3079 * Builds and transmit messages
3081 * @param array $owner the array of the item owner
3082 * @param array $contact Target of the communication
3083 * @param string $type The message type
3084 * @param array $message The message data
3085 * @param bool $public_batch Is it a public post?
3086 * @param string $guid message guid
3088 * @return int Result of the transmission
3089 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3090 * @throws \ImagickException
3092 private static function buildAndTransmit(array $owner, array $contact, string $type, array $message, bool $public_batch = false, string $guid = "")
3094 $msg = self::buildPostXml($type, $message);
3096 // Fallback if the private key wasn't transmitted in the expected field
3097 if (empty($owner['uprvkey'])) {
3098 $owner['uprvkey'] = $owner['prvkey'];
3101 // When sending content to Friendica contacts using the Diaspora protocol
3102 // we have to fetch the public key from the fcontact.
3103 // This is due to the fact that legacy DFRN had unique keys for every contact.
3104 $pubkey = $contact['pubkey'];
3105 if (!empty($contact['addr'])) {
3106 $fcontact = FContact::getByURL($contact['addr']);
3107 if (!empty($fcontact)) {
3108 $pubkey = $fcontact['pubkey'];
3111 // The "addr" field should always be filled.
3112 // If this isn't the case, it will raise a notice some lines later.
3113 // And in the log we will see where it came from and we can handle it there.
3114 Logger::notice('Empty addr', ['contact' => $contact ?? [], 'callstack' => System::callstack(20)]);
3117 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
3119 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3121 Logger::info('Transmitted message', ['owner' => $owner['uid'], 'target' => $contact['addr'], 'type' => $type, 'guid' => $guid, 'result' => $return_code]);
3123 return $return_code;
3127 * sends a participation (Used to get all further updates)
3129 * @param array $contact Target of the communication
3130 * @param array $item Item array
3132 * @return int The result of the transmission
3133 * @throws \Exception
3135 private static function sendParticipation(array $contact, array $item): int
3137 // Don't send notifications for private postings
3138 if ($item['private'] == Item::PRIVATE) {
3142 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3144 $result = DI::cache()->get($cachekey);
3145 if (!is_null($result)) {
3149 // Fetch some user id to have a valid handle to transmit the participation.
3150 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3151 // If the item belongs to a user, we take this user id.
3152 if ($item['uid'] == 0) {
3153 // @todo Possibly use an administrator account?
3154 $condition = ['verified' => true, 'blocked' => false,
3155 'account_removed' => false, 'account_expired' => false, 'account-type' => User::ACCOUNT_TYPE_PERSON];
3156 $first_user = DBA::selectFirst('user', ['uid'], $condition, ['order' => ['uid']]);
3157 $owner = User::getOwnerDataById($first_user['uid']);
3159 $owner = User::getOwnerDataById($item['uid']);
3162 $author = self::myHandle($owner);
3164 $message = ["author" => $author,
3165 "guid" => System::createUUID(),
3166 "parent_type" => "Post",
3167 "parent_guid" => $item["guid"]];
3169 Logger::info("Send participation for ".$item["guid"]." by ".$author);
3171 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3172 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3174 return self::buildAndTransmit($owner, $contact, "participation", $message);
3178 * sends an account migration
3180 * @param array $owner the array of the item owner
3181 * @param array $contact Target of the communication
3182 * @param int $uid User ID
3184 * @return int The result of the transmission
3185 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3186 * @throws \ImagickException
3188 public static function sendAccountMigration(array $owner, array $contact, int $uid): int
3190 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3191 $profile = self::createProfileData($uid);
3193 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3194 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3196 $message = ["author" => $old_handle,
3197 "profile" => $profile,
3198 "signature" => $signature];
3200 Logger::info('Send account migration', ['msg' => $message]);
3202 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3206 * Sends a "share" message
3208 * @param array $owner the array of the item owner
3209 * @param array $contact Target of the communication
3211 * @return int The result of the transmission
3212 * @throws \Exception
3214 public static function sendShare(array $owner, array $contact): int
3217 * @todo support the different possible combinations of "following" and "sharing"
3218 * Currently, Diaspora only interprets the "sharing" field
3220 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3224 switch ($contact["rel"]) {
3225 case Contact::FRIEND:
3229 case Contact::SHARING:
3233 case Contact::FOLLOWER:
3239 $message = ["author" => self::myHandle($owner),
3240 "recipient" => $contact["addr"],
3241 "following" => "true",
3242 "sharing" => "true"];
3244 Logger::info('Send share', ['msg' => $message]);
3246 return self::buildAndTransmit($owner, $contact, "contact", $message);
3250 * sends an "unshare"
3252 * @param array $owner the array of the item owner
3253 * @param array $contact Target of the communication
3255 * @return int The result of the transmission
3256 * @throws \Exception
3258 public static function sendUnshare(array $owner, array $contact): int
3260 $message = ["author" => self::myHandle($owner),
3261 "recipient" => $contact["addr"],
3262 "following" => "false",
3263 "sharing" => "false"];
3265 Logger::info('Send unshare', ['msg' => $message]);
3267 return self::buildAndTransmit($owner, $contact, "contact", $message);
3271 * Checks a message body if it is a reshare
3273 * @param string $body The message body that is to be check
3274 * @param bool $complete Should it be a complete check or a simple check?
3276 * @return array|bool Reshare details or "false" if no reshare
3277 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3278 * @throws \ImagickException
3280 public static function isReshare(string $body, bool $complete = true)
3282 $body = trim($body);
3284 $reshared = Item::getShareArray(['body' => $body]);
3285 if (empty($reshared)) {
3289 // Skip if it isn't a pure repeated messages
3290 // Does it start with a share?
3291 if (!empty($reshared['comment']) && $complete) {
3295 if (!empty($reshared['guid']) && $complete) {
3296 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3297 $item = Post::selectFirst(['contact-id'], $condition);
3298 if (DBA::isResult($item)) {
3300 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3301 $ret["root_guid"] = $reshared['guid'];
3303 } elseif ($complete) {
3304 // We are resharing something that isn't a DFRN or Diaspora post.
3305 // So we have to return "false" on "$complete" to not trigger a reshare.
3308 } elseif (empty($reshared['guid']) && $complete) {
3314 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3315 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3316 if (!empty($contact['addr'])) {
3317 $ret['root_handle'] = $contact['addr'];
3321 if (empty($ret) && !$complete) {
3329 * Create an event array
3331 * @param integer $event_id The id of the event
3333 * @return array with event data
3334 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3336 private static function buildEvent(string $event_id): array
3338 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
3339 if (!DBA::isResult($event)) {
3345 $owner = User::getOwnerDataById($event['uid']);
3350 $eventdata['author'] = self::myHandle($owner);
3352 if ($event['guid']) {
3353 $eventdata['guid'] = $event['guid'];
3356 $mask = DateTimeFormat::ATOM;
3358 /// @todo - establish "all day" events in Friendica
3359 $eventdata["all_day"] = "false";
3361 $eventdata['timezone'] = 'UTC';
3363 if ($event['start']) {
3364 $eventdata['start'] = DateTimeFormat::utc($event['start'], $mask);
3366 if ($event['finish'] && !$event['nofinish']) {
3367 $eventdata['end'] = DateTimeFormat::utc($event['finish'], $mask);
3369 if ($event['summary']) {
3370 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3372 if ($event['desc']) {
3373 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3375 if ($event['location']) {
3376 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3377 $coord = Map::getCoordinates($event['location']);
3380 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3381 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3382 $location["lat"] = $coord['lat'];
3383 $location["lng"] = $coord['lon'];
3385 $location["lat"] = 0;
3386 $location["lng"] = 0;
3388 $eventdata['location'] = $location;
3395 * Create a post (status message or reshare)
3397 * @param array $item The item that will be exported
3398 * @param array $owner the array of the item owner
3401 * 'type' -> Message type ("status_message" or "reshare")
3402 * 'message' -> Array of XML elements of the status
3403 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3404 * @throws \ImagickException
3406 public static function buildStatus(array $item, array $owner)
3408 $cachekey = "diaspora:buildStatus:".$item['guid'];
3410 $result = DI::cache()->get($cachekey);
3411 if (!is_null($result)) {
3415 $myaddr = self::myHandle($owner);
3417 $public = ($item["private"] == Item::PRIVATE ? "false" : "true");
3418 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3419 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3421 // Detect a share element and do a reshare
3422 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) {
3423 $message = ["author" => $myaddr,
3424 "guid" => $item["guid"],
3425 "created_at" => $created,
3426 "root_author" => $ret["root_handle"],
3427 "root_guid" => $ret["root_guid"],
3428 "provider_display_name" => $item["app"],
3429 "public" => $public];
3433 $title = $item["title"];
3434 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
3436 // Fetch the title from an attached link - if there is one
3437 if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3438 $page_data = BBCode::getAttachmentData($item['body']);
3439 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3440 $title = $page_data['title'];
3444 if ($item['author-link'] != $item['owner-link']) {
3445 $body = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'],
3446 $item['plink'], $item['created']) . $body . '[/share]';
3449 // convert to markdown
3450 $body = html_entity_decode(BBCode::toMarkdown($body));
3453 if (strlen($title)) {
3454 $body = "### ".html_entity_decode($title)."\n\n".$body;
3457 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]);
3458 if (!empty($attachments)) {
3459 $body .= "\n[hr]\n";
3460 foreach ($attachments as $attachment) {
3461 $body .= "[" . $attachment['description'] . "](" . $attachment['url'] . ")\n";
3467 if ($item["location"] != "")
3468 $location["address"] = $item["location"];
3470 if ($item["coord"] != "") {
3471 $coord = explode(" ", $item["coord"]);
3472 $location["lat"] = $coord[0];
3473 $location["lng"] = $coord[1];
3476 $message = ["author" => $myaddr,
3477 "guid" => $item["guid"],
3478 "created_at" => $created,
3479 "edited_at" => $edited,
3480 "public" => $public,
3482 "provider_display_name" => $item["app"],
3483 "location" => $location];
3485 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3486 if (!isset($location["lat"]) || !isset($location["lng"])) {
3487 unset($message["location"]);
3490 if ($item['event-id'] > 0) {
3491 $event = self::buildEvent($item['event-id']);
3492 if (count($event)) {
3493 $message['event'] = $event;
3495 if (!empty($event['location']['address']) &&
3496 !empty($event['location']['lat']) &&
3497 !empty($event['location']['lng'])) {
3498 $message['location'] = $event['location'];
3501 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3502 // $message['text'] = '';
3506 $type = "status_message";
3509 $msg = ["type" => $type, "message" => $message];
3511 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3516 private static function prependParentAuthorMention(string $body, string $profile_url): string
3518 $profile = Contact::getByURL($profile_url, false, ['addr', 'name']);
3519 if (!empty($profile['addr'])
3520 && !strstr($body, $profile['addr'])
3521 && !strstr($body, $profile_url)
3523 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3532 * @param array $item The item that will be exported
3533 * @param array $owner the array of the item owner
3534 * @param array $contact Target of the communication
3535 * @param bool $public_batch Is it a public post?
3537 * @return int The result of the transmission
3538 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3539 * @throws \ImagickException
3541 public static function sendStatus(array $item, array $owner, array $contact, bool $public_batch = false): int
3543 $status = self::buildStatus($item, $owner);
3545 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3549 * Creates a "like" object
3551 * @param array $item The item that will be exported
3552 * @param array $owner the array of the item owner
3554 * @return array|bool The data for a "like" or false on error
3555 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3557 private static function constructLike(array $item, array $owner)
3559 $parent = Post::selectFirst(['guid', 'uri', 'thr-parent'], ['uri' => $item["thr-parent"]]);
3560 if (!DBA::isResult($parent)) {
3564 $target_type = ($parent["uri"] === $parent["thr-parent"] ? "Post" : "Comment");
3566 if ($item['verb'] === Activity::LIKE) {
3568 } elseif ($item['verb'] === Activity::DISLIKE) {
3569 $positive = "false";
3572 return ["author" => self::myHandle($owner),
3573 "guid" => $item["guid"],
3574 "parent_guid" => $parent["guid"],
3575 "parent_type" => $target_type,
3576 "positive" => $positive,
3577 "author_signature" => ""];
3581 * Creates an "EventParticipation" object
3583 * @param array $item The item that will be exported
3584 * @param array $owner the array of the item owner
3586 * @return array|bool The data for an "EventParticipation" or false on error
3587 * @throws \Exception
3589 private static function constructAttend(array $item, array $owner)
3591 $parent = Post::selectFirst(['guid'], ['uri' => $item['thr-parent']]);
3592 if (!DBA::isResult($parent)) {
3596 switch ($item['verb']) {
3597 case Activity::ATTEND:
3598 $attend_answer = 'accepted';
3600 case Activity::ATTENDNO:
3601 $attend_answer = 'declined';
3603 case Activity::ATTENDMAYBE:
3604 $attend_answer = 'tentative';
3607 Logger::notice('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3611 return ["author" => self::myHandle($owner),
3612 "guid" => $item["guid"],
3613 "parent_guid" => $parent["guid"],
3614 "status" => $attend_answer,
3615 "author_signature" => ""];
3619 * Creates the object for a comment
3621 * @param array $item The item that will be exported
3622 * @param array $owner the array of the item owner
3624 * @return array|false The data for a comment
3625 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3627 private static function constructComment(array $item, array $owner)
3629 $cachekey = "diaspora:constructComment:".$item['guid'];
3631 $result = DI::cache()->get($cachekey);
3632 if (!is_null($result)) {
3636 $toplevel_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3637 if (!DBA::isResult($toplevel_item)) {
3638 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3642 $thread_parent_item = $toplevel_item;
3643 if ($item['thr-parent'] != $item['parent-uri']) {
3644 $thread_parent_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3647 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
3649 // The replied to autor mention is prepended for clarity if:
3650 // - Item replied isn't yours
3651 // - Item is public or explicit mentions are disabled
3652 // - Implicit mentions are enabled
3654 $item['author-id'] != $thread_parent_item['author-id']
3655 && ($thread_parent_item['gravity'] != GRAVITY_PARENT)
3656 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3657 && !DI::config()->get('system', 'disable_implicit_mentions')
3659 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3662 $text = html_entity_decode(BBCode::toMarkdown($body));
3663 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3664 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3667 "author" => self::myHandle($owner),
3668 "guid" => $item["guid"],
3669 "created_at" => $created,
3670 "edited_at" => $edited,
3671 "parent_guid" => $toplevel_item["guid"],
3673 "author_signature" => ""
3676 // Send the thread parent guid only if it is a threaded comment
3677 if ($item['thr-parent'] != $item['parent-uri']) {
3678 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3681 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3687 * Send a like or a comment
3689 * @param array $item The item that will be exported
3690 * @param array $owner the array of the item owner
3691 * @param array $contact Target of the communication
3692 * @param bool $public_batch Is it a public post?
3694 * @return int The result of the transmission
3695 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3696 * @throws \ImagickException
3698 public static function sendFollowup(array $item, array $owner, array $contact, bool $public_batch = false): int
3700 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3701 $message = self::constructAttend($item, $owner);
3702 $type = "event_participation";
3703 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3704 $message = self::constructLike($item, $owner);
3706 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3707 $message = self::constructComment($item, $owner);
3711 if (empty($message)) {
3715 $message["author_signature"] = self::signature($owner, $message);
3717 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3721 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3723 * @param array $item The item that will be exported
3724 * @param array $owner the array of the item owner
3725 * @param array $contact Target of the communication
3726 * @param bool $public_batch Is it a public post?
3728 * @return int The result of the transmission
3729 * @throws \Exception
3731 public static function sendRelay(array $item, array $owner, array $contact, bool $public_batch = false): int
3733 if ($item["deleted"]) {
3734 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3735 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3741 Logger::info("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")");
3743 $msg = json_decode($item['signed_text'], true);
3746 if (is_array($msg)) {
3747 foreach ($msg as $field => $data) {
3748 if (!$item["deleted"]) {
3749 if ($field == "diaspora_handle") {
3752 if ($field == "target_type") {
3753 $field = "parent_type";
3757 $message[$field] = $data;
3760 Logger::info("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text']);
3763 $message["parent_author_signature"] = self::signature($owner, $message);
3765 Logger::info('Relayed data', ['msg' => $message]);
3767 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3771 * Sends a retraction (deletion) of a message, like or comment
3773 * @param array $item The item that will be exported
3774 * @param array $owner the array of the item owner
3775 * @param array $contact Target of the communication
3776 * @param bool $public_batch Is it a public post?
3777 * @param bool $relay Is the retraction transmitted from a relay?
3779 * @return int The result of the transmission
3780 * @throws \Exception
3782 public static function sendRetraction(array $item, array $owner, array $contact, bool $public_batch = false, bool $relay = false): int
3784 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3786 $msg_type = "retraction";
3788 if ($item['gravity'] == GRAVITY_PARENT) {
3789 $target_type = "Post";
3790 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3791 $target_type = "Like";
3793 $target_type = "Comment";
3796 $message = ["author" => $itemaddr,
3797 "target_guid" => $item['guid'],
3798 "target_type" => $target_type];
3800 Logger::info('Got message', ['msg' => $message]);
3802 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3808 * @param array $item The item that will be exported
3809 * @param array $owner The owner
3810 * @param array $contact Target of the communication
3812 * @return int The result of the transmission
3813 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3814 * @throws \ImagickException
3816 public static function sendMail(array $item, array $owner, array $contact): int
3818 $myaddr = self::myHandle($owner);
3820 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
3821 if (!DBA::isResult($cnv)) {
3822 Logger::notice("conversation not found.");
3826 $body = BBCode::toMarkdown($item["body"]);
3827 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3830 "author" => $myaddr,
3831 "guid" => $item["guid"],
3832 "conversation_guid" => $cnv["guid"],
3834 "created_at" => $created,
3837 if ($item["reply"]) {
3842 "author" => $cnv["creator"],
3843 "guid" => $cnv["guid"],
3844 "subject" => $cnv["subject"],
3845 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3846 "participants" => $cnv["recips"],
3850 $type = "conversation";
3853 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
3857 * Split a name into first name and last name
3859 * @param string $name The name
3861 * @return array The array with "first" and "last"
3863 public static function splitName(string $name): array
3865 $name = trim($name);
3867 // Is the name longer than 64 characters? Then cut the rest of it.
3868 if (strlen($name) > 64) {
3869 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3870 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3872 $name = substr($name, 0, 64);
3876 // Take the first word as first name
3877 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3878 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3879 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3880 return ['first' => $first, 'last' => $last];
3883 // Take the last word as last name
3884 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3885 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3887 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3888 return ['first' => $first, 'last' => $last];
3891 // Take the first 32 characters if there is no space in the first 32 characters
3892 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3893 $first = substr($name, 0, 32);
3894 $last = substr($name, 32);
3895 return ['first' => $first, 'last' => $last];
3898 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3899 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3901 // Check if the last name is longer than 32 characters
3902 if (strlen($last) > 32) {
3903 if (strpos($last, ' ') <= 32) {
3904 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
3906 $last = substr($last, 0, 32);
3910 return ['first' => $first, 'last' => $last];
3914 * Create profile data
3916 * @param int $uid The user id
3918 * @return array The profile data
3919 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3921 private static function createProfileData(int $uid): array
3923 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
3924 if (!DBA::isResult($profile)) {
3928 $handle = $profile["addr"];
3930 $split_name = self::splitName($profile['name']);
3931 $first = $split_name['first'];
3932 $last = $split_name['last'];
3934 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3935 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3936 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3937 $searchable = ($profile['net-publish'] ? 'true' : 'false');
3943 if ($searchable === 'true') {
3946 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
3947 [$year, $month, $day] = sscanf($profile['dob'], '%4d-%2d-%2d');
3951 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
3954 $about = BBCode::toMarkdown($profile['about']);
3956 $location = $profile['location'];
3958 if ($profile['pub_keywords']) {
3959 $kw = str_replace(',', ' ', $profile['pub_keywords']);
3960 $kw = str_replace(' ', ' ', $kw);
3961 $arr = explode(' ', $kw);
3963 for ($x = 0; $x < 5; $x ++) {
3964 if (!empty($arr[$x])) {
3965 $tags .= '#'. trim($arr[$x]) .' ';
3970 $tags = trim($tags);
3973 return ["author" => $handle,
3974 "first_name" => $first,
3975 "last_name" => $last,
3976 "image_url" => $large,
3977 "image_url_medium" => $medium,
3978 "image_url_small" => $small,
3981 "location" => $location,
3982 "searchable" => $searchable,
3984 "tag_string" => $tags];
3988 * Sends profile data
3990 * @param int $uid The user id
3991 * @param bool $recips optional, default false
3993 * @throws \Exception
3995 public static function sendProfile(int $uid, bool $recips = false)
4001 $owner = User::getOwnerDataById($uid);
4007 $recips = DBA::selectToArray('contact', [], ['network' => Protocol::DIASPORA, 'uid' => $uid, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
4014 $message = self::createProfileData($uid);
4016 // @ToDo Split this into single worker jobs
4017 foreach ($recips as $recip) {
4018 Logger::info("Send updated profile data for user ".$uid." to contact ".$recip["id"]);
4019 self::buildAndTransmit($owner, $recip, "profile", $message);
4024 * Creates the signature for likes that are created on our system
4026 * @param integer $uid The user of that comment
4027 * @param array $item Item array
4029 * @return array|bool Signed content or false on error
4030 * @throws \Exception
4032 public static function createLikeSignature(int $uid, array $item)
4034 $owner = User::getOwnerDataById($uid);
4035 if (empty($owner)) {
4036 Logger::info('No owner post, so not storing signature');
4040 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4044 $message = self::constructLike($item, $owner);
4045 if ($message === false) {
4049 $message["author_signature"] = self::signature($owner, $message);
4055 * Creates the signature for Comments that are created on our system
4057 * @param array $item Item array
4059 * @return array|bool Signed content or false on error
4060 * @throws \Exception
4062 public static function createCommentSignature(array $item)
4064 if (!empty($item['author-link'])) {
4065 $url = $item['author-link'];
4067 $contact = Contact::getById($item['author-id'], ['url']);
4068 if (empty($contact['url'])) {
4069 Logger::warning('Author Contact not found', ['author-id' => $item['author-id']]);
4072 $url = $contact['url'];
4075 $uid = User::getIdForURL($url);
4077 Logger::info('No owner post, so not storing signature', ['url' => $contact['url']]);
4081 $owner = User::getOwnerDataById($uid);
4082 if (empty($owner)) {
4083 Logger::info('No owner post, so not storing signature');
4087 // This is only needed for the automated tests
4088 if (empty($owner['uprvkey'])) {
4092 $message = self::constructComment($item, $owner);
4093 if ($message === false) {
4097 $message["author_signature"] = self::signature($owner, $message);
4102 public static function performReshare(int $UriId, int $uid): int
4104 $fields = ['uri-id', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
4105 $item = Post::selectFirst($fields, ['uri-id' => $UriId, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
4106 if (!DBA::isResult($item)) {
4110 if (strpos($item['body'], '[/share]') !== false) {
4111 $pos = strpos($item['body'], '[share');
4112 $post = substr($item['body'], $pos);
4114 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
4116 if (!empty($item['title'])) {
4117 $post .= '[h3]' . $item['title'] . "[/h3]\n";
4120 $post .= $item['body'];
4121 $post .= '[/share]';
4124 $owner = User::getOwnerDataById($uid);
4125 $author = Contact::getPublicIdByUserId($uid);
4129 'verb' => Activity::POST,
4130 'contact-id' => $owner['id'],
4131 'author-id' => $author,
4132 'owner-id' => $author,
4134 'allow_cid' => $owner['allow_cid'] ?? '',
4135 'allow_gid' => $owner['allow_gid']?? '',
4136 'deny_cid' => $owner['deny_cid'] ?? '',
4137 'deny_gid' => $owner['deny_gid'] ?? '',
4140 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
4141 $item['private'] = Item::PRIVATE;
4142 } elseif (DI::pConfig()->get($uid, 'system', 'unlisted')) {
4143 $item['private'] = Item::UNLISTED;
4145 $item['private'] = Item::PUBLIC;
4148 // Don't trigger the addons
4149 $item['api_source'] = false;
4151 return Item::insert($item, true);