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\Item;
39 use Friendica\Model\ItemURI;
40 use Friendica\Model\Mail;
41 use Friendica\Model\Post;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Network\Probe;
45 use Friendica\Util\Crypto;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\Map;
48 use Friendica\Util\Network;
49 use Friendica\Util\Strings;
50 use Friendica\Util\XML;
51 use Friendica\Worker\Delivery;
55 * This class contain functions to create and send Diaspora XML files
60 * Return a list of participating contacts for a thread
62 * This is used for the participation feature.
63 * One of the parameters is a contact array.
64 * This is done to avoid duplicates.
66 * @param array $item Item that is about to be delivered
67 * @param array $contacts The previously fetched contacts
69 * @return array of relay servers
72 public static function participantsForThread(array $item, array $contacts)
74 if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
75 Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]);
79 $items = Item::select(['author-id', 'author-link', 'parent-author-link', 'parent-guid', 'guid'],
80 ['parent' => $item['parent'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
81 while ($item = DBA::fetch($items)) {
82 $contact = DBA::selectFirst('contact', ['id', 'url', 'name', 'protocol', 'batch', 'network'],
83 ['id' => $item['author-id']]);
84 if (!DBA::isResult($contact) || empty($contact['batch']) ||
85 ($contact['network'] != Protocol::DIASPORA) ||
86 Strings::compareLink($item['parent-author-link'], $item['author-link'])) {
91 foreach ($contacts as $entry) {
92 if ($entry['batch'] == $contact['batch']) {
98 Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]);
99 $contacts[] = $contact;
108 * verify the envelope and return the verified data
110 * @param string $envelope The magic envelope
112 * @return string verified data
113 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
114 * @throws \ImagickException
116 private static function verifyMagicEnvelope($envelope)
118 $basedom = XML::parseString($envelope, true);
120 if (!is_object($basedom)) {
121 Logger::log("Envelope is no XML file");
125 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
127 if (sizeof($children) == 0) {
128 Logger::log("XML has no children");
134 $data = Strings::base64UrlDecode($children->data);
135 $type = $children->data->attributes()->type[0];
137 $encoding = $children->encoding;
139 $alg = $children->alg;
141 $sig = Strings::base64UrlDecode($children->sig);
142 $key_id = $children->sig->attributes()->key_id[0];
144 $handle = Strings::base64UrlDecode($key_id);
147 $b64url_data = Strings::base64UrlEncode($data);
148 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
150 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
153 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
157 $key = self::key($handle);
159 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
163 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
165 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
173 * encrypts data via AES
175 * @param string $key The AES key
176 * @param string $iv The IV (is used for CBC encoding)
177 * @param string $data The data that is to be encrypted
179 * @return string encrypted data
181 private static function aesEncrypt($key, $iv, $data)
183 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
187 * decrypts data via AES
189 * @param string $key The AES key
190 * @param string $iv The IV (is used for CBC encoding)
191 * @param string $encrypted The encrypted data
193 * @return string decrypted data
195 private static function aesDecrypt($key, $iv, $encrypted)
197 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
201 * Decodes incoming Diaspora message in the new format
203 * @param string $raw raw post message
204 * @param string $privKey The private key of the importer
205 * @param boolean $no_exit Don't do an http exit on error
208 * 'message' -> decoded Diaspora XML message
209 * 'author' -> author diaspora handle
210 * 'key' -> author public key (converted to pkcs#8)
211 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
212 * @throws \ImagickException
214 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
216 $data = json_decode($raw);
218 // Is it a private post? Then decrypt the outer Salmon
219 if (is_object($data)) {
220 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
221 $ciphertext = base64_decode($data->encrypted_magic_envelope);
223 $outer_key_bundle = '';
224 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
225 $j_outer_key_bundle = json_decode($outer_key_bundle);
227 if (!is_object($j_outer_key_bundle)) {
228 Logger::log('Outer Salmon did not verify. Discarding.');
232 throw new \Friendica\Network\HTTPException\BadRequestException();
236 $outer_iv = base64_decode($j_outer_key_bundle->iv);
237 $outer_key = base64_decode($j_outer_key_bundle->key);
239 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
244 $basedom = XML::parseString($xml, true);
246 if (!is_object($basedom)) {
247 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
251 throw new \Friendica\Network\HTTPException\BadRequestException();
255 $base = $basedom->children(ActivityNamespace::SALMON_ME);
257 // Not sure if this cleaning is needed
258 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
260 // Build the signed data
261 $type = $base->data[0]->attributes()->type[0];
262 $encoding = $base->encoding;
264 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
266 // This is the signature
267 $signature = Strings::base64UrlDecode($base->sig);
269 // Get the senders' public key
270 $key_id = $base->sig[0]->attributes()->key_id[0];
271 $author_addr = base64_decode($key_id);
272 if ($author_addr == '') {
273 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
277 throw new \Friendica\Network\HTTPException\BadRequestException();
281 $key = self::key($author_addr);
283 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
287 throw new \Friendica\Network\HTTPException\BadRequestException();
291 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
293 Logger::log('Message did not verify. Discarding.');
297 throw new \Friendica\Network\HTTPException\BadRequestException();
301 return ['message' => (string)Strings::base64UrlDecode($base->data),
302 'author' => XML::unescape($author_addr),
303 'key' => (string)$key];
307 * Decodes incoming Diaspora message in the deprecated format
309 * @param string $xml urldecoded Diaspora salmon
310 * @param string $privKey The private key of the importer
313 * 'message' -> decoded Diaspora XML message
314 * 'author' -> author diaspora handle
315 * 'key' -> author public key (converted to pkcs#8)
316 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
317 * @throws \ImagickException
319 public static function decode(string $xml, string $privKey = '')
322 $basedom = XML::parseString($xml);
324 if (!is_object($basedom)) {
325 Logger::notice('XML is not parseable.');
328 $children = $basedom->children('https://joindiaspora.com/protocol');
330 $inner_aes_key = null;
333 if ($children->header) {
335 $author_link = str_replace('acct:', '', $children->header->author_id);
337 // This happens with posts from a relais
338 if (empty($privKey)) {
339 Logger::info('This is no private post in the old format');
343 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
345 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
346 $ciphertext = base64_decode($encrypted_header->ciphertext);
348 $outer_key_bundle = '';
349 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
351 $j_outer_key_bundle = json_decode($outer_key_bundle);
353 $outer_iv = base64_decode($j_outer_key_bundle->iv);
354 $outer_key = base64_decode($j_outer_key_bundle->key);
356 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
358 Logger::info('decrypted', ['data' => $decrypted]);
359 $idom = XML::parseString($decrypted);
361 $inner_iv = base64_decode($idom->iv);
362 $inner_aes_key = base64_decode($idom->aes_key);
364 $author_link = str_replace('acct:', '', $idom->author_id);
367 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
369 // figure out where in the DOM tree our data is hiding
372 if ($dom->provenance->data) {
373 $base = $dom->provenance;
374 } elseif ($dom->env->data) {
376 } elseif ($dom->data) {
381 Logger::log('unable to locate salmon data in xml');
382 throw new \Friendica\Network\HTTPException\BadRequestException();
386 // Stash the signature away for now. We have to find their key or it won't be good for anything.
387 $signature = Strings::base64UrlDecode($base->sig);
391 // strip whitespace so our data element will return to one big base64 blob
392 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
395 // stash away some other stuff for later
397 $type = $base->data[0]->attributes()->type[0];
398 $keyhash = $base->sig[0]->attributes()->keyhash[0];
399 $encoding = $base->encoding;
403 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
407 $data = Strings::base64UrlDecode($data);
411 $inner_decrypted = $data;
413 // Decode the encrypted blob
414 $inner_encrypted = base64_decode($data);
415 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
419 Logger::log('Could not retrieve author URI.');
420 throw new \Friendica\Network\HTTPException\BadRequestException();
422 // Once we have the author URI, go to the web and try to find their public key
423 // (first this will look it up locally if it is in the fcontact cache)
424 // This will also convert diaspora public key from pkcs#1 to pkcs#8
426 Logger::log('Fetching key for '.$author_link);
427 $key = self::key($author_link);
430 Logger::log('Could not retrieve author key.');
431 throw new \Friendica\Network\HTTPException\BadRequestException();
434 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
437 Logger::log('Message did not verify. Discarding.');
438 throw new \Friendica\Network\HTTPException\BadRequestException();
441 Logger::log('Message verified.');
443 return ['message' => (string)$inner_decrypted,
444 'author' => XML::unescape($author_link),
445 'key' => (string)$key];
450 * Dispatches public messages and find the fitting receivers
452 * @param array $msg The post that will be dispatched
453 * @param bool $fetched The message had been fetched (default "false")
455 * @return int The message id of the generated message, "true" or "false" if there was an error
456 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
457 * @throws \ImagickException
459 public static function dispatchPublic($msg, bool $fetched = false)
461 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
463 Logger::log("diaspora is disabled");
467 if (!($fields = self::validPosting($msg))) {
468 Logger::log("Invalid posting");
472 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
473 $success = self::dispatch($importer, $msg, $fields, $fetched);
479 * Dispatches the different message types to the different functions
481 * @param array $importer Array of the importer user
482 * @param array $msg The post that will be dispatched
483 * @param SimpleXMLElement $fields SimpleXML object that contains the message
484 * @param bool $fetched The message had been fetched (default "false")
486 * @return int The message id of the generated message, "true" or "false" if there was an error
487 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
488 * @throws \ImagickException
490 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null, bool $fetched = false)
492 // The sender is the handle of the contact that sent the message.
493 // This will often be different with relayed messages (for example "like" and "comment")
494 $sender = $msg["author"];
496 // This is only needed for private postings since this is already done for public ones before
497 if (is_null($fields)) {
499 if (!($fields = self::validPosting($msg))) {
500 Logger::log("Invalid posting");
507 $type = $fields->getName();
509 Logger::info('Received message', ['type' => $type, 'sender' => $sender, 'user' => $importer["uid"]]);
512 case "account_migration":
514 Logger::log('Message with type ' . $type . ' is not private, quitting.');
517 return self::receiveAccountMigration($importer, $fields);
519 case "account_deletion":
520 return self::receiveAccountDeletion($fields);
523 return self::receiveComment($importer, $sender, $fields, $msg["message"], $fetched);
527 Logger::log('Message with type ' . $type . ' is not private, quitting.');
530 return self::receiveContactRequest($importer, $fields);
534 Logger::log('Message with type ' . $type . ' is not private, quitting.');
537 return self::receiveConversation($importer, $msg, $fields);
540 return self::receiveLike($importer, $sender, $fields);
544 Logger::log('Message with type ' . $type . ' is not private, quitting.');
547 return self::receiveMessage($importer, $fields);
549 case "participation":
551 Logger::log('Message with type ' . $type . ' is not private, quitting.');
554 return self::receiveParticipation($importer, $fields);
556 case "photo": // Not implemented
557 return self::receivePhoto($importer, $fields);
559 case "poll_participation": // Not implemented
560 return self::receivePollParticipation($importer, $fields);
564 Logger::log('Message with type ' . $type . ' is not private, quitting.');
567 return self::receiveProfile($importer, $fields);
570 return self::receiveReshare($importer, $fields, $msg["message"]);
573 return self::receiveRetraction($importer, $sender, $fields);
575 case "status_message":
576 return self::receiveStatusMessage($importer, $fields, $msg["message"], $fetched);
579 Logger::log("Unknown message type ".$type);
585 * Checks if a posting is valid and fetches the data fields.
587 * This function does not only check the signature.
588 * It also does the conversion between the old and the new diaspora format.
590 * @param array $msg Array with the XML, the sender handle and the sender signature
592 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
593 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
594 * @throws \ImagickException
596 private static function validPosting($msg)
598 $data = XML::parseString($msg["message"]);
600 if (!is_object($data)) {
601 Logger::info('No valid XML', ['message' => $msg['message']]);
605 // Is this the new or the old version?
606 if ($data->getName() == "XML") {
608 foreach ($data->post->children() as $child) {
616 $type = $element->getName();
619 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
621 // All retractions are handled identically from now on.
622 // In the new version there will only be "retraction".
623 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
624 $type = "retraction";
626 if ($type == "request") {
630 $fields = new SimpleXMLElement("<".$type."/>");
633 $author_signature = null;
634 $parent_author_signature = null;
636 foreach ($element->children() as $fieldname => $entry) {
638 // Translation for the old XML structure
639 if ($fieldname == "diaspora_handle") {
640 $fieldname = "author";
642 if ($fieldname == "participant_handles") {
643 $fieldname = "participants";
645 if (in_array($type, ["like", "participation"])) {
646 if ($fieldname == "target_type") {
647 $fieldname = "parent_type";
650 if ($fieldname == "sender_handle") {
651 $fieldname = "author";
653 if ($fieldname == "recipient_handle") {
654 $fieldname = "recipient";
656 if ($fieldname == "root_diaspora_id") {
657 $fieldname = "root_author";
659 if ($type == "status_message") {
660 if ($fieldname == "raw_message") {
664 if ($type == "retraction") {
665 if ($fieldname == "post_guid") {
666 $fieldname = "target_guid";
668 if ($fieldname == "type") {
669 $fieldname = "target_type";
674 if (($fieldname == "author_signature") && ($entry != "")) {
675 $author_signature = base64_decode($entry);
676 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
677 $parent_author_signature = base64_decode($entry);
678 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
679 if ($signed_data != "") {
683 $signed_data .= $entry;
685 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
686 || ($orig_type == "relayable_retraction")
688 XML::copy($entry, $fields, $fieldname);
692 // This is something that shouldn't happen at all.
693 if (in_array($type, ["status_message", "reshare", "profile"])) {
694 if ($msg["author"] != $fields->author) {
695 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
700 // Only some message types have signatures. So we quit here for the other types.
701 if (!in_array($type, ["comment", "like"])) {
704 // No author_signature? This is a must, so we quit.
705 if (!isset($author_signature)) {
706 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
710 if (isset($parent_author_signature)) {
711 $key = self::key($msg["author"]);
713 Logger::info('No key found for parent', ['author' => $msg["author"]]);
717 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
718 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);
723 $key = self::key($fields->author);
725 Logger::info('No key found', ['author' => $fields->author]);
729 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
730 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);
738 * Fetches the public key for a given handle
740 * @param string $handle The handle
742 * @return string The public key
743 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
744 * @throws \ImagickException
746 private static function key($handle)
748 $handle = strval($handle);
750 Logger::log("Fetching diaspora key for: ".$handle);
752 $r = FContact::getByURL($handle);
761 * get a handle (user@domain.tld) from a given contact id
763 * @param int $contact_id The id in the contact table
764 * @param int $pcontact_id The id in the contact table (Used for the public contact)
766 * @return string the handle
769 private static function handleFromContact($contact_id, $pcontact_id = 0)
773 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
775 if ($pcontact_id != 0) {
776 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
778 if (DBA::isResult($contact) && !empty($contact["addr"])) {
779 return strtolower($contact["addr"]);
784 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
788 if (DBA::isResult($r)) {
791 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
793 if ($contact['addr'] != "") {
794 $handle = $contact['addr'];
796 $baseurl_start = strpos($contact['url'], '://') + 3;
797 // allows installations in a subdirectory--not sure how Diaspora will handle
798 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
799 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
800 $handle = $contact['nick'].'@'.$baseurl;
804 return strtolower($handle);
808 * Get a contact id for a given handle
810 * @todo Move to Friendica\Model\Contact
812 * @param int $uid The user id
813 * @param string $handle The handle in the format user@domain.tld
815 * @return array Contact data
816 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
817 * @throws \ImagickException
819 private static function contactByHandle($uid, $handle)
821 return Contact::getByURL($handle, null, [], $uid);
825 * Checks if the given contact url does support ActivityPub
827 * @param string $url profile url
828 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
830 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
831 * @throws \ImagickException
833 public static function isSupportedByContactUrl($url, $update = null)
835 return !empty(FContact::getByURL($url, $update));
839 * Check if posting is allowed for this contact
841 * @param array $importer Array of the importer user
842 * @param array $contact The contact that is checked
843 * @param bool $is_comment Is the check for a comment?
845 * @return bool is the contact allowed to post?
847 private static function postAllow(array $importer, array $contact, $is_comment = false)
850 * Perhaps we were already sharing with this person. Now they're sharing with us.
851 * That makes us friends.
852 * Normally this should have handled by getting a request - but this could get lost
854 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
855 // It is not removed by now. Possibly the code is needed?
856 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
859 // array('rel' => Contact::FRIEND, 'writable' => true),
860 // array('id' => $contact["id"], 'uid' => $contact["uid"])
863 // $contact["rel"] = Contact::FRIEND;
864 // Logger::log("defining user ".$contact["nick"]." as friend");
867 // Contact server is blocked
868 if (Network::isUrlBlocked($contact['url'])) {
870 // We don't seem to like that person
871 } elseif ($contact["blocked"]) {
872 // Maybe blocked, don't accept.
874 // We are following this person?
875 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
876 // Yes, then it is fine.
878 // Is it a post to a community?
879 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
882 // Is the message a global user or a comment?
883 } elseif (($importer["uid"] == 0) || $is_comment) {
884 // Messages for the global users and comments are always accepted
892 * Fetches the contact id for a handle and checks if posting is allowed
894 * @param array $importer Array of the importer user
895 * @param string $handle The checked handle in the format user@domain.tld
896 * @param bool $is_comment Is the check for a comment?
898 * @return array The contact data
901 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
903 $contact = self::contactByHandle($importer["uid"], $handle);
905 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
906 // If a contact isn't found, we accept it anyway if it is a comment
907 if ($is_comment && ($importer["uid"] != 0)) {
908 return self::contactByHandle(0, $handle);
909 } elseif ($is_comment) {
916 if (!self::postAllow($importer, $contact, $is_comment)) {
917 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
924 * Does the message already exists on the system?
926 * @param int $uid The user id
927 * @param string $guid The guid of the message
929 * @return int|bool message id if the message already was stored into the system - or false.
932 private static function messageExists($uid, $guid)
934 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
935 if (DBA::isResult($item)) {
936 Logger::log("message ".$guid." already exists for user ".$uid);
944 * Checks for links to posts in a message
946 * @param array $item The item array
949 private static function fetchGuid(array $item)
951 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
952 preg_replace_callback(
954 function ($match) use ($item) {
955 self::fetchGuidSub($match, $item);
960 preg_replace_callback(
961 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
962 function ($match) use ($item) {
963 self::fetchGuidSub($match, $item);
970 * Checks for relative /people/* links in an item body to match local
971 * contacts or prepends the remote host taken from the author link.
973 * @param string $body The item body to replace links from
974 * @param string $author_link The author link for missing local contact fallback
976 * @return string the replaced string
978 public static function replacePeopleGuid($body, $author_link)
980 $return = preg_replace_callback(
981 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
982 function ($match) use ($author_link) {
984 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
985 // 1 => '0123456789abcdef'
987 $handle = FContact::getUrlByGuid($match[1]);
990 $return = '@[url='.$handle.']'.$match[2].'[/url]';
992 // No local match, restoring absolute remote URL from author scheme and host
993 $author_url = parse_url($author_link);
994 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1006 * sub function of "fetchGuid" which checks for links in messages
1008 * @param array $match array containing a link that has to be checked for a message link
1009 * @param array $item The item array
1011 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1012 * @throws \ImagickException
1014 private static function fetchGuidSub($match, $item)
1016 if (!self::storeByGuid($match[1], $item["author-link"])) {
1017 self::storeByGuid($match[1], $item["owner-link"]);
1022 * Fetches an item with a given guid from a given server
1024 * @param string $guid the message guid
1025 * @param string $server The server address
1026 * @param int $uid The user id of the user
1028 * @return int the message id of the stored message or false
1029 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1030 * @throws \ImagickException
1032 private static function storeByGuid($guid, $server, $uid = 0)
1034 $serverparts = parse_url($server);
1036 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1040 $server = $serverparts["scheme"]."://".$serverparts["host"];
1042 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1044 $msg = self::message($guid, $server);
1050 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1052 // Now call the dispatcher
1053 return self::dispatchPublic($msg, true);
1057 * Fetches a message from a server
1059 * @param string $guid message guid
1060 * @param string $server The url of the server
1061 * @param int $level Endless loop prevention
1064 * 'message' => The message XML
1065 * 'author' => The author handle
1066 * 'key' => The public key of the author
1067 * @throws \Exception
1069 private static function message($guid, $server, $level = 0)
1075 // This will work for new Diaspora servers and Friendica servers from 3.5
1076 $source_url = $server."/fetch/post/".urlencode($guid);
1078 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1080 $envelope = DI::httpRequest()->fetch($source_url);
1082 Logger::log("Envelope was fetched.", Logger::DEBUG);
1083 $x = self::verifyMagicEnvelope($envelope);
1085 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1087 Logger::log("Envelope was verified.", Logger::DEBUG);
1097 $source_xml = XML::parseString($x);
1099 if (!is_object($source_xml)) {
1103 if ($source_xml->post->reshare) {
1104 // Reshare of a reshare - old Diaspora version
1105 Logger::log("Message is a reshare", Logger::DEBUG);
1106 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1107 } elseif ($source_xml->getName() == "reshare") {
1108 // Reshare of a reshare - new Diaspora version
1109 Logger::log("Message is a new reshare", Logger::DEBUG);
1110 return self::message($source_xml->root_guid, $server, ++$level);
1115 // Fetch the author - for the old and the new Diaspora version
1116 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1117 $author = (string)$source_xml->post->status_message->diaspora_handle;
1118 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1119 $author = (string)$source_xml->author;
1122 // If this isn't a "status_message" then quit
1124 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1128 $msg = ["message" => $x, "author" => $author];
1130 $msg["key"] = self::key($msg["author"]);
1136 * Fetches an item with a given URL
1138 * @param string $url the message url
1140 * @return int the message id of the stored message or false
1141 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1142 * @throws \ImagickException
1144 public static function fetchByURL($url, $uid = 0)
1146 // Check for Diaspora (and Friendica) typical paths
1147 if (!preg_match("=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1148 Logger::info('Invalid url', ['url' => $url]);
1152 $guid = urldecode($matches[2]);
1154 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1155 if (DBA::isResult($item)) {
1156 Logger::info('Found', ['id' => $item['id']]);
1160 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1161 $ret = self::storeByGuid($guid, $matches[1], $uid);
1162 Logger::info('Result', ['ret' => $ret]);
1164 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1165 if (DBA::isResult($item)) {
1166 Logger::info('Found', ['id' => $item['id']]);
1169 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1175 * Fetches the item record of a given guid
1177 * @param int $uid The user id
1178 * @param string $guid message guid
1179 * @param string $author The handle of the item
1180 * @param array $contact The contact of the item owner
1182 * @return array the item record
1183 * @throws \Exception
1185 private static function parentItem($uid, $guid, $author, array $contact)
1187 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1188 'author-name', 'author-link', 'author-avatar', 'gravity',
1189 'owner-name', 'owner-link', 'owner-avatar'];
1190 $condition = ['uid' => $uid, 'guid' => $guid];
1191 $item = Item::selectFirst($fields, $condition);
1193 if (!DBA::isResult($item)) {
1194 $person = FContact::getByURL($author);
1195 $result = self::storeByGuid($guid, $person["url"], $uid);
1197 // We don't have an url for items that arrived at the public dispatcher
1198 if (!$result && !empty($contact["url"])) {
1199 $result = self::storeByGuid($guid, $contact["url"], $uid);
1203 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1205 $item = Item::selectFirst($fields, $condition);
1209 if (!DBA::isResult($item)) {
1210 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1213 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1219 * returns contact details
1221 * @param array $def_contact The default contact if the person isn't found
1222 * @param array $person The record of the person
1223 * @param int $uid The user id
1226 * 'cid' => contact id
1227 * 'network' => network type
1228 * @throws \Exception
1230 private static function authorContactByUrl($def_contact, $person, $uid)
1232 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1233 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1234 if (DBA::isResult($contact)) {
1235 $cid = $contact["id"];
1236 $network = $contact["network"];
1238 $cid = $def_contact["id"];
1239 $network = Protocol::DIASPORA;
1242 return ["cid" => $cid, "network" => $network];
1246 * Is the profile a hubzilla profile?
1248 * @param string $url The profile link
1250 * @return bool is it a hubzilla server?
1252 private static function isHubzilla($url)
1254 return(strstr($url, '/channel/'));
1258 * Generate a post link with a given handle and message guid
1260 * @param string $addr The user handle
1261 * @param string $guid message guid
1262 * @param string $parent_guid optional parent guid
1264 * @return string the post link
1265 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1266 * @throws \ImagickException
1268 private static function plink($addr, $guid, $parent_guid = '')
1270 $contact = Contact::getByURL($addr);
1271 if (empty($contact)) {
1272 Logger::info('No contact data for address', ['addr' => $addr]);
1276 if (empty($contact['baseurl'])) {
1277 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1278 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1282 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1283 if (!empty($gserver['platform'])) {
1284 $platform = strtolower($gserver['platform']);
1285 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1288 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1289 if (self::isHubzilla($contact['url'])) {
1290 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1291 $platform = 'hubzilla';
1292 } elseif ($contact['network'] == Protocol::DFRN) {
1293 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1294 $platform = 'friendica';
1298 if ($platform == 'friendica') {
1299 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1302 if ($platform == 'hubzilla') {
1303 return $contact['baseurl'] . '/item/' . $guid;
1306 if ($platform == 'socialhome') {
1307 return $contact['baseurl'] . '/content/' . $guid;
1310 if ($platform != 'diaspora') {
1311 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1315 if ($parent_guid != '') {
1316 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1318 return $contact['baseurl'] . '/posts/' . $guid;
1323 * Receives account migration
1325 * @param array $importer Array of the importer user
1326 * @param object $data The message object
1328 * @return bool Success
1329 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1330 * @throws \ImagickException
1332 private static function receiveAccountMigration(array $importer, $data)
1334 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1335 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1336 $signature = Strings::escapeTags(XML::unescape($data->signature));
1338 $contact = self::contactByHandle($importer["uid"], $old_handle);
1340 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1344 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1347 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1348 $key = self::key($old_handle);
1349 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1350 Logger::log('No valid signature for migration.');
1354 // Update the profile
1355 self::receiveProfile($importer, $data->profile);
1357 // change the technical stuff in contact
1358 $data = Probe::uri($new_handle);
1359 if ($data['network'] == Protocol::PHANTOM) {
1360 Logger::log('Account for '.$new_handle." couldn't be probed.");
1364 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1365 'name' => $data['name'], 'nick' => $data['nick'],
1366 'addr' => $data['addr'], 'batch' => $data['batch'],
1367 'notify' => $data['notify'], 'poll' => $data['poll'],
1368 'network' => $data['network']];
1370 DBA::update('contact', $fields, ['addr' => $old_handle]);
1372 Logger::log('Contacts are updated.');
1378 * Processes an account deletion
1380 * @param object $data The message object
1382 * @return bool Success
1383 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1385 private static function receiveAccountDeletion($data)
1387 $author = Strings::escapeTags(XML::unescape($data->author));
1389 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1390 while ($contact = DBA::fetch($contacts)) {
1391 Contact::remove($contact["id"]);
1393 DBA::close($contacts);
1395 Logger::log('Removed contacts for ' . $author);
1401 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1403 * @param string $author Author handle
1404 * @param string $guid Message guid
1405 * @param boolean $onlyfound Only return uri when found in the database
1407 * @return string The constructed uri or the one from our database
1408 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1409 * @throws \ImagickException
1411 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1413 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1414 if (DBA::isResult($item)) {
1415 return $item["uri"];
1416 } elseif (!$onlyfound) {
1417 $person = FContact::getByURL($author);
1419 $parts = parse_url($person['url']);
1420 unset($parts['path']);
1421 $host_url = Network::unparseURL($parts);
1423 return $host_url . '/objects/' . $guid;
1430 * Fetch the guid from our database with a given uri
1432 * @param string $uri Message uri
1433 * @param string $uid Author handle
1435 * @return string The post guid
1436 * @throws \Exception
1438 private static function getGuidFromUri($uri, $uid)
1440 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1441 if (DBA::isResult($item)) {
1442 return $item["guid"];
1449 * Store the mentions in the tag table
1451 * @param integer $uriid
1452 * @param string $text
1454 private static function storeMentions(int $uriid, string $text)
1456 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1457 if (empty($matches)) {
1462 * Matching values for the preg match
1463 * [1] = mention type (@ or !)
1464 * [2] = name (optional)
1468 foreach ($matches as $match) {
1469 if (empty($match)) {
1473 $person = FContact::getByURL($match[3]);
1474 if (empty($person)) {
1478 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1483 * Processes an incoming comment
1485 * @param array $importer Array of the importer user
1486 * @param string $sender The sender of the message
1487 * @param object $data The message object
1488 * @param string $xml The original XML of the message
1489 * @param bool $fetched The message had been fetched and not pushed
1491 * @return int The message id of the generated comment or "false" if there was an error
1492 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1493 * @throws \ImagickException
1495 private static function receiveComment(array $importer, $sender, $data, $xml, bool $fetched)
1497 $author = Strings::escapeTags(XML::unescape($data->author));
1498 $guid = Strings::escapeTags(XML::unescape($data->guid));
1499 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1500 $text = XML::unescape($data->text);
1502 if (isset($data->created_at)) {
1503 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1505 $created_at = DateTimeFormat::utcNow();
1508 if (isset($data->thread_parent_guid)) {
1509 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1510 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1515 $contact = self::allowedContactByHandle($importer, $sender, true);
1520 $message_id = self::messageExists($importer["uid"], $guid);
1525 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1526 if (!$parent_item) {
1530 $person = FContact::getByURL($author);
1531 if (!is_array($person)) {
1532 Logger::log("unable to find author details");
1536 // Fetch the contact id - if we know this contact
1537 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1541 $datarray["uid"] = $importer["uid"];
1542 $datarray["contact-id"] = $author_contact["cid"];
1543 $datarray["network"] = $author_contact["network"];
1545 $datarray["author-link"] = $person["url"];
1546 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1548 $datarray["owner-link"] = $contact["url"];
1549 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1551 // Will be overwritten for sharing accounts in Item::insert
1553 $datarray["post-type"] = Item::PT_FETCHED;
1554 } elseif ($datarray["uid"] == 0) {
1555 $datarray["post-type"] = Item::PT_GLOBAL;
1557 $datarray["post-type"] = Item::PT_COMMENT;
1560 $datarray["guid"] = $guid;
1561 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1562 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1564 $datarray["verb"] = Activity::POST;
1565 $datarray["gravity"] = GRAVITY_COMMENT;
1567 if ($thr_uri != "") {
1568 $datarray["parent-uri"] = $thr_uri;
1570 $datarray["parent-uri"] = $parent_item["uri"];
1573 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1575 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1576 $datarray["source"] = $xml;
1578 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1580 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1581 $body = Markdown::toBBCode($text);
1583 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1585 self::storeMentions($datarray['uri-id'], $text);
1586 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
1588 self::fetchGuid($datarray);
1590 // If we are the origin of the parent we store the original data.
1591 // We notify our followers during the item storage.
1592 if ($parent_item["origin"]) {
1593 $datarray['diaspora_signed_text'] = json_encode($data);
1596 $message_id = Item::insert($datarray);
1598 if ($message_id <= 0) {
1603 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1604 if ($datarray['uid'] == 0) {
1605 Item::distribute($message_id, json_encode($data));
1613 * processes and stores private messages
1615 * @param array $importer Array of the importer user
1616 * @param array $contact The contact of the message
1617 * @param object $data The message object
1618 * @param array $msg Array of the processed message, author handle and key
1619 * @param object $mesg The private message
1620 * @param array $conversation The conversation record to which this message belongs
1622 * @return bool "true" if it was successful
1623 * @throws \Exception
1625 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1627 $author = Strings::escapeTags(XML::unescape($data->author));
1628 $guid = Strings::escapeTags(XML::unescape($data->guid));
1629 $subject = Strings::escapeTags(XML::unescape($data->subject));
1631 // "diaspora_handle" is the element name from the old version
1632 // "author" is the element name from the new version
1633 if ($mesg->author) {
1634 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1635 } elseif ($mesg->diaspora_handle) {
1636 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1641 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1642 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1643 $msg_text = XML::unescape($mesg->text);
1644 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1646 if ($msg_conversation_guid != $guid) {
1647 Logger::log("message conversation guid does not belong to the current conversation.");
1651 $body = Markdown::toBBCode($msg_text);
1652 $message_uri = $msg_author.":".$msg_guid;
1654 $person = FContact::getByURL($msg_author);
1656 return Mail::insert([
1657 'uid' => $importer['uid'],
1658 'guid' => $msg_guid,
1659 'convid' => $conversation['id'],
1660 'from-name' => $person['name'],
1661 'from-photo' => $person['photo'],
1662 'from-url' => $person['url'],
1663 'contact-id' => $contact['id'],
1664 'title' => $subject,
1666 'uri' => $message_uri,
1667 'parent-uri' => $author . ':' . $guid,
1668 'created' => $msg_created_at
1673 * Processes new private messages (answers to private messages are processed elsewhere)
1675 * @param array $importer Array of the importer user
1676 * @param array $msg Array of the processed message, author handle and key
1677 * @param object $data The message object
1679 * @return bool Success
1680 * @throws \Exception
1682 private static function receiveConversation(array $importer, $msg, $data)
1684 $author = Strings::escapeTags(XML::unescape($data->author));
1685 $guid = Strings::escapeTags(XML::unescape($data->guid));
1686 $subject = Strings::escapeTags(XML::unescape($data->subject));
1687 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1688 $participants = Strings::escapeTags(XML::unescape($data->participants));
1690 $messages = $data->message;
1692 if (!count($messages)) {
1693 Logger::log("empty conversation");
1697 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1702 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1703 if (!DBA::isResult($conversation)) {
1705 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1706 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1707 intval($importer["uid"]),
1709 DBA::escape($author),
1710 DBA::escape($created_at),
1711 DBA::escape(DateTimeFormat::utcNow()),
1712 DBA::escape($subject),
1713 DBA::escape($participants)
1716 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1719 if (!$conversation) {
1720 Logger::log("unable to create conversation.");
1724 foreach ($messages as $mesg) {
1725 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1732 * Processes "like" messages
1734 * @param array $importer Array of the importer user
1735 * @param string $sender The sender of the message
1736 * @param object $data The message object
1738 * @return int The message id of the generated like or "false" if there was an error
1739 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1740 * @throws \ImagickException
1742 private static function receiveLike(array $importer, $sender, $data)
1744 $author = Strings::escapeTags(XML::unescape($data->author));
1745 $guid = Strings::escapeTags(XML::unescape($data->guid));
1746 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1747 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
1748 $positive = Strings::escapeTags(XML::unescape($data->positive));
1750 // likes on comments aren't supported by Diaspora - only on posts
1751 // But maybe this will be supported in the future, so we will accept it.
1752 if (!in_array($parent_type, ["Post", "Comment"])) {
1756 $contact = self::allowedContactByHandle($importer, $sender, true);
1761 $message_id = self::messageExists($importer["uid"], $guid);
1766 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1767 if (!$parent_item) {
1771 $person = FContact::getByURL($author);
1772 if (!is_array($person)) {
1773 Logger::log("unable to find author details");
1777 // Fetch the contact id - if we know this contact
1778 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1780 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1781 // We would accept this anyhow.
1782 if ($positive == "true") {
1783 $verb = Activity::LIKE;
1785 $verb = Activity::DISLIKE;
1790 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1792 $datarray["uid"] = $importer["uid"];
1793 $datarray["contact-id"] = $author_contact["cid"];
1794 $datarray["network"] = $author_contact["network"];
1796 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
1797 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1799 $datarray["guid"] = $guid;
1800 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1802 $datarray["verb"] = $verb;
1803 $datarray["gravity"] = GRAVITY_ACTIVITY;
1804 $datarray["parent-uri"] = $parent_item["uri"];
1806 $datarray["object-type"] = Activity\ObjectType::NOTE;
1808 $datarray["body"] = $verb;
1810 // Diaspora doesn't provide a date for likes
1811 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
1813 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1814 if ($parent_item['gravity'] != GRAVITY_PARENT) {
1815 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item['parent']]);
1816 $origin = $toplevel["origin"];
1818 $origin = $parent_item["origin"];
1821 // If we are the origin of the parent we store the original data.
1822 // We notify our followers during the item storage.
1824 $datarray['diaspora_signed_text'] = json_encode($data);
1827 $message_id = Item::insert($datarray);
1829 if ($message_id <= 0) {
1834 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1835 if ($datarray['uid'] == 0) {
1836 Item::distribute($message_id, json_encode($data));
1844 * Processes private messages
1846 * @param array $importer Array of the importer user
1847 * @param object $data The message object
1849 * @return bool Success?
1850 * @throws \Exception
1852 private static function receiveMessage(array $importer, $data)
1854 $author = Strings::escapeTags(XML::unescape($data->author));
1855 $guid = Strings::escapeTags(XML::unescape($data->guid));
1856 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
1857 $text = XML::unescape($data->text);
1858 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1860 $contact = self::allowedContactByHandle($importer, $author, true);
1865 $conversation = null;
1867 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
1868 $conversation = DBA::selectFirst('conv', [], $condition);
1870 if (!DBA::isResult($conversation)) {
1871 Logger::log("conversation not available.");
1875 $message_uri = $author.":".$guid;
1877 $person = FContact::getByURL($author);
1879 Logger::log("unable to find author details");
1883 $body = Markdown::toBBCode($text);
1885 $body = self::replacePeopleGuid($body, $person["url"]);
1887 return Mail::insert([
1888 'uid' => $importer['uid'],
1890 'convid' => $conversation['id'],
1891 'from-name' => $person['name'],
1892 'from-photo' => $person['photo'],
1893 'from-url' => $person['url'],
1894 'contact-id' => $contact['id'],
1895 'title' => $conversation['subject'],
1898 'uri' => $message_uri,
1899 'parent-uri' => $author.":".$conversation['guid'],
1900 'created' => $created_at
1905 * Processes participations - unsupported by now
1907 * @param array $importer Array of the importer user
1908 * @param object $data The message object
1910 * @return bool success
1911 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1912 * @throws \ImagickException
1914 private static function receiveParticipation(array $importer, $data)
1916 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
1917 $guid = Strings::escapeTags(XML::unescape($data->guid));
1918 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1920 $contact = self::allowedContactByHandle($importer, $author, true);
1925 if (self::messageExists($importer["uid"], $guid)) {
1929 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1930 if (!$parent_item) {
1934 if (!$parent_item['origin']) {
1935 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1938 if (!in_array($parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
1939 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1943 $person = FContact::getByURL($author);
1944 if (!is_array($person)) {
1945 Logger::log("Person not found: ".$author);
1949 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1951 // Store participation
1954 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1956 $datarray["uid"] = $importer["uid"];
1957 $datarray["contact-id"] = $author_contact["cid"];
1958 $datarray["network"] = $author_contact["network"];
1960 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
1961 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1963 $datarray["guid"] = $guid;
1964 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1966 $datarray["verb"] = Activity::FOLLOW;
1967 $datarray["gravity"] = GRAVITY_ACTIVITY;
1968 $datarray["parent-uri"] = $parent_item["uri"];
1970 $datarray["object-type"] = Activity\ObjectType::NOTE;
1972 $datarray["body"] = Activity::FOLLOW;
1974 // Diaspora doesn't provide a date for a participation
1975 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
1977 $message_id = Item::insert($datarray);
1979 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
1981 // Send all existing comments and likes to the requesting server
1982 $comments = Item::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb'],
1983 ['parent' => $parent_item['id'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
1984 while ($comment = Item::fetch($comments)) {
1985 if (in_array($comment['verb'], [Activity::FOLLOW, Activity::TAG])) {
1986 Logger::info('participation messages are not relayed', ['item' => $comment['id']]);
1990 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
1991 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
1995 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
1996 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2000 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact["cid"]]);
2001 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $author_contact["cid"])) {
2002 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2005 DBA::close($comments);
2011 * Processes photos - unneeded
2013 * @param array $importer Array of the importer user
2014 * @param object $data The message object
2016 * @return bool always true
2018 private static function receivePhoto(array $importer, $data)
2020 // There doesn't seem to be a reason for this function,
2021 // since the photo data is transmitted in the status message as well
2026 * Processes poll participations - unssupported
2028 * @param array $importer Array of the importer user
2029 * @param object $data The message object
2031 * @return bool always true
2033 private static function receivePollParticipation(array $importer, $data)
2035 // We don't support polls by now
2040 * Processes incoming profile updates
2042 * @param array $importer Array of the importer user
2043 * @param object $data The message object
2045 * @return bool Success
2046 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2047 * @throws \ImagickException
2049 private static function receiveProfile(array $importer, $data)
2051 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2053 $contact = self::contactByHandle($importer["uid"], $author);
2058 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2059 $image_url = XML::unescape($data->image_url);
2060 $birthday = XML::unescape($data->birthday);
2061 $about = Markdown::toBBCode(XML::unescape($data->bio));
2062 $location = Markdown::toBBCode(XML::unescape($data->location));
2063 $searchable = (XML::unescape($data->searchable) == "true");
2064 $nsfw = (XML::unescape($data->nsfw) == "true");
2065 $tags = XML::unescape($data->tag_string);
2067 $tags = explode("#", $tags);
2070 foreach ($tags as $tag) {
2071 $tag = trim(strtolower($tag));
2077 $keywords = implode(", ", $keywords);
2079 $handle_parts = explode("@", $author);
2080 $nick = $handle_parts[0];
2083 $name = $handle_parts[0];
2086 if (preg_match("|^https?://|", $image_url) === 0) {
2087 $image_url = "http://".$handle_parts[1].$image_url;
2090 Contact::updateAvatar($contact["id"], $image_url);
2092 // Generic birthday. We don't know the timezone. The year is irrelevant.
2094 $birthday = str_replace("1000", "1901", $birthday);
2096 if ($birthday != "") {
2097 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2100 // this is to prevent multiple birthday notifications in a single year
2101 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2103 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2104 $birthday = $contact["bd"];
2107 $fields = ['name' => $name, 'location' => $location,
2108 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2109 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2110 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2112 if (!empty($birthday)) {
2113 $fields['bd'] = $birthday;
2116 DBA::update('contact', $fields, ['id' => $contact['id']]);
2118 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2124 * Processes incoming friend requests
2126 * @param array $importer Array of the importer user
2127 * @param array $contact The contact that send the request
2129 * @throws \Exception
2131 private static function receiveRequestMakeFriend(array $importer, array $contact)
2133 if ($contact["rel"] == Contact::SHARING) {
2136 ['rel' => Contact::FRIEND, 'writable' => true],
2137 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2143 * Processes incoming sharing notification
2145 * @param array $importer Array of the importer user
2146 * @param object $data The message object
2148 * @return bool Success
2149 * @throws \Exception
2151 private static function receiveContactRequest(array $importer, $data)
2153 $author = XML::unescape($data->author);
2154 $recipient = XML::unescape($data->recipient);
2156 if (!$author || !$recipient) {
2160 // the current protocol version doesn't know these fields
2161 // That means that we will assume their existance
2162 if (isset($data->following)) {
2163 $following = (XML::unescape($data->following) == "true");
2168 if (isset($data->sharing)) {
2169 $sharing = (XML::unescape($data->sharing) == "true");
2174 $contact = self::contactByHandle($importer["uid"], $author);
2176 // perhaps we were already sharing with this person. Now they're sharing with us.
2177 // That makes us friends.
2180 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2181 self::receiveRequestMakeFriend($importer, $contact);
2183 // refetch the contact array
2184 $contact = self::contactByHandle($importer["uid"], $author);
2186 // If we are now friends, we are sending a share message.
2187 // Normally we needn't to do so, but the first message could have been vanished.
2188 if (in_array($contact["rel"], [Contact::FRIEND])) {
2189 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2190 if (DBA::isResult($user)) {
2191 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2192 self::sendShare($user, $contact);
2197 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2198 Contact::removeFollower($importer, $contact);
2203 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2204 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2206 } elseif (!$following && !$sharing) {
2207 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2209 } elseif (!$following && $sharing) {
2210 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2211 } elseif ($following && $sharing) {
2212 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2213 } elseif ($following && !$sharing) {
2214 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2217 $ret = FContact::getByURL($author);
2219 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2220 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2224 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2226 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2231 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2232 'author-link' => $ret['url']];
2234 $result = Contact::addRelationship($importer, $contact, $item, false);
2235 if ($result === true) {
2236 $contact_record = self::contactByHandle($importer['uid'], $author);
2237 if (!$contact_record) {
2238 Logger::info('unable to locate newly created contact record.');
2242 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2243 if (DBA::isResult($user)) {
2244 self::sendShare($user, $contact_record);
2246 // Send the profile data, maybe it weren't transmitted before
2247 self::sendProfile($importer['uid'], [$contact_record]);
2255 * Fetches a message with a given guid
2257 * @param string $guid message guid
2258 * @param string $orig_author handle of the original post
2259 * @return array The fetched item
2260 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2261 * @throws \ImagickException
2263 public static function originalItem($guid, $orig_author)
2266 Logger::log('Empty guid. Quitting.');
2270 // Do we already have this item?
2271 $fields = ['body', 'title', 'app', 'created', 'object-type', 'uri', 'guid',
2272 'author-name', 'author-link', 'author-avatar', 'plink', 'uri-id'];
2273 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2274 $item = Item::selectFirst($fields, $condition);
2276 if (DBA::isResult($item)) {
2277 Logger::log("reshared message ".$guid." already exists on system.");
2279 // Maybe it is already a reshared item?
2280 // Then refetch the content, if it is a reshare from a reshare.
2281 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2282 if (self::isReshare($item["body"], true)) {
2284 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2285 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2287 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2289 // Add OEmbed and other information to the body
2290 $item["body"] = PageInfo::searchAndAppendToBody($item["body"], false, true);
2298 if (!DBA::isResult($item)) {
2299 if (empty($orig_author)) {
2300 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2304 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2305 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2306 $stored = self::storeByGuid($guid, $server);
2309 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2310 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2311 $stored = self::storeByGuid($guid, $server);
2315 $fields = ['body', 'title', 'app', 'created', 'object-type', 'uri', 'guid',
2316 'author-name', 'author-link', 'author-avatar', 'plink', 'uri-id'];
2317 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2318 $item = Item::selectFirst($fields, $condition);
2320 if (DBA::isResult($item)) {
2321 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2322 if (self::isReshare($item["body"], false)) {
2323 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2324 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2335 * Stores a reshare activity
2337 * @param array $item Array of reshare post
2338 * @param integer $parent_message_id Id of the parent post
2339 * @param string $guid GUID string of reshare action
2340 * @param string $author Author handle
2342 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2344 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2348 $datarray['uid'] = $item['uid'];
2349 $datarray['contact-id'] = $item['contact-id'];
2350 $datarray['network'] = $item['network'];
2352 $datarray['author-link'] = $item['author-link'];
2353 $datarray['author-id'] = $item['author-id'];
2355 $datarray['owner-link'] = $datarray['author-link'];
2356 $datarray['owner-id'] = $datarray['author-id'];
2358 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2359 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2360 $datarray['parent-uri'] = $parent['uri'];
2362 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2363 $datarray['gravity'] = GRAVITY_ACTIVITY;
2364 $datarray['object-type'] = Activity\ObjectType::NOTE;
2366 $datarray['protocol'] = $item['protocol'];
2368 $datarray['plink'] = self::plink($author, $datarray['guid']);
2369 $datarray['private'] = $item['private'];
2370 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2372 $message_id = Item::insert($datarray);
2375 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2376 if ($datarray['uid'] == 0) {
2377 Item::distribute($message_id);
2383 * Processes a reshare message
2385 * @param array $importer Array of the importer user
2386 * @param object $data The message object
2387 * @param string $xml The original XML of the message
2389 * @return int the message id
2390 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2391 * @throws \ImagickException
2393 private static function receiveReshare(array $importer, $data, $xml)
2395 $author = Strings::escapeTags(XML::unescape($data->author));
2396 $guid = Strings::escapeTags(XML::unescape($data->guid));
2397 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2398 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2399 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2400 /// @todo handle unprocessed property "provider_display_name"
2401 $public = Strings::escapeTags(XML::unescape($data->public));
2403 $contact = self::allowedContactByHandle($importer, $author, false);
2408 $message_id = self::messageExists($importer["uid"], $guid);
2413 $original_item = self::originalItem($root_guid, $root_author);
2414 if (!$original_item) {
2420 $datarray["uid"] = $importer["uid"];
2421 $datarray["contact-id"] = $contact["id"];
2422 $datarray["network"] = Protocol::DIASPORA;
2424 $datarray["author-link"] = $contact["url"];
2425 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2427 $datarray["owner-link"] = $datarray["author-link"];
2428 $datarray["owner-id"] = $datarray["author-id"];
2430 $datarray["guid"] = $guid;
2431 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2432 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2434 $datarray["verb"] = Activity::POST;
2435 $datarray["gravity"] = GRAVITY_PARENT;
2437 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2438 $datarray["source"] = $xml;
2440 /// @todo Copy tag data from original post
2442 $prefix = BBCode::getShareOpeningTag(
2443 $original_item["author-name"],
2444 $original_item["author-link"],
2445 $original_item["author-avatar"],
2446 $original_item["plink"],
2447 $original_item["created"],
2448 $original_item["guid"]
2451 if (!empty($original_item['title'])) {
2452 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2455 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2457 Tag::storeFromBody($datarray['uri-id'], $datarray["body"]);
2459 Post\Media::copy($original_item['uri-id'], $datarray['uri-id']);
2460 $datarray["app"] = $original_item["app"];
2462 $datarray["plink"] = self::plink($author, $guid);
2463 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2464 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2466 $datarray["object-type"] = $original_item["object-type"];
2468 self::fetchGuid($datarray);
2469 $message_id = Item::insert($datarray);
2471 self::sendParticipation($contact, $datarray);
2473 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2474 if ($root_message_id) {
2475 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2479 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2480 if ($datarray['uid'] == 0) {
2481 Item::distribute($message_id);
2490 * Processes retractions
2492 * @param array $importer Array of the importer user
2493 * @param array $contact The contact of the item owner
2494 * @param object $data The message object
2496 * @return bool success
2497 * @throws \Exception
2499 private static function itemRetraction(array $importer, array $contact, $data)
2501 $author = Strings::escapeTags(XML::unescape($data->author));
2502 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2503 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2505 $person = FContact::getByURL($author);
2506 if (!is_array($person)) {
2507 Logger::log("unable to find author detail for ".$author);
2511 if (empty($contact["url"])) {
2512 $contact["url"] = $person["url"];
2515 // Fetch items that are about to be deleted
2516 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2518 // When we receive a public retraction, we delete every item that we find.
2519 if ($importer['uid'] == 0) {
2520 $condition = ['guid' => $target_guid, 'deleted' => false];
2522 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2525 $r = Item::select($fields, $condition);
2526 if (!DBA::isResult($r)) {
2527 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2531 while ($item = Item::fetch($r)) {
2532 if (strstr($item['file'], '[')) {
2533 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2537 // Fetch the parent item
2538 $parent = Item::selectFirst(['author-link'], ['id' => $item['parent']]);
2540 // Only delete it if the parent author really fits
2541 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2542 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2546 Item::markForDeletion(['id' => $item['id']]);
2548 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item['parent'], Logger::DEBUG);
2555 * Receives retraction messages
2557 * @param array $importer Array of the importer user
2558 * @param string $sender The sender of the message
2559 * @param object $data The message object
2561 * @return bool Success
2562 * @throws \Exception
2564 private static function receiveRetraction(array $importer, $sender, $data)
2566 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2568 $contact = self::contactByHandle($importer["uid"], $sender);
2569 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2570 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2578 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2580 switch ($target_type) {
2585 case "StatusMessage":
2586 return self::itemRetraction($importer, $contact, $data);
2588 case "PollParticipation":
2590 // Currently unsupported
2594 Logger::log("Unknown target type ".$target_type);
2601 * Checks if an incoming message is wanted
2603 * @param string $url
2604 * @param integer $uriid
2605 * @param string $author
2606 * @param string $body
2607 * @return boolean Is the message wanted?
2609 private static function isSolicitedMessage(string $url, int $uriid, string $author, string $body)
2611 $contact = Contact::getByURL($author);
2612 if (DBA::exists('contact', ["`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)",
2613 $contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) {
2614 Logger::info('Author has got followers - accepted', ['url' => $url, 'author' => $author]);
2618 $taglist = Tag::getByURIId($uriid, [Tag::HASHTAG]);
2619 $tags = array_column($taglist, 'name');
2620 return Relay::isSolicitedPost($tags, $body, $contact['id'], $url, Protocol::DIASPORA);
2624 * Store an attached photo in the post-media table
2627 * @param object $photo
2630 private static function storePhotoAsMedia(int $uriid, $photo)
2633 $data['uri-id'] = $uriid;
2634 $data['type'] = Post\Media::IMAGE;
2635 $data['url'] = XML::unescape($photo->remote_photo_path) . XML::unescape($photo->remote_photo_name);
2636 $data['height'] = (int)XML::unescape($photo->height ?? 0);
2637 $data['width'] = (int)XML::unescape($photo->width ?? 0);
2638 $data['description'] = XML::unescape($photo->text ?? '');
2640 Post\Media::insert($data);
2644 * Receives status messages
2646 * @param array $importer Array of the importer user
2647 * @param SimpleXMLElement $data The message object
2648 * @param string $xml The original XML of the message
2649 * @param bool $fetched The message had been fetched and not pushed
2650 * @return int The message id of the newly created item
2651 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2652 * @throws \ImagickException
2654 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml, bool $fetched)
2656 $author = Strings::escapeTags(XML::unescape($data->author));
2657 $guid = Strings::escapeTags(XML::unescape($data->guid));
2658 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2659 $public = Strings::escapeTags(XML::unescape($data->public));
2660 $text = XML::unescape($data->text);
2661 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2663 $contact = self::allowedContactByHandle($importer, $author, false);
2668 $message_id = self::messageExists($importer["uid"], $guid);
2674 if ($data->location) {
2675 foreach ($data->location->children() as $fieldname => $data) {
2676 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2680 $raw_body = $body = Markdown::toBBCode($text);
2684 $datarray["guid"] = $guid;
2685 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2686 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2688 // Attach embedded pictures to the body
2690 foreach ($data->photo as $photo) {
2691 self::storePhotoAsMedia($datarray['uri-id'], $photo);
2692 $body = "[img]".XML::unescape($photo->remote_photo_path).
2693 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2696 $datarray["object-type"] = Activity\ObjectType::IMAGE;
2698 $datarray["object-type"] = Activity\ObjectType::NOTE;
2700 // Add OEmbed and other information to the body
2701 if (!self::isHubzilla($contact["url"])) {
2702 $body = PageInfo::searchAndAppendToBody($body, false, true);
2706 /// @todo enable support for polls
2707 //if ($data->poll) {
2708 // foreach ($data->poll AS $poll)
2713 /// @todo enable support for events
2715 $datarray["uid"] = $importer["uid"];
2716 $datarray["contact-id"] = $contact["id"];
2717 $datarray["network"] = Protocol::DIASPORA;
2719 $datarray["author-link"] = $contact["url"];
2720 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2722 $datarray["owner-link"] = $datarray["author-link"];
2723 $datarray["owner-id"] = $datarray["author-id"];
2725 $datarray["verb"] = Activity::POST;
2726 $datarray["gravity"] = GRAVITY_PARENT;
2728 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2729 $datarray["source"] = $xml;
2732 $datarray["post-type"] = Item::PT_FETCHED;
2733 } elseif ($datarray["uid"] == 0) {
2734 $datarray["post-type"] = Item::PT_GLOBAL;
2737 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2738 $datarray["raw-body"] = self::replacePeopleGuid($raw_body, $contact["url"]);
2740 self::storeMentions($datarray['uri-id'], $text);
2741 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
2743 if (!$fetched && !self::isSolicitedMessage($datarray["uri"], $datarray['uri-id'], $author, $body)) {
2744 DBA::delete('item-uri', ['uri' => $datarray['uri']]);
2748 if ($provider_display_name != "") {
2749 $datarray["app"] = $provider_display_name;
2752 $datarray["plink"] = self::plink($author, $guid);
2753 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2754 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2756 if (isset($address["address"])) {
2757 $datarray["location"] = $address["address"];
2760 if (isset($address["lat"]) && isset($address["lng"])) {
2761 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2764 self::fetchGuid($datarray);
2765 $message_id = Item::insert($datarray);
2767 self::sendParticipation($contact, $datarray);
2770 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2771 if ($datarray['uid'] == 0) {
2772 Item::distribute($message_id);
2780 /* ************************************************************************************** *
2781 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2782 * ************************************************************************************** */
2785 * returnes the handle of a contact
2787 * @param array $contact contact array
2789 * @return string the handle in the format user@domain.tld
2790 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2792 private static function myHandle(array $contact)
2794 if (!empty($contact["addr"])) {
2795 return $contact["addr"];
2798 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2799 // So - just in case - we build the the address here.
2800 if ($contact["nickname"] != "") {
2801 $nick = $contact["nickname"];
2803 $nick = $contact["nick"];
2806 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
2811 * Creates the data for a private message in the new format
2813 * @param string $msg The message that is to be transmitted
2814 * @param array $user The record of the sender
2815 * @param array $contact Target of the communication
2816 * @param string $prvkey The private key of the sender
2817 * @param string $pubkey The public key of the receiver
2819 * @return string The encrypted data
2820 * @throws \Exception
2822 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
2824 Logger::log("Message: ".$msg, Logger::DATA);
2826 // without a public key nothing will work
2828 Logger::log("pubkey missing: contact id: ".$contact["id"]);
2832 $aes_key = openssl_random_pseudo_bytes(32);
2833 $b_aes_key = base64_encode($aes_key);
2834 $iv = openssl_random_pseudo_bytes(16);
2835 $b_iv = base64_encode($iv);
2837 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2839 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
2841 $encrypted_key_bundle = "";
2842 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
2846 $json_object = json_encode(
2847 ["aes_key" => base64_encode($encrypted_key_bundle),
2848 "encrypted_magic_envelope" => base64_encode($ciphertext)]
2851 return $json_object;
2855 * Creates the envelope for the "fetch" endpoint and for the new format
2857 * @param string $msg The message that is to be transmitted
2858 * @param array $user The record of the sender
2860 * @return string The envelope
2861 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2863 public static function buildMagicEnvelope($msg, array $user)
2865 $b64url_data = Strings::base64UrlEncode($msg);
2866 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
2868 $key_id = Strings::base64UrlEncode(self::myHandle($user));
2869 $type = "application/xml";
2870 $encoding = "base64url";
2871 $alg = "RSA-SHA256";
2872 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
2874 // Fallback if the private key wasn't transmitted in the expected field
2875 if ($user['uprvkey'] == "") {
2876 $user['uprvkey'] = $user['prvkey'];
2879 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
2880 $sig = Strings::base64UrlEncode($signature);
2882 $xmldata = ["me:env" => ["me:data" => $data,
2883 "@attributes" => ["type" => $type],
2884 "me:encoding" => $encoding,
2887 "@attributes2" => ["key_id" => $key_id]]];
2889 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
2891 return XML::fromArray($xmldata, $xml, false, $namespaces);
2895 * Create the envelope for a message
2897 * @param string $msg The message that is to be transmitted
2898 * @param array $user The record of the sender
2899 * @param array $contact Target of the communication
2900 * @param string $prvkey The private key of the sender
2901 * @param string $pubkey The public key of the receiver
2902 * @param bool $public Is the message public?
2904 * @return string The message that will be transmitted to other servers
2905 * @throws \Exception
2907 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
2909 // The message is put into an envelope with the sender's signature
2910 $envelope = self::buildMagicEnvelope($msg, $user);
2912 // Private messages are put into a second envelope, encrypted with the receivers public key
2914 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
2921 * Creates a signature for a message
2923 * @param array $owner the array of the owner of the message
2924 * @param array $message The message that is to be signed
2926 * @return string The signature
2928 private static function signature($owner, $message)
2931 unset($sigmsg["author_signature"]);
2932 unset($sigmsg["parent_author_signature"]);
2934 $signed_text = implode(";", $sigmsg);
2936 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
2940 * Transmit a message to a target server
2942 * @param array $owner the array of the item owner
2943 * @param array $contact Target of the communication
2944 * @param string $envelope The message that is to be transmitted
2945 * @param bool $public_batch Is it a public post?
2946 * @param string $guid message guid
2948 * @return int Result of the transmission
2949 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2950 * @throws \ImagickException
2952 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
2954 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
2959 $logid = Strings::getRandomHex(4);
2961 // We always try to use the data from the fcontact table.
2962 // This is important for transmitting data to Friendica servers.
2963 if (!empty($contact['addr'])) {
2964 $fcontact = FContact::getByURL($contact['addr']);
2965 if (!empty($fcontact)) {
2966 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
2970 if (empty($dest_url)) {
2971 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
2975 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2979 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
2981 if (!intval(DI::config()->get("system", "diaspora_test"))) {
2982 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
2984 $postResult = DI::httpRequest()->post($dest_url . "/", $envelope, ["Content-Type: " . $content_type]);
2985 $return_code = $postResult->getReturnCode();
2987 Logger::log("test_mode");
2991 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
2993 return $return_code ? $return_code : -1;
2998 * Build the post xml
3000 * @param string $type The message type
3001 * @param array $message The message data
3003 * @return string The post XML
3005 public static function buildPostXml($type, $message)
3007 $data = [$type => $message];
3009 return XML::fromArray($data, $xml);
3013 * Builds and transmit messages
3015 * @param array $owner the array of the item owner
3016 * @param array $contact Target of the communication
3017 * @param string $type The message type
3018 * @param array $message The message data
3019 * @param bool $public_batch Is it a public post?
3020 * @param string $guid message guid
3022 * @return int Result of the transmission
3023 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3024 * @throws \ImagickException
3026 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3028 $msg = self::buildPostXml($type, $message);
3030 Logger::log('message: '.$msg, Logger::DATA);
3031 Logger::log('send guid '.$guid, Logger::DEBUG);
3033 // Fallback if the private key wasn't transmitted in the expected field
3034 if (empty($owner['uprvkey'])) {
3035 $owner['uprvkey'] = $owner['prvkey'];
3038 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3040 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3042 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3044 return $return_code;
3048 * sends a participation (Used to get all further updates)
3050 * @param array $contact Target of the communication
3051 * @param array $item Item array
3053 * @return int The result of the transmission
3054 * @throws \Exception
3056 private static function sendParticipation(array $contact, array $item)
3058 // Don't send notifications for private postings
3059 if ($item['private'] == Item::PRIVATE) {
3063 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3065 $result = DI::cache()->get($cachekey);
3066 if (!is_null($result)) {
3070 // Fetch some user id to have a valid handle to transmit the participation.
3071 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3072 // If the item belongs to a user, we take this user id.
3073 if ($item['uid'] == 0) {
3074 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3075 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3076 $owner = User::getOwnerDataById($first_user['uid']);
3078 $owner = User::getOwnerDataById($item['uid']);
3081 $author = self::myHandle($owner);
3083 $message = ["author" => $author,
3084 "guid" => System::createUUID(),
3085 "parent_type" => "Post",
3086 "parent_guid" => $item["guid"]];
3088 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3090 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3091 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3093 return self::buildAndTransmit($owner, $contact, "participation", $message);
3097 * sends an account migration
3099 * @param array $owner the array of the item owner
3100 * @param array $contact Target of the communication
3101 * @param int $uid User ID
3103 * @return int The result of the transmission
3104 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3105 * @throws \ImagickException
3107 public static function sendAccountMigration(array $owner, array $contact, $uid)
3109 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3110 $profile = self::createProfileData($uid);
3112 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3113 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3115 $message = ["author" => $old_handle,
3116 "profile" => $profile,
3117 "signature" => $signature];
3119 Logger::info('Send account migration', ['msg' => $message]);
3121 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3125 * Sends a "share" message
3127 * @param array $owner the array of the item owner
3128 * @param array $contact Target of the communication
3130 * @return int The result of the transmission
3131 * @throws \Exception
3133 public static function sendShare(array $owner, array $contact)
3136 * @todo support the different possible combinations of "following" and "sharing"
3137 * Currently, Diaspora only interprets the "sharing" field
3139 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3143 switch ($contact["rel"]) {
3144 case Contact::FRIEND:
3148 case Contact::SHARING:
3152 case Contact::FOLLOWER:
3158 $message = ["author" => self::myHandle($owner),
3159 "recipient" => $contact["addr"],
3160 "following" => "true",
3161 "sharing" => "true"];
3163 Logger::info('Send share', ['msg' => $message]);
3165 return self::buildAndTransmit($owner, $contact, "contact", $message);
3169 * sends an "unshare"
3171 * @param array $owner the array of the item owner
3172 * @param array $contact Target of the communication
3174 * @return int The result of the transmission
3175 * @throws \Exception
3177 public static function sendUnshare(array $owner, array $contact)
3179 $message = ["author" => self::myHandle($owner),
3180 "recipient" => $contact["addr"],
3181 "following" => "false",
3182 "sharing" => "false"];
3184 Logger::info('Send unshare', ['msg' => $message]);
3186 return self::buildAndTransmit($owner, $contact, "contact", $message);
3190 * Checks a message body if it is a reshare
3192 * @param string $body The message body that is to be check
3193 * @param bool $complete Should it be a complete check or a simple check?
3195 * @return array|bool Reshare details or "false" if no reshare
3196 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3197 * @throws \ImagickException
3199 public static function isReshare($body, $complete = true)
3201 $body = trim($body);
3203 $reshared = Item::getShareArray(['body' => $body]);
3204 if (empty($reshared)) {
3208 // Skip if it isn't a pure repeated messages
3209 // Does it start with a share?
3210 if (!empty($reshared['comment']) && $complete) {
3214 if (!empty($reshared['guid']) && $complete) {
3215 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3216 $item = Item::selectFirst(['contact-id'], $condition);
3217 if (DBA::isResult($item)) {
3219 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3220 $ret["root_guid"] = $reshared['guid'];
3222 } elseif ($complete) {
3223 // We are resharing something that isn't a DFRN or Diaspora post.
3224 // So we have to return "false" on "$complete" to not trigger a reshare.
3227 } elseif (empty($reshared['guid']) && $complete) {
3233 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3234 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3235 if (!empty($contact['addr'])) {
3236 $ret['root_handle'] = $contact['addr'];
3240 if (empty($ret) && !$complete) {
3248 * Create an event array
3250 * @param integer $event_id The id of the event
3252 * @return array with event data
3253 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3255 private static function buildEvent($event_id)
3257 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3258 if (!DBA::isResult($r)) {
3266 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3267 if (!DBA::isResult($r)) {
3273 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3274 if (!DBA::isResult($r)) {
3280 $eventdata['author'] = self::myHandle($owner);
3282 if ($event['guid']) {
3283 $eventdata['guid'] = $event['guid'];
3286 $mask = DateTimeFormat::ATOM;
3288 /// @todo - establish "all day" events in Friendica
3289 $eventdata["all_day"] = "false";
3291 $eventdata['timezone'] = 'UTC';
3292 if (!$event['adjust'] && $user['timezone']) {
3293 $eventdata['timezone'] = $user['timezone'];
3296 if ($event['start']) {
3297 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3299 if ($event['finish'] && !$event['nofinish']) {
3300 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3302 if ($event['summary']) {
3303 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3305 if ($event['desc']) {
3306 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3308 if ($event['location']) {
3309 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3310 $coord = Map::getCoordinates($event['location']);
3313 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3314 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3315 $location["lat"] = $coord['lat'];
3316 $location["lng"] = $coord['lon'];
3318 $location["lat"] = 0;
3319 $location["lng"] = 0;
3321 $eventdata['location'] = $location;
3328 * Create a post (status message or reshare)
3330 * @param array $item The item that will be exported
3331 * @param array $owner the array of the item owner
3334 * 'type' -> Message type ("status_message" or "reshare")
3335 * 'message' -> Array of XML elements of the status
3336 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3337 * @throws \ImagickException
3339 public static function buildStatus(array $item, array $owner)
3341 $cachekey = "diaspora:buildStatus:".$item['guid'];
3343 $result = DI::cache()->get($cachekey);
3344 if (!is_null($result)) {
3348 $myaddr = self::myHandle($owner);
3350 $public = ($item["private"] == Item::PRIVATE ? "false" : "true");
3351 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3352 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3354 // Detect a share element and do a reshare
3355 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) {
3356 $message = ["author" => $myaddr,
3357 "guid" => $item["guid"],
3358 "created_at" => $created,
3359 "root_author" => $ret["root_handle"],
3360 "root_guid" => $ret["root_guid"],
3361 "provider_display_name" => $item["app"],
3362 "public" => $public];
3366 $title = $item["title"];
3367 $body = $item["body"];
3369 // Fetch the title from an attached link - if there is one
3370 if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3371 $page_data = BBCode::getAttachmentData($item['body']);
3372 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3373 $title = $page_data['title'];
3377 if ($item['author-link'] != $item['owner-link']) {
3378 require_once 'mod/share.php';
3379 $body = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'],
3380 $item['plink'], $item['created']) . $body . '[/share]';
3383 // convert to markdown
3384 $body = html_entity_decode(BBCode::toMarkdown($body));
3387 if (strlen($title)) {
3388 $body = "### ".html_entity_decode($title)."\n\n".$body;
3391 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]);
3392 if (!empty($attachments)) {
3393 $body .= "\n".DI::l10n()->t("Attachments:")."\n";
3394 foreach ($attachments as $attachment) {
3395 $body .= "[" . $attachment['description'] . "](" . $attachment['url'] . ")\n";
3401 if ($item["location"] != "")
3402 $location["address"] = $item["location"];
3404 if ($item["coord"] != "") {
3405 $coord = explode(" ", $item["coord"]);
3406 $location["lat"] = $coord[0];
3407 $location["lng"] = $coord[1];
3410 $message = ["author" => $myaddr,
3411 "guid" => $item["guid"],
3412 "created_at" => $created,
3413 "edited_at" => $edited,
3414 "public" => $public,
3416 "provider_display_name" => $item["app"],
3417 "location" => $location];
3419 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3420 if (!isset($location["lat"]) || !isset($location["lng"])) {
3421 unset($message["location"]);
3424 if ($item['event-id'] > 0) {
3425 $event = self::buildEvent($item['event-id']);
3426 if (count($event)) {
3427 $message['event'] = $event;
3429 if (!empty($event['location']['address']) &&
3430 !empty($event['location']['lat']) &&
3431 !empty($event['location']['lng'])) {
3432 $message['location'] = $event['location'];
3435 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3436 // $message['text'] = '';
3440 $type = "status_message";
3443 $msg = ["type" => $type, "message" => $message];
3445 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3450 private static function prependParentAuthorMention($body, $profile_url)
3452 $profile = Contact::getByURL($profile_url, false, ['addr', 'name', 'contact-type']);
3453 if (!empty($profile['addr'])
3454 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3455 && !strstr($body, $profile['addr'])
3456 && !strstr($body, $profile_url)
3458 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3467 * @param array $item The item that will be exported
3468 * @param array $owner the array of the item owner
3469 * @param array $contact Target of the communication
3470 * @param bool $public_batch Is it a public post?
3472 * @return int The result of the transmission
3473 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3474 * @throws \ImagickException
3476 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3478 $status = self::buildStatus($item, $owner);
3480 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3484 * Creates a "like" object
3486 * @param array $item The item that will be exported
3487 * @param array $owner the array of the item owner
3489 * @return array The data for a "like"
3490 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3492 private static function constructLike(array $item, array $owner)
3494 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3495 if (!DBA::isResult($parent)) {
3499 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3501 if ($item['verb'] === Activity::LIKE) {
3503 } elseif ($item['verb'] === Activity::DISLIKE) {
3504 $positive = "false";
3507 return(["author" => self::myHandle($owner),
3508 "guid" => $item["guid"],
3509 "parent_guid" => $parent["guid"],
3510 "parent_type" => $target_type,
3511 "positive" => $positive,
3512 "author_signature" => ""]);
3516 * Creates an "EventParticipation" object
3518 * @param array $item The item that will be exported
3519 * @param array $owner the array of the item owner
3521 * @return array The data for an "EventParticipation"
3522 * @throws \Exception
3524 private static function constructAttend(array $item, array $owner)
3526 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3527 if (!DBA::isResult($parent)) {
3531 switch ($item['verb']) {
3532 case Activity::ATTEND:
3533 $attend_answer = 'accepted';
3535 case Activity::ATTENDNO:
3536 $attend_answer = 'declined';
3538 case Activity::ATTENDMAYBE:
3539 $attend_answer = 'tentative';
3542 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3546 return(["author" => self::myHandle($owner),
3547 "guid" => $item["guid"],
3548 "parent_guid" => $parent["guid"],
3549 "status" => $attend_answer,
3550 "author_signature" => ""]);
3554 * Creates the object for a comment
3556 * @param array $item The item that will be exported
3557 * @param array $owner the array of the item owner
3559 * @return array|false The data for a comment
3560 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3562 private static function constructComment(array $item, array $owner)
3564 $cachekey = "diaspora:constructComment:".$item['guid'];
3566 $result = DI::cache()->get($cachekey);
3567 if (!is_null($result)) {
3571 $toplevel_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3572 if (!DBA::isResult($toplevel_item)) {
3573 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3577 $thread_parent_item = $toplevel_item;
3578 if ($item['thr-parent'] != $item['parent-uri']) {
3579 $thread_parent_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3582 $body = $item["body"];
3584 // The replied to autor mention is prepended for clarity if:
3585 // - Item replied isn't yours
3586 // - Item is public or explicit mentions are disabled
3587 // - Implicit mentions are enabled
3589 $item['author-id'] != $thread_parent_item['author-id']
3590 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3591 && !DI::config()->get('system', 'disable_implicit_mentions')
3593 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3596 $text = html_entity_decode(BBCode::toMarkdown($body));
3597 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3598 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3601 "author" => self::myHandle($owner),
3602 "guid" => $item["guid"],
3603 "created_at" => $created,
3604 "edited_at" => $edited,
3605 "parent_guid" => $toplevel_item["guid"],
3607 "author_signature" => ""
3610 // Send the thread parent guid only if it is a threaded comment
3611 if ($item['thr-parent'] != $item['parent-uri']) {
3612 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3615 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3621 * Send a like or a comment
3623 * @param array $item The item that will be exported
3624 * @param array $owner the array of the item owner
3625 * @param array $contact Target of the communication
3626 * @param bool $public_batch Is it a public post?
3628 * @return int The result of the transmission
3629 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3630 * @throws \ImagickException
3632 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3634 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3635 $message = self::constructAttend($item, $owner);
3636 $type = "event_participation";
3637 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3638 $message = self::constructLike($item, $owner);
3640 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3641 $message = self::constructComment($item, $owner);
3645 if (empty($message)) {
3649 $message["author_signature"] = self::signature($owner, $message);
3651 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3655 * Creates a message from a signature record entry
3657 * @param array $item The item that will be exported
3658 * @return array The message
3660 private static function messageFromSignature(array $item)
3662 // Split the signed text
3663 $signed_parts = explode(";", $item['signed_text']);
3665 if ($item["deleted"]) {
3666 $message = ["author" => $item['signer'],
3667 "target_guid" => $signed_parts[0],
3668 "target_type" => $signed_parts[1]];
3669 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3670 $message = ["author" => $signed_parts[4],
3671 "guid" => $signed_parts[1],
3672 "parent_guid" => $signed_parts[3],
3673 "parent_type" => $signed_parts[2],
3674 "positive" => $signed_parts[0],
3675 "author_signature" => $item['signature'],
3676 "parent_author_signature" => ""];
3678 // Remove the comment guid
3679 $guid = array_shift($signed_parts);
3681 // Remove the parent guid
3682 $parent_guid = array_shift($signed_parts);
3684 // Remove the handle
3685 $handle = array_pop($signed_parts);
3688 "author" => $handle,
3690 "parent_guid" => $parent_guid,
3691 "text" => implode(";", $signed_parts),
3692 "author_signature" => $item['signature'],
3693 "parent_author_signature" => ""
3700 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3702 * @param array $item The item that will be exported
3703 * @param array $owner the array of the item owner
3704 * @param array $contact Target of the communication
3705 * @param bool $public_batch Is it a public post?
3707 * @return int The result of the transmission
3708 * @throws \Exception
3710 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3712 if ($item["deleted"]) {
3713 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3714 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3720 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3722 $msg = json_decode($item['signed_text'], true);
3725 if (is_array($msg)) {
3726 foreach ($msg as $field => $data) {
3727 if (!$item["deleted"]) {
3728 if ($field == "diaspora_handle") {
3731 if ($field == "target_type") {
3732 $field = "parent_type";
3736 $message[$field] = $data;
3739 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
3742 $message["parent_author_signature"] = self::signature($owner, $message);
3744 Logger::info('Relayed data', ['msg' => $message]);
3746 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3750 * Sends a retraction (deletion) of a message, like or comment
3752 * @param array $item The item that will be exported
3753 * @param array $owner the array of the item owner
3754 * @param array $contact Target of the communication
3755 * @param bool $public_batch Is it a public post?
3756 * @param bool $relay Is the retraction transmitted from a relay?
3758 * @return int The result of the transmission
3759 * @throws \Exception
3761 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
3763 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3765 $msg_type = "retraction";
3767 if ($item['gravity'] == GRAVITY_PARENT) {
3768 $target_type = "Post";
3769 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3770 $target_type = "Like";
3772 $target_type = "Comment";
3775 $message = ["author" => $itemaddr,
3776 "target_guid" => $item['guid'],
3777 "target_type" => $target_type];
3779 Logger::info('Got message', ['msg' => $message]);
3781 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3787 * @param array $item The item that will be exported
3788 * @param array $owner The owner
3789 * @param array $contact Target of the communication
3791 * @return int The result of the transmission
3792 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3793 * @throws \ImagickException
3795 public static function sendMail(array $item, array $owner, array $contact)
3797 $myaddr = self::myHandle($owner);
3799 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
3800 if (!DBA::isResult($cnv)) {
3801 Logger::log("conversation not found.");
3805 $body = BBCode::toMarkdown($item["body"]);
3806 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3809 "author" => $myaddr,
3810 "guid" => $item["guid"],
3811 "conversation_guid" => $cnv["guid"],
3813 "created_at" => $created,
3816 if ($item["reply"]) {
3821 "author" => $cnv["creator"],
3822 "guid" => $cnv["guid"],
3823 "subject" => $cnv["subject"],
3824 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3825 "participants" => $cnv["recips"],
3829 $type = "conversation";
3832 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
3836 * Split a name into first name and last name
3838 * @param string $name The name
3840 * @return array The array with "first" and "last"
3842 public static function splitName($name) {
3843 $name = trim($name);
3845 // Is the name longer than 64 characters? Then cut the rest of it.
3846 if (strlen($name) > 64) {
3847 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3848 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3850 $name = substr($name, 0, 64);
3854 // Take the first word as first name
3855 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3856 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3857 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3858 return ['first' => $first, 'last' => $last];
3861 // Take the last word as last name
3862 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3863 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3865 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3866 return ['first' => $first, 'last' => $last];
3869 // Take the first 32 characters if there is no space in the first 32 characters
3870 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3871 $first = substr($name, 0, 32);
3872 $last = substr($name, 32);
3873 return ['first' => $first, 'last' => $last];
3876 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3877 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3879 // Check if the last name is longer than 32 characters
3880 if (strlen($last) > 32) {
3881 if (strpos($last, ' ') <= 32) {
3882 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
3884 $last = substr($last, 0, 32);
3888 return ['first' => $first, 'last' => $last];
3892 * Create profile data
3894 * @param int $uid The user id
3896 * @return array The profile data
3897 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3899 private static function createProfileData($uid)
3901 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
3902 if (!DBA::isResult($profile)) {
3906 $handle = $profile["addr"];
3908 $split_name = self::splitName($profile['name']);
3909 $first = $split_name['first'];
3910 $last = $split_name['last'];
3912 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3913 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3914 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3915 $searchable = ($profile['net-publish'] ? 'true' : 'false');
3921 if ($searchable === 'true') {
3924 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
3925 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
3929 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
3932 $about = BBCode::toMarkdown($profile['about']);
3934 $location = $profile['location'];
3936 if ($profile['pub_keywords']) {
3937 $kw = str_replace(',', ' ', $profile['pub_keywords']);
3938 $kw = str_replace(' ', ' ', $kw);
3939 $arr = explode(' ', $kw);
3941 for ($x = 0; $x < 5; $x ++) {
3942 if (!empty($arr[$x])) {
3943 $tags .= '#'. trim($arr[$x]) .' ';
3948 $tags = trim($tags);
3951 return ["author" => $handle,
3952 "first_name" => $first,
3953 "last_name" => $last,
3954 "image_url" => $large,
3955 "image_url_medium" => $medium,
3956 "image_url_small" => $small,
3959 "location" => $location,
3960 "searchable" => $searchable,
3962 "tag_string" => $tags];
3966 * Sends profile data
3968 * @param int $uid The user id
3969 * @param bool $recips optional, default false
3971 * @throws \Exception
3973 public static function sendProfile($uid, $recips = false)
3979 $owner = User::getOwnerDataById($uid);
3986 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3987 AND `uid` = %d AND `rel` != %d",
3988 DBA::escape(Protocol::DIASPORA),
3990 intval(Contact::SHARING)
3998 $message = self::createProfileData($uid);
4000 // @ToDo Split this into single worker jobs
4001 foreach ($recips as $recip) {
4002 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4003 self::buildAndTransmit($owner, $recip, "profile", $message);
4008 * Creates the signature for likes that are created on our system
4010 * @param integer $uid The user of that comment
4011 * @param array $item Item array
4013 * @return array Signed content
4014 * @throws \Exception
4016 public static function createLikeSignature($uid, array $item)
4018 $owner = User::getOwnerDataById($uid);
4019 if (empty($owner)) {
4020 Logger::info('No owner post, so not storing signature');
4024 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4028 $message = self::constructLike($item, $owner);
4029 if ($message === false) {
4033 $message["author_signature"] = self::signature($owner, $message);
4039 * Creates the signature for Comments that are created on our system
4041 * @param integer $uid The user of that comment
4042 * @param array $item Item array
4044 * @return array Signed content
4045 * @throws \Exception
4047 public static function createCommentSignature($uid, array $item)
4049 $owner = User::getOwnerDataById($uid);
4050 if (empty($owner)) {
4051 Logger::info('No owner post, so not storing signature');
4055 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4056 $item['thr-parent'] = $item['parent-uri'];
4058 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4059 if (!DBA::isResult($parent)) {
4063 $item['parent-uri'] = $parent['parent-uri'];
4065 $message = self::constructComment($item, $owner);
4066 if ($message === false) {
4070 $message["author_signature"] = self::signature($owner, $message);