3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol;
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\Markdown;
27 use Friendica\Core\Cache\Enum\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\FContact;
37 use Friendica\Model\GServer;
38 use Friendica\Model\Item;
39 use Friendica\Model\ItemURI;
40 use Friendica\Model\Mail;
41 use Friendica\Model\Post;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
45 use Friendica\Network\Probe;
46 use Friendica\Util\Crypto;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Map;
49 use Friendica\Util\Network;
50 use Friendica\Util\Strings;
51 use Friendica\Util\XML;
52 use Friendica\Worker\Delivery;
56 * This class contain functions to create and send Diaspora XML files
62 const FORCED_FETCH = 2;
65 * Return a list of participating contacts for a thread
67 * This is used for the participation feature.
68 * One of the parameters is a contact array.
69 * This is done to avoid duplicates.
71 * @param array $item Item that is about to be delivered
72 * @param array $contacts The previously fetched contacts
74 * @return array of relay servers
77 public static function participantsForThread(array $item, array $contacts)
79 if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
80 Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]);
84 $items = Post::select(['author-id', 'author-link', 'parent-author-link', 'parent-guid', 'guid'],
85 ['parent' => $item['parent'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
86 while ($item = Post::fetch($items)) {
87 $contact = DBA::selectFirst('contact', ['id', 'url', 'name', 'protocol', 'batch', 'network'],
88 ['id' => $item['author-id']]);
89 if (!DBA::isResult($contact) || empty($contact['batch']) ||
90 ($contact['network'] != Protocol::DIASPORA) ||
91 Strings::compareLink($item['parent-author-link'], $item['author-link'])) {
96 foreach ($contacts as $entry) {
97 if ($entry['batch'] == $contact['batch']) {
103 Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]);
104 $contacts[] = $contact;
113 * verify the envelope and return the verified data
115 * @param string $envelope The magic envelope
117 * @return string verified data
118 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
119 * @throws \ImagickException
121 private static function verifyMagicEnvelope($envelope)
123 $basedom = XML::parseString($envelope, true);
125 if (!is_object($basedom)) {
126 Logger::notice("Envelope is no XML file");
130 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
132 if (sizeof($children) == 0) {
133 Logger::notice("XML has no children");
139 $data = Strings::base64UrlDecode($children->data);
140 $type = $children->data->attributes()->type[0];
142 $encoding = $children->encoding;
144 $alg = $children->alg;
146 $sig = Strings::base64UrlDecode($children->sig);
147 $key_id = $children->sig->attributes()->key_id[0];
149 $handle = Strings::base64UrlDecode($key_id);
152 $b64url_data = Strings::base64UrlEncode($data);
153 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
155 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
158 Logger::notice('No author could be decoded. Discarding. Message: ' . $envelope);
162 $key = self::key($handle);
164 Logger::notice("Couldn't get a key for handle " . $handle . ". Discarding.");
168 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
170 Logger::notice('Message from ' . $handle . ' did not verify. Discarding.');
178 * encrypts data via AES
180 * @param string $key The AES key
181 * @param string $iv The IV (is used for CBC encoding)
182 * @param string $data The data that is to be encrypted
184 * @return string encrypted data
186 private static function aesEncrypt($key, $iv, $data)
188 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
192 * decrypts data via AES
194 * @param string $key The AES key
195 * @param string $iv The IV (is used for CBC encoding)
196 * @param string $encrypted The encrypted data
198 * @return string decrypted data
200 private static function aesDecrypt($key, $iv, $encrypted)
202 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
206 * Decodes incoming Diaspora message in the new format
208 * @param string $raw raw post message
209 * @param string $privKey The private key of the importer
210 * @param boolean $no_exit Don't do an http exit on error
213 * 'message' -> decoded Diaspora XML message
214 * 'author' -> author diaspora handle
215 * 'key' -> author public key (converted to pkcs#8)
216 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
217 * @throws \ImagickException
219 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
221 $data = json_decode($raw);
223 // Is it a private post? Then decrypt the outer Salmon
224 if (is_object($data)) {
225 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
226 $ciphertext = base64_decode($data->encrypted_magic_envelope);
228 $outer_key_bundle = '';
229 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
230 $j_outer_key_bundle = json_decode($outer_key_bundle);
232 if (!is_object($j_outer_key_bundle)) {
233 Logger::notice('Outer Salmon did not verify. Discarding.');
237 throw new \Friendica\Network\HTTPException\BadRequestException();
241 $outer_iv = base64_decode($j_outer_key_bundle->iv);
242 $outer_key = base64_decode($j_outer_key_bundle->key);
244 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
249 $basedom = XML::parseString($xml, true);
251 if (!is_object($basedom)) {
252 Logger::notice('Received data does not seem to be an XML. Discarding. '.$xml);
256 throw new \Friendica\Network\HTTPException\BadRequestException();
260 $base = $basedom->children(ActivityNamespace::SALMON_ME);
262 // Not sure if this cleaning is needed
263 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
265 // Build the signed data
266 $type = $base->data[0]->attributes()->type[0];
267 $encoding = $base->encoding;
269 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
271 // This is the signature
272 $signature = Strings::base64UrlDecode($base->sig);
274 // Get the senders' public key
275 $key_id = $base->sig[0]->attributes()->key_id[0];
276 $author_addr = base64_decode($key_id);
277 if ($author_addr == '') {
278 Logger::notice('No author could be decoded. Discarding. Message: ' . $xml);
282 throw new \Friendica\Network\HTTPException\BadRequestException();
286 $key = self::key($author_addr);
288 Logger::notice("Couldn't get a key for handle " . $author_addr . ". Discarding.");
292 throw new \Friendica\Network\HTTPException\BadRequestException();
296 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
298 Logger::notice('Message did not verify. Discarding.');
302 throw new \Friendica\Network\HTTPException\BadRequestException();
306 return ['message' => (string)Strings::base64UrlDecode($base->data),
307 'author' => XML::unescape($author_addr),
308 'key' => (string)$key];
312 * Decodes incoming Diaspora message in the deprecated format
314 * @param string $xml urldecoded Diaspora salmon
315 * @param string $privKey The private key of the importer
318 * 'message' -> decoded Diaspora XML message
319 * 'author' -> author diaspora handle
320 * 'key' -> author public key (converted to pkcs#8)
321 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
322 * @throws \ImagickException
324 public static function decode(string $xml, string $privKey = '')
327 $basedom = XML::parseString($xml);
329 if (!is_object($basedom)) {
330 Logger::notice('XML is not parseable.');
333 $children = $basedom->children('https://joindiaspora.com/protocol');
335 $inner_aes_key = null;
338 if ($children->header) {
340 $author_link = str_replace('acct:', '', $children->header->author_id);
342 // This happens with posts from a relais
343 if (empty($privKey)) {
344 Logger::info('This is no private post in the old format');
348 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
350 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
351 $ciphertext = base64_decode($encrypted_header->ciphertext);
353 $outer_key_bundle = '';
354 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
356 $j_outer_key_bundle = json_decode($outer_key_bundle);
358 $outer_iv = base64_decode($j_outer_key_bundle->iv);
359 $outer_key = base64_decode($j_outer_key_bundle->key);
361 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
363 Logger::info('decrypted', ['data' => $decrypted]);
364 $idom = XML::parseString($decrypted);
366 $inner_iv = base64_decode($idom->iv);
367 $inner_aes_key = base64_decode($idom->aes_key);
369 $author_link = str_replace('acct:', '', $idom->author_id);
372 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
374 // figure out where in the DOM tree our data is hiding
377 if ($dom->provenance->data) {
378 $base = $dom->provenance;
379 } elseif ($dom->env->data) {
381 } elseif ($dom->data) {
386 Logger::notice('unable to locate salmon data in xml');
387 throw new \Friendica\Network\HTTPException\BadRequestException();
391 // Stash the signature away for now. We have to find their key or it won't be good for anything.
392 $signature = Strings::base64UrlDecode($base->sig);
396 // strip whitespace so our data element will return to one big base64 blob
397 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
400 // stash away some other stuff for later
402 $type = $base->data[0]->attributes()->type[0];
403 $keyhash = $base->sig[0]->attributes()->keyhash[0];
404 $encoding = $base->encoding;
408 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
412 $data = Strings::base64UrlDecode($data);
416 $inner_decrypted = $data;
418 // Decode the encrypted blob
419 $inner_encrypted = base64_decode($data);
420 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
424 Logger::notice('Could not retrieve author URI.');
425 throw new \Friendica\Network\HTTPException\BadRequestException();
427 // Once we have the author URI, go to the web and try to find their public key
428 // (first this will look it up locally if it is in the fcontact cache)
429 // This will also convert diaspora public key from pkcs#1 to pkcs#8
431 Logger::notice('Fetching key for '.$author_link);
432 $key = self::key($author_link);
435 Logger::notice('Could not retrieve author key.');
436 throw new \Friendica\Network\HTTPException\BadRequestException();
439 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
442 Logger::notice('Message did not verify. Discarding.');
443 throw new \Friendica\Network\HTTPException\BadRequestException();
446 Logger::notice('Message verified.');
448 return ['message' => (string)$inner_decrypted,
449 'author' => XML::unescape($author_link),
450 'key' => (string)$key];
455 * Dispatches public messages and find the fitting receivers
457 * @param array $msg The post that will be dispatched
458 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
460 * @return int The message id of the generated message, "true" or "false" if there was an error
461 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
462 * @throws \ImagickException
464 public static function dispatchPublic($msg, int $direction)
466 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
468 Logger::notice("diaspora is disabled");
472 if (!($fields = self::validPosting($msg))) {
473 Logger::notice("Invalid posting");
477 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
478 $success = self::dispatch($importer, $msg, $fields, $direction);
484 * Dispatches the different message types to the different functions
486 * @param array $importer Array of the importer user
487 * @param array $msg The post that will be dispatched
488 * @param SimpleXMLElement $fields SimpleXML object that contains the message
489 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
491 * @return int The message id of the generated message, "true" or "false" if there was an error
492 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
493 * @throws \ImagickException
495 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null, int $direction = self::PUSHED)
497 // The sender is the handle of the contact that sent the message.
498 // This will often be different with relayed messages (for example "like" and "comment")
499 $sender = $msg["author"];
501 // This is only needed for private postings since this is already done for public ones before
502 if (is_null($fields)) {
504 if (!($fields = self::validPosting($msg))) {
505 Logger::notice("Invalid posting");
512 $type = $fields->getName();
514 Logger::info('Received message', ['type' => $type, 'sender' => $sender, 'user' => $importer["uid"]]);
517 case "account_migration":
519 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
522 return self::receiveAccountMigration($importer, $fields);
524 case "account_deletion":
525 return self::receiveAccountDeletion($fields);
528 return self::receiveComment($importer, $sender, $fields, $msg["message"], $direction);
532 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
535 return self::receiveContactRequest($importer, $fields);
539 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
542 return self::receiveConversation($importer, $msg, $fields);
545 return self::receiveLike($importer, $sender, $fields, $direction);
549 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
552 return self::receiveMessage($importer, $fields);
554 case "participation":
556 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
559 return self::receiveParticipation($importer, $fields, $direction);
561 case "photo": // Not implemented
562 return self::receivePhoto($importer, $fields);
564 case "poll_participation": // Not implemented
565 return self::receivePollParticipation($importer, $fields);
569 Logger::notice('Message with type ' . $type . ' is not private, quitting.');
572 return self::receiveProfile($importer, $fields);
575 return self::receiveReshare($importer, $fields, $msg["message"], $direction);
578 return self::receiveRetraction($importer, $sender, $fields);
580 case "status_message":
581 return self::receiveStatusMessage($importer, $fields, $msg["message"], $direction);
584 Logger::notice("Unknown message type ".$type);
590 * Checks if a posting is valid and fetches the data fields.
592 * This function does not only check the signature.
593 * It also does the conversion between the old and the new diaspora format.
595 * @param array $msg Array with the XML, the sender handle and the sender signature
597 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
598 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
599 * @throws \ImagickException
601 private static function validPosting($msg)
603 $data = XML::parseString($msg["message"]);
605 if (!is_object($data)) {
606 Logger::info('No valid XML', ['message' => $msg['message']]);
610 // Is this the new or the old version?
611 if ($data->getName() == "XML") {
613 foreach ($data->post->children() as $child) {
621 $type = $element->getName();
624 Logger::debug("Got message type ".$type.": ".$msg["message"]);
626 // All retractions are handled identically from now on.
627 // In the new version there will only be "retraction".
628 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
629 $type = "retraction";
631 if ($type == "request") {
635 $fields = new SimpleXMLElement("<".$type."/>");
638 $author_signature = null;
639 $parent_author_signature = null;
641 foreach ($element->children() as $fieldname => $entry) {
643 // Translation for the old XML structure
644 if ($fieldname == "diaspora_handle") {
645 $fieldname = "author";
647 if ($fieldname == "participant_handles") {
648 $fieldname = "participants";
650 if (in_array($type, ["like", "participation"])) {
651 if ($fieldname == "target_type") {
652 $fieldname = "parent_type";
655 if ($fieldname == "sender_handle") {
656 $fieldname = "author";
658 if ($fieldname == "recipient_handle") {
659 $fieldname = "recipient";
661 if ($fieldname == "root_diaspora_id") {
662 $fieldname = "root_author";
664 if ($type == "status_message") {
665 if ($fieldname == "raw_message") {
669 if ($type == "retraction") {
670 if ($fieldname == "post_guid") {
671 $fieldname = "target_guid";
673 if ($fieldname == "type") {
674 $fieldname = "target_type";
679 if (($fieldname == "author_signature") && ($entry != "")) {
680 $author_signature = base64_decode($entry);
681 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
682 $parent_author_signature = base64_decode($entry);
683 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
684 if ($signed_data != "") {
688 $signed_data .= $entry;
690 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
691 || ($orig_type == "relayable_retraction")
693 XML::copy($entry, $fields, $fieldname);
697 // This is something that shouldn't happen at all.
698 if (in_array($type, ["status_message", "reshare", "profile"])) {
699 if ($msg["author"] != $fields->author) {
700 Logger::notice("Message handle is not the same as envelope sender. Quitting this message.");
705 // Only some message types have signatures. So we quit here for the other types.
706 if (!in_array($type, ["comment", "like"])) {
709 // No author_signature? This is a must, so we quit.
710 if (!isset($author_signature)) {
711 Logger::info("No author signature for type ".$type." - Message: ".$msg["message"]);
715 if (isset($parent_author_signature)) {
716 $key = self::key($msg["author"]);
718 Logger::info('No key found for parent', ['author' => $msg["author"]]);
722 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
723 Logger::info("No valid parent author signature for parent author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$parent_author_signature);
728 $key = self::key($fields->author);
730 Logger::info('No key found', ['author' => $fields->author]);
734 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
735 Logger::info("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature);
743 * Fetches the public key for a given handle
745 * @param string $handle The handle
747 * @return string The public key
748 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
749 * @throws \ImagickException
751 private static function key($handle)
753 $handle = strval($handle);
755 Logger::notice("Fetching diaspora key for: ".$handle);
757 $r = FContact::getByURL($handle);
766 * get a handle (user@domain.tld) from a given contact id
768 * @param int $contact_id The id in the contact table
769 * @param int $pcontact_id The id in the contact table (Used for the public contact)
771 * @return string the handle
774 private static function handleFromContact($contact_id, $pcontact_id = 0)
778 if ($pcontact_id != 0) {
779 $contact = Contact::getById($pcontact_id, ['addr']);
780 if (DBA::isResult($contact)) {
781 $handle = $contact['addr'];
785 if (empty($handle)) {
786 $contact = Contact::getById($contact_id, ['addr']);
787 if (DBA::isResult($contact)) {
788 $handle = $contact['addr'];
792 return strtolower($handle);
796 * Get a contact id for a given handle
798 * @todo Move to Friendica\Model\Contact
800 * @param int $uid The user id
801 * @param string $handle The handle in the format user@domain.tld
803 * @return array Contact data
804 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
805 * @throws \ImagickException
807 private static function contactByHandle($uid, $handle)
809 return Contact::getByURL($handle, null, [], $uid);
813 * Checks if the given contact url does support ActivityPub
815 * @param string $url profile url
816 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
818 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
819 * @throws \ImagickException
821 public static function isSupportedByContactUrl($url, $update = null)
823 return !empty(FContact::getByURL($url, $update));
827 * Check if posting is allowed for this contact
829 * @param array $importer Array of the importer user
830 * @param array $contact The contact that is checked
831 * @param bool $is_comment Is the check for a comment?
833 * @return bool is the contact allowed to post?
835 private static function postAllow(array $importer, array $contact, $is_comment = false)
838 * Perhaps we were already sharing with this person. Now they're sharing with us.
839 * That makes us friends.
840 * Normally this should have handled by getting a request - but this could get lost
842 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
843 // It is not removed by now. Possibly the code is needed?
844 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
846 // array('rel' => Contact::FRIEND, 'writable' => true),
847 // array('id' => $contact["id"], 'uid' => $contact["uid"])
850 // $contact["rel"] = Contact::FRIEND;
851 // Logger::notice("defining user ".$contact["nick"]." as friend");
854 // Contact server is blocked
855 if (Network::isUrlBlocked($contact['url'])) {
857 // We don't seem to like that person
858 } elseif ($contact["blocked"]) {
859 // Maybe blocked, don't accept.
861 // We are following this person?
862 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
863 // Yes, then it is fine.
865 // Is the message a global user or a comment?
866 } elseif (($importer["uid"] == 0) || $is_comment) {
867 // Messages for the global users and comments are always accepted
875 * Fetches the contact id for a handle and checks if posting is allowed
877 * @param array $importer Array of the importer user
878 * @param string $handle The checked handle in the format user@domain.tld
879 * @param bool $is_comment Is the check for a comment?
881 * @return array The contact data
884 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
886 $contact = self::contactByHandle($importer["uid"], $handle);
888 Logger::notice("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
889 // If a contact isn't found, we accept it anyway if it is a comment
890 if ($is_comment && ($importer["uid"] != 0)) {
891 return self::contactByHandle(0, $handle);
892 } elseif ($is_comment) {
899 if (!self::postAllow($importer, $contact, $is_comment)) {
900 Logger::notice("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
907 * Does the message already exists on the system?
909 * @param int $uid The user id
910 * @param string $guid The guid of the message
912 * @return int|bool message id if the message already was stored into the system - or false.
915 private static function messageExists($uid, $guid)
917 $item = Post::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
918 if (DBA::isResult($item)) {
919 Logger::notice("message ".$guid." already exists for user ".$uid);
927 * Checks for links to posts in a message
929 * @param array $item The item array
932 private static function fetchGuid(array $item)
934 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
935 preg_replace_callback(
937 function ($match) use ($item) {
938 self::fetchGuidSub($match, $item);
943 preg_replace_callback(
944 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
945 function ($match) use ($item) {
946 self::fetchGuidSub($match, $item);
953 * Checks for relative /people/* links in an item body to match local
954 * contacts or prepends the remote host taken from the author link.
956 * @param string $body The item body to replace links from
957 * @param string $author_link The author link for missing local contact fallback
959 * @return string the replaced string
961 public static function replacePeopleGuid($body, $author_link)
963 $return = preg_replace_callback(
964 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
965 function ($match) use ($author_link) {
967 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
968 // 1 => '0123456789abcdef'
970 $handle = FContact::getUrlByGuid($match[1]);
973 $return = '@[url='.$handle.']'.$match[2].'[/url]';
975 // No local match, restoring absolute remote URL from author scheme and host
976 $author_url = parse_url($author_link);
977 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
989 * sub function of "fetchGuid" which checks for links in messages
991 * @param array $match array containing a link that has to be checked for a message link
992 * @param array $item The item array
994 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
995 * @throws \ImagickException
997 private static function fetchGuidSub($match, $item)
999 if (!self::storeByGuid($match[1], $item["author-link"], true)) {
1000 self::storeByGuid($match[1], $item["owner-link"], true);
1005 * Fetches an item with a given guid from a given server
1007 * @param string $guid the message guid
1008 * @param string $server The server address
1009 * @param bool $force Forced fetch
1011 * @return int the message id of the stored message or false
1012 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1013 * @throws \ImagickException
1015 private static function storeByGuid($guid, $server, $force)
1017 $serverparts = parse_url($server);
1019 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1023 $server = $serverparts["scheme"]."://".$serverparts["host"];
1025 Logger::info("Trying to fetch item ".$guid." from ".$server);
1027 $msg = self::message($guid, $server);
1033 Logger::info("Successfully fetched item ".$guid." from ".$server);
1035 // Now call the dispatcher
1036 return self::dispatchPublic($msg, $force ? self::FORCED_FETCH : self::FETCHED);
1040 * Fetches a message from a server
1042 * @param string $guid message guid
1043 * @param string $server The url of the server
1044 * @param int $level Endless loop prevention
1047 * 'message' => The message XML
1048 * 'author' => The author handle
1049 * 'key' => The public key of the author
1050 * @throws \Exception
1052 public static function message($guid, $server, $level = 0)
1058 // This will work for new Diaspora servers and Friendica servers from 3.5
1059 $source_url = $server."/fetch/post/".urlencode($guid);
1061 Logger::info("Fetch post from ".$source_url);
1063 $envelope = DI::httpClient()->fetch($source_url, HttpClientAccept::MAGIC);
1065 Logger::info("Envelope was fetched.");
1066 $x = self::verifyMagicEnvelope($envelope);
1068 Logger::info("Envelope could not be verified.");
1070 Logger::info("Envelope was verified.");
1080 $source_xml = XML::parseString($x);
1082 if (!is_object($source_xml)) {
1086 if ($source_xml->post->reshare) {
1087 // Reshare of a reshare - old Diaspora version
1088 Logger::info("Message is a reshare");
1089 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1090 } elseif ($source_xml->getName() == "reshare") {
1091 // Reshare of a reshare - new Diaspora version
1092 Logger::info("Message is a new reshare");
1093 return self::message($source_xml->root_guid, $server, ++$level);
1098 // Fetch the author - for the old and the new Diaspora version
1099 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1100 $author = (string)$source_xml->post->status_message->diaspora_handle;
1101 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1102 $author = (string)$source_xml->author;
1105 // If this isn't a "status_message" then quit
1107 Logger::info("Message doesn't seem to be a status message");
1111 $msg = ["message" => $x, "author" => $author];
1113 $msg["key"] = self::key($msg["author"]);
1119 * Fetches an item with a given URL
1121 * @param string $url the message url
1123 * @return int the message id of the stored message or false
1124 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1125 * @throws \ImagickException
1127 public static function fetchByURL($url, $uid = 0)
1129 // Check for Diaspora (and Friendica) typical paths
1130 if (!preg_match("=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1131 Logger::info('Invalid url', ['url' => $url]);
1135 $guid = urldecode($matches[2]);
1137 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1138 if (DBA::isResult($item)) {
1139 Logger::info('Found', ['id' => $item['id']]);
1143 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1144 $ret = self::storeByGuid($guid, $matches[1], true);
1145 Logger::info('Result', ['ret' => $ret]);
1147 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1148 if (DBA::isResult($item)) {
1149 Logger::info('Found', ['id' => $item['id']]);
1152 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1158 * Fetches the item record of a given guid
1160 * @param int $uid The user id
1161 * @param string $guid message guid
1162 * @param string $author The handle of the item
1163 * @param array $contact The contact of the item owner
1165 * @return array the item record
1166 * @throws \Exception
1168 private static function parentItem($uid, $guid, $author, array $contact)
1170 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1171 'author-name', 'author-link', 'author-avatar', 'gravity',
1172 'owner-name', 'owner-link', 'owner-avatar'];
1173 $condition = ['uid' => $uid, 'guid' => $guid];
1174 $item = Post::selectFirst($fields, $condition);
1176 if (!DBA::isResult($item)) {
1177 $person = FContact::getByURL($author);
1178 $result = self::storeByGuid($guid, $person["url"], false);
1180 // We don't have an url for items that arrived at the public dispatcher
1181 if (!$result && !empty($contact["url"])) {
1182 $result = self::storeByGuid($guid, $contact["url"], false);
1186 Logger::info("Fetched missing item ".$guid." - result: ".$result);
1188 $item = Post::selectFirst($fields, $condition);
1192 if (!DBA::isResult($item)) {
1193 Logger::notice("parent item not found: parent: ".$guid." - user: ".$uid);
1196 Logger::notice("parent item found: parent: ".$guid." - user: ".$uid);
1202 * returns contact details
1204 * @param array $def_contact The default contact if the person isn't found
1205 * @param array $person The record of the person
1206 * @param int $uid The user id
1209 * 'cid' => contact id
1210 * 'network' => network type
1211 * @throws \Exception
1213 private static function authorContactByUrl($def_contact, $person, $uid)
1215 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1216 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1217 if (DBA::isResult($contact)) {
1218 $cid = $contact["id"];
1219 $network = $contact["network"];
1221 $cid = $def_contact["id"];
1222 $network = Protocol::DIASPORA;
1225 return ["cid" => $cid, "network" => $network];
1229 * Is the profile a hubzilla profile?
1231 * @param string $url The profile link
1233 * @return bool is it a hubzilla server?
1235 private static function isHubzilla($url)
1237 return(strstr($url, '/channel/'));
1241 * Generate a post link with a given handle and message guid
1243 * @param string $addr The user handle
1244 * @param string $guid message guid
1245 * @param string $parent_guid optional parent guid
1247 * @return string the post link
1248 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1249 * @throws \ImagickException
1251 private static function plink(string $addr, string $guid, string $parent_guid = '')
1253 $contact = Contact::getByURL($addr);
1254 if (empty($contact)) {
1255 Logger::info('No contact data for address', ['addr' => $addr]);
1259 if (empty($contact['baseurl'])) {
1260 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1261 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1265 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1266 if (!empty($gserver['platform'])) {
1267 $platform = strtolower($gserver['platform']);
1268 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1271 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1272 if (self::isHubzilla($contact['url'])) {
1273 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1274 $platform = 'hubzilla';
1275 } elseif ($contact['network'] == Protocol::DFRN) {
1276 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1277 $platform = 'friendica';
1281 if ($platform == 'friendica') {
1282 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1285 if ($platform == 'hubzilla') {
1286 return $contact['baseurl'] . '/item/' . $guid;
1289 if ($platform == 'socialhome') {
1290 return $contact['baseurl'] . '/content/' . $guid;
1293 if ($platform != 'diaspora') {
1294 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1298 if ($parent_guid != '') {
1299 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1301 return $contact['baseurl'] . '/posts/' . $guid;
1306 * Receives account migration
1308 * @param array $importer Array of the importer user
1309 * @param object $data The message object
1311 * @return bool Success
1312 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1313 * @throws \ImagickException
1315 private static function receiveAccountMigration(array $importer, $data)
1317 $old_handle = XML::unescape($data->author);
1318 $new_handle = XML::unescape($data->profile->author);
1319 $signature = XML::unescape($data->signature);
1321 $contact = self::contactByHandle($importer["uid"], $old_handle);
1323 Logger::notice("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1327 Logger::notice("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1330 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1331 $key = self::key($old_handle);
1332 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1333 Logger::notice('No valid signature for migration.');
1337 // Update the profile
1338 self::receiveProfile($importer, $data->profile);
1340 // change the technical stuff in contact
1341 $data = Probe::uri($new_handle);
1342 if ($data['network'] == Protocol::PHANTOM) {
1343 Logger::notice('Account for '.$new_handle." couldn't be probed.");
1347 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1348 'name' => $data['name'], 'nick' => $data['nick'],
1349 'addr' => $data['addr'], 'batch' => $data['batch'],
1350 'notify' => $data['notify'], 'poll' => $data['poll'],
1351 'network' => $data['network']];
1353 Contact::update($fields, ['addr' => $old_handle]);
1355 Logger::notice('Contacts are updated.');
1361 * Processes an account deletion
1363 * @param object $data The message object
1365 * @return bool Success
1366 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1368 private static function receiveAccountDeletion($data)
1370 $author = XML::unescape($data->author);
1372 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1373 while ($contact = DBA::fetch($contacts)) {
1374 Contact::remove($contact["id"]);
1376 DBA::close($contacts);
1378 Logger::notice('Removed contacts for ' . $author);
1384 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1386 * @param string $author Author handle
1387 * @param string $guid Message guid
1388 * @param boolean $onlyfound Only return uri when found in the database
1390 * @return string The constructed uri or the one from our database
1391 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1392 * @throws \ImagickException
1394 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1396 $item = Post::selectFirst(['uri'], ['guid' => $guid]);
1397 if (DBA::isResult($item)) {
1398 return $item["uri"];
1399 } elseif (!$onlyfound) {
1400 $person = FContact::getByURL($author);
1402 $parts = parse_url($person['url']);
1403 unset($parts['path']);
1404 $host_url = Network::unparseURL($parts);
1406 return $host_url . '/objects/' . $guid;
1413 * Store the mentions in the tag table
1415 * @param integer $uriid
1416 * @param string $text
1418 private static function storeMentions(int $uriid, string $text)
1420 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1421 if (empty($matches)) {
1426 * Matching values for the preg match
1427 * [1] = mention type (@ or !)
1428 * [2] = name (optional)
1432 foreach ($matches as $match) {
1433 if (empty($match)) {
1437 $person = FContact::getByURL($match[3]);
1438 if (empty($person)) {
1442 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1447 * Processes an incoming comment
1449 * @param array $importer Array of the importer user
1450 * @param string $sender The sender of the message
1451 * @param object $data The message object
1452 * @param string $xml The original XML of the message
1453 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1455 * @return int The message id of the generated comment or "false" if there was an error
1456 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1457 * @throws \ImagickException
1459 private static function receiveComment(array $importer, $sender, $data, $xml, int $direction)
1461 $author = XML::unescape($data->author);
1462 $guid = XML::unescape($data->guid);
1463 $parent_guid = XML::unescape($data->parent_guid);
1464 $text = XML::unescape($data->text);
1466 if (isset($data->created_at)) {
1467 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1469 $created_at = DateTimeFormat::utcNow();
1472 if (isset($data->thread_parent_guid)) {
1473 $thread_parent_guid = XML::unescape($data->thread_parent_guid);
1474 $thr_parent = self::getUriFromGuid("", $thread_parent_guid, true);
1479 $contact = self::allowedContactByHandle($importer, $sender, true);
1484 if (!empty($contact['gsid'])) {
1485 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1488 $message_id = self::messageExists($importer["uid"], $guid);
1493 $toplevel_parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1494 if (!$toplevel_parent_item) {
1498 $person = FContact::getByURL($author);
1499 if (!is_array($person)) {
1500 Logger::notice("unable to find author details");
1504 // Fetch the contact id - if we know this contact
1505 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1509 $datarray["uid"] = $importer["uid"];
1510 $datarray["contact-id"] = $author_contact["cid"];
1511 $datarray["network"] = $author_contact["network"];
1513 $datarray["author-link"] = $person["url"];
1514 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1516 $datarray["owner-link"] = $contact["url"];
1517 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1519 // Will be overwritten for sharing accounts in Item::insert
1520 if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
1521 $datarray["post-reason"] = Item::PR_FETCHED;
1522 } elseif ($datarray["uid"] == 0) {
1523 $datarray["post-reason"] = Item::PR_GLOBAL;
1525 $datarray["post-reason"] = Item::PR_COMMENT;
1528 $datarray["guid"] = $guid;
1529 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1530 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1532 $datarray["verb"] = Activity::POST;
1533 $datarray["gravity"] = GRAVITY_COMMENT;
1535 $datarray['thr-parent'] = $thr_parent ?: $toplevel_parent_item['uri'];
1537 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1538 $datarray["post-type"] = Item::PT_NOTE;
1540 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1541 $datarray["source"] = $xml;
1542 $datarray["direction"] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
1544 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1546 $datarray["plink"] = self::plink($author, $guid, $toplevel_parent_item['guid']);
1547 $body = Markdown::toBBCode($text);
1549 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1551 self::storeMentions($datarray['uri-id'], $text);
1552 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
1554 self::fetchGuid($datarray);
1556 // If we are the origin of the parent we store the original data.
1557 // We notify our followers during the item storage.
1558 if ($toplevel_parent_item["origin"]) {
1559 $datarray['diaspora_signed_text'] = json_encode($data);
1562 if (Item::isTooOld($datarray)) {
1563 Logger::info('Comment is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1567 $message_id = Item::insert($datarray);
1569 if ($message_id <= 0) {
1574 Logger::info("Stored comment ".$datarray["guid"]." with message id ".$message_id);
1575 if ($datarray['uid'] == 0) {
1576 Item::distribute($message_id, json_encode($data));
1584 * processes and stores private messages
1586 * @param array $importer Array of the importer user
1587 * @param array $contact The contact of the message
1588 * @param object $data The message object
1589 * @param array $msg Array of the processed message, author handle and key
1590 * @param object $mesg The private message
1591 * @param array $conversation The conversation record to which this message belongs
1593 * @return bool "true" if it was successful
1594 * @throws \Exception
1596 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1598 $author = XML::unescape($data->author);
1599 $guid = XML::unescape($data->guid);
1600 $subject = XML::unescape($data->subject);
1602 // "diaspora_handle" is the element name from the old version
1603 // "author" is the element name from the new version
1604 if ($mesg->author) {
1605 $msg_author = XML::unescape($mesg->author);
1606 } elseif ($mesg->diaspora_handle) {
1607 $msg_author = XML::unescape($mesg->diaspora_handle);
1612 $msg_guid = XML::unescape($mesg->guid);
1613 $msg_conversation_guid = XML::unescape($mesg->conversation_guid);
1614 $msg_text = XML::unescape($mesg->text);
1615 $msg_created_at = DateTimeFormat::utc(XML::unescape($mesg->created_at));
1617 if ($msg_conversation_guid != $guid) {
1618 Logger::notice("message conversation guid does not belong to the current conversation.");
1622 $body = Markdown::toBBCode($msg_text);
1623 $message_uri = $msg_author.":".$msg_guid;
1625 $person = FContact::getByURL($msg_author);
1627 return Mail::insert([
1628 'uid' => $importer['uid'],
1629 'guid' => $msg_guid,
1630 'convid' => $conversation['id'],
1631 'from-name' => $person['name'],
1632 'from-photo' => $person['photo'],
1633 'from-url' => $person['url'],
1634 'contact-id' => $contact['id'],
1635 'title' => $subject,
1637 'uri' => $message_uri,
1638 'parent-uri' => $author . ':' . $guid,
1639 'created' => $msg_created_at
1644 * Processes new private messages (answers to private messages are processed elsewhere)
1646 * @param array $importer Array of the importer user
1647 * @param array $msg Array of the processed message, author handle and key
1648 * @param object $data The message object
1650 * @return bool Success
1651 * @throws \Exception
1653 private static function receiveConversation(array $importer, $msg, $data)
1655 $author = XML::unescape($data->author);
1656 $guid = XML::unescape($data->guid);
1657 $subject = XML::unescape($data->subject);
1658 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1659 $participants = XML::unescape($data->participants);
1661 $messages = $data->message;
1663 if (!count($messages)) {
1664 Logger::notice("empty conversation");
1668 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1673 if (!empty($contact['gsid'])) {
1674 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1677 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1678 if (!DBA::isResult($conversation)) {
1679 $r = DBA::insert('conv', [
1680 'uid' => $importer['uid'],
1682 'creator' => $author,
1683 'created' => $created_at,
1684 'updated' => DateTimeFormat::utcNow(),
1685 'subject' => $subject,
1686 'recips' => $participants]);
1688 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1691 if (!$conversation) {
1692 Logger::notice("unable to create conversation.");
1696 foreach ($messages as $mesg) {
1697 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1704 * Processes "like" messages
1706 * @param array $importer Array of the importer user
1707 * @param string $sender The sender of the message
1708 * @param object $data The message object
1709 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1711 * @return int The message id of the generated like or "false" if there was an error
1712 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1713 * @throws \ImagickException
1715 private static function receiveLike(array $importer, $sender, $data, int $direction)
1717 $author = XML::unescape($data->author);
1718 $guid = XML::unescape($data->guid);
1719 $parent_guid = XML::unescape($data->parent_guid);
1720 $parent_type = XML::unescape($data->parent_type);
1721 $positive = XML::unescape($data->positive);
1723 // likes on comments aren't supported by Diaspora - only on posts
1724 // But maybe this will be supported in the future, so we will accept it.
1725 if (!in_array($parent_type, ["Post", "Comment"])) {
1729 $contact = self::allowedContactByHandle($importer, $sender, true);
1734 if (!empty($contact['gsid'])) {
1735 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1738 $message_id = self::messageExists($importer["uid"], $guid);
1743 $toplevel_parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1744 if (!$toplevel_parent_item) {
1748 $person = FContact::getByURL($author);
1749 if (!is_array($person)) {
1750 Logger::notice("unable to find author details");
1754 // Fetch the contact id - if we know this contact
1755 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1757 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1758 // We would accept this anyhow.
1759 if ($positive == "true") {
1760 $verb = Activity::LIKE;
1762 $verb = Activity::DISLIKE;
1767 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1768 $datarray["direction"] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
1770 $datarray["uid"] = $importer["uid"];
1771 $datarray["contact-id"] = $author_contact["cid"];
1772 $datarray["network"] = $author_contact["network"];
1774 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
1775 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1777 $datarray["guid"] = $guid;
1778 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1780 $datarray["verb"] = $verb;
1781 $datarray["gravity"] = GRAVITY_ACTIVITY;
1782 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1784 $datarray["object-type"] = Activity\ObjectType::NOTE;
1786 $datarray["body"] = $verb;
1788 // Diaspora doesn't provide a date for likes
1789 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
1791 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1792 if ($toplevel_parent_item['gravity'] != GRAVITY_PARENT) {
1793 $toplevel = Post::selectFirst(['origin'], ['id' => $toplevel_parent_item['parent']]);
1794 $origin = $toplevel["origin"];
1796 $origin = $toplevel_parent_item["origin"];
1799 // If we are the origin of the parent we store the original data.
1800 // We notify our followers during the item storage.
1802 $datarray['diaspora_signed_text'] = json_encode($data);
1805 if (Item::isTooOld($datarray)) {
1806 Logger::info('Like is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1810 $message_id = Item::insert($datarray);
1812 if ($message_id <= 0) {
1817 Logger::info("Stored like ".$datarray["guid"]." with message id ".$message_id);
1818 if ($datarray['uid'] == 0) {
1819 Item::distribute($message_id, json_encode($data));
1827 * Processes private messages
1829 * @param array $importer Array of the importer user
1830 * @param object $data The message object
1832 * @return bool Success?
1833 * @throws \Exception
1835 private static function receiveMessage(array $importer, $data)
1837 $author = XML::unescape($data->author);
1838 $guid = XML::unescape($data->guid);
1839 $conversation_guid = XML::unescape($data->conversation_guid);
1840 $text = XML::unescape($data->text);
1841 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
1843 $contact = self::allowedContactByHandle($importer, $author, true);
1848 if (!empty($contact['gsid'])) {
1849 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1852 $conversation = null;
1854 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
1855 $conversation = DBA::selectFirst('conv', [], $condition);
1857 if (!DBA::isResult($conversation)) {
1858 Logger::notice("conversation not available.");
1862 $message_uri = $author.":".$guid;
1864 $person = FContact::getByURL($author);
1866 Logger::notice("unable to find author details");
1870 $body = Markdown::toBBCode($text);
1872 $body = self::replacePeopleGuid($body, $person["url"]);
1874 return Mail::insert([
1875 'uid' => $importer['uid'],
1877 'convid' => $conversation['id'],
1878 'from-name' => $person['name'],
1879 'from-photo' => $person['photo'],
1880 'from-url' => $person['url'],
1881 'contact-id' => $contact['id'],
1882 'title' => $conversation['subject'],
1885 'uri' => $message_uri,
1886 'parent-uri' => $author.":".$conversation['guid'],
1887 'created' => $created_at
1892 * Processes participations - unsupported by now
1894 * @param array $importer Array of the importer user
1895 * @param object $data The message object
1896 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
1898 * @return bool success
1899 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1900 * @throws \ImagickException
1902 private static function receiveParticipation(array $importer, $data, int $direction)
1904 $author = strtolower(XML::unescape($data->author));
1905 $guid = XML::unescape($data->guid);
1906 $parent_guid = XML::unescape($data->parent_guid);
1908 $contact = self::allowedContactByHandle($importer, $author, true);
1913 if (!empty($contact['gsid'])) {
1914 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1917 if (self::messageExists($importer["uid"], $guid)) {
1921 $toplevel_parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1922 if (!$toplevel_parent_item) {
1926 if (!$toplevel_parent_item['origin']) {
1927 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1930 if (!in_array($toplevel_parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
1931 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1935 $person = FContact::getByURL($author);
1936 if (!is_array($person)) {
1937 Logger::notice("Person not found: ".$author);
1941 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1943 // Store participation
1946 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1947 $datarray["direction"] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
1949 $datarray["uid"] = $importer["uid"];
1950 $datarray["contact-id"] = $author_contact["cid"];
1951 $datarray["network"] = $author_contact["network"];
1953 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
1954 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1956 $datarray["guid"] = $guid;
1957 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1959 $datarray["verb"] = Activity::FOLLOW;
1960 $datarray["gravity"] = GRAVITY_ACTIVITY;
1961 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1963 $datarray["object-type"] = Activity\ObjectType::NOTE;
1965 $datarray["body"] = Activity::FOLLOW;
1967 // Diaspora doesn't provide a date for a participation
1968 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
1970 if (Item::isTooOld($datarray)) {
1971 Logger::info('Participation is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1975 $message_id = Item::insert($datarray);
1977 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
1979 // Send all existing comments and likes to the requesting server
1980 $comments = Post::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb'],
1981 ['parent' => $toplevel_parent_item['id'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
1982 while ($comment = Post::fetch($comments)) {
1983 if (in_array($comment['verb'], [Activity::FOLLOW, Activity::TAG])) {
1984 Logger::info('participation messages are not relayed', ['item' => $comment['id']]);
1988 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
1989 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
1993 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
1994 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
1998 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact["cid"]]);
1999 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $author_contact["cid"])) {
2000 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2003 DBA::close($comments);
2009 * Processes photos - unneeded
2011 * @param array $importer Array of the importer user
2012 * @param object $data The message object
2014 * @return bool always true
2016 private static function receivePhoto(array $importer, $data)
2018 // There doesn't seem to be a reason for this function,
2019 // since the photo data is transmitted in the status message as well
2024 * Processes poll participations - unssupported
2026 * @param array $importer Array of the importer user
2027 * @param object $data The message object
2029 * @return bool always true
2031 private static function receivePollParticipation(array $importer, $data)
2033 // We don't support polls by now
2038 * Processes incoming profile updates
2040 * @param array $importer Array of the importer user
2041 * @param object $data The message object
2043 * @return bool Success
2044 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2045 * @throws \ImagickException
2047 private static function receiveProfile(array $importer, $data)
2049 $author = strtolower(XML::unescape($data->author));
2051 $contact = self::contactByHandle($importer["uid"], $author);
2056 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2057 $image_url = XML::unescape($data->image_url);
2058 $birthday = XML::unescape($data->birthday);
2059 $about = Markdown::toBBCode(XML::unescape($data->bio));
2060 $location = Markdown::toBBCode(XML::unescape($data->location));
2061 $searchable = (XML::unescape($data->searchable) == "true");
2062 $nsfw = (XML::unescape($data->nsfw) == "true");
2063 $tags = XML::unescape($data->tag_string);
2065 $tags = explode("#", $tags);
2068 foreach ($tags as $tag) {
2069 $tag = trim(strtolower($tag));
2075 $keywords = implode(", ", $keywords);
2077 $handle_parts = explode("@", $author);
2078 $nick = $handle_parts[0];
2081 $name = $handle_parts[0];
2084 if (preg_match("|^https?://|", $image_url) === 0) {
2085 $image_url = "http://".$handle_parts[1].$image_url;
2088 Contact::updateAvatar($contact["id"], $image_url);
2090 // Generic birthday. We don't know the timezone. The year is irrelevant.
2092 $birthday = str_replace("1000", "1901", $birthday);
2094 if ($birthday != "") {
2095 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2098 // this is to prevent multiple birthday notifications in a single year
2099 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2101 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2102 $birthday = $contact["bd"];
2105 $fields = ['name' => $name, 'location' => $location,
2106 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2107 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2108 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2110 if (!empty($birthday)) {
2111 $fields['bd'] = $birthday;
2114 Contact::update($fields, ['id' => $contact['id']]);
2116 Logger::info("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"]);
2122 * Processes incoming friend requests
2124 * @param array $importer Array of the importer user
2125 * @param array $contact The contact that send the request
2127 * @throws \Exception
2129 private static function receiveRequestMakeFriend(array $importer, array $contact)
2131 if ($contact["rel"] == Contact::SHARING) {
2133 ['rel' => Contact::FRIEND, 'writable' => true],
2134 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2140 * Processes incoming sharing notification
2142 * @param array $importer Array of the importer user
2143 * @param object $data The message object
2145 * @return bool Success
2146 * @throws \Exception
2148 private static function receiveContactRequest(array $importer, $data)
2150 $author = XML::unescape($data->author);
2151 $recipient = XML::unescape($data->recipient);
2153 if (!$author || !$recipient) {
2157 // the current protocol version doesn't know these fields
2158 // That means that we will assume their existance
2159 if (isset($data->following)) {
2160 $following = (XML::unescape($data->following) == "true");
2165 if (isset($data->sharing)) {
2166 $sharing = (XML::unescape($data->sharing) == "true");
2171 $contact = self::contactByHandle($importer["uid"], $author);
2173 // perhaps we were already sharing with this person. Now they're sharing with us.
2174 // That makes us friends.
2177 Logger::info("Author ".$author." (Contact ".$contact["id"].") wants to follow us.");
2178 self::receiveRequestMakeFriend($importer, $contact);
2180 // refetch the contact array
2181 $contact = self::contactByHandle($importer["uid"], $author);
2183 // If we are now friends, we are sending a share message.
2184 // Normally we needn't to do so, but the first message could have been vanished.
2185 if (in_array($contact["rel"], [Contact::FRIEND])) {
2186 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2187 if (DBA::isResult($user)) {
2188 Logger::info("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"]);
2189 self::sendShare($user, $contact);
2194 Logger::info("Author ".$author." doesn't want to follow us anymore.");
2195 Contact::removeFollower($contact);
2200 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2201 Logger::info("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.");
2203 } elseif (!$following && !$sharing) {
2204 Logger::info("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.");
2206 } elseif (!$following && $sharing) {
2207 Logger::info("Author ".$author." wants to share with us.");
2208 } elseif ($following && $sharing) {
2209 Logger::info("Author ".$author." wants to have a bidirectional conection.");
2210 } elseif ($following && !$sharing) {
2211 Logger::info("Author ".$author." wants to listen to us.");
2214 $ret = FContact::getByURL($author);
2216 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2217 Logger::notice("Cannot resolve diaspora handle ".$author." for ".$recipient);
2221 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2223 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2228 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2229 'author-link' => $ret['url']];
2231 $result = Contact::addRelationship($importer, $contact, $item, false);
2232 if ($result === true) {
2233 $contact_record = self::contactByHandle($importer['uid'], $author);
2234 if (!$contact_record) {
2235 Logger::info('unable to locate newly created contact record.');
2239 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2240 if (DBA::isResult($user)) {
2241 self::sendShare($user, $contact_record);
2243 // Send the profile data, maybe it weren't transmitted before
2244 self::sendProfile($importer['uid'], [$contact_record]);
2252 * Fetches a message with a given guid
2254 * @param string $guid message guid
2255 * @param string $orig_author handle of the original post
2256 * @return array The fetched item
2257 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2258 * @throws \ImagickException
2260 public static function originalItem($guid, $orig_author)
2263 Logger::notice('Empty guid. Quitting.');
2267 // Do we already have this item?
2268 $fields = ['body', 'title', 'app', 'created', 'object-type', 'uri', 'guid',
2269 'author-name', 'author-link', 'author-avatar', 'plink', 'uri-id'];
2270 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2271 $item = Post::selectFirst($fields, $condition);
2273 if (DBA::isResult($item)) {
2274 Logger::notice("reshared message ".$guid." already exists on system.");
2276 // Maybe it is already a reshared item?
2277 // Then refetch the content, if it is a reshare from a reshare.
2278 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2279 if (self::isReshare($item["body"], true)) {
2281 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2282 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2284 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2292 if (!DBA::isResult($item)) {
2293 if (empty($orig_author)) {
2294 Logger::notice('Empty author for guid ' . $guid . '. Quitting.');
2298 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2299 Logger::notice("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2300 $stored = self::storeByGuid($guid, $server, true);
2303 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2304 Logger::notice("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2305 $stored = self::storeByGuid($guid, $server, true);
2309 $fields = ['body', 'title', 'app', 'created', 'object-type', 'uri', 'guid',
2310 'author-name', 'author-link', 'author-avatar', 'plink', 'uri-id'];
2311 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2312 $item = Post::selectFirst($fields, $condition);
2314 if (DBA::isResult($item)) {
2315 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2316 if (self::isReshare($item["body"], false)) {
2317 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2318 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2329 * Stores a reshare activity
2331 * @param array $item Array of reshare post
2332 * @param integer $parent_message_id Id of the parent post
2333 * @param string $guid GUID string of reshare action
2334 * @param string $author Author handle
2336 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2338 $parent = Post::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2342 $datarray['uid'] = $item['uid'];
2343 $datarray['contact-id'] = $item['contact-id'];
2344 $datarray['network'] = $item['network'];
2346 $datarray['author-link'] = $item['author-link'];
2347 $datarray['author-id'] = $item['author-id'];
2349 $datarray['owner-link'] = $datarray['author-link'];
2350 $datarray['owner-id'] = $datarray['author-id'];
2352 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2353 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2354 $datarray['thr-parent'] = $parent['uri'];
2356 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2357 $datarray['gravity'] = GRAVITY_ACTIVITY;
2358 $datarray['object-type'] = Activity\ObjectType::NOTE;
2360 $datarray['protocol'] = $item['protocol'];
2361 $datarray['source'] = $item['source'];
2362 $datarray['direction'] = $item['direction'];
2364 $datarray['plink'] = self::plink($author, $datarray['guid']);
2365 $datarray['private'] = $item['private'];
2366 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2368 if (Item::isTooOld($datarray)) {
2369 Logger::info('Reshare activity is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2373 $message_id = Item::insert($datarray);
2376 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2377 if ($datarray['uid'] == 0) {
2378 Item::distribute($message_id);
2384 * Processes a reshare message
2386 * @param array $importer Array of the importer user
2387 * @param object $data The message object
2388 * @param string $xml The original XML of the message
2389 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2391 * @return int the message id
2392 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2393 * @throws \ImagickException
2395 private static function receiveReshare(array $importer, $data, $xml, int $direction)
2397 $author = XML::unescape($data->author);
2398 $guid = XML::unescape($data->guid);
2399 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2400 $root_author = XML::unescape($data->root_author);
2401 $root_guid = XML::unescape($data->root_guid);
2402 /// @todo handle unprocessed property "provider_display_name"
2403 $public = XML::unescape($data->public);
2405 $contact = self::allowedContactByHandle($importer, $author, false);
2410 if (!empty($contact['gsid'])) {
2411 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2414 $message_id = self::messageExists($importer["uid"], $guid);
2419 $original_item = self::originalItem($root_guid, $root_author);
2420 if (!$original_item) {
2424 if (empty($original_item['plink'])) {
2425 $original_item['plink'] = self::plink($root_author, $root_guid);
2430 $datarray["uid"] = $importer["uid"];
2431 $datarray["contact-id"] = $contact["id"];
2432 $datarray["network"] = Protocol::DIASPORA;
2434 $datarray["author-link"] = $contact["url"];
2435 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2437 $datarray["owner-link"] = $datarray["author-link"];
2438 $datarray["owner-id"] = $datarray["author-id"];
2440 $datarray["guid"] = $guid;
2441 $datarray["uri"] = $datarray["thr-parent"] = self::getUriFromGuid($author, $guid);
2442 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2444 $datarray["verb"] = Activity::POST;
2445 $datarray["gravity"] = GRAVITY_PARENT;
2447 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2448 $datarray["source"] = $xml;
2449 $datarray["direction"] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
2451 /// @todo Copy tag data from original post
2453 $prefix = BBCode::getShareOpeningTag(
2454 $original_item["author-name"],
2455 $original_item["author-link"],
2456 $original_item["author-avatar"],
2457 $original_item["plink"],
2458 $original_item["created"],
2459 $original_item["guid"]
2462 if (!empty($original_item['title'])) {
2463 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2466 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2468 Tag::storeFromBody($datarray['uri-id'], $datarray["body"]);
2470 $datarray["app"] = $original_item["app"];
2472 $datarray["plink"] = self::plink($author, $guid);
2473 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2474 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2476 $datarray["object-type"] = $original_item["object-type"];
2478 self::fetchGuid($datarray);
2480 if (Item::isTooOld($datarray)) {
2481 Logger::info('Reshare is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2485 $message_id = Item::insert($datarray);
2487 self::sendParticipation($contact, $datarray);
2489 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2490 if ($root_message_id) {
2491 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2495 Logger::info("Stored reshare ".$datarray["guid"]." with message id ".$message_id);
2496 if ($datarray['uid'] == 0) {
2497 Item::distribute($message_id);
2506 * Processes retractions
2508 * @param array $importer Array of the importer user
2509 * @param array $contact The contact of the item owner
2510 * @param object $data The message object
2512 * @return bool success
2513 * @throws \Exception
2515 private static function itemRetraction(array $importer, array $contact, $data)
2517 $author = XML::unescape($data->author);
2518 $target_guid = XML::unescape($data->target_guid);
2519 $target_type = XML::unescape($data->target_type);
2521 $person = FContact::getByURL($author);
2522 if (!is_array($person)) {
2523 Logger::notice("unable to find author detail for ".$author);
2527 if (empty($contact["url"])) {
2528 $contact["url"] = $person["url"];
2531 // Fetch items that are about to be deleted
2532 $fields = ['uid', 'id', 'parent', 'author-link', 'uri-id'];
2534 // When we receive a public retraction, we delete every item that we find.
2535 if ($importer['uid'] == 0) {
2536 $condition = ['guid' => $target_guid, 'deleted' => false];
2538 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2541 $r = Post::select($fields, $condition);
2542 if (!DBA::isResult($r)) {
2543 Logger::notice("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2547 while ($item = Post::fetch($r)) {
2548 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2549 Logger::info("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.");
2553 // Fetch the parent item
2554 $parent = Post::selectFirst(['author-link'], ['id' => $item['parent']]);
2556 // Only delete it if the parent author really fits
2557 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2558 Logger::info("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"]);
2562 Item::markForDeletion(['id' => $item['id']]);
2564 Logger::info("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item['parent']);
2572 * Receives retraction messages
2574 * @param array $importer Array of the importer user
2575 * @param string $sender The sender of the message
2576 * @param object $data The message object
2578 * @return bool Success
2579 * @throws \Exception
2581 private static function receiveRetraction(array $importer, $sender, $data)
2583 $target_type = XML::unescape($data->target_type);
2585 $contact = self::contactByHandle($importer["uid"], $sender);
2586 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2587 Logger::notice("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2595 Logger::info("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"]);
2597 switch ($target_type) {
2602 case "StatusMessage":
2603 return self::itemRetraction($importer, $contact, $data);
2605 case "PollParticipation":
2607 // Currently unsupported
2611 Logger::notice("Unknown target type ".$target_type);
2618 * Checks if an incoming message is wanted
2620 * @param array $item
2621 * @param string $author
2622 * @param string $body
2623 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2625 * @return boolean Is the message wanted?
2627 private static function isSolicitedMessage(array $item, string $author, string $body, int $direction)
2629 $contact = Contact::getByURL($author);
2630 if (DBA::exists('contact', ["`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)",
2631 $contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) {
2632 Logger::debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2636 if ($direction == self::FORCED_FETCH) {
2637 Logger::debug('Post is a forced fetch - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2641 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
2642 if (Relay::isSolicitedPost($tags, $body, $contact['id'], $item['uri'], Protocol::DIASPORA)) {
2643 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
2651 * Store an attached photo in the post-media table
2654 * @param object $photo
2657 private static function storePhotoAsMedia(int $uriid, $photo)
2660 $data['uri-id'] = $uriid;
2661 $data['type'] = Post\Media::IMAGE;
2662 $data['url'] = XML::unescape($photo->remote_photo_path) . XML::unescape($photo->remote_photo_name);
2663 $data['height'] = (int)XML::unescape($photo->height ?? 0);
2664 $data['width'] = (int)XML::unescape($photo->width ?? 0);
2665 $data['description'] = XML::unescape($photo->text ?? '');
2667 Post\Media::insert($data);
2671 * Receives status messages
2673 * @param array $importer Array of the importer user
2674 * @param SimpleXMLElement $data The message object
2675 * @param string $xml The original XML of the message
2676 * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
2678 * @return int The message id of the newly created item
2679 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2680 * @throws \ImagickException
2682 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml, int $direction)
2684 $author = XML::unescape($data->author);
2685 $guid = XML::unescape($data->guid);
2686 $created_at = DateTimeFormat::utc(XML::unescape($data->created_at));
2687 $public = XML::unescape($data->public);
2688 $text = XML::unescape($data->text);
2689 $provider_display_name = XML::unescape($data->provider_display_name);
2691 $contact = self::allowedContactByHandle($importer, $author, false);
2696 if (!empty($contact['gsid'])) {
2697 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2700 $message_id = self::messageExists($importer["uid"], $guid);
2706 if ($data->location) {
2707 foreach ($data->location->children() as $fieldname => $data) {
2708 $address[$fieldname] = XML::unescape($data);
2712 $raw_body = $body = Markdown::toBBCode($text);
2716 $datarray["guid"] = $guid;
2717 $datarray["uri"] = $datarray["thr-parent"] = self::getUriFromGuid($author, $guid);
2718 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2720 // Attach embedded pictures to the body
2722 foreach ($data->photo as $photo) {
2723 self::storePhotoAsMedia($datarray['uri-id'], $photo);
2726 $datarray["object-type"] = Activity\ObjectType::IMAGE;
2727 $datarray["post-type"] = Item::PT_IMAGE;
2728 } elseif ($data->poll) {
2729 $datarray["object-type"] = Activity\ObjectType::NOTE;
2730 $datarray["post-type"] = Item::PT_POLL;
2732 $datarray["object-type"] = Activity\ObjectType::NOTE;
2733 $datarray["post-type"] = Item::PT_NOTE;
2736 /// @todo enable support for polls
2737 //if ($data->poll) {
2738 // foreach ($data->poll as $poll)
2743 /// @todo enable support for events
2745 $datarray["uid"] = $importer["uid"];
2746 $datarray["contact-id"] = $contact["id"];
2747 $datarray["network"] = Protocol::DIASPORA;
2749 $datarray["author-link"] = $contact["url"];
2750 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2752 $datarray["owner-link"] = $datarray["author-link"];
2753 $datarray["owner-id"] = $datarray["author-id"];
2755 $datarray["verb"] = Activity::POST;
2756 $datarray["gravity"] = GRAVITY_PARENT;
2758 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2759 $datarray["source"] = $xml;
2760 $datarray["direction"] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
2762 if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
2763 $datarray["post-reason"] = Item::PR_FETCHED;
2764 } elseif ($datarray["uid"] == 0) {
2765 $datarray["post-reason"] = Item::PR_GLOBAL;
2768 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2769 $datarray["raw-body"] = self::replacePeopleGuid($raw_body, $contact["url"]);
2771 self::storeMentions($datarray['uri-id'], $text);
2772 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
2774 if (!self::isSolicitedMessage($datarray, $author, $body, $direction)) {
2775 DBA::delete('item-uri', ['uri' => $datarray['uri']]);
2779 if ($provider_display_name != "") {
2780 $datarray["app"] = $provider_display_name;
2783 $datarray["plink"] = self::plink($author, $guid);
2784 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2785 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2787 if (isset($address["address"])) {
2788 $datarray["location"] = $address["address"];
2791 if (isset($address["lat"]) && isset($address["lng"])) {
2792 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2795 self::fetchGuid($datarray);
2797 if (Item::isTooOld($datarray)) {
2798 Logger::info('Status is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2802 $message_id = Item::insert($datarray);
2804 self::sendParticipation($contact, $datarray);
2807 Logger::info("Stored item ".$datarray["guid"]." with message id ".$message_id);
2808 if ($datarray['uid'] == 0) {
2809 Item::distribute($message_id);
2817 /* ************************************************************************************** *
2818 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2819 * ************************************************************************************** */
2822 * returnes the handle of a contact
2824 * @param array $contact contact array
2826 * @return string the handle in the format user@domain.tld
2827 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2829 private static function myHandle(array $contact)
2831 if (!empty($contact["addr"])) {
2832 return $contact["addr"];
2835 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2836 // So - just in case - we build the the address here.
2837 if ($contact["nickname"] != "") {
2838 $nick = $contact["nickname"];
2840 $nick = $contact["nick"];
2843 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
2848 * Creates the data for a private message in the new format
2850 * @param string $msg The message that is to be transmitted
2851 * @param array $user The record of the sender
2852 * @param array $contact Target of the communication
2853 * @param string $prvkey The private key of the sender
2854 * @param string $pubkey The public key of the receiver
2856 * @return string The encrypted data
2857 * @throws \Exception
2859 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
2861 Logger::debug("Message: ".$msg);
2863 // without a public key nothing will work
2865 Logger::notice("pubkey missing: contact id: ".$contact["id"]);
2869 $aes_key = random_bytes(32);
2870 $b_aes_key = base64_encode($aes_key);
2871 $iv = random_bytes(16);
2872 $b_iv = base64_encode($iv);
2874 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2876 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
2878 $encrypted_key_bundle = "";
2879 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
2883 $json_object = json_encode(
2884 ["aes_key" => base64_encode($encrypted_key_bundle),
2885 "encrypted_magic_envelope" => base64_encode($ciphertext)]
2888 return $json_object;
2892 * Creates the envelope for the "fetch" endpoint and for the new format
2894 * @param string $msg The message that is to be transmitted
2895 * @param array $user The record of the sender
2897 * @return string The envelope
2898 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2900 public static function buildMagicEnvelope($msg, array $user)
2902 $b64url_data = Strings::base64UrlEncode($msg);
2903 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
2905 $key_id = Strings::base64UrlEncode(self::myHandle($user));
2906 $type = "application/xml";
2907 $encoding = "base64url";
2908 $alg = "RSA-SHA256";
2909 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
2911 // Fallback if the private key wasn't transmitted in the expected field
2912 if ($user['uprvkey'] == "") {
2913 $user['uprvkey'] = $user['prvkey'];
2916 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
2917 $sig = Strings::base64UrlEncode($signature);
2919 $xmldata = ["me:env" => ["me:data" => $data,
2920 "@attributes" => ["type" => $type],
2921 "me:encoding" => $encoding,
2924 "@attributes2" => ["key_id" => $key_id]]];
2926 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
2928 return XML::fromArray($xmldata, $xml, false, $namespaces);
2932 * Create the envelope for a message
2934 * @param string $msg The message that is to be transmitted
2935 * @param array $user The record of the sender
2936 * @param array $contact Target of the communication
2937 * @param string $prvkey The private key of the sender
2938 * @param string $pubkey The public key of the receiver
2939 * @param bool $public Is the message public?
2941 * @return string The message that will be transmitted to other servers
2942 * @throws \Exception
2944 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
2946 // The message is put into an envelope with the sender's signature
2947 $envelope = self::buildMagicEnvelope($msg, $user);
2949 // Private messages are put into a second envelope, encrypted with the receivers public key
2951 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
2958 * Creates a signature for a message
2960 * @param array $owner the array of the owner of the message
2961 * @param array $message The message that is to be signed
2963 * @return string The signature
2965 private static function signature($owner, $message)
2968 unset($sigmsg["author_signature"]);
2969 unset($sigmsg["parent_author_signature"]);
2971 $signed_text = implode(";", $sigmsg);
2973 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
2977 * Transmit a message to a target server
2979 * @param array $owner the array of the item owner
2980 * @param array $contact Target of the communication
2981 * @param string $envelope The message that is to be transmitted
2982 * @param bool $public_batch Is it a public post?
2983 * @param string $guid message guid
2985 * @return int Result of the transmission
2986 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2987 * @throws \ImagickException
2989 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
2991 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
2996 $logid = Strings::getRandomHex(4);
2998 // We always try to use the data from the fcontact table.
2999 // This is important for transmitting data to Friendica servers.
3000 if (!empty($contact['addr'])) {
3001 $fcontact = FContact::getByURL($contact['addr']);
3002 if (!empty($fcontact)) {
3003 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3007 if (empty($dest_url)) {
3008 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3012 Logger::notice("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3016 Logger::notice("transmit: ".$logid."-".$guid." ".$dest_url);
3018 if (!intval(DI::config()->get("system", "diaspora_test"))) {
3019 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3021 $postResult = DI::httpClient()->post($dest_url . "/", $envelope, ['Content-Type' => $content_type]);
3022 $return_code = $postResult->getReturnCode();
3024 Logger::notice("test_mode");
3028 Logger::notice("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3030 return $return_code ? $return_code : -1;
3035 * Build the post xml
3037 * @param string $type The message type
3038 * @param array $message The message data
3040 * @return string The post XML
3042 public static function buildPostXml($type, $message)
3044 $data = [$type => $message];
3046 return XML::fromArray($data, $xml);
3050 * Builds and transmit messages
3052 * @param array $owner the array of the item owner
3053 * @param array $contact Target of the communication
3054 * @param string $type The message type
3055 * @param array $message The message data
3056 * @param bool $public_batch Is it a public post?
3057 * @param string $guid message guid
3059 * @return int Result of the transmission
3060 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3061 * @throws \ImagickException
3063 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3065 $msg = self::buildPostXml($type, $message);
3067 // Fallback if the private key wasn't transmitted in the expected field
3068 if (empty($owner['uprvkey'])) {
3069 $owner['uprvkey'] = $owner['prvkey'];
3072 // When sending content to Friendica contacts using the Diaspora protocol
3073 // we have to fetch the public key from the fcontact.
3074 // This is due to the fact that legacy DFRN had unique keys for every contact.
3075 $pubkey = $contact['pubkey'];
3076 if (!empty($contact['addr'])) {
3077 $fcontact = FContact::getByURL($contact['addr']);
3078 if (!empty($fcontact)) {
3079 $pubkey = $fcontact['pubkey'];
3082 // The "addr" field should always be filled.
3083 // If this isn't the case, it will raise a notice some lines later.
3084 // And in the log we will see where it came from and we can handle it there.
3085 Logger::notice('Empty addr', ['contact' => $contact ?? [], 'callstack' => System::callstack(20)]);
3088 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
3090 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3092 Logger::info('Transmitted message', ['owner' => $owner['uid'], 'target' => $contact['addr'], 'type' => $type, 'guid' => $guid, 'result' => $return_code]);
3094 return $return_code;
3098 * sends a participation (Used to get all further updates)
3100 * @param array $contact Target of the communication
3101 * @param array $item Item array
3103 * @return int The result of the transmission
3104 * @throws \Exception
3106 private static function sendParticipation(array $contact, array $item)
3108 // Don't send notifications for private postings
3109 if ($item['private'] == Item::PRIVATE) {
3113 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3115 $result = DI::cache()->get($cachekey);
3116 if (!is_null($result)) {
3120 // Fetch some user id to have a valid handle to transmit the participation.
3121 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3122 // If the item belongs to a user, we take this user id.
3123 if ($item['uid'] == 0) {
3124 // @todo Possibly use an administrator account?
3125 $condition = ['verified' => true, 'blocked' => false,
3126 'account_removed' => false, 'account_expired' => false, 'account-type' => User::ACCOUNT_TYPE_PERSON];
3127 $first_user = DBA::selectFirst('user', ['uid'], $condition, ['order' => ['uid']]);
3128 $owner = User::getOwnerDataById($first_user['uid']);
3130 $owner = User::getOwnerDataById($item['uid']);
3133 $author = self::myHandle($owner);
3135 $message = ["author" => $author,
3136 "guid" => System::createUUID(),
3137 "parent_type" => "Post",
3138 "parent_guid" => $item["guid"]];
3140 Logger::info("Send participation for ".$item["guid"]." by ".$author);
3142 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3143 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3145 return self::buildAndTransmit($owner, $contact, "participation", $message);
3149 * sends an account migration
3151 * @param array $owner the array of the item owner
3152 * @param array $contact Target of the communication
3153 * @param int $uid User ID
3155 * @return int The result of the transmission
3156 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3157 * @throws \ImagickException
3159 public static function sendAccountMigration(array $owner, array $contact, $uid)
3161 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3162 $profile = self::createProfileData($uid);
3164 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3165 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3167 $message = ["author" => $old_handle,
3168 "profile" => $profile,
3169 "signature" => $signature];
3171 Logger::info('Send account migration', ['msg' => $message]);
3173 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3177 * Sends a "share" message
3179 * @param array $owner the array of the item owner
3180 * @param array $contact Target of the communication
3182 * @return int The result of the transmission
3183 * @throws \Exception
3185 public static function sendShare(array $owner, array $contact)
3188 * @todo support the different possible combinations of "following" and "sharing"
3189 * Currently, Diaspora only interprets the "sharing" field
3191 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3195 switch ($contact["rel"]) {
3196 case Contact::FRIEND:
3200 case Contact::SHARING:
3204 case Contact::FOLLOWER:
3210 $message = ["author" => self::myHandle($owner),
3211 "recipient" => $contact["addr"],
3212 "following" => "true",
3213 "sharing" => "true"];
3215 Logger::info('Send share', ['msg' => $message]);
3217 return self::buildAndTransmit($owner, $contact, "contact", $message);
3221 * sends an "unshare"
3223 * @param array $owner the array of the item owner
3224 * @param array $contact Target of the communication
3226 * @return int The result of the transmission
3227 * @throws \Exception
3229 public static function sendUnshare(array $owner, array $contact)
3231 $message = ["author" => self::myHandle($owner),
3232 "recipient" => $contact["addr"],
3233 "following" => "false",
3234 "sharing" => "false"];
3236 Logger::info('Send unshare', ['msg' => $message]);
3238 return self::buildAndTransmit($owner, $contact, "contact", $message);
3242 * Checks a message body if it is a reshare
3244 * @param string $body The message body that is to be check
3245 * @param bool $complete Should it be a complete check or a simple check?
3247 * @return array|bool Reshare details or "false" if no reshare
3248 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3249 * @throws \ImagickException
3251 public static function isReshare($body, $complete = true)
3253 $body = trim($body);
3255 $reshared = Item::getShareArray(['body' => $body]);
3256 if (empty($reshared)) {
3260 // Skip if it isn't a pure repeated messages
3261 // Does it start with a share?
3262 if (!empty($reshared['comment']) && $complete) {
3266 if (!empty($reshared['guid']) && $complete) {
3267 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3268 $item = Post::selectFirst(['contact-id'], $condition);
3269 if (DBA::isResult($item)) {
3271 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3272 $ret["root_guid"] = $reshared['guid'];
3274 } elseif ($complete) {
3275 // We are resharing something that isn't a DFRN or Diaspora post.
3276 // So we have to return "false" on "$complete" to not trigger a reshare.
3279 } elseif (empty($reshared['guid']) && $complete) {
3285 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3286 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3287 if (!empty($contact['addr'])) {
3288 $ret['root_handle'] = $contact['addr'];
3292 if (empty($ret) && !$complete) {
3300 * Create an event array
3302 * @param integer $event_id The id of the event
3304 * @return array with event data
3305 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3307 private static function buildEvent($event_id)
3309 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
3310 if (!DBA::isResult($event)) {
3316 $owner = User::getOwnerDataById($event['uid']);
3321 $eventdata['author'] = self::myHandle($owner);
3323 if ($event['guid']) {
3324 $eventdata['guid'] = $event['guid'];
3327 $mask = DateTimeFormat::ATOM;
3329 /// @todo - establish "all day" events in Friendica
3330 $eventdata["all_day"] = "false";
3332 $eventdata['timezone'] = 'UTC';
3334 if ($event['start']) {
3335 $eventdata['start'] = DateTimeFormat::utc($event['start'], $mask);
3337 if ($event['finish'] && !$event['nofinish']) {
3338 $eventdata['end'] = DateTimeFormat::utc($event['finish'], $mask);
3340 if ($event['summary']) {
3341 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3343 if ($event['desc']) {
3344 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3346 if ($event['location']) {
3347 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3348 $coord = Map::getCoordinates($event['location']);
3351 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3352 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3353 $location["lat"] = $coord['lat'];
3354 $location["lng"] = $coord['lon'];
3356 $location["lat"] = 0;
3357 $location["lng"] = 0;
3359 $eventdata['location'] = $location;
3366 * Create a post (status message or reshare)
3368 * @param array $item The item that will be exported
3369 * @param array $owner the array of the item owner
3372 * 'type' -> Message type ("status_message" or "reshare")
3373 * 'message' -> Array of XML elements of the status
3374 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3375 * @throws \ImagickException
3377 public static function buildStatus(array $item, array $owner)
3379 $cachekey = "diaspora:buildStatus:".$item['guid'];
3381 $result = DI::cache()->get($cachekey);
3382 if (!is_null($result)) {
3386 $myaddr = self::myHandle($owner);
3388 $public = ($item["private"] == Item::PRIVATE ? "false" : "true");
3389 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3390 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3392 // Detect a share element and do a reshare
3393 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) {
3394 $message = ["author" => $myaddr,
3395 "guid" => $item["guid"],
3396 "created_at" => $created,
3397 "root_author" => $ret["root_handle"],
3398 "root_guid" => $ret["root_guid"],
3399 "provider_display_name" => $item["app"],
3400 "public" => $public];
3404 $title = $item["title"];
3405 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
3407 // Fetch the title from an attached link - if there is one
3408 if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3409 $page_data = BBCode::getAttachmentData($item['body']);
3410 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3411 $title = $page_data['title'];
3415 if ($item['author-link'] != $item['owner-link']) {
3416 $body = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'],
3417 $item['plink'], $item['created']) . $body . '[/share]';
3420 // convert to markdown
3421 $body = html_entity_decode(BBCode::toMarkdown($body));
3424 if (strlen($title)) {
3425 $body = "### ".html_entity_decode($title)."\n\n".$body;
3428 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]);
3429 if (!empty($attachments)) {
3430 $body .= "\n[hr]\n";
3431 foreach ($attachments as $attachment) {
3432 $body .= "[" . $attachment['description'] . "](" . $attachment['url'] . ")\n";
3438 if ($item["location"] != "")
3439 $location["address"] = $item["location"];
3441 if ($item["coord"] != "") {
3442 $coord = explode(" ", $item["coord"]);
3443 $location["lat"] = $coord[0];
3444 $location["lng"] = $coord[1];
3447 $message = ["author" => $myaddr,
3448 "guid" => $item["guid"],
3449 "created_at" => $created,
3450 "edited_at" => $edited,
3451 "public" => $public,
3453 "provider_display_name" => $item["app"],
3454 "location" => $location];
3456 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3457 if (!isset($location["lat"]) || !isset($location["lng"])) {
3458 unset($message["location"]);
3461 if ($item['event-id'] > 0) {
3462 $event = self::buildEvent($item['event-id']);
3463 if (count($event)) {
3464 $message['event'] = $event;
3466 if (!empty($event['location']['address']) &&
3467 !empty($event['location']['lat']) &&
3468 !empty($event['location']['lng'])) {
3469 $message['location'] = $event['location'];
3472 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3473 // $message['text'] = '';
3477 $type = "status_message";
3480 $msg = ["type" => $type, "message" => $message];
3482 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3487 private static function prependParentAuthorMention($body, $profile_url)
3489 $profile = Contact::getByURL($profile_url, false, ['addr', 'name']);
3490 if (!empty($profile['addr'])
3491 && !strstr($body, $profile['addr'])
3492 && !strstr($body, $profile_url)
3494 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3503 * @param array $item The item that will be exported
3504 * @param array $owner the array of the item owner
3505 * @param array $contact Target of the communication
3506 * @param bool $public_batch Is it a public post?
3508 * @return int The result of the transmission
3509 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3510 * @throws \ImagickException
3512 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3514 $status = self::buildStatus($item, $owner);
3516 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3520 * Creates a "like" object
3522 * @param array $item The item that will be exported
3523 * @param array $owner the array of the item owner
3525 * @return array The data for a "like"
3526 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3528 private static function constructLike(array $item, array $owner)
3530 $parent = Post::selectFirst(['guid', 'uri', 'thr-parent'], ['uri' => $item["thr-parent"]]);
3531 if (!DBA::isResult($parent)) {
3535 $target_type = ($parent["uri"] === $parent["thr-parent"] ? "Post" : "Comment");
3537 if ($item['verb'] === Activity::LIKE) {
3539 } elseif ($item['verb'] === Activity::DISLIKE) {
3540 $positive = "false";
3543 return(["author" => self::myHandle($owner),
3544 "guid" => $item["guid"],
3545 "parent_guid" => $parent["guid"],
3546 "parent_type" => $target_type,
3547 "positive" => $positive,
3548 "author_signature" => ""]);
3552 * Creates an "EventParticipation" object
3554 * @param array $item The item that will be exported
3555 * @param array $owner the array of the item owner
3557 * @return array The data for an "EventParticipation"
3558 * @throws \Exception
3560 private static function constructAttend(array $item, array $owner)
3562 $parent = Post::selectFirst(['guid'], ['uri' => $item['thr-parent']]);
3563 if (!DBA::isResult($parent)) {
3567 switch ($item['verb']) {
3568 case Activity::ATTEND:
3569 $attend_answer = 'accepted';
3571 case Activity::ATTENDNO:
3572 $attend_answer = 'declined';
3574 case Activity::ATTENDMAYBE:
3575 $attend_answer = 'tentative';
3578 Logger::notice('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3582 return(["author" => self::myHandle($owner),
3583 "guid" => $item["guid"],
3584 "parent_guid" => $parent["guid"],
3585 "status" => $attend_answer,
3586 "author_signature" => ""]);
3590 * Creates the object for a comment
3592 * @param array $item The item that will be exported
3593 * @param array $owner the array of the item owner
3595 * @return array|false The data for a comment
3596 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3598 private static function constructComment(array $item, array $owner)
3600 $cachekey = "diaspora:constructComment:".$item['guid'];
3602 $result = DI::cache()->get($cachekey);
3603 if (!is_null($result)) {
3607 $toplevel_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3608 if (!DBA::isResult($toplevel_item)) {
3609 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3613 $thread_parent_item = $toplevel_item;
3614 if ($item['thr-parent'] != $item['parent-uri']) {
3615 $thread_parent_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3618 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
3620 // The replied to autor mention is prepended for clarity if:
3621 // - Item replied isn't yours
3622 // - Item is public or explicit mentions are disabled
3623 // - Implicit mentions are enabled
3625 $item['author-id'] != $thread_parent_item['author-id']
3626 && ($thread_parent_item['gravity'] != GRAVITY_PARENT)
3627 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3628 && !DI::config()->get('system', 'disable_implicit_mentions')
3630 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3633 $text = html_entity_decode(BBCode::toMarkdown($body));
3634 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3635 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3638 "author" => self::myHandle($owner),
3639 "guid" => $item["guid"],
3640 "created_at" => $created,
3641 "edited_at" => $edited,
3642 "parent_guid" => $toplevel_item["guid"],
3644 "author_signature" => ""
3647 // Send the thread parent guid only if it is a threaded comment
3648 if ($item['thr-parent'] != $item['parent-uri']) {
3649 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3652 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3658 * Send a like or a comment
3660 * @param array $item The item that will be exported
3661 * @param array $owner the array of the item owner
3662 * @param array $contact Target of the communication
3663 * @param bool $public_batch Is it a public post?
3665 * @return int The result of the transmission
3666 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3667 * @throws \ImagickException
3669 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3671 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3672 $message = self::constructAttend($item, $owner);
3673 $type = "event_participation";
3674 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3675 $message = self::constructLike($item, $owner);
3677 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3678 $message = self::constructComment($item, $owner);
3682 if (empty($message)) {
3686 $message["author_signature"] = self::signature($owner, $message);
3688 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3692 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3694 * @param array $item The item that will be exported
3695 * @param array $owner the array of the item owner
3696 * @param array $contact Target of the communication
3697 * @param bool $public_batch Is it a public post?
3699 * @return int The result of the transmission
3700 * @throws \Exception
3702 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3704 if ($item["deleted"]) {
3705 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3706 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3712 Logger::info("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")");
3714 $msg = json_decode($item['signed_text'], true);
3717 if (is_array($msg)) {
3718 foreach ($msg as $field => $data) {
3719 if (!$item["deleted"]) {
3720 if ($field == "diaspora_handle") {
3723 if ($field == "target_type") {
3724 $field = "parent_type";
3728 $message[$field] = $data;
3731 Logger::info("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text']);
3734 $message["parent_author_signature"] = self::signature($owner, $message);
3736 Logger::info('Relayed data', ['msg' => $message]);
3738 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3742 * Sends a retraction (deletion) of a message, like or comment
3744 * @param array $item The item that will be exported
3745 * @param array $owner the array of the item owner
3746 * @param array $contact Target of the communication
3747 * @param bool $public_batch Is it a public post?
3748 * @param bool $relay Is the retraction transmitted from a relay?
3750 * @return int The result of the transmission
3751 * @throws \Exception
3753 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
3755 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3757 $msg_type = "retraction";
3759 if ($item['gravity'] == GRAVITY_PARENT) {
3760 $target_type = "Post";
3761 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3762 $target_type = "Like";
3764 $target_type = "Comment";
3767 $message = ["author" => $itemaddr,
3768 "target_guid" => $item['guid'],
3769 "target_type" => $target_type];
3771 Logger::info('Got message', ['msg' => $message]);
3773 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3779 * @param array $item The item that will be exported
3780 * @param array $owner The owner
3781 * @param array $contact Target of the communication
3783 * @return int The result of the transmission
3784 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3785 * @throws \ImagickException
3787 public static function sendMail(array $item, array $owner, array $contact)
3789 $myaddr = self::myHandle($owner);
3791 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
3792 if (!DBA::isResult($cnv)) {
3793 Logger::notice("conversation not found.");
3797 $body = BBCode::toMarkdown($item["body"]);
3798 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3801 "author" => $myaddr,
3802 "guid" => $item["guid"],
3803 "conversation_guid" => $cnv["guid"],
3805 "created_at" => $created,
3808 if ($item["reply"]) {
3813 "author" => $cnv["creator"],
3814 "guid" => $cnv["guid"],
3815 "subject" => $cnv["subject"],
3816 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3817 "participants" => $cnv["recips"],
3821 $type = "conversation";
3824 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
3828 * Split a name into first name and last name
3830 * @param string $name The name
3832 * @return array The array with "first" and "last"
3834 public static function splitName($name) {
3835 $name = trim($name);
3837 // Is the name longer than 64 characters? Then cut the rest of it.
3838 if (strlen($name) > 64) {
3839 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3840 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3842 $name = substr($name, 0, 64);
3846 // Take the first word as first name
3847 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3848 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3849 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3850 return ['first' => $first, 'last' => $last];
3853 // Take the last word as last name
3854 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3855 $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 first 32 characters if there is no space in the first 32 characters
3862 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3863 $first = substr($name, 0, 32);
3864 $last = substr($name, 32);
3865 return ['first' => $first, 'last' => $last];
3868 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3869 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3871 // Check if the last name is longer than 32 characters
3872 if (strlen($last) > 32) {
3873 if (strpos($last, ' ') <= 32) {
3874 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
3876 $last = substr($last, 0, 32);
3880 return ['first' => $first, 'last' => $last];
3884 * Create profile data
3886 * @param int $uid The user id
3888 * @return array The profile data
3889 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3891 private static function createProfileData($uid)
3893 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
3894 if (!DBA::isResult($profile)) {
3898 $handle = $profile["addr"];
3900 $split_name = self::splitName($profile['name']);
3901 $first = $split_name['first'];
3902 $last = $split_name['last'];
3904 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3905 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3906 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3907 $searchable = ($profile['net-publish'] ? 'true' : 'false');
3913 if ($searchable === 'true') {
3916 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
3917 [$year, $month, $day] = sscanf($profile['dob'], '%4d-%2d-%2d');
3921 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
3924 $about = BBCode::toMarkdown($profile['about']);
3926 $location = $profile['location'];
3928 if ($profile['pub_keywords']) {
3929 $kw = str_replace(',', ' ', $profile['pub_keywords']);
3930 $kw = str_replace(' ', ' ', $kw);
3931 $arr = explode(' ', $kw);
3933 for ($x = 0; $x < 5; $x ++) {
3934 if (!empty($arr[$x])) {
3935 $tags .= '#'. trim($arr[$x]) .' ';
3940 $tags = trim($tags);
3943 return ["author" => $handle,
3944 "first_name" => $first,
3945 "last_name" => $last,
3946 "image_url" => $large,
3947 "image_url_medium" => $medium,
3948 "image_url_small" => $small,
3951 "location" => $location,
3952 "searchable" => $searchable,
3954 "tag_string" => $tags];
3958 * Sends profile data
3960 * @param int $uid The user id
3961 * @param bool $recips optional, default false
3963 * @throws \Exception
3965 public static function sendProfile($uid, $recips = false)
3971 $owner = User::getOwnerDataById($uid);
3977 $recips = DBA::selectToArray('contact', [], ['network' => Protocol::DIASPORA, 'uid' => $uid, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
3984 $message = self::createProfileData($uid);
3986 // @ToDo Split this into single worker jobs
3987 foreach ($recips as $recip) {
3988 Logger::info("Send updated profile data for user ".$uid." to contact ".$recip["id"]);
3989 self::buildAndTransmit($owner, $recip, "profile", $message);
3994 * Creates the signature for likes that are created on our system
3996 * @param integer $uid The user of that comment
3997 * @param array $item Item array
3999 * @return array Signed content
4000 * @throws \Exception
4002 public static function createLikeSignature($uid, array $item)
4004 $owner = User::getOwnerDataById($uid);
4005 if (empty($owner)) {
4006 Logger::info('No owner post, so not storing signature');
4010 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4014 $message = self::constructLike($item, $owner);
4015 if ($message === false) {
4019 $message["author_signature"] = self::signature($owner, $message);
4025 * Creates the signature for Comments that are created on our system
4027 * @param array $item Item array
4029 * @return array Signed content
4030 * @throws \Exception
4032 public static function createCommentSignature(array $item)
4034 if (!empty($item['author-link'])) {
4035 $url = $item['author-link'];
4037 $contact = Contact::getById($item['author-id'], ['url']);
4038 if (empty($contact['url'])) {
4039 Logger::warning('Author Contact not found', ['author-id' => $item['author-id']]);
4042 $url = $contact['url'];
4045 $uid = User::getIdForURL($url);
4047 Logger::info('No owner post, so not storing signature', ['url' => $contact['url']]);
4051 $owner = User::getOwnerDataById($uid);
4052 if (empty($owner)) {
4053 Logger::info('No owner post, so not storing signature');
4057 // This is only needed for the automated tests
4058 if (empty($owner['uprvkey'])) {
4062 $message = self::constructComment($item, $owner);
4063 if ($message === false) {
4067 $message["author_signature"] = self::signature($owner, $message);
4072 public static function performReshare(int $UriId, int $uid)
4074 $fields = ['uri-id', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
4075 $item = Post::selectFirst($fields, ['uri-id' => $UriId, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
4076 if (!DBA::isResult($item)) {
4080 if (strpos($item['body'], '[/share]') !== false) {
4081 $pos = strpos($item['body'], '[share');
4082 $post = substr($item['body'], $pos);
4084 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
4086 if (!empty($item['title'])) {
4087 $post .= '[h3]' . $item['title'] . "[/h3]\n";
4090 $post .= $item['body'];
4091 $post .= '[/share]';
4094 $owner = User::getOwnerDataById($uid);
4095 $author = Contact::getPublicIdByUserId($uid);
4099 'verb' => Activity::POST,
4100 'contact-id' => $owner['id'],
4101 'author-id' => $author,
4102 'owner-id' => $author,
4104 'allow_cid' => $owner['allow_cid'] ?? '',
4105 'allow_gid' => $owner['allow_gid']?? '',
4106 'deny_cid' => $owner['deny_cid'] ?? '',
4107 'deny_gid' => $owner['deny_gid'] ?? '',
4110 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
4111 $item['private'] = Item::PRIVATE;
4112 } elseif (DI::pConfig()->get($uid, 'system', 'unlisted')) {
4113 $item['private'] = Item::UNLISTED;
4115 $item['private'] = Item::PUBLIC;
4118 // Don't trigger the addons
4119 $item['api_source'] = false;
4121 return Item::insert($item, true);