3 * @copyright Copyright (C) 2010-2021, 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\PageInfo;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Cache\Duration;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\System;
32 use Friendica\Core\Worker;
33 use Friendica\Database\DBA;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Conversation;
37 use Friendica\Model\FContact;
38 use Friendica\Model\GServer;
39 use Friendica\Model\Item;
40 use Friendica\Model\ItemURI;
41 use Friendica\Model\Mail;
42 use Friendica\Model\Post;
43 use Friendica\Model\Tag;
44 use Friendica\Model\User;
45 use Friendica\Network\Probe;
46 use Friendica\Util\Crypto;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Map;
49 use Friendica\Util\Network;
50 use Friendica\Util\Strings;
51 use Friendica\Util\XML;
52 use Friendica\Worker\Delivery;
56 * This class contain functions to create and send Diaspora XML files
61 * Return a list of participating contacts for a thread
63 * This is used for the participation feature.
64 * One of the parameters is a contact array.
65 * This is done to avoid duplicates.
67 * @param array $item Item that is about to be delivered
68 * @param array $contacts The previously fetched contacts
70 * @return array of relay servers
73 public static function participantsForThread(array $item, array $contacts)
75 if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
76 Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]);
80 $items = Post::select(['author-id', 'author-link', 'parent-author-link', 'parent-guid', 'guid'],
81 ['parent' => $item['parent'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
82 while ($item = Post::fetch($items)) {
83 $contact = DBA::selectFirst('contact', ['id', 'url', 'name', 'protocol', 'batch', 'network'],
84 ['id' => $item['author-id']]);
85 if (!DBA::isResult($contact) || empty($contact['batch']) ||
86 ($contact['network'] != Protocol::DIASPORA) ||
87 Strings::compareLink($item['parent-author-link'], $item['author-link'])) {
92 foreach ($contacts as $entry) {
93 if ($entry['batch'] == $contact['batch']) {
99 Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]);
100 $contacts[] = $contact;
109 * verify the envelope and return the verified data
111 * @param string $envelope The magic envelope
113 * @return string verified data
114 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
115 * @throws \ImagickException
117 private static function verifyMagicEnvelope($envelope)
119 $basedom = XML::parseString($envelope, true);
121 if (!is_object($basedom)) {
122 Logger::log("Envelope is no XML file");
126 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
128 if (sizeof($children) == 0) {
129 Logger::log("XML has no children");
135 $data = Strings::base64UrlDecode($children->data);
136 $type = $children->data->attributes()->type[0];
138 $encoding = $children->encoding;
140 $alg = $children->alg;
142 $sig = Strings::base64UrlDecode($children->sig);
143 $key_id = $children->sig->attributes()->key_id[0];
145 $handle = Strings::base64UrlDecode($key_id);
148 $b64url_data = Strings::base64UrlEncode($data);
149 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
151 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
154 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
158 $key = self::key($handle);
160 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
164 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
166 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
174 * encrypts data via AES
176 * @param string $key The AES key
177 * @param string $iv The IV (is used for CBC encoding)
178 * @param string $data The data that is to be encrypted
180 * @return string encrypted data
182 private static function aesEncrypt($key, $iv, $data)
184 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
188 * decrypts data via AES
190 * @param string $key The AES key
191 * @param string $iv The IV (is used for CBC encoding)
192 * @param string $encrypted The encrypted data
194 * @return string decrypted data
196 private static function aesDecrypt($key, $iv, $encrypted)
198 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
202 * Decodes incoming Diaspora message in the new format
204 * @param string $raw raw post message
205 * @param string $privKey The private key of the importer
206 * @param boolean $no_exit Don't do an http exit on error
209 * 'message' -> decoded Diaspora XML message
210 * 'author' -> author diaspora handle
211 * 'key' -> author public key (converted to pkcs#8)
212 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
213 * @throws \ImagickException
215 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
217 $data = json_decode($raw);
219 // Is it a private post? Then decrypt the outer Salmon
220 if (is_object($data)) {
221 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
222 $ciphertext = base64_decode($data->encrypted_magic_envelope);
224 $outer_key_bundle = '';
225 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
226 $j_outer_key_bundle = json_decode($outer_key_bundle);
228 if (!is_object($j_outer_key_bundle)) {
229 Logger::log('Outer Salmon did not verify. Discarding.');
233 throw new \Friendica\Network\HTTPException\BadRequestException();
237 $outer_iv = base64_decode($j_outer_key_bundle->iv);
238 $outer_key = base64_decode($j_outer_key_bundle->key);
240 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
245 $basedom = XML::parseString($xml, true);
247 if (!is_object($basedom)) {
248 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
252 throw new \Friendica\Network\HTTPException\BadRequestException();
256 $base = $basedom->children(ActivityNamespace::SALMON_ME);
258 // Not sure if this cleaning is needed
259 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
261 // Build the signed data
262 $type = $base->data[0]->attributes()->type[0];
263 $encoding = $base->encoding;
265 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
267 // This is the signature
268 $signature = Strings::base64UrlDecode($base->sig);
270 // Get the senders' public key
271 $key_id = $base->sig[0]->attributes()->key_id[0];
272 $author_addr = base64_decode($key_id);
273 if ($author_addr == '') {
274 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
278 throw new \Friendica\Network\HTTPException\BadRequestException();
282 $key = self::key($author_addr);
284 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
288 throw new \Friendica\Network\HTTPException\BadRequestException();
292 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
294 Logger::log('Message did not verify. Discarding.');
298 throw new \Friendica\Network\HTTPException\BadRequestException();
302 return ['message' => (string)Strings::base64UrlDecode($base->data),
303 'author' => XML::unescape($author_addr),
304 'key' => (string)$key];
308 * Decodes incoming Diaspora message in the deprecated format
310 * @param string $xml urldecoded Diaspora salmon
311 * @param string $privKey The private key of the importer
314 * 'message' -> decoded Diaspora XML message
315 * 'author' -> author diaspora handle
316 * 'key' -> author public key (converted to pkcs#8)
317 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
318 * @throws \ImagickException
320 public static function decode(string $xml, string $privKey = '')
323 $basedom = XML::parseString($xml);
325 if (!is_object($basedom)) {
326 Logger::notice('XML is not parseable.');
329 $children = $basedom->children('https://joindiaspora.com/protocol');
331 $inner_aes_key = null;
334 if ($children->header) {
336 $author_link = str_replace('acct:', '', $children->header->author_id);
338 // This happens with posts from a relais
339 if (empty($privKey)) {
340 Logger::info('This is no private post in the old format');
344 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
346 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
347 $ciphertext = base64_decode($encrypted_header->ciphertext);
349 $outer_key_bundle = '';
350 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
352 $j_outer_key_bundle = json_decode($outer_key_bundle);
354 $outer_iv = base64_decode($j_outer_key_bundle->iv);
355 $outer_key = base64_decode($j_outer_key_bundle->key);
357 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
359 Logger::info('decrypted', ['data' => $decrypted]);
360 $idom = XML::parseString($decrypted);
362 $inner_iv = base64_decode($idom->iv);
363 $inner_aes_key = base64_decode($idom->aes_key);
365 $author_link = str_replace('acct:', '', $idom->author_id);
368 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
370 // figure out where in the DOM tree our data is hiding
373 if ($dom->provenance->data) {
374 $base = $dom->provenance;
375 } elseif ($dom->env->data) {
377 } elseif ($dom->data) {
382 Logger::log('unable to locate salmon data in xml');
383 throw new \Friendica\Network\HTTPException\BadRequestException();
387 // Stash the signature away for now. We have to find their key or it won't be good for anything.
388 $signature = Strings::base64UrlDecode($base->sig);
392 // strip whitespace so our data element will return to one big base64 blob
393 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
396 // stash away some other stuff for later
398 $type = $base->data[0]->attributes()->type[0];
399 $keyhash = $base->sig[0]->attributes()->keyhash[0];
400 $encoding = $base->encoding;
404 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
408 $data = Strings::base64UrlDecode($data);
412 $inner_decrypted = $data;
414 // Decode the encrypted blob
415 $inner_encrypted = base64_decode($data);
416 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
420 Logger::log('Could not retrieve author URI.');
421 throw new \Friendica\Network\HTTPException\BadRequestException();
423 // Once we have the author URI, go to the web and try to find their public key
424 // (first this will look it up locally if it is in the fcontact cache)
425 // This will also convert diaspora public key from pkcs#1 to pkcs#8
427 Logger::log('Fetching key for '.$author_link);
428 $key = self::key($author_link);
431 Logger::log('Could not retrieve author key.');
432 throw new \Friendica\Network\HTTPException\BadRequestException();
435 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
438 Logger::log('Message did not verify. Discarding.');
439 throw new \Friendica\Network\HTTPException\BadRequestException();
442 Logger::log('Message verified.');
444 return ['message' => (string)$inner_decrypted,
445 'author' => XML::unescape($author_link),
446 'key' => (string)$key];
451 * Dispatches public messages and find the fitting receivers
453 * @param array $msg The post that will be dispatched
454 * @param bool $fetched The message had been fetched (default "false")
456 * @return int The message id of the generated message, "true" or "false" if there was an error
457 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
458 * @throws \ImagickException
460 public static function dispatchPublic($msg, bool $fetched = false)
462 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
464 Logger::log("diaspora is disabled");
468 if (!($fields = self::validPosting($msg))) {
469 Logger::log("Invalid posting");
473 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
474 $success = self::dispatch($importer, $msg, $fields, $fetched);
480 * Dispatches the different message types to the different functions
482 * @param array $importer Array of the importer user
483 * @param array $msg The post that will be dispatched
484 * @param SimpleXMLElement $fields SimpleXML object that contains the message
485 * @param bool $fetched The message had been fetched (default "false")
487 * @return int The message id of the generated message, "true" or "false" if there was an error
488 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
489 * @throws \ImagickException
491 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null, bool $fetched = false)
493 // The sender is the handle of the contact that sent the message.
494 // This will often be different with relayed messages (for example "like" and "comment")
495 $sender = $msg["author"];
497 // This is only needed for private postings since this is already done for public ones before
498 if (is_null($fields)) {
500 if (!($fields = self::validPosting($msg))) {
501 Logger::log("Invalid posting");
508 $type = $fields->getName();
510 Logger::info('Received message', ['type' => $type, 'sender' => $sender, 'user' => $importer["uid"]]);
513 case "account_migration":
515 Logger::log('Message with type ' . $type . ' is not private, quitting.');
518 return self::receiveAccountMigration($importer, $fields);
520 case "account_deletion":
521 return self::receiveAccountDeletion($fields);
524 return self::receiveComment($importer, $sender, $fields, $msg["message"], $fetched);
528 Logger::log('Message with type ' . $type . ' is not private, quitting.');
531 return self::receiveContactRequest($importer, $fields);
535 Logger::log('Message with type ' . $type . ' is not private, quitting.');
538 return self::receiveConversation($importer, $msg, $fields);
541 return self::receiveLike($importer, $sender, $fields, $fetched);
545 Logger::log('Message with type ' . $type . ' is not private, quitting.');
548 return self::receiveMessage($importer, $fields);
550 case "participation":
552 Logger::log('Message with type ' . $type . ' is not private, quitting.');
555 return self::receiveParticipation($importer, $fields, $fetched);
557 case "photo": // Not implemented
558 return self::receivePhoto($importer, $fields);
560 case "poll_participation": // Not implemented
561 return self::receivePollParticipation($importer, $fields);
565 Logger::log('Message with type ' . $type . ' is not private, quitting.');
568 return self::receiveProfile($importer, $fields);
571 return self::receiveReshare($importer, $fields, $msg["message"], $fetched);
574 return self::receiveRetraction($importer, $sender, $fields);
576 case "status_message":
577 return self::receiveStatusMessage($importer, $fields, $msg["message"], $fetched);
580 Logger::log("Unknown message type ".$type);
586 * Checks if a posting is valid and fetches the data fields.
588 * This function does not only check the signature.
589 * It also does the conversion between the old and the new diaspora format.
591 * @param array $msg Array with the XML, the sender handle and the sender signature
593 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
594 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
595 * @throws \ImagickException
597 private static function validPosting($msg)
599 $data = XML::parseString($msg["message"]);
601 if (!is_object($data)) {
602 Logger::info('No valid XML', ['message' => $msg['message']]);
606 // Is this the new or the old version?
607 if ($data->getName() == "XML") {
609 foreach ($data->post->children() as $child) {
617 $type = $element->getName();
620 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
622 // All retractions are handled identically from now on.
623 // In the new version there will only be "retraction".
624 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
625 $type = "retraction";
627 if ($type == "request") {
631 $fields = new SimpleXMLElement("<".$type."/>");
634 $author_signature = null;
635 $parent_author_signature = null;
637 foreach ($element->children() as $fieldname => $entry) {
639 // Translation for the old XML structure
640 if ($fieldname == "diaspora_handle") {
641 $fieldname = "author";
643 if ($fieldname == "participant_handles") {
644 $fieldname = "participants";
646 if (in_array($type, ["like", "participation"])) {
647 if ($fieldname == "target_type") {
648 $fieldname = "parent_type";
651 if ($fieldname == "sender_handle") {
652 $fieldname = "author";
654 if ($fieldname == "recipient_handle") {
655 $fieldname = "recipient";
657 if ($fieldname == "root_diaspora_id") {
658 $fieldname = "root_author";
660 if ($type == "status_message") {
661 if ($fieldname == "raw_message") {
665 if ($type == "retraction") {
666 if ($fieldname == "post_guid") {
667 $fieldname = "target_guid";
669 if ($fieldname == "type") {
670 $fieldname = "target_type";
675 if (($fieldname == "author_signature") && ($entry != "")) {
676 $author_signature = base64_decode($entry);
677 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
678 $parent_author_signature = base64_decode($entry);
679 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
680 if ($signed_data != "") {
684 $signed_data .= $entry;
686 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
687 || ($orig_type == "relayable_retraction")
689 XML::copy($entry, $fields, $fieldname);
693 // This is something that shouldn't happen at all.
694 if (in_array($type, ["status_message", "reshare", "profile"])) {
695 if ($msg["author"] != $fields->author) {
696 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
701 // Only some message types have signatures. So we quit here for the other types.
702 if (!in_array($type, ["comment", "like"])) {
705 // No author_signature? This is a must, so we quit.
706 if (!isset($author_signature)) {
707 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
711 if (isset($parent_author_signature)) {
712 $key = self::key($msg["author"]);
714 Logger::info('No key found for parent', ['author' => $msg["author"]]);
718 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
719 Logger::log("No valid parent author signature for parent author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$parent_author_signature, Logger::DEBUG);
724 $key = self::key($fields->author);
726 Logger::info('No key found', ['author' => $fields->author]);
730 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
731 Logger::log("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, Logger::DEBUG);
739 * Fetches the public key for a given handle
741 * @param string $handle The handle
743 * @return string The public key
744 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
745 * @throws \ImagickException
747 private static function key($handle)
749 $handle = strval($handle);
751 Logger::log("Fetching diaspora key for: ".$handle);
753 $r = FContact::getByURL($handle);
762 * get a handle (user@domain.tld) from a given contact id
764 * @param int $contact_id The id in the contact table
765 * @param int $pcontact_id The id in the contact table (Used for the public contact)
767 * @return string the handle
770 private static function handleFromContact($contact_id, $pcontact_id = 0)
774 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
776 if ($pcontact_id != 0) {
777 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
779 if (DBA::isResult($contact) && !empty($contact["addr"])) {
780 return strtolower($contact["addr"]);
785 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
789 if (DBA::isResult($r)) {
792 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
794 if ($contact['addr'] != "") {
795 $handle = $contact['addr'];
797 $baseurl_start = strpos($contact['url'], '://') + 3;
798 // allows installations in a subdirectory--not sure how Diaspora will handle
799 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
800 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
801 $handle = $contact['nick'].'@'.$baseurl;
805 return strtolower($handle);
809 * Get a contact id for a given handle
811 * @todo Move to Friendica\Model\Contact
813 * @param int $uid The user id
814 * @param string $handle The handle in the format user@domain.tld
816 * @return array Contact data
817 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
818 * @throws \ImagickException
820 private static function contactByHandle($uid, $handle)
822 return Contact::getByURL($handle, null, [], $uid);
826 * Checks if the given contact url does support ActivityPub
828 * @param string $url profile url
829 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
831 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
832 * @throws \ImagickException
834 public static function isSupportedByContactUrl($url, $update = null)
836 return !empty(FContact::getByURL($url, $update));
840 * Check if posting is allowed for this contact
842 * @param array $importer Array of the importer user
843 * @param array $contact The contact that is checked
844 * @param bool $is_comment Is the check for a comment?
846 * @return bool is the contact allowed to post?
848 private static function postAllow(array $importer, array $contact, $is_comment = false)
851 * Perhaps we were already sharing with this person. Now they're sharing with us.
852 * That makes us friends.
853 * Normally this should have handled by getting a request - but this could get lost
855 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
856 // It is not removed by now. Possibly the code is needed?
857 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
860 // array('rel' => Contact::FRIEND, 'writable' => true),
861 // array('id' => $contact["id"], 'uid' => $contact["uid"])
864 // $contact["rel"] = Contact::FRIEND;
865 // Logger::log("defining user ".$contact["nick"]." as friend");
868 // Contact server is blocked
869 if (Network::isUrlBlocked($contact['url'])) {
871 // We don't seem to like that person
872 } elseif ($contact["blocked"]) {
873 // Maybe blocked, don't accept.
875 // We are following this person?
876 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
877 // Yes, then it is fine.
879 // Is it a post to a community?
880 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
883 // Is the message a global user or a comment?
884 } elseif (($importer["uid"] == 0) || $is_comment) {
885 // Messages for the global users and comments are always accepted
893 * Fetches the contact id for a handle and checks if posting is allowed
895 * @param array $importer Array of the importer user
896 * @param string $handle The checked handle in the format user@domain.tld
897 * @param bool $is_comment Is the check for a comment?
899 * @return array The contact data
902 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
904 $contact = self::contactByHandle($importer["uid"], $handle);
906 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
907 // If a contact isn't found, we accept it anyway if it is a comment
908 if ($is_comment && ($importer["uid"] != 0)) {
909 return self::contactByHandle(0, $handle);
910 } elseif ($is_comment) {
917 if (!self::postAllow($importer, $contact, $is_comment)) {
918 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
925 * Does the message already exists on the system?
927 * @param int $uid The user id
928 * @param string $guid The guid of the message
930 * @return int|bool message id if the message already was stored into the system - or false.
933 private static function messageExists($uid, $guid)
935 $item = Post::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
936 if (DBA::isResult($item)) {
937 Logger::log("message ".$guid." already exists for user ".$uid);
945 * Checks for links to posts in a message
947 * @param array $item The item array
950 private static function fetchGuid(array $item)
952 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
953 preg_replace_callback(
955 function ($match) use ($item) {
956 self::fetchGuidSub($match, $item);
961 preg_replace_callback(
962 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
963 function ($match) use ($item) {
964 self::fetchGuidSub($match, $item);
971 * Checks for relative /people/* links in an item body to match local
972 * contacts or prepends the remote host taken from the author link.
974 * @param string $body The item body to replace links from
975 * @param string $author_link The author link for missing local contact fallback
977 * @return string the replaced string
979 public static function replacePeopleGuid($body, $author_link)
981 $return = preg_replace_callback(
982 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
983 function ($match) use ($author_link) {
985 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
986 // 1 => '0123456789abcdef'
988 $handle = FContact::getUrlByGuid($match[1]);
991 $return = '@[url='.$handle.']'.$match[2].'[/url]';
993 // No local match, restoring absolute remote URL from author scheme and host
994 $author_url = parse_url($author_link);
995 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1007 * sub function of "fetchGuid" which checks for links in messages
1009 * @param array $match array containing a link that has to be checked for a message link
1010 * @param array $item The item array
1012 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1013 * @throws \ImagickException
1015 private static function fetchGuidSub($match, $item)
1017 if (!self::storeByGuid($match[1], $item["author-link"])) {
1018 self::storeByGuid($match[1], $item["owner-link"]);
1023 * Fetches an item with a given guid from a given server
1025 * @param string $guid the message guid
1026 * @param string $server The server address
1027 * @param int $uid The user id of the user
1029 * @return int the message id of the stored message or false
1030 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1031 * @throws \ImagickException
1033 private static function storeByGuid($guid, $server, $uid = 0)
1035 $serverparts = parse_url($server);
1037 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1041 $server = $serverparts["scheme"]."://".$serverparts["host"];
1043 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1045 $msg = self::message($guid, $server);
1051 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1053 // Now call the dispatcher
1054 return self::dispatchPublic($msg, true);
1058 * Fetches a message from a server
1060 * @param string $guid message guid
1061 * @param string $server The url of the server
1062 * @param int $level Endless loop prevention
1065 * 'message' => The message XML
1066 * 'author' => The author handle
1067 * 'key' => The public key of the author
1068 * @throws \Exception
1070 private static function message($guid, $server, $level = 0)
1076 // This will work for new Diaspora servers and Friendica servers from 3.5
1077 $source_url = $server."/fetch/post/".urlencode($guid);
1079 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1081 $envelope = DI::httpRequest()->fetch($source_url);
1083 Logger::log("Envelope was fetched.", Logger::DEBUG);
1084 $x = self::verifyMagicEnvelope($envelope);
1086 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1088 Logger::log("Envelope was verified.", Logger::DEBUG);
1098 $source_xml = XML::parseString($x);
1100 if (!is_object($source_xml)) {
1104 if ($source_xml->post->reshare) {
1105 // Reshare of a reshare - old Diaspora version
1106 Logger::log("Message is a reshare", Logger::DEBUG);
1107 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1108 } elseif ($source_xml->getName() == "reshare") {
1109 // Reshare of a reshare - new Diaspora version
1110 Logger::log("Message is a new reshare", Logger::DEBUG);
1111 return self::message($source_xml->root_guid, $server, ++$level);
1116 // Fetch the author - for the old and the new Diaspora version
1117 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1118 $author = (string)$source_xml->post->status_message->diaspora_handle;
1119 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1120 $author = (string)$source_xml->author;
1123 // If this isn't a "status_message" then quit
1125 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1129 $msg = ["message" => $x, "author" => $author];
1131 $msg["key"] = self::key($msg["author"]);
1137 * Fetches an item with a given URL
1139 * @param string $url the message url
1141 * @return int the message id of the stored message or false
1142 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1143 * @throws \ImagickException
1145 public static function fetchByURL($url, $uid = 0)
1147 // Check for Diaspora (and Friendica) typical paths
1148 if (!preg_match("=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1149 Logger::info('Invalid url', ['url' => $url]);
1153 $guid = urldecode($matches[2]);
1155 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1156 if (DBA::isResult($item)) {
1157 Logger::info('Found', ['id' => $item['id']]);
1161 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1162 $ret = self::storeByGuid($guid, $matches[1], $uid);
1163 Logger::info('Result', ['ret' => $ret]);
1165 $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1166 if (DBA::isResult($item)) {
1167 Logger::info('Found', ['id' => $item['id']]);
1170 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1176 * Fetches the item record of a given guid
1178 * @param int $uid The user id
1179 * @param string $guid message guid
1180 * @param string $author The handle of the item
1181 * @param array $contact The contact of the item owner
1183 * @return array the item record
1184 * @throws \Exception
1186 private static function parentItem($uid, $guid, $author, array $contact)
1188 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1189 'author-name', 'author-link', 'author-avatar', 'gravity',
1190 'owner-name', 'owner-link', 'owner-avatar'];
1191 $condition = ['uid' => $uid, 'guid' => $guid];
1192 $item = Post::selectFirst($fields, $condition);
1194 if (!DBA::isResult($item)) {
1195 $person = FContact::getByURL($author);
1196 $result = self::storeByGuid($guid, $person["url"], $uid);
1198 // We don't have an url for items that arrived at the public dispatcher
1199 if (!$result && !empty($contact["url"])) {
1200 $result = self::storeByGuid($guid, $contact["url"], $uid);
1204 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1206 $item = Post::selectFirst($fields, $condition);
1210 if (!DBA::isResult($item)) {
1211 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1214 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1220 * returns contact details
1222 * @param array $def_contact The default contact if the person isn't found
1223 * @param array $person The record of the person
1224 * @param int $uid The user id
1227 * 'cid' => contact id
1228 * 'network' => network type
1229 * @throws \Exception
1231 private static function authorContactByUrl($def_contact, $person, $uid)
1233 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1234 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1235 if (DBA::isResult($contact)) {
1236 $cid = $contact["id"];
1237 $network = $contact["network"];
1239 $cid = $def_contact["id"];
1240 $network = Protocol::DIASPORA;
1243 return ["cid" => $cid, "network" => $network];
1247 * Is the profile a hubzilla profile?
1249 * @param string $url The profile link
1251 * @return bool is it a hubzilla server?
1253 private static function isHubzilla($url)
1255 return(strstr($url, '/channel/'));
1259 * Generate a post link with a given handle and message guid
1261 * @param string $addr The user handle
1262 * @param string $guid message guid
1263 * @param string $parent_guid optional parent guid
1265 * @return string the post link
1266 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1267 * @throws \ImagickException
1269 private static function plink(string $addr, string $guid, string $parent_guid = '')
1271 $contact = Contact::getByURL($addr);
1272 if (empty($contact)) {
1273 Logger::info('No contact data for address', ['addr' => $addr]);
1277 if (empty($contact['baseurl'])) {
1278 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1279 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1283 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1284 if (!empty($gserver['platform'])) {
1285 $platform = strtolower($gserver['platform']);
1286 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1289 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1290 if (self::isHubzilla($contact['url'])) {
1291 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1292 $platform = 'hubzilla';
1293 } elseif ($contact['network'] == Protocol::DFRN) {
1294 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1295 $platform = 'friendica';
1299 if ($platform == 'friendica') {
1300 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1303 if ($platform == 'hubzilla') {
1304 return $contact['baseurl'] . '/item/' . $guid;
1307 if ($platform == 'socialhome') {
1308 return $contact['baseurl'] . '/content/' . $guid;
1311 if ($platform != 'diaspora') {
1312 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1316 if ($parent_guid != '') {
1317 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1319 return $contact['baseurl'] . '/posts/' . $guid;
1324 * Receives account migration
1326 * @param array $importer Array of the importer user
1327 * @param object $data The message object
1329 * @return bool Success
1330 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1331 * @throws \ImagickException
1333 private static function receiveAccountMigration(array $importer, $data)
1335 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1336 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1337 $signature = Strings::escapeTags(XML::unescape($data->signature));
1339 $contact = self::contactByHandle($importer["uid"], $old_handle);
1341 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1345 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1348 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1349 $key = self::key($old_handle);
1350 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1351 Logger::log('No valid signature for migration.');
1355 // Update the profile
1356 self::receiveProfile($importer, $data->profile);
1358 // change the technical stuff in contact
1359 $data = Probe::uri($new_handle);
1360 if ($data['network'] == Protocol::PHANTOM) {
1361 Logger::log('Account for '.$new_handle." couldn't be probed.");
1365 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1366 'name' => $data['name'], 'nick' => $data['nick'],
1367 'addr' => $data['addr'], 'batch' => $data['batch'],
1368 'notify' => $data['notify'], 'poll' => $data['poll'],
1369 'network' => $data['network']];
1371 DBA::update('contact', $fields, ['addr' => $old_handle]);
1373 Logger::log('Contacts are updated.');
1379 * Processes an account deletion
1381 * @param object $data The message object
1383 * @return bool Success
1384 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1386 private static function receiveAccountDeletion($data)
1388 $author = Strings::escapeTags(XML::unescape($data->author));
1390 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1391 while ($contact = DBA::fetch($contacts)) {
1392 Contact::remove($contact["id"]);
1394 DBA::close($contacts);
1396 Logger::log('Removed contacts for ' . $author);
1402 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1404 * @param string $author Author handle
1405 * @param string $guid Message guid
1406 * @param boolean $onlyfound Only return uri when found in the database
1408 * @return string The constructed uri or the one from our database
1409 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1410 * @throws \ImagickException
1412 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1414 $item = Post::selectFirst(['uri'], ['guid' => $guid]);
1415 if (DBA::isResult($item)) {
1416 return $item["uri"];
1417 } elseif (!$onlyfound) {
1418 $person = FContact::getByURL($author);
1420 $parts = parse_url($person['url']);
1421 unset($parts['path']);
1422 $host_url = Network::unparseURL($parts);
1424 return $host_url . '/objects/' . $guid;
1431 * Store the mentions in the tag table
1433 * @param integer $uriid
1434 * @param string $text
1436 private static function storeMentions(int $uriid, string $text)
1438 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1439 if (empty($matches)) {
1444 * Matching values for the preg match
1445 * [1] = mention type (@ or !)
1446 * [2] = name (optional)
1450 foreach ($matches as $match) {
1451 if (empty($match)) {
1455 $person = FContact::getByURL($match[3]);
1456 if (empty($person)) {
1460 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1465 * Processes an incoming comment
1467 * @param array $importer Array of the importer user
1468 * @param string $sender The sender of the message
1469 * @param object $data The message object
1470 * @param string $xml The original XML of the message
1471 * @param bool $fetched The message had been fetched and not pushed
1473 * @return int The message id of the generated comment or "false" if there was an error
1474 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1475 * @throws \ImagickException
1477 private static function receiveComment(array $importer, $sender, $data, $xml, bool $fetched)
1479 $author = Strings::escapeTags(XML::unescape($data->author));
1480 $guid = Strings::escapeTags(XML::unescape($data->guid));
1481 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1482 $text = XML::unescape($data->text);
1484 if (isset($data->created_at)) {
1485 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1487 $created_at = DateTimeFormat::utcNow();
1490 if (isset($data->thread_parent_guid)) {
1491 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1492 $thr_parent = self::getUriFromGuid("", $thread_parent_guid, true);
1497 $contact = self::allowedContactByHandle($importer, $sender, true);
1502 if (!empty($contact['gsid'])) {
1503 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1506 $message_id = self::messageExists($importer["uid"], $guid);
1511 $toplevel_parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1512 if (!$toplevel_parent_item) {
1516 $person = FContact::getByURL($author);
1517 if (!is_array($person)) {
1518 Logger::log("unable to find author details");
1522 // Fetch the contact id - if we know this contact
1523 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1527 $datarray["uid"] = $importer["uid"];
1528 $datarray["contact-id"] = $author_contact["cid"];
1529 $datarray["network"] = $author_contact["network"];
1531 $datarray["author-link"] = $person["url"];
1532 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1534 $datarray["owner-link"] = $contact["url"];
1535 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1537 // Will be overwritten for sharing accounts in Item::insert
1539 $datarray["post-reason"] = Item::PR_FETCHED;
1540 } elseif ($datarray["uid"] == 0) {
1541 $datarray["post-reason"] = Item::PR_GLOBAL;
1543 $datarray["post-reason"] = Item::PR_COMMENT;
1546 $datarray["guid"] = $guid;
1547 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1548 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1550 $datarray["verb"] = Activity::POST;
1551 $datarray["gravity"] = GRAVITY_COMMENT;
1553 $datarray['thr-parent'] = $thr_parent ?: $toplevel_parent_item['uri'];
1555 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1556 $datarray["post-type"] = Item::PT_NOTE;
1558 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1559 $datarray["source"] = $xml;
1560 $datarray["direction"] = $fetched ? Conversation::PULL : Conversation::PUSH;
1562 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1564 $datarray["plink"] = self::plink($author, $guid, $toplevel_parent_item['guid']);
1565 $body = Markdown::toBBCode($text);
1567 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1569 self::storeMentions($datarray['uri-id'], $text);
1570 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
1572 self::fetchGuid($datarray);
1574 // If we are the origin of the parent we store the original data.
1575 // We notify our followers during the item storage.
1576 if ($toplevel_parent_item["origin"]) {
1577 $datarray['diaspora_signed_text'] = json_encode($data);
1580 if (Item::isTooOld($datarray)) {
1581 Logger::info('Comment is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1585 $message_id = Item::insert($datarray);
1587 if ($message_id <= 0) {
1592 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1593 if ($datarray['uid'] == 0) {
1594 Item::distribute($message_id, json_encode($data));
1602 * processes and stores private messages
1604 * @param array $importer Array of the importer user
1605 * @param array $contact The contact of the message
1606 * @param object $data The message object
1607 * @param array $msg Array of the processed message, author handle and key
1608 * @param object $mesg The private message
1609 * @param array $conversation The conversation record to which this message belongs
1611 * @return bool "true" if it was successful
1612 * @throws \Exception
1614 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1616 $author = Strings::escapeTags(XML::unescape($data->author));
1617 $guid = Strings::escapeTags(XML::unescape($data->guid));
1618 $subject = Strings::escapeTags(XML::unescape($data->subject));
1620 // "diaspora_handle" is the element name from the old version
1621 // "author" is the element name from the new version
1622 if ($mesg->author) {
1623 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1624 } elseif ($mesg->diaspora_handle) {
1625 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1630 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1631 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1632 $msg_text = XML::unescape($mesg->text);
1633 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1635 if ($msg_conversation_guid != $guid) {
1636 Logger::log("message conversation guid does not belong to the current conversation.");
1640 $body = Markdown::toBBCode($msg_text);
1641 $message_uri = $msg_author.":".$msg_guid;
1643 $person = FContact::getByURL($msg_author);
1645 return Mail::insert([
1646 'uid' => $importer['uid'],
1647 'guid' => $msg_guid,
1648 'convid' => $conversation['id'],
1649 'from-name' => $person['name'],
1650 'from-photo' => $person['photo'],
1651 'from-url' => $person['url'],
1652 'contact-id' => $contact['id'],
1653 'title' => $subject,
1655 'uri' => $message_uri,
1656 'parent-uri' => $author . ':' . $guid,
1657 'created' => $msg_created_at
1662 * Processes new private messages (answers to private messages are processed elsewhere)
1664 * @param array $importer Array of the importer user
1665 * @param array $msg Array of the processed message, author handle and key
1666 * @param object $data The message object
1668 * @return bool Success
1669 * @throws \Exception
1671 private static function receiveConversation(array $importer, $msg, $data)
1673 $author = Strings::escapeTags(XML::unescape($data->author));
1674 $guid = Strings::escapeTags(XML::unescape($data->guid));
1675 $subject = Strings::escapeTags(XML::unescape($data->subject));
1676 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1677 $participants = Strings::escapeTags(XML::unescape($data->participants));
1679 $messages = $data->message;
1681 if (!count($messages)) {
1682 Logger::log("empty conversation");
1686 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1691 if (!empty($contact['gsid'])) {
1692 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1695 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1696 if (!DBA::isResult($conversation)) {
1698 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1699 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1700 intval($importer["uid"]),
1702 DBA::escape($author),
1703 DBA::escape($created_at),
1704 DBA::escape(DateTimeFormat::utcNow()),
1705 DBA::escape($subject),
1706 DBA::escape($participants)
1709 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1712 if (!$conversation) {
1713 Logger::log("unable to create conversation.");
1717 foreach ($messages as $mesg) {
1718 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1725 * Processes "like" messages
1727 * @param array $importer Array of the importer user
1728 * @param string $sender The sender of the message
1729 * @param object $data The message object
1731 * @return int The message id of the generated like or "false" if there was an error
1732 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1733 * @throws \ImagickException
1735 private static function receiveLike(array $importer, $sender, $data, bool $fetched)
1737 $author = Strings::escapeTags(XML::unescape($data->author));
1738 $guid = Strings::escapeTags(XML::unescape($data->guid));
1739 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1740 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
1741 $positive = Strings::escapeTags(XML::unescape($data->positive));
1743 // likes on comments aren't supported by Diaspora - only on posts
1744 // But maybe this will be supported in the future, so we will accept it.
1745 if (!in_array($parent_type, ["Post", "Comment"])) {
1749 $contact = self::allowedContactByHandle($importer, $sender, true);
1754 if (!empty($contact['gsid'])) {
1755 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1758 $message_id = self::messageExists($importer["uid"], $guid);
1763 $toplevel_parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1764 if (!$toplevel_parent_item) {
1768 $person = FContact::getByURL($author);
1769 if (!is_array($person)) {
1770 Logger::log("unable to find author details");
1774 // Fetch the contact id - if we know this contact
1775 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1777 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1778 // We would accept this anyhow.
1779 if ($positive == "true") {
1780 $verb = Activity::LIKE;
1782 $verb = Activity::DISLIKE;
1787 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1788 $datarray["direction"] = $fetched ? Conversation::PULL : Conversation::PUSH;
1790 $datarray["uid"] = $importer["uid"];
1791 $datarray["contact-id"] = $author_contact["cid"];
1792 $datarray["network"] = $author_contact["network"];
1794 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
1795 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1797 $datarray["guid"] = $guid;
1798 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1800 $datarray["verb"] = $verb;
1801 $datarray["gravity"] = GRAVITY_ACTIVITY;
1802 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1804 $datarray["object-type"] = Activity\ObjectType::NOTE;
1806 $datarray["body"] = $verb;
1808 // Diaspora doesn't provide a date for likes
1809 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
1811 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1812 if ($toplevel_parent_item['gravity'] != GRAVITY_PARENT) {
1813 $toplevel = Post::selectFirst(['origin'], ['id' => $toplevel_parent_item['parent']]);
1814 $origin = $toplevel["origin"];
1816 $origin = $toplevel_parent_item["origin"];
1819 // If we are the origin of the parent we store the original data.
1820 // We notify our followers during the item storage.
1822 $datarray['diaspora_signed_text'] = json_encode($data);
1825 if (Item::isTooOld($datarray)) {
1826 Logger::info('Like is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1830 $message_id = Item::insert($datarray);
1832 if ($message_id <= 0) {
1837 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1838 if ($datarray['uid'] == 0) {
1839 Item::distribute($message_id, json_encode($data));
1847 * Processes private messages
1849 * @param array $importer Array of the importer user
1850 * @param object $data The message object
1852 * @return bool Success?
1853 * @throws \Exception
1855 private static function receiveMessage(array $importer, $data)
1857 $author = Strings::escapeTags(XML::unescape($data->author));
1858 $guid = Strings::escapeTags(XML::unescape($data->guid));
1859 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
1860 $text = XML::unescape($data->text);
1861 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1863 $contact = self::allowedContactByHandle($importer, $author, true);
1868 if (!empty($contact['gsid'])) {
1869 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1872 $conversation = null;
1874 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
1875 $conversation = DBA::selectFirst('conv', [], $condition);
1877 if (!DBA::isResult($conversation)) {
1878 Logger::log("conversation not available.");
1882 $message_uri = $author.":".$guid;
1884 $person = FContact::getByURL($author);
1886 Logger::log("unable to find author details");
1890 $body = Markdown::toBBCode($text);
1892 $body = self::replacePeopleGuid($body, $person["url"]);
1894 return Mail::insert([
1895 'uid' => $importer['uid'],
1897 'convid' => $conversation['id'],
1898 'from-name' => $person['name'],
1899 'from-photo' => $person['photo'],
1900 'from-url' => $person['url'],
1901 'contact-id' => $contact['id'],
1902 'title' => $conversation['subject'],
1905 'uri' => $message_uri,
1906 'parent-uri' => $author.":".$conversation['guid'],
1907 'created' => $created_at
1912 * Processes participations - unsupported by now
1914 * @param array $importer Array of the importer user
1915 * @param object $data The message object
1917 * @return bool success
1918 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1919 * @throws \ImagickException
1921 private static function receiveParticipation(array $importer, $data, bool $fetched)
1923 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
1924 $guid = Strings::escapeTags(XML::unescape($data->guid));
1925 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1927 $contact = self::allowedContactByHandle($importer, $author, true);
1932 if (!empty($contact['gsid'])) {
1933 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
1936 if (self::messageExists($importer["uid"], $guid)) {
1940 $toplevel_parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1941 if (!$toplevel_parent_item) {
1945 if (!$toplevel_parent_item['origin']) {
1946 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1949 if (!in_array($toplevel_parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
1950 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
1954 $person = FContact::getByURL($author);
1955 if (!is_array($person)) {
1956 Logger::log("Person not found: ".$author);
1960 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1962 // Store participation
1965 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1966 $datarray["direction"] = $fetched ? Conversation::PULL : Conversation::PUSH;
1968 $datarray["uid"] = $importer["uid"];
1969 $datarray["contact-id"] = $author_contact["cid"];
1970 $datarray["network"] = $author_contact["network"];
1972 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
1973 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1975 $datarray["guid"] = $guid;
1976 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1978 $datarray["verb"] = Activity::FOLLOW;
1979 $datarray["gravity"] = GRAVITY_ACTIVITY;
1980 $datarray['thr-parent'] = $toplevel_parent_item['uri'];
1982 $datarray["object-type"] = Activity\ObjectType::NOTE;
1984 $datarray["body"] = Activity::FOLLOW;
1986 // Diaspora doesn't provide a date for a participation
1987 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
1989 if (Item::isTooOld($datarray)) {
1990 Logger::info('Participation is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
1994 $message_id = Item::insert($datarray);
1996 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
1998 // Send all existing comments and likes to the requesting server
1999 $comments = Post::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb'],
2000 ['parent' => $toplevel_parent_item['id'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
2001 while ($comment = Post::fetch($comments)) {
2002 if (in_array($comment['verb'], [Activity::FOLLOW, Activity::TAG])) {
2003 Logger::info('participation messages are not relayed', ['item' => $comment['id']]);
2007 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
2008 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2012 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
2013 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2017 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact["cid"]]);
2018 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $author_contact["cid"])) {
2019 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2022 DBA::close($comments);
2028 * Processes photos - unneeded
2030 * @param array $importer Array of the importer user
2031 * @param object $data The message object
2033 * @return bool always true
2035 private static function receivePhoto(array $importer, $data)
2037 // There doesn't seem to be a reason for this function,
2038 // since the photo data is transmitted in the status message as well
2043 * Processes poll participations - unssupported
2045 * @param array $importer Array of the importer user
2046 * @param object $data The message object
2048 * @return bool always true
2050 private static function receivePollParticipation(array $importer, $data)
2052 // We don't support polls by now
2057 * Processes incoming profile updates
2059 * @param array $importer Array of the importer user
2060 * @param object $data The message object
2062 * @return bool Success
2063 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2064 * @throws \ImagickException
2066 private static function receiveProfile(array $importer, $data)
2068 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2070 $contact = self::contactByHandle($importer["uid"], $author);
2075 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2076 $image_url = XML::unescape($data->image_url);
2077 $birthday = XML::unescape($data->birthday);
2078 $about = Markdown::toBBCode(XML::unescape($data->bio));
2079 $location = Markdown::toBBCode(XML::unescape($data->location));
2080 $searchable = (XML::unescape($data->searchable) == "true");
2081 $nsfw = (XML::unescape($data->nsfw) == "true");
2082 $tags = XML::unescape($data->tag_string);
2084 $tags = explode("#", $tags);
2087 foreach ($tags as $tag) {
2088 $tag = trim(strtolower($tag));
2094 $keywords = implode(", ", $keywords);
2096 $handle_parts = explode("@", $author);
2097 $nick = $handle_parts[0];
2100 $name = $handle_parts[0];
2103 if (preg_match("|^https?://|", $image_url) === 0) {
2104 $image_url = "http://".$handle_parts[1].$image_url;
2107 Contact::updateAvatar($contact["id"], $image_url);
2109 // Generic birthday. We don't know the timezone. The year is irrelevant.
2111 $birthday = str_replace("1000", "1901", $birthday);
2113 if ($birthday != "") {
2114 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2117 // this is to prevent multiple birthday notifications in a single year
2118 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2120 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2121 $birthday = $contact["bd"];
2124 $fields = ['name' => $name, 'location' => $location,
2125 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2126 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2127 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2129 if (!empty($birthday)) {
2130 $fields['bd'] = $birthday;
2133 DBA::update('contact', $fields, ['id' => $contact['id']]);
2135 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2141 * Processes incoming friend requests
2143 * @param array $importer Array of the importer user
2144 * @param array $contact The contact that send the request
2146 * @throws \Exception
2148 private static function receiveRequestMakeFriend(array $importer, array $contact)
2150 if ($contact["rel"] == Contact::SHARING) {
2153 ['rel' => Contact::FRIEND, 'writable' => true],
2154 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2160 * Processes incoming sharing notification
2162 * @param array $importer Array of the importer user
2163 * @param object $data The message object
2165 * @return bool Success
2166 * @throws \Exception
2168 private static function receiveContactRequest(array $importer, $data)
2170 $author = XML::unescape($data->author);
2171 $recipient = XML::unescape($data->recipient);
2173 if (!$author || !$recipient) {
2177 // the current protocol version doesn't know these fields
2178 // That means that we will assume their existance
2179 if (isset($data->following)) {
2180 $following = (XML::unescape($data->following) == "true");
2185 if (isset($data->sharing)) {
2186 $sharing = (XML::unescape($data->sharing) == "true");
2191 $contact = self::contactByHandle($importer["uid"], $author);
2193 // perhaps we were already sharing with this person. Now they're sharing with us.
2194 // That makes us friends.
2197 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2198 self::receiveRequestMakeFriend($importer, $contact);
2200 // refetch the contact array
2201 $contact = self::contactByHandle($importer["uid"], $author);
2203 // If we are now friends, we are sending a share message.
2204 // Normally we needn't to do so, but the first message could have been vanished.
2205 if (in_array($contact["rel"], [Contact::FRIEND])) {
2206 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2207 if (DBA::isResult($user)) {
2208 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2209 self::sendShare($user, $contact);
2214 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2215 Contact::removeFollower($importer, $contact);
2220 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2221 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2223 } elseif (!$following && !$sharing) {
2224 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2226 } elseif (!$following && $sharing) {
2227 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2228 } elseif ($following && $sharing) {
2229 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2230 } elseif ($following && !$sharing) {
2231 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2234 $ret = FContact::getByURL($author);
2236 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2237 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2241 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2243 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2248 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2249 'author-link' => $ret['url']];
2251 $result = Contact::addRelationship($importer, $contact, $item, false);
2252 if ($result === true) {
2253 $contact_record = self::contactByHandle($importer['uid'], $author);
2254 if (!$contact_record) {
2255 Logger::info('unable to locate newly created contact record.');
2259 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2260 if (DBA::isResult($user)) {
2261 self::sendShare($user, $contact_record);
2263 // Send the profile data, maybe it weren't transmitted before
2264 self::sendProfile($importer['uid'], [$contact_record]);
2272 * Fetches a message with a given guid
2274 * @param string $guid message guid
2275 * @param string $orig_author handle of the original post
2276 * @return array The fetched item
2277 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2278 * @throws \ImagickException
2280 public static function originalItem($guid, $orig_author)
2283 Logger::log('Empty guid. Quitting.');
2287 // Do we already have this item?
2288 $fields = ['body', 'title', 'app', 'created', 'object-type', 'uri', 'guid',
2289 'author-name', 'author-link', 'author-avatar', 'plink', 'uri-id'];
2290 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2291 $item = Post::selectFirst($fields, $condition);
2293 if (DBA::isResult($item)) {
2294 Logger::log("reshared message ".$guid." already exists on system.");
2296 // Maybe it is already a reshared item?
2297 // Then refetch the content, if it is a reshare from a reshare.
2298 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2299 if (self::isReshare($item["body"], true)) {
2301 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2302 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2304 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2306 // Add OEmbed and other information to the body
2307 $item["body"] = PageInfo::searchAndAppendToBody($item["body"], false, true);
2315 if (!DBA::isResult($item)) {
2316 if (empty($orig_author)) {
2317 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2321 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2322 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2323 $stored = self::storeByGuid($guid, $server);
2326 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2327 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2328 $stored = self::storeByGuid($guid, $server);
2332 $fields = ['body', 'title', 'app', 'created', 'object-type', 'uri', 'guid',
2333 'author-name', 'author-link', 'author-avatar', 'plink', 'uri-id'];
2334 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2335 $item = Post::selectFirst($fields, $condition);
2337 if (DBA::isResult($item)) {
2338 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2339 if (self::isReshare($item["body"], false)) {
2340 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2341 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2352 * Stores a reshare activity
2354 * @param array $item Array of reshare post
2355 * @param integer $parent_message_id Id of the parent post
2356 * @param string $guid GUID string of reshare action
2357 * @param string $author Author handle
2359 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2361 $parent = Post::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2365 $datarray['uid'] = $item['uid'];
2366 $datarray['contact-id'] = $item['contact-id'];
2367 $datarray['network'] = $item['network'];
2369 $datarray['author-link'] = $item['author-link'];
2370 $datarray['author-id'] = $item['author-id'];
2372 $datarray['owner-link'] = $datarray['author-link'];
2373 $datarray['owner-id'] = $datarray['author-id'];
2375 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2376 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2377 $datarray['thr-parent'] = $parent['uri'];
2379 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2380 $datarray['gravity'] = GRAVITY_ACTIVITY;
2381 $datarray['object-type'] = Activity\ObjectType::NOTE;
2383 $datarray['protocol'] = $item['protocol'];
2384 $datarray['source'] = $item['source'];
2385 $datarray['direction'] = $item['direction'];
2387 $datarray['plink'] = self::plink($author, $datarray['guid']);
2388 $datarray['private'] = $item['private'];
2389 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2391 if (Item::isTooOld($datarray)) {
2392 Logger::info('Reshare activity is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2396 $message_id = Item::insert($datarray);
2399 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2400 if ($datarray['uid'] == 0) {
2401 Item::distribute($message_id);
2407 * Processes a reshare message
2409 * @param array $importer Array of the importer user
2410 * @param object $data The message object
2411 * @param string $xml The original XML of the message
2413 * @return int the message id
2414 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2415 * @throws \ImagickException
2417 private static function receiveReshare(array $importer, $data, $xml, bool $fetched)
2419 $author = Strings::escapeTags(XML::unescape($data->author));
2420 $guid = Strings::escapeTags(XML::unescape($data->guid));
2421 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2422 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2423 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2424 /// @todo handle unprocessed property "provider_display_name"
2425 $public = Strings::escapeTags(XML::unescape($data->public));
2427 $contact = self::allowedContactByHandle($importer, $author, false);
2432 if (!empty($contact['gsid'])) {
2433 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2436 $message_id = self::messageExists($importer["uid"], $guid);
2441 $original_item = self::originalItem($root_guid, $root_author);
2442 if (!$original_item) {
2446 if (empty($original_item['plink'])) {
2447 $original_item['plink'] = self::plink($root_author, $root_guid);
2452 $datarray["uid"] = $importer["uid"];
2453 $datarray["contact-id"] = $contact["id"];
2454 $datarray["network"] = Protocol::DIASPORA;
2456 $datarray["author-link"] = $contact["url"];
2457 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2459 $datarray["owner-link"] = $datarray["author-link"];
2460 $datarray["owner-id"] = $datarray["author-id"];
2462 $datarray["guid"] = $guid;
2463 $datarray["uri"] = $datarray["thr-parent"] = self::getUriFromGuid($author, $guid);
2464 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2466 $datarray["verb"] = Activity::POST;
2467 $datarray["gravity"] = GRAVITY_PARENT;
2469 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2470 $datarray["source"] = $xml;
2471 $datarray["direction"] = $fetched ? Conversation::PULL : Conversation::PUSH;
2473 /// @todo Copy tag data from original post
2475 $prefix = BBCode::getShareOpeningTag(
2476 $original_item["author-name"],
2477 $original_item["author-link"],
2478 $original_item["author-avatar"],
2479 $original_item["plink"],
2480 $original_item["created"],
2481 $original_item["guid"]
2484 if (!empty($original_item['title'])) {
2485 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2488 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2490 Tag::storeFromBody($datarray['uri-id'], $datarray["body"]);
2492 Post\Media::copy($original_item['uri-id'], $datarray['uri-id']);
2493 $datarray["app"] = $original_item["app"];
2495 $datarray["plink"] = self::plink($author, $guid);
2496 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2497 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2499 $datarray["object-type"] = $original_item["object-type"];
2501 self::fetchGuid($datarray);
2503 if (Item::isTooOld($datarray)) {
2504 Logger::info('Reshare is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2508 $message_id = Item::insert($datarray);
2510 self::sendParticipation($contact, $datarray);
2512 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2513 if ($root_message_id) {
2514 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2518 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2519 if ($datarray['uid'] == 0) {
2520 Item::distribute($message_id);
2529 * Processes retractions
2531 * @param array $importer Array of the importer user
2532 * @param array $contact The contact of the item owner
2533 * @param object $data The message object
2535 * @return bool success
2536 * @throws \Exception
2538 private static function itemRetraction(array $importer, array $contact, $data)
2540 $author = Strings::escapeTags(XML::unescape($data->author));
2541 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2542 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2544 $person = FContact::getByURL($author);
2545 if (!is_array($person)) {
2546 Logger::log("unable to find author detail for ".$author);
2550 if (empty($contact["url"])) {
2551 $contact["url"] = $person["url"];
2554 // Fetch items that are about to be deleted
2555 $fields = ['uid', 'id', 'parent', 'author-link', 'uri-id'];
2557 // When we receive a public retraction, we delete every item that we find.
2558 if ($importer['uid'] == 0) {
2559 $condition = ['guid' => $target_guid, 'deleted' => false];
2561 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2564 $r = Post::select($fields, $condition);
2565 if (!DBA::isResult($r)) {
2566 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2570 while ($item = Post::fetch($r)) {
2571 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2572 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2576 // Fetch the parent item
2577 $parent = Post::selectFirst(['author-link'], ['id' => $item['parent']]);
2579 // Only delete it if the parent author really fits
2580 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2581 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2585 Item::markForDeletion(['id' => $item['id']]);
2587 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item['parent'], Logger::DEBUG);
2595 * Receives retraction messages
2597 * @param array $importer Array of the importer user
2598 * @param string $sender The sender of the message
2599 * @param object $data The message object
2601 * @return bool Success
2602 * @throws \Exception
2604 private static function receiveRetraction(array $importer, $sender, $data)
2606 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2608 $contact = self::contactByHandle($importer["uid"], $sender);
2609 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2610 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2618 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2620 switch ($target_type) {
2625 case "StatusMessage":
2626 return self::itemRetraction($importer, $contact, $data);
2628 case "PollParticipation":
2630 // Currently unsupported
2634 Logger::log("Unknown target type ".$target_type);
2641 * Checks if an incoming message is wanted
2643 * @param string $url
2644 * @param integer $uriid
2645 * @param string $author
2646 * @param string $body
2647 * @return boolean Is the message wanted?
2649 private static function isSolicitedMessage(string $url, int $uriid, string $author, string $body)
2651 $contact = Contact::getByURL($author);
2652 if (DBA::exists('contact', ["`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)",
2653 $contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) {
2654 Logger::info('Author has got followers - accepted', ['url' => $url, 'author' => $author]);
2658 $taglist = Tag::getByURIId($uriid, [Tag::HASHTAG]);
2659 $tags = array_column($taglist, 'name');
2660 return Relay::isSolicitedPost($tags, $body, $contact['id'], $url, Protocol::DIASPORA);
2664 * Store an attached photo in the post-media table
2667 * @param object $photo
2670 private static function storePhotoAsMedia(int $uriid, $photo)
2673 $data['uri-id'] = $uriid;
2674 $data['type'] = Post\Media::IMAGE;
2675 $data['url'] = XML::unescape($photo->remote_photo_path) . XML::unescape($photo->remote_photo_name);
2676 $data['height'] = (int)XML::unescape($photo->height ?? 0);
2677 $data['width'] = (int)XML::unescape($photo->width ?? 0);
2678 $data['description'] = XML::unescape($photo->text ?? '');
2680 Post\Media::insert($data);
2684 * Receives status messages
2686 * @param array $importer Array of the importer user
2687 * @param SimpleXMLElement $data The message object
2688 * @param string $xml The original XML of the message
2689 * @param bool $fetched The message had been fetched and not pushed
2690 * @return int The message id of the newly created item
2691 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2692 * @throws \ImagickException
2694 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml, bool $fetched)
2696 $author = Strings::escapeTags(XML::unescape($data->author));
2697 $guid = Strings::escapeTags(XML::unescape($data->guid));
2698 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2699 $public = Strings::escapeTags(XML::unescape($data->public));
2700 $text = XML::unescape($data->text);
2701 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2703 $contact = self::allowedContactByHandle($importer, $author, false);
2708 if (!empty($contact['gsid'])) {
2709 GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
2712 $message_id = self::messageExists($importer["uid"], $guid);
2718 if ($data->location) {
2719 foreach ($data->location->children() as $fieldname => $data) {
2720 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2724 $raw_body = $body = Markdown::toBBCode($text);
2728 $datarray["guid"] = $guid;
2729 $datarray["uri"] = $datarray["thr-parent"] = self::getUriFromGuid($author, $guid);
2730 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2732 // Attach embedded pictures to the body
2734 foreach ($data->photo as $photo) {
2735 self::storePhotoAsMedia($datarray['uri-id'], $photo);
2736 $body = "[img]".XML::unescape($photo->remote_photo_path).
2737 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2740 $datarray["object-type"] = Activity\ObjectType::IMAGE;
2741 $datarray["post-type"] = Item::PT_IMAGE;
2743 $datarray["object-type"] = Activity\ObjectType::NOTE;
2744 $datarray["post-type"] = Item::PT_NOTE;
2746 // Add OEmbed and other information to the body
2747 if (!self::isHubzilla($contact["url"])) {
2748 $body = PageInfo::searchAndAppendToBody($body, false, true);
2752 /// @todo enable support for polls
2753 //if ($data->poll) {
2754 // foreach ($data->poll AS $poll)
2759 /// @todo enable support for events
2761 $datarray["uid"] = $importer["uid"];
2762 $datarray["contact-id"] = $contact["id"];
2763 $datarray["network"] = Protocol::DIASPORA;
2765 $datarray["author-link"] = $contact["url"];
2766 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2768 $datarray["owner-link"] = $datarray["author-link"];
2769 $datarray["owner-id"] = $datarray["author-id"];
2771 $datarray["verb"] = Activity::POST;
2772 $datarray["gravity"] = GRAVITY_PARENT;
2774 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2775 $datarray["source"] = $xml;
2776 $datarray["direction"] = $fetched ? Conversation::PULL : Conversation::PUSH;
2779 $datarray["post-reason"] = Item::PR_FETCHED;
2780 } elseif ($datarray["uid"] == 0) {
2781 $datarray["post-reason"] = Item::PR_GLOBAL;
2784 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2785 $datarray["raw-body"] = self::replacePeopleGuid($raw_body, $contact["url"]);
2787 self::storeMentions($datarray['uri-id'], $text);
2788 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
2790 if (!$fetched && !self::isSolicitedMessage($datarray["uri"], $datarray['uri-id'], $author, $body)) {
2791 DBA::delete('item-uri', ['uri' => $datarray['uri']]);
2795 if ($provider_display_name != "") {
2796 $datarray["app"] = $provider_display_name;
2799 $datarray["plink"] = self::plink($author, $guid);
2800 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2801 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2803 if (isset($address["address"])) {
2804 $datarray["location"] = $address["address"];
2807 if (isset($address["lat"]) && isset($address["lng"])) {
2808 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2811 self::fetchGuid($datarray);
2813 if (Item::isTooOld($datarray)) {
2814 Logger::info('Status is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
2818 $message_id = Item::insert($datarray);
2820 self::sendParticipation($contact, $datarray);
2823 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2824 if ($datarray['uid'] == 0) {
2825 Item::distribute($message_id);
2833 /* ************************************************************************************** *
2834 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2835 * ************************************************************************************** */
2838 * returnes the handle of a contact
2840 * @param array $contact contact array
2842 * @return string the handle in the format user@domain.tld
2843 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2845 private static function myHandle(array $contact)
2847 if (!empty($contact["addr"])) {
2848 return $contact["addr"];
2851 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2852 // So - just in case - we build the the address here.
2853 if ($contact["nickname"] != "") {
2854 $nick = $contact["nickname"];
2856 $nick = $contact["nick"];
2859 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
2864 * Creates the data for a private message in the new format
2866 * @param string $msg The message that is to be transmitted
2867 * @param array $user The record of the sender
2868 * @param array $contact Target of the communication
2869 * @param string $prvkey The private key of the sender
2870 * @param string $pubkey The public key of the receiver
2872 * @return string The encrypted data
2873 * @throws \Exception
2875 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
2877 Logger::log("Message: ".$msg, Logger::DATA);
2879 // without a public key nothing will work
2881 Logger::log("pubkey missing: contact id: ".$contact["id"]);
2885 $aes_key = openssl_random_pseudo_bytes(32);
2886 $b_aes_key = base64_encode($aes_key);
2887 $iv = openssl_random_pseudo_bytes(16);
2888 $b_iv = base64_encode($iv);
2890 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2892 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
2894 $encrypted_key_bundle = "";
2895 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
2899 $json_object = json_encode(
2900 ["aes_key" => base64_encode($encrypted_key_bundle),
2901 "encrypted_magic_envelope" => base64_encode($ciphertext)]
2904 return $json_object;
2908 * Creates the envelope for the "fetch" endpoint and for the new format
2910 * @param string $msg The message that is to be transmitted
2911 * @param array $user The record of the sender
2913 * @return string The envelope
2914 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2916 public static function buildMagicEnvelope($msg, array $user)
2918 $b64url_data = Strings::base64UrlEncode($msg);
2919 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
2921 $key_id = Strings::base64UrlEncode(self::myHandle($user));
2922 $type = "application/xml";
2923 $encoding = "base64url";
2924 $alg = "RSA-SHA256";
2925 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
2927 // Fallback if the private key wasn't transmitted in the expected field
2928 if ($user['uprvkey'] == "") {
2929 $user['uprvkey'] = $user['prvkey'];
2932 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
2933 $sig = Strings::base64UrlEncode($signature);
2935 $xmldata = ["me:env" => ["me:data" => $data,
2936 "@attributes" => ["type" => $type],
2937 "me:encoding" => $encoding,
2940 "@attributes2" => ["key_id" => $key_id]]];
2942 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
2944 return XML::fromArray($xmldata, $xml, false, $namespaces);
2948 * Create the envelope for a message
2950 * @param string $msg The message that is to be transmitted
2951 * @param array $user The record of the sender
2952 * @param array $contact Target of the communication
2953 * @param string $prvkey The private key of the sender
2954 * @param string $pubkey The public key of the receiver
2955 * @param bool $public Is the message public?
2957 * @return string The message that will be transmitted to other servers
2958 * @throws \Exception
2960 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
2962 // The message is put into an envelope with the sender's signature
2963 $envelope = self::buildMagicEnvelope($msg, $user);
2965 // Private messages are put into a second envelope, encrypted with the receivers public key
2967 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
2974 * Creates a signature for a message
2976 * @param array $owner the array of the owner of the message
2977 * @param array $message The message that is to be signed
2979 * @return string The signature
2981 private static function signature($owner, $message)
2984 unset($sigmsg["author_signature"]);
2985 unset($sigmsg["parent_author_signature"]);
2987 $signed_text = implode(";", $sigmsg);
2989 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
2993 * Transmit a message to a target server
2995 * @param array $owner the array of the item owner
2996 * @param array $contact Target of the communication
2997 * @param string $envelope The message that is to be transmitted
2998 * @param bool $public_batch Is it a public post?
2999 * @param string $guid message guid
3001 * @return int Result of the transmission
3002 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3003 * @throws \ImagickException
3005 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3007 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
3012 $logid = Strings::getRandomHex(4);
3014 // We always try to use the data from the fcontact table.
3015 // This is important for transmitting data to Friendica servers.
3016 if (!empty($contact['addr'])) {
3017 $fcontact = FContact::getByURL($contact['addr']);
3018 if (!empty($fcontact)) {
3019 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3023 if (empty($dest_url)) {
3024 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3028 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3032 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3034 if (!intval(DI::config()->get("system", "diaspora_test"))) {
3035 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3037 $postResult = DI::httpRequest()->post($dest_url . "/", $envelope, ["Content-Type: " . $content_type]);
3038 $return_code = $postResult->getReturnCode();
3040 Logger::log("test_mode");
3044 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3046 return $return_code ? $return_code : -1;
3051 * Build the post xml
3053 * @param string $type The message type
3054 * @param array $message The message data
3056 * @return string The post XML
3058 public static function buildPostXml($type, $message)
3060 $data = [$type => $message];
3062 return XML::fromArray($data, $xml);
3066 * Builds and transmit messages
3068 * @param array $owner the array of the item owner
3069 * @param array $contact Target of the communication
3070 * @param string $type The message type
3071 * @param array $message The message data
3072 * @param bool $public_batch Is it a public post?
3073 * @param string $guid message guid
3075 * @return int Result of the transmission
3076 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3077 * @throws \ImagickException
3079 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3081 $msg = self::buildPostXml($type, $message);
3083 Logger::log('message: '.$msg, Logger::DATA);
3084 Logger::log('send guid '.$guid, Logger::DEBUG);
3086 // Fallback if the private key wasn't transmitted in the expected field
3087 if (empty($owner['uprvkey'])) {
3088 $owner['uprvkey'] = $owner['prvkey'];
3091 // When sending content to Friendica contacts using the Diaspora protocol
3092 // we have to fetch the public key from the fcontact.
3093 // This is due to the fact that legacy DFRN had unique keys for every contact.
3094 $pubkey = $contact['pubkey'];
3095 if (!empty($contact['addr'])) {
3096 $fcontact = FContact::getByURL($contact['addr']);
3097 if (!empty($fcontact)) {
3098 $pubkey = $fcontact['pubkey'];
3102 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
3104 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3106 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3108 return $return_code;
3112 * sends a participation (Used to get all further updates)
3114 * @param array $contact Target of the communication
3115 * @param array $item Item array
3117 * @return int The result of the transmission
3118 * @throws \Exception
3120 private static function sendParticipation(array $contact, array $item)
3122 // Don't send notifications for private postings
3123 if ($item['private'] == Item::PRIVATE) {
3127 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3129 $result = DI::cache()->get($cachekey);
3130 if (!is_null($result)) {
3134 $owner = User::getOwnerDataById($item['uid']);
3135 $author = self::myHandle($owner);
3137 $message = ["author" => $author,
3138 "guid" => System::createUUID(),
3139 "parent_type" => "Post",
3140 "parent_guid" => $item["guid"]];
3142 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3144 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3145 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3147 return self::buildAndTransmit($owner, $contact, "participation", $message);
3151 * sends an account migration
3153 * @param array $owner the array of the item owner
3154 * @param array $contact Target of the communication
3155 * @param int $uid User ID
3157 * @return int The result of the transmission
3158 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3159 * @throws \ImagickException
3161 public static function sendAccountMigration(array $owner, array $contact, $uid)
3163 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3164 $profile = self::createProfileData($uid);
3166 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3167 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3169 $message = ["author" => $old_handle,
3170 "profile" => $profile,
3171 "signature" => $signature];
3173 Logger::info('Send account migration', ['msg' => $message]);
3175 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3179 * Sends a "share" message
3181 * @param array $owner the array of the item owner
3182 * @param array $contact Target of the communication
3184 * @return int The result of the transmission
3185 * @throws \Exception
3187 public static function sendShare(array $owner, array $contact)
3190 * @todo support the different possible combinations of "following" and "sharing"
3191 * Currently, Diaspora only interprets the "sharing" field
3193 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3197 switch ($contact["rel"]) {
3198 case Contact::FRIEND:
3202 case Contact::SHARING:
3206 case Contact::FOLLOWER:
3212 $message = ["author" => self::myHandle($owner),
3213 "recipient" => $contact["addr"],
3214 "following" => "true",
3215 "sharing" => "true"];
3217 Logger::info('Send share', ['msg' => $message]);
3219 return self::buildAndTransmit($owner, $contact, "contact", $message);
3223 * sends an "unshare"
3225 * @param array $owner the array of the item owner
3226 * @param array $contact Target of the communication
3228 * @return int The result of the transmission
3229 * @throws \Exception
3231 public static function sendUnshare(array $owner, array $contact)
3233 $message = ["author" => self::myHandle($owner),
3234 "recipient" => $contact["addr"],
3235 "following" => "false",
3236 "sharing" => "false"];
3238 Logger::info('Send unshare', ['msg' => $message]);
3240 return self::buildAndTransmit($owner, $contact, "contact", $message);
3244 * Checks a message body if it is a reshare
3246 * @param string $body The message body that is to be check
3247 * @param bool $complete Should it be a complete check or a simple check?
3249 * @return array|bool Reshare details or "false" if no reshare
3250 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3251 * @throws \ImagickException
3253 public static function isReshare($body, $complete = true)
3255 $body = trim($body);
3257 $reshared = Item::getShareArray(['body' => $body]);
3258 if (empty($reshared)) {
3262 // Skip if it isn't a pure repeated messages
3263 // Does it start with a share?
3264 if (!empty($reshared['comment']) && $complete) {
3268 if (!empty($reshared['guid']) && $complete) {
3269 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3270 $item = Post::selectFirst(['contact-id'], $condition);
3271 if (DBA::isResult($item)) {
3273 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3274 $ret["root_guid"] = $reshared['guid'];
3276 } elseif ($complete) {
3277 // We are resharing something that isn't a DFRN or Diaspora post.
3278 // So we have to return "false" on "$complete" to not trigger a reshare.
3281 } elseif (empty($reshared['guid']) && $complete) {
3287 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3288 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3289 if (!empty($contact['addr'])) {
3290 $ret['root_handle'] = $contact['addr'];
3294 if (empty($ret) && !$complete) {
3302 * Create an event array
3304 * @param integer $event_id The id of the event
3306 * @return array with event data
3307 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3309 private static function buildEvent($event_id)
3311 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3312 if (!DBA::isResult($r)) {
3320 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3321 if (!DBA::isResult($r)) {
3327 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3328 if (!DBA::isResult($r)) {
3334 $eventdata['author'] = self::myHandle($owner);
3336 if ($event['guid']) {
3337 $eventdata['guid'] = $event['guid'];
3340 $mask = DateTimeFormat::ATOM;
3342 /// @todo - establish "all day" events in Friendica
3343 $eventdata["all_day"] = "false";
3345 $eventdata['timezone'] = 'UTC';
3346 if (!$event['adjust'] && $user['timezone']) {
3347 $eventdata['timezone'] = $user['timezone'];
3350 if ($event['start']) {
3351 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3353 if ($event['finish'] && !$event['nofinish']) {
3354 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3356 if ($event['summary']) {
3357 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3359 if ($event['desc']) {
3360 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3362 if ($event['location']) {
3363 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3364 $coord = Map::getCoordinates($event['location']);
3367 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3368 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3369 $location["lat"] = $coord['lat'];
3370 $location["lng"] = $coord['lon'];
3372 $location["lat"] = 0;
3373 $location["lng"] = 0;
3375 $eventdata['location'] = $location;
3382 * Create a post (status message or reshare)
3384 * @param array $item The item that will be exported
3385 * @param array $owner the array of the item owner
3388 * 'type' -> Message type ("status_message" or "reshare")
3389 * 'message' -> Array of XML elements of the status
3390 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3391 * @throws \ImagickException
3393 public static function buildStatus(array $item, array $owner)
3395 $cachekey = "diaspora:buildStatus:".$item['guid'];
3397 $result = DI::cache()->get($cachekey);
3398 if (!is_null($result)) {
3402 $myaddr = self::myHandle($owner);
3404 $public = ($item["private"] == Item::PRIVATE ? "false" : "true");
3405 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3406 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3408 // Detect a share element and do a reshare
3409 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) {
3410 $message = ["author" => $myaddr,
3411 "guid" => $item["guid"],
3412 "created_at" => $created,
3413 "root_author" => $ret["root_handle"],
3414 "root_guid" => $ret["root_guid"],
3415 "provider_display_name" => $item["app"],
3416 "public" => $public];
3420 $title = $item["title"];
3421 $body = $item["body"];
3423 // Fetch the title from an attached link - if there is one
3424 if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3425 $page_data = BBCode::getAttachmentData($item['body']);
3426 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3427 $title = $page_data['title'];
3431 if ($item['author-link'] != $item['owner-link']) {
3432 $body = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'],
3433 $item['plink'], $item['created']) . $body . '[/share]';
3436 // convert to markdown
3437 $body = html_entity_decode(BBCode::toMarkdown($body));
3440 if (strlen($title)) {
3441 $body = "### ".html_entity_decode($title)."\n\n".$body;
3444 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]);
3445 if (!empty($attachments)) {
3446 $body .= "\n".DI::l10n()->t("Attachments:")."\n";
3447 foreach ($attachments as $attachment) {
3448 $body .= "[" . $attachment['description'] . "](" . $attachment['url'] . ")\n";
3454 if ($item["location"] != "")
3455 $location["address"] = $item["location"];
3457 if ($item["coord"] != "") {
3458 $coord = explode(" ", $item["coord"]);
3459 $location["lat"] = $coord[0];
3460 $location["lng"] = $coord[1];
3463 $message = ["author" => $myaddr,
3464 "guid" => $item["guid"],
3465 "created_at" => $created,
3466 "edited_at" => $edited,
3467 "public" => $public,
3469 "provider_display_name" => $item["app"],
3470 "location" => $location];
3472 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3473 if (!isset($location["lat"]) || !isset($location["lng"])) {
3474 unset($message["location"]);
3477 if ($item['event-id'] > 0) {
3478 $event = self::buildEvent($item['event-id']);
3479 if (count($event)) {
3480 $message['event'] = $event;
3482 if (!empty($event['location']['address']) &&
3483 !empty($event['location']['lat']) &&
3484 !empty($event['location']['lng'])) {
3485 $message['location'] = $event['location'];
3488 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3489 // $message['text'] = '';
3493 $type = "status_message";
3496 $msg = ["type" => $type, "message" => $message];
3498 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3503 private static function prependParentAuthorMention($body, $profile_url)
3505 $profile = Contact::getByURL($profile_url, false, ['addr', 'name', 'contact-type']);
3506 if (!empty($profile['addr'])
3507 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3508 && !strstr($body, $profile['addr'])
3509 && !strstr($body, $profile_url)
3511 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3520 * @param array $item The item that will be exported
3521 * @param array $owner the array of the item owner
3522 * @param array $contact Target of the communication
3523 * @param bool $public_batch Is it a public post?
3525 * @return int The result of the transmission
3526 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3527 * @throws \ImagickException
3529 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3531 $status = self::buildStatus($item, $owner);
3533 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3537 * Creates a "like" object
3539 * @param array $item The item that will be exported
3540 * @param array $owner the array of the item owner
3542 * @return array The data for a "like"
3543 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3545 private static function constructLike(array $item, array $owner)
3547 $parent = Post::selectFirst(['guid', 'uri', 'thr-parent'], ['uri' => $item["thr-parent"]]);
3548 if (!DBA::isResult($parent)) {
3552 $target_type = ($parent["uri"] === $parent["thr-parent"] ? "Post" : "Comment");
3554 if ($item['verb'] === Activity::LIKE) {
3556 } elseif ($item['verb'] === Activity::DISLIKE) {
3557 $positive = "false";
3560 return(["author" => self::myHandle($owner),
3561 "guid" => $item["guid"],
3562 "parent_guid" => $parent["guid"],
3563 "parent_type" => $target_type,
3564 "positive" => $positive,
3565 "author_signature" => ""]);
3569 * Creates an "EventParticipation" object
3571 * @param array $item The item that will be exported
3572 * @param array $owner the array of the item owner
3574 * @return array The data for an "EventParticipation"
3575 * @throws \Exception
3577 private static function constructAttend(array $item, array $owner)
3579 $parent = Post::selectFirst(['guid'], ['uri' => $item['thr-parent']]);
3580 if (!DBA::isResult($parent)) {
3584 switch ($item['verb']) {
3585 case Activity::ATTEND:
3586 $attend_answer = 'accepted';
3588 case Activity::ATTENDNO:
3589 $attend_answer = 'declined';
3591 case Activity::ATTENDMAYBE:
3592 $attend_answer = 'tentative';
3595 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3599 return(["author" => self::myHandle($owner),
3600 "guid" => $item["guid"],
3601 "parent_guid" => $parent["guid"],
3602 "status" => $attend_answer,
3603 "author_signature" => ""]);
3607 * Creates the object for a comment
3609 * @param array $item The item that will be exported
3610 * @param array $owner the array of the item owner
3612 * @return array|false The data for a comment
3613 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3615 private static function constructComment(array $item, array $owner)
3617 $cachekey = "diaspora:constructComment:".$item['guid'];
3619 $result = DI::cache()->get($cachekey);
3620 if (!is_null($result)) {
3624 $toplevel_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3625 if (!DBA::isResult($toplevel_item)) {
3626 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3630 $thread_parent_item = $toplevel_item;
3631 if ($item['thr-parent'] != $item['parent-uri']) {
3632 $thread_parent_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3635 $body = $item["body"];
3637 // The replied to autor mention is prepended for clarity if:
3638 // - Item replied isn't yours
3639 // - Item is public or explicit mentions are disabled
3640 // - Implicit mentions are enabled
3642 $item['author-id'] != $thread_parent_item['author-id']
3643 && ($thread_parent_item['gravity'] != GRAVITY_PARENT)
3644 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3645 && !DI::config()->get('system', 'disable_implicit_mentions')
3647 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3650 $text = html_entity_decode(BBCode::toMarkdown($body));
3651 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3652 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3655 "author" => self::myHandle($owner),
3656 "guid" => $item["guid"],
3657 "created_at" => $created,
3658 "edited_at" => $edited,
3659 "parent_guid" => $toplevel_item["guid"],
3661 "author_signature" => ""
3664 // Send the thread parent guid only if it is a threaded comment
3665 if ($item['thr-parent'] != $item['parent-uri']) {
3666 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3669 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3675 * Send a like or a comment
3677 * @param array $item The item that will be exported
3678 * @param array $owner the array of the item owner
3679 * @param array $contact Target of the communication
3680 * @param bool $public_batch Is it a public post?
3682 * @return int The result of the transmission
3683 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3684 * @throws \ImagickException
3686 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3688 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3689 $message = self::constructAttend($item, $owner);
3690 $type = "event_participation";
3691 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3692 $message = self::constructLike($item, $owner);
3694 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3695 $message = self::constructComment($item, $owner);
3699 if (empty($message)) {
3703 $message["author_signature"] = self::signature($owner, $message);
3705 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3709 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3711 * @param array $item The item that will be exported
3712 * @param array $owner the array of the item owner
3713 * @param array $contact Target of the communication
3714 * @param bool $public_batch Is it a public post?
3716 * @return int The result of the transmission
3717 * @throws \Exception
3719 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3721 if ($item["deleted"]) {
3722 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3723 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3729 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3731 $msg = json_decode($item['signed_text'], true);
3734 if (is_array($msg)) {
3735 foreach ($msg as $field => $data) {
3736 if (!$item["deleted"]) {
3737 if ($field == "diaspora_handle") {
3740 if ($field == "target_type") {
3741 $field = "parent_type";
3745 $message[$field] = $data;
3748 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
3751 $message["parent_author_signature"] = self::signature($owner, $message);
3753 Logger::info('Relayed data', ['msg' => $message]);
3755 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3759 * Sends a retraction (deletion) of a message, like or comment
3761 * @param array $item The item that will be exported
3762 * @param array $owner the array of the item owner
3763 * @param array $contact Target of the communication
3764 * @param bool $public_batch Is it a public post?
3765 * @param bool $relay Is the retraction transmitted from a relay?
3767 * @return int The result of the transmission
3768 * @throws \Exception
3770 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
3772 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3774 $msg_type = "retraction";
3776 if ($item['gravity'] == GRAVITY_PARENT) {
3777 $target_type = "Post";
3778 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3779 $target_type = "Like";
3781 $target_type = "Comment";
3784 $message = ["author" => $itemaddr,
3785 "target_guid" => $item['guid'],
3786 "target_type" => $target_type];
3788 Logger::info('Got message', ['msg' => $message]);
3790 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3796 * @param array $item The item that will be exported
3797 * @param array $owner The owner
3798 * @param array $contact Target of the communication
3800 * @return int The result of the transmission
3801 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3802 * @throws \ImagickException
3804 public static function sendMail(array $item, array $owner, array $contact)
3806 $myaddr = self::myHandle($owner);
3808 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
3809 if (!DBA::isResult($cnv)) {
3810 Logger::log("conversation not found.");
3814 $body = BBCode::toMarkdown($item["body"]);
3815 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3818 "author" => $myaddr,
3819 "guid" => $item["guid"],
3820 "conversation_guid" => $cnv["guid"],
3822 "created_at" => $created,
3825 if ($item["reply"]) {
3830 "author" => $cnv["creator"],
3831 "guid" => $cnv["guid"],
3832 "subject" => $cnv["subject"],
3833 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3834 "participants" => $cnv["recips"],
3838 $type = "conversation";
3841 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
3845 * Split a name into first name and last name
3847 * @param string $name The name
3849 * @return array The array with "first" and "last"
3851 public static function splitName($name) {
3852 $name = trim($name);
3854 // Is the name longer than 64 characters? Then cut the rest of it.
3855 if (strlen($name) > 64) {
3856 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3857 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3859 $name = substr($name, 0, 64);
3863 // Take the first word as first name
3864 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3865 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3866 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3867 return ['first' => $first, 'last' => $last];
3870 // Take the last word as last name
3871 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3872 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3874 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3875 return ['first' => $first, 'last' => $last];
3878 // Take the first 32 characters if there is no space in the first 32 characters
3879 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3880 $first = substr($name, 0, 32);
3881 $last = substr($name, 32);
3882 return ['first' => $first, 'last' => $last];
3885 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3886 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3888 // Check if the last name is longer than 32 characters
3889 if (strlen($last) > 32) {
3890 if (strpos($last, ' ') <= 32) {
3891 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
3893 $last = substr($last, 0, 32);
3897 return ['first' => $first, 'last' => $last];
3901 * Create profile data
3903 * @param int $uid The user id
3905 * @return array The profile data
3906 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3908 private static function createProfileData($uid)
3910 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
3911 if (!DBA::isResult($profile)) {
3915 $handle = $profile["addr"];
3917 $split_name = self::splitName($profile['name']);
3918 $first = $split_name['first'];
3919 $last = $split_name['last'];
3921 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3922 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3923 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3924 $searchable = ($profile['net-publish'] ? 'true' : 'false');
3930 if ($searchable === 'true') {
3933 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
3934 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
3938 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
3941 $about = BBCode::toMarkdown($profile['about']);
3943 $location = $profile['location'];
3945 if ($profile['pub_keywords']) {
3946 $kw = str_replace(',', ' ', $profile['pub_keywords']);
3947 $kw = str_replace(' ', ' ', $kw);
3948 $arr = explode(' ', $kw);
3950 for ($x = 0; $x < 5; $x ++) {
3951 if (!empty($arr[$x])) {
3952 $tags .= '#'. trim($arr[$x]) .' ';
3957 $tags = trim($tags);
3960 return ["author" => $handle,
3961 "first_name" => $first,
3962 "last_name" => $last,
3963 "image_url" => $large,
3964 "image_url_medium" => $medium,
3965 "image_url_small" => $small,
3968 "location" => $location,
3969 "searchable" => $searchable,
3971 "tag_string" => $tags];
3975 * Sends profile data
3977 * @param int $uid The user id
3978 * @param bool $recips optional, default false
3980 * @throws \Exception
3982 public static function sendProfile($uid, $recips = false)
3988 $owner = User::getOwnerDataById($uid);
3995 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3996 AND `uid` = %d AND `rel` != %d",
3997 DBA::escape(Protocol::DIASPORA),
3999 intval(Contact::SHARING)
4007 $message = self::createProfileData($uid);
4009 // @ToDo Split this into single worker jobs
4010 foreach ($recips as $recip) {
4011 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4012 self::buildAndTransmit($owner, $recip, "profile", $message);
4017 * Creates the signature for likes that are created on our system
4019 * @param integer $uid The user of that comment
4020 * @param array $item Item array
4022 * @return array Signed content
4023 * @throws \Exception
4025 public static function createLikeSignature($uid, array $item)
4027 $owner = User::getOwnerDataById($uid);
4028 if (empty($owner)) {
4029 Logger::info('No owner post, so not storing signature');
4033 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4037 $message = self::constructLike($item, $owner);
4038 if ($message === false) {
4042 $message["author_signature"] = self::signature($owner, $message);
4048 * Creates the signature for Comments that are created on our system
4050 * @param integer $uid The user of that comment
4051 * @param array $item Item array
4053 * @return array Signed content
4054 * @throws \Exception
4056 public static function createCommentSignature($uid, array $item)
4058 $owner = User::getOwnerDataById($uid);
4059 if (empty($owner)) {
4060 Logger::info('No owner post, so not storing signature');
4064 $parent = Post::selectFirst(['parent-uri'], ['uri' => $item['thr-parent']]);
4065 if (!DBA::isResult($parent)) {
4069 $item['parent-uri'] = $parent['parent-uri'];
4071 $message = self::constructComment($item, $owner);
4072 if ($message === false) {
4076 $message["author_signature"] = self::signature($owner, $message);