3 * @copyright Copyright (C) 2020, Friendica
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\PageInfo;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Cache\Duration;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\System;
32 use Friendica\Core\Worker;
33 use Friendica\Database\DBA;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Conversation;
37 use Friendica\Model\FContact;
38 use Friendica\Model\GServer;
39 use Friendica\Model\Item;
40 use Friendica\Model\ItemURI;
41 use Friendica\Model\Mail;
42 use Friendica\Model\Post;
43 use Friendica\Model\Tag;
44 use Friendica\Model\User;
45 use Friendica\Network\Probe;
46 use Friendica\Util\Crypto;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Map;
49 use Friendica\Util\Network;
50 use Friendica\Util\Strings;
51 use Friendica\Util\XML;
52 use Friendica\Worker\Delivery;
56 * This class contain functions to create and send Diaspora XML files
61 * Return a list of participating contacts for a thread
63 * This is used for the participation feature.
64 * One of the parameters is a contact array.
65 * This is done to avoid duplicates.
67 * @param array $item Item that is about to be delivered
68 * @param array $contacts The previously fetched contacts
70 * @return array of relay servers
73 public static function participantsForThread(array $item, array $contacts)
75 if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
76 Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]);
80 $items = Post::select(['author-id', 'author-link', 'parent-author-link', 'parent-guid', 'guid'],
81 ['parent' => $item['parent'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
82 while ($item = Post::fetch($items)) {
83 $contact = DBA::selectFirst('contact', ['id', 'url', 'name', 'protocol', 'batch', 'network'],
84 ['id' => $item['author-id']]);
85 if (!DBA::isResult($contact) || empty($contact['batch']) ||
86 ($contact['network'] != Protocol::DIASPORA) ||
87 Strings::compareLink($item['parent-author-link'], $item['author-link'])) {
92 foreach ($contacts as $entry) {
93 if ($entry['batch'] == $contact['batch']) {
99 Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]);
100 $contacts[] = $contact;
109 * verify the envelope and return the verified data
111 * @param string $envelope The magic envelope
113 * @return string verified data
114 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
115 * @throws \ImagickException
117 private static function verifyMagicEnvelope($envelope)
119 $basedom = XML::parseString($envelope, true);
121 if (!is_object($basedom)) {
122 Logger::log("Envelope is no XML file");
126 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
128 if (sizeof($children) == 0) {
129 Logger::log("XML has no children");
135 $data = Strings::base64UrlDecode($children->data);
136 $type = $children->data->attributes()->type[0];
138 $encoding = $children->encoding;
140 $alg = $children->alg;
142 $sig = Strings::base64UrlDecode($children->sig);
143 $key_id = $children->sig->attributes()->key_id[0];
145 $handle = Strings::base64UrlDecode($key_id);
148 $b64url_data = Strings::base64UrlEncode($data);
149 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
151 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
154 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
158 $key = self::key($handle);
160 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
164 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
166 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
174 * encrypts data via AES
176 * @param string $key The AES key
177 * @param string $iv The IV (is used for CBC encoding)
178 * @param string $data The data that is to be encrypted
180 * @return string encrypted data
182 private static function aesEncrypt($key, $iv, $data)
184 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
188 * decrypts data via AES
190 * @param string $key The AES key
191 * @param string $iv The IV (is used for CBC encoding)
192 * @param string $encrypted The encrypted data
194 * @return string decrypted data
196 private static function aesDecrypt($key, $iv, $encrypted)
198 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
202 * Decodes incoming Diaspora message in the new format
204 * @param string $raw raw post message
205 * @param string $privKey The private key of the importer
206 * @param boolean $no_exit Don't do an http exit on error
209 * 'message' -> decoded Diaspora XML message
210 * 'author' -> author diaspora handle
211 * 'key' -> author public key (converted to pkcs#8)
212 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
213 * @throws \ImagickException
215 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
217 $data = json_decode($raw);
219 // Is it a private post? Then decrypt the outer Salmon
220 if (is_object($data)) {
221 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
222 $ciphertext = base64_decode($data->encrypted_magic_envelope);
224 $outer_key_bundle = '';
225 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
226 $j_outer_key_bundle = json_decode($outer_key_bundle);
228 if (!is_object($j_outer_key_bundle)) {
229 Logger::log('Outer Salmon did not verify. Discarding.');
233 throw new \Friendica\Network\HTTPException\BadRequestException();
237 $outer_iv = base64_decode($j_outer_key_bundle->iv);
238 $outer_key = base64_decode($j_outer_key_bundle->key);
240 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
245 $basedom = XML::parseString($xml, true);
247 if (!is_object($basedom)) {
248 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
252 throw new \Friendica\Network\HTTPException\BadRequestException();
256 $base = $basedom->children(ActivityNamespace::SALMON_ME);
258 // Not sure if this cleaning is needed
259 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
261 // Build the signed data
262 $type = $base->data[0]->attributes()->type[0];
263 $encoding = $base->encoding;
265 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
267 // This is the signature
268 $signature = Strings::base64UrlDecode($base->sig);
270 // Get the senders' public key
271 $key_id = $base->sig[0]->attributes()->key_id[0];
272 $author_addr = base64_decode($key_id);
273 if ($author_addr == '') {
274 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
278 throw new \Friendica\Network\HTTPException\BadRequestException();
282 $key = self::key($author_addr);
284 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
288 throw new \Friendica\Network\HTTPException\BadRequestException();
292 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
294 Logger::log('Message did not verify. Discarding.');
298 throw new \Friendica\Network\HTTPException\BadRequestException();
302 return ['message' => (string)Strings::base64UrlDecode($base->data),
303 'author' => XML::unescape($author_addr),
304 'key' => (string)$key];
308 * Decodes incoming Diaspora message in the deprecated format
310 * @param string $xml urldecoded Diaspora salmon
311 * @param string $privKey The private key of the importer
314 * 'message' -> decoded Diaspora XML message
315 * 'author' -> author diaspora handle
316 * 'key' -> author public key (converted to pkcs#8)
317 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
318 * @throws \ImagickException
320 public static function decode(string $xml, string $privKey = '')
323 $basedom = XML::parseString($xml);
325 if (!is_object($basedom)) {
326 Logger::notice('XML is not parseable.');
329 $children = $basedom->children('https://joindiaspora.com/protocol');
331 $inner_aes_key = null;
334 if ($children->header) {
336 $author_link = str_replace('acct:', '', $children->header->author_id);
338 // This happens with posts from a relais
339 if (empty($privKey)) {
340 Logger::info('This is no private post in the old format');
344 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
346 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
347 $ciphertext = base64_decode($encrypted_header->ciphertext);
349 $outer_key_bundle = '';
350 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
352 $j_outer_key_bundle = json_decode($outer_key_bundle);
354 $outer_iv = base64_decode($j_outer_key_bundle->iv);
355 $outer_key = base64_decode($j_outer_key_bundle->key);
357 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
359 Logger::info('decrypted', ['data' => $decrypted]);
360 $idom = XML::parseString($decrypted);
362 $inner_iv = base64_decode($idom->iv);
363 $inner_aes_key = base64_decode($idom->aes_key);
365 $author_link = str_replace('acct:', '', $idom->author_id);
368 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
370 // figure out where in the DOM tree our data is hiding
373 if ($dom->provenance->data) {
374 $base = $dom->provenance;
375 } elseif ($dom->env->data) {
377 } elseif ($dom->data) {
382 Logger::log('unable to locate salmon data in xml');
383 throw new \Friendica\Network\HTTPException\BadRequestException();
387 // Stash the signature away for now. We have to find their key or it won't be good for anything.
388 $signature = Strings::base64UrlDecode($base->sig);
392 // strip whitespace so our data element will return to one big base64 blob
393 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
396 // stash away some other stuff for later
398 $type = $base->data[0]->attributes()->type[0];
399 $keyhash = $base->sig[0]->attributes()->keyhash[0];
400 $encoding = $base->encoding;
404 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
408 $data = Strings::base64UrlDecode($data);
412 $inner_decrypted = $data;
414 // Decode the encrypted blob
415 $inner_encrypted = base64_decode($data);
416 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
420 Logger::log('Could not retrieve author URI.');
421 throw new \Friendica\Network\HTTPException\BadRequestException();
423 // Once we have the author URI, go to the web and try to find their public key
424 // (first this will look it up locally if it is in the fcontact cache)
425 // This will also convert diaspora public key from pkcs#1 to pkcs#8
427 Logger::log('Fetching key for '.$author_link);
428 $key = self::key($author_link);
431 Logger::log('Could not retrieve author key.');
432 throw new \Friendica\Network\HTTPException\BadRequestException();
435 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
438 Logger::log('Message did not verify. Discarding.');
439 throw new \Friendica\Network\HTTPException\BadRequestException();
442 Logger::log('Message verified.');
444 return ['message' => (string)$inner_decrypted,
445 'author' => XML::unescape($author_link),
446 'key' => (string)$key];
451 * Dispatches public messages and find the fitting receivers
453 * @param array $msg The post that will be dispatched
454 * @param bool $fetched The message had been fetched (default "false")
456 * @return int The message id of the generated message, "true" or "false" if there was an error
457 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
458 * @throws \ImagickException
460 public static function dispatchPublic($msg, bool $fetched = false)
462 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
464 Logger::log("diaspora is disabled");
468 if (!($fields = self::validPosting($msg))) {
469 Logger::log("Invalid posting");
473 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
474 $success = self::dispatch($importer, $msg, $fields, $fetched);
480 * Dispatches the different message types to the different functions
482 * @param array $importer Array of the importer user
483 * @param array $msg The post that will be dispatched
484 * @param SimpleXMLElement $fields SimpleXML object that contains the message
485 * @param bool $fetched The message had been fetched (default "false")
487 * @return int The message id of the generated message, "true" or "false" if there was an error
488 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
489 * @throws \ImagickException
491 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null, bool $fetched = false)
493 // The sender is the handle of the contact that sent the message.
494 // This will often be different with relayed messages (for example "like" and "comment")
495 $sender = $msg["author"];
497 // This is only needed for private postings since this is already done for public ones before
498 if (is_null($fields)) {
500 if (!($fields = self::validPosting($msg))) {
501 Logger::log("Invalid posting");
508 $type = $fields->getName();
510 Logger::info('Received message', ['type' => $type, 'sender' => $sender, 'user' => $importer["uid"]]);
513 case "account_migration":
515 Logger::log('Message with type ' . $type . ' is not private, quitting.');
518 return self::receiveAccountMigration($importer, $fields);
520 case "account_deletion":
521 return self::receiveAccountDeletion($fields);
524 return self::receiveComment($importer, $sender, $fields, $msg["message"], $fetched);
528 Logger::log('Message with type ' . $type . ' is not private, quitting.');
531 return self::receiveContactRequest($importer, $fields);
535 Logger::log('Message with type ' . $type . ' is not private, quitting.');
538 return self::receiveConversation($importer, $msg, $fields);
541 return self::receiveLike($importer, $sender, $fields, $fetched);
545 Logger::log('Message with type ' . $type . ' is not private, quitting.');
548 return self::receiveMessage($importer, $fields);
550 case "participation":
552 Logger::log('Message with type ' . $type . ' is not private, quitting.');
555 return self::receiveParticipation($importer, $fields, $fetched);
557 case "photo": // Not implemented
558 return self::receivePhoto($importer, $fields);
560 case "poll_participation": // Not implemented
561 return self::receivePollParticipation($importer, $fields);
565 Logger::log('Message with type ' . $type . ' is not private, quitting.');
568 return self::receiveProfile($importer, $fields);
571 return self::receiveReshare($importer, $fields, $msg["message"], $fetched);
574 return self::receiveRetraction($importer, $sender, $fields);
576 case "status_message":
577 return self::receiveStatusMessage($importer, $fields, $msg["message"], $fetched);
580 Logger::log("Unknown message type ".$type);
586 * Checks if a posting is valid and fetches the data fields.
588 * This function does not only check the signature.
589 * It also does the conversion between the old and the new diaspora format.
591 * @param array $msg Array with the XML, the sender handle and the sender signature
593 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
594 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
595 * @throws \ImagickException
597 private static function validPosting($msg)
599 $data = XML::parseString($msg["message"]);
601 if (!is_object($data)) {
602 Logger::info('No valid XML', ['message' => $msg['message']]);
606 // Is this the new or the old version?
607 if ($data->getName() == "XML") {
609 foreach ($data->post->children() as $child) {
617 $type = $element->getName();
620 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
622 // All retractions are handled identically from now on.
623 // In the new version there will only be "retraction".
624 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
625 $type = "retraction";
627 if ($type == "request") {
631 $fields = new SimpleXMLElement("<".$type."/>");
634 $author_signature = null;
635 $parent_author_signature = null;
637 foreach ($element->children() as $fieldname => $entry) {
639 // Translation for the old XML structure
640 if ($fieldname == "diaspora_handle") {
641 $fieldname = "author";
643 if ($fieldname == "participant_handles") {
644 $fieldname = "participants";
646 if (in_array($type, ["like", "participation"])) {
647 if ($fieldname == "target_type") {
648 $fieldname = "parent_type";
651 if ($fieldname == "sender_handle") {
652 $fieldname = "author";
654 if ($fieldname == "recipient_handle") {
655 $fieldname = "recipient";
657 if ($fieldname == "root_diaspora_id") {
658 $fieldname = "root_author";
660 if ($type == "status_message") {
661 if ($fieldname == "raw_message") {
665 if ($type == "retraction") {
666 if ($fieldname == "post_guid") {
667 $fieldname = "target_guid";
669 if ($fieldname == "type") {
670 $fieldname = "target_type";
675 if (($fieldname == "author_signature") && ($entry != "")) {
676 $author_signature = base64_decode($entry);
677 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
678 $parent_author_signature = base64_decode($entry);
679 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
680 if ($signed_data != "") {
684 $signed_data .= $entry;
686 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
687 || ($orig_type == "relayable_retraction")
689 XML::copy($entry, $fields, $fieldname);
693 // This is something that shouldn't happen at all.
694 if (in_array($type, ["status_message", "reshare", "profile"])) {
695 if ($msg["author"] != $fields->author) {
696 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
701 // Only some message types have signatures. So we quit here for the other types.
702 if (!in_array($type, ["comment", "like"])) {
705 // No author_signature? This is a must, so we quit.
706 if (!isset($author_signature)) {
707 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
711 if (isset($parent_author_signature)) {
712 $key = self::key($msg["author"]);
714 Logger::info('No key found for parent', ['author' => $msg["author"]]);
718 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
719 Logger::log("No valid parent author signature for parent author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$parent_author_signature, Logger::DEBUG);
724 $key = self::key($fields->author);
726 Logger::info('No key found', ['author' => $fields->author]);
730 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
731 Logger::log("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, Logger::DEBUG);
739 * Fetches the public key for a given handle
741 * @param string $handle The handle
743 * @return string The public key
744 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
745 * @throws \ImagickException
747 private static function key($handle)
749 $handle = strval($handle);
751 Logger::log("Fetching diaspora key for: ".$handle);
753 $r = FContact::getByURL($handle);
762 * get a handle (user@domain.tld) from a given contact id
764 * @param int $contact_id The id in the contact table
765 * @param int $pcontact_id The id in the contact table (Used for the public contact)
767 * @return string the handle
770 private static function handleFromContact($contact_id, $pcontact_id = 0)
774 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
776 if ($pcontact_id != 0) {
777 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
779 if (DBA::isResult($contact) && !empty($contact["addr"])) {
780 return strtolower($contact["addr"]);
785 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
789 if (DBA::isResult($r)) {
792 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
794 if ($contact['addr'] != "") {
795 $handle = $contact['addr'];
797 $baseurl_start = strpos($contact['url'], '://') + 3;
798 // allows installations in a subdirectory--not sure how Diaspora will handle
799 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
800 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
801 $handle = $contact['nick'].'@'.$baseurl;
805 return strtolower($handle);
809 * Get a contact id for a given handle
811 * @todo Move to Friendica\Model\Contact
813 * @param int $uid The user id
814 * @param string $handle The handle in the format user@domain.tld
816 * @return array Contact data
817 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
818 * @throws \ImagickException
820 private static function contactByHandle($uid, $handle)
822 return Contact::getByURL($handle, null, [], $uid);
826 * Checks if the given contact url does support ActivityPub
828 * @param string $url profile url
829 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
831 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
832 * @throws \ImagickException
834 public static function isSupportedByContactUrl($url, $update = null)
836 return !empty(FContact::getByURL($url, $update));
840 * Check if posting is allowed for this contact
842 * @param array $importer Array of the importer user
843 * @param array $contact The contact that is checked
844 * @param bool $is_comment Is the check for a comment?
846 * @return bool is the contact allowed to post?
848 private static function postAllow(array $importer, array $contact, $is_comment = false)
851 * Perhaps we were already sharing with this person. Now they're sharing with us.
852 * That makes us friends.
853 * Normally this should have handled by getting a request - but this could get lost
855 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
856 // It is not removed by now. Possibly the code is needed?
857 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
860 // array('rel' => Contact::FRIEND, 'writable' => true),
861 // array('id' => $contact["id"], 'uid' => $contact["uid"])
864 // $contact["rel"] = Contact::FRIEND;
865 // Logger::log("defining user ".$contact["nick"]." as friend");
868 // Contact server is blocked
869 if (Network::isUrlBlocked($contact['url'])) {
871 // We don't seem to like that person
872 } elseif ($contact["blocked"]) {
873 // Maybe blocked, don't accept.
875 // We are following this person?
876 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
877 // Yes, then it is fine.
879 // Is it a post to a community?
880 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
883 // Is the message a global user or a comment?
884 } elseif (($importer["uid"] == 0) || $is_comment) {
885 // Messages for the global users and comments are always accepted
893 * Fetches the contact id for a handle and checks if posting is allowed
895 * @param array $importer Array of the importer user
896 * @param string $handle The checked handle in the format user@domain.tld
897 * @param bool $is_comment Is the check for a comment?
899 * @return array The contact data
902 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
904 $contact = self::contactByHandle($importer["uid"], $handle);
906 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
907 // If a contact isn't found, we accept it anyway if it is a comment
908 if ($is_comment && ($importer["uid"] != 0)) {
909 return self::contactByHandle(0, $handle);
910 } elseif ($is_comment) {
917 if (!self::postAllow($importer, $contact, $is_comment)) {
918 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
925 * Does the message already exists on the system?
927 * @param int $uid The user id
928 * @param string $guid The guid of the message
930 * @return int|bool message id if the message already was stored into the system - or false.
933 private static function messageExists($uid, $guid)
935 $item = Post::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
936 if (DBA::isResult($item)) {
937 Logger::log("message ".$guid." already exists for user ".$uid);
945 * Checks for links to posts in a message
947 * @param array $item The item array
950 private static function fetchGuid(array $item)
952 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
953 preg_replace_callback(
955 function ($match) use ($item) {
956 self::fetchGuidSub($match, $item);
961 preg_replace_callback(
962 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
963 function ($match) use ($item) {
964 self::fetchGuidSub($match, $item);
971 * Checks for relative /people/* links in an item body to match local
972 * contacts or prepends the remote host taken from the author link.
974 * @param string $body The item body to replace links from
975 * @param string $author_link The author link for missing local contact fallback
977 * @return string the replaced string
979 public static function replacePeopleGuid($body, $author_link)
981 $return = preg_replace_callback(
982 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
983 function ($match) use ($author_link) {
985 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
986 // 1 => '0123456789abcdef'
988 $handle = FContact::getUrlByGuid($match[1]);
991 $return = '@[url='.$handle.']'.$match[2].'[/url]';
993 // No local match, restoring absolute remote URL from author scheme and host
994 $author_url = parse_url($author_link);
995 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1007 * sub function of "fetchGuid" which checks for links in messages
1009 * @param array $match array containing a link that has to be checked for a message link
1010 * @param array $item The item array
1012 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1013 * @throws \ImagickException
1015 private static function fetchGuidSub($match, $item)
1017 if (!self::storeByGuid($match[1], $item["author-link"])) {
1018 self::storeByGuid($match[1], $item["owner-link"]);
1023 * Fetches an item with a given guid from a given server
1025 * @param string $guid the message guid
1026 * @param string $server The server address
1027 * @param int $uid The user id of the user
1029 * @return int the message id of the stored message or false
1030 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1031 * @throws \ImagickException
1033 private static function storeByGuid($guid, $server, $uid = 0)
1035 $serverparts = parse_url($server);
1037 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1041 $server = $serverparts["scheme"]."://".$serverparts["host"];
1043 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1045 $msg = self::message($guid, $server);
1051 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1053 // Now call the dispatcher
1054 return self::dispatchPublic($msg, true);
1058 * Fetches a message from a server
1060 * @param string $guid message guid
1061 * @param string $server The url of the server
1062 * @param int $level Endless loop prevention
1065 * 'message' => The message XML
1066 * 'author' => The author handle
1067 * 'key' => The public key of the author
1068 * @throws \Exception
1070 private static function message($guid, $server, $level = 0)
1076 // This will work for new Diaspora servers and Friendica servers from 3.5
1077 $source_url = $server."/fetch/post/".urlencode($guid);
1079 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1081 $envelope = DI::httpRequest()->fetch($source_url);
1083 Logger::log("Envelope was fetched.", Logger::DEBUG);
1084 $x = self::verifyMagicEnvelope($envelope);
1086 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1088 Logger::log("Envelope was verified.", Logger::DEBUG);
1098 $source_xml = XML::parseString($x);
1100 if (!is_object($source_xml)) {
1104 if ($source_xml->post->reshare) {
1105 // Reshare of a reshare - old Diaspora version
1106 Logger::log("Message is a reshare", Logger::DEBUG);
1107 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1108 } elseif ($source_xml->getName() == "reshare") {
1109 // Reshare of a reshare - new Diaspora version
1110 Logger::log("Message is a new reshare", Logger::DEBUG);
1111 return self::message($source_xml->root_guid, $server, ++$level);
1116 // Fetch the author - for the old and the new Diaspora version
1117 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1118 $author = (string)$source_xml->post->status_message->diaspora_handle;
1119 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1120 $author = (string)$source_xml->author;
1123 // If this isn't a "status_message" then quit
1125 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1129 $msg = ["message" => $x, "author" => $author];
1131 $msg["key"] = self::key($msg["author"]);
1137 * Fetches an item with a given URL
1139 * @param string $url the message url
1141 * @return int the message id of the stored message or false
1142 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1143 * @throws \ImagickException
1145 public static function fetchByURL($url, $uid = 0)
1147 // Check for Diaspora (and Friendica) typical paths
1148 if (!preg_match("=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1149 Logger::info('Invalid url', ['url' => $url]);
1153 $guid = urldecode($matches[2]);
1155 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1156 if (DBA::isResult($item)) {
1157 Logger::info('Found', ['id' => $item['id']]);
1161 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1162 $ret = self::storeByGuid($guid, $matches[1], $uid);
1163 Logger::info('Result', ['ret' => $ret]);
1165 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1166 if (DBA::isResult($item)) {
1167 Logger::info('Found', ['id' => $item['id']]);
1170 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1176 * Fetches the item record of a given guid
1178 * @param int $uid The user id
1179 * @param string $guid message guid
1180 * @param string $author The handle of the item
1181 * @param array $contact The contact of the item owner
1183 * @return array the item record
1184 * @throws \Exception
1186 private static function parentItem($uid, $guid, $author, array $contact)
1188 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1189 'author-name', 'author-link', 'author-avatar', 'gravity',
1190 'owner-name', 'owner-link', 'owner-avatar'];
1191 $condition = ['uid' => $uid, 'guid' => $guid];
1192 $item = Post::selectFirst($fields, $condition);
1194 if (!DBA::isResult($item)) {
1195 $person = FContact::getByURL($author);
1196 $result = self::storeByGuid($guid, $person["url"], $uid);
1198 // We don't have an url for items that arrived at the public dispatcher
1199 if (!$result && !empty($contact["url"])) {
1200 $result = self::storeByGuid($guid, $contact["url"], $uid);
1204 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1206 $item = Post::selectFirst($fields, $condition);
1210 if (!DBA::isResult($item)) {
1211 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1214 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1220 * returns contact details
1222 * @param array $def_contact The default contact if the person isn't found
1223 * @param array $person The record of the person
1224 * @param int $uid The user id
1227 * 'cid' => contact id
1228 * 'network' => network type
1229 * @throws \Exception
1231 private static function authorContactByUrl($def_contact, $person, $uid)
1233 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1234 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1235 if (DBA::isResult($contact)) {
1236 $cid = $contact["id"];
1237 $network = $contact["network"];
1239 $cid = $def_contact["id"];
1240 $network = Protocol::DIASPORA;
1243 return ["cid" => $cid, "network" => $network];
1247 * Is the profile a hubzilla profile?
1249 * @param string $url The profile link
1251 * @return bool is it a hubzilla server?
1253 private static function isHubzilla($url)
1255 return(strstr($url, '/channel/'));
1259 * Generate a post link with a given handle and message guid
1261 * @param string $addr The user handle
1262 * @param string $guid message guid
1263 * @param string $parent_guid optional parent guid
1265 * @return string the post link
1266 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1267 * @throws \ImagickException
1269 private static function plink(string $addr, string $guid, string $parent_guid = '')
1271 $contact = Contact::getByURL($addr);
1272 if (empty($contact)) {
1273 Logger::info('No contact data for address', ['addr' => $addr]);
1277 if (empty($contact['baseurl'])) {
1278 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1279 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1283 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1284 if (!empty($gserver['platform'])) {
1285 $platform = strtolower($gserver['platform']);
1286 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1289 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1290 if (self::isHubzilla($contact['url'])) {
1291 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1292 $platform = 'hubzilla';
1293 } elseif ($contact['network'] == Protocol::DFRN) {
1294 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1295 $platform = 'friendica';
1299 if ($platform == 'friendica') {
1300 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1303 if ($platform == 'hubzilla') {
1304 return $contact['baseurl'] . '/item/' . $guid;
1307 if ($platform == 'socialhome') {
1308 return $contact['baseurl'] . '/content/' . $guid;
1311 if ($platform != 'diaspora') {
1312 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1316 if ($parent_guid != '') {
1317 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1319 return $contact['baseurl'] . '/posts/' . $guid;
1324 * Receives account migration
1326 * @param array $importer Array of the importer user
1327 * @param object $data The message object
1329 * @return bool Success
1330 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1331 * @throws \ImagickException
1333 private static function receiveAccountMigration(array $importer, $data)
1335 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1336 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1337 $signature = Strings::escapeTags(XML::unescape($data->signature));
1339 $contact = self::contactByHandle($importer["uid"], $old_handle);
1341 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1345 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1348 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1349 $key = self::key($old_handle);
1350 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1351 Logger::log('No valid signature for migration.');
1355 // Update the profile
1356 self::receiveProfile($importer, $data->profile);
1358 // change the technical stuff in contact
1359 $data = Probe::uri($new_handle);
1360 if ($data['network'] == Protocol::PHANTOM) {
1361 Logger::log('Account for '.$new_handle." couldn't be probed.");
1365 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1366 'name' => $data['name'], 'nick' => $data['nick'],
1367 'addr' => $data['addr'], 'batch' => $data['batch'],
1368 'notify' => $data['notify'], 'poll' => $data['poll'],
1369 'network' => $data['network']];
1371 DBA::update('contact', $fields, ['addr' => $old_handle]);
1373 Logger::log('Contacts are updated.');
1379 * Processes an account deletion
1381 * @param object $data The message object
1383 * @return bool Success
1384 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1386 private static function receiveAccountDeletion($data)
1388 $author = Strings::escapeTags(XML::unescape($data->author));
1390 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1391 while ($contact = DBA::fetch($contacts)) {
1392 Contact::remove($contact["id"]);
1394 DBA::close($contacts);
1396 Logger::log('Removed contacts for ' . $author);
1402 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1404 * @param string $author Author handle
1405 * @param string $guid Message guid
1406 * @param boolean $onlyfound Only return uri when found in the database
1408 * @return string The constructed uri or the one from our database
1409 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1410 * @throws \ImagickException
1412 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1414 $item = Post::selectFirst(['uri'], ['guid' => $guid]);
1415 if (DBA::isResult($item)) {
1416 return $item["uri"];
1417 } elseif (!$onlyfound) {
1418 $person = FContact::getByURL($author);
1420 $parts = parse_url($person['url']);
1421 unset($parts['path']);
1422 $host_url = Network::unparseURL($parts);
1424 return $host_url . '/objects/' . $guid;
1431 * Store the mentions in the tag table
1433 * @param integer $uriid
1434 * @param string $text
1436 private static function storeMentions(int $uriid, string $text)
1438 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1439 if (empty($matches)) {
1444 * Matching values for the preg match
1445 * [1] = mention type (@ or !)
1446 * [2] = name (optional)
1450 foreach ($matches as $match) {
1451 if (empty($match)) {
1455 $person = FContact::getByURL($match[3]);
1456 if (empty($person)) {
1460 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1465 * Processes an incoming comment
1467 * @param array $importer Array of the importer user
1468 * @param string $sender The sender of the message
1469 * @param object $data The message object
1470 * @param string $xml The original XML of the message
1471 * @param bool $fetched The message had been fetched and not pushed
1473 * @return int The message id of the generated comment or "false" if there was an error
1474 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1475 * @throws \ImagickException
1477 private static function receiveComment(array $importer, $sender, $data, $xml, bool $fetched)
1479 $author = Strings::escapeTags(XML::unescape($data->author));
1480 $guid = Strings::escapeTags(XML::unescape($data->guid));
1481 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1482 $text = XML::unescape($data->text);
1484 if (isset($data->created_at)) {
1485 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1487 $created_at = DateTimeFormat::utcNow();
1490 if (isset($data->thread_parent_guid)) {
1491 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1492 $thr_parent = self::getUriFromGuid("", $thread_parent_guid, true);
1497 $contact = self::allowedContactByHandle($importer, $sender, true);
1502 if (!empty($contact['gsid'])) {
1503 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1506 $message_id = self::messageExists($importer["uid"], $guid);
1511 $toplevel_parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1512 if (!$toplevel_parent_item) {
1516 $person = FContact::getByURL($author);
1517 if (!is_array($person)) {
1518 Logger::log("unable to find author details");
1522 // Fetch the contact id - if we know this contact
1523 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1527 $datarray["uid"] = $importer["uid"];
1528 $datarray["contact-id"] = $author_contact["cid"];
1529 $datarray["network"] = $author_contact["network"];
1531 $datarray["author-link"] = $person["url"];
1532 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1534 $datarray["owner-link"] = $contact["url"];
1535 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1537 // Will be overwritten for sharing accounts in Item::insert
1539 $datarray["post-type"] = Item::PT_FETCHED;
1540 } elseif ($datarray["uid"] == 0) {
1541 $datarray["post-type"] = Item::PT_GLOBAL;
1543 $datarray["post-type"] = Item::PT_COMMENT;
1546 $datarray["guid"] = $guid;
1547 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1548 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1550 $datarray["verb"] = Activity::POST;
1551 $datarray["gravity"] = GRAVITY_COMMENT;
1553 $datarray['thr-parent'] = $thr_parent ?: $toplevel_parent_item['uri'];
1555 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1557 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1558 $datarray["source"] = $xml;
1559 $datarray["direction"] = $fetched ? Conversation::PULL : Conversation::PUSH;
1561 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1563 $datarray["plink"] = self::plink($author, $guid, $toplevel_parent_item['guid']);
1564 $body = Markdown::toBBCode($text);
1566 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1568 self::storeMentions($datarray['uri-id'], $text);
1569 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
1571 self::fetchGuid($datarray);
1573 // If we are the origin of the parent we store the original data.
1574 // We notify our followers during the item storage.
1575 if ($toplevel_parent_item["origin"]) {
1576 $datarray['diaspora_signed_text'] = json_encode($data);
1579 if (Item::isTooOld($datarray)) {
1580 Logger::info('Comment is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1584 $message_id = Item::insert($datarray);
1586 if ($message_id <= 0) {
1591 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1592 if ($datarray['uid'] == 0) {
1593 Item::distribute($message_id, json_encode($data));
1601 * processes and stores private messages
1603 * @param array $importer Array of the importer user
1604 * @param array $contact The contact of the message
1605 * @param object $data The message object
1606 * @param array $msg Array of the processed message, author handle and key
1607 * @param object $mesg The private message
1608 * @param array $conversation The conversation record to which this message belongs
1610 * @return bool "true" if it was successful
1611 * @throws \Exception
1613 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1615 $author = Strings::escapeTags(XML::unescape($data->author));
1616 $guid = Strings::escapeTags(XML::unescape($data->guid));
1617 $subject = Strings::escapeTags(XML::unescape($data->subject));
1619 // "diaspora_handle" is the element name from the old version
1620 // "author" is the element name from the new version
1621 if ($mesg->author) {
1622 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1623 } elseif ($mesg->diaspora_handle) {
1624 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1629 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1630 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1631 $msg_text = XML::unescape($mesg->text);
1632 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1634 if ($msg_conversation_guid != $guid) {
1635 Logger::log("message conversation guid does not belong to the current conversation.");
1639 $body = Markdown::toBBCode($msg_text);
1640 $message_uri = $msg_author.":".$msg_guid;
1642 $person = FContact::getByURL($msg_author);
1644 return Mail::insert([
1645 'uid' => $importer['uid'],
1646 'guid' => $msg_guid,
1647 'convid' => $conversation['id'],
1648 'from-name' => $person['name'],
1649 'from-photo' => $person['photo'],
1650 'from-url' => $person['url'],
1651 'contact-id' => $contact['id'],
1652 'title' => $subject,
1654 'uri' => $message_uri,
1655 'parent-uri' => $author . ':' . $guid,
1656 'created' => $msg_created_at
1661 * Processes new private messages (answers to private messages are processed elsewhere)
1663 * @param array $importer Array of the importer user
1664 * @param array $msg Array of the processed message, author handle and key
1665 * @param object $data The message object
1667 * @return bool Success
1668 * @throws \Exception
1670 private static function receiveConversation(array $importer, $msg, $data)
1672 $author = Strings::escapeTags(XML::unescape($data->author));
1673 $guid = Strings::escapeTags(XML::unescape($data->guid));
1674 $subject = Strings::escapeTags(XML::unescape($data->subject));
1675 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1676 $participants = Strings::escapeTags(XML::unescape($data->participants));
1678 $messages = $data->message;
1680 if (!count($messages)) {
1681 Logger::log("empty conversation");
1685 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1690 if (!empty($contact['gsid'])) {
1691 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1694 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1695 if (!DBA::isResult($conversation)) {
1697 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1698 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1699 intval($importer["uid"]),
1701 DBA::escape($author),
1702 DBA::escape($created_at),
1703 DBA::escape(DateTimeFormat::utcNow()),
1704 DBA::escape($subject),
1705 DBA::escape($participants)
1708 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1711 if (!$conversation) {
1712 Logger::log("unable to create conversation.");
1716 foreach ($messages as $mesg) {
1717 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1724 * Processes "like" messages
1726 * @param array $importer Array of the importer user
1727 * @param string $sender The sender of the message
1728 * @param object $data The message object
1730 * @return int The message id of the generated like or "false" if there was an error
1731 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1732 * @throws \ImagickException
1734 private static function receiveLike(array $importer, $sender, $data, bool $fetched)
1736 $author = Strings::escapeTags(XML::unescape($data->author));
1737 $guid = Strings::escapeTags(XML::unescape($data->guid));
1738 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1739 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
1740 $positive = Strings::escapeTags(XML::unescape($data->positive));
1742 // likes on comments aren't supported by Diaspora - only on posts
1743 // But maybe this will be supported in the future, so we will accept it.
1744 if (!in_array($parent_type, ["Post", "Comment"])) {
1748 $contact = self::allowedContactByHandle($importer, $sender, true);
1753 if (!empty($contact['gsid'])) {
1754 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1757 $message_id = self::messageExists($importer["uid"], $guid);
1762 $toplevel_parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1763 if (!$toplevel_parent_item) {
1767 $person = FContact::getByURL($author);
1768 if (!is_array($person)) {
1769 Logger::log("unable to find author details");
1773 // Fetch the contact id - if we know this contact
1774 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1776 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1777 // We would accept this anyhow.
1778 if ($positive == "true") {
1779 $verb = Activity::LIKE;
1781 $verb = Activity::DISLIKE;
1786 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1787 $datarray["direction"] = $fetched ? Conversation::PULL : Conversation::PUSH;
1789 $datarray["uid"] = $importer["uid"];
1790 $datarray["contact-id"] = $author_contact["cid"];
1791 $datarray["network"] = $author_contact["network"];
1793 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
1794 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1796 $datarray["guid"] = $guid;
1797 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1799 $datarray["verb"] = $verb;
1800 $datarray["gravity"] = GRAVITY_ACTIVITY;
1801 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1803 $datarray["object-type"] = Activity\ObjectType::NOTE;
1805 $datarray["body"] = $verb;
1807 // Diaspora doesn't provide a date for likes
1808 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
1810 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1811 if ($toplevel_parent_item['gravity'] != GRAVITY_PARENT) {
1812 $toplevel = Post::selectFirst(['origin'], ['id' => $toplevel_parent_item['parent']]);
1813 $origin = $toplevel["origin"];
1815 $origin = $toplevel_parent_item["origin"];
1818 // If we are the origin of the parent we store the original data.
1819 // We notify our followers during the item storage.
1821 $datarray['diaspora_signed_text'] = json_encode($data);
1824 if (Item::isTooOld($datarray)) {
1825 Logger::info('Like is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1829 $message_id = Item::insert($datarray);
1831 if ($message_id <= 0) {
1836 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1837 if ($datarray['uid'] == 0) {
1838 Item::distribute($message_id, json_encode($data));
1846 * Processes private messages
1848 * @param array $importer Array of the importer user
1849 * @param object $data The message object
1851 * @return bool Success?
1852 * @throws \Exception
1854 private static function receiveMessage(array $importer, $data)
1856 $author = Strings::escapeTags(XML::unescape($data->author));
1857 $guid = Strings::escapeTags(XML::unescape($data->guid));
1858 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
1859 $text = XML::unescape($data->text);
1860 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1862 $contact = self::allowedContactByHandle($importer, $author, true);
1867 if (!empty($contact['gsid'])) {
1868 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1871 $conversation = null;
1873 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
1874 $conversation = DBA::selectFirst('conv', [], $condition);
1876 if (!DBA::isResult($conversation)) {
1877 Logger::log("conversation not available.");
1881 $message_uri = $author.":".$guid;
1883 $person = FContact::getByURL($author);
1885 Logger::log("unable to find author details");
1889 $body = Markdown::toBBCode($text);
1891 $body = self::replacePeopleGuid($body, $person["url"]);
1893 return Mail::insert([
1894 'uid' => $importer['uid'],
1896 'convid' => $conversation['id'],
1897 'from-name' => $person['name'],
1898 'from-photo' => $person['photo'],
1899 'from-url' => $person['url'],
1900 'contact-id' => $contact['id'],
1901 'title' => $conversation['subject'],
1904 'uri' => $message_uri,
1905 'parent-uri' => $author.":".$conversation['guid'],
1906 'created' => $created_at
1911 * Processes participations - unsupported by now
1913 * @param array $importer Array of the importer user
1914 * @param object $data The message object
1916 * @return bool success
1917 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1918 * @throws \ImagickException
1920 private static function receiveParticipation(array $importer, $data, bool $fetched)
1922 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
1923 $guid = Strings::escapeTags(XML::unescape($data->guid));
1924 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1926 $contact = self::allowedContactByHandle($importer, $author, true);
1931 if (!empty($contact['gsid'])) {
1932 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1935 if (self::messageExists($importer["uid"], $guid)) {
1939 $toplevel_parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1940 if (!$toplevel_parent_item) {
1944 if (!$toplevel_parent_item['origin']) {
1945 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1948 if (!in_array($toplevel_parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
1949 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1953 $person = FContact::getByURL($author);
1954 if (!is_array($person)) {
1955 Logger::log("Person not found: ".$author);
1959 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1961 // Store participation
1964 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1965 $datarray["direction"] = $fetched ? Conversation::PULL : Conversation::PUSH;
1967 $datarray["uid"] = $importer["uid"];
1968 $datarray["contact-id"] = $author_contact["cid"];
1969 $datarray["network"] = $author_contact["network"];
1971 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
1972 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1974 $datarray["guid"] = $guid;
1975 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1977 $datarray["verb"] = Activity::FOLLOW;
1978 $datarray["gravity"] = GRAVITY_ACTIVITY;
1979 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1981 $datarray["object-type"] = Activity\ObjectType::NOTE;
1983 $datarray["body"] = Activity::FOLLOW;
1985 // Diaspora doesn't provide a date for a participation
1986 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
1988 if (Item::isTooOld($datarray)) {
1989 Logger::info('Participation is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1993 $message_id = Item::insert($datarray);
1995 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
1997 // Send all existing comments and likes to the requesting server
1998 $comments = Post::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb'],
1999 ['parent' => $toplevel_parent_item['id'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
2000 while ($comment = Post::fetch($comments)) {
2001 if (in_array($comment['verb'], [Activity::FOLLOW, Activity::TAG])) {
2002 Logger::info('participation messages are not relayed', ['item' => $comment['id']]);
2006 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
2007 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2011 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
2012 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2016 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact["cid"]]);
2017 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $author_contact["cid"])) {
2018 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2021 DBA::close($comments);
2027 * Processes photos - unneeded
2029 * @param array $importer Array of the importer user
2030 * @param object $data The message object
2032 * @return bool always true
2034 private static function receivePhoto(array $importer, $data)
2036 // There doesn't seem to be a reason for this function,
2037 // since the photo data is transmitted in the status message as well
2042 * Processes poll participations - unssupported
2044 * @param array $importer Array of the importer user
2045 * @param object $data The message object
2047 * @return bool always true
2049 private static function receivePollParticipation(array $importer, $data)
2051 // We don't support polls by now
2056 * Processes incoming profile updates
2058 * @param array $importer Array of the importer user
2059 * @param object $data The message object
2061 * @return bool Success
2062 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2063 * @throws \ImagickException
2065 private static function receiveProfile(array $importer, $data)
2067 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2069 $contact = self::contactByHandle($importer["uid"], $author);
2074 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2075 $image_url = XML::unescape($data->image_url);
2076 $birthday = XML::unescape($data->birthday);
2077 $about = Markdown::toBBCode(XML::unescape($data->bio));
2078 $location = Markdown::toBBCode(XML::unescape($data->location));
2079 $searchable = (XML::unescape($data->searchable) == "true");
2080 $nsfw = (XML::unescape($data->nsfw) == "true");
2081 $tags = XML::unescape($data->tag_string);
2083 $tags = explode("#", $tags);
2086 foreach ($tags as $tag) {
2087 $tag = trim(strtolower($tag));
2093 $keywords = implode(", ", $keywords);
2095 $handle_parts = explode("@", $author);
2096 $nick = $handle_parts[0];
2099 $name = $handle_parts[0];
2102 if (preg_match("|^https?://|", $image_url) === 0) {
2103 $image_url = "http://".$handle_parts[1].$image_url;
2106 Contact::updateAvatar($contact["id"], $image_url);
2108 // Generic birthday. We don't know the timezone. The year is irrelevant.
2110 $birthday = str_replace("1000", "1901", $birthday);
2112 if ($birthday != "") {
2113 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2116 // this is to prevent multiple birthday notifications in a single year
2117 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2119 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2120 $birthday = $contact["bd"];
2123 $fields = ['name' => $name, 'location' => $location,
2124 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2125 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2126 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2128 if (!empty($birthday)) {
2129 $fields['bd'] = $birthday;
2132 DBA::update('contact', $fields, ['id' => $contact['id']]);
2134 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2140 * Processes incoming friend requests
2142 * @param array $importer Array of the importer user
2143 * @param array $contact The contact that send the request
2145 * @throws \Exception
2147 private static function receiveRequestMakeFriend(array $importer, array $contact)
2149 if ($contact["rel"] == Contact::SHARING) {
2152 ['rel' => Contact::FRIEND, 'writable' => true],
2153 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2159 * Processes incoming sharing notification
2161 * @param array $importer Array of the importer user
2162 * @param object $data The message object
2164 * @return bool Success
2165 * @throws \Exception
2167 private static function receiveContactRequest(array $importer, $data)
2169 $author = XML::unescape($data->author);
2170 $recipient = XML::unescape($data->recipient);
2172 if (!$author || !$recipient) {
2176 // the current protocol version doesn't know these fields
2177 // That means that we will assume their existance
2178 if (isset($data->following)) {
2179 $following = (XML::unescape($data->following) == "true");
2184 if (isset($data->sharing)) {
2185 $sharing = (XML::unescape($data->sharing) == "true");
2190 $contact = self::contactByHandle($importer["uid"], $author);
2192 // perhaps we were already sharing with this person. Now they're sharing with us.
2193 // That makes us friends.
2196 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2197 self::receiveRequestMakeFriend($importer, $contact);
2199 // refetch the contact array
2200 $contact = self::contactByHandle($importer["uid"], $author);
2202 // If we are now friends, we are sending a share message.
2203 // Normally we needn't to do so, but the first message could have been vanished.
2204 if (in_array($contact["rel"], [Contact::FRIEND])) {
2205 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2206 if (DBA::isResult($user)) {
2207 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2208 self::sendShare($user, $contact);
2213 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2214 Contact::removeFollower($importer, $contact);
2219 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2220 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2222 } elseif (!$following && !$sharing) {
2223 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2225 } elseif (!$following && $sharing) {
2226 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2227 } elseif ($following && $sharing) {
2228 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2229 } elseif ($following && !$sharing) {
2230 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2233 $ret = FContact::getByURL($author);
2235 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2236 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2240 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2242 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2247 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2248 'author-link' => $ret['url']];
2250 $result = Contact::addRelationship($importer, $contact, $item, false);
2251 if ($result === true) {
2252 $contact_record = self::contactByHandle($importer['uid'], $author);
2253 if (!$contact_record) {
2254 Logger::info('unable to locate newly created contact record.');
2258 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2259 if (DBA::isResult($user)) {
2260 self::sendShare($user, $contact_record);
2262 // Send the profile data, maybe it weren't transmitted before
2263 self::sendProfile($importer['uid'], [$contact_record]);
2271 * Fetches a message with a given guid
2273 * @param string $guid message guid
2274 * @param string $orig_author handle of the original post
2275 * @return array The fetched item
2276 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2277 * @throws \ImagickException
2279 public static function originalItem($guid, $orig_author)
2282 Logger::log('Empty guid. Quitting.');
2286 // Do we already have this item?
2287 $fields = ['body', 'title', 'app', 'created', 'object-type', 'uri', 'guid',
2288 'author-name', 'author-link', 'author-avatar', 'plink', 'uri-id'];
2289 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2290 $item = Post::selectFirst($fields, $condition);
2292 if (DBA::isResult($item)) {
2293 Logger::log("reshared message ".$guid." already exists on system.");
2295 // Maybe it is already a reshared item?
2296 // Then refetch the content, if it is a reshare from a reshare.
2297 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2298 if (self::isReshare($item["body"], true)) {
2300 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2301 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2303 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2305 // Add OEmbed and other information to the body
2306 $item["body"] = PageInfo::searchAndAppendToBody($item["body"], false, true);
2314 if (!DBA::isResult($item)) {
2315 if (empty($orig_author)) {
2316 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2320 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2321 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2322 $stored = self::storeByGuid($guid, $server);
2325 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2326 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2327 $stored = self::storeByGuid($guid, $server);
2331 $fields = ['body', 'title', 'app', 'created', 'object-type', 'uri', 'guid',
2332 'author-name', 'author-link', 'author-avatar', 'plink', 'uri-id'];
2333 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2334 $item = Post::selectFirst($fields, $condition);
2336 if (DBA::isResult($item)) {
2337 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2338 if (self::isReshare($item["body"], false)) {
2339 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2340 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2351 * Stores a reshare activity
2353 * @param array $item Array of reshare post
2354 * @param integer $parent_message_id Id of the parent post
2355 * @param string $guid GUID string of reshare action
2356 * @param string $author Author handle
2358 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2360 $parent = Post::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2364 $datarray['uid'] = $item['uid'];
2365 $datarray['contact-id'] = $item['contact-id'];
2366 $datarray['network'] = $item['network'];
2368 $datarray['author-link'] = $item['author-link'];
2369 $datarray['author-id'] = $item['author-id'];
2371 $datarray['owner-link'] = $datarray['author-link'];
2372 $datarray['owner-id'] = $datarray['author-id'];
2374 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2375 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2376 $datarray['thr-parent'] = $parent['uri'];
2378 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2379 $datarray['gravity'] = GRAVITY_ACTIVITY;
2380 $datarray['object-type'] = Activity\ObjectType::NOTE;
2382 $datarray['protocol'] = $item['protocol'];
2383 $datarray['source'] = $item['source'];
2384 $datarray['direction'] = $item['direction'];
2386 $datarray['plink'] = self::plink($author, $datarray['guid']);
2387 $datarray['private'] = $item['private'];
2388 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2390 if (Item::isTooOld($datarray)) {
2391 Logger::info('Reshare activity is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2395 $message_id = Item::insert($datarray);
2398 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2399 if ($datarray['uid'] == 0) {
2400 Item::distribute($message_id);
2406 * Processes a reshare message
2408 * @param array $importer Array of the importer user
2409 * @param object $data The message object
2410 * @param string $xml The original XML of the message
2412 * @return int the message id
2413 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2414 * @throws \ImagickException
2416 private static function receiveReshare(array $importer, $data, $xml, bool $fetched)
2418 $author = Strings::escapeTags(XML::unescape($data->author));
2419 $guid = Strings::escapeTags(XML::unescape($data->guid));
2420 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2421 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2422 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2423 /// @todo handle unprocessed property "provider_display_name"
2424 $public = Strings::escapeTags(XML::unescape($data->public));
2426 $contact = self::allowedContactByHandle($importer, $author, false);
2431 if (!empty($contact['gsid'])) {
2432 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2435 $message_id = self::messageExists($importer["uid"], $guid);
2440 $original_item = self::originalItem($root_guid, $root_author);
2441 if (!$original_item) {
2445 if (empty($original_item['plink'])) {
2446 $original_item['plink'] = self::plink($root_author, $root_guid);
2451 $datarray["uid"] = $importer["uid"];
2452 $datarray["contact-id"] = $contact["id"];
2453 $datarray["network"] = Protocol::DIASPORA;
2455 $datarray["author-link"] = $contact["url"];
2456 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2458 $datarray["owner-link"] = $datarray["author-link"];
2459 $datarray["owner-id"] = $datarray["author-id"];
2461 $datarray["guid"] = $guid;
2462 $datarray["uri"] = $datarray["thr-parent"] = self::getUriFromGuid($author, $guid);
2463 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2465 $datarray["verb"] = Activity::POST;
2466 $datarray["gravity"] = GRAVITY_PARENT;
2468 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2469 $datarray["source"] = $xml;
2470 $datarray["direction"] = $fetched ? Conversation::PULL : Conversation::PUSH;
2472 /// @todo Copy tag data from original post
2474 $prefix = BBCode::getShareOpeningTag(
2475 $original_item["author-name"],
2476 $original_item["author-link"],
2477 $original_item["author-avatar"],
2478 $original_item["plink"],
2479 $original_item["created"],
2480 $original_item["guid"]
2483 if (!empty($original_item['title'])) {
2484 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2487 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2489 Tag::storeFromBody($datarray['uri-id'], $datarray["body"]);
2491 Post\Media::copy($original_item['uri-id'], $datarray['uri-id']);
2492 $datarray["app"] = $original_item["app"];
2494 $datarray["plink"] = self::plink($author, $guid);
2495 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2496 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2498 $datarray["object-type"] = $original_item["object-type"];
2500 self::fetchGuid($datarray);
2502 if (Item::isTooOld($datarray)) {
2503 Logger::info('Reshare is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2507 $message_id = Item::insert($datarray);
2509 self::sendParticipation($contact, $datarray);
2511 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2512 if ($root_message_id) {
2513 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2517 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2518 if ($datarray['uid'] == 0) {
2519 Item::distribute($message_id);
2528 * Processes retractions
2530 * @param array $importer Array of the importer user
2531 * @param array $contact The contact of the item owner
2532 * @param object $data The message object
2534 * @return bool success
2535 * @throws \Exception
2537 private static function itemRetraction(array $importer, array $contact, $data)
2539 $author = Strings::escapeTags(XML::unescape($data->author));
2540 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2541 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2543 $person = FContact::getByURL($author);
2544 if (!is_array($person)) {
2545 Logger::log("unable to find author detail for ".$author);
2549 if (empty($contact["url"])) {
2550 $contact["url"] = $person["url"];
2553 // Fetch items that are about to be deleted
2554 $fields = ['uid', 'id', 'parent', 'author-link', 'uri-id'];
2556 // When we receive a public retraction, we delete every item that we find.
2557 if ($importer['uid'] == 0) {
2558 $condition = ['guid' => $target_guid, 'deleted' => false];
2560 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2563 $r = Post::select($fields, $condition);
2564 if (!DBA::isResult($r)) {
2565 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2569 while ($item = Post::fetch($r)) {
2570 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2571 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2575 // Fetch the parent item
2576 $parent = Post::selectFirst(['author-link'], ['id' => $item['parent']]);
2578 // Only delete it if the parent author really fits
2579 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2580 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2584 Item::markForDeletion(['id' => $item['id']]);
2586 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item['parent'], Logger::DEBUG);
2594 * Receives retraction messages
2596 * @param array $importer Array of the importer user
2597 * @param string $sender The sender of the message
2598 * @param object $data The message object
2600 * @return bool Success
2601 * @throws \Exception
2603 private static function receiveRetraction(array $importer, $sender, $data)
2605 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2607 $contact = self::contactByHandle($importer["uid"], $sender);
2608 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2609 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2617 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2619 switch ($target_type) {
2624 case "StatusMessage":
2625 return self::itemRetraction($importer, $contact, $data);
2627 case "PollParticipation":
2629 // Currently unsupported
2633 Logger::log("Unknown target type ".$target_type);
2640 * Checks if an incoming message is wanted
2642 * @param string $url
2643 * @param integer $uriid
2644 * @param string $author
2645 * @param string $body
2646 * @return boolean Is the message wanted?
2648 private static function isSolicitedMessage(string $url, int $uriid, string $author, string $body)
2650 $contact = Contact::getByURL($author);
2651 if (DBA::exists('contact', ["`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)",
2652 $contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) {
2653 Logger::info('Author has got followers - accepted', ['url' => $url, 'author' => $author]);
2657 $taglist = Tag::getByURIId($uriid, [Tag::HASHTAG]);
2658 $tags = array_column($taglist, 'name');
2659 return Relay::isSolicitedPost($tags, $body, $contact['id'], $url, Protocol::DIASPORA);
2663 * Store an attached photo in the post-media table
2666 * @param object $photo
2669 private static function storePhotoAsMedia(int $uriid, $photo)
2672 $data['uri-id'] = $uriid;
2673 $data['type'] = Post\Media::IMAGE;
2674 $data['url'] = XML::unescape($photo->remote_photo_path) . XML::unescape($photo->remote_photo_name);
2675 $data['height'] = (int)XML::unescape($photo->height ?? 0);
2676 $data['width'] = (int)XML::unescape($photo->width ?? 0);
2677 $data['description'] = XML::unescape($photo->text ?? '');
2679 Post\Media::insert($data);
2683 * Receives status messages
2685 * @param array $importer Array of the importer user
2686 * @param SimpleXMLElement $data The message object
2687 * @param string $xml The original XML of the message
2688 * @param bool $fetched The message had been fetched and not pushed
2689 * @return int The message id of the newly created item
2690 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2691 * @throws \ImagickException
2693 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml, bool $fetched)
2695 $author = Strings::escapeTags(XML::unescape($data->author));
2696 $guid = Strings::escapeTags(XML::unescape($data->guid));
2697 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2698 $public = Strings::escapeTags(XML::unescape($data->public));
2699 $text = XML::unescape($data->text);
2700 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2702 $contact = self::allowedContactByHandle($importer, $author, false);
2707 if (!empty($contact['gsid'])) {
2708 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2711 $message_id = self::messageExists($importer["uid"], $guid);
2717 if ($data->location) {
2718 foreach ($data->location->children() as $fieldname => $data) {
2719 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2723 $raw_body = $body = Markdown::toBBCode($text);
2727 $datarray["guid"] = $guid;
2728 $datarray["uri"] = $datarray["thr-parent"] = self::getUriFromGuid($author, $guid);
2729 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2731 // Attach embedded pictures to the body
2733 foreach ($data->photo as $photo) {
2734 self::storePhotoAsMedia($datarray['uri-id'], $photo);
2735 $body = "[img]".XML::unescape($photo->remote_photo_path).
2736 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2739 $datarray["object-type"] = Activity\ObjectType::IMAGE;
2741 $datarray["object-type"] = Activity\ObjectType::NOTE;
2743 // Add OEmbed and other information to the body
2744 if (!self::isHubzilla($contact["url"])) {
2745 $body = PageInfo::searchAndAppendToBody($body, false, true);
2749 /// @todo enable support for polls
2750 //if ($data->poll) {
2751 // foreach ($data->poll AS $poll)
2756 /// @todo enable support for events
2758 $datarray["uid"] = $importer["uid"];
2759 $datarray["contact-id"] = $contact["id"];
2760 $datarray["network"] = Protocol::DIASPORA;
2762 $datarray["author-link"] = $contact["url"];
2763 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2765 $datarray["owner-link"] = $datarray["author-link"];
2766 $datarray["owner-id"] = $datarray["author-id"];
2768 $datarray["verb"] = Activity::POST;
2769 $datarray["gravity"] = GRAVITY_PARENT;
2771 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2772 $datarray["source"] = $xml;
2773 $datarray["direction"] = $fetched ? Conversation::PULL : Conversation::PUSH;
2776 $datarray["post-type"] = Item::PT_FETCHED;
2777 } elseif ($datarray["uid"] == 0) {
2778 $datarray["post-type"] = Item::PT_GLOBAL;
2781 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2782 $datarray["raw-body"] = self::replacePeopleGuid($raw_body, $contact["url"]);
2784 self::storeMentions($datarray['uri-id'], $text);
2785 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
2787 if (!$fetched && !self::isSolicitedMessage($datarray["uri"], $datarray['uri-id'], $author, $body)) {
2788 DBA::delete('item-uri', ['uri' => $datarray['uri']]);
2792 if ($provider_display_name != "") {
2793 $datarray["app"] = $provider_display_name;
2796 $datarray["plink"] = self::plink($author, $guid);
2797 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2798 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2800 if (isset($address["address"])) {
2801 $datarray["location"] = $address["address"];
2804 if (isset($address["lat"]) && isset($address["lng"])) {
2805 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2808 self::fetchGuid($datarray);
2810 if (Item::isTooOld($datarray)) {
2811 Logger::info('Status is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2815 $message_id = Item::insert($datarray);
2817 self::sendParticipation($contact, $datarray);
2820 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2821 if ($datarray['uid'] == 0) {
2822 Item::distribute($message_id);
2830 /* ************************************************************************************** *
2831 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2832 * ************************************************************************************** */
2835 * returnes the handle of a contact
2837 * @param array $contact contact array
2839 * @return string the handle in the format user@domain.tld
2840 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2842 private static function myHandle(array $contact)
2844 if (!empty($contact["addr"])) {
2845 return $contact["addr"];
2848 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2849 // So - just in case - we build the the address here.
2850 if ($contact["nickname"] != "") {
2851 $nick = $contact["nickname"];
2853 $nick = $contact["nick"];
2856 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
2861 * Creates the data for a private message in the new format
2863 * @param string $msg The message that is to be transmitted
2864 * @param array $user The record of the sender
2865 * @param array $contact Target of the communication
2866 * @param string $prvkey The private key of the sender
2867 * @param string $pubkey The public key of the receiver
2869 * @return string The encrypted data
2870 * @throws \Exception
2872 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
2874 Logger::log("Message: ".$msg, Logger::DATA);
2876 // without a public key nothing will work
2878 Logger::log("pubkey missing: contact id: ".$contact["id"]);
2882 $aes_key = openssl_random_pseudo_bytes(32);
2883 $b_aes_key = base64_encode($aes_key);
2884 $iv = openssl_random_pseudo_bytes(16);
2885 $b_iv = base64_encode($iv);
2887 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2889 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
2891 $encrypted_key_bundle = "";
2892 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
2896 $json_object = json_encode(
2897 ["aes_key" => base64_encode($encrypted_key_bundle),
2898 "encrypted_magic_envelope" => base64_encode($ciphertext)]
2901 return $json_object;
2905 * Creates the envelope for the "fetch" endpoint and for the new format
2907 * @param string $msg The message that is to be transmitted
2908 * @param array $user The record of the sender
2910 * @return string The envelope
2911 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2913 public static function buildMagicEnvelope($msg, array $user)
2915 $b64url_data = Strings::base64UrlEncode($msg);
2916 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
2918 $key_id = Strings::base64UrlEncode(self::myHandle($user));
2919 $type = "application/xml";
2920 $encoding = "base64url";
2921 $alg = "RSA-SHA256";
2922 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
2924 // Fallback if the private key wasn't transmitted in the expected field
2925 if ($user['uprvkey'] == "") {
2926 $user['uprvkey'] = $user['prvkey'];
2929 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
2930 $sig = Strings::base64UrlEncode($signature);
2932 $xmldata = ["me:env" => ["me:data" => $data,
2933 "@attributes" => ["type" => $type],
2934 "me:encoding" => $encoding,
2937 "@attributes2" => ["key_id" => $key_id]]];
2939 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
2941 return XML::fromArray($xmldata, $xml, false, $namespaces);
2945 * Create the envelope for a message
2947 * @param string $msg The message that is to be transmitted
2948 * @param array $user The record of the sender
2949 * @param array $contact Target of the communication
2950 * @param string $prvkey The private key of the sender
2951 * @param string $pubkey The public key of the receiver
2952 * @param bool $public Is the message public?
2954 * @return string The message that will be transmitted to other servers
2955 * @throws \Exception
2957 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
2959 // The message is put into an envelope with the sender's signature
2960 $envelope = self::buildMagicEnvelope($msg, $user);
2962 // Private messages are put into a second envelope, encrypted with the receivers public key
2964 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
2971 * Creates a signature for a message
2973 * @param array $owner the array of the owner of the message
2974 * @param array $message The message that is to be signed
2976 * @return string The signature
2978 private static function signature($owner, $message)
2981 unset($sigmsg["author_signature"]);
2982 unset($sigmsg["parent_author_signature"]);
2984 $signed_text = implode(";", $sigmsg);
2986 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
2990 * Transmit a message to a target server
2992 * @param array $owner the array of the item owner
2993 * @param array $contact Target of the communication
2994 * @param string $envelope The message that is to be transmitted
2995 * @param bool $public_batch Is it a public post?
2996 * @param string $guid message guid
2998 * @return int Result of the transmission
2999 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3000 * @throws \ImagickException
3002 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3004 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
3009 $logid = Strings::getRandomHex(4);
3011 // We always try to use the data from the fcontact table.
3012 // This is important for transmitting data to Friendica servers.
3013 if (!empty($contact['addr'])) {
3014 $fcontact = FContact::getByURL($contact['addr']);
3015 if (!empty($fcontact)) {
3016 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3020 if (empty($dest_url)) {
3021 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3025 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3029 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3031 if (!intval(DI::config()->get("system", "diaspora_test"))) {
3032 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3034 $postResult = DI::httpRequest()->post($dest_url . "/", $envelope, ["Content-Type: " . $content_type]);
3035 $return_code = $postResult->getReturnCode();
3037 Logger::log("test_mode");
3041 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3043 return $return_code ? $return_code : -1;
3048 * Build the post xml
3050 * @param string $type The message type
3051 * @param array $message The message data
3053 * @return string The post XML
3055 public static function buildPostXml($type, $message)
3057 $data = [$type => $message];
3059 return XML::fromArray($data, $xml);
3063 * Builds and transmit messages
3065 * @param array $owner the array of the item owner
3066 * @param array $contact Target of the communication
3067 * @param string $type The message type
3068 * @param array $message The message data
3069 * @param bool $public_batch Is it a public post?
3070 * @param string $guid message guid
3072 * @return int Result of the transmission
3073 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3074 * @throws \ImagickException
3076 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3078 $msg = self::buildPostXml($type, $message);
3080 Logger::log('message: '.$msg, Logger::DATA);
3081 Logger::log('send guid '.$guid, Logger::DEBUG);
3083 // Fallback if the private key wasn't transmitted in the expected field
3084 if (empty($owner['uprvkey'])) {
3085 $owner['uprvkey'] = $owner['prvkey'];
3088 // When sending content to Friendica contacts using the Diaspora protocol
3089 // we have to fetch the public key from the fcontact.
3090 // This is due to the fact that legacy DFRN had unique keys for every contact.
3091 $pubkey = $contact['pubkey'];
3092 if (!empty($contact['addr'])) {
3093 $fcontact = FContact::getByURL($contact['addr']);
3094 if (!empty($fcontact)) {
3095 $pubkey = $fcontact['pubkey'];
3099 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
3101 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3103 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3105 return $return_code;
3109 * sends a participation (Used to get all further updates)
3111 * @param array $contact Target of the communication
3112 * @param array $item Item array
3114 * @return int The result of the transmission
3115 * @throws \Exception
3117 private static function sendParticipation(array $contact, array $item)
3119 // Don't send notifications for private postings
3120 if ($item['private'] == Item::PRIVATE) {
3124 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3126 $result = DI::cache()->get($cachekey);
3127 if (!is_null($result)) {
3131 $owner = User::getOwnerDataById($item['uid']);
3132 $author = self::myHandle($owner);
3134 $message = ["author" => $author,
3135 "guid" => System::createUUID(),
3136 "parent_type" => "Post",
3137 "parent_guid" => $item["guid"]];
3139 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3141 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3142 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3144 return self::buildAndTransmit($owner, $contact, "participation", $message);
3148 * sends an account migration
3150 * @param array $owner the array of the item owner
3151 * @param array $contact Target of the communication
3152 * @param int $uid User ID
3154 * @return int The result of the transmission
3155 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3156 * @throws \ImagickException
3158 public static function sendAccountMigration(array $owner, array $contact, $uid)
3160 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3161 $profile = self::createProfileData($uid);
3163 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3164 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3166 $message = ["author" => $old_handle,
3167 "profile" => $profile,
3168 "signature" => $signature];
3170 Logger::info('Send account migration', ['msg' => $message]);
3172 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3176 * Sends a "share" message
3178 * @param array $owner the array of the item owner
3179 * @param array $contact Target of the communication
3181 * @return int The result of the transmission
3182 * @throws \Exception
3184 public static function sendShare(array $owner, array $contact)
3187 * @todo support the different possible combinations of "following" and "sharing"
3188 * Currently, Diaspora only interprets the "sharing" field
3190 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3194 switch ($contact["rel"]) {
3195 case Contact::FRIEND:
3199 case Contact::SHARING:
3203 case Contact::FOLLOWER:
3209 $message = ["author" => self::myHandle($owner),
3210 "recipient" => $contact["addr"],
3211 "following" => "true",
3212 "sharing" => "true"];
3214 Logger::info('Send share', ['msg' => $message]);
3216 return self::buildAndTransmit($owner, $contact, "contact", $message);
3220 * sends an "unshare"
3222 * @param array $owner the array of the item owner
3223 * @param array $contact Target of the communication
3225 * @return int The result of the transmission
3226 * @throws \Exception
3228 public static function sendUnshare(array $owner, array $contact)
3230 $message = ["author" => self::myHandle($owner),
3231 "recipient" => $contact["addr"],
3232 "following" => "false",
3233 "sharing" => "false"];
3235 Logger::info('Send unshare', ['msg' => $message]);
3237 return self::buildAndTransmit($owner, $contact, "contact", $message);
3241 * Checks a message body if it is a reshare
3243 * @param string $body The message body that is to be check
3244 * @param bool $complete Should it be a complete check or a simple check?
3246 * @return array|bool Reshare details or "false" if no reshare
3247 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3248 * @throws \ImagickException
3250 public static function isReshare($body, $complete = true)
3252 $body = trim($body);
3254 $reshared = Item::getShareArray(['body' => $body]);
3255 if (empty($reshared)) {
3259 // Skip if it isn't a pure repeated messages
3260 // Does it start with a share?
3261 if (!empty($reshared['comment']) && $complete) {
3265 if (!empty($reshared['guid']) && $complete) {
3266 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3267 $item = Post::selectFirst(['contact-id'], $condition);
3268 if (DBA::isResult($item)) {
3270 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3271 $ret["root_guid"] = $reshared['guid'];
3273 } elseif ($complete) {
3274 // We are resharing something that isn't a DFRN or Diaspora post.
3275 // So we have to return "false" on "$complete" to not trigger a reshare.
3278 } elseif (empty($reshared['guid']) && $complete) {
3284 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3285 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3286 if (!empty($contact['addr'])) {
3287 $ret['root_handle'] = $contact['addr'];
3291 if (empty($ret) && !$complete) {
3299 * Create an event array
3301 * @param integer $event_id The id of the event
3303 * @return array with event data
3304 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3306 private static function buildEvent($event_id)
3308 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3309 if (!DBA::isResult($r)) {
3317 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3318 if (!DBA::isResult($r)) {
3324 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3325 if (!DBA::isResult($r)) {
3331 $eventdata['author'] = self::myHandle($owner);
3333 if ($event['guid']) {
3334 $eventdata['guid'] = $event['guid'];
3337 $mask = DateTimeFormat::ATOM;
3339 /// @todo - establish "all day" events in Friendica
3340 $eventdata["all_day"] = "false";
3342 $eventdata['timezone'] = 'UTC';
3343 if (!$event['adjust'] && $user['timezone']) {
3344 $eventdata['timezone'] = $user['timezone'];
3347 if ($event['start']) {
3348 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3350 if ($event['finish'] && !$event['nofinish']) {
3351 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3353 if ($event['summary']) {
3354 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3356 if ($event['desc']) {
3357 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3359 if ($event['location']) {
3360 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3361 $coord = Map::getCoordinates($event['location']);
3364 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3365 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3366 $location["lat"] = $coord['lat'];
3367 $location["lng"] = $coord['lon'];
3369 $location["lat"] = 0;
3370 $location["lng"] = 0;
3372 $eventdata['location'] = $location;
3379 * Create a post (status message or reshare)
3381 * @param array $item The item that will be exported
3382 * @param array $owner the array of the item owner
3385 * 'type' -> Message type ("status_message" or "reshare")
3386 * 'message' -> Array of XML elements of the status
3387 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3388 * @throws \ImagickException
3390 public static function buildStatus(array $item, array $owner)
3392 $cachekey = "diaspora:buildStatus:".$item['guid'];
3394 $result = DI::cache()->get($cachekey);
3395 if (!is_null($result)) {
3399 $myaddr = self::myHandle($owner);
3401 $public = ($item["private"] == Item::PRIVATE ? "false" : "true");
3402 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3403 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3405 // Detect a share element and do a reshare
3406 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) {
3407 $message = ["author" => $myaddr,
3408 "guid" => $item["guid"],
3409 "created_at" => $created,
3410 "root_author" => $ret["root_handle"],
3411 "root_guid" => $ret["root_guid"],
3412 "provider_display_name" => $item["app"],
3413 "public" => $public];
3417 $title = $item["title"];
3418 $body = $item["body"];
3420 // Fetch the title from an attached link - if there is one
3421 if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3422 $page_data = BBCode::getAttachmentData($item['body']);
3423 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3424 $title = $page_data['title'];
3428 if ($item['author-link'] != $item['owner-link']) {
3429 $body = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'],
3430 $item['plink'], $item['created']) . $body . '[/share]';
3433 // convert to markdown
3434 $body = html_entity_decode(BBCode::toMarkdown($body));
3437 if (strlen($title)) {
3438 $body = "### ".html_entity_decode($title)."\n\n".$body;
3441 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]);
3442 if (!empty($attachments)) {
3443 $body .= "\n".DI::l10n()->t("Attachments:")."\n";
3444 foreach ($attachments as $attachment) {
3445 $body .= "[" . $attachment['description'] . "](" . $attachment['url'] . ")\n";
3451 if ($item["location"] != "")
3452 $location["address"] = $item["location"];
3454 if ($item["coord"] != "") {
3455 $coord = explode(" ", $item["coord"]);
3456 $location["lat"] = $coord[0];
3457 $location["lng"] = $coord[1];
3460 $message = ["author" => $myaddr,
3461 "guid" => $item["guid"],
3462 "created_at" => $created,
3463 "edited_at" => $edited,
3464 "public" => $public,
3466 "provider_display_name" => $item["app"],
3467 "location" => $location];
3469 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3470 if (!isset($location["lat"]) || !isset($location["lng"])) {
3471 unset($message["location"]);
3474 if ($item['event-id'] > 0) {
3475 $event = self::buildEvent($item['event-id']);
3476 if (count($event)) {
3477 $message['event'] = $event;
3479 if (!empty($event['location']['address']) &&
3480 !empty($event['location']['lat']) &&
3481 !empty($event['location']['lng'])) {
3482 $message['location'] = $event['location'];
3485 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3486 // $message['text'] = '';
3490 $type = "status_message";
3493 $msg = ["type" => $type, "message" => $message];
3495 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3500 private static function prependParentAuthorMention($body, $profile_url)
3502 $profile = Contact::getByURL($profile_url, false, ['addr', 'name', 'contact-type']);
3503 if (!empty($profile['addr'])
3504 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3505 && !strstr($body, $profile['addr'])
3506 && !strstr($body, $profile_url)
3508 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3517 * @param array $item The item that will be exported
3518 * @param array $owner the array of the item owner
3519 * @param array $contact Target of the communication
3520 * @param bool $public_batch Is it a public post?
3522 * @return int The result of the transmission
3523 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3524 * @throws \ImagickException
3526 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3528 $status = self::buildStatus($item, $owner);
3530 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3534 * Creates a "like" object
3536 * @param array $item The item that will be exported
3537 * @param array $owner the array of the item owner
3539 * @return array The data for a "like"
3540 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3542 private static function constructLike(array $item, array $owner)
3544 $parent = Post::selectFirst(['guid', 'uri', 'thr-parent'], ['uri' => $item["thr-parent"]]);
3545 if (!DBA::isResult($parent)) {
3549 $target_type = ($parent["uri"] === $parent["thr-parent"] ? "Post" : "Comment");
3551 if ($item['verb'] === Activity::LIKE) {
3553 } elseif ($item['verb'] === Activity::DISLIKE) {
3554 $positive = "false";
3557 return(["author" => self::myHandle($owner),
3558 "guid" => $item["guid"],
3559 "parent_guid" => $parent["guid"],
3560 "parent_type" => $target_type,
3561 "positive" => $positive,
3562 "author_signature" => ""]);
3566 * Creates an "EventParticipation" object
3568 * @param array $item The item that will be exported
3569 * @param array $owner the array of the item owner
3571 * @return array The data for an "EventParticipation"
3572 * @throws \Exception
3574 private static function constructAttend(array $item, array $owner)
3576 $parent = Post::selectFirst(['guid'], ['uri' => $item['thr-parent']]);
3577 if (!DBA::isResult($parent)) {
3581 switch ($item['verb']) {
3582 case Activity::ATTEND:
3583 $attend_answer = 'accepted';
3585 case Activity::ATTENDNO:
3586 $attend_answer = 'declined';
3588 case Activity::ATTENDMAYBE:
3589 $attend_answer = 'tentative';
3592 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3596 return(["author" => self::myHandle($owner),
3597 "guid" => $item["guid"],
3598 "parent_guid" => $parent["guid"],
3599 "status" => $attend_answer,
3600 "author_signature" => ""]);
3604 * Creates the object for a comment
3606 * @param array $item The item that will be exported
3607 * @param array $owner the array of the item owner
3609 * @return array|false The data for a comment
3610 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3612 private static function constructComment(array $item, array $owner)
3614 $cachekey = "diaspora:constructComment:".$item['guid'];
3616 $result = DI::cache()->get($cachekey);
3617 if (!is_null($result)) {
3621 $toplevel_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3622 if (!DBA::isResult($toplevel_item)) {
3623 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3627 $thread_parent_item = $toplevel_item;
3628 if ($item['thr-parent'] != $item['parent-uri']) {
3629 $thread_parent_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3632 $body = $item["body"];
3634 // The replied to autor mention is prepended for clarity if:
3635 // - Item replied isn't yours
3636 // - Item is public or explicit mentions are disabled
3637 // - Implicit mentions are enabled
3639 $item['author-id'] != $thread_parent_item['author-id']
3640 && ($thread_parent_item['gravity'] != GRAVITY_PARENT)
3641 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3642 && !DI::config()->get('system', 'disable_implicit_mentions')
3644 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3647 $text = html_entity_decode(BBCode::toMarkdown($body));
3648 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3649 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3652 "author" => self::myHandle($owner),
3653 "guid" => $item["guid"],
3654 "created_at" => $created,
3655 "edited_at" => $edited,
3656 "parent_guid" => $toplevel_item["guid"],
3658 "author_signature" => ""
3661 // Send the thread parent guid only if it is a threaded comment
3662 if ($item['thr-parent'] != $item['parent-uri']) {
3663 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3666 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3672 * Send a like or a comment
3674 * @param array $item The item that will be exported
3675 * @param array $owner the array of the item owner
3676 * @param array $contact Target of the communication
3677 * @param bool $public_batch Is it a public post?
3679 * @return int The result of the transmission
3680 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3681 * @throws \ImagickException
3683 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3685 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3686 $message = self::constructAttend($item, $owner);
3687 $type = "event_participation";
3688 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3689 $message = self::constructLike($item, $owner);
3691 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3692 $message = self::constructComment($item, $owner);
3696 if (empty($message)) {
3700 $message["author_signature"] = self::signature($owner, $message);
3702 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3706 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3708 * @param array $item The item that will be exported
3709 * @param array $owner the array of the item owner
3710 * @param array $contact Target of the communication
3711 * @param bool $public_batch Is it a public post?
3713 * @return int The result of the transmission
3714 * @throws \Exception
3716 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3718 if ($item["deleted"]) {
3719 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3720 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3726 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3728 $msg = json_decode($item['signed_text'], true);
3731 if (is_array($msg)) {
3732 foreach ($msg as $field => $data) {
3733 if (!$item["deleted"]) {
3734 if ($field == "diaspora_handle") {
3737 if ($field == "target_type") {
3738 $field = "parent_type";
3742 $message[$field] = $data;
3745 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
3748 $message["parent_author_signature"] = self::signature($owner, $message);
3750 Logger::info('Relayed data', ['msg' => $message]);
3752 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3756 * Sends a retraction (deletion) of a message, like or comment
3758 * @param array $item The item that will be exported
3759 * @param array $owner the array of the item owner
3760 * @param array $contact Target of the communication
3761 * @param bool $public_batch Is it a public post?
3762 * @param bool $relay Is the retraction transmitted from a relay?
3764 * @return int The result of the transmission
3765 * @throws \Exception
3767 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
3769 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3771 $msg_type = "retraction";
3773 if ($item['gravity'] == GRAVITY_PARENT) {
3774 $target_type = "Post";
3775 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3776 $target_type = "Like";
3778 $target_type = "Comment";
3781 $message = ["author" => $itemaddr,
3782 "target_guid" => $item['guid'],
3783 "target_type" => $target_type];
3785 Logger::info('Got message', ['msg' => $message]);
3787 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3793 * @param array $item The item that will be exported
3794 * @param array $owner The owner
3795 * @param array $contact Target of the communication
3797 * @return int The result of the transmission
3798 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3799 * @throws \ImagickException
3801 public static function sendMail(array $item, array $owner, array $contact)
3803 $myaddr = self::myHandle($owner);
3805 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
3806 if (!DBA::isResult($cnv)) {
3807 Logger::log("conversation not found.");
3811 $body = BBCode::toMarkdown($item["body"]);
3812 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3815 "author" => $myaddr,
3816 "guid" => $item["guid"],
3817 "conversation_guid" => $cnv["guid"],
3819 "created_at" => $created,
3822 if ($item["reply"]) {
3827 "author" => $cnv["creator"],
3828 "guid" => $cnv["guid"],
3829 "subject" => $cnv["subject"],
3830 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3831 "participants" => $cnv["recips"],
3835 $type = "conversation";
3838 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
3842 * Split a name into first name and last name
3844 * @param string $name The name
3846 * @return array The array with "first" and "last"
3848 public static function splitName($name) {
3849 $name = trim($name);
3851 // Is the name longer than 64 characters? Then cut the rest of it.
3852 if (strlen($name) > 64) {
3853 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3854 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3856 $name = substr($name, 0, 64);
3860 // Take the first word as first name
3861 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3862 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3863 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3864 return ['first' => $first, 'last' => $last];
3867 // Take the last word as last name
3868 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3869 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3871 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3872 return ['first' => $first, 'last' => $last];
3875 // Take the first 32 characters if there is no space in the first 32 characters
3876 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3877 $first = substr($name, 0, 32);
3878 $last = substr($name, 32);
3879 return ['first' => $first, 'last' => $last];
3882 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3883 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3885 // Check if the last name is longer than 32 characters
3886 if (strlen($last) > 32) {
3887 if (strpos($last, ' ') <= 32) {
3888 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
3890 $last = substr($last, 0, 32);
3894 return ['first' => $first, 'last' => $last];
3898 * Create profile data
3900 * @param int $uid The user id
3902 * @return array The profile data
3903 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3905 private static function createProfileData($uid)
3907 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
3908 if (!DBA::isResult($profile)) {
3912 $handle = $profile["addr"];
3914 $split_name = self::splitName($profile['name']);
3915 $first = $split_name['first'];
3916 $last = $split_name['last'];
3918 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3919 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3920 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3921 $searchable = ($profile['net-publish'] ? 'true' : 'false');
3927 if ($searchable === 'true') {
3930 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
3931 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
3935 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
3938 $about = BBCode::toMarkdown($profile['about']);
3940 $location = $profile['location'];
3942 if ($profile['pub_keywords']) {
3943 $kw = str_replace(',', ' ', $profile['pub_keywords']);
3944 $kw = str_replace(' ', ' ', $kw);
3945 $arr = explode(' ', $kw);
3947 for ($x = 0; $x < 5; $x ++) {
3948 if (!empty($arr[$x])) {
3949 $tags .= '#'. trim($arr[$x]) .' ';
3954 $tags = trim($tags);
3957 return ["author" => $handle,
3958 "first_name" => $first,
3959 "last_name" => $last,
3960 "image_url" => $large,
3961 "image_url_medium" => $medium,
3962 "image_url_small" => $small,
3965 "location" => $location,
3966 "searchable" => $searchable,
3968 "tag_string" => $tags];
3972 * Sends profile data
3974 * @param int $uid The user id
3975 * @param bool $recips optional, default false
3977 * @throws \Exception
3979 public static function sendProfile($uid, $recips = false)
3985 $owner = User::getOwnerDataById($uid);
3992 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3993 AND `uid` = %d AND `rel` != %d",
3994 DBA::escape(Protocol::DIASPORA),
3996 intval(Contact::SHARING)
4004 $message = self::createProfileData($uid);
4006 // @ToDo Split this into single worker jobs
4007 foreach ($recips as $recip) {
4008 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4009 self::buildAndTransmit($owner, $recip, "profile", $message);
4014 * Creates the signature for likes that are created on our system
4016 * @param integer $uid The user of that comment
4017 * @param array $item Item array
4019 * @return array Signed content
4020 * @throws \Exception
4022 public static function createLikeSignature($uid, array $item)
4024 $owner = User::getOwnerDataById($uid);
4025 if (empty($owner)) {
4026 Logger::info('No owner post, so not storing signature');
4030 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4034 $message = self::constructLike($item, $owner);
4035 if ($message === false) {
4039 $message["author_signature"] = self::signature($owner, $message);
4045 * Creates the signature for Comments that are created on our system
4047 * @param integer $uid The user of that comment
4048 * @param array $item Item array
4050 * @return array Signed content
4051 * @throws \Exception
4053 public static function createCommentSignature($uid, array $item)
4055 $owner = User::getOwnerDataById($uid);
4056 if (empty($owner)) {
4057 Logger::info('No owner post, so not storing signature');
4061 $parent = Post::selectFirst(['parent-uri'], ['uri' => $item['thr-parent']]);
4062 if (!DBA::isResult($parent)) {
4066 $item['parent-uri'] = $parent['parent-uri'];
4068 $message = self::constructComment($item, $owner);
4069 if ($message === false) {
4073 $message["author_signature"] = self::signature($owner, $message);