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\Text\BBCode;
26 use Friendica\Content\Text\Markdown;
27 use Friendica\Core\Cache\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\GContact;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\ItemDeliveryData;
40 use Friendica\Model\Mail;
41 use Friendica\Model\Profile;
42 use Friendica\Model\Tag;
43 use Friendica\Model\Term;
44 use Friendica\Model\User;
45 use Friendica\Network\Probe;
46 use Friendica\Util\Crypto;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Map;
49 use Friendica\Util\Network;
50 use Friendica\Util\Strings;
51 use Friendica\Util\XML;
52 use Friendica\Worker\Delivery;
56 * This class contain functions to create and send Diaspora XML files
61 * Mark the relay contact of the given contact for archival
62 * This is called whenever there is a communication issue with the server.
63 * It avoids sending stuff to servers who don't exist anymore.
64 * The relay contact is a technical contact entry that exists once per server.
66 * @param array $contact of the relay contact
68 public static function markRelayForArchival(array $contact)
70 if (!empty($contact['contact-type']) && ($contact['contact-type'] == Contact::TYPE_RELAY)) {
71 // This is already the relay contact, we don't need to fetch it
72 $relay_contact = $contact;
73 } elseif (empty($contact['baseurl'])) {
74 if (!empty($contact['batch'])) {
75 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => Contact::TYPE_RELAY];
76 $relay_contact = DBA::selectFirst('contact', [], $condition);
81 $relay_contact = self::getRelayContact($contact['baseurl'], []);
84 if (!empty($relay_contact)) {
85 Logger::info('Relay contact will be marked for archival', ['id' => $relay_contact['id'], 'url' => $relay_contact['url']]);
86 Contact::markForArchival($relay_contact);
91 * Return a list of relay servers
93 * The list contains not only the official relays but also servers that we serve directly
95 * @param integer $item_id The id of the item that is sent
96 * @param array $contacts The previously fetched contacts
98 * @return array of relay servers
99 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
101 public static function relayList($item_id, array $contacts = [])
105 // Fetching relay servers
106 $serverdata = DI::config()->get("system", "relay_server");
108 if (!empty($serverdata)) {
109 $servers = explode(",", $serverdata);
110 foreach ($servers as $server) {
111 $serverlist[$server] = trim($server);
115 if (DI::config()->get("system", "relay_directly", false)) {
116 // We distribute our stuff based on the parent to ensure that the thread will be complete
117 $parent = Item::selectFirst(['parent'], ['id' => $item_id]);
118 if (!DBA::isResult($parent)) {
122 // Servers that want to get all content
123 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
124 while ($server = DBA::fetch($servers)) {
125 $serverlist[$server['url']] = $server['url'];
128 // All tags of the current post
129 $condition = ['otype' => Term::OBJECT_TYPE_POST, 'type' => Term::HASHTAG, 'oid' => $parent['parent']];
130 $tags = DBA::select('term', ['term'], $condition);
132 while ($tag = DBA::fetch($tags)) {
133 $taglist[] = $tag['term'];
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'];
145 // All adresses with the given id
146 if (!empty($tagserverlist)) {
147 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
148 while ($server = DBA::fetch($servers)) {
149 $serverlist[$server['url']] = $server['url'];
154 // Now we are collecting all relay contacts
155 foreach ($serverlist as $server_url) {
156 // We don't send messages to ourselves
157 if (Strings::compareLink($server_url, DI::baseUrl())) {
160 $contact = self::getRelayContact($server_url);
161 if (is_bool($contact)) {
166 foreach ($contacts as $entry) {
167 if ($entry['batch'] == $contact['batch']) {
173 $contacts[] = $contact;
181 * Return a contact for a given server address or creates a dummy entry
183 * @param string $server_url The url of the server
184 * @param array $fields Fieldlist
185 * @return array with the contact
188 private static function getRelayContact(string $server_url, array $fields = ['batch', 'id', 'url', 'name', 'network', 'protocol', 'archive', 'blocked'])
190 // Fetch the relay contact
191 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
192 'contact-type' => Contact::TYPE_RELAY];
193 $contact = DBA::selectFirst('contact', $fields, $condition);
195 if (DBA::isResult($contact)) {
196 if ($contact['archive'] || $contact['blocked']) {
201 self::setRelayContact($server_url);
203 $contact = DBA::selectFirst('contact', $fields, $condition);
204 if (DBA::isResult($contact)) {
209 // It should never happen that we arrive here
214 * Update or insert a relay contact
216 * @param string $server_url The url of the server
217 * @param array $network_fields Optional network specific fields
220 public static function setRelayContact($server_url, array $network_fields = [])
222 $fields = ['created' => DateTimeFormat::utcNow(),
223 'name' => 'relay', 'nick' => 'relay', 'url' => $server_url,
224 'nurl' => Strings::normaliseLink($server_url),
225 'network' => Protocol::DIASPORA, 'uid' => 0,
226 'batch' => $server_url . '/receive/public',
227 'rel' => Contact::FOLLOWER, 'blocked' => false,
228 'pending' => false, 'writable' => true,
229 'baseurl' => $server_url, 'contact-type' => Contact::TYPE_RELAY];
231 $fields = array_merge($fields, $network_fields);
233 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url)];
234 $old = DBA::selectFirst('contact', [], $condition);
235 if (DBA::isResult($old)) {
236 unset($fields['created']);
237 $condition = ['id' => $old['id']];
239 Logger::info('Update relay contact', ['fields' => $fields, 'condition' => $condition]);
240 DBA::update('contact', $fields, $condition, $old);
242 Logger::info('Create relay contact', ['fields' => $fields]);
243 Contact::insert($fields);
248 * Return a list of participating contacts for a thread
250 * This is used for the participation feature.
251 * One of the parameters is a contact array.
252 * This is done to avoid duplicates.
254 * @param integer $thread The id of the thread
255 * @param array $contacts The previously fetched contacts
257 * @return array of relay servers
260 public static function participantsForThread($thread, array $contacts)
262 $participation = DBA::select('participation-view', [], ['iid' => $thread]);
264 while ($contact = DBA::fetch($participation)) {
265 if (empty($contact['protocol'])) {
266 $contact['protocol'] = $contact['network'];
270 foreach ($contacts as $entry) {
271 if ($entry['batch'] == $contact['batch']) {
277 $contacts[] = $contact;
281 DBA::close($participation);
287 * repairs a signature that was double encoded
289 * The function is unused at the moment. It was copied from the old implementation.
291 * @param string $signature The signature
292 * @param string $handle The handle of the signature owner
293 * @param integer $level This value is only set inside this function to avoid endless loops
295 * @return string the repaired signature
298 private static function repairSignature($signature, $handle = "", $level = 1)
300 if ($signature == "") {
304 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
305 $signature = base64_decode($signature);
306 Logger::log("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, Logger::DEBUG);
308 // Do a recursive call to be able to fix even multiple levels
310 $signature = self::repairSignature($signature, $handle, ++$level);
318 * verify the envelope and return the verified data
320 * @param string $envelope The magic envelope
322 * @return string verified data
323 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
324 * @throws \ImagickException
326 private static function verifyMagicEnvelope($envelope)
328 $basedom = XML::parseString($envelope, true);
330 if (!is_object($basedom)) {
331 Logger::log("Envelope is no XML file");
335 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
337 if (sizeof($children) == 0) {
338 Logger::log("XML has no children");
344 $data = Strings::base64UrlDecode($children->data);
345 $type = $children->data->attributes()->type[0];
347 $encoding = $children->encoding;
349 $alg = $children->alg;
351 $sig = Strings::base64UrlDecode($children->sig);
352 $key_id = $children->sig->attributes()->key_id[0];
354 $handle = Strings::base64UrlDecode($key_id);
357 $b64url_data = Strings::base64UrlEncode($data);
358 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
360 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
363 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
367 $key = self::key($handle);
369 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
373 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
375 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
383 * encrypts data via AES
385 * @param string $key The AES key
386 * @param string $iv The IV (is used for CBC encoding)
387 * @param string $data The data that is to be encrypted
389 * @return string encrypted data
391 private static function aesEncrypt($key, $iv, $data)
393 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
397 * decrypts data via AES
399 * @param string $key The AES key
400 * @param string $iv The IV (is used for CBC encoding)
401 * @param string $encrypted The encrypted data
403 * @return string decrypted data
405 private static function aesDecrypt($key, $iv, $encrypted)
407 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
411 * Decodes incoming Diaspora message in the new format
413 * @param string $raw raw post message
414 * @param string $privKey The private key of the importer
415 * @param boolean $no_exit Don't do an http exit on error
418 * 'message' -> decoded Diaspora XML message
419 * 'author' -> author diaspora handle
420 * 'key' -> author public key (converted to pkcs#8)
421 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
422 * @throws \ImagickException
424 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
426 $data = json_decode($raw);
428 // Is it a private post? Then decrypt the outer Salmon
429 if (is_object($data)) {
430 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
431 $ciphertext = base64_decode($data->encrypted_magic_envelope);
433 $outer_key_bundle = '';
434 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
435 $j_outer_key_bundle = json_decode($outer_key_bundle);
437 if (!is_object($j_outer_key_bundle)) {
438 Logger::log('Outer Salmon did not verify. Discarding.');
442 throw new \Friendica\Network\HTTPException\BadRequestException();
446 $outer_iv = base64_decode($j_outer_key_bundle->iv);
447 $outer_key = base64_decode($j_outer_key_bundle->key);
449 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
454 $basedom = XML::parseString($xml, true);
456 if (!is_object($basedom)) {
457 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
461 throw new \Friendica\Network\HTTPException\BadRequestException();
465 $base = $basedom->children(ActivityNamespace::SALMON_ME);
467 // Not sure if this cleaning is needed
468 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
470 // Build the signed data
471 $type = $base->data[0]->attributes()->type[0];
472 $encoding = $base->encoding;
474 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
476 // This is the signature
477 $signature = Strings::base64UrlDecode($base->sig);
479 // Get the senders' public key
480 $key_id = $base->sig[0]->attributes()->key_id[0];
481 $author_addr = base64_decode($key_id);
482 if ($author_addr == '') {
483 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
487 throw new \Friendica\Network\HTTPException\BadRequestException();
491 $key = self::key($author_addr);
493 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
497 throw new \Friendica\Network\HTTPException\BadRequestException();
501 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
503 Logger::log('Message did not verify. Discarding.');
507 throw new \Friendica\Network\HTTPException\BadRequestException();
511 return ['message' => (string)Strings::base64UrlDecode($base->data),
512 'author' => XML::unescape($author_addr),
513 'key' => (string)$key];
517 * Decodes incoming Diaspora message in the deprecated format
519 * @param string $xml urldecoded Diaspora salmon
520 * @param string $privKey The private key of the importer
523 * 'message' -> decoded Diaspora XML message
524 * 'author' -> author diaspora handle
525 * 'key' -> author public key (converted to pkcs#8)
526 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
527 * @throws \ImagickException
529 public static function decode(string $xml, string $privKey = '')
532 $basedom = XML::parseString($xml);
534 if (!is_object($basedom)) {
535 Logger::log("XML is not parseable.");
538 $children = $basedom->children('https://joindiaspora.com/protocol');
540 $inner_aes_key = null;
543 if ($children->header) {
545 $author_link = str_replace('acct:', '', $children->header->author_id);
547 // This happens with posts from a relais
548 if (empty($privKey)) {
549 Logger::log("This is no private post in the old format", Logger::DEBUG);
553 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
555 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
556 $ciphertext = base64_decode($encrypted_header->ciphertext);
558 $outer_key_bundle = '';
559 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
561 $j_outer_key_bundle = json_decode($outer_key_bundle);
563 $outer_iv = base64_decode($j_outer_key_bundle->iv);
564 $outer_key = base64_decode($j_outer_key_bundle->key);
566 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
568 Logger::log('decrypted: '.$decrypted, Logger::DEBUG);
569 $idom = XML::parseString($decrypted);
571 $inner_iv = base64_decode($idom->iv);
572 $inner_aes_key = base64_decode($idom->aes_key);
574 $author_link = str_replace('acct:', '', $idom->author_id);
577 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
579 // figure out where in the DOM tree our data is hiding
582 if ($dom->provenance->data) {
583 $base = $dom->provenance;
584 } elseif ($dom->env->data) {
586 } elseif ($dom->data) {
591 Logger::log('unable to locate salmon data in xml');
592 throw new \Friendica\Network\HTTPException\BadRequestException();
596 // Stash the signature away for now. We have to find their key or it won't be good for anything.
597 $signature = Strings::base64UrlDecode($base->sig);
601 // strip whitespace so our data element will return to one big base64 blob
602 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
605 // stash away some other stuff for later
607 $type = $base->data[0]->attributes()->type[0];
608 $keyhash = $base->sig[0]->attributes()->keyhash[0];
609 $encoding = $base->encoding;
613 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
617 $data = Strings::base64UrlDecode($data);
621 $inner_decrypted = $data;
623 // Decode the encrypted blob
624 $inner_encrypted = base64_decode($data);
625 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
629 Logger::log('Could not retrieve author URI.');
630 throw new \Friendica\Network\HTTPException\BadRequestException();
632 // Once we have the author URI, go to the web and try to find their public key
633 // (first this will look it up locally if it is in the fcontact cache)
634 // This will also convert diaspora public key from pkcs#1 to pkcs#8
636 Logger::log('Fetching key for '.$author_link);
637 $key = self::key($author_link);
640 Logger::log('Could not retrieve author key.');
641 throw new \Friendica\Network\HTTPException\BadRequestException();
644 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
647 Logger::log('Message did not verify. Discarding.');
648 throw new \Friendica\Network\HTTPException\BadRequestException();
651 Logger::log('Message verified.');
653 return ['message' => (string)$inner_decrypted,
654 'author' => XML::unescape($author_link),
655 'key' => (string)$key];
660 * Dispatches public messages and find the fitting receivers
662 * @param array $msg The post that will be dispatched
664 * @return int The message id of the generated message, "true" or "false" if there was an error
665 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
666 * @throws \ImagickException
668 public static function dispatchPublic($msg)
670 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
672 Logger::log("diaspora is disabled");
676 if (!($fields = self::validPosting($msg))) {
677 Logger::log("Invalid posting");
681 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
682 $success = self::dispatch($importer, $msg, $fields);
688 * Dispatches the different message types to the different functions
690 * @param array $importer Array of the importer user
691 * @param array $msg The post that will be dispatched
692 * @param SimpleXMLElement $fields SimpleXML object that contains the message
694 * @return int The message id of the generated message, "true" or "false" if there was an error
695 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
696 * @throws \ImagickException
698 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
700 // The sender is the handle of the contact that sent the message.
701 // This will often be different with relayed messages (for example "like" and "comment")
702 $sender = $msg["author"];
704 // This is only needed for private postings since this is already done for public ones before
705 if (is_null($fields)) {
707 if (!($fields = self::validPosting($msg))) {
708 Logger::log("Invalid posting");
715 $type = $fields->getName();
717 Logger::log("Received message type ".$type." from ".$sender." for user ".$importer["uid"], Logger::DEBUG);
720 case "account_migration":
722 Logger::log('Message with type ' . $type . ' is not private, quitting.');
725 return self::receiveAccountMigration($importer, $fields);
727 case "account_deletion":
728 return self::receiveAccountDeletion($fields);
731 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
735 Logger::log('Message with type ' . $type . ' is not private, quitting.');
738 return self::receiveContactRequest($importer, $fields);
742 Logger::log('Message with type ' . $type . ' is not private, quitting.');
745 return self::receiveConversation($importer, $msg, $fields);
748 return self::receiveLike($importer, $sender, $fields);
752 Logger::log('Message with type ' . $type . ' is not private, quitting.');
755 return self::receiveMessage($importer, $fields);
757 case "participation":
759 Logger::log('Message with type ' . $type . ' is not private, quitting.');
762 return self::receiveParticipation($importer, $fields);
764 case "photo": // Not implemented
765 return self::receivePhoto($importer, $fields);
767 case "poll_participation": // Not implemented
768 return self::receivePollParticipation($importer, $fields);
772 Logger::log('Message with type ' . $type . ' is not private, quitting.');
775 return self::receiveProfile($importer, $fields);
778 return self::receiveReshare($importer, $fields, $msg["message"]);
781 return self::receiveRetraction($importer, $sender, $fields);
783 case "status_message":
784 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
787 Logger::log("Unknown message type ".$type);
793 * Checks if a posting is valid and fetches the data fields.
795 * This function does not only check the signature.
796 * It also does the conversion between the old and the new diaspora format.
798 * @param array $msg Array with the XML, the sender handle and the sender signature
800 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
801 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
802 * @throws \ImagickException
804 private static function validPosting($msg)
806 $data = XML::parseString($msg["message"]);
808 if (!is_object($data)) {
809 Logger::log("No valid XML ".$msg["message"], Logger::DEBUG);
813 // Is this the new or the old version?
814 if ($data->getName() == "XML") {
816 foreach ($data->post->children() as $child) {
824 $type = $element->getName();
827 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
829 // All retractions are handled identically from now on.
830 // In the new version there will only be "retraction".
831 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
832 $type = "retraction";
834 if ($type == "request") {
838 $fields = new SimpleXMLElement("<".$type."/>");
841 $author_signature = null;
842 $parent_author_signature = null;
844 foreach ($element->children() as $fieldname => $entry) {
846 // Translation for the old XML structure
847 if ($fieldname == "diaspora_handle") {
848 $fieldname = "author";
850 if ($fieldname == "participant_handles") {
851 $fieldname = "participants";
853 if (in_array($type, ["like", "participation"])) {
854 if ($fieldname == "target_type") {
855 $fieldname = "parent_type";
858 if ($fieldname == "sender_handle") {
859 $fieldname = "author";
861 if ($fieldname == "recipient_handle") {
862 $fieldname = "recipient";
864 if ($fieldname == "root_diaspora_id") {
865 $fieldname = "root_author";
867 if ($type == "status_message") {
868 if ($fieldname == "raw_message") {
872 if ($type == "retraction") {
873 if ($fieldname == "post_guid") {
874 $fieldname = "target_guid";
876 if ($fieldname == "type") {
877 $fieldname = "target_type";
882 if (($fieldname == "author_signature") && ($entry != "")) {
883 $author_signature = base64_decode($entry);
884 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
885 $parent_author_signature = base64_decode($entry);
886 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
887 if ($signed_data != "") {
891 $signed_data .= $entry;
893 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
894 || ($orig_type == "relayable_retraction")
896 XML::copy($entry, $fields, $fieldname);
900 // This is something that shouldn't happen at all.
901 if (in_array($type, ["status_message", "reshare", "profile"])) {
902 if ($msg["author"] != $fields->author) {
903 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
908 // Only some message types have signatures. So we quit here for the other types.
909 if (!in_array($type, ["comment", "like"])) {
912 // No author_signature? This is a must, so we quit.
913 if (!isset($author_signature)) {
914 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
918 if (isset($parent_author_signature)) {
919 $key = self::key($msg["author"]);
921 Logger::log("No key found for parent author ".$msg["author"], Logger::DEBUG);
925 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
926 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);
931 $key = self::key($fields->author);
933 Logger::log("No key found for author ".$fields->author, Logger::DEBUG);
937 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
938 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);
946 * Fetches the public key for a given handle
948 * @param string $handle The handle
950 * @return string The public key
951 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
952 * @throws \ImagickException
954 private static function key($handle)
956 $handle = strval($handle);
958 Logger::log("Fetching diaspora key for: ".$handle);
960 $r = self::personByHandle($handle);
969 * Fetches data for a given handle
971 * @param string $handle The handle
972 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
974 * @return array the queried data
975 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
976 * @throws \ImagickException
978 public static function personByHandle($handle, $update = null)
980 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
981 if (!DBA::isResult($person)) {
982 $urls = [$handle, str_replace('http://', 'https://', $handle), Strings::normaliseLink($handle)];
983 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'url' => $urls]);
986 if (DBA::isResult($person)) {
987 Logger::debug("In cache " . print_r($person, true));
989 if (is_null($update)) {
990 // update record occasionally so it doesn't get stale
991 $d = strtotime($person["updated"]." +00:00");
992 if ($d < strtotime("now - 14 days")) {
996 if ($person["guid"] == "") {
1000 } elseif (is_null($update)) {
1001 $update = !DBA::isResult($person);
1007 Logger::log("create or refresh", Logger::DEBUG);
1008 $r = Probe::uri($handle, Protocol::DIASPORA);
1010 // Note that Friendica contacts will return a "Diaspora person"
1011 // if Diaspora connectivity is enabled on their server
1012 if ($r && ($r["network"] === Protocol::DIASPORA)) {
1013 self::updateFContact($r);
1015 $person = self::personByHandle($handle, false);
1023 * Updates the fcontact table
1025 * @param array $arr The fcontact data
1026 * @throws \Exception
1028 private static function updateFContact($arr)
1030 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
1031 'request' => $arr["request"], 'nick' => $arr["nick"],
1032 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
1033 'batch' => $arr["batch"], 'notify' => $arr["notify"],
1034 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
1035 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
1036 'updated' => DateTimeFormat::utcNow()];
1038 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
1040 DBA::update('fcontact', $fields, $condition, true);
1044 * get a handle (user@domain.tld) from a given contact id
1046 * @param int $contact_id The id in the contact table
1047 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1049 * @return string the handle
1050 * @throws \Exception
1052 private static function handleFromContact($contact_id, $pcontact_id = 0)
1056 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
1058 if ($pcontact_id != 0) {
1059 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
1061 if (DBA::isResult($contact) && !empty($contact["addr"])) {
1062 return strtolower($contact["addr"]);
1067 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1071 if (DBA::isResult($r)) {
1074 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1076 if ($contact['addr'] != "") {
1077 $handle = $contact['addr'];
1079 $baseurl_start = strpos($contact['url'], '://') + 3;
1080 // allows installations in a subdirectory--not sure how Diaspora will handle
1081 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1082 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1083 $handle = $contact['nick'].'@'.$baseurl;
1087 return strtolower($handle);
1091 * get a url (scheme://domain.tld/u/user) from a given Diaspora*
1094 * @param mixed $fcontact_guid Hexadecimal string guid
1096 * @return string the contact url or null
1097 * @throws \Exception
1099 public static function urlFromContactGuid($fcontact_guid)
1101 Logger::log("fcontact guid is ".$fcontact_guid, Logger::DEBUG);
1104 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1105 DBA::escape(Protocol::DIASPORA),
1106 DBA::escape($fcontact_guid)
1109 if (DBA::isResult($r)) {
1110 return $r[0]['url'];
1117 * Get a contact id for a given handle
1119 * @todo Move to Friendica\Model\Contact
1121 * @param int $uid The user id
1122 * @param string $handle The handle in the format user@domain.tld
1124 * @return array Contact data
1125 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1126 * @throws \ImagickException
1128 private static function contactByHandle($uid, $handle)
1130 $cid = Contact::getIdForURL($handle, $uid);
1132 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1136 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1137 if (!DBA::isResult($contact)) {
1138 // This here shouldn't happen at all
1139 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1147 * Checks if the given contact url does support ActivityPub
1149 * @param string $url profile url
1150 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1152 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1153 * @throws \ImagickException
1155 public static function isSupportedByContactUrl($url, $update = null)
1157 return !empty(self::personByHandle($url, $update));
1161 * Check if posting is allowed for this contact
1163 * @param array $importer Array of the importer user
1164 * @param array $contact The contact that is checked
1165 * @param bool $is_comment Is the check for a comment?
1167 * @return bool is the contact allowed to post?
1169 private static function postAllow(array $importer, array $contact, $is_comment = false)
1172 * Perhaps we were already sharing with this person. Now they're sharing with us.
1173 * That makes us friends.
1174 * Normally this should have handled by getting a request - but this could get lost
1176 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1177 // It is not removed by now. Possibly the code is needed?
1178 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1181 // array('rel' => Contact::FRIEND, 'writable' => true),
1182 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1185 // $contact["rel"] = Contact::FRIEND;
1186 // Logger::log("defining user ".$contact["nick"]." as friend");
1189 // Contact server is blocked
1190 if (Network::isUrlBlocked($contact['url'])) {
1192 // We don't seem to like that person
1193 } elseif ($contact["blocked"]) {
1194 // Maybe blocked, don't accept.
1196 // We are following this person?
1197 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1198 // Yes, then it is fine.
1200 // Is it a post to a community?
1201 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1204 // Is the message a global user or a comment?
1205 } elseif (($importer["uid"] == 0) || $is_comment) {
1206 // Messages for the global users and comments are always accepted
1214 * Fetches the contact id for a handle and checks if posting is allowed
1216 * @param array $importer Array of the importer user
1217 * @param string $handle The checked handle in the format user@domain.tld
1218 * @param bool $is_comment Is the check for a comment?
1220 * @return array The contact data
1221 * @throws \Exception
1223 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1225 $contact = self::contactByHandle($importer["uid"], $handle);
1227 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1228 // If a contact isn't found, we accept it anyway if it is a comment
1229 if ($is_comment && ($importer["uid"] != 0)) {
1230 return self::contactByHandle(0, $handle);
1231 } elseif ($is_comment) {
1238 if (!self::postAllow($importer, $contact, $is_comment)) {
1239 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1246 * Does the message already exists on the system?
1248 * @param int $uid The user id
1249 * @param string $guid The guid of the message
1251 * @return int|bool message id if the message already was stored into the system - or false.
1252 * @throws \Exception
1254 private static function messageExists($uid, $guid)
1256 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1257 if (DBA::isResult($item)) {
1258 Logger::log("message ".$guid." already exists for user ".$uid);
1266 * Checks for links to posts in a message
1268 * @param array $item The item array
1271 private static function fetchGuid(array $item)
1273 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1274 preg_replace_callback(
1276 function ($match) use ($item) {
1277 self::fetchGuidSub($match, $item);
1282 preg_replace_callback(
1283 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1284 function ($match) use ($item) {
1285 self::fetchGuidSub($match, $item);
1292 * Checks for relative /people/* links in an item body to match local
1293 * contacts or prepends the remote host taken from the author link.
1295 * @param string $body The item body to replace links from
1296 * @param string $author_link The author link for missing local contact fallback
1298 * @return string the replaced string
1300 public static function replacePeopleGuid($body, $author_link)
1302 $return = preg_replace_callback(
1303 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1304 function ($match) use ($author_link) {
1306 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1307 // 1 => '0123456789abcdef'
1309 $handle = self::urlFromContactGuid($match[1]);
1312 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1314 // No local match, restoring absolute remote URL from author scheme and host
1315 $author_url = parse_url($author_link);
1316 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1328 * sub function of "fetchGuid" which checks for links in messages
1330 * @param array $match array containing a link that has to be checked for a message link
1331 * @param array $item The item array
1333 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1334 * @throws \ImagickException
1336 private static function fetchGuidSub($match, $item)
1338 if (!self::storeByGuid($match[1], $item["author-link"])) {
1339 self::storeByGuid($match[1], $item["owner-link"]);
1344 * Fetches an item with a given guid from a given server
1346 * @param string $guid the message guid
1347 * @param string $server The server address
1348 * @param int $uid The user id of the user
1350 * @return int the message id of the stored message or false
1351 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1352 * @throws \ImagickException
1354 private static function storeByGuid($guid, $server, $uid = 0)
1356 $serverparts = parse_url($server);
1358 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1362 $server = $serverparts["scheme"]."://".$serverparts["host"];
1364 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1366 $msg = self::message($guid, $server);
1372 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1374 // Now call the dispatcher
1375 return self::dispatchPublic($msg);
1379 * Fetches a message from a server
1381 * @param string $guid message guid
1382 * @param string $server The url of the server
1383 * @param int $level Endless loop prevention
1386 * 'message' => The message XML
1387 * 'author' => The author handle
1388 * 'key' => The public key of the author
1389 * @throws \Exception
1391 private static function message($guid, $server, $level = 0)
1397 // This will work for new Diaspora servers and Friendica servers from 3.5
1398 $source_url = $server."/fetch/post/".urlencode($guid);
1400 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1402 $envelope = Network::fetchUrl($source_url);
1404 Logger::log("Envelope was fetched.", Logger::DEBUG);
1405 $x = self::verifyMagicEnvelope($envelope);
1407 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1409 Logger::log("Envelope was verified.", Logger::DEBUG);
1419 $source_xml = XML::parseString($x);
1421 if (!is_object($source_xml)) {
1425 if ($source_xml->post->reshare) {
1426 // Reshare of a reshare - old Diaspora version
1427 Logger::log("Message is a reshare", Logger::DEBUG);
1428 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1429 } elseif ($source_xml->getName() == "reshare") {
1430 // Reshare of a reshare - new Diaspora version
1431 Logger::log("Message is a new reshare", Logger::DEBUG);
1432 return self::message($source_xml->root_guid, $server, ++$level);
1437 // Fetch the author - for the old and the new Diaspora version
1438 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1439 $author = (string)$source_xml->post->status_message->diaspora_handle;
1440 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1441 $author = (string)$source_xml->author;
1444 // If this isn't a "status_message" then quit
1446 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1450 $msg = ["message" => $x, "author" => $author];
1452 $msg["key"] = self::key($msg["author"]);
1458 * Fetches an item with a given URL
1460 * @param string $url the message url
1462 * @return int the message id of the stored message or false
1463 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1464 * @throws \ImagickException
1466 public static function fetchByURL($url, $uid = 0)
1468 // Check for Diaspora (and Friendica) typical paths
1469 if (!preg_match("=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1470 Logger::info('Invalid url', ['url' => $url]);
1474 $guid = urldecode($matches[2]);
1476 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1477 if (DBA::isResult($item)) {
1478 Logger::info('Found', ['id' => $item['id']]);
1482 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1483 $ret = self::storeByGuid($guid, $matches[1], $uid);
1484 Logger::info('Result', ['ret' => $ret]);
1486 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1487 if (DBA::isResult($item)) {
1488 Logger::info('Found', ['id' => $item['id']]);
1491 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1497 * Fetches the item record of a given guid
1499 * @param int $uid The user id
1500 * @param string $guid message guid
1501 * @param string $author The handle of the item
1502 * @param array $contact The contact of the item owner
1504 * @return array the item record
1505 * @throws \Exception
1507 private static function parentItem($uid, $guid, $author, array $contact)
1509 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1510 'author-name', 'author-link', 'author-avatar',
1511 'owner-name', 'owner-link', 'owner-avatar'];
1512 $condition = ['uid' => $uid, 'guid' => $guid];
1513 $item = Item::selectFirst($fields, $condition);
1515 if (!DBA::isResult($item)) {
1516 $person = self::personByHandle($author);
1517 $result = self::storeByGuid($guid, $person["url"], $uid);
1519 // We don't have an url for items that arrived at the public dispatcher
1520 if (!$result && !empty($contact["url"])) {
1521 $result = self::storeByGuid($guid, $contact["url"], $uid);
1525 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1527 $item = Item::selectFirst($fields, $condition);
1531 if (!DBA::isResult($item)) {
1532 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1535 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1541 * returns contact details
1543 * @param array $def_contact The default contact if the person isn't found
1544 * @param array $person The record of the person
1545 * @param int $uid The user id
1548 * 'cid' => contact id
1549 * 'network' => network type
1550 * @throws \Exception
1552 private static function authorContactByUrl($def_contact, $person, $uid)
1554 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1555 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1556 if (DBA::isResult($contact)) {
1557 $cid = $contact["id"];
1558 $network = $contact["network"];
1560 $cid = $def_contact["id"];
1561 $network = Protocol::DIASPORA;
1564 return ["cid" => $cid, "network" => $network];
1568 * Is the profile a hubzilla profile?
1570 * @param string $url The profile link
1572 * @return bool is it a hubzilla server?
1574 private static function isHubzilla($url)
1576 return(strstr($url, '/channel/'));
1580 * Generate a post link with a given handle and message guid
1582 * @param string $addr The user handle
1583 * @param string $guid message guid
1584 * @param string $parent_guid optional parent guid
1586 * @return string the post link
1587 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1588 * @throws \ImagickException
1590 private static function plink($addr, $guid, $parent_guid = '')
1592 $contact = Contact::getDetailsByAddr($addr);
1593 if (empty($contact)) {
1594 Logger::info('No contact data for address', ['addr' => $addr]);
1598 if (empty($contact['baseurl'])) {
1599 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1600 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1604 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1605 if (!empty($gserver['platform'])) {
1606 $platform = strtolower($gserver['platform']);
1607 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1610 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1611 if (self::isHubzilla($contact['url'])) {
1612 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1613 $platform = 'hubzilla';
1614 } elseif ($contact['network'] == Protocol::DFRN) {
1615 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1616 $platform = 'friendica';
1620 if ($platform == 'friendica') {
1621 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1624 if ($platform == 'hubzilla') {
1625 return $contact['baseurl'] . '/item/' . $guid;
1628 if ($platform == 'socialhome') {
1629 return $contact['baseurl'] . '/content/' . $guid;
1632 if ($platform != 'diaspora') {
1633 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1637 if ($parent_guid != '') {
1638 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1640 return $contact['baseurl'] . '/posts/' . $guid;
1645 * Receives account migration
1647 * @param array $importer Array of the importer user
1648 * @param object $data The message object
1650 * @return bool Success
1651 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1652 * @throws \ImagickException
1654 private static function receiveAccountMigration(array $importer, $data)
1656 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1657 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1658 $signature = Strings::escapeTags(XML::unescape($data->signature));
1660 $contact = self::contactByHandle($importer["uid"], $old_handle);
1662 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1666 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1669 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1670 $key = self::key($old_handle);
1671 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1672 Logger::log('No valid signature for migration.');
1676 // Update the profile
1677 self::receiveProfile($importer, $data->profile);
1679 // change the technical stuff in contact and gcontact
1680 $data = Probe::uri($new_handle);
1681 if ($data['network'] == Protocol::PHANTOM) {
1682 Logger::log('Account for '.$new_handle." couldn't be probed.");
1686 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1687 'name' => $data['name'], 'nick' => $data['nick'],
1688 'addr' => $data['addr'], 'batch' => $data['batch'],
1689 'notify' => $data['notify'], 'poll' => $data['poll'],
1690 'network' => $data['network']];
1692 DBA::update('contact', $fields, ['addr' => $old_handle]);
1694 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1695 'name' => $data['name'], 'nick' => $data['nick'],
1696 'addr' => $data['addr'], 'connect' => $data['addr'],
1697 'notify' => $data['notify'], 'photo' => $data['photo'],
1698 'server_url' => $data['baseurl'], 'network' => $data['network']];
1700 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1702 Logger::log('Contacts are updated.');
1708 * Processes an account deletion
1710 * @param object $data The message object
1712 * @return bool Success
1713 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1715 private static function receiveAccountDeletion($data)
1717 $author = Strings::escapeTags(XML::unescape($data->author));
1719 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1720 while ($contact = DBA::fetch($contacts)) {
1721 Contact::remove($contact["id"]);
1724 DBA::delete('gcontact', ['addr' => $author]);
1726 Logger::log('Removed contacts for ' . $author);
1732 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1734 * @param string $author Author handle
1735 * @param string $guid Message guid
1736 * @param boolean $onlyfound Only return uri when found in the database
1738 * @return string The constructed uri or the one from our database
1739 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1740 * @throws \ImagickException
1742 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1744 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1745 if (DBA::isResult($item)) {
1746 return $item["uri"];
1747 } elseif (!$onlyfound) {
1748 $person = self::personByHandle($author);
1750 $parts = parse_url($person['url']);
1751 unset($parts['path']);
1752 $host_url = Network::unparseURL($parts);
1754 return $host_url . '/objects/' . $guid;
1761 * Fetch the guid from our database with a given uri
1763 * @param string $uri Message uri
1764 * @param string $uid Author handle
1766 * @return string The post guid
1767 * @throws \Exception
1769 private static function getGuidFromUri($uri, $uid)
1771 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1772 if (DBA::isResult($item)) {
1773 return $item["guid"];
1780 * Find the best importer for a comment, like, ...
1782 * @param string $guid The guid of the item
1784 * @return array|boolean the origin owner of that post - or false
1785 * @throws \Exception
1787 private static function importerForGuid($guid)
1789 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1790 if (DBA::isResult($item)) {
1791 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1792 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1793 if (DBA::isResult($contact)) {
1801 * Store the mentions in the tag table
1803 * @param integer $uriid
1804 * @param string $text
1806 private static function storeMentions(int $uriid, string $text)
1808 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1809 if (empty($matches)) {
1814 * Matching values for the preg match
1815 * [1] = mention type (@ or !)
1816 * [2] = name (optional)
1820 foreach ($matches as $match) {
1821 if (empty($match)) {
1825 $person = self::personByHandle($match[3]);
1826 if (empty($person)) {
1830 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1835 * Processes an incoming comment
1837 * @param array $importer Array of the importer user
1838 * @param string $sender The sender of the message
1839 * @param object $data The message object
1840 * @param string $xml The original XML of the message
1842 * @return int The message id of the generated comment or "false" if there was an error
1843 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1844 * @throws \ImagickException
1846 private static function receiveComment(array $importer, $sender, $data, $xml)
1848 $author = Strings::escapeTags(XML::unescape($data->author));
1849 $guid = Strings::escapeTags(XML::unescape($data->guid));
1850 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1851 $text = XML::unescape($data->text);
1853 if (isset($data->created_at)) {
1854 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1856 $created_at = DateTimeFormat::utcNow();
1859 if (isset($data->thread_parent_guid)) {
1860 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1861 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1866 $contact = self::allowedContactByHandle($importer, $sender, true);
1871 $message_id = self::messageExists($importer["uid"], $guid);
1876 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1877 if (!$parent_item) {
1881 $person = self::personByHandle($author);
1882 if (!is_array($person)) {
1883 Logger::log("unable to find author details");
1887 // Fetch the contact id - if we know this contact
1888 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1892 $datarray["uid"] = $importer["uid"];
1893 $datarray["contact-id"] = $author_contact["cid"];
1894 $datarray["network"] = $author_contact["network"];
1896 $datarray["author-link"] = $person["url"];
1897 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1899 $datarray["owner-link"] = $contact["url"];
1900 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1902 $datarray["guid"] = $guid;
1903 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1904 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1906 $datarray["verb"] = Activity::POST;
1907 $datarray["gravity"] = GRAVITY_COMMENT;
1909 if ($thr_uri != "") {
1910 $datarray["parent-uri"] = $thr_uri;
1912 $datarray["parent-uri"] = $parent_item["uri"];
1915 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1917 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1918 $datarray["source"] = $xml;
1920 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1922 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1923 $body = Markdown::toBBCode($text);
1925 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1927 self::storeMentions($datarray['uri-id'], $text);
1928 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
1930 self::fetchGuid($datarray);
1932 // If we are the origin of the parent we store the original data.
1933 // We notify our followers during the item storage.
1934 if ($parent_item["origin"]) {
1935 $datarray['diaspora_signed_text'] = json_encode($data);
1938 $message_id = Item::insert($datarray);
1940 if ($message_id <= 0) {
1945 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1946 if ($datarray['uid'] == 0) {
1947 Item::distribute($message_id, json_encode($data));
1955 * processes and stores private messages
1957 * @param array $importer Array of the importer user
1958 * @param array $contact The contact of the message
1959 * @param object $data The message object
1960 * @param array $msg Array of the processed message, author handle and key
1961 * @param object $mesg The private message
1962 * @param array $conversation The conversation record to which this message belongs
1964 * @return bool "true" if it was successful
1965 * @throws \Exception
1967 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1969 $author = Strings::escapeTags(XML::unescape($data->author));
1970 $guid = Strings::escapeTags(XML::unescape($data->guid));
1971 $subject = Strings::escapeTags(XML::unescape($data->subject));
1973 // "diaspora_handle" is the element name from the old version
1974 // "author" is the element name from the new version
1975 if ($mesg->author) {
1976 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1977 } elseif ($mesg->diaspora_handle) {
1978 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1983 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1984 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1985 $msg_text = XML::unescape($mesg->text);
1986 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1988 if ($msg_conversation_guid != $guid) {
1989 Logger::log("message conversation guid does not belong to the current conversation.");
1993 $body = Markdown::toBBCode($msg_text);
1994 $message_uri = $msg_author.":".$msg_guid;
1996 $person = self::personByHandle($msg_author);
1998 return Mail::insert([
1999 'uid' => $importer['uid'],
2000 'guid' => $msg_guid,
2001 'convid' => $conversation['id'],
2002 'from-name' => $person['name'],
2003 'from-photo' => $person['photo'],
2004 'from-url' => $person['url'],
2005 'contact-id' => $contact['id'],
2006 'title' => $subject,
2008 'uri' => $message_uri,
2009 'parent-uri' => $author . ':' . $guid,
2010 'created' => $msg_created_at
2015 * Processes new private messages (answers to private messages are processed elsewhere)
2017 * @param array $importer Array of the importer user
2018 * @param array $msg Array of the processed message, author handle and key
2019 * @param object $data The message object
2021 * @return bool Success
2022 * @throws \Exception
2024 private static function receiveConversation(array $importer, $msg, $data)
2026 $author = Strings::escapeTags(XML::unescape($data->author));
2027 $guid = Strings::escapeTags(XML::unescape($data->guid));
2028 $subject = Strings::escapeTags(XML::unescape($data->subject));
2029 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2030 $participants = Strings::escapeTags(XML::unescape($data->participants));
2032 $messages = $data->message;
2034 if (!count($messages)) {
2035 Logger::log("empty conversation");
2039 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
2044 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2045 if (!DBA::isResult($conversation)) {
2047 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
2048 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
2049 intval($importer["uid"]),
2051 DBA::escape($author),
2052 DBA::escape($created_at),
2053 DBA::escape(DateTimeFormat::utcNow()),
2054 DBA::escape($subject),
2055 DBA::escape($participants)
2058 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2061 if (!$conversation) {
2062 Logger::log("unable to create conversation.");
2066 foreach ($messages as $mesg) {
2067 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
2074 * Processes "like" messages
2076 * @param array $importer Array of the importer user
2077 * @param string $sender The sender of the message
2078 * @param object $data The message object
2080 * @return int The message id of the generated like or "false" if there was an error
2081 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2082 * @throws \ImagickException
2084 private static function receiveLike(array $importer, $sender, $data)
2086 $author = Strings::escapeTags(XML::unescape($data->author));
2087 $guid = Strings::escapeTags(XML::unescape($data->guid));
2088 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2089 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
2090 $positive = Strings::escapeTags(XML::unescape($data->positive));
2092 // likes on comments aren't supported by Diaspora - only on posts
2093 // But maybe this will be supported in the future, so we will accept it.
2094 if (!in_array($parent_type, ["Post", "Comment"])) {
2098 $contact = self::allowedContactByHandle($importer, $sender, true);
2103 $message_id = self::messageExists($importer["uid"], $guid);
2108 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2109 if (!$parent_item) {
2113 $person = self::personByHandle($author);
2114 if (!is_array($person)) {
2115 Logger::log("unable to find author details");
2119 // Fetch the contact id - if we know this contact
2120 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2122 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2123 // We would accept this anyhow.
2124 if ($positive == "true") {
2125 $verb = Activity::LIKE;
2127 $verb = Activity::DISLIKE;
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"] = $verb;
2145 $datarray["gravity"] = GRAVITY_ACTIVITY;
2146 $datarray["parent-uri"] = $parent_item["uri"];
2148 $datarray["object-type"] = Activity\ObjectType::NOTE;
2150 $datarray["body"] = $verb;
2152 // Diaspora doesn't provide a date for likes
2153 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2155 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2156 if ($parent_item["id"] != $parent_item["parent"]) {
2157 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
2158 $origin = $toplevel["origin"];
2160 $origin = $parent_item["origin"];
2163 // If we are the origin of the parent we store the original data.
2164 // We notify our followers during the item storage.
2166 $datarray['diaspora_signed_text'] = json_encode($data);
2169 $message_id = Item::insert($datarray);
2171 if ($message_id <= 0) {
2176 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2177 if ($datarray['uid'] == 0) {
2178 Item::distribute($message_id, json_encode($data));
2186 * Processes private messages
2188 * @param array $importer Array of the importer user
2189 * @param object $data The message object
2191 * @return bool Success?
2192 * @throws \Exception
2194 private static function receiveMessage(array $importer, $data)
2196 $author = Strings::escapeTags(XML::unescape($data->author));
2197 $guid = Strings::escapeTags(XML::unescape($data->guid));
2198 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2199 $text = XML::unescape($data->text);
2200 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2202 $contact = self::allowedContactByHandle($importer, $author, true);
2207 $conversation = null;
2209 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2210 $conversation = DBA::selectFirst('conv', [], $condition);
2212 if (!DBA::isResult($conversation)) {
2213 Logger::log("conversation not available.");
2217 $message_uri = $author.":".$guid;
2219 $person = self::personByHandle($author);
2221 Logger::log("unable to find author details");
2225 $body = Markdown::toBBCode($text);
2227 $body = self::replacePeopleGuid($body, $person["url"]);
2229 return Mail::insert([
2230 'uid' => $importer['uid'],
2232 'convid' => $conversation['id'],
2233 'from-name' => $person['name'],
2234 'from-photo' => $person['photo'],
2235 'from-url' => $person['url'],
2236 'contact-id' => $contact['id'],
2237 'title' => $conversation['subject'],
2240 'uri' => $message_uri,
2241 'parent-uri' => $author.":".$conversation['guid'],
2242 'created' => $created_at
2247 * Processes participations - unsupported by now
2249 * @param array $importer Array of the importer user
2250 * @param object $data The message object
2252 * @return bool always true
2253 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2254 * @throws \ImagickException
2256 private static function receiveParticipation(array $importer, $data)
2258 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2259 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2261 $contact_id = Contact::getIdForURL($author);
2263 Logger::log('Contact not found: '.$author);
2267 $person = self::personByHandle($author);
2268 if (!is_array($person)) {
2269 Logger::log("Person not found: ".$author);
2273 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2274 if (!DBA::isResult($item)) {
2275 Logger::log('Item not found, no origin or private: '.$parent_guid);
2279 $author_parts = explode('@', $author);
2280 if (isset($author_parts[1])) {
2281 $server = $author_parts[1];
2283 // Should never happen
2287 Logger::log('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, Logger::DEBUG);
2289 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2290 DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2293 // Send all existing comments and likes to the requesting server
2294 $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2295 while ($comment = Item::fetch($comments)) {
2296 if ($comment['id'] == $comment['parent']) {
2300 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $contact_id]);
2301 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $contact_id)) {
2302 ItemDeliveryData::incrementQueueCount($comment['id'], 1);
2305 DBA::close($comments);
2311 * Processes photos - unneeded
2313 * @param array $importer Array of the importer user
2314 * @param object $data The message object
2316 * @return bool always true
2318 private static function receivePhoto(array $importer, $data)
2320 // There doesn't seem to be a reason for this function,
2321 // since the photo data is transmitted in the status message as well
2326 * Processes poll participations - unssupported
2328 * @param array $importer Array of the importer user
2329 * @param object $data The message object
2331 * @return bool always true
2333 private static function receivePollParticipation(array $importer, $data)
2335 // We don't support polls by now
2340 * Processes incoming profile updates
2342 * @param array $importer Array of the importer user
2343 * @param object $data The message object
2345 * @return bool Success
2346 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2347 * @throws \ImagickException
2349 private static function receiveProfile(array $importer, $data)
2351 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2353 $contact = self::contactByHandle($importer["uid"], $author);
2358 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2359 $image_url = XML::unescape($data->image_url);
2360 $birthday = XML::unescape($data->birthday);
2361 $about = Markdown::toBBCode(XML::unescape($data->bio));
2362 $location = Markdown::toBBCode(XML::unescape($data->location));
2363 $searchable = (XML::unescape($data->searchable) == "true");
2364 $nsfw = (XML::unescape($data->nsfw) == "true");
2365 $tags = XML::unescape($data->tag_string);
2367 $tags = explode("#", $tags);
2370 foreach ($tags as $tag) {
2371 $tag = trim(strtolower($tag));
2377 $keywords = implode(", ", $keywords);
2379 $handle_parts = explode("@", $author);
2380 $nick = $handle_parts[0];
2383 $name = $handle_parts[0];
2386 if (preg_match("|^https?://|", $image_url) === 0) {
2387 $image_url = "http://".$handle_parts[1].$image_url;
2390 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2392 // Generic birthday. We don't know the timezone. The year is irrelevant.
2394 $birthday = str_replace("1000", "1901", $birthday);
2396 if ($birthday != "") {
2397 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2400 // this is to prevent multiple birthday notifications in a single year
2401 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2403 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2404 $birthday = $contact["bd"];
2407 $fields = ['name' => $name, 'location' => $location,
2408 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2409 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2410 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2412 if (!empty($birthday)) {
2413 $fields['bd'] = $birthday;
2416 DBA::update('contact', $fields, ['id' => $contact['id']]);
2418 // @todo Update the public contact, then update the gcontact from that
2420 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2421 "photo" => $image_url, "name" => $name, "location" => $location,
2422 "about" => $about, "birthday" => $birthday,
2423 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2424 "hide" => !$searchable, "nsfw" => $nsfw];
2426 $gcid = GContact::update($gcontact);
2428 GContact::link($gcid, $importer["uid"], $contact["id"]);
2430 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2436 * Processes incoming friend requests
2438 * @param array $importer Array of the importer user
2439 * @param array $contact The contact that send the request
2441 * @throws \Exception
2443 private static function receiveRequestMakeFriend(array $importer, array $contact)
2445 if ($contact["rel"] == Contact::SHARING) {
2448 ['rel' => Contact::FRIEND, 'writable' => true],
2449 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2455 * Processes incoming sharing notification
2457 * @param array $importer Array of the importer user
2458 * @param object $data The message object
2460 * @return bool Success
2461 * @throws \Exception
2463 private static function receiveContactRequest(array $importer, $data)
2465 $author = XML::unescape($data->author);
2466 $recipient = XML::unescape($data->recipient);
2468 if (!$author || !$recipient) {
2472 // the current protocol version doesn't know these fields
2473 // That means that we will assume their existance
2474 if (isset($data->following)) {
2475 $following = (XML::unescape($data->following) == "true");
2480 if (isset($data->sharing)) {
2481 $sharing = (XML::unescape($data->sharing) == "true");
2486 $contact = self::contactByHandle($importer["uid"], $author);
2488 // perhaps we were already sharing with this person. Now they're sharing with us.
2489 // That makes us friends.
2492 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2493 self::receiveRequestMakeFriend($importer, $contact);
2495 // refetch the contact array
2496 $contact = self::contactByHandle($importer["uid"], $author);
2498 // If we are now friends, we are sending a share message.
2499 // Normally we needn't to do so, but the first message could have been vanished.
2500 if (in_array($contact["rel"], [Contact::FRIEND])) {
2501 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2502 if (DBA::isResult($user)) {
2503 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2504 self::sendShare($user, $contact);
2509 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2510 Contact::removeFollower($importer, $contact);
2515 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2516 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2518 } elseif (!$following && !$sharing) {
2519 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2521 } elseif (!$following && $sharing) {
2522 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2523 } elseif ($following && $sharing) {
2524 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2525 } elseif ($following && !$sharing) {
2526 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2529 $ret = self::personByHandle($author);
2531 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2532 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2536 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2538 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2543 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2544 'author-link' => $ret['url']];
2546 $result = Contact::addRelationship($importer, $contact, $item, false);
2547 if ($result === true) {
2548 $contact_record = self::contactByHandle($importer['uid'], $author);
2549 if (!$contact_record) {
2550 Logger::info('unable to locate newly created contact record.');
2554 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2555 if (DBA::isResult($user)) {
2556 self::sendShare($user, $contact_record);
2558 // Send the profile data, maybe it weren't transmitted before
2559 self::sendProfile($importer['uid'], [$contact_record]);
2567 * Fetches a message with a given guid
2569 * @param string $guid message guid
2570 * @param string $orig_author handle of the original post
2571 * @return array The fetched item
2572 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2573 * @throws \ImagickException
2575 public static function originalItem($guid, $orig_author)
2578 Logger::log('Empty guid. Quitting.');
2582 // Do we already have this item?
2583 $fields = ['body', 'title', 'attach', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2584 'author-name', 'author-link', 'author-avatar'];
2585 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2586 $item = Item::selectFirst($fields, $condition);
2588 if (DBA::isResult($item)) {
2589 Logger::log("reshared message ".$guid." already exists on system.");
2591 // Maybe it is already a reshared item?
2592 // Then refetch the content, if it is a reshare from a reshare.
2593 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2594 if (self::isReshare($item["body"], true)) {
2596 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2597 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2599 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2601 // Add OEmbed and other information to the body
2602 $item["body"] = add_page_info_to_body($item["body"], false, true);
2610 if (!DBA::isResult($item)) {
2611 if (empty($orig_author)) {
2612 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2616 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2617 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2618 $stored = self::storeByGuid($guid, $server);
2621 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2622 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2623 $stored = self::storeByGuid($guid, $server);
2627 $fields = ['body', 'title', 'attach', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2628 'author-name', 'author-link', 'author-avatar'];
2629 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2630 $item = Item::selectFirst($fields, $condition);
2632 if (DBA::isResult($item)) {
2633 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2634 if (self::isReshare($item["body"], false)) {
2635 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2636 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2647 * Stores a reshare activity
2649 * @param array $item Array of reshare post
2650 * @param integer $parent_message_id Id of the parent post
2651 * @param string $guid GUID string of reshare action
2652 * @param string $author Author handle
2654 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2656 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2660 $datarray['uid'] = $item['uid'];
2661 $datarray['contact-id'] = $item['contact-id'];
2662 $datarray['network'] = $item['network'];
2664 $datarray['author-link'] = $item['author-link'];
2665 $datarray['author-id'] = $item['author-id'];
2667 $datarray['owner-link'] = $datarray['author-link'];
2668 $datarray['owner-id'] = $datarray['author-id'];
2670 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2671 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2672 $datarray['parent-uri'] = $parent['uri'];
2674 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2675 $datarray['gravity'] = GRAVITY_ACTIVITY;
2676 $datarray['object-type'] = Activity\ObjectType::NOTE;
2678 $datarray['protocol'] = $item['protocol'];
2680 $datarray['plink'] = self::plink($author, $datarray['guid']);
2681 $datarray['private'] = $item['private'];
2682 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2684 $message_id = Item::insert($datarray);
2687 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2688 if ($datarray['uid'] == 0) {
2689 Item::distribute($message_id);
2695 * Processes a reshare message
2697 * @param array $importer Array of the importer user
2698 * @param object $data The message object
2699 * @param string $xml The original XML of the message
2701 * @return int the message id
2702 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2703 * @throws \ImagickException
2705 private static function receiveReshare(array $importer, $data, $xml)
2707 $author = Strings::escapeTags(XML::unescape($data->author));
2708 $guid = Strings::escapeTags(XML::unescape($data->guid));
2709 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2710 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2711 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2712 /// @todo handle unprocessed property "provider_display_name"
2713 $public = Strings::escapeTags(XML::unescape($data->public));
2715 $contact = self::allowedContactByHandle($importer, $author, false);
2720 $message_id = self::messageExists($importer["uid"], $guid);
2725 $original_item = self::originalItem($root_guid, $root_author);
2726 if (!$original_item) {
2730 $orig_url = DI::baseUrl()."/display/".$original_item["guid"];
2734 $datarray["uid"] = $importer["uid"];
2735 $datarray["contact-id"] = $contact["id"];
2736 $datarray["network"] = Protocol::DIASPORA;
2738 $datarray["author-link"] = $contact["url"];
2739 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2741 $datarray["owner-link"] = $datarray["author-link"];
2742 $datarray["owner-id"] = $datarray["author-id"];
2744 $datarray["guid"] = $guid;
2745 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2746 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2748 $datarray["verb"] = Activity::POST;
2749 $datarray["gravity"] = GRAVITY_PARENT;
2751 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2752 $datarray["source"] = $xml;
2754 /// @todo Copy tag data from original post
2756 $prefix = share_header(
2757 $original_item["author-name"],
2758 $original_item["author-link"],
2759 $original_item["author-avatar"],
2760 $original_item["guid"],
2761 $original_item["created"],
2765 if (!empty($original_item['title'])) {
2766 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2769 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2771 Tag::storeFromBody($datarray['uri-id'], $datarray["body"]);
2773 $datarray["tag"] = $original_item["tag"];
2774 $datarray["attach"] = $original_item["attach"];
2775 $datarray["app"] = $original_item["app"];
2777 $datarray["plink"] = self::plink($author, $guid);
2778 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2779 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2781 $datarray["object-type"] = $original_item["object-type"];
2783 self::fetchGuid($datarray);
2784 $message_id = Item::insert($datarray);
2786 self::sendParticipation($contact, $datarray);
2788 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2789 if ($root_message_id) {
2790 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2794 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2795 if ($datarray['uid'] == 0) {
2796 Item::distribute($message_id);
2805 * Processes retractions
2807 * @param array $importer Array of the importer user
2808 * @param array $contact The contact of the item owner
2809 * @param object $data The message object
2811 * @return bool success
2812 * @throws \Exception
2814 private static function itemRetraction(array $importer, array $contact, $data)
2816 $author = Strings::escapeTags(XML::unescape($data->author));
2817 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2818 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2820 $person = self::personByHandle($author);
2821 if (!is_array($person)) {
2822 Logger::log("unable to find author detail for ".$author);
2826 if (empty($contact["url"])) {
2827 $contact["url"] = $person["url"];
2830 // Fetch items that are about to be deleted
2831 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2833 // When we receive a public retraction, we delete every item that we find.
2834 if ($importer['uid'] == 0) {
2835 $condition = ['guid' => $target_guid, 'deleted' => false];
2837 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2840 $r = Item::select($fields, $condition);
2841 if (!DBA::isResult($r)) {
2842 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2846 while ($item = Item::fetch($r)) {
2847 if (strstr($item['file'], '[')) {
2848 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2852 // Fetch the parent item
2853 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2855 // Only delete it if the parent author really fits
2856 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2857 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2861 Item::markForDeletion(['id' => $item['id']]);
2863 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], Logger::DEBUG);
2870 * Receives retraction messages
2872 * @param array $importer Array of the importer user
2873 * @param string $sender The sender of the message
2874 * @param object $data The message object
2876 * @return bool Success
2877 * @throws \Exception
2879 private static function receiveRetraction(array $importer, $sender, $data)
2881 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2883 $contact = self::contactByHandle($importer["uid"], $sender);
2884 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2885 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2893 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2895 switch ($target_type) {
2900 case "StatusMessage":
2901 return self::itemRetraction($importer, $contact, $data);
2903 case "PollParticipation":
2905 // Currently unsupported
2909 Logger::log("Unknown target type ".$target_type);
2916 * Receives status messages
2918 * @param array $importer Array of the importer user
2919 * @param SimpleXMLElement $data The message object
2920 * @param string $xml The original XML of the message
2922 * @return int The message id of the newly created item
2923 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2924 * @throws \ImagickException
2926 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2928 $author = Strings::escapeTags(XML::unescape($data->author));
2929 $guid = Strings::escapeTags(XML::unescape($data->guid));
2930 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2931 $public = Strings::escapeTags(XML::unescape($data->public));
2932 $text = XML::unescape($data->text);
2933 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2935 $contact = self::allowedContactByHandle($importer, $author, false);
2940 $message_id = self::messageExists($importer["uid"], $guid);
2946 if ($data->location) {
2947 foreach ($data->location->children() as $fieldname => $data) {
2948 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2952 $body = Markdown::toBBCode($text);
2956 // Attach embedded pictures to the body
2958 foreach ($data->photo as $photo) {
2959 $body = "[img]".XML::unescape($photo->remote_photo_path).
2960 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2963 $datarray["object-type"] = Activity\ObjectType::IMAGE;
2965 $datarray["object-type"] = Activity\ObjectType::NOTE;
2967 // Add OEmbed and other information to the body
2968 if (!self::isHubzilla($contact["url"])) {
2969 $body = add_page_info_to_body($body, false, true);
2973 /// @todo enable support for polls
2974 //if ($data->poll) {
2975 // foreach ($data->poll AS $poll)
2980 /// @todo enable support for events
2982 $datarray["uid"] = $importer["uid"];
2983 $datarray["contact-id"] = $contact["id"];
2984 $datarray["network"] = Protocol::DIASPORA;
2986 $datarray["author-link"] = $contact["url"];
2987 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2989 $datarray["owner-link"] = $datarray["author-link"];
2990 $datarray["owner-id"] = $datarray["author-id"];
2992 $datarray["guid"] = $guid;
2993 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2994 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2996 $datarray["verb"] = Activity::POST;
2997 $datarray["gravity"] = GRAVITY_PARENT;
2999 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
3000 $datarray["source"] = $xml;
3002 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3004 self::storeMentions($datarray['uri-id'], $text);
3005 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
3007 if ($provider_display_name != "") {
3008 $datarray["app"] = $provider_display_name;
3011 $datarray["plink"] = self::plink($author, $guid);
3012 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
3013 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3015 if (isset($address["address"])) {
3016 $datarray["location"] = $address["address"];
3019 if (isset($address["lat"]) && isset($address["lng"])) {
3020 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3023 self::fetchGuid($datarray);
3024 $message_id = Item::insert($datarray);
3026 self::sendParticipation($contact, $datarray);
3029 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
3030 if ($datarray['uid'] == 0) {
3031 Item::distribute($message_id);
3039 /* ************************************************************************************** *
3040 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3041 * ************************************************************************************** */
3044 * returnes the handle of a contact
3046 * @param array $contact contact array
3048 * @return string the handle in the format user@domain.tld
3049 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3051 private static function myHandle(array $contact)
3053 if (!empty($contact["addr"])) {
3054 return $contact["addr"];
3057 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3058 // So - just in case - we build the the address here.
3059 if ($contact["nickname"] != "") {
3060 $nick = $contact["nickname"];
3062 $nick = $contact["nick"];
3065 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
3070 * Creates the data for a private message in the new format
3072 * @param string $msg The message that is to be transmitted
3073 * @param array $user The record of the sender
3074 * @param array $contact Target of the communication
3075 * @param string $prvkey The private key of the sender
3076 * @param string $pubkey The public key of the receiver
3078 * @return string The encrypted data
3079 * @throws \Exception
3081 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
3083 Logger::log("Message: ".$msg, Logger::DATA);
3085 // without a public key nothing will work
3087 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3091 $aes_key = openssl_random_pseudo_bytes(32);
3092 $b_aes_key = base64_encode($aes_key);
3093 $iv = openssl_random_pseudo_bytes(16);
3094 $b_iv = base64_encode($iv);
3096 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3098 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3100 $encrypted_key_bundle = "";
3101 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3103 $json_object = json_encode(
3104 ["aes_key" => base64_encode($encrypted_key_bundle),
3105 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3108 return $json_object;
3112 * Creates the envelope for the "fetch" endpoint and for the new format
3114 * @param string $msg The message that is to be transmitted
3115 * @param array $user The record of the sender
3117 * @return string The envelope
3118 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3120 public static function buildMagicEnvelope($msg, array $user)
3122 $b64url_data = Strings::base64UrlEncode($msg);
3123 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3125 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3126 $type = "application/xml";
3127 $encoding = "base64url";
3128 $alg = "RSA-SHA256";
3129 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3131 // Fallback if the private key wasn't transmitted in the expected field
3132 if ($user['uprvkey'] == "") {
3133 $user['uprvkey'] = $user['prvkey'];
3136 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3137 $sig = Strings::base64UrlEncode($signature);
3139 $xmldata = ["me:env" => ["me:data" => $data,
3140 "@attributes" => ["type" => $type],
3141 "me:encoding" => $encoding,
3144 "@attributes2" => ["key_id" => $key_id]]];
3146 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3148 return XML::fromArray($xmldata, $xml, false, $namespaces);
3152 * Create the envelope for a message
3154 * @param string $msg The message that is to be transmitted
3155 * @param array $user The record of the sender
3156 * @param array $contact Target of the communication
3157 * @param string $prvkey The private key of the sender
3158 * @param string $pubkey The public key of the receiver
3159 * @param bool $public Is the message public?
3161 * @return string The message that will be transmitted to other servers
3162 * @throws \Exception
3164 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3166 // The message is put into an envelope with the sender's signature
3167 $envelope = self::buildMagicEnvelope($msg, $user);
3169 // Private messages are put into a second envelope, encrypted with the receivers public key
3171 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3178 * Creates a signature for a message
3180 * @param array $owner the array of the owner of the message
3181 * @param array $message The message that is to be signed
3183 * @return string The signature
3185 private static function signature($owner, $message)
3188 unset($sigmsg["author_signature"]);
3189 unset($sigmsg["parent_author_signature"]);
3191 $signed_text = implode(";", $sigmsg);
3193 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3197 * Transmit a message to a target server
3199 * @param array $owner the array of the item owner
3200 * @param array $contact Target of the communication
3201 * @param string $envelope The message that is to be transmitted
3202 * @param bool $public_batch Is it a public post?
3203 * @param string $guid message guid
3205 * @return int Result of the transmission
3206 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3207 * @throws \ImagickException
3209 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3211 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
3216 $logid = Strings::getRandomHex(4);
3218 // We always try to use the data from the fcontact table.
3219 // This is important for transmitting data to Friendica servers.
3220 if (!empty($contact['addr'])) {
3221 $fcontact = self::personByHandle($contact['addr']);
3222 if (!empty($fcontact)) {
3223 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3227 if (empty($dest_url)) {
3228 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3232 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3236 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3238 if (!intval(DI::config()->get("system", "diaspora_test"))) {
3239 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3241 $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3242 $return_code = $postResult->getReturnCode();
3244 Logger::log("test_mode");
3248 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3250 return $return_code ? $return_code : -1;
3255 * Build the post xml
3257 * @param string $type The message type
3258 * @param array $message The message data
3260 * @return string The post XML
3262 public static function buildPostXml($type, $message)
3264 $data = [$type => $message];
3266 return XML::fromArray($data, $xml);
3270 * Builds and transmit messages
3272 * @param array $owner the array of the item owner
3273 * @param array $contact Target of the communication
3274 * @param string $type The message type
3275 * @param array $message The message data
3276 * @param bool $public_batch Is it a public post?
3277 * @param string $guid message guid
3279 * @return int Result of the transmission
3280 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3281 * @throws \ImagickException
3283 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3285 $msg = self::buildPostXml($type, $message);
3287 Logger::log('message: '.$msg, Logger::DATA);
3288 Logger::log('send guid '.$guid, Logger::DEBUG);
3290 // Fallback if the private key wasn't transmitted in the expected field
3291 if (empty($owner['uprvkey'])) {
3292 $owner['uprvkey'] = $owner['prvkey'];
3295 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3297 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3299 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3301 return $return_code;
3305 * sends a participation (Used to get all further updates)
3307 * @param array $contact Target of the communication
3308 * @param array $item Item array
3310 * @return int The result of the transmission
3311 * @throws \Exception
3313 private static function sendParticipation(array $contact, array $item)
3315 // Don't send notifications for private postings
3316 if ($item['private'] == Item::PRIVATE) {
3320 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3322 $result = DI::cache()->get($cachekey);
3323 if (!is_null($result)) {
3327 // Fetch some user id to have a valid handle to transmit the participation.
3328 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3329 // If the item belongs to a user, we take this user id.
3330 if ($item['uid'] == 0) {
3331 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3332 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3333 $owner = User::getOwnerDataById($first_user['uid']);
3335 $owner = User::getOwnerDataById($item['uid']);
3338 $author = self::myHandle($owner);
3340 $message = ["author" => $author,
3341 "guid" => System::createUUID(),
3342 "parent_type" => "Post",
3343 "parent_guid" => $item["guid"]];
3345 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3347 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3348 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3350 return self::buildAndTransmit($owner, $contact, "participation", $message);
3354 * sends an account migration
3356 * @param array $owner the array of the item owner
3357 * @param array $contact Target of the communication
3358 * @param int $uid User ID
3360 * @return int The result of the transmission
3361 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3362 * @throws \ImagickException
3364 public static function sendAccountMigration(array $owner, array $contact, $uid)
3366 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3367 $profile = self::createProfileData($uid);
3369 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3370 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3372 $message = ["author" => $old_handle,
3373 "profile" => $profile,
3374 "signature" => $signature];
3376 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3378 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3382 * Sends a "share" message
3384 * @param array $owner the array of the item owner
3385 * @param array $contact Target of the communication
3387 * @return int The result of the transmission
3388 * @throws \Exception
3390 public static function sendShare(array $owner, array $contact)
3393 * @todo support the different possible combinations of "following" and "sharing"
3394 * Currently, Diaspora only interprets the "sharing" field
3396 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3400 switch ($contact["rel"]) {
3401 case Contact::FRIEND:
3405 case Contact::SHARING:
3409 case Contact::FOLLOWER:
3415 $message = ["author" => self::myHandle($owner),
3416 "recipient" => $contact["addr"],
3417 "following" => "true",
3418 "sharing" => "true"];
3420 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3422 return self::buildAndTransmit($owner, $contact, "contact", $message);
3426 * sends an "unshare"
3428 * @param array $owner the array of the item owner
3429 * @param array $contact Target of the communication
3431 * @return int The result of the transmission
3432 * @throws \Exception
3434 public static function sendUnshare(array $owner, array $contact)
3436 $message = ["author" => self::myHandle($owner),
3437 "recipient" => $contact["addr"],
3438 "following" => "false",
3439 "sharing" => "false"];
3441 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3443 return self::buildAndTransmit($owner, $contact, "contact", $message);
3447 * Checks a message body if it is a reshare
3449 * @param string $body The message body that is to be check
3450 * @param bool $complete Should it be a complete check or a simple check?
3452 * @return array|bool Reshare details or "false" if no reshare
3453 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3454 * @throws \ImagickException
3456 public static function isReshare($body, $complete = true)
3458 $body = trim($body);
3460 $reshared = Item::getShareArray(['body' => $body]);
3461 if (empty($reshared)) {
3465 // Skip if it isn't a pure repeated messages
3466 // Does it start with a share?
3467 if (!empty($reshared['comment']) && $complete) {
3471 if (!empty($reshared['guid']) && $complete) {
3472 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3473 $item = Item::selectFirst(['contact-id'], $condition);
3474 if (DBA::isResult($item)) {
3476 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3477 $ret["root_guid"] = $reshared['guid'];
3479 } elseif ($complete) {
3480 // We are resharing something that isn't a DFRN or Diaspora post.
3481 // So we have to return "false" on "$complete" to not trigger a reshare.
3484 } elseif (empty($reshared['guid']) && $complete) {
3490 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3491 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3492 if (!empty($contact['addr'])) {
3493 $ret['root_handle'] = $contact['addr'];
3497 if (empty($ret) && !$complete) {
3505 * Create an event array
3507 * @param integer $event_id The id of the event
3509 * @return array with event data
3510 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3512 private static function buildEvent($event_id)
3514 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3515 if (!DBA::isResult($r)) {
3523 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3524 if (!DBA::isResult($r)) {
3530 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3531 if (!DBA::isResult($r)) {
3537 $eventdata['author'] = self::myHandle($owner);
3539 if ($event['guid']) {
3540 $eventdata['guid'] = $event['guid'];
3543 $mask = DateTimeFormat::ATOM;
3545 /// @todo - establish "all day" events in Friendica
3546 $eventdata["all_day"] = "false";
3548 $eventdata['timezone'] = 'UTC';
3549 if (!$event['adjust'] && $user['timezone']) {
3550 $eventdata['timezone'] = $user['timezone'];
3553 if ($event['start']) {
3554 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3556 if ($event['finish'] && !$event['nofinish']) {
3557 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3559 if ($event['summary']) {
3560 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3562 if ($event['desc']) {
3563 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3565 if ($event['location']) {
3566 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3567 $coord = Map::getCoordinates($event['location']);
3570 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3571 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3572 $location["lat"] = $coord['lat'];
3573 $location["lng"] = $coord['lon'];
3575 $location["lat"] = 0;
3576 $location["lng"] = 0;
3578 $eventdata['location'] = $location;
3585 * Create a post (status message or reshare)
3587 * @param array $item The item that will be exported
3588 * @param array $owner the array of the item owner
3591 * 'type' -> Message type ("status_message" or "reshare")
3592 * 'message' -> Array of XML elements of the status
3593 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3594 * @throws \ImagickException
3596 public static function buildStatus(array $item, array $owner)
3598 $cachekey = "diaspora:buildStatus:".$item['guid'];
3600 $result = DI::cache()->get($cachekey);
3601 if (!is_null($result)) {
3605 $myaddr = self::myHandle($owner);
3607 $public = ($item["private"] == Item::PRIVATE ? "false" : "true");
3608 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3609 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3611 // Detect a share element and do a reshare
3612 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) {
3613 $message = ["author" => $myaddr,
3614 "guid" => $item["guid"],
3615 "created_at" => $created,
3616 "root_author" => $ret["root_handle"],
3617 "root_guid" => $ret["root_guid"],
3618 "provider_display_name" => $item["app"],
3619 "public" => $public];
3623 $title = $item["title"];
3624 $body = $item["body"];
3626 // Fetch the title from an attached link - if there is one
3627 if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3628 $page_data = BBCode::getAttachmentData($item['body']);
3629 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3630 $title = $page_data['title'];
3634 if ($item['author-link'] != $item['owner-link']) {
3635 require_once 'mod/share.php';
3636 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3637 "", $item['created'], $item['plink']) . $body . '[/share]';
3640 // convert to markdown
3641 $body = html_entity_decode(BBCode::toMarkdown($body));
3644 if (strlen($title)) {
3645 $body = "### ".html_entity_decode($title)."\n\n".$body;
3648 if ($item["attach"]) {
3649 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3651 $body .= "\n".DI::l10n()->t("Attachments:")."\n";
3652 foreach ($matches as $mtch) {
3653 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3660 if ($item["location"] != "")
3661 $location["address"] = $item["location"];
3663 if ($item["coord"] != "") {
3664 $coord = explode(" ", $item["coord"]);
3665 $location["lat"] = $coord[0];
3666 $location["lng"] = $coord[1];
3669 $message = ["author" => $myaddr,
3670 "guid" => $item["guid"],
3671 "created_at" => $created,
3672 "edited_at" => $edited,
3673 "public" => $public,
3675 "provider_display_name" => $item["app"],
3676 "location" => $location];
3678 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3679 if (!isset($location["lat"]) || !isset($location["lng"])) {
3680 unset($message["location"]);
3683 if ($item['event-id'] > 0) {
3684 $event = self::buildEvent($item['event-id']);
3685 if (count($event)) {
3686 $message['event'] = $event;
3688 if (!empty($event['location']['address']) &&
3689 !empty($event['location']['lat']) &&
3690 !empty($event['location']['lng'])) {
3691 $message['location'] = $event['location'];
3694 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3695 // $message['text'] = '';
3699 $type = "status_message";
3702 $msg = ["type" => $type, "message" => $message];
3704 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3709 private static function prependParentAuthorMention($body, $profile_url)
3711 $profile = Contact::getDetailsByURL($profile_url);
3712 if (!empty($profile['addr'])
3713 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3714 && !strstr($body, $profile['addr'])
3715 && !strstr($body, $profile_url)
3717 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3726 * @param array $item The item that will be exported
3727 * @param array $owner the array of the item owner
3728 * @param array $contact Target of the communication
3729 * @param bool $public_batch Is it a public post?
3731 * @return int The result of the transmission
3732 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3733 * @throws \ImagickException
3735 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3737 $status = self::buildStatus($item, $owner);
3739 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3743 * Creates a "like" object
3745 * @param array $item The item that will be exported
3746 * @param array $owner the array of the item owner
3748 * @return array The data for a "like"
3749 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3751 private static function constructLike(array $item, array $owner)
3753 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3754 if (!DBA::isResult($parent)) {
3758 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3760 if ($item['verb'] === Activity::LIKE) {
3762 } elseif ($item['verb'] === Activity::DISLIKE) {
3763 $positive = "false";
3766 return(["author" => self::myHandle($owner),
3767 "guid" => $item["guid"],
3768 "parent_guid" => $parent["guid"],
3769 "parent_type" => $target_type,
3770 "positive" => $positive,
3771 "author_signature" => ""]);
3775 * Creates an "EventParticipation" object
3777 * @param array $item The item that will be exported
3778 * @param array $owner the array of the item owner
3780 * @return array The data for an "EventParticipation"
3781 * @throws \Exception
3783 private static function constructAttend(array $item, array $owner)
3785 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3786 if (!DBA::isResult($parent)) {
3790 switch ($item['verb']) {
3791 case Activity::ATTEND:
3792 $attend_answer = 'accepted';
3794 case Activity::ATTENDNO:
3795 $attend_answer = 'declined';
3797 case Activity::ATTENDMAYBE:
3798 $attend_answer = 'tentative';
3801 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3805 return(["author" => self::myHandle($owner),
3806 "guid" => $item["guid"],
3807 "parent_guid" => $parent["guid"],
3808 "status" => $attend_answer,
3809 "author_signature" => ""]);
3813 * Creates the object for a comment
3815 * @param array $item The item that will be exported
3816 * @param array $owner the array of the item owner
3818 * @return array|false The data for a comment
3819 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3821 private static function constructComment(array $item, array $owner)
3823 $cachekey = "diaspora:constructComment:".$item['guid'];
3825 $result = DI::cache()->get($cachekey);
3826 if (!is_null($result)) {
3830 $toplevel_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3831 if (!DBA::isResult($toplevel_item)) {
3832 Logger::error('Missing parent conversation item', ['parent' => $item["parent"]]);
3836 $thread_parent_item = $toplevel_item;
3837 if ($item['thr-parent'] != $item['parent-uri']) {
3838 $thread_parent_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3841 $body = $item["body"];
3843 // The replied to autor mention is prepended for clarity if:
3844 // - Item replied isn't yours
3845 // - Item is public or explicit mentions are disabled
3846 // - Implicit mentions are enabled
3848 $item['author-id'] != $thread_parent_item['author-id']
3849 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3850 && !DI::config()->get('system', 'disable_implicit_mentions')
3852 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3855 $text = html_entity_decode(BBCode::toMarkdown($body));
3856 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3857 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3860 "author" => self::myHandle($owner),
3861 "guid" => $item["guid"],
3862 "created_at" => $created,
3863 "edited_at" => $edited,
3864 "parent_guid" => $toplevel_item["guid"],
3866 "author_signature" => ""
3869 // Send the thread parent guid only if it is a threaded comment
3870 if ($item['thr-parent'] != $item['parent-uri']) {
3871 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3874 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3880 * Send a like or a comment
3882 * @param array $item The item that will be exported
3883 * @param array $owner the array of the item owner
3884 * @param array $contact Target of the communication
3885 * @param bool $public_batch Is it a public post?
3887 * @return int The result of the transmission
3888 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3889 * @throws \ImagickException
3891 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3893 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3894 $message = self::constructAttend($item, $owner);
3895 $type = "event_participation";
3896 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3897 $message = self::constructLike($item, $owner);
3899 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3900 $message = self::constructComment($item, $owner);
3904 if (empty($message)) {
3908 $message["author_signature"] = self::signature($owner, $message);
3910 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3914 * Creates a message from a signature record entry
3916 * @param array $item The item that will be exported
3917 * @return array The message
3919 private static function messageFromSignature(array $item)
3921 // Split the signed text
3922 $signed_parts = explode(";", $item['signed_text']);
3924 if ($item["deleted"]) {
3925 $message = ["author" => $item['signer'],
3926 "target_guid" => $signed_parts[0],
3927 "target_type" => $signed_parts[1]];
3928 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3929 $message = ["author" => $signed_parts[4],
3930 "guid" => $signed_parts[1],
3931 "parent_guid" => $signed_parts[3],
3932 "parent_type" => $signed_parts[2],
3933 "positive" => $signed_parts[0],
3934 "author_signature" => $item['signature'],
3935 "parent_author_signature" => ""];
3937 // Remove the comment guid
3938 $guid = array_shift($signed_parts);
3940 // Remove the parent guid
3941 $parent_guid = array_shift($signed_parts);
3943 // Remove the handle
3944 $handle = array_pop($signed_parts);
3947 "author" => $handle,
3949 "parent_guid" => $parent_guid,
3950 "text" => implode(";", $signed_parts),
3951 "author_signature" => $item['signature'],
3952 "parent_author_signature" => ""
3959 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3961 * @param array $item The item that will be exported
3962 * @param array $owner the array of the item owner
3963 * @param array $contact Target of the communication
3964 * @param bool $public_batch Is it a public post?
3966 * @return int The result of the transmission
3967 * @throws \Exception
3969 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3971 if ($item["deleted"]) {
3972 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3973 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3979 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3981 $msg = json_decode($item['signed_text'], true);
3984 if (is_array($msg)) {
3985 foreach ($msg as $field => $data) {
3986 if (!$item["deleted"]) {
3987 if ($field == "diaspora_handle") {
3990 if ($field == "target_type") {
3991 $field = "parent_type";
3995 $message[$field] = $data;
3998 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
4001 $message["parent_author_signature"] = self::signature($owner, $message);
4003 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
4005 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4009 * Sends a retraction (deletion) of a message, like or comment
4011 * @param array $item The item that will be exported
4012 * @param array $owner the array of the item owner
4013 * @param array $contact Target of the communication
4014 * @param bool $public_batch Is it a public post?
4015 * @param bool $relay Is the retraction transmitted from a relay?
4017 * @return int The result of the transmission
4018 * @throws \Exception
4020 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
4022 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4024 $msg_type = "retraction";
4026 if ($item['id'] == $item['parent']) {
4027 $target_type = "Post";
4028 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4029 $target_type = "Like";
4031 $target_type = "Comment";
4034 $message = ["author" => $itemaddr,
4035 "target_guid" => $item['guid'],
4036 "target_type" => $target_type];
4038 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
4040 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4046 * @param array $item The item that will be exported
4047 * @param array $owner The owner
4048 * @param array $contact Target of the communication
4050 * @return int The result of the transmission
4051 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4052 * @throws \ImagickException
4054 public static function sendMail(array $item, array $owner, array $contact)
4056 $myaddr = self::myHandle($owner);
4058 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
4059 if (!DBA::isResult($cnv)) {
4060 Logger::log("conversation not found.");
4064 $body = BBCode::toMarkdown($item["body"]);
4065 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4068 "author" => $myaddr,
4069 "guid" => $item["guid"],
4070 "conversation_guid" => $cnv["guid"],
4072 "created_at" => $created,
4075 if ($item["reply"]) {
4080 "author" => $cnv["creator"],
4081 "guid" => $cnv["guid"],
4082 "subject" => $cnv["subject"],
4083 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4084 "participants" => $cnv["recips"],
4088 $type = "conversation";
4091 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4095 * Split a name into first name and last name
4097 * @param string $name The name
4099 * @return array The array with "first" and "last"
4101 public static function splitName($name) {
4102 $name = trim($name);
4104 // Is the name longer than 64 characters? Then cut the rest of it.
4105 if (strlen($name) > 64) {
4106 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4107 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4109 $name = substr($name, 0, 64);
4113 // Take the first word as first name
4114 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4115 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4116 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4117 return ['first' => $first, 'last' => $last];
4120 // Take the last word as last name
4121 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4122 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4124 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4125 return ['first' => $first, 'last' => $last];
4128 // Take the first 32 characters if there is no space in the first 32 characters
4129 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4130 $first = substr($name, 0, 32);
4131 $last = substr($name, 32);
4132 return ['first' => $first, 'last' => $last];
4135 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4136 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4138 // Check if the last name is longer than 32 characters
4139 if (strlen($last) > 32) {
4140 if (strpos($last, ' ') <= 32) {
4141 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4143 $last = substr($last, 0, 32);
4147 return ['first' => $first, 'last' => $last];
4151 * Create profile data
4153 * @param int $uid The user id
4155 * @return array The profile data
4156 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4158 private static function createProfileData($uid)
4160 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
4161 if (!DBA::isResult($profile)) {
4165 $handle = $profile["addr"];
4167 $split_name = self::splitName($profile['name']);
4168 $first = $split_name['first'];
4169 $last = $split_name['last'];
4171 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4172 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4173 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4174 $searchable = ($profile['net-publish'] ? 'true' : 'false');
4180 if ($searchable === 'true') {
4183 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4184 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4188 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4191 $about = BBCode::toMarkdown($profile['about']);
4193 $location = $profile['location'];
4195 if ($profile['pub_keywords']) {
4196 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4197 $kw = str_replace(' ', ' ', $kw);
4198 $arr = explode(' ', $kw);
4200 for ($x = 0; $x < 5; $x ++) {
4201 if (!empty($arr[$x])) {
4202 $tags .= '#'. trim($arr[$x]) .' ';
4207 $tags = trim($tags);
4210 return ["author" => $handle,
4211 "first_name" => $first,
4212 "last_name" => $last,
4213 "image_url" => $large,
4214 "image_url_medium" => $medium,
4215 "image_url_small" => $small,
4218 "location" => $location,
4219 "searchable" => $searchable,
4221 "tag_string" => $tags];
4225 * Sends profile data
4227 * @param int $uid The user id
4228 * @param bool $recips optional, default false
4230 * @throws \Exception
4232 public static function sendProfile($uid, $recips = false)
4238 $owner = User::getOwnerDataById($uid);
4245 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4246 AND `uid` = %d AND `rel` != %d",
4247 DBA::escape(Protocol::DIASPORA),
4249 intval(Contact::SHARING)
4257 $message = self::createProfileData($uid);
4259 // @ToDo Split this into single worker jobs
4260 foreach ($recips as $recip) {
4261 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4262 self::buildAndTransmit($owner, $recip, "profile", $message);
4267 * Creates the signature for likes that are created on our system
4269 * @param integer $uid The user of that comment
4270 * @param array $item Item array
4272 * @return array Signed content
4273 * @throws \Exception
4275 public static function createLikeSignature($uid, array $item)
4277 $owner = User::getOwnerDataById($uid);
4278 if (empty($owner)) {
4279 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4283 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4287 $message = self::constructLike($item, $owner);
4288 if ($message === false) {
4292 $message["author_signature"] = self::signature($owner, $message);
4298 * Creates the signature for Comments that are created on our system
4300 * @param integer $uid The user of that comment
4301 * @param array $item Item array
4303 * @return array Signed content
4304 * @throws \Exception
4306 public static function createCommentSignature($uid, array $item)
4308 $owner = User::getOwnerDataById($uid);
4309 if (empty($owner)) {
4310 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4314 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4315 $item['thr-parent'] = $item['parent-uri'];
4317 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4318 if (!DBA::isResult($parent)) {
4322 $item['parent-uri'] = $parent['parent-uri'];
4324 $message = self::constructComment($item, $owner);
4325 if ($message === false) {
4329 $message["author_signature"] = self::signature($owner, $message);