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\Probe;
45 use Friendica\Util\Crypto;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\Map;
48 use Friendica\Util\Network;
49 use Friendica\Util\Strings;
50 use Friendica\Util\XML;
51 use Friendica\Worker\Delivery;
55 * This class contain functions to create and send Diaspora XML files
61 const FORCED_FETCH = 2;
64 * Return a list of participating contacts for a thread
66 * This is used for the participation feature.
67 * One of the parameters is a contact array.
68 * This is done to avoid duplicates.
70 * @param array $item Item that is about to be delivered
71 * @param array $contacts The previously fetched contacts
73 * @return array of relay servers
76 public static function participantsForThread(array $item, array $contacts)
78 if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
79 Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]);
83 $items = Post::select(['author-id', 'author-link', 'parent-author-link', 'parent-guid', 'guid'],
84 ['parent' => $item['parent'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
85 while ($item = Post::fetch($items)) {
86 $contact = DBA::selectFirst('contact', ['id', 'url', 'name', 'protocol', 'batch', 'network'],
87 ['id' => $item['author-id']]);
88 if (!DBA::isResult($contact) || empty($contact['batch']) ||
89 ($contact['network'] != Protocol::DIASPORA) ||
90 Strings::compareLink($item['parent-author-link'], $item['author-link'])) {
95 foreach ($contacts as $entry) {
96 if ($entry['batch'] == $contact['batch']) {
102 Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]);
103 $contacts[] = $contact;
112 * verify the envelope and return the verified data
114 * @param string $envelope The magic envelope
116 * @return string verified data
117 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
118 * @throws \ImagickException
120 private static function verifyMagicEnvelope($envelope)
122 $basedom = XML::parseString($envelope, true);
124 if (!is_object($basedom)) {
125 Logger::notice("Envelope is no XML file");
129 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
131 if (sizeof($children) == 0) {
132 Logger::notice("XML has no children");
138 $data = Strings::base64UrlDecode($children->data);
139 $type = $children->data->attributes()->type[0];
141 $encoding = $children->encoding;
143 $alg = $children->alg;
145 $sig = Strings::base64UrlDecode($children->sig);
146 $key_id = $children->sig->attributes()->key_id[0];
148 $handle = Strings::base64UrlDecode($key_id);
151 $b64url_data = Strings::base64UrlEncode($data);
152 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
154 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
157 Logger::notice('No author could be decoded. Discarding. Message: ' . $envelope);
161 $key = self::key($handle);
163 Logger::notice("Couldn't get a key for handle " . $handle . ". Discarding.");
167 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
169 Logger::notice('Message from ' . $handle . ' did not verify. Discarding.');
177 * encrypts data via AES
179 * @param string $key The AES key
180 * @param string $iv The IV (is used for CBC encoding)
181 * @param string $data The data that is to be encrypted
183 * @return string encrypted data
185 private static function aesEncrypt($key, $iv, $data)
187 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
191 * decrypts data via AES
193 * @param string $key The AES key
194 * @param string $iv The IV (is used for CBC encoding)
195 * @param string $encrypted The encrypted data
197 * @return string decrypted data
199 private static function aesDecrypt($key, $iv, $encrypted)
201 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
205 * Decodes incoming Diaspora message in the new format
207 * @param string $raw raw post message
208 * @param string $privKey The private key of the importer
209 * @param boolean $no_exit Don't do an http exit on error
212 * 'message' -> decoded Diaspora XML message
213 * 'author' -> author diaspora handle
214 * 'key' -> author public key (converted to pkcs#8)
215 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
216 * @throws \ImagickException
218 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
220 $data = json_decode($raw);
222 // Is it a private post? Then decrypt the outer Salmon
223 if (is_object($data)) {
224 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
225 $ciphertext = base64_decode($data->encrypted_magic_envelope);
227 $outer_key_bundle = '';
228 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
229 $j_outer_key_bundle = json_decode($outer_key_bundle);
231 if (!is_object($j_outer_key_bundle)) {
232 Logger::notice('Outer Salmon did not verify. Discarding.');
236 throw new \Friendica\Network\HTTPException\BadRequestException();
240 $outer_iv = base64_decode($j_outer_key_bundle->iv);
241 $outer_key = base64_decode($j_outer_key_bundle->key);
243 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
248 $basedom = XML::parseString($xml, true);
250 if (!is_object($basedom)) {
251 Logger::notice('Received data does not seem to be an XML. Discarding. '.$xml);
255 throw new \Friendica\Network\HTTPException\BadRequestException();
259 $base = $basedom->children(ActivityNamespace::SALMON_ME);
261 // Not sure if this cleaning is needed
262 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
264 // Build the signed data
265 $type = $base->data[0]->attributes()->type[0];
266 $encoding = $base->encoding;
268 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
270 // This is the signature
271 $signature = Strings::base64UrlDecode($base->sig);
273 // Get the senders' public key
274 $key_id = $base->sig[0]->attributes()->key_id[0];
275 $author_addr = base64_decode($key_id);
276 if ($author_addr == '') {
277 Logger::notice('No author could be decoded. Discarding. Message: ' . $xml);
281 throw new \Friendica\Network\HTTPException\BadRequestException();
285 $key = self::key($author_addr);
287 Logger::notice("Couldn't get a key for handle " . $author_addr . ". Discarding.");
291 throw new \Friendica\Network\HTTPException\BadRequestException();
295 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
297 Logger::notice('Message did not verify. Discarding.');
301 throw new \Friendica\Network\HTTPException\BadRequestException();
305 return ['message' => (string)Strings::base64UrlDecode($base->data),
306 'author' => XML::unescape($author_addr),
307 'key' => (string)$key];
311 * Decodes incoming Diaspora message in the deprecated format
313 * @param string $xml urldecoded Diaspora salmon
314 * @param string $privKey The private key of the importer
317 * 'message' -> decoded Diaspora XML message
318 * 'author' -> author diaspora handle
319 * 'key' -> author public key (converted to pkcs#8)
320 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
321 * @throws \ImagickException
323 public static function decode(string $xml, string $privKey = '')
326 $basedom = XML::parseString($xml);
328 if (!is_object($basedom)) {
329 Logger::notice('XML is not parseable.');
332 $children = $basedom->children('https://joindiaspora.com/protocol');
334 $inner_aes_key = null;
337 if ($children->header) {
339 $author_link = str_replace('acct:', '', $children->header->author_id);
341 // This happens with posts from a relais
342 if (empty($privKey)) {
343 Logger::info('This is no private post in the old format');
347 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
349 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
350 $ciphertext = base64_decode($encrypted_header->ciphertext);
352 $outer_key_bundle = '';
353 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
355 $j_outer_key_bundle = json_decode($outer_key_bundle);
357 $outer_iv = base64_decode($j_outer_key_bundle->iv);
358 $outer_key = base64_decode($j_outer_key_bundle->key);
360 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
362 Logger::info('decrypted', ['data' => $decrypted]);
363 $idom = XML::parseString($decrypted);
365 $inner_iv = base64_decode($idom->iv);
366 $inner_aes_key = base64_decode($idom->aes_key);
368 $author_link = str_replace('acct:', '', $idom->author_id);
371 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
373 // figure out where in the DOM tree our data is hiding
376 if ($dom->provenance->data) {
377 $base = $dom->provenance;
378 } elseif ($dom->env->data) {
380 } elseif ($dom->data) {
385 Logger::notice('unable to locate salmon data in xml');
386 throw new \Friendica\Network\HTTPException\BadRequestException();
390 // Stash the signature away for now. We have to find their key or it won't be good for anything.
391 $signature = Strings::base64UrlDecode($base->sig);
395 // strip whitespace so our data element will return to one big base64 blob
396 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
399 // stash away some other stuff for later
401 $type = $base->data[0]->attributes()->type[0];
402 $keyhash = $base->sig[0]->attributes()->keyhash[0];
403 $encoding = $base->encoding;
407 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
411 $data = Strings::base64UrlDecode($data);
415 $inner_decrypted = $data;
417 // Decode the encrypted blob
418 $inner_encrypted = base64_decode($data);
419 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
423 Logger::notice('Could not retrieve author URI.');
424 throw new \Friendica\Network\HTTPException\BadRequestException();
426 // Once we have the author URI, go to the web and try to find their public key
427 // (first this will look it up locally if it is in the fcontact cache)
428 // This will also convert diaspora public key from pkcs#1 to pkcs#8
430 Logger::notice('Fetching key for '.$author_link);
431 $key = self::key($author_link);
434 Logger::notice('Could not retrieve author key.');
435 throw new \Friendica\Network\HTTPException\BadRequestException();
438 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
441 Logger::notice('Message did not verify. Discarding.');
442 throw new \Friendica\Network\HTTPException\BadRequestException();
445 Logger::notice('Message verified.');
447 return ['message' => (string)$inner_decrypted,
448 'author' => XML::unescape($author_link),
449 'key' => (string)$key];
454 * Dispatches public messages and find the fitting receivers
456 * @param array $msg The post that will be dispatched
457 * @param int $direction Indicates if the message had been fetched or pushed
459 * @return int The message id of the generated message, "true" or "false" if there was an error
460 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
461 * @throws \ImagickException
463 public static function dispatchPublic($msg, int $direction)
465 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
467 Logger::notice("diaspora is disabled");
471 if (!($fields = self::validPosting($msg))) {
472 Logger::notice("Invalid posting");
476 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
477 $success = self::dispatch($importer, $msg, $fields, $direction);
483 * Dispatches the different message types to the different functions
485 * @param array $importer Array of the importer user
486 * @param array $msg The post that will be dispatched
487 * @param SimpleXMLElement $fields SimpleXML object that contains the message
488 * @param int $direction Indicates if the message had been fetched or pushed
490 * @return int The message id of the generated message, "true" or "false" if there was an error
491 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
492 * @throws \ImagickException
494 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null, int $direction = self::PUSHED)
496 // The sender is the handle of the contact that sent the message.
497 // This will often be different with relayed messages (for example "like" and "comment")
498 $sender = $msg["author"];
500 // This is only needed for private postings since this is already done for public ones before
501 if (is_null($fields)) {
503 if (!($fields = self::validPosting($msg))) {
504 Logger::notice("Invalid posting");
511 $type = $fields->getName();
513 Logger::info('Received message', ['type' => $type, 'sender' => $sender, 'user' => $importer["uid"]]);
516 case "account_migration":
518 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
521 return self::receiveAccountMigration($importer, $fields);
523 case "account_deletion":
524 return self::receiveAccountDeletion($fields);
527 return self::receiveComment($importer, $sender, $fields, $msg["message"], $direction);
531 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
534 return self::receiveContactRequest($importer, $fields);
538 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
541 return self::receiveConversation($importer, $msg, $fields);
544 return self::receiveLike($importer, $sender, $fields, $direction);
548 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
551 return self::receiveMessage($importer, $fields);
553 case "participation":
555 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
558 return self::receiveParticipation($importer, $fields, $direction);
560 case "photo": // Not implemented
561 return self::receivePhoto($importer, $fields);
563 case "poll_participation": // Not implemented
564 return self::receivePollParticipation($importer, $fields);
568 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
571 return self::receiveProfile($importer, $fields);
574 return self::receiveReshare($importer, $fields, $msg["message"], $direction);
577 return self::receiveRetraction($importer, $sender, $fields);
579 case "status_message":
580 return self::receiveStatusMessage($importer, $fields, $msg["message"], $direction);
583 Logger::notice("Unknown message type ".$type);
589 * Checks if a posting is valid and fetches the data fields.
591 * This function does not only check the signature.
592 * It also does the conversion between the old and the new diaspora format.
594 * @param array $msg Array with the XML, the sender handle and the sender signature
596 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
597 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
598 * @throws \ImagickException
600 private static function validPosting($msg)
602 $data = XML::parseString($msg["message"]);
604 if (!is_object($data)) {
605 Logger::info('No valid XML', ['message' => $msg['message']]);
609 // Is this the new or the old version?
610 if ($data->getName() == "XML") {
612 foreach ($data->post->children() as $child) {
620 $type = $element->getName();
623 Logger::debug("Got message type ".$type.": ".$msg["message"]);
625 // All retractions are handled identically from now on.
626 // In the new version there will only be "retraction".
627 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
628 $type = "retraction";
630 if ($type == "request") {
634 $fields = new SimpleXMLElement("<".$type."/>");
637 $author_signature = null;
638 $parent_author_signature = null;
640 foreach ($element->children() as $fieldname => $entry) {
642 // Translation for the old XML structure
643 if ($fieldname == "diaspora_handle") {
644 $fieldname = "author";
646 if ($fieldname == "participant_handles") {
647 $fieldname = "participants";
649 if (in_array($type, ["like", "participation"])) {
650 if ($fieldname == "target_type") {
651 $fieldname = "parent_type";
654 if ($fieldname == "sender_handle") {
655 $fieldname = "author";
657 if ($fieldname == "recipient_handle") {
658 $fieldname = "recipient";
660 if ($fieldname == "root_diaspora_id") {
661 $fieldname = "root_author";
663 if ($type == "status_message") {
664 if ($fieldname == "raw_message") {
668 if ($type == "retraction") {
669 if ($fieldname == "post_guid") {
670 $fieldname = "target_guid";
672 if ($fieldname == "type") {
673 $fieldname = "target_type";
678 if (($fieldname == "author_signature") && ($entry != "")) {
679 $author_signature = base64_decode($entry);
680 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
681 $parent_author_signature = base64_decode($entry);
682 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
683 if ($signed_data != "") {
687 $signed_data .= $entry;
689 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
690 || ($orig_type == "relayable_retraction")
692 XML::copy($entry, $fields, $fieldname);
696 // This is something that shouldn't happen at all.
697 if (in_array($type, ["status_message", "reshare", "profile"])) {
698 if ($msg["author"] != $fields->author) {
699 Logger::notice("Message handle is not the same as envelope sender. Quitting this message.");
704 // Only some message types have signatures. So we quit here for the other types.
705 if (!in_array($type, ["comment", "like"])) {
708 // No author_signature? This is a must, so we quit.
709 if (!isset($author_signature)) {
710 Logger::info("No author signature for type ".$type." - Message: ".$msg["message"]);
714 if (isset($parent_author_signature)) {
715 $key = self::key($msg["author"]);
717 Logger::info('No key found for parent', ['author' => $msg["author"]]);
721 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
722 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);
727 $key = self::key($fields->author);
729 Logger::info('No key found', ['author' => $fields->author]);
733 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
734 Logger::info("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature);
742 * Fetches the public key for a given handle
744 * @param string $handle The handle
746 * @return string The public key
747 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
748 * @throws \ImagickException
750 private static function key($handle)
752 $handle = strval($handle);
754 Logger::notice("Fetching diaspora key for: ".$handle);
756 $r = FContact::getByURL($handle);
765 * get a handle (user@domain.tld) from a given contact id
767 * @param int $contact_id The id in the contact table
768 * @param int $pcontact_id The id in the contact table (Used for the public contact)
770 * @return string the handle
773 private static function handleFromContact($contact_id, $pcontact_id = 0)
777 if ($pcontact_id != 0) {
778 $contact = Contact::getById($pcontact_id, ['addr']);
779 if (DBA::isResult($contact)) {
780 $handle = $contact['addr'];
784 if (empty($handle)) {
785 $contact = Contact::getById($contact_id, ['addr']);
786 if (DBA::isResult($contact)) {
787 $handle = $contact['addr'];
791 return strtolower($handle);
795 * Get a contact id for a given handle
797 * @todo Move to Friendica\Model\Contact
799 * @param int $uid The user id
800 * @param string $handle The handle in the format user@domain.tld
802 * @return array Contact data
803 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
804 * @throws \ImagickException
806 private static function contactByHandle($uid, $handle)
808 return Contact::getByURL($handle, null, [], $uid);
812 * Checks if the given contact url does support ActivityPub
814 * @param string $url profile url
815 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
817 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
818 * @throws \ImagickException
820 public static function isSupportedByContactUrl($url, $update = null)
822 return !empty(FContact::getByURL($url, $update));
826 * Check if posting is allowed for this contact
828 * @param array $importer Array of the importer user
829 * @param array $contact The contact that is checked
830 * @param bool $is_comment Is the check for a comment?
832 * @return bool is the contact allowed to post?
834 private static function postAllow(array $importer, array $contact, $is_comment = false)
837 * Perhaps we were already sharing with this person. Now they're sharing with us.
838 * That makes us friends.
839 * Normally this should have handled by getting a request - but this could get lost
841 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
842 // It is not removed by now. Possibly the code is needed?
843 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
845 // array('rel' => Contact::FRIEND, 'writable' => true),
846 // array('id' => $contact["id"], 'uid' => $contact["uid"])
849 // $contact["rel"] = Contact::FRIEND;
850 // Logger::notice("defining user ".$contact["nick"]." as friend");
853 // Contact server is blocked
854 if (Network::isUrlBlocked($contact['url'])) {
856 // We don't seem to like that person
857 } elseif ($contact["blocked"]) {
858 // Maybe blocked, don't accept.
860 // We are following this person?
861 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
862 // Yes, then it is fine.
864 // Is the message a global user or a comment?
865 } elseif (($importer["uid"] == 0) || $is_comment) {
866 // Messages for the global users and comments are always accepted
874 * Fetches the contact id for a handle and checks if posting is allowed
876 * @param array $importer Array of the importer user
877 * @param string $handle The checked handle in the format user@domain.tld
878 * @param bool $is_comment Is the check for a comment?
880 * @return array The contact data
883 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
885 $contact = self::contactByHandle($importer["uid"], $handle);
887 Logger::notice("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
888 // If a contact isn't found, we accept it anyway if it is a comment
889 if ($is_comment && ($importer["uid"] != 0)) {
890 return self::contactByHandle(0, $handle);
891 } elseif ($is_comment) {
898 if (!self::postAllow($importer, $contact, $is_comment)) {
899 Logger::notice("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
906 * Does the message already exists on the system?
908 * @param int $uid The user id
909 * @param string $guid The guid of the message
911 * @return int|bool message id if the message already was stored into the system - or false.
914 private static function messageExists($uid, $guid)
916 $item = Post::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
917 if (DBA::isResult($item)) {
918 Logger::notice("message ".$guid." already exists for user ".$uid);
926 * Checks for links to posts in a message
928 * @param array $item The item array
931 private static function fetchGuid(array $item)
933 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
934 preg_replace_callback(
936 function ($match) use ($item) {
937 self::fetchGuidSub($match, $item);
942 preg_replace_callback(
943 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
944 function ($match) use ($item) {
945 self::fetchGuidSub($match, $item);
952 * Checks for relative /people/* links in an item body to match local
953 * contacts or prepends the remote host taken from the author link.
955 * @param string $body The item body to replace links from
956 * @param string $author_link The author link for missing local contact fallback
958 * @return string the replaced string
960 public static function replacePeopleGuid($body, $author_link)
962 $return = preg_replace_callback(
963 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
964 function ($match) use ($author_link) {
966 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
967 // 1 => '0123456789abcdef'
969 $handle = FContact::getUrlByGuid($match[1]);
972 $return = '@[url='.$handle.']'.$match[2].'[/url]';
974 // No local match, restoring absolute remote URL from author scheme and host
975 $author_url = parse_url($author_link);
976 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
988 * sub function of "fetchGuid" which checks for links in messages
990 * @param array $match array containing a link that has to be checked for a message link
991 * @param array $item The item array
993 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
994 * @throws \ImagickException
996 private static function fetchGuidSub($match, $item)
998 if (!self::storeByGuid($match[1], $item["author-link"], true)) {
999 self::storeByGuid($match[1], $item["owner-link"], true);
1004 * Fetches an item with a given guid from a given server
1006 * @param string $guid the message guid
1007 * @param string $server The server address
1008 * @param bool $force Forced fetch
1010 * @return int the message id of the stored message or false
1011 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1012 * @throws \ImagickException
1014 private static function storeByGuid($guid, $server, $force)
1016 $serverparts = parse_url($server);
1018 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1022 $server = $serverparts["scheme"]."://".$serverparts["host"];
1024 Logger::info("Trying to fetch item ".$guid." from ".$server);
1026 $msg = self::message($guid, $server);
1032 Logger::info("Successfully fetched item ".$guid." from ".$server);
1034 // Now call the dispatcher
1035 return self::dispatchPublic($msg, $force ? self::FORCED_FETCH : self::FETCHED);
1039 * Fetches a message from a server
1041 * @param string $guid message guid
1042 * @param string $server The url of the server
1043 * @param int $level Endless loop prevention
1046 * 'message' => The message XML
1047 * 'author' => The author handle
1048 * 'key' => The public key of the author
1049 * @throws \Exception
1051 public static function message($guid, $server, $level = 0)
1057 // This will work for new Diaspora servers and Friendica servers from 3.5
1058 $source_url = $server."/fetch/post/".urlencode($guid);
1060 Logger::info("Fetch post from ".$source_url);
1062 $envelope = DI::httpClient()->fetch($source_url);
1064 Logger::info("Envelope was fetched.");
1065 $x = self::verifyMagicEnvelope($envelope);
1067 Logger::info("Envelope could not be verified.");
1069 Logger::info("Envelope was verified.");
1079 $source_xml = XML::parseString($x);
1081 if (!is_object($source_xml)) {
1085 if ($source_xml->post->reshare) {
1086 // Reshare of a reshare - old Diaspora version
1087 Logger::info("Message is a reshare");
1088 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1089 } elseif ($source_xml->getName() == "reshare") {
1090 // Reshare of a reshare - new Diaspora version
1091 Logger::info("Message is a new reshare");
1092 return self::message($source_xml->root_guid, $server, ++$level);
1097 // Fetch the author - for the old and the new Diaspora version
1098 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1099 $author = (string)$source_xml->post->status_message->diaspora_handle;
1100 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1101 $author = (string)$source_xml->author;
1104 // If this isn't a "status_message" then quit
1106 Logger::info("Message doesn't seem to be a status message");
1110 $msg = ["message" => $x, "author" => $author];
1112 $msg["key"] = self::key($msg["author"]);
1118 * Fetches an item with a given URL
1120 * @param string $url the message url
1122 * @return int the message id of the stored message or false
1123 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1124 * @throws \ImagickException
1126 public static function fetchByURL($url, $uid = 0)
1128 // Check for Diaspora (and Friendica) typical paths
1129 if (!preg_match("=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1130 Logger::info('Invalid url', ['url' => $url]);
1134 $guid = urldecode($matches[2]);
1136 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1137 if (DBA::isResult($item)) {
1138 Logger::info('Found', ['id' => $item['id']]);
1142 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1143 $ret = self::storeByGuid($guid, $matches[1], true);
1144 Logger::info('Result', ['ret' => $ret]);
1146 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1147 if (DBA::isResult($item)) {
1148 Logger::info('Found', ['id' => $item['id']]);
1151 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1157 * Fetches the item record of a given guid
1159 * @param int $uid The user id
1160 * @param string $guid message guid
1161 * @param string $author The handle of the item
1162 * @param array $contact The contact of the item owner
1164 * @return array the item record
1165 * @throws \Exception
1167 private static function parentItem($uid, $guid, $author, array $contact)
1169 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1170 'author-name', 'author-link', 'author-avatar', 'gravity',
1171 'owner-name', 'owner-link', 'owner-avatar'];
1172 $condition = ['uid' => $uid, 'guid' => $guid];
1173 $item = Post::selectFirst($fields, $condition);
1175 if (!DBA::isResult($item)) {
1176 $person = FContact::getByURL($author);
1177 $result = self::storeByGuid($guid, $person["url"], false);
1179 // We don't have an url for items that arrived at the public dispatcher
1180 if (!$result && !empty($contact["url"])) {
1181 $result = self::storeByGuid($guid, $contact["url"], false);
1185 Logger::info("Fetched missing item ".$guid." - result: ".$result);
1187 $item = Post::selectFirst($fields, $condition);
1191 if (!DBA::isResult($item)) {
1192 Logger::notice("parent item not found: parent: ".$guid." - user: ".$uid);
1195 Logger::notice("parent item found: parent: ".$guid." - user: ".$uid);
1201 * returns contact details
1203 * @param array $def_contact The default contact if the person isn't found
1204 * @param array $person The record of the person
1205 * @param int $uid The user id
1208 * 'cid' => contact id
1209 * 'network' => network type
1210 * @throws \Exception
1212 private static function authorContactByUrl($def_contact, $person, $uid)
1214 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1215 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1216 if (DBA::isResult($contact)) {
1217 $cid = $contact["id"];
1218 $network = $contact["network"];
1220 $cid = $def_contact["id"];
1221 $network = Protocol::DIASPORA;
1224 return ["cid" => $cid, "network" => $network];
1228 * Is the profile a hubzilla profile?
1230 * @param string $url The profile link
1232 * @return bool is it a hubzilla server?
1234 private static function isHubzilla($url)
1236 return(strstr($url, '/channel/'));
1240 * Generate a post link with a given handle and message guid
1242 * @param string $addr The user handle
1243 * @param string $guid message guid
1244 * @param string $parent_guid optional parent guid
1246 * @return string the post link
1247 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1248 * @throws \ImagickException
1250 private static function plink(string $addr, string $guid, string $parent_guid = '')
1252 $contact = Contact::getByURL($addr);
1253 if (empty($contact)) {
1254 Logger::info('No contact data for address', ['addr' => $addr]);
1258 if (empty($contact['baseurl'])) {
1259 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1260 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1264 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1265 if (!empty($gserver['platform'])) {
1266 $platform = strtolower($gserver['platform']);
1267 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1270 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1271 if (self::isHubzilla($contact['url'])) {
1272 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1273 $platform = 'hubzilla';
1274 } elseif ($contact['network'] == Protocol::DFRN) {
1275 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1276 $platform = 'friendica';
1280 if ($platform == 'friendica') {
1281 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1284 if ($platform == 'hubzilla') {
1285 return $contact['baseurl'] . '/item/' . $guid;
1288 if ($platform == 'socialhome') {
1289 return $contact['baseurl'] . '/content/' . $guid;
1292 if ($platform != 'diaspora') {
1293 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1297 if ($parent_guid != '') {
1298 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1300 return $contact['baseurl'] . '/posts/' . $guid;
1305 * Receives account migration
1307 * @param array $importer Array of the importer user
1308 * @param object $data The message object
1310 * @return bool Success
1311 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1312 * @throws \ImagickException
1314 private static function receiveAccountMigration(array $importer, $data)
1316 $old_handle = XML::unescape($data->author);
1317 $new_handle = XML::unescape($data->profile->author);
1318 $signature = XML::unescape($data->signature);
1320 $contact = self::contactByHandle($importer["uid"], $old_handle);
1322 Logger::notice("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1326 Logger::notice("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1329 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1330 $key = self::key($old_handle);
1331 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1332 Logger::notice('No valid signature for migration.');
1336 // Update the profile
1337 self::receiveProfile($importer, $data->profile);
1339 // change the technical stuff in contact
1340 $data = Probe::uri($new_handle);
1341 if ($data['network'] == Protocol::PHANTOM) {
1342 Logger::notice('Account for '.$new_handle." couldn't be probed.");
1346 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1347 'name' => $data['name'], 'nick' => $data['nick'],
1348 'addr' => $data['addr'], 'batch' => $data['batch'],
1349 'notify' => $data['notify'], 'poll' => $data['poll'],
1350 'network' => $data['network']];
1352 Contact::update($fields, ['addr' => $old_handle]);
1354 Logger::notice('Contacts are updated.');
1360 * Processes an account deletion
1362 * @param object $data The message object
1364 * @return bool Success
1365 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1367 private static function receiveAccountDeletion($data)
1369 $author = XML::unescape($data->author);
1371 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1372 while ($contact = DBA::fetch($contacts)) {
1373 Contact::remove($contact["id"]);
1375 DBA::close($contacts);
1377 Logger::notice('Removed contacts for ' . $author);
1383 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1385 * @param string $author Author handle
1386 * @param string $guid Message guid
1387 * @param boolean $onlyfound Only return uri when found in the database
1389 * @return string The constructed uri or the one from our database
1390 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1391 * @throws \ImagickException
1393 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1395 $item = Post::selectFirst(['uri'], ['guid' => $guid]);
1396 if (DBA::isResult($item)) {
1397 return $item["uri"];
1398 } elseif (!$onlyfound) {
1399 $person = FContact::getByURL($author);
1401 $parts = parse_url($person['url']);
1402 unset($parts['path']);
1403 $host_url = Network::unparseURL($parts);
1405 return $host_url . '/objects/' . $guid;
1412 * Store the mentions in the tag table
1414 * @param integer $uriid
1415 * @param string $text
1417 private static function storeMentions(int $uriid, string $text)
1419 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1420 if (empty($matches)) {
1425 * Matching values for the preg match
1426 * [1] = mention type (@ or !)
1427 * [2] = name (optional)
1431 foreach ($matches as $match) {
1432 if (empty($match)) {
1436 $person = FContact::getByURL($match[3]);
1437 if (empty($person)) {
1441 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1446 * Processes an incoming comment
1448 * @param array $importer Array of the importer user
1449 * @param string $sender The sender of the message
1450 * @param object $data The message object
1451 * @param string $xml The original XML of the message
1452 * @param int $direction Indicates if the message had been fetched or pushed
1454 * @return int The message id of the generated comment or "false" if there was an error
1455 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1456 * @throws \ImagickException
1458 private static function receiveComment(array $importer, $sender, $data, $xml, int $direction)
1460 $author = XML::unescape($data->author);
1461 $guid = XML::unescape($data->guid);
1462 $parent_guid = XML::unescape($data->parent_guid);
1463 $text = XML::unescape($data->text);
1465 if (isset($data->created_at)) {
1466 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1468 $created_at = DateTimeFormat::utcNow();
1471 if (isset($data->thread_parent_guid)) {
1472 $thread_parent_guid = XML::unescape($data->thread_parent_guid);
1473 $thr_parent = self::getUriFromGuid("", $thread_parent_guid, true);
1478 $contact = self::allowedContactByHandle($importer, $sender, true);
1483 if (!empty($contact['gsid'])) {
1484 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1487 $message_id = self::messageExists($importer["uid"], $guid);
1492 $toplevel_parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1493 if (!$toplevel_parent_item) {
1497 $person = FContact::getByURL($author);
1498 if (!is_array($person)) {
1499 Logger::notice("unable to find author details");
1503 // Fetch the contact id - if we know this contact
1504 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1508 $datarray["uid"] = $importer["uid"];
1509 $datarray["contact-id"] = $author_contact["cid"];
1510 $datarray["network"] = $author_contact["network"];
1512 $datarray["author-link"] = $person["url"];
1513 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1515 $datarray["owner-link"] = $contact["url"];
1516 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1518 // Will be overwritten for sharing accounts in Item::insert
1519 if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
1520 $datarray["post-reason"] = Item::PR_FETCHED;
1521 } elseif ($datarray["uid"] == 0) {
1522 $datarray["post-reason"] = Item::PR_GLOBAL;
1524 $datarray["post-reason"] = Item::PR_COMMENT;
1527 $datarray["guid"] = $guid;
1528 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1529 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1531 $datarray["verb"] = Activity::POST;
1532 $datarray["gravity"] = GRAVITY_COMMENT;
1534 $datarray['thr-parent'] = $thr_parent ?: $toplevel_parent_item['uri'];
1536 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1537 $datarray["post-type"] = Item::PT_NOTE;
1539 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1540 $datarray["source"] = $xml;
1541 $datarray["direction"] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
1543 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1545 $datarray["plink"] = self::plink($author, $guid, $toplevel_parent_item['guid']);
1546 $body = Markdown::toBBCode($text);
1548 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1550 self::storeMentions($datarray['uri-id'], $text);
1551 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
1553 self::fetchGuid($datarray);
1555 // If we are the origin of the parent we store the original data.
1556 // We notify our followers during the item storage.
1557 if ($toplevel_parent_item["origin"]) {
1558 $datarray['diaspora_signed_text'] = json_encode($data);
1561 if (Item::isTooOld($datarray)) {
1562 Logger::info('Comment is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1566 $message_id = Item::insert($datarray);
1568 if ($message_id <= 0) {
1573 Logger::info("Stored comment ".$datarray["guid"]." with message id ".$message_id);
1574 if ($datarray['uid'] == 0) {
1575 Item::distribute($message_id, json_encode($data));
1583 * processes and stores private messages
1585 * @param array $importer Array of the importer user
1586 * @param array $contact The contact of the message
1587 * @param object $data The message object
1588 * @param array $msg Array of the processed message, author handle and key
1589 * @param object $mesg The private message
1590 * @param array $conversation The conversation record to which this message belongs
1592 * @return bool "true" if it was successful
1593 * @throws \Exception
1595 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1597 $author = XML::unescape($data->author);
1598 $guid = XML::unescape($data->guid);
1599 $subject = XML::unescape($data->subject);
1601 // "diaspora_handle" is the element name from the old version
1602 // "author" is the element name from the new version
1603 if ($mesg->author) {
1604 $msg_author = XML::unescape($mesg->author);
1605 } elseif ($mesg->diaspora_handle) {
1606 $msg_author = XML::unescape($mesg->diaspora_handle);
1611 $msg_guid = XML::unescape($mesg->guid);
1612 $msg_conversation_guid = XML::unescape($mesg->conversation_guid);
1613 $msg_text = XML::unescape($mesg->text);
1614 $msg_created_at = DateTimeFormat::utc(XML::unescape($mesg->created_at));
1616 if ($msg_conversation_guid != $guid) {
1617 Logger::notice("message conversation guid does not belong to the current conversation.");
1621 $body = Markdown::toBBCode($msg_text);
1622 $message_uri = $msg_author.":".$msg_guid;
1624 $person = FContact::getByURL($msg_author);
1626 return Mail::insert([
1627 'uid' => $importer['uid'],
1628 'guid' => $msg_guid,
1629 'convid' => $conversation['id'],
1630 'from-name' => $person['name'],
1631 'from-photo' => $person['photo'],
1632 'from-url' => $person['url'],
1633 'contact-id' => $contact['id'],
1634 'title' => $subject,
1636 'uri' => $message_uri,
1637 'parent-uri' => $author . ':' . $guid,
1638 'created' => $msg_created_at
1643 * Processes new private messages (answers to private messages are processed elsewhere)
1645 * @param array $importer Array of the importer user
1646 * @param array $msg Array of the processed message, author handle and key
1647 * @param object $data The message object
1649 * @return bool Success
1650 * @throws \Exception
1652 private static function receiveConversation(array $importer, $msg, $data)
1654 $author = XML::unescape($data->author);
1655 $guid = XML::unescape($data->guid);
1656 $subject = XML::unescape($data->subject);
1657 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1658 $participants = XML::unescape($data->participants);
1660 $messages = $data->message;
1662 if (!count($messages)) {
1663 Logger::notice("empty conversation");
1667 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1672 if (!empty($contact['gsid'])) {
1673 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1676 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1677 if (!DBA::isResult($conversation)) {
1678 $r = DBA::insert('conv', [
1679 'uid' => $importer['uid'],
1681 'creator' => $author,
1682 'created' => $created_at,
1683 'updated' => DateTimeFormat::utcNow(),
1684 'subject' => $subject,
1685 'recips' => $participants]);
1687 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1690 if (!$conversation) {
1691 Logger::notice("unable to create conversation.");
1695 foreach ($messages as $mesg) {
1696 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1703 * Processes "like" messages
1705 * @param array $importer Array of the importer user
1706 * @param string $sender The sender of the message
1707 * @param object $data The message object
1708 * @param int $direction Indicates if the message had been fetched or pushed
1710 * @return int The message id of the generated like or "false" if there was an error
1711 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1712 * @throws \ImagickException
1714 private static function receiveLike(array $importer, $sender, $data, int $direction)
1716 $author = XML::unescape($data->author);
1717 $guid = XML::unescape($data->guid);
1718 $parent_guid = XML::unescape($data->parent_guid);
1719 $parent_type = XML::unescape($data->parent_type);
1720 $positive = XML::unescape($data->positive);
1722 // likes on comments aren't supported by Diaspora - only on posts
1723 // But maybe this will be supported in the future, so we will accept it.
1724 if (!in_array($parent_type, ["Post", "Comment"])) {
1728 $contact = self::allowedContactByHandle($importer, $sender, true);
1733 if (!empty($contact['gsid'])) {
1734 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1737 $message_id = self::messageExists($importer["uid"], $guid);
1742 $toplevel_parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1743 if (!$toplevel_parent_item) {
1747 $person = FContact::getByURL($author);
1748 if (!is_array($person)) {
1749 Logger::notice("unable to find author details");
1753 // Fetch the contact id - if we know this contact
1754 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1756 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1757 // We would accept this anyhow.
1758 if ($positive == "true") {
1759 $verb = Activity::LIKE;
1761 $verb = Activity::DISLIKE;
1766 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1767 $datarray["direction"] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
1769 $datarray["uid"] = $importer["uid"];
1770 $datarray["contact-id"] = $author_contact["cid"];
1771 $datarray["network"] = $author_contact["network"];
1773 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
1774 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1776 $datarray["guid"] = $guid;
1777 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1779 $datarray["verb"] = $verb;
1780 $datarray["gravity"] = GRAVITY_ACTIVITY;
1781 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1783 $datarray["object-type"] = Activity\ObjectType::NOTE;
1785 $datarray["body"] = $verb;
1787 // Diaspora doesn't provide a date for likes
1788 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
1790 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1791 if ($toplevel_parent_item['gravity'] != GRAVITY_PARENT) {
1792 $toplevel = Post::selectFirst(['origin'], ['id' => $toplevel_parent_item['parent']]);
1793 $origin = $toplevel["origin"];
1795 $origin = $toplevel_parent_item["origin"];
1798 // If we are the origin of the parent we store the original data.
1799 // We notify our followers during the item storage.
1801 $datarray['diaspora_signed_text'] = json_encode($data);
1804 if (Item::isTooOld($datarray)) {
1805 Logger::info('Like is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1809 $message_id = Item::insert($datarray);
1811 if ($message_id <= 0) {
1816 Logger::info("Stored like ".$datarray["guid"]." with message id ".$message_id);
1817 if ($datarray['uid'] == 0) {
1818 Item::distribute($message_id, json_encode($data));
1826 * Processes private messages
1828 * @param array $importer Array of the importer user
1829 * @param object $data The message object
1831 * @return bool Success?
1832 * @throws \Exception
1834 private static function receiveMessage(array $importer, $data)
1836 $author = XML::unescape($data->author);
1837 $guid = XML::unescape($data->guid);
1838 $conversation_guid = XML::unescape($data->conversation_guid);
1839 $text = XML::unescape($data->text);
1840 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1842 $contact = self::allowedContactByHandle($importer, $author, true);
1847 if (!empty($contact['gsid'])) {
1848 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1851 $conversation = null;
1853 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
1854 $conversation = DBA::selectFirst('conv', [], $condition);
1856 if (!DBA::isResult($conversation)) {
1857 Logger::notice("conversation not available.");
1861 $message_uri = $author.":".$guid;
1863 $person = FContact::getByURL($author);
1865 Logger::notice("unable to find author details");
1869 $body = Markdown::toBBCode($text);
1871 $body = self::replacePeopleGuid($body, $person["url"]);
1873 return Mail::insert([
1874 'uid' => $importer['uid'],
1876 'convid' => $conversation['id'],
1877 'from-name' => $person['name'],
1878 'from-photo' => $person['photo'],
1879 'from-url' => $person['url'],
1880 'contact-id' => $contact['id'],
1881 'title' => $conversation['subject'],
1884 'uri' => $message_uri,
1885 'parent-uri' => $author.":".$conversation['guid'],
1886 'created' => $created_at
1891 * Processes participations - unsupported by now
1893 * @param array $importer Array of the importer user
1894 * @param object $data The message object
1895 * @param int $direction Indicates if the message had been fetched or pushed
1897 * @return bool success
1898 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1899 * @throws \ImagickException
1901 private static function receiveParticipation(array $importer, $data, int $direction)
1903 $author = strtolower(XML::unescape($data->author));
1904 $guid = XML::unescape($data->guid);
1905 $parent_guid = XML::unescape($data->parent_guid);
1907 $contact = self::allowedContactByHandle($importer, $author, true);
1912 if (!empty($contact['gsid'])) {
1913 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1916 if (self::messageExists($importer["uid"], $guid)) {
1920 $toplevel_parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1921 if (!$toplevel_parent_item) {
1925 if (!$toplevel_parent_item['origin']) {
1926 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1929 if (!in_array($toplevel_parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
1930 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1934 $person = FContact::getByURL($author);
1935 if (!is_array($person)) {
1936 Logger::notice("Person not found: ".$author);
1940 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1942 // Store participation
1945 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1946 $datarray["direction"] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
1948 $datarray["uid"] = $importer["uid"];
1949 $datarray["contact-id"] = $author_contact["cid"];
1950 $datarray["network"] = $author_contact["network"];
1952 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
1953 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1955 $datarray["guid"] = $guid;
1956 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1958 $datarray["verb"] = Activity::FOLLOW;
1959 $datarray["gravity"] = GRAVITY_ACTIVITY;
1960 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1962 $datarray["object-type"] = Activity\ObjectType::NOTE;
1964 $datarray["body"] = Activity::FOLLOW;
1966 // Diaspora doesn't provide a date for a participation
1967 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
1969 if (Item::isTooOld($datarray)) {
1970 Logger::info('Participation is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1974 $message_id = Item::insert($datarray);
1976 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
1978 // Send all existing comments and likes to the requesting server
1979 $comments = Post::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb'],
1980 ['parent' => $toplevel_parent_item['id'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
1981 while ($comment = Post::fetch($comments)) {
1982 if (in_array($comment['verb'], [Activity::FOLLOW, Activity::TAG])) {
1983 Logger::info('participation messages are not relayed', ['item' => $comment['id']]);
1987 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
1988 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
1992 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
1993 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
1997 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact["cid"]]);
1998 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $author_contact["cid"])) {
1999 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2002 DBA::close($comments);
2008 * Processes photos - unneeded
2010 * @param array $importer Array of the importer user
2011 * @param object $data The message object
2013 * @return bool always true
2015 private static function receivePhoto(array $importer, $data)
2017 // There doesn't seem to be a reason for this function,
2018 // since the photo data is transmitted in the status message as well
2023 * Processes poll participations - unssupported
2025 * @param array $importer Array of the importer user
2026 * @param object $data The message object
2028 * @return bool always true
2030 private static function receivePollParticipation(array $importer, $data)
2032 // We don't support polls by now
2037 * Processes incoming profile updates
2039 * @param array $importer Array of the importer user
2040 * @param object $data The message object
2042 * @return bool Success
2043 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2044 * @throws \ImagickException
2046 private static function receiveProfile(array $importer, $data)
2048 $author = strtolower(XML::unescape($data->author));
2050 $contact = self::contactByHandle($importer["uid"], $author);
2055 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2056 $image_url = XML::unescape($data->image_url);
2057 $birthday = XML::unescape($data->birthday);
2058 $about = Markdown::toBBCode(XML::unescape($data->bio));
2059 $location = Markdown::toBBCode(XML::unescape($data->location));
2060 $searchable = (XML::unescape($data->searchable) == "true");
2061 $nsfw = (XML::unescape($data->nsfw) == "true");
2062 $tags = XML::unescape($data->tag_string);
2064 $tags = explode("#", $tags);
2067 foreach ($tags as $tag) {
2068 $tag = trim(strtolower($tag));
2074 $keywords = implode(", ", $keywords);
2076 $handle_parts = explode("@", $author);
2077 $nick = $handle_parts[0];
2080 $name = $handle_parts[0];
2083 if (preg_match("|^https?://|", $image_url) === 0) {
2084 $image_url = "http://".$handle_parts[1].$image_url;
2087 Contact::updateAvatar($contact["id"], $image_url);
2089 // Generic birthday. We don't know the timezone. The year is irrelevant.
2091 $birthday = str_replace("1000", "1901", $birthday);
2093 if ($birthday != "") {
2094 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2097 // this is to prevent multiple birthday notifications in a single year
2098 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2100 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2101 $birthday = $contact["bd"];
2104 $fields = ['name' => $name, 'location' => $location,
2105 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2106 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2107 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2109 if (!empty($birthday)) {
2110 $fields['bd'] = $birthday;
2113 Contact::update($fields, ['id' => $contact['id']]);
2115 Logger::info("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"]);
2121 * Processes incoming friend requests
2123 * @param array $importer Array of the importer user
2124 * @param array $contact The contact that send the request
2126 * @throws \Exception
2128 private static function receiveRequestMakeFriend(array $importer, array $contact)
2130 if ($contact["rel"] == Contact::SHARING) {
2132 ['rel' => Contact::FRIEND, 'writable' => true],
2133 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2139 * Processes incoming sharing notification
2141 * @param array $importer Array of the importer user
2142 * @param object $data The message object
2144 * @return bool Success
2145 * @throws \Exception
2147 private static function receiveContactRequest(array $importer, $data)
2149 $author = XML::unescape($data->author);
2150 $recipient = XML::unescape($data->recipient);
2152 if (!$author || !$recipient) {
2156 // the current protocol version doesn't know these fields
2157 // That means that we will assume their existance
2158 if (isset($data->following)) {
2159 $following = (XML::unescape($data->following) == "true");
2164 if (isset($data->sharing)) {
2165 $sharing = (XML::unescape($data->sharing) == "true");
2170 $contact = self::contactByHandle($importer["uid"], $author);
2172 // perhaps we were already sharing with this person. Now they're sharing with us.
2173 // That makes us friends.
2176 Logger::info("Author ".$author." (Contact ".$contact["id"].") wants to follow us.");
2177 self::receiveRequestMakeFriend($importer, $contact);
2179 // refetch the contact array
2180 $contact = self::contactByHandle($importer["uid"], $author);
2182 // If we are now friends, we are sending a share message.
2183 // Normally we needn't to do so, but the first message could have been vanished.
2184 if (in_array($contact["rel"], [Contact::FRIEND])) {
2185 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2186 if (DBA::isResult($user)) {
2187 Logger::info("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"]);
2188 self::sendShare($user, $contact);
2193 Logger::info("Author ".$author." doesn't want to follow us anymore.");
2194 Contact::removeFollower($contact);
2199 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2200 Logger::info("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.");
2202 } elseif (!$following && !$sharing) {
2203 Logger::info("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.");
2205 } elseif (!$following && $sharing) {
2206 Logger::info("Author ".$author." wants to share with us.");
2207 } elseif ($following && $sharing) {
2208 Logger::info("Author ".$author." wants to have a bidirectional conection.");
2209 } elseif ($following && !$sharing) {
2210 Logger::info("Author ".$author." wants to listen to us.");
2213 $ret = FContact::getByURL($author);
2215 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2216 Logger::notice("Cannot resolve diaspora handle ".$author." for ".$recipient);
2220 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2222 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2227 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2228 'author-link' => $ret['url']];
2230 $result = Contact::addRelationship($importer, $contact, $item, false);
2231 if ($result === true) {
2232 $contact_record = self::contactByHandle($importer['uid'], $author);
2233 if (!$contact_record) {
2234 Logger::info('unable to locate newly created contact record.');
2238 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2239 if (DBA::isResult($user)) {
2240 self::sendShare($user, $contact_record);
2242 // Send the profile data, maybe it weren't transmitted before
2243 self::sendProfile($importer['uid'], [$contact_record]);
2251 * Fetches a message with a given guid
2253 * @param string $guid message guid
2254 * @param string $orig_author handle of the original post
2255 * @return array The fetched item
2256 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2257 * @throws \ImagickException
2259 public static function originalItem($guid, $orig_author)
2262 Logger::notice('Empty guid. Quitting.');
2266 // Do we already have this item?
2267 $fields = ['body', 'title', 'app', 'created', 'object-type', 'uri', 'guid',
2268 'author-name', 'author-link', 'author-avatar', 'plink', 'uri-id'];
2269 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2270 $item = Post::selectFirst($fields, $condition);
2272 if (DBA::isResult($item)) {
2273 Logger::notice("reshared message ".$guid." already exists on system.");
2275 // Maybe it is already a reshared item?
2276 // Then refetch the content, if it is a reshare from a reshare.
2277 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2278 if (self::isReshare($item["body"], true)) {
2280 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2281 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2283 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2291 if (!DBA::isResult($item)) {
2292 if (empty($orig_author)) {
2293 Logger::notice('Empty author for guid ' . $guid . '. Quitting.');
2297 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2298 Logger::notice("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2299 $stored = self::storeByGuid($guid, $server, true);
2302 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2303 Logger::notice("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2304 $stored = self::storeByGuid($guid, $server, true);
2308 $fields = ['body', 'title', 'app', 'created', 'object-type', 'uri', 'guid',
2309 'author-name', 'author-link', 'author-avatar', 'plink', 'uri-id'];
2310 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2311 $item = Post::selectFirst($fields, $condition);
2313 if (DBA::isResult($item)) {
2314 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2315 if (self::isReshare($item["body"], false)) {
2316 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2317 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2328 * Stores a reshare activity
2330 * @param array $item Array of reshare post
2331 * @param integer $parent_message_id Id of the parent post
2332 * @param string $guid GUID string of reshare action
2333 * @param string $author Author handle
2335 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2337 $parent = Post::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2341 $datarray['uid'] = $item['uid'];
2342 $datarray['contact-id'] = $item['contact-id'];
2343 $datarray['network'] = $item['network'];
2345 $datarray['author-link'] = $item['author-link'];
2346 $datarray['author-id'] = $item['author-id'];
2348 $datarray['owner-link'] = $datarray['author-link'];
2349 $datarray['owner-id'] = $datarray['author-id'];
2351 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2352 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2353 $datarray['thr-parent'] = $parent['uri'];
2355 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2356 $datarray['gravity'] = GRAVITY_ACTIVITY;
2357 $datarray['object-type'] = Activity\ObjectType::NOTE;
2359 $datarray['protocol'] = $item['protocol'];
2360 $datarray['source'] = $item['source'];
2361 $datarray['direction'] = $item['direction'];
2363 $datarray['plink'] = self::plink($author, $datarray['guid']);
2364 $datarray['private'] = $item['private'];
2365 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2367 if (Item::isTooOld($datarray)) {
2368 Logger::info('Reshare activity is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2372 $message_id = Item::insert($datarray);
2375 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2376 if ($datarray['uid'] == 0) {
2377 Item::distribute($message_id);
2383 * Processes a reshare message
2385 * @param array $importer Array of the importer user
2386 * @param object $data The message object
2387 * @param string $xml The original XML of the message
2388 * @param int $direction Indicates if the message had been fetched or pushed
2390 * @return int the message id
2391 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2392 * @throws \ImagickException
2394 private static function receiveReshare(array $importer, $data, $xml, int $direction)
2396 $author = XML::unescape($data->author);
2397 $guid = XML::unescape($data->guid);
2398 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2399 $root_author = XML::unescape($data->root_author);
2400 $root_guid = XML::unescape($data->root_guid);
2401 /// @todo handle unprocessed property "provider_display_name"
2402 $public = XML::unescape($data->public);
2404 $contact = self::allowedContactByHandle($importer, $author, false);
2409 if (!empty($contact['gsid'])) {
2410 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2413 $message_id = self::messageExists($importer["uid"], $guid);
2418 $original_item = self::originalItem($root_guid, $root_author);
2419 if (!$original_item) {
2423 if (empty($original_item['plink'])) {
2424 $original_item['plink'] = self::plink($root_author, $root_guid);
2429 $datarray["uid"] = $importer["uid"];
2430 $datarray["contact-id"] = $contact["id"];
2431 $datarray["network"] = Protocol::DIASPORA;
2433 $datarray["author-link"] = $contact["url"];
2434 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2436 $datarray["owner-link"] = $datarray["author-link"];
2437 $datarray["owner-id"] = $datarray["author-id"];
2439 $datarray["guid"] = $guid;
2440 $datarray["uri"] = $datarray["thr-parent"] = self::getUriFromGuid($author, $guid);
2441 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2443 $datarray["verb"] = Activity::POST;
2444 $datarray["gravity"] = GRAVITY_PARENT;
2446 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2447 $datarray["source"] = $xml;
2448 $datarray["direction"] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
2450 /// @todo Copy tag data from original post
2452 $prefix = BBCode::getShareOpeningTag(
2453 $original_item["author-name"],
2454 $original_item["author-link"],
2455 $original_item["author-avatar"],
2456 $original_item["plink"],
2457 $original_item["created"],
2458 $original_item["guid"]
2461 if (!empty($original_item['title'])) {
2462 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2465 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2467 Tag::storeFromBody($datarray['uri-id'], $datarray["body"]);
2469 $datarray["app"] = $original_item["app"];
2471 $datarray["plink"] = self::plink($author, $guid);
2472 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2473 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2475 $datarray["object-type"] = $original_item["object-type"];
2477 self::fetchGuid($datarray);
2479 if (Item::isTooOld($datarray)) {
2480 Logger::info('Reshare is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2484 $message_id = Item::insert($datarray);
2486 self::sendParticipation($contact, $datarray);
2488 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2489 if ($root_message_id) {
2490 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2494 Logger::info("Stored reshare ".$datarray["guid"]." with message id ".$message_id);
2495 if ($datarray['uid'] == 0) {
2496 Item::distribute($message_id);
2505 * Processes retractions
2507 * @param array $importer Array of the importer user
2508 * @param array $contact The contact of the item owner
2509 * @param object $data The message object
2511 * @return bool success
2512 * @throws \Exception
2514 private static function itemRetraction(array $importer, array $contact, $data)
2516 $author = XML::unescape($data->author);
2517 $target_guid = XML::unescape($data->target_guid);
2518 $target_type = XML::unescape($data->target_type);
2520 $person = FContact::getByURL($author);
2521 if (!is_array($person)) {
2522 Logger::notice("unable to find author detail for ".$author);
2526 if (empty($contact["url"])) {
2527 $contact["url"] = $person["url"];
2530 // Fetch items that are about to be deleted
2531 $fields = ['uid', 'id', 'parent', 'author-link', 'uri-id'];
2533 // When we receive a public retraction, we delete every item that we find.
2534 if ($importer['uid'] == 0) {
2535 $condition = ['guid' => $target_guid, 'deleted' => false];
2537 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2540 $r = Post::select($fields, $condition);
2541 if (!DBA::isResult($r)) {
2542 Logger::notice("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2546 while ($item = Post::fetch($r)) {
2547 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2548 Logger::info("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.");
2552 // Fetch the parent item
2553 $parent = Post::selectFirst(['author-link'], ['id' => $item['parent']]);
2555 // Only delete it if the parent author really fits
2556 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2557 Logger::info("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"]);
2561 Item::markForDeletion(['id' => $item['id']]);
2563 Logger::info("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item['parent']);
2571 * Receives retraction messages
2573 * @param array $importer Array of the importer user
2574 * @param string $sender The sender of the message
2575 * @param object $data The message object
2577 * @return bool Success
2578 * @throws \Exception
2580 private static function receiveRetraction(array $importer, $sender, $data)
2582 $target_type = XML::unescape($data->target_type);
2584 $contact = self::contactByHandle($importer["uid"], $sender);
2585 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2586 Logger::notice("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2594 Logger::info("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"]);
2596 switch ($target_type) {
2601 case "StatusMessage":
2602 return self::itemRetraction($importer, $contact, $data);
2604 case "PollParticipation":
2606 // Currently unsupported
2610 Logger::notice("Unknown target type ".$target_type);
2617 * Checks if an incoming message is wanted
2619 * @param string $url
2620 * @param integer $uriid
2621 * @param string $author
2622 * @param string $body
2623 * @param int $direction Indicates if the message had been fetched or pushed
2625 * @return boolean Is the message wanted?
2627 private static function isSolicitedMessage(string $url, int $uriid, string $author, string $body, int $direction)
2629 $contact = Contact::getByURL($author);
2630 if (DBA::exists('contact', ["`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)",
2631 $contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) {
2632 Logger::debug('Author has got followers - accepted', ['url' => $url, 'author' => $author]);
2636 if ($direction == self::FORCED_FETCH) {
2637 Logger::debug('Post is a forced fetch - accepted', ['url' => $url, 'author' => $author]);
2641 $tags = array_column(Tag::getByURIId($uriid, [Tag::HASHTAG]), 'name');
2642 return Relay::isSolicitedPost($tags, $body, $contact['id'], $url, Protocol::DIASPORA);
2646 * Store an attached photo in the post-media table
2649 * @param object $photo
2652 private static function storePhotoAsMedia(int $uriid, $photo)
2655 $data['uri-id'] = $uriid;
2656 $data['type'] = Post\Media::IMAGE;
2657 $data['url'] = XML::unescape($photo->remote_photo_path) . XML::unescape($photo->remote_photo_name);
2658 $data['height'] = (int)XML::unescape($photo->height ?? 0);
2659 $data['width'] = (int)XML::unescape($photo->width ?? 0);
2660 $data['description'] = XML::unescape($photo->text ?? '');
2662 Post\Media::insert($data);
2666 * Receives status messages
2668 * @param array $importer Array of the importer user
2669 * @param SimpleXMLElement $data The message object
2670 * @param string $xml The original XML of the message
2671 * @param int $direction Indicates if the message had been fetched or pushed
2673 * @return int The message id of the newly created item
2674 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2675 * @throws \ImagickException
2677 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml, int $direction)
2679 $author = XML::unescape($data->author);
2680 $guid = XML::unescape($data->guid);
2681 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2682 $public = XML::unescape($data->public);
2683 $text = XML::unescape($data->text);
2684 $provider_display_name = XML::unescape($data->provider_display_name);
2686 $contact = self::allowedContactByHandle($importer, $author, false);
2691 if (!empty($contact['gsid'])) {
2692 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2695 $message_id = self::messageExists($importer["uid"], $guid);
2701 if ($data->location) {
2702 foreach ($data->location->children() as $fieldname => $data) {
2703 $address[$fieldname] = XML::unescape($data);
2707 $raw_body = $body = Markdown::toBBCode($text);
2711 $datarray["guid"] = $guid;
2712 $datarray["uri"] = $datarray["thr-parent"] = self::getUriFromGuid($author, $guid);
2713 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2715 // Attach embedded pictures to the body
2717 foreach ($data->photo as $photo) {
2718 self::storePhotoAsMedia($datarray['uri-id'], $photo);
2721 $datarray["object-type"] = Activity\ObjectType::IMAGE;
2722 $datarray["post-type"] = Item::PT_IMAGE;
2723 } elseif ($data->poll) {
2724 $datarray["object-type"] = Activity\ObjectType::NOTE;
2725 $datarray["post-type"] = Item::PT_POLL;
2727 $datarray["object-type"] = Activity\ObjectType::NOTE;
2728 $datarray["post-type"] = Item::PT_NOTE;
2731 /// @todo enable support for polls
2732 //if ($data->poll) {
2733 // foreach ($data->poll as $poll)
2738 /// @todo enable support for events
2740 $datarray["uid"] = $importer["uid"];
2741 $datarray["contact-id"] = $contact["id"];
2742 $datarray["network"] = Protocol::DIASPORA;
2744 $datarray["author-link"] = $contact["url"];
2745 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2747 $datarray["owner-link"] = $datarray["author-link"];
2748 $datarray["owner-id"] = $datarray["author-id"];
2750 $datarray["verb"] = Activity::POST;
2751 $datarray["gravity"] = GRAVITY_PARENT;
2753 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2754 $datarray["source"] = $xml;
2755 $datarray["direction"] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
2757 if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
2758 $datarray["post-reason"] = Item::PR_FETCHED;
2759 } elseif ($datarray["uid"] == 0) {
2760 $datarray["post-reason"] = Item::PR_GLOBAL;
2763 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2764 $datarray["raw-body"] = self::replacePeopleGuid($raw_body, $contact["url"]);
2766 self::storeMentions($datarray['uri-id'], $text);
2767 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
2769 if (!self::isSolicitedMessage($datarray["uri"], $datarray['uri-id'], $author, $body, $direction)) {
2770 DBA::delete('item-uri', ['uri' => $datarray['uri']]);
2774 if ($provider_display_name != "") {
2775 $datarray["app"] = $provider_display_name;
2778 $datarray["plink"] = self::plink($author, $guid);
2779 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2780 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2782 if (isset($address["address"])) {
2783 $datarray["location"] = $address["address"];
2786 if (isset($address["lat"]) && isset($address["lng"])) {
2787 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2790 self::fetchGuid($datarray);
2792 if (Item::isTooOld($datarray)) {
2793 Logger::info('Status is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2797 $message_id = Item::insert($datarray);
2799 self::sendParticipation($contact, $datarray);
2802 Logger::info("Stored item ".$datarray["guid"]." with message id ".$message_id);
2803 if ($datarray['uid'] == 0) {
2804 Item::distribute($message_id);
2812 /* ************************************************************************************** *
2813 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2814 * ************************************************************************************** */
2817 * returnes the handle of a contact
2819 * @param array $contact contact array
2821 * @return string the handle in the format user@domain.tld
2822 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2824 private static function myHandle(array $contact)
2826 if (!empty($contact["addr"])) {
2827 return $contact["addr"];
2830 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2831 // So - just in case - we build the the address here.
2832 if ($contact["nickname"] != "") {
2833 $nick = $contact["nickname"];
2835 $nick = $contact["nick"];
2838 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
2843 * Creates the data for a private message in the new format
2845 * @param string $msg The message that is to be transmitted
2846 * @param array $user The record of the sender
2847 * @param array $contact Target of the communication
2848 * @param string $prvkey The private key of the sender
2849 * @param string $pubkey The public key of the receiver
2851 * @return string The encrypted data
2852 * @throws \Exception
2854 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
2856 Logger::debug("Message: ".$msg);
2858 // without a public key nothing will work
2860 Logger::notice("pubkey missing: contact id: ".$contact["id"]);
2864 $aes_key = random_bytes(32);
2865 $b_aes_key = base64_encode($aes_key);
2866 $iv = random_bytes(16);
2867 $b_iv = base64_encode($iv);
2869 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2871 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
2873 $encrypted_key_bundle = "";
2874 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
2878 $json_object = json_encode(
2879 ["aes_key" => base64_encode($encrypted_key_bundle),
2880 "encrypted_magic_envelope" => base64_encode($ciphertext)]
2883 return $json_object;
2887 * Creates the envelope for the "fetch" endpoint and for the new format
2889 * @param string $msg The message that is to be transmitted
2890 * @param array $user The record of the sender
2892 * @return string The envelope
2893 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2895 public static function buildMagicEnvelope($msg, array $user)
2897 $b64url_data = Strings::base64UrlEncode($msg);
2898 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
2900 $key_id = Strings::base64UrlEncode(self::myHandle($user));
2901 $type = "application/xml";
2902 $encoding = "base64url";
2903 $alg = "RSA-SHA256";
2904 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
2906 // Fallback if the private key wasn't transmitted in the expected field
2907 if ($user['uprvkey'] == "") {
2908 $user['uprvkey'] = $user['prvkey'];
2911 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
2912 $sig = Strings::base64UrlEncode($signature);
2914 $xmldata = ["me:env" => ["me:data" => $data,
2915 "@attributes" => ["type" => $type],
2916 "me:encoding" => $encoding,
2919 "@attributes2" => ["key_id" => $key_id]]];
2921 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
2923 return XML::fromArray($xmldata, $xml, false, $namespaces);
2927 * Create the envelope for a message
2929 * @param string $msg The message that is to be transmitted
2930 * @param array $user The record of the sender
2931 * @param array $contact Target of the communication
2932 * @param string $prvkey The private key of the sender
2933 * @param string $pubkey The public key of the receiver
2934 * @param bool $public Is the message public?
2936 * @return string The message that will be transmitted to other servers
2937 * @throws \Exception
2939 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
2941 // The message is put into an envelope with the sender's signature
2942 $envelope = self::buildMagicEnvelope($msg, $user);
2944 // Private messages are put into a second envelope, encrypted with the receivers public key
2946 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
2953 * Creates a signature for a message
2955 * @param array $owner the array of the owner of the message
2956 * @param array $message The message that is to be signed
2958 * @return string The signature
2960 private static function signature($owner, $message)
2963 unset($sigmsg["author_signature"]);
2964 unset($sigmsg["parent_author_signature"]);
2966 $signed_text = implode(";", $sigmsg);
2968 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
2972 * Transmit a message to a target server
2974 * @param array $owner the array of the item owner
2975 * @param array $contact Target of the communication
2976 * @param string $envelope The message that is to be transmitted
2977 * @param bool $public_batch Is it a public post?
2978 * @param string $guid message guid
2980 * @return int Result of the transmission
2981 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2982 * @throws \ImagickException
2984 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
2986 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
2991 $logid = Strings::getRandomHex(4);
2993 // We always try to use the data from the fcontact table.
2994 // This is important for transmitting data to Friendica servers.
2995 if (!empty($contact['addr'])) {
2996 $fcontact = FContact::getByURL($contact['addr']);
2997 if (!empty($fcontact)) {
2998 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3002 if (empty($dest_url)) {
3003 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3007 Logger::notice("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3011 Logger::notice("transmit: ".$logid."-".$guid." ".$dest_url);
3013 if (!intval(DI::config()->get("system", "diaspora_test"))) {
3014 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3016 $postResult = DI::httpClient()->post($dest_url . "/", $envelope, ['Content-Type' => $content_type]);
3017 $return_code = $postResult->getReturnCode();
3019 Logger::notice("test_mode");
3023 Logger::notice("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3025 return $return_code ? $return_code : -1;
3030 * Build the post xml
3032 * @param string $type The message type
3033 * @param array $message The message data
3035 * @return string The post XML
3037 public static function buildPostXml($type, $message)
3039 $data = [$type => $message];
3041 return XML::fromArray($data, $xml);
3045 * Builds and transmit messages
3047 * @param array $owner the array of the item owner
3048 * @param array $contact Target of the communication
3049 * @param string $type The message type
3050 * @param array $message The message data
3051 * @param bool $public_batch Is it a public post?
3052 * @param string $guid message guid
3054 * @return int Result of the transmission
3055 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3056 * @throws \ImagickException
3058 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3060 $msg = self::buildPostXml($type, $message);
3062 // Fallback if the private key wasn't transmitted in the expected field
3063 if (empty($owner['uprvkey'])) {
3064 $owner['uprvkey'] = $owner['prvkey'];
3067 // When sending content to Friendica contacts using the Diaspora protocol
3068 // we have to fetch the public key from the fcontact.
3069 // This is due to the fact that legacy DFRN had unique keys for every contact.
3070 $pubkey = $contact['pubkey'];
3071 if (!empty($contact['addr'])) {
3072 $fcontact = FContact::getByURL($contact['addr']);
3073 if (!empty($fcontact)) {
3074 $pubkey = $fcontact['pubkey'];
3077 // The "addr" field should always be filled.
3078 // If this isn't the case, it will raise a notice some lines later.
3079 // And in the log we will see where it came from and we can handle it there.
3080 Logger::notice('Empty addr', ['contact' => $contact ?? [], 'callstack' => System::callstack(20)]);
3083 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
3085 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3087 Logger::info('Transmitted message', ['owner' => $owner['uid'], 'target' => $contact['addr'], 'type' => $type, 'guid' => $guid, 'result' => $return_code]);
3089 return $return_code;
3093 * sends a participation (Used to get all further updates)
3095 * @param array $contact Target of the communication
3096 * @param array $item Item array
3098 * @return int The result of the transmission
3099 * @throws \Exception
3101 private static function sendParticipation(array $contact, array $item)
3103 // Don't send notifications for private postings
3104 if ($item['private'] == Item::PRIVATE) {
3108 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3110 $result = DI::cache()->get($cachekey);
3111 if (!is_null($result)) {
3115 // Fetch some user id to have a valid handle to transmit the participation.
3116 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3117 // If the item belongs to a user, we take this user id.
3118 if ($item['uid'] == 0) {
3119 // @todo Possibly use an administrator account?
3120 $condition = ['verified' => true, 'blocked' => false,
3121 'account_removed' => false, 'account_expired' => false, 'account-type' => User::ACCOUNT_TYPE_PERSON];
3122 $first_user = DBA::selectFirst('user', ['uid'], $condition, ['order' => ['uid']]);
3123 $owner = User::getOwnerDataById($first_user['uid']);
3125 $owner = User::getOwnerDataById($item['uid']);
3128 $author = self::myHandle($owner);
3130 $message = ["author" => $author,
3131 "guid" => System::createUUID(),
3132 "parent_type" => "Post",
3133 "parent_guid" => $item["guid"]];
3135 Logger::info("Send participation for ".$item["guid"]." by ".$author);
3137 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3138 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3140 return self::buildAndTransmit($owner, $contact, "participation", $message);
3144 * sends an account migration
3146 * @param array $owner the array of the item owner
3147 * @param array $contact Target of the communication
3148 * @param int $uid User ID
3150 * @return int The result of the transmission
3151 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3152 * @throws \ImagickException
3154 public static function sendAccountMigration(array $owner, array $contact, $uid)
3156 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3157 $profile = self::createProfileData($uid);
3159 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3160 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3162 $message = ["author" => $old_handle,
3163 "profile" => $profile,
3164 "signature" => $signature];
3166 Logger::info('Send account migration', ['msg' => $message]);
3168 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3172 * Sends a "share" message
3174 * @param array $owner the array of the item owner
3175 * @param array $contact Target of the communication
3177 * @return int The result of the transmission
3178 * @throws \Exception
3180 public static function sendShare(array $owner, array $contact)
3183 * @todo support the different possible combinations of "following" and "sharing"
3184 * Currently, Diaspora only interprets the "sharing" field
3186 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3190 switch ($contact["rel"]) {
3191 case Contact::FRIEND:
3195 case Contact::SHARING:
3199 case Contact::FOLLOWER:
3205 $message = ["author" => self::myHandle($owner),
3206 "recipient" => $contact["addr"],
3207 "following" => "true",
3208 "sharing" => "true"];
3210 Logger::info('Send share', ['msg' => $message]);
3212 return self::buildAndTransmit($owner, $contact, "contact", $message);
3216 * sends an "unshare"
3218 * @param array $owner the array of the item owner
3219 * @param array $contact Target of the communication
3221 * @return int The result of the transmission
3222 * @throws \Exception
3224 public static function sendUnshare(array $owner, array $contact)
3226 $message = ["author" => self::myHandle($owner),
3227 "recipient" => $contact["addr"],
3228 "following" => "false",
3229 "sharing" => "false"];
3231 Logger::info('Send unshare', ['msg' => $message]);
3233 return self::buildAndTransmit($owner, $contact, "contact", $message);
3237 * Checks a message body if it is a reshare
3239 * @param string $body The message body that is to be check
3240 * @param bool $complete Should it be a complete check or a simple check?
3242 * @return array|bool Reshare details or "false" if no reshare
3243 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3244 * @throws \ImagickException
3246 public static function isReshare($body, $complete = true)
3248 $body = trim($body);
3250 $reshared = Item::getShareArray(['body' => $body]);
3251 if (empty($reshared)) {
3255 // Skip if it isn't a pure repeated messages
3256 // Does it start with a share?
3257 if (!empty($reshared['comment']) && $complete) {
3261 if (!empty($reshared['guid']) && $complete) {
3262 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3263 $item = Post::selectFirst(['contact-id'], $condition);
3264 if (DBA::isResult($item)) {
3266 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3267 $ret["root_guid"] = $reshared['guid'];
3269 } elseif ($complete) {
3270 // We are resharing something that isn't a DFRN or Diaspora post.
3271 // So we have to return "false" on "$complete" to not trigger a reshare.
3274 } elseif (empty($reshared['guid']) && $complete) {
3280 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3281 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3282 if (!empty($contact['addr'])) {
3283 $ret['root_handle'] = $contact['addr'];
3287 if (empty($ret) && !$complete) {
3295 * Create an event array
3297 * @param integer $event_id The id of the event
3299 * @return array with event data
3300 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3302 private static function buildEvent($event_id)
3304 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
3305 if (!DBA::isResult($event)) {
3311 $owner = User::getOwnerDataById($event['uid']);
3316 $eventdata['author'] = self::myHandle($owner);
3318 if ($event['guid']) {
3319 $eventdata['guid'] = $event['guid'];
3322 $mask = DateTimeFormat::ATOM;
3324 /// @todo - establish "all day" events in Friendica
3325 $eventdata["all_day"] = "false";
3327 $eventdata['timezone'] = 'UTC';
3329 if ($event['start']) {
3330 $eventdata['start'] = DateTimeFormat::utc($event['start'], $mask);
3332 if ($event['finish'] && !$event['nofinish']) {
3333 $eventdata['end'] = DateTimeFormat::utc($event['finish'], $mask);
3335 if ($event['summary']) {
3336 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3338 if ($event['desc']) {
3339 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3341 if ($event['location']) {
3342 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3343 $coord = Map::getCoordinates($event['location']);
3346 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3347 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3348 $location["lat"] = $coord['lat'];
3349 $location["lng"] = $coord['lon'];
3351 $location["lat"] = 0;
3352 $location["lng"] = 0;
3354 $eventdata['location'] = $location;
3361 * Create a post (status message or reshare)
3363 * @param array $item The item that will be exported
3364 * @param array $owner the array of the item owner
3367 * 'type' -> Message type ("status_message" or "reshare")
3368 * 'message' -> Array of XML elements of the status
3369 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3370 * @throws \ImagickException
3372 public static function buildStatus(array $item, array $owner)
3374 $cachekey = "diaspora:buildStatus:".$item['guid'];
3376 $result = DI::cache()->get($cachekey);
3377 if (!is_null($result)) {
3381 $myaddr = self::myHandle($owner);
3383 $public = ($item["private"] == Item::PRIVATE ? "false" : "true");
3384 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3385 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3387 // Detect a share element and do a reshare
3388 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) {
3389 $message = ["author" => $myaddr,
3390 "guid" => $item["guid"],
3391 "created_at" => $created,
3392 "root_author" => $ret["root_handle"],
3393 "root_guid" => $ret["root_guid"],
3394 "provider_display_name" => $item["app"],
3395 "public" => $public];
3399 $title = $item["title"];
3400 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
3402 // Fetch the title from an attached link - if there is one
3403 if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3404 $page_data = BBCode::getAttachmentData($item['body']);
3405 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3406 $title = $page_data['title'];
3410 if ($item['author-link'] != $item['owner-link']) {
3411 $body = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'],
3412 $item['plink'], $item['created']) . $body . '[/share]';
3415 // convert to markdown
3416 $body = html_entity_decode(BBCode::toMarkdown($body));
3419 if (strlen($title)) {
3420 $body = "### ".html_entity_decode($title)."\n\n".$body;
3423 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]);
3424 if (!empty($attachments)) {
3425 $body .= "\n[hr]\n";
3426 foreach ($attachments as $attachment) {
3427 $body .= "[" . $attachment['description'] . "](" . $attachment['url'] . ")\n";
3433 if ($item["location"] != "")
3434 $location["address"] = $item["location"];
3436 if ($item["coord"] != "") {
3437 $coord = explode(" ", $item["coord"]);
3438 $location["lat"] = $coord[0];
3439 $location["lng"] = $coord[1];
3442 $message = ["author" => $myaddr,
3443 "guid" => $item["guid"],
3444 "created_at" => $created,
3445 "edited_at" => $edited,
3446 "public" => $public,
3448 "provider_display_name" => $item["app"],
3449 "location" => $location];
3451 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3452 if (!isset($location["lat"]) || !isset($location["lng"])) {
3453 unset($message["location"]);
3456 if ($item['event-id'] > 0) {
3457 $event = self::buildEvent($item['event-id']);
3458 if (count($event)) {
3459 $message['event'] = $event;
3461 if (!empty($event['location']['address']) &&
3462 !empty($event['location']['lat']) &&
3463 !empty($event['location']['lng'])) {
3464 $message['location'] = $event['location'];
3467 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3468 // $message['text'] = '';
3472 $type = "status_message";
3475 $msg = ["type" => $type, "message" => $message];
3477 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3482 private static function prependParentAuthorMention($body, $profile_url)
3484 $profile = Contact::getByURL($profile_url, false, ['addr', 'name']);
3485 if (!empty($profile['addr'])
3486 && !strstr($body, $profile['addr'])
3487 && !strstr($body, $profile_url)
3489 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3498 * @param array $item The item that will be exported
3499 * @param array $owner the array of the item owner
3500 * @param array $contact Target of the communication
3501 * @param bool $public_batch Is it a public post?
3503 * @return int The result of the transmission
3504 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3505 * @throws \ImagickException
3507 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3509 $status = self::buildStatus($item, $owner);
3511 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3515 * Creates a "like" object
3517 * @param array $item The item that will be exported
3518 * @param array $owner the array of the item owner
3520 * @return array The data for a "like"
3521 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3523 private static function constructLike(array $item, array $owner)
3525 $parent = Post::selectFirst(['guid', 'uri', 'thr-parent'], ['uri' => $item["thr-parent"]]);
3526 if (!DBA::isResult($parent)) {
3530 $target_type = ($parent["uri"] === $parent["thr-parent"] ? "Post" : "Comment");
3532 if ($item['verb'] === Activity::LIKE) {
3534 } elseif ($item['verb'] === Activity::DISLIKE) {
3535 $positive = "false";
3538 return(["author" => self::myHandle($owner),
3539 "guid" => $item["guid"],
3540 "parent_guid" => $parent["guid"],
3541 "parent_type" => $target_type,
3542 "positive" => $positive,
3543 "author_signature" => ""]);
3547 * Creates an "EventParticipation" object
3549 * @param array $item The item that will be exported
3550 * @param array $owner the array of the item owner
3552 * @return array The data for an "EventParticipation"
3553 * @throws \Exception
3555 private static function constructAttend(array $item, array $owner)
3557 $parent = Post::selectFirst(['guid'], ['uri' => $item['thr-parent']]);
3558 if (!DBA::isResult($parent)) {
3562 switch ($item['verb']) {
3563 case Activity::ATTEND:
3564 $attend_answer = 'accepted';
3566 case Activity::ATTENDNO:
3567 $attend_answer = 'declined';
3569 case Activity::ATTENDMAYBE:
3570 $attend_answer = 'tentative';
3573 Logger::notice('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3577 return(["author" => self::myHandle($owner),
3578 "guid" => $item["guid"],
3579 "parent_guid" => $parent["guid"],
3580 "status" => $attend_answer,
3581 "author_signature" => ""]);
3585 * Creates the object for a comment
3587 * @param array $item The item that will be exported
3588 * @param array $owner the array of the item owner
3590 * @return array|false The data for a comment
3591 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3593 private static function constructComment(array $item, array $owner)
3595 $cachekey = "diaspora:constructComment:".$item['guid'];
3597 $result = DI::cache()->get($cachekey);
3598 if (!is_null($result)) {
3602 $toplevel_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3603 if (!DBA::isResult($toplevel_item)) {
3604 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3608 $thread_parent_item = $toplevel_item;
3609 if ($item['thr-parent'] != $item['parent-uri']) {
3610 $thread_parent_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3613 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
3615 // The replied to autor mention is prepended for clarity if:
3616 // - Item replied isn't yours
3617 // - Item is public or explicit mentions are disabled
3618 // - Implicit mentions are enabled
3620 $item['author-id'] != $thread_parent_item['author-id']
3621 && ($thread_parent_item['gravity'] != GRAVITY_PARENT)
3622 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3623 && !DI::config()->get('system', 'disable_implicit_mentions')
3625 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3628 $text = html_entity_decode(BBCode::toMarkdown($body));
3629 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3630 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3633 "author" => self::myHandle($owner),
3634 "guid" => $item["guid"],
3635 "created_at" => $created,
3636 "edited_at" => $edited,
3637 "parent_guid" => $toplevel_item["guid"],
3639 "author_signature" => ""
3642 // Send the thread parent guid only if it is a threaded comment
3643 if ($item['thr-parent'] != $item['parent-uri']) {
3644 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3647 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3653 * Send a like or a comment
3655 * @param array $item The item that will be exported
3656 * @param array $owner the array of the item owner
3657 * @param array $contact Target of the communication
3658 * @param bool $public_batch Is it a public post?
3660 * @return int The result of the transmission
3661 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3662 * @throws \ImagickException
3664 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3666 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3667 $message = self::constructAttend($item, $owner);
3668 $type = "event_participation";
3669 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3670 $message = self::constructLike($item, $owner);
3672 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3673 $message = self::constructComment($item, $owner);
3677 if (empty($message)) {
3681 $message["author_signature"] = self::signature($owner, $message);
3683 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3687 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
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 \Exception
3697 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3699 if ($item["deleted"]) {
3700 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3701 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3707 Logger::info("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")");
3709 $msg = json_decode($item['signed_text'], true);
3712 if (is_array($msg)) {
3713 foreach ($msg as $field => $data) {
3714 if (!$item["deleted"]) {
3715 if ($field == "diaspora_handle") {
3718 if ($field == "target_type") {
3719 $field = "parent_type";
3723 $message[$field] = $data;
3726 Logger::info("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text']);
3729 $message["parent_author_signature"] = self::signature($owner, $message);
3731 Logger::info('Relayed data', ['msg' => $message]);
3733 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3737 * Sends a retraction (deletion) of a message, like or comment
3739 * @param array $item The item that will be exported
3740 * @param array $owner the array of the item owner
3741 * @param array $contact Target of the communication
3742 * @param bool $public_batch Is it a public post?
3743 * @param bool $relay Is the retraction transmitted from a relay?
3745 * @return int The result of the transmission
3746 * @throws \Exception
3748 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
3750 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3752 $msg_type = "retraction";
3754 if ($item['gravity'] == GRAVITY_PARENT) {
3755 $target_type = "Post";
3756 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3757 $target_type = "Like";
3759 $target_type = "Comment";
3762 $message = ["author" => $itemaddr,
3763 "target_guid" => $item['guid'],
3764 "target_type" => $target_type];
3766 Logger::info('Got message', ['msg' => $message]);
3768 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3774 * @param array $item The item that will be exported
3775 * @param array $owner The owner
3776 * @param array $contact Target of the communication
3778 * @return int The result of the transmission
3779 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3780 * @throws \ImagickException
3782 public static function sendMail(array $item, array $owner, array $contact)
3784 $myaddr = self::myHandle($owner);
3786 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
3787 if (!DBA::isResult($cnv)) {
3788 Logger::notice("conversation not found.");
3792 $body = BBCode::toMarkdown($item["body"]);
3793 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3796 "author" => $myaddr,
3797 "guid" => $item["guid"],
3798 "conversation_guid" => $cnv["guid"],
3800 "created_at" => $created,
3803 if ($item["reply"]) {
3808 "author" => $cnv["creator"],
3809 "guid" => $cnv["guid"],
3810 "subject" => $cnv["subject"],
3811 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3812 "participants" => $cnv["recips"],
3816 $type = "conversation";
3819 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
3823 * Split a name into first name and last name
3825 * @param string $name The name
3827 * @return array The array with "first" and "last"
3829 public static function splitName($name) {
3830 $name = trim($name);
3832 // Is the name longer than 64 characters? Then cut the rest of it.
3833 if (strlen($name) > 64) {
3834 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3835 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3837 $name = substr($name, 0, 64);
3841 // Take the first word as first name
3842 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3843 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3844 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3845 return ['first' => $first, 'last' => $last];
3848 // Take the last word as last name
3849 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3850 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3852 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3853 return ['first' => $first, 'last' => $last];
3856 // Take the first 32 characters if there is no space in the first 32 characters
3857 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3858 $first = substr($name, 0, 32);
3859 $last = substr($name, 32);
3860 return ['first' => $first, 'last' => $last];
3863 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3864 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3866 // Check if the last name is longer than 32 characters
3867 if (strlen($last) > 32) {
3868 if (strpos($last, ' ') <= 32) {
3869 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
3871 $last = substr($last, 0, 32);
3875 return ['first' => $first, 'last' => $last];
3879 * Create profile data
3881 * @param int $uid The user id
3883 * @return array The profile data
3884 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3886 private static function createProfileData($uid)
3888 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
3889 if (!DBA::isResult($profile)) {
3893 $handle = $profile["addr"];
3895 $split_name = self::splitName($profile['name']);
3896 $first = $split_name['first'];
3897 $last = $split_name['last'];
3899 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3900 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3901 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3902 $searchable = ($profile['net-publish'] ? 'true' : 'false');
3908 if ($searchable === 'true') {
3911 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
3912 [$year, $month, $day] = sscanf($profile['dob'], '%4d-%2d-%2d');
3916 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
3919 $about = BBCode::toMarkdown($profile['about']);
3921 $location = $profile['location'];
3923 if ($profile['pub_keywords']) {
3924 $kw = str_replace(',', ' ', $profile['pub_keywords']);
3925 $kw = str_replace(' ', ' ', $kw);
3926 $arr = explode(' ', $kw);
3928 for ($x = 0; $x < 5; $x ++) {
3929 if (!empty($arr[$x])) {
3930 $tags .= '#'. trim($arr[$x]) .' ';
3935 $tags = trim($tags);
3938 return ["author" => $handle,
3939 "first_name" => $first,
3940 "last_name" => $last,
3941 "image_url" => $large,
3942 "image_url_medium" => $medium,
3943 "image_url_small" => $small,
3946 "location" => $location,
3947 "searchable" => $searchable,
3949 "tag_string" => $tags];
3953 * Sends profile data
3955 * @param int $uid The user id
3956 * @param bool $recips optional, default false
3958 * @throws \Exception
3960 public static function sendProfile($uid, $recips = false)
3966 $owner = User::getOwnerDataById($uid);
3972 $recips = DBA::selectToArray('contact', [], ['network' => Protocol::DIASPORA, 'uid' => $uid, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
3979 $message = self::createProfileData($uid);
3981 // @ToDo Split this into single worker jobs
3982 foreach ($recips as $recip) {
3983 Logger::info("Send updated profile data for user ".$uid." to contact ".$recip["id"]);
3984 self::buildAndTransmit($owner, $recip, "profile", $message);
3989 * Creates the signature for likes that are created on our system
3991 * @param integer $uid The user of that comment
3992 * @param array $item Item array
3994 * @return array Signed content
3995 * @throws \Exception
3997 public static function createLikeSignature($uid, array $item)
3999 $owner = User::getOwnerDataById($uid);
4000 if (empty($owner)) {
4001 Logger::info('No owner post, so not storing signature');
4005 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4009 $message = self::constructLike($item, $owner);
4010 if ($message === false) {
4014 $message["author_signature"] = self::signature($owner, $message);
4020 * Creates the signature for Comments that are created on our system
4022 * @param array $item Item array
4024 * @return array Signed content
4025 * @throws \Exception
4027 public static function createCommentSignature(array $item)
4029 if (!empty($item['author-link'])) {
4030 $url = $item['author-link'];
4032 $contact = Contact::getById($item['author-id'], ['url']);
4033 if (empty($contact['url'])) {
4034 Logger::warning('Author Contact not found', ['author-id' => $item['author-id']]);
4037 $url = $contact['url'];
4040 $uid = User::getIdForURL($url);
4042 Logger::info('No owner post, so not storing signature', ['url' => $contact['url']]);
4046 $owner = User::getOwnerDataById($uid);
4047 if (empty($owner)) {
4048 Logger::info('No owner post, so not storing signature');
4052 // This is only needed for the automated tests
4053 if (empty($owner['uprvkey'])) {
4057 $message = self::constructComment($item, $owner);
4058 if ($message === false) {
4062 $message["author_signature"] = self::signature($owner, $message);
4067 public static function performReshare(int $UriId, int $uid)
4069 $fields = ['uri-id', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
4070 $item = Post::selectFirst($fields, ['uri-id' => $UriId, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
4071 if (!DBA::isResult($item)) {
4075 if (strpos($item['body'], '[/share]') !== false) {
4076 $pos = strpos($item['body'], '[share');
4077 $post = substr($item['body'], $pos);
4079 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
4081 if (!empty($item['title'])) {
4082 $post .= '[h3]' . $item['title'] . "[/h3]\n";
4085 $post .= $item['body'];
4086 $post .= '[/share]';
4089 $owner = User::getOwnerDataById($uid);
4090 $author = Contact::getPublicIdByUserId($uid);
4094 'verb' => Activity::POST,
4095 'contact-id' => $owner['id'],
4096 'author-id' => $author,
4097 'owner-id' => $author,
4099 'allow_cid' => $owner['allow_cid'],
4100 'allow_gid' => $owner['allow_gid'],
4101 'deny_cid' => $owner['deny_cid'],
4102 'deny_gid' => $owner['deny_gid'],
4105 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
4106 $item['private'] = Item::PRIVATE;
4107 } elseif (DI::pConfig()->get($uid, 'system', 'unlisted')) {
4108 $item['private'] = Item::UNLISTED;
4110 $item['private'] = Item::PUBLIC;
4113 // Don't trigger the addons
4114 $item['api_source'] = false;
4116 return Item::insert($item, true);