3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol;
24 use Friendica\Content\Feature;
25 use Friendica\Content\PageInfo;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Cache\Duration;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\System;
32 use Friendica\Core\Worker;
33 use Friendica\Database\DBA;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Conversation;
37 use Friendica\Model\FContact;
38 use Friendica\Model\Item;
39 use Friendica\Model\ItemURI;
40 use Friendica\Model\Mail;
41 use Friendica\Model\Post;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Network\Probe;
45 use Friendica\Util\Crypto;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\Map;
48 use Friendica\Util\Network;
49 use Friendica\Util\Strings;
50 use Friendica\Util\XML;
51 use Friendica\Worker\Delivery;
55 * This class contain functions to create and send Diaspora XML files
60 * Mark the relay contact of the given contact for archival
61 * This is called whenever there is a communication issue with the server.
62 * It avoids sending stuff to servers who don't exist anymore.
63 * The relay contact is a technical contact entry that exists once per server.
65 * @param array $contact of the relay contact
67 public static function markRelayForArchival(array $contact)
69 if (!empty($contact['contact-type']) && ($contact['contact-type'] == Contact::TYPE_RELAY)) {
70 // This is already the relay contact, we don't need to fetch it
71 $relay_contact = $contact;
72 } elseif (empty($contact['baseurl'])) {
73 if (!empty($contact['batch'])) {
74 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => Contact::TYPE_RELAY];
75 $relay_contact = DBA::selectFirst('contact', [], $condition);
80 $relay_contact = self::getRelayContact($contact['baseurl'], []);
83 if (!empty($relay_contact)) {
84 Logger::info('Relay contact will be marked for archival', ['id' => $relay_contact['id'], 'url' => $relay_contact['url']]);
85 Contact::markForArchival($relay_contact);
90 * Return a list of relay servers
92 * The list contains not only the official relays but also servers that we serve directly
94 * @param integer $item_id The id of the item that is sent
95 * @param array $contacts The previously fetched contacts
97 * @return array of relay servers
98 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
100 public static function relayList($item_id, array $contacts = [])
104 // Fetching relay servers
105 $serverdata = DI::config()->get("system", "relay_server");
107 if (!empty($serverdata)) {
108 $servers = explode(",", $serverdata);
109 foreach ($servers as $server) {
110 $serverlist[$server] = trim($server);
114 if (DI::config()->get("system", "relay_directly", false)) {
115 // We distribute our stuff based on the parent to ensure that the thread will be complete
116 $parent = Item::selectFirst(['uri-id'], ['id' => $item_id]);
117 if (!DBA::isResult($parent)) {
121 // Servers that want to get all content
122 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
123 while ($server = DBA::fetch($servers)) {
124 $serverlist[$server['url']] = $server['url'];
126 DBA::close($servers);
128 // All tags of the current post
129 $tags = DBA::select('tag-view', ['name'], ['uri-id' => $parent['uri-id'], 'type' => Tag::HASHTAG]);
131 while ($tag = DBA::fetch($tags)) {
132 $taglist[] = $tag['name'];
136 // All servers who wants content with this tag
138 if (!empty($taglist)) {
139 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
140 while ($server = DBA::fetch($tagserver)) {
141 $tagserverlist[] = $server['gserver-id'];
143 DBA::close($tagserver);
146 // All adresses with the given id
147 if (!empty($tagserverlist)) {
148 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
149 while ($server = DBA::fetch($servers)) {
150 $serverlist[$server['url']] = $server['url'];
152 DBA::close($servers);
156 // Now we are collecting all relay contacts
157 foreach ($serverlist as $server_url) {
158 // We don't send messages to ourselves
159 if (Strings::compareLink($server_url, DI::baseUrl())) {
162 $contact = self::getRelayContact($server_url);
163 if (is_bool($contact)) {
168 foreach ($contacts as $entry) {
169 if ($entry['batch'] == $contact['batch']) {
175 $contacts[] = $contact;
183 * Return a contact for a given server address or creates a dummy entry
185 * @param string $server_url The url of the server
186 * @param array $fields Fieldlist
187 * @return array with the contact
190 private static function getRelayContact(string $server_url, array $fields = ['batch', 'id', 'url', 'name', 'network', 'protocol', 'archive', 'blocked'])
192 // Fetch the relay contact
193 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
194 'contact-type' => Contact::TYPE_RELAY];
195 $contact = DBA::selectFirst('contact', $fields, $condition);
197 if (DBA::isResult($contact)) {
198 if ($contact['archive'] || $contact['blocked']) {
203 self::setRelayContact($server_url);
205 $contact = DBA::selectFirst('contact', $fields, $condition);
206 if (DBA::isResult($contact)) {
211 // It should never happen that we arrive here
216 * Update or insert a relay contact
218 * @param string $server_url The url of the server
219 * @param array $network_fields Optional network specific fields
222 public static function setRelayContact($server_url, array $network_fields = [])
224 $fields = ['created' => DateTimeFormat::utcNow(),
225 'name' => 'relay', 'nick' => 'relay', 'url' => $server_url,
226 'nurl' => Strings::normaliseLink($server_url),
227 'network' => Protocol::DIASPORA, 'uid' => 0,
228 'batch' => $server_url . '/receive/public',
229 'rel' => Contact::FOLLOWER, 'blocked' => false,
230 'pending' => false, 'writable' => true,
231 'baseurl' => $server_url, 'contact-type' => Contact::TYPE_RELAY];
233 $fields = array_merge($fields, $network_fields);
235 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url)];
236 $old = DBA::selectFirst('contact', [], $condition);
237 if (DBA::isResult($old)) {
238 unset($fields['created']);
239 $condition = ['id' => $old['id']];
241 Logger::info('Update relay contact', ['fields' => $fields, 'condition' => $condition]);
242 DBA::update('contact', $fields, $condition, $old);
244 Logger::info('Create relay contact', ['fields' => $fields]);
245 Contact::insert($fields);
250 * Return a list of participating contacts for a thread
252 * This is used for the participation feature.
253 * One of the parameters is a contact array.
254 * This is done to avoid duplicates.
256 * @param array $item Item that is about to be delivered
257 * @param array $contacts The previously fetched contacts
259 * @return array of relay servers
262 public static function participantsForThread(array $item, array $contacts)
264 if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
265 Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]);
269 $items = Item::select(['author-id', 'author-link', 'parent-author-link', 'parent-guid', 'guid'],
270 ['parent' => $item['parent'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
271 while ($item = DBA::fetch($items)) {
272 $contact = DBA::selectFirst('contact', ['id', 'url', 'name', 'protocol', 'batch', 'network'],
273 ['id' => $item['author-id']]);
274 if (!DBA::isResult($contact) || empty($contact['batch']) ||
275 ($contact['network'] != Protocol::DIASPORA) ||
276 Strings::compareLink($item['parent-author-link'], $item['author-link'])) {
281 foreach ($contacts as $entry) {
282 if ($entry['batch'] == $contact['batch']) {
288 Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]);
289 $contacts[] = $contact;
298 * verify the envelope and return the verified data
300 * @param string $envelope The magic envelope
302 * @return string verified data
303 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
304 * @throws \ImagickException
306 private static function verifyMagicEnvelope($envelope)
308 $basedom = XML::parseString($envelope, true);
310 if (!is_object($basedom)) {
311 Logger::log("Envelope is no XML file");
315 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
317 if (sizeof($children) == 0) {
318 Logger::log("XML has no children");
324 $data = Strings::base64UrlDecode($children->data);
325 $type = $children->data->attributes()->type[0];
327 $encoding = $children->encoding;
329 $alg = $children->alg;
331 $sig = Strings::base64UrlDecode($children->sig);
332 $key_id = $children->sig->attributes()->key_id[0];
334 $handle = Strings::base64UrlDecode($key_id);
337 $b64url_data = Strings::base64UrlEncode($data);
338 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
340 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
343 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
347 $key = self::key($handle);
349 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
353 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
355 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
363 * encrypts data via AES
365 * @param string $key The AES key
366 * @param string $iv The IV (is used for CBC encoding)
367 * @param string $data The data that is to be encrypted
369 * @return string encrypted data
371 private static function aesEncrypt($key, $iv, $data)
373 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
377 * decrypts data via AES
379 * @param string $key The AES key
380 * @param string $iv The IV (is used for CBC encoding)
381 * @param string $encrypted The encrypted data
383 * @return string decrypted data
385 private static function aesDecrypt($key, $iv, $encrypted)
387 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
391 * Decodes incoming Diaspora message in the new format
393 * @param string $raw raw post message
394 * @param string $privKey The private key of the importer
395 * @param boolean $no_exit Don't do an http exit on error
398 * 'message' -> decoded Diaspora XML message
399 * 'author' -> author diaspora handle
400 * 'key' -> author public key (converted to pkcs#8)
401 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
402 * @throws \ImagickException
404 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
406 $data = json_decode($raw);
408 // Is it a private post? Then decrypt the outer Salmon
409 if (is_object($data)) {
410 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
411 $ciphertext = base64_decode($data->encrypted_magic_envelope);
413 $outer_key_bundle = '';
414 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
415 $j_outer_key_bundle = json_decode($outer_key_bundle);
417 if (!is_object($j_outer_key_bundle)) {
418 Logger::log('Outer Salmon did not verify. Discarding.');
422 throw new \Friendica\Network\HTTPException\BadRequestException();
426 $outer_iv = base64_decode($j_outer_key_bundle->iv);
427 $outer_key = base64_decode($j_outer_key_bundle->key);
429 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
434 $basedom = XML::parseString($xml, true);
436 if (!is_object($basedom)) {
437 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
441 throw new \Friendica\Network\HTTPException\BadRequestException();
445 $base = $basedom->children(ActivityNamespace::SALMON_ME);
447 // Not sure if this cleaning is needed
448 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
450 // Build the signed data
451 $type = $base->data[0]->attributes()->type[0];
452 $encoding = $base->encoding;
454 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
456 // This is the signature
457 $signature = Strings::base64UrlDecode($base->sig);
459 // Get the senders' public key
460 $key_id = $base->sig[0]->attributes()->key_id[0];
461 $author_addr = base64_decode($key_id);
462 if ($author_addr == '') {
463 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
467 throw new \Friendica\Network\HTTPException\BadRequestException();
471 $key = self::key($author_addr);
473 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
477 throw new \Friendica\Network\HTTPException\BadRequestException();
481 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
483 Logger::log('Message did not verify. Discarding.');
487 throw new \Friendica\Network\HTTPException\BadRequestException();
491 return ['message' => (string)Strings::base64UrlDecode($base->data),
492 'author' => XML::unescape($author_addr),
493 'key' => (string)$key];
497 * Decodes incoming Diaspora message in the deprecated format
499 * @param string $xml urldecoded Diaspora salmon
500 * @param string $privKey The private key of the importer
503 * 'message' -> decoded Diaspora XML message
504 * 'author' -> author diaspora handle
505 * 'key' -> author public key (converted to pkcs#8)
506 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
507 * @throws \ImagickException
509 public static function decode(string $xml, string $privKey = '')
512 $basedom = XML::parseString($xml);
514 if (!is_object($basedom)) {
515 Logger::notice('XML is not parseable.');
518 $children = $basedom->children('https://joindiaspora.com/protocol');
520 $inner_aes_key = null;
523 if ($children->header) {
525 $author_link = str_replace('acct:', '', $children->header->author_id);
527 // This happens with posts from a relais
528 if (empty($privKey)) {
529 Logger::info('This is no private post in the old format');
533 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
535 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
536 $ciphertext = base64_decode($encrypted_header->ciphertext);
538 $outer_key_bundle = '';
539 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
541 $j_outer_key_bundle = json_decode($outer_key_bundle);
543 $outer_iv = base64_decode($j_outer_key_bundle->iv);
544 $outer_key = base64_decode($j_outer_key_bundle->key);
546 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
548 Logger::info('decrypted', ['data' => $decrypted]);
549 $idom = XML::parseString($decrypted);
551 $inner_iv = base64_decode($idom->iv);
552 $inner_aes_key = base64_decode($idom->aes_key);
554 $author_link = str_replace('acct:', '', $idom->author_id);
557 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
559 // figure out where in the DOM tree our data is hiding
562 if ($dom->provenance->data) {
563 $base = $dom->provenance;
564 } elseif ($dom->env->data) {
566 } elseif ($dom->data) {
571 Logger::log('unable to locate salmon data in xml');
572 throw new \Friendica\Network\HTTPException\BadRequestException();
576 // Stash the signature away for now. We have to find their key or it won't be good for anything.
577 $signature = Strings::base64UrlDecode($base->sig);
581 // strip whitespace so our data element will return to one big base64 blob
582 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
585 // stash away some other stuff for later
587 $type = $base->data[0]->attributes()->type[0];
588 $keyhash = $base->sig[0]->attributes()->keyhash[0];
589 $encoding = $base->encoding;
593 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
597 $data = Strings::base64UrlDecode($data);
601 $inner_decrypted = $data;
603 // Decode the encrypted blob
604 $inner_encrypted = base64_decode($data);
605 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
609 Logger::log('Could not retrieve author URI.');
610 throw new \Friendica\Network\HTTPException\BadRequestException();
612 // Once we have the author URI, go to the web and try to find their public key
613 // (first this will look it up locally if it is in the fcontact cache)
614 // This will also convert diaspora public key from pkcs#1 to pkcs#8
616 Logger::log('Fetching key for '.$author_link);
617 $key = self::key($author_link);
620 Logger::log('Could not retrieve author key.');
621 throw new \Friendica\Network\HTTPException\BadRequestException();
624 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
627 Logger::log('Message did not verify. Discarding.');
628 throw new \Friendica\Network\HTTPException\BadRequestException();
631 Logger::log('Message verified.');
633 return ['message' => (string)$inner_decrypted,
634 'author' => XML::unescape($author_link),
635 'key' => (string)$key];
640 * Dispatches public messages and find the fitting receivers
642 * @param array $msg The post that will be dispatched
644 * @return int The message id of the generated message, "true" or "false" if there was an error
645 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
646 * @throws \ImagickException
648 public static function dispatchPublic($msg)
650 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
652 Logger::log("diaspora is disabled");
656 if (!($fields = self::validPosting($msg))) {
657 Logger::log("Invalid posting");
661 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
662 $success = self::dispatch($importer, $msg, $fields);
668 * Dispatches the different message types to the different functions
670 * @param array $importer Array of the importer user
671 * @param array $msg The post that will be dispatched
672 * @param SimpleXMLElement $fields SimpleXML object that contains the message
674 * @return int The message id of the generated message, "true" or "false" if there was an error
675 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
676 * @throws \ImagickException
678 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
680 // The sender is the handle of the contact that sent the message.
681 // This will often be different with relayed messages (for example "like" and "comment")
682 $sender = $msg["author"];
684 // This is only needed for private postings since this is already done for public ones before
685 if (is_null($fields)) {
687 if (!($fields = self::validPosting($msg))) {
688 Logger::log("Invalid posting");
695 $type = $fields->getName();
697 Logger::info('Received message', ['type' => $type, 'sender' => $sender, 'user' => $importer["uid"]]);
700 case "account_migration":
702 Logger::log('Message with type ' . $type . ' is not private, quitting.');
705 return self::receiveAccountMigration($importer, $fields);
707 case "account_deletion":
708 return self::receiveAccountDeletion($fields);
711 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
715 Logger::log('Message with type ' . $type . ' is not private, quitting.');
718 return self::receiveContactRequest($importer, $fields);
722 Logger::log('Message with type ' . $type . ' is not private, quitting.');
725 return self::receiveConversation($importer, $msg, $fields);
728 return self::receiveLike($importer, $sender, $fields);
732 Logger::log('Message with type ' . $type . ' is not private, quitting.');
735 return self::receiveMessage($importer, $fields);
737 case "participation":
739 Logger::log('Message with type ' . $type . ' is not private, quitting.');
742 return self::receiveParticipation($importer, $fields);
744 case "photo": // Not implemented
745 return self::receivePhoto($importer, $fields);
747 case "poll_participation": // Not implemented
748 return self::receivePollParticipation($importer, $fields);
752 Logger::log('Message with type ' . $type . ' is not private, quitting.');
755 return self::receiveProfile($importer, $fields);
758 return self::receiveReshare($importer, $fields, $msg["message"]);
761 return self::receiveRetraction($importer, $sender, $fields);
763 case "status_message":
764 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
767 Logger::log("Unknown message type ".$type);
773 * Checks if a posting is valid and fetches the data fields.
775 * This function does not only check the signature.
776 * It also does the conversion between the old and the new diaspora format.
778 * @param array $msg Array with the XML, the sender handle and the sender signature
780 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
781 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
782 * @throws \ImagickException
784 private static function validPosting($msg)
786 $data = XML::parseString($msg["message"]);
788 if (!is_object($data)) {
789 Logger::info('No valid XML', ['message' => $msg['message']]);
793 // Is this the new or the old version?
794 if ($data->getName() == "XML") {
796 foreach ($data->post->children() as $child) {
804 $type = $element->getName();
807 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
809 // All retractions are handled identically from now on.
810 // In the new version there will only be "retraction".
811 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
812 $type = "retraction";
814 if ($type == "request") {
818 $fields = new SimpleXMLElement("<".$type."/>");
821 $author_signature = null;
822 $parent_author_signature = null;
824 foreach ($element->children() as $fieldname => $entry) {
826 // Translation for the old XML structure
827 if ($fieldname == "diaspora_handle") {
828 $fieldname = "author";
830 if ($fieldname == "participant_handles") {
831 $fieldname = "participants";
833 if (in_array($type, ["like", "participation"])) {
834 if ($fieldname == "target_type") {
835 $fieldname = "parent_type";
838 if ($fieldname == "sender_handle") {
839 $fieldname = "author";
841 if ($fieldname == "recipient_handle") {
842 $fieldname = "recipient";
844 if ($fieldname == "root_diaspora_id") {
845 $fieldname = "root_author";
847 if ($type == "status_message") {
848 if ($fieldname == "raw_message") {
852 if ($type == "retraction") {
853 if ($fieldname == "post_guid") {
854 $fieldname = "target_guid";
856 if ($fieldname == "type") {
857 $fieldname = "target_type";
862 if (($fieldname == "author_signature") && ($entry != "")) {
863 $author_signature = base64_decode($entry);
864 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
865 $parent_author_signature = base64_decode($entry);
866 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
867 if ($signed_data != "") {
871 $signed_data .= $entry;
873 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
874 || ($orig_type == "relayable_retraction")
876 XML::copy($entry, $fields, $fieldname);
880 // This is something that shouldn't happen at all.
881 if (in_array($type, ["status_message", "reshare", "profile"])) {
882 if ($msg["author"] != $fields->author) {
883 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
888 // Only some message types have signatures. So we quit here for the other types.
889 if (!in_array($type, ["comment", "like"])) {
892 // No author_signature? This is a must, so we quit.
893 if (!isset($author_signature)) {
894 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
898 if (isset($parent_author_signature)) {
899 $key = self::key($msg["author"]);
901 Logger::info('No key found for parent', ['author' => $msg["author"]]);
905 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
906 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);
911 $key = self::key($fields->author);
913 Logger::info('No key found', ['author' => $fields->author]);
917 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
918 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);
926 * Fetches the public key for a given handle
928 * @param string $handle The handle
930 * @return string The public key
931 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
932 * @throws \ImagickException
934 private static function key($handle)
936 $handle = strval($handle);
938 Logger::log("Fetching diaspora key for: ".$handle);
940 $r = FContact::getByURL($handle);
949 * get a handle (user@domain.tld) from a given contact id
951 * @param int $contact_id The id in the contact table
952 * @param int $pcontact_id The id in the contact table (Used for the public contact)
954 * @return string the handle
957 private static function handleFromContact($contact_id, $pcontact_id = 0)
961 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
963 if ($pcontact_id != 0) {
964 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
966 if (DBA::isResult($contact) && !empty($contact["addr"])) {
967 return strtolower($contact["addr"]);
972 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
976 if (DBA::isResult($r)) {
979 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
981 if ($contact['addr'] != "") {
982 $handle = $contact['addr'];
984 $baseurl_start = strpos($contact['url'], '://') + 3;
985 // allows installations in a subdirectory--not sure how Diaspora will handle
986 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
987 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
988 $handle = $contact['nick'].'@'.$baseurl;
992 return strtolower($handle);
996 * Get a contact id for a given handle
998 * @todo Move to Friendica\Model\Contact
1000 * @param int $uid The user id
1001 * @param string $handle The handle in the format user@domain.tld
1003 * @return array Contact data
1004 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1005 * @throws \ImagickException
1007 private static function contactByHandle($uid, $handle)
1009 return Contact::getByURL($handle, null, [], $uid);
1013 * Checks if the given contact url does support ActivityPub
1015 * @param string $url profile url
1016 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1018 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1019 * @throws \ImagickException
1021 public static function isSupportedByContactUrl($url, $update = null)
1023 return !empty(FContact::getByURL($url, $update));
1027 * Check if posting is allowed for this contact
1029 * @param array $importer Array of the importer user
1030 * @param array $contact The contact that is checked
1031 * @param bool $is_comment Is the check for a comment?
1033 * @return bool is the contact allowed to post?
1035 private static function postAllow(array $importer, array $contact, $is_comment = false)
1038 * Perhaps we were already sharing with this person. Now they're sharing with us.
1039 * That makes us friends.
1040 * Normally this should have handled by getting a request - but this could get lost
1042 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1043 // It is not removed by now. Possibly the code is needed?
1044 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1047 // array('rel' => Contact::FRIEND, 'writable' => true),
1048 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1051 // $contact["rel"] = Contact::FRIEND;
1052 // Logger::log("defining user ".$contact["nick"]." as friend");
1055 // Contact server is blocked
1056 if (Network::isUrlBlocked($contact['url'])) {
1058 // We don't seem to like that person
1059 } elseif ($contact["blocked"]) {
1060 // Maybe blocked, don't accept.
1062 // We are following this person?
1063 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1064 // Yes, then it is fine.
1066 // Is it a post to a community?
1067 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1070 // Is the message a global user or a comment?
1071 } elseif (($importer["uid"] == 0) || $is_comment) {
1072 // Messages for the global users and comments are always accepted
1080 * Fetches the contact id for a handle and checks if posting is allowed
1082 * @param array $importer Array of the importer user
1083 * @param string $handle The checked handle in the format user@domain.tld
1084 * @param bool $is_comment Is the check for a comment?
1086 * @return array The contact data
1087 * @throws \Exception
1089 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1091 $contact = self::contactByHandle($importer["uid"], $handle);
1093 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1094 // If a contact isn't found, we accept it anyway if it is a comment
1095 if ($is_comment && ($importer["uid"] != 0)) {
1096 return self::contactByHandle(0, $handle);
1097 } elseif ($is_comment) {
1104 if (!self::postAllow($importer, $contact, $is_comment)) {
1105 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1112 * Does the message already exists on the system?
1114 * @param int $uid The user id
1115 * @param string $guid The guid of the message
1117 * @return int|bool message id if the message already was stored into the system - or false.
1118 * @throws \Exception
1120 private static function messageExists($uid, $guid)
1122 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1123 if (DBA::isResult($item)) {
1124 Logger::log("message ".$guid." already exists for user ".$uid);
1132 * Checks for links to posts in a message
1134 * @param array $item The item array
1137 private static function fetchGuid(array $item)
1139 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1140 preg_replace_callback(
1142 function ($match) use ($item) {
1143 self::fetchGuidSub($match, $item);
1148 preg_replace_callback(
1149 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1150 function ($match) use ($item) {
1151 self::fetchGuidSub($match, $item);
1158 * Checks for relative /people/* links in an item body to match local
1159 * contacts or prepends the remote host taken from the author link.
1161 * @param string $body The item body to replace links from
1162 * @param string $author_link The author link for missing local contact fallback
1164 * @return string the replaced string
1166 public static function replacePeopleGuid($body, $author_link)
1168 $return = preg_replace_callback(
1169 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1170 function ($match) use ($author_link) {
1172 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1173 // 1 => '0123456789abcdef'
1175 $handle = FContact::getUrlByGuid($match[1]);
1178 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1180 // No local match, restoring absolute remote URL from author scheme and host
1181 $author_url = parse_url($author_link);
1182 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1194 * sub function of "fetchGuid" which checks for links in messages
1196 * @param array $match array containing a link that has to be checked for a message link
1197 * @param array $item The item array
1199 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1200 * @throws \ImagickException
1202 private static function fetchGuidSub($match, $item)
1204 if (!self::storeByGuid($match[1], $item["author-link"])) {
1205 self::storeByGuid($match[1], $item["owner-link"]);
1210 * Fetches an item with a given guid from a given server
1212 * @param string $guid the message guid
1213 * @param string $server The server address
1214 * @param int $uid The user id of the user
1216 * @return int the message id of the stored message or false
1217 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1218 * @throws \ImagickException
1220 private static function storeByGuid($guid, $server, $uid = 0)
1222 $serverparts = parse_url($server);
1224 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1228 $server = $serverparts["scheme"]."://".$serverparts["host"];
1230 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1232 $msg = self::message($guid, $server);
1238 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1240 // Now call the dispatcher
1241 return self::dispatchPublic($msg);
1245 * Fetches a message from a server
1247 * @param string $guid message guid
1248 * @param string $server The url of the server
1249 * @param int $level Endless loop prevention
1252 * 'message' => The message XML
1253 * 'author' => The author handle
1254 * 'key' => The public key of the author
1255 * @throws \Exception
1257 private static function message($guid, $server, $level = 0)
1263 // This will work for new Diaspora servers and Friendica servers from 3.5
1264 $source_url = $server."/fetch/post/".urlencode($guid);
1266 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1268 $envelope = DI::httpRequest()->fetch($source_url);
1270 Logger::log("Envelope was fetched.", Logger::DEBUG);
1271 $x = self::verifyMagicEnvelope($envelope);
1273 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1275 Logger::log("Envelope was verified.", Logger::DEBUG);
1285 $source_xml = XML::parseString($x);
1287 if (!is_object($source_xml)) {
1291 if ($source_xml->post->reshare) {
1292 // Reshare of a reshare - old Diaspora version
1293 Logger::log("Message is a reshare", Logger::DEBUG);
1294 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1295 } elseif ($source_xml->getName() == "reshare") {
1296 // Reshare of a reshare - new Diaspora version
1297 Logger::log("Message is a new reshare", Logger::DEBUG);
1298 return self::message($source_xml->root_guid, $server, ++$level);
1303 // Fetch the author - for the old and the new Diaspora version
1304 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1305 $author = (string)$source_xml->post->status_message->diaspora_handle;
1306 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1307 $author = (string)$source_xml->author;
1310 // If this isn't a "status_message" then quit
1312 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1316 $msg = ["message" => $x, "author" => $author];
1318 $msg["key"] = self::key($msg["author"]);
1324 * Fetches an item with a given URL
1326 * @param string $url the message url
1328 * @return int the message id of the stored message or false
1329 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1330 * @throws \ImagickException
1332 public static function fetchByURL($url, $uid = 0)
1334 // Check for Diaspora (and Friendica) typical paths
1335 if (!preg_match("=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1336 Logger::info('Invalid url', ['url' => $url]);
1340 $guid = urldecode($matches[2]);
1342 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1343 if (DBA::isResult($item)) {
1344 Logger::info('Found', ['id' => $item['id']]);
1348 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1349 $ret = self::storeByGuid($guid, $matches[1], $uid);
1350 Logger::info('Result', ['ret' => $ret]);
1352 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1353 if (DBA::isResult($item)) {
1354 Logger::info('Found', ['id' => $item['id']]);
1357 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1363 * Fetches the item record of a given guid
1365 * @param int $uid The user id
1366 * @param string $guid message guid
1367 * @param string $author The handle of the item
1368 * @param array $contact The contact of the item owner
1370 * @return array the item record
1371 * @throws \Exception
1373 private static function parentItem($uid, $guid, $author, array $contact)
1375 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1376 'author-name', 'author-link', 'author-avatar', 'gravity',
1377 'owner-name', 'owner-link', 'owner-avatar'];
1378 $condition = ['uid' => $uid, 'guid' => $guid];
1379 $item = Item::selectFirst($fields, $condition);
1381 if (!DBA::isResult($item)) {
1382 $person = FContact::getByURL($author);
1383 $result = self::storeByGuid($guid, $person["url"], $uid);
1385 // We don't have an url for items that arrived at the public dispatcher
1386 if (!$result && !empty($contact["url"])) {
1387 $result = self::storeByGuid($guid, $contact["url"], $uid);
1391 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1393 $item = Item::selectFirst($fields, $condition);
1397 if (!DBA::isResult($item)) {
1398 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1401 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1407 * returns contact details
1409 * @param array $def_contact The default contact if the person isn't found
1410 * @param array $person The record of the person
1411 * @param int $uid The user id
1414 * 'cid' => contact id
1415 * 'network' => network type
1416 * @throws \Exception
1418 private static function authorContactByUrl($def_contact, $person, $uid)
1420 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1421 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1422 if (DBA::isResult($contact)) {
1423 $cid = $contact["id"];
1424 $network = $contact["network"];
1426 $cid = $def_contact["id"];
1427 $network = Protocol::DIASPORA;
1430 return ["cid" => $cid, "network" => $network];
1434 * Is the profile a hubzilla profile?
1436 * @param string $url The profile link
1438 * @return bool is it a hubzilla server?
1440 private static function isHubzilla($url)
1442 return(strstr($url, '/channel/'));
1446 * Generate a post link with a given handle and message guid
1448 * @param string $addr The user handle
1449 * @param string $guid message guid
1450 * @param string $parent_guid optional parent guid
1452 * @return string the post link
1453 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1454 * @throws \ImagickException
1456 private static function plink($addr, $guid, $parent_guid = '')
1458 $contact = Contact::getByURL($addr);
1459 if (empty($contact)) {
1460 Logger::info('No contact data for address', ['addr' => $addr]);
1464 if (empty($contact['baseurl'])) {
1465 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1466 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1470 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1471 if (!empty($gserver['platform'])) {
1472 $platform = strtolower($gserver['platform']);
1473 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1476 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1477 if (self::isHubzilla($contact['url'])) {
1478 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1479 $platform = 'hubzilla';
1480 } elseif ($contact['network'] == Protocol::DFRN) {
1481 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1482 $platform = 'friendica';
1486 if ($platform == 'friendica') {
1487 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1490 if ($platform == 'hubzilla') {
1491 return $contact['baseurl'] . '/item/' . $guid;
1494 if ($platform == 'socialhome') {
1495 return $contact['baseurl'] . '/content/' . $guid;
1498 if ($platform != 'diaspora') {
1499 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1503 if ($parent_guid != '') {
1504 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1506 return $contact['baseurl'] . '/posts/' . $guid;
1511 * Receives account migration
1513 * @param array $importer Array of the importer user
1514 * @param object $data The message object
1516 * @return bool Success
1517 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1518 * @throws \ImagickException
1520 private static function receiveAccountMigration(array $importer, $data)
1522 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1523 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1524 $signature = Strings::escapeTags(XML::unescape($data->signature));
1526 $contact = self::contactByHandle($importer["uid"], $old_handle);
1528 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1532 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1535 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1536 $key = self::key($old_handle);
1537 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1538 Logger::log('No valid signature for migration.');
1542 // Update the profile
1543 self::receiveProfile($importer, $data->profile);
1545 // change the technical stuff in contact
1546 $data = Probe::uri($new_handle);
1547 if ($data['network'] == Protocol::PHANTOM) {
1548 Logger::log('Account for '.$new_handle." couldn't be probed.");
1552 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1553 'name' => $data['name'], 'nick' => $data['nick'],
1554 'addr' => $data['addr'], 'batch' => $data['batch'],
1555 'notify' => $data['notify'], 'poll' => $data['poll'],
1556 'network' => $data['network']];
1558 DBA::update('contact', $fields, ['addr' => $old_handle]);
1560 Logger::log('Contacts are updated.');
1566 * Processes an account deletion
1568 * @param object $data The message object
1570 * @return bool Success
1571 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1573 private static function receiveAccountDeletion($data)
1575 $author = Strings::escapeTags(XML::unescape($data->author));
1577 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1578 while ($contact = DBA::fetch($contacts)) {
1579 Contact::remove($contact["id"]);
1581 DBA::close($contacts);
1583 Logger::log('Removed contacts for ' . $author);
1589 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1591 * @param string $author Author handle
1592 * @param string $guid Message guid
1593 * @param boolean $onlyfound Only return uri when found in the database
1595 * @return string The constructed uri or the one from our database
1596 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1597 * @throws \ImagickException
1599 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1601 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1602 if (DBA::isResult($item)) {
1603 return $item["uri"];
1604 } elseif (!$onlyfound) {
1605 $person = FContact::getByURL($author);
1607 $parts = parse_url($person['url']);
1608 unset($parts['path']);
1609 $host_url = Network::unparseURL($parts);
1611 return $host_url . '/objects/' . $guid;
1618 * Fetch the guid from our database with a given uri
1620 * @param string $uri Message uri
1621 * @param string $uid Author handle
1623 * @return string The post guid
1624 * @throws \Exception
1626 private static function getGuidFromUri($uri, $uid)
1628 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1629 if (DBA::isResult($item)) {
1630 return $item["guid"];
1637 * Store the mentions in the tag table
1639 * @param integer $uriid
1640 * @param string $text
1642 private static function storeMentions(int $uriid, string $text)
1644 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1645 if (empty($matches)) {
1650 * Matching values for the preg match
1651 * [1] = mention type (@ or !)
1652 * [2] = name (optional)
1656 foreach ($matches as $match) {
1657 if (empty($match)) {
1661 $person = FContact::getByURL($match[3]);
1662 if (empty($person)) {
1666 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1671 * Processes an incoming comment
1673 * @param array $importer Array of the importer user
1674 * @param string $sender The sender of the message
1675 * @param object $data The message object
1676 * @param string $xml The original XML of the message
1678 * @return int The message id of the generated comment or "false" if there was an error
1679 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1680 * @throws \ImagickException
1682 private static function receiveComment(array $importer, $sender, $data, $xml)
1684 $author = Strings::escapeTags(XML::unescape($data->author));
1685 $guid = Strings::escapeTags(XML::unescape($data->guid));
1686 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1687 $text = XML::unescape($data->text);
1689 if (isset($data->created_at)) {
1690 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1692 $created_at = DateTimeFormat::utcNow();
1695 if (isset($data->thread_parent_guid)) {
1696 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1697 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1702 $contact = self::allowedContactByHandle($importer, $sender, true);
1707 $message_id = self::messageExists($importer["uid"], $guid);
1712 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1713 if (!$parent_item) {
1717 $person = FContact::getByURL($author);
1718 if (!is_array($person)) {
1719 Logger::log("unable to find author details");
1723 // Fetch the contact id - if we know this contact
1724 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1728 $datarray["uid"] = $importer["uid"];
1729 $datarray["contact-id"] = $author_contact["cid"];
1730 $datarray["network"] = $author_contact["network"];
1732 $datarray["author-link"] = $person["url"];
1733 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1735 $datarray["owner-link"] = $contact["url"];
1736 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1738 $datarray["guid"] = $guid;
1739 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1740 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1742 $datarray["verb"] = Activity::POST;
1743 $datarray["gravity"] = GRAVITY_COMMENT;
1745 if ($thr_uri != "") {
1746 $datarray["parent-uri"] = $thr_uri;
1748 $datarray["parent-uri"] = $parent_item["uri"];
1751 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1753 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1754 $datarray["source"] = $xml;
1756 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1758 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1759 $body = Markdown::toBBCode($text);
1761 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1763 self::storeMentions($datarray['uri-id'], $text);
1764 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
1766 self::fetchGuid($datarray);
1768 // If we are the origin of the parent we store the original data.
1769 // We notify our followers during the item storage.
1770 if ($parent_item["origin"]) {
1771 $datarray['diaspora_signed_text'] = json_encode($data);
1774 $message_id = Item::insert($datarray);
1776 if ($message_id <= 0) {
1781 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1782 if ($datarray['uid'] == 0) {
1783 Item::distribute($message_id, json_encode($data));
1791 * processes and stores private messages
1793 * @param array $importer Array of the importer user
1794 * @param array $contact The contact of the message
1795 * @param object $data The message object
1796 * @param array $msg Array of the processed message, author handle and key
1797 * @param object $mesg The private message
1798 * @param array $conversation The conversation record to which this message belongs
1800 * @return bool "true" if it was successful
1801 * @throws \Exception
1803 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1805 $author = Strings::escapeTags(XML::unescape($data->author));
1806 $guid = Strings::escapeTags(XML::unescape($data->guid));
1807 $subject = Strings::escapeTags(XML::unescape($data->subject));
1809 // "diaspora_handle" is the element name from the old version
1810 // "author" is the element name from the new version
1811 if ($mesg->author) {
1812 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1813 } elseif ($mesg->diaspora_handle) {
1814 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1819 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1820 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1821 $msg_text = XML::unescape($mesg->text);
1822 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1824 if ($msg_conversation_guid != $guid) {
1825 Logger::log("message conversation guid does not belong to the current conversation.");
1829 $body = Markdown::toBBCode($msg_text);
1830 $message_uri = $msg_author.":".$msg_guid;
1832 $person = FContact::getByURL($msg_author);
1834 return Mail::insert([
1835 'uid' => $importer['uid'],
1836 'guid' => $msg_guid,
1837 'convid' => $conversation['id'],
1838 'from-name' => $person['name'],
1839 'from-photo' => $person['photo'],
1840 'from-url' => $person['url'],
1841 'contact-id' => $contact['id'],
1842 'title' => $subject,
1844 'uri' => $message_uri,
1845 'parent-uri' => $author . ':' . $guid,
1846 'created' => $msg_created_at
1851 * Processes new private messages (answers to private messages are processed elsewhere)
1853 * @param array $importer Array of the importer user
1854 * @param array $msg Array of the processed message, author handle and key
1855 * @param object $data The message object
1857 * @return bool Success
1858 * @throws \Exception
1860 private static function receiveConversation(array $importer, $msg, $data)
1862 $author = Strings::escapeTags(XML::unescape($data->author));
1863 $guid = Strings::escapeTags(XML::unescape($data->guid));
1864 $subject = Strings::escapeTags(XML::unescape($data->subject));
1865 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1866 $participants = Strings::escapeTags(XML::unescape($data->participants));
1868 $messages = $data->message;
1870 if (!count($messages)) {
1871 Logger::log("empty conversation");
1875 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1880 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1881 if (!DBA::isResult($conversation)) {
1883 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1884 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1885 intval($importer["uid"]),
1887 DBA::escape($author),
1888 DBA::escape($created_at),
1889 DBA::escape(DateTimeFormat::utcNow()),
1890 DBA::escape($subject),
1891 DBA::escape($participants)
1894 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1897 if (!$conversation) {
1898 Logger::log("unable to create conversation.");
1902 foreach ($messages as $mesg) {
1903 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1910 * Processes "like" messages
1912 * @param array $importer Array of the importer user
1913 * @param string $sender The sender of the message
1914 * @param object $data The message object
1916 * @return int The message id of the generated like or "false" if there was an error
1917 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1918 * @throws \ImagickException
1920 private static function receiveLike(array $importer, $sender, $data)
1922 $author = Strings::escapeTags(XML::unescape($data->author));
1923 $guid = Strings::escapeTags(XML::unescape($data->guid));
1924 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1925 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
1926 $positive = Strings::escapeTags(XML::unescape($data->positive));
1928 // likes on comments aren't supported by Diaspora - only on posts
1929 // But maybe this will be supported in the future, so we will accept it.
1930 if (!in_array($parent_type, ["Post", "Comment"])) {
1934 $contact = self::allowedContactByHandle($importer, $sender, true);
1939 $message_id = self::messageExists($importer["uid"], $guid);
1944 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1945 if (!$parent_item) {
1949 $person = FContact::getByURL($author);
1950 if (!is_array($person)) {
1951 Logger::log("unable to find author details");
1955 // Fetch the contact id - if we know this contact
1956 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1958 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1959 // We would accept this anyhow.
1960 if ($positive == "true") {
1961 $verb = Activity::LIKE;
1963 $verb = Activity::DISLIKE;
1968 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1970 $datarray["uid"] = $importer["uid"];
1971 $datarray["contact-id"] = $author_contact["cid"];
1972 $datarray["network"] = $author_contact["network"];
1974 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
1975 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1977 $datarray["guid"] = $guid;
1978 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1980 $datarray["verb"] = $verb;
1981 $datarray["gravity"] = GRAVITY_ACTIVITY;
1982 $datarray["parent-uri"] = $parent_item["uri"];
1984 $datarray["object-type"] = Activity\ObjectType::NOTE;
1986 $datarray["body"] = $verb;
1988 // Diaspora doesn't provide a date for likes
1989 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
1991 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1992 if ($parent_item['gravity'] != GRAVITY_PARENT) {
1993 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item['parent']]);
1994 $origin = $toplevel["origin"];
1996 $origin = $parent_item["origin"];
1999 // If we are the origin of the parent we store the original data.
2000 // We notify our followers during the item storage.
2002 $datarray['diaspora_signed_text'] = json_encode($data);
2005 $message_id = Item::insert($datarray);
2007 if ($message_id <= 0) {
2012 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2013 if ($datarray['uid'] == 0) {
2014 Item::distribute($message_id, json_encode($data));
2022 * Processes private messages
2024 * @param array $importer Array of the importer user
2025 * @param object $data The message object
2027 * @return bool Success?
2028 * @throws \Exception
2030 private static function receiveMessage(array $importer, $data)
2032 $author = Strings::escapeTags(XML::unescape($data->author));
2033 $guid = Strings::escapeTags(XML::unescape($data->guid));
2034 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2035 $text = XML::unescape($data->text);
2036 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2038 $contact = self::allowedContactByHandle($importer, $author, true);
2043 $conversation = null;
2045 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2046 $conversation = DBA::selectFirst('conv', [], $condition);
2048 if (!DBA::isResult($conversation)) {
2049 Logger::log("conversation not available.");
2053 $message_uri = $author.":".$guid;
2055 $person = FContact::getByURL($author);
2057 Logger::log("unable to find author details");
2061 $body = Markdown::toBBCode($text);
2063 $body = self::replacePeopleGuid($body, $person["url"]);
2065 return Mail::insert([
2066 'uid' => $importer['uid'],
2068 'convid' => $conversation['id'],
2069 'from-name' => $person['name'],
2070 'from-photo' => $person['photo'],
2071 'from-url' => $person['url'],
2072 'contact-id' => $contact['id'],
2073 'title' => $conversation['subject'],
2076 'uri' => $message_uri,
2077 'parent-uri' => $author.":".$conversation['guid'],
2078 'created' => $created_at
2083 * Processes participations - unsupported by now
2085 * @param array $importer Array of the importer user
2086 * @param object $data The message object
2088 * @return bool success
2089 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2090 * @throws \ImagickException
2092 private static function receiveParticipation(array $importer, $data)
2094 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2095 $guid = Strings::escapeTags(XML::unescape($data->guid));
2096 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2098 $contact = self::allowedContactByHandle($importer, $author, true);
2103 if (self::messageExists($importer["uid"], $guid)) {
2107 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2108 if (!$parent_item) {
2112 if (!$parent_item['origin']) {
2113 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
2116 if (!in_array($parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
2117 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
2121 $person = FContact::getByURL($author);
2122 if (!is_array($person)) {
2123 Logger::log("Person not found: ".$author);
2127 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2129 // Store participation
2132 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2134 $datarray["uid"] = $importer["uid"];
2135 $datarray["contact-id"] = $author_contact["cid"];
2136 $datarray["network"] = $author_contact["network"];
2138 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2139 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2141 $datarray["guid"] = $guid;
2142 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2144 $datarray["verb"] = Activity::FOLLOW;
2145 $datarray["gravity"] = GRAVITY_ACTIVITY;
2146 $datarray["parent-uri"] = $parent_item["uri"];
2148 $datarray["object-type"] = Activity\ObjectType::NOTE;
2150 $datarray["body"] = Activity::FOLLOW;
2152 // Diaspora doesn't provide a date for a participation
2153 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2155 $message_id = Item::insert($datarray);
2157 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
2159 // Send all existing comments and likes to the requesting server
2160 $comments = Item::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb'],
2161 ['parent' => $parent_item['id'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
2162 while ($comment = Item::fetch($comments)) {
2163 if (in_array($comment['verb'], [Activity::FOLLOW, Activity::TAG])) {
2164 Logger::info('participation messages are not relayed', ['item' => $comment['id']]);
2168 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
2169 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2173 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
2174 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2178 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact["cid"]]);
2179 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $author_contact["cid"])) {
2180 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2183 DBA::close($comments);
2189 * Processes photos - unneeded
2191 * @param array $importer Array of the importer user
2192 * @param object $data The message object
2194 * @return bool always true
2196 private static function receivePhoto(array $importer, $data)
2198 // There doesn't seem to be a reason for this function,
2199 // since the photo data is transmitted in the status message as well
2204 * Processes poll participations - unssupported
2206 * @param array $importer Array of the importer user
2207 * @param object $data The message object
2209 * @return bool always true
2211 private static function receivePollParticipation(array $importer, $data)
2213 // We don't support polls by now
2218 * Processes incoming profile updates
2220 * @param array $importer Array of the importer user
2221 * @param object $data The message object
2223 * @return bool Success
2224 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2225 * @throws \ImagickException
2227 private static function receiveProfile(array $importer, $data)
2229 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2231 $contact = self::contactByHandle($importer["uid"], $author);
2236 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2237 $image_url = XML::unescape($data->image_url);
2238 $birthday = XML::unescape($data->birthday);
2239 $about = Markdown::toBBCode(XML::unescape($data->bio));
2240 $location = Markdown::toBBCode(XML::unescape($data->location));
2241 $searchable = (XML::unescape($data->searchable) == "true");
2242 $nsfw = (XML::unescape($data->nsfw) == "true");
2243 $tags = XML::unescape($data->tag_string);
2245 $tags = explode("#", $tags);
2248 foreach ($tags as $tag) {
2249 $tag = trim(strtolower($tag));
2255 $keywords = implode(", ", $keywords);
2257 $handle_parts = explode("@", $author);
2258 $nick = $handle_parts[0];
2261 $name = $handle_parts[0];
2264 if (preg_match("|^https?://|", $image_url) === 0) {
2265 $image_url = "http://".$handle_parts[1].$image_url;
2268 Contact::updateAvatar($contact["id"], $image_url);
2270 // Generic birthday. We don't know the timezone. The year is irrelevant.
2272 $birthday = str_replace("1000", "1901", $birthday);
2274 if ($birthday != "") {
2275 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2278 // this is to prevent multiple birthday notifications in a single year
2279 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2281 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2282 $birthday = $contact["bd"];
2285 $fields = ['name' => $name, 'location' => $location,
2286 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2287 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2288 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2290 if (!empty($birthday)) {
2291 $fields['bd'] = $birthday;
2294 DBA::update('contact', $fields, ['id' => $contact['id']]);
2296 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2302 * Processes incoming friend requests
2304 * @param array $importer Array of the importer user
2305 * @param array $contact The contact that send the request
2307 * @throws \Exception
2309 private static function receiveRequestMakeFriend(array $importer, array $contact)
2311 if ($contact["rel"] == Contact::SHARING) {
2314 ['rel' => Contact::FRIEND, 'writable' => true],
2315 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2321 * Processes incoming sharing notification
2323 * @param array $importer Array of the importer user
2324 * @param object $data The message object
2326 * @return bool Success
2327 * @throws \Exception
2329 private static function receiveContactRequest(array $importer, $data)
2331 $author = XML::unescape($data->author);
2332 $recipient = XML::unescape($data->recipient);
2334 if (!$author || !$recipient) {
2338 // the current protocol version doesn't know these fields
2339 // That means that we will assume their existance
2340 if (isset($data->following)) {
2341 $following = (XML::unescape($data->following) == "true");
2346 if (isset($data->sharing)) {
2347 $sharing = (XML::unescape($data->sharing) == "true");
2352 $contact = self::contactByHandle($importer["uid"], $author);
2354 // perhaps we were already sharing with this person. Now they're sharing with us.
2355 // That makes us friends.
2358 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2359 self::receiveRequestMakeFriend($importer, $contact);
2361 // refetch the contact array
2362 $contact = self::contactByHandle($importer["uid"], $author);
2364 // If we are now friends, we are sending a share message.
2365 // Normally we needn't to do so, but the first message could have been vanished.
2366 if (in_array($contact["rel"], [Contact::FRIEND])) {
2367 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2368 if (DBA::isResult($user)) {
2369 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2370 self::sendShare($user, $contact);
2375 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2376 Contact::removeFollower($importer, $contact);
2381 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2382 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2384 } elseif (!$following && !$sharing) {
2385 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2387 } elseif (!$following && $sharing) {
2388 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2389 } elseif ($following && $sharing) {
2390 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2391 } elseif ($following && !$sharing) {
2392 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2395 $ret = FContact::getByURL($author);
2397 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2398 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2402 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2404 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2409 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2410 'author-link' => $ret['url']];
2412 $result = Contact::addRelationship($importer, $contact, $item, false);
2413 if ($result === true) {
2414 $contact_record = self::contactByHandle($importer['uid'], $author);
2415 if (!$contact_record) {
2416 Logger::info('unable to locate newly created contact record.');
2420 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2421 if (DBA::isResult($user)) {
2422 self::sendShare($user, $contact_record);
2424 // Send the profile data, maybe it weren't transmitted before
2425 self::sendProfile($importer['uid'], [$contact_record]);
2433 * Fetches a message with a given guid
2435 * @param string $guid message guid
2436 * @param string $orig_author handle of the original post
2437 * @return array The fetched item
2438 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2439 * @throws \ImagickException
2441 public static function originalItem($guid, $orig_author)
2444 Logger::log('Empty guid. Quitting.');
2448 // Do we already have this item?
2449 $fields = ['body', 'title', 'attach', 'app', 'created', 'object-type', 'uri', 'guid',
2450 'author-name', 'author-link', 'author-avatar', 'plink'];
2451 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2452 $item = Item::selectFirst($fields, $condition);
2454 if (DBA::isResult($item)) {
2455 Logger::log("reshared message ".$guid." already exists on system.");
2457 // Maybe it is already a reshared item?
2458 // Then refetch the content, if it is a reshare from a reshare.
2459 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2460 if (self::isReshare($item["body"], true)) {
2462 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2463 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2465 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2467 // Add OEmbed and other information to the body
2468 $item["body"] = PageInfo::searchAndAppendToBody($item["body"], false, true);
2476 if (!DBA::isResult($item)) {
2477 if (empty($orig_author)) {
2478 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2482 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2483 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2484 $stored = self::storeByGuid($guid, $server);
2487 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2488 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2489 $stored = self::storeByGuid($guid, $server);
2493 $fields = ['body', 'title', 'attach', 'app', 'created', 'object-type', 'uri', 'guid',
2494 'author-name', 'author-link', 'author-avatar', 'plink'];
2495 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2496 $item = Item::selectFirst($fields, $condition);
2498 if (DBA::isResult($item)) {
2499 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2500 if (self::isReshare($item["body"], false)) {
2501 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2502 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2513 * Stores a reshare activity
2515 * @param array $item Array of reshare post
2516 * @param integer $parent_message_id Id of the parent post
2517 * @param string $guid GUID string of reshare action
2518 * @param string $author Author handle
2520 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2522 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2526 $datarray['uid'] = $item['uid'];
2527 $datarray['contact-id'] = $item['contact-id'];
2528 $datarray['network'] = $item['network'];
2530 $datarray['author-link'] = $item['author-link'];
2531 $datarray['author-id'] = $item['author-id'];
2533 $datarray['owner-link'] = $datarray['author-link'];
2534 $datarray['owner-id'] = $datarray['author-id'];
2536 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2537 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2538 $datarray['parent-uri'] = $parent['uri'];
2540 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2541 $datarray['gravity'] = GRAVITY_ACTIVITY;
2542 $datarray['object-type'] = Activity\ObjectType::NOTE;
2544 $datarray['protocol'] = $item['protocol'];
2546 $datarray['plink'] = self::plink($author, $datarray['guid']);
2547 $datarray['private'] = $item['private'];
2548 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2550 $message_id = Item::insert($datarray);
2553 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2554 if ($datarray['uid'] == 0) {
2555 Item::distribute($message_id);
2561 * Processes a reshare message
2563 * @param array $importer Array of the importer user
2564 * @param object $data The message object
2565 * @param string $xml The original XML of the message
2567 * @return int the message id
2568 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2569 * @throws \ImagickException
2571 private static function receiveReshare(array $importer, $data, $xml)
2573 $author = Strings::escapeTags(XML::unescape($data->author));
2574 $guid = Strings::escapeTags(XML::unescape($data->guid));
2575 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2576 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2577 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2578 /// @todo handle unprocessed property "provider_display_name"
2579 $public = Strings::escapeTags(XML::unescape($data->public));
2581 $contact = self::allowedContactByHandle($importer, $author, false);
2586 $message_id = self::messageExists($importer["uid"], $guid);
2591 $original_item = self::originalItem($root_guid, $root_author);
2592 if (!$original_item) {
2598 $datarray["uid"] = $importer["uid"];
2599 $datarray["contact-id"] = $contact["id"];
2600 $datarray["network"] = Protocol::DIASPORA;
2602 $datarray["author-link"] = $contact["url"];
2603 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2605 $datarray["owner-link"] = $datarray["author-link"];
2606 $datarray["owner-id"] = $datarray["author-id"];
2608 $datarray["guid"] = $guid;
2609 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2610 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2612 $datarray["verb"] = Activity::POST;
2613 $datarray["gravity"] = GRAVITY_PARENT;
2615 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2616 $datarray["source"] = $xml;
2618 /// @todo Copy tag data from original post
2620 $prefix = BBCode::getShareOpeningTag(
2621 $original_item["author-name"],
2622 $original_item["author-link"],
2623 $original_item["author-avatar"],
2624 $original_item["plink"],
2625 $original_item["created"],
2626 $original_item["guid"]
2629 if (!empty($original_item['title'])) {
2630 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2633 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2635 Tag::storeFromBody($datarray['uri-id'], $datarray["body"]);
2637 $datarray["attach"] = $original_item["attach"];
2638 $datarray["app"] = $original_item["app"];
2640 $datarray["plink"] = self::plink($author, $guid);
2641 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2642 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2644 $datarray["object-type"] = $original_item["object-type"];
2646 self::fetchGuid($datarray);
2647 $message_id = Item::insert($datarray);
2649 self::sendParticipation($contact, $datarray);
2651 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2652 if ($root_message_id) {
2653 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2657 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2658 if ($datarray['uid'] == 0) {
2659 Item::distribute($message_id);
2668 * Processes retractions
2670 * @param array $importer Array of the importer user
2671 * @param array $contact The contact of the item owner
2672 * @param object $data The message object
2674 * @return bool success
2675 * @throws \Exception
2677 private static function itemRetraction(array $importer, array $contact, $data)
2679 $author = Strings::escapeTags(XML::unescape($data->author));
2680 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2681 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2683 $person = FContact::getByURL($author);
2684 if (!is_array($person)) {
2685 Logger::log("unable to find author detail for ".$author);
2689 if (empty($contact["url"])) {
2690 $contact["url"] = $person["url"];
2693 // Fetch items that are about to be deleted
2694 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2696 // When we receive a public retraction, we delete every item that we find.
2697 if ($importer['uid'] == 0) {
2698 $condition = ['guid' => $target_guid, 'deleted' => false];
2700 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2703 $r = Item::select($fields, $condition);
2704 if (!DBA::isResult($r)) {
2705 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2709 while ($item = Item::fetch($r)) {
2710 if (strstr($item['file'], '[')) {
2711 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2715 // Fetch the parent item
2716 $parent = Item::selectFirst(['author-link'], ['id' => $item['parent']]);
2718 // Only delete it if the parent author really fits
2719 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2720 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2724 Item::markForDeletion(['id' => $item['id']]);
2726 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item['parent'], Logger::DEBUG);
2733 * Receives retraction messages
2735 * @param array $importer Array of the importer user
2736 * @param string $sender The sender of the message
2737 * @param object $data The message object
2739 * @return bool Success
2740 * @throws \Exception
2742 private static function receiveRetraction(array $importer, $sender, $data)
2744 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2746 $contact = self::contactByHandle($importer["uid"], $sender);
2747 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2748 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2756 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2758 switch ($target_type) {
2763 case "StatusMessage":
2764 return self::itemRetraction($importer, $contact, $data);
2766 case "PollParticipation":
2768 // Currently unsupported
2772 Logger::log("Unknown target type ".$target_type);
2779 * Receives status messages
2781 * @param array $importer Array of the importer user
2782 * @param SimpleXMLElement $data The message object
2783 * @param string $xml The original XML of the message
2785 * @return int The message id of the newly created item
2786 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2787 * @throws \ImagickException
2789 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2791 $author = Strings::escapeTags(XML::unescape($data->author));
2792 $guid = Strings::escapeTags(XML::unescape($data->guid));
2793 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2794 $public = Strings::escapeTags(XML::unescape($data->public));
2795 $text = XML::unescape($data->text);
2796 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2798 $contact = self::allowedContactByHandle($importer, $author, false);
2803 $message_id = self::messageExists($importer["uid"], $guid);
2809 if ($data->location) {
2810 foreach ($data->location->children() as $fieldname => $data) {
2811 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2815 $body = Markdown::toBBCode($text);
2819 // Attach embedded pictures to the body
2821 foreach ($data->photo as $photo) {
2822 $body = "[img]".XML::unescape($photo->remote_photo_path).
2823 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2826 $datarray["object-type"] = Activity\ObjectType::IMAGE;
2828 $datarray["object-type"] = Activity\ObjectType::NOTE;
2830 // Add OEmbed and other information to the body
2831 if (!self::isHubzilla($contact["url"])) {
2832 $body = PageInfo::searchAndAppendToBody($body, false, true);
2836 /// @todo enable support for polls
2837 //if ($data->poll) {
2838 // foreach ($data->poll AS $poll)
2843 /// @todo enable support for events
2845 $datarray["uid"] = $importer["uid"];
2846 $datarray["contact-id"] = $contact["id"];
2847 $datarray["network"] = Protocol::DIASPORA;
2849 $datarray["author-link"] = $contact["url"];
2850 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2852 $datarray["owner-link"] = $datarray["author-link"];
2853 $datarray["owner-id"] = $datarray["author-id"];
2855 $datarray["guid"] = $guid;
2856 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2857 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2859 $datarray["verb"] = Activity::POST;
2860 $datarray["gravity"] = GRAVITY_PARENT;
2862 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2863 $datarray["source"] = $xml;
2865 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2867 self::storeMentions($datarray['uri-id'], $text);
2868 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
2870 if ($provider_display_name != "") {
2871 $datarray["app"] = $provider_display_name;
2874 $datarray["plink"] = self::plink($author, $guid);
2875 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2876 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2878 if (isset($address["address"])) {
2879 $datarray["location"] = $address["address"];
2882 if (isset($address["lat"]) && isset($address["lng"])) {
2883 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2886 self::fetchGuid($datarray);
2887 $message_id = Item::insert($datarray);
2889 self::sendParticipation($contact, $datarray);
2892 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2893 if ($datarray['uid'] == 0) {
2894 Item::distribute($message_id);
2902 /* ************************************************************************************** *
2903 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2904 * ************************************************************************************** */
2907 * returnes the handle of a contact
2909 * @param array $contact contact array
2911 * @return string the handle in the format user@domain.tld
2912 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2914 private static function myHandle(array $contact)
2916 if (!empty($contact["addr"])) {
2917 return $contact["addr"];
2920 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2921 // So - just in case - we build the the address here.
2922 if ($contact["nickname"] != "") {
2923 $nick = $contact["nickname"];
2925 $nick = $contact["nick"];
2928 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
2933 * Creates the data for a private message in the new format
2935 * @param string $msg The message that is to be transmitted
2936 * @param array $user The record of the sender
2937 * @param array $contact Target of the communication
2938 * @param string $prvkey The private key of the sender
2939 * @param string $pubkey The public key of the receiver
2941 * @return string The encrypted data
2942 * @throws \Exception
2944 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
2946 Logger::log("Message: ".$msg, Logger::DATA);
2948 // without a public key nothing will work
2950 Logger::log("pubkey missing: contact id: ".$contact["id"]);
2954 $aes_key = openssl_random_pseudo_bytes(32);
2955 $b_aes_key = base64_encode($aes_key);
2956 $iv = openssl_random_pseudo_bytes(16);
2957 $b_iv = base64_encode($iv);
2959 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2961 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
2963 $encrypted_key_bundle = "";
2964 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
2968 $json_object = json_encode(
2969 ["aes_key" => base64_encode($encrypted_key_bundle),
2970 "encrypted_magic_envelope" => base64_encode($ciphertext)]
2973 return $json_object;
2977 * Creates the envelope for the "fetch" endpoint and for the new format
2979 * @param string $msg The message that is to be transmitted
2980 * @param array $user The record of the sender
2982 * @return string The envelope
2983 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2985 public static function buildMagicEnvelope($msg, array $user)
2987 $b64url_data = Strings::base64UrlEncode($msg);
2988 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
2990 $key_id = Strings::base64UrlEncode(self::myHandle($user));
2991 $type = "application/xml";
2992 $encoding = "base64url";
2993 $alg = "RSA-SHA256";
2994 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
2996 // Fallback if the private key wasn't transmitted in the expected field
2997 if ($user['uprvkey'] == "") {
2998 $user['uprvkey'] = $user['prvkey'];
3001 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3002 $sig = Strings::base64UrlEncode($signature);
3004 $xmldata = ["me:env" => ["me:data" => $data,
3005 "@attributes" => ["type" => $type],
3006 "me:encoding" => $encoding,
3009 "@attributes2" => ["key_id" => $key_id]]];
3011 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3013 return XML::fromArray($xmldata, $xml, false, $namespaces);
3017 * Create the envelope for a message
3019 * @param string $msg The message that is to be transmitted
3020 * @param array $user The record of the sender
3021 * @param array $contact Target of the communication
3022 * @param string $prvkey The private key of the sender
3023 * @param string $pubkey The public key of the receiver
3024 * @param bool $public Is the message public?
3026 * @return string The message that will be transmitted to other servers
3027 * @throws \Exception
3029 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3031 // The message is put into an envelope with the sender's signature
3032 $envelope = self::buildMagicEnvelope($msg, $user);
3034 // Private messages are put into a second envelope, encrypted with the receivers public key
3036 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3043 * Creates a signature for a message
3045 * @param array $owner the array of the owner of the message
3046 * @param array $message The message that is to be signed
3048 * @return string The signature
3050 private static function signature($owner, $message)
3053 unset($sigmsg["author_signature"]);
3054 unset($sigmsg["parent_author_signature"]);
3056 $signed_text = implode(";", $sigmsg);
3058 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3062 * Transmit a message to a target server
3064 * @param array $owner the array of the item owner
3065 * @param array $contact Target of the communication
3066 * @param string $envelope The message that is to be transmitted
3067 * @param bool $public_batch Is it a public post?
3068 * @param string $guid message guid
3070 * @return int Result of the transmission
3071 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3072 * @throws \ImagickException
3074 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3076 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
3081 $logid = Strings::getRandomHex(4);
3083 // We always try to use the data from the fcontact table.
3084 // This is important for transmitting data to Friendica servers.
3085 if (!empty($contact['addr'])) {
3086 $fcontact = FContact::getByURL($contact['addr']);
3087 if (!empty($fcontact)) {
3088 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3092 if (empty($dest_url)) {
3093 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3097 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3101 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3103 if (!intval(DI::config()->get("system", "diaspora_test"))) {
3104 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3106 $postResult = DI::httpRequest()->post($dest_url . "/", $envelope, ["Content-Type: " . $content_type]);
3107 $return_code = $postResult->getReturnCode();
3109 Logger::log("test_mode");
3113 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3115 return $return_code ? $return_code : -1;
3120 * Build the post xml
3122 * @param string $type The message type
3123 * @param array $message The message data
3125 * @return string The post XML
3127 public static function buildPostXml($type, $message)
3129 $data = [$type => $message];
3131 return XML::fromArray($data, $xml);
3135 * Builds and transmit messages
3137 * @param array $owner the array of the item owner
3138 * @param array $contact Target of the communication
3139 * @param string $type The message type
3140 * @param array $message The message data
3141 * @param bool $public_batch Is it a public post?
3142 * @param string $guid message guid
3144 * @return int Result of the transmission
3145 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3146 * @throws \ImagickException
3148 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3150 $msg = self::buildPostXml($type, $message);
3152 Logger::log('message: '.$msg, Logger::DATA);
3153 Logger::log('send guid '.$guid, Logger::DEBUG);
3155 // Fallback if the private key wasn't transmitted in the expected field
3156 if (empty($owner['uprvkey'])) {
3157 $owner['uprvkey'] = $owner['prvkey'];
3160 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3162 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3164 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3166 return $return_code;
3170 * sends a participation (Used to get all further updates)
3172 * @param array $contact Target of the communication
3173 * @param array $item Item array
3175 * @return int The result of the transmission
3176 * @throws \Exception
3178 private static function sendParticipation(array $contact, array $item)
3180 // Don't send notifications for private postings
3181 if ($item['private'] == Item::PRIVATE) {
3185 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3187 $result = DI::cache()->get($cachekey);
3188 if (!is_null($result)) {
3192 // Fetch some user id to have a valid handle to transmit the participation.
3193 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3194 // If the item belongs to a user, we take this user id.
3195 if ($item['uid'] == 0) {
3196 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3197 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3198 $owner = User::getOwnerDataById($first_user['uid']);
3200 $owner = User::getOwnerDataById($item['uid']);
3203 $author = self::myHandle($owner);
3205 $message = ["author" => $author,
3206 "guid" => System::createUUID(),
3207 "parent_type" => "Post",
3208 "parent_guid" => $item["guid"]];
3210 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3212 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3213 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3215 return self::buildAndTransmit($owner, $contact, "participation", $message);
3219 * sends an account migration
3221 * @param array $owner the array of the item owner
3222 * @param array $contact Target of the communication
3223 * @param int $uid User ID
3225 * @return int The result of the transmission
3226 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3227 * @throws \ImagickException
3229 public static function sendAccountMigration(array $owner, array $contact, $uid)
3231 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3232 $profile = self::createProfileData($uid);
3234 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3235 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3237 $message = ["author" => $old_handle,
3238 "profile" => $profile,
3239 "signature" => $signature];
3241 Logger::info('Send account migration', ['msg' => $message]);
3243 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3247 * Sends a "share" message
3249 * @param array $owner the array of the item owner
3250 * @param array $contact Target of the communication
3252 * @return int The result of the transmission
3253 * @throws \Exception
3255 public static function sendShare(array $owner, array $contact)
3258 * @todo support the different possible combinations of "following" and "sharing"
3259 * Currently, Diaspora only interprets the "sharing" field
3261 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3265 switch ($contact["rel"]) {
3266 case Contact::FRIEND:
3270 case Contact::SHARING:
3274 case Contact::FOLLOWER:
3280 $message = ["author" => self::myHandle($owner),
3281 "recipient" => $contact["addr"],
3282 "following" => "true",
3283 "sharing" => "true"];
3285 Logger::info('Send share', ['msg' => $message]);
3287 return self::buildAndTransmit($owner, $contact, "contact", $message);
3291 * sends an "unshare"
3293 * @param array $owner the array of the item owner
3294 * @param array $contact Target of the communication
3296 * @return int The result of the transmission
3297 * @throws \Exception
3299 public static function sendUnshare(array $owner, array $contact)
3301 $message = ["author" => self::myHandle($owner),
3302 "recipient" => $contact["addr"],
3303 "following" => "false",
3304 "sharing" => "false"];
3306 Logger::info('Send unshare', ['msg' => $message]);
3308 return self::buildAndTransmit($owner, $contact, "contact", $message);
3312 * Checks a message body if it is a reshare
3314 * @param string $body The message body that is to be check
3315 * @param bool $complete Should it be a complete check or a simple check?
3317 * @return array|bool Reshare details or "false" if no reshare
3318 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3319 * @throws \ImagickException
3321 public static function isReshare($body, $complete = true)
3323 $body = trim($body);
3325 $reshared = Item::getShareArray(['body' => $body]);
3326 if (empty($reshared)) {
3330 // Skip if it isn't a pure repeated messages
3331 // Does it start with a share?
3332 if (!empty($reshared['comment']) && $complete) {
3336 if (!empty($reshared['guid']) && $complete) {
3337 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3338 $item = Item::selectFirst(['contact-id'], $condition);
3339 if (DBA::isResult($item)) {
3341 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3342 $ret["root_guid"] = $reshared['guid'];
3344 } elseif ($complete) {
3345 // We are resharing something that isn't a DFRN or Diaspora post.
3346 // So we have to return "false" on "$complete" to not trigger a reshare.
3349 } elseif (empty($reshared['guid']) && $complete) {
3355 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3356 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3357 if (!empty($contact['addr'])) {
3358 $ret['root_handle'] = $contact['addr'];
3362 if (empty($ret) && !$complete) {
3370 * Create an event array
3372 * @param integer $event_id The id of the event
3374 * @return array with event data
3375 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3377 private static function buildEvent($event_id)
3379 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3380 if (!DBA::isResult($r)) {
3388 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3389 if (!DBA::isResult($r)) {
3395 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3396 if (!DBA::isResult($r)) {
3402 $eventdata['author'] = self::myHandle($owner);
3404 if ($event['guid']) {
3405 $eventdata['guid'] = $event['guid'];
3408 $mask = DateTimeFormat::ATOM;
3410 /// @todo - establish "all day" events in Friendica
3411 $eventdata["all_day"] = "false";
3413 $eventdata['timezone'] = 'UTC';
3414 if (!$event['adjust'] && $user['timezone']) {
3415 $eventdata['timezone'] = $user['timezone'];
3418 if ($event['start']) {
3419 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3421 if ($event['finish'] && !$event['nofinish']) {
3422 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3424 if ($event['summary']) {
3425 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3427 if ($event['desc']) {
3428 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3430 if ($event['location']) {
3431 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3432 $coord = Map::getCoordinates($event['location']);
3435 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3436 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3437 $location["lat"] = $coord['lat'];
3438 $location["lng"] = $coord['lon'];
3440 $location["lat"] = 0;
3441 $location["lng"] = 0;
3443 $eventdata['location'] = $location;
3450 * Create a post (status message or reshare)
3452 * @param array $item The item that will be exported
3453 * @param array $owner the array of the item owner
3456 * 'type' -> Message type ("status_message" or "reshare")
3457 * 'message' -> Array of XML elements of the status
3458 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3459 * @throws \ImagickException
3461 public static function buildStatus(array $item, array $owner)
3463 $cachekey = "diaspora:buildStatus:".$item['guid'];
3465 $result = DI::cache()->get($cachekey);
3466 if (!is_null($result)) {
3470 $myaddr = self::myHandle($owner);
3472 $public = ($item["private"] == Item::PRIVATE ? "false" : "true");
3473 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3474 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3476 // Detect a share element and do a reshare
3477 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) {
3478 $message = ["author" => $myaddr,
3479 "guid" => $item["guid"],
3480 "created_at" => $created,
3481 "root_author" => $ret["root_handle"],
3482 "root_guid" => $ret["root_guid"],
3483 "provider_display_name" => $item["app"],
3484 "public" => $public];
3488 $title = $item["title"];
3489 $body = $item["body"];
3491 // Fetch the title from an attached link - if there is one
3492 if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3493 $page_data = BBCode::getAttachmentData($item['body']);
3494 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3495 $title = $page_data['title'];
3499 if ($item['author-link'] != $item['owner-link']) {
3500 require_once 'mod/share.php';
3501 $body = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'],
3502 $item['plink'], $item['created']) . $body . '[/share]';
3505 // convert to markdown
3506 $body = html_entity_decode(BBCode::toMarkdown($body));
3509 if (strlen($title)) {
3510 $body = "### ".html_entity_decode($title)."\n\n".$body;
3513 if ($item["attach"]) {
3514 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3516 $body .= "\n".DI::l10n()->t("Attachments:")."\n";
3517 foreach ($matches as $mtch) {
3518 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3525 if ($item["location"] != "")
3526 $location["address"] = $item["location"];
3528 if ($item["coord"] != "") {
3529 $coord = explode(" ", $item["coord"]);
3530 $location["lat"] = $coord[0];
3531 $location["lng"] = $coord[1];
3534 $message = ["author" => $myaddr,
3535 "guid" => $item["guid"],
3536 "created_at" => $created,
3537 "edited_at" => $edited,
3538 "public" => $public,
3540 "provider_display_name" => $item["app"],
3541 "location" => $location];
3543 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3544 if (!isset($location["lat"]) || !isset($location["lng"])) {
3545 unset($message["location"]);
3548 if ($item['event-id'] > 0) {
3549 $event = self::buildEvent($item['event-id']);
3550 if (count($event)) {
3551 $message['event'] = $event;
3553 if (!empty($event['location']['address']) &&
3554 !empty($event['location']['lat']) &&
3555 !empty($event['location']['lng'])) {
3556 $message['location'] = $event['location'];
3559 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3560 // $message['text'] = '';
3564 $type = "status_message";
3567 $msg = ["type" => $type, "message" => $message];
3569 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3574 private static function prependParentAuthorMention($body, $profile_url)
3576 $profile = Contact::getByURL($profile_url, false, ['addr', 'name', 'contact-type']);
3577 if (!empty($profile['addr'])
3578 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3579 && !strstr($body, $profile['addr'])
3580 && !strstr($body, $profile_url)
3582 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3591 * @param array $item The item that will be exported
3592 * @param array $owner the array of the item owner
3593 * @param array $contact Target of the communication
3594 * @param bool $public_batch Is it a public post?
3596 * @return int The result of the transmission
3597 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3598 * @throws \ImagickException
3600 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3602 $status = self::buildStatus($item, $owner);
3604 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3608 * Creates a "like" object
3610 * @param array $item The item that will be exported
3611 * @param array $owner the array of the item owner
3613 * @return array The data for a "like"
3614 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3616 private static function constructLike(array $item, array $owner)
3618 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3619 if (!DBA::isResult($parent)) {
3623 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3625 if ($item['verb'] === Activity::LIKE) {
3627 } elseif ($item['verb'] === Activity::DISLIKE) {
3628 $positive = "false";
3631 return(["author" => self::myHandle($owner),
3632 "guid" => $item["guid"],
3633 "parent_guid" => $parent["guid"],
3634 "parent_type" => $target_type,
3635 "positive" => $positive,
3636 "author_signature" => ""]);
3640 * Creates an "EventParticipation" object
3642 * @param array $item The item that will be exported
3643 * @param array $owner the array of the item owner
3645 * @return array The data for an "EventParticipation"
3646 * @throws \Exception
3648 private static function constructAttend(array $item, array $owner)
3650 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3651 if (!DBA::isResult($parent)) {
3655 switch ($item['verb']) {
3656 case Activity::ATTEND:
3657 $attend_answer = 'accepted';
3659 case Activity::ATTENDNO:
3660 $attend_answer = 'declined';
3662 case Activity::ATTENDMAYBE:
3663 $attend_answer = 'tentative';
3666 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3670 return(["author" => self::myHandle($owner),
3671 "guid" => $item["guid"],
3672 "parent_guid" => $parent["guid"],
3673 "status" => $attend_answer,
3674 "author_signature" => ""]);
3678 * Creates the object for a comment
3680 * @param array $item The item that will be exported
3681 * @param array $owner the array of the item owner
3683 * @return array|false The data for a comment
3684 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3686 private static function constructComment(array $item, array $owner)
3688 $cachekey = "diaspora:constructComment:".$item['guid'];
3690 $result = DI::cache()->get($cachekey);
3691 if (!is_null($result)) {
3695 $toplevel_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3696 if (!DBA::isResult($toplevel_item)) {
3697 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3701 $thread_parent_item = $toplevel_item;
3702 if ($item['thr-parent'] != $item['parent-uri']) {
3703 $thread_parent_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3706 $body = $item["body"];
3708 // The replied to autor mention is prepended for clarity if:
3709 // - Item replied isn't yours
3710 // - Item is public or explicit mentions are disabled
3711 // - Implicit mentions are enabled
3713 $item['author-id'] != $thread_parent_item['author-id']
3714 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3715 && !DI::config()->get('system', 'disable_implicit_mentions')
3717 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3720 $text = html_entity_decode(BBCode::toMarkdown($body));
3721 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3722 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3725 "author" => self::myHandle($owner),
3726 "guid" => $item["guid"],
3727 "created_at" => $created,
3728 "edited_at" => $edited,
3729 "parent_guid" => $toplevel_item["guid"],
3731 "author_signature" => ""
3734 // Send the thread parent guid only if it is a threaded comment
3735 if ($item['thr-parent'] != $item['parent-uri']) {
3736 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3739 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3745 * Send a like or a comment
3747 * @param array $item The item that will be exported
3748 * @param array $owner the array of the item owner
3749 * @param array $contact Target of the communication
3750 * @param bool $public_batch Is it a public post?
3752 * @return int The result of the transmission
3753 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3754 * @throws \ImagickException
3756 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3758 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3759 $message = self::constructAttend($item, $owner);
3760 $type = "event_participation";
3761 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3762 $message = self::constructLike($item, $owner);
3764 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3765 $message = self::constructComment($item, $owner);
3769 if (empty($message)) {
3773 $message["author_signature"] = self::signature($owner, $message);
3775 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3779 * Creates a message from a signature record entry
3781 * @param array $item The item that will be exported
3782 * @return array The message
3784 private static function messageFromSignature(array $item)
3786 // Split the signed text
3787 $signed_parts = explode(";", $item['signed_text']);
3789 if ($item["deleted"]) {
3790 $message = ["author" => $item['signer'],
3791 "target_guid" => $signed_parts[0],
3792 "target_type" => $signed_parts[1]];
3793 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3794 $message = ["author" => $signed_parts[4],
3795 "guid" => $signed_parts[1],
3796 "parent_guid" => $signed_parts[3],
3797 "parent_type" => $signed_parts[2],
3798 "positive" => $signed_parts[0],
3799 "author_signature" => $item['signature'],
3800 "parent_author_signature" => ""];
3802 // Remove the comment guid
3803 $guid = array_shift($signed_parts);
3805 // Remove the parent guid
3806 $parent_guid = array_shift($signed_parts);
3808 // Remove the handle
3809 $handle = array_pop($signed_parts);
3812 "author" => $handle,
3814 "parent_guid" => $parent_guid,
3815 "text" => implode(";", $signed_parts),
3816 "author_signature" => $item['signature'],
3817 "parent_author_signature" => ""
3824 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3826 * @param array $item The item that will be exported
3827 * @param array $owner the array of the item owner
3828 * @param array $contact Target of the communication
3829 * @param bool $public_batch Is it a public post?
3831 * @return int The result of the transmission
3832 * @throws \Exception
3834 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3836 if ($item["deleted"]) {
3837 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3838 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3844 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3846 $msg = json_decode($item['signed_text'], true);
3849 if (is_array($msg)) {
3850 foreach ($msg as $field => $data) {
3851 if (!$item["deleted"]) {
3852 if ($field == "diaspora_handle") {
3855 if ($field == "target_type") {
3856 $field = "parent_type";
3860 $message[$field] = $data;
3863 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
3866 $message["parent_author_signature"] = self::signature($owner, $message);
3868 Logger::info('Relayed data', ['msg' => $message]);
3870 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3874 * Sends a retraction (deletion) of a message, like or comment
3876 * @param array $item The item that will be exported
3877 * @param array $owner the array of the item owner
3878 * @param array $contact Target of the communication
3879 * @param bool $public_batch Is it a public post?
3880 * @param bool $relay Is the retraction transmitted from a relay?
3882 * @return int The result of the transmission
3883 * @throws \Exception
3885 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
3887 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3889 $msg_type = "retraction";
3891 if ($item['gravity'] == GRAVITY_PARENT) {
3892 $target_type = "Post";
3893 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3894 $target_type = "Like";
3896 $target_type = "Comment";
3899 $message = ["author" => $itemaddr,
3900 "target_guid" => $item['guid'],
3901 "target_type" => $target_type];
3903 Logger::info('Got message', ['msg' => $message]);
3905 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3911 * @param array $item The item that will be exported
3912 * @param array $owner The owner
3913 * @param array $contact Target of the communication
3915 * @return int The result of the transmission
3916 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3917 * @throws \ImagickException
3919 public static function sendMail(array $item, array $owner, array $contact)
3921 $myaddr = self::myHandle($owner);
3923 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
3924 if (!DBA::isResult($cnv)) {
3925 Logger::log("conversation not found.");
3929 $body = BBCode::toMarkdown($item["body"]);
3930 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3933 "author" => $myaddr,
3934 "guid" => $item["guid"],
3935 "conversation_guid" => $cnv["guid"],
3937 "created_at" => $created,
3940 if ($item["reply"]) {
3945 "author" => $cnv["creator"],
3946 "guid" => $cnv["guid"],
3947 "subject" => $cnv["subject"],
3948 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3949 "participants" => $cnv["recips"],
3953 $type = "conversation";
3956 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
3960 * Split a name into first name and last name
3962 * @param string $name The name
3964 * @return array The array with "first" and "last"
3966 public static function splitName($name) {
3967 $name = trim($name);
3969 // Is the name longer than 64 characters? Then cut the rest of it.
3970 if (strlen($name) > 64) {
3971 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3972 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3974 $name = substr($name, 0, 64);
3978 // Take the first word as first name
3979 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3980 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3981 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3982 return ['first' => $first, 'last' => $last];
3985 // Take the last word as last name
3986 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3987 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3989 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3990 return ['first' => $first, 'last' => $last];
3993 // Take the first 32 characters if there is no space in the first 32 characters
3994 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3995 $first = substr($name, 0, 32);
3996 $last = substr($name, 32);
3997 return ['first' => $first, 'last' => $last];
4000 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4001 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4003 // Check if the last name is longer than 32 characters
4004 if (strlen($last) > 32) {
4005 if (strpos($last, ' ') <= 32) {
4006 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4008 $last = substr($last, 0, 32);
4012 return ['first' => $first, 'last' => $last];
4016 * Create profile data
4018 * @param int $uid The user id
4020 * @return array The profile data
4021 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4023 private static function createProfileData($uid)
4025 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
4026 if (!DBA::isResult($profile)) {
4030 $handle = $profile["addr"];
4032 $split_name = self::splitName($profile['name']);
4033 $first = $split_name['first'];
4034 $last = $split_name['last'];
4036 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4037 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4038 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4039 $searchable = ($profile['net-publish'] ? 'true' : 'false');
4045 if ($searchable === 'true') {
4048 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4049 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4053 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4056 $about = BBCode::toMarkdown($profile['about']);
4058 $location = $profile['location'];
4060 if ($profile['pub_keywords']) {
4061 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4062 $kw = str_replace(' ', ' ', $kw);
4063 $arr = explode(' ', $kw);
4065 for ($x = 0; $x < 5; $x ++) {
4066 if (!empty($arr[$x])) {
4067 $tags .= '#'. trim($arr[$x]) .' ';
4072 $tags = trim($tags);
4075 return ["author" => $handle,
4076 "first_name" => $first,
4077 "last_name" => $last,
4078 "image_url" => $large,
4079 "image_url_medium" => $medium,
4080 "image_url_small" => $small,
4083 "location" => $location,
4084 "searchable" => $searchable,
4086 "tag_string" => $tags];
4090 * Sends profile data
4092 * @param int $uid The user id
4093 * @param bool $recips optional, default false
4095 * @throws \Exception
4097 public static function sendProfile($uid, $recips = false)
4103 $owner = User::getOwnerDataById($uid);
4110 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4111 AND `uid` = %d AND `rel` != %d",
4112 DBA::escape(Protocol::DIASPORA),
4114 intval(Contact::SHARING)
4122 $message = self::createProfileData($uid);
4124 // @ToDo Split this into single worker jobs
4125 foreach ($recips as $recip) {
4126 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4127 self::buildAndTransmit($owner, $recip, "profile", $message);
4132 * Creates the signature for likes that are created on our system
4134 * @param integer $uid The user of that comment
4135 * @param array $item Item array
4137 * @return array Signed content
4138 * @throws \Exception
4140 public static function createLikeSignature($uid, array $item)
4142 $owner = User::getOwnerDataById($uid);
4143 if (empty($owner)) {
4144 Logger::info('No owner post, so not storing signature');
4148 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4152 $message = self::constructLike($item, $owner);
4153 if ($message === false) {
4157 $message["author_signature"] = self::signature($owner, $message);
4163 * Creates the signature for Comments that are created on our system
4165 * @param integer $uid The user of that comment
4166 * @param array $item Item array
4168 * @return array Signed content
4169 * @throws \Exception
4171 public static function createCommentSignature($uid, array $item)
4173 $owner = User::getOwnerDataById($uid);
4174 if (empty($owner)) {
4175 Logger::info('No owner post, so not storing signature');
4179 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4180 $item['thr-parent'] = $item['parent-uri'];
4182 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4183 if (!DBA::isResult($parent)) {
4187 $item['parent-uri'] = $parent['parent-uri'];
4189 $message = self::constructComment($item, $owner);
4190 if ($message === false) {
4194 $message["author_signature"] = self::signature($owner, $message);