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'];
127 DBA::close($servers);
129 // All tags of the current post
130 $condition = ['otype' => Term::OBJECT_TYPE_POST, 'type' => Term::HASHTAG, 'oid' => $parent['parent']];
131 $tags = DBA::select('term', ['term'], $condition);
133 while ($tag = DBA::fetch($tags)) {
134 $taglist[] = $tag['term'];
138 // All servers who wants content with this tag
140 if (!empty($taglist)) {
141 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
142 while ($server = DBA::fetch($tagserver)) {
143 $tagserverlist[] = $server['gserver-id'];
145 DBA::close($tagserver);
148 // All adresses with the given id
149 if (!empty($tagserverlist)) {
150 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
151 while ($server = DBA::fetch($servers)) {
152 $serverlist[$server['url']] = $server['url'];
154 DBA::close($servers);
158 // Now we are collecting all relay contacts
159 foreach ($serverlist as $server_url) {
160 // We don't send messages to ourselves
161 if (Strings::compareLink($server_url, DI::baseUrl())) {
164 $contact = self::getRelayContact($server_url);
165 if (is_bool($contact)) {
170 foreach ($contacts as $entry) {
171 if ($entry['batch'] == $contact['batch']) {
177 $contacts[] = $contact;
185 * Return a contact for a given server address or creates a dummy entry
187 * @param string $server_url The url of the server
188 * @param array $fields Fieldlist
189 * @return array with the contact
192 private static function getRelayContact(string $server_url, array $fields = ['batch', 'id', 'url', 'name', 'network', 'protocol', 'archive', 'blocked'])
194 // Fetch the relay contact
195 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
196 'contact-type' => Contact::TYPE_RELAY];
197 $contact = DBA::selectFirst('contact', $fields, $condition);
199 if (DBA::isResult($contact)) {
200 if ($contact['archive'] || $contact['blocked']) {
205 self::setRelayContact($server_url);
207 $contact = DBA::selectFirst('contact', $fields, $condition);
208 if (DBA::isResult($contact)) {
213 // It should never happen that we arrive here
218 * Update or insert a relay contact
220 * @param string $server_url The url of the server
221 * @param array $network_fields Optional network specific fields
224 public static function setRelayContact($server_url, array $network_fields = [])
226 $fields = ['created' => DateTimeFormat::utcNow(),
227 'name' => 'relay', 'nick' => 'relay', 'url' => $server_url,
228 'nurl' => Strings::normaliseLink($server_url),
229 'network' => Protocol::DIASPORA, 'uid' => 0,
230 'batch' => $server_url . '/receive/public',
231 'rel' => Contact::FOLLOWER, 'blocked' => false,
232 'pending' => false, 'writable' => true,
233 'baseurl' => $server_url, 'contact-type' => Contact::TYPE_RELAY];
235 $fields = array_merge($fields, $network_fields);
237 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url)];
238 $old = DBA::selectFirst('contact', [], $condition);
239 if (DBA::isResult($old)) {
240 unset($fields['created']);
241 $condition = ['id' => $old['id']];
243 Logger::info('Update relay contact', ['fields' => $fields, 'condition' => $condition]);
244 DBA::update('contact', $fields, $condition, $old);
246 Logger::info('Create relay contact', ['fields' => $fields]);
247 Contact::insert($fields);
252 * Return a list of participating contacts for a thread
254 * This is used for the participation feature.
255 * One of the parameters is a contact array.
256 * This is done to avoid duplicates.
258 * @param integer $thread The id of the thread
259 * @param array $contacts The previously fetched contacts
261 * @return array of relay servers
264 public static function participantsForThread($thread, array $contacts)
266 $participation = DBA::select('participation-view', [], ['iid' => $thread]);
268 while ($contact = DBA::fetch($participation)) {
269 if (empty($contact['protocol'])) {
270 $contact['protocol'] = $contact['network'];
274 foreach ($contacts as $entry) {
275 if ($entry['batch'] == $contact['batch']) {
281 $contacts[] = $contact;
285 DBA::close($participation);
291 * repairs a signature that was double encoded
293 * The function is unused at the moment. It was copied from the old implementation.
295 * @param string $signature The signature
296 * @param string $handle The handle of the signature owner
297 * @param integer $level This value is only set inside this function to avoid endless loops
299 * @return string the repaired signature
302 private static function repairSignature($signature, $handle = "", $level = 1)
304 if ($signature == "") {
308 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
309 $signature = base64_decode($signature);
310 Logger::log("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, Logger::DEBUG);
312 // Do a recursive call to be able to fix even multiple levels
314 $signature = self::repairSignature($signature, $handle, ++$level);
322 * verify the envelope and return the verified data
324 * @param string $envelope The magic envelope
326 * @return string verified data
327 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
328 * @throws \ImagickException
330 private static function verifyMagicEnvelope($envelope)
332 $basedom = XML::parseString($envelope, true);
334 if (!is_object($basedom)) {
335 Logger::log("Envelope is no XML file");
339 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
341 if (sizeof($children) == 0) {
342 Logger::log("XML has no children");
348 $data = Strings::base64UrlDecode($children->data);
349 $type = $children->data->attributes()->type[0];
351 $encoding = $children->encoding;
353 $alg = $children->alg;
355 $sig = Strings::base64UrlDecode($children->sig);
356 $key_id = $children->sig->attributes()->key_id[0];
358 $handle = Strings::base64UrlDecode($key_id);
361 $b64url_data = Strings::base64UrlEncode($data);
362 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
364 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
367 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
371 $key = self::key($handle);
373 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
377 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
379 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
387 * encrypts data via AES
389 * @param string $key The AES key
390 * @param string $iv The IV (is used for CBC encoding)
391 * @param string $data The data that is to be encrypted
393 * @return string encrypted data
395 private static function aesEncrypt($key, $iv, $data)
397 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
401 * decrypts data via AES
403 * @param string $key The AES key
404 * @param string $iv The IV (is used for CBC encoding)
405 * @param string $encrypted The encrypted data
407 * @return string decrypted data
409 private static function aesDecrypt($key, $iv, $encrypted)
411 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
415 * Decodes incoming Diaspora message in the new format
417 * @param string $raw raw post message
418 * @param string $privKey The private key of the importer
419 * @param boolean $no_exit Don't do an http exit on error
422 * 'message' -> decoded Diaspora XML message
423 * 'author' -> author diaspora handle
424 * 'key' -> author public key (converted to pkcs#8)
425 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
426 * @throws \ImagickException
428 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
430 $data = json_decode($raw);
432 // Is it a private post? Then decrypt the outer Salmon
433 if (is_object($data)) {
434 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
435 $ciphertext = base64_decode($data->encrypted_magic_envelope);
437 $outer_key_bundle = '';
438 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
439 $j_outer_key_bundle = json_decode($outer_key_bundle);
441 if (!is_object($j_outer_key_bundle)) {
442 Logger::log('Outer Salmon did not verify. Discarding.');
446 throw new \Friendica\Network\HTTPException\BadRequestException();
450 $outer_iv = base64_decode($j_outer_key_bundle->iv);
451 $outer_key = base64_decode($j_outer_key_bundle->key);
453 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
458 $basedom = XML::parseString($xml, true);
460 if (!is_object($basedom)) {
461 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
465 throw new \Friendica\Network\HTTPException\BadRequestException();
469 $base = $basedom->children(ActivityNamespace::SALMON_ME);
471 // Not sure if this cleaning is needed
472 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
474 // Build the signed data
475 $type = $base->data[0]->attributes()->type[0];
476 $encoding = $base->encoding;
478 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
480 // This is the signature
481 $signature = Strings::base64UrlDecode($base->sig);
483 // Get the senders' public key
484 $key_id = $base->sig[0]->attributes()->key_id[0];
485 $author_addr = base64_decode($key_id);
486 if ($author_addr == '') {
487 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
491 throw new \Friendica\Network\HTTPException\BadRequestException();
495 $key = self::key($author_addr);
497 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
501 throw new \Friendica\Network\HTTPException\BadRequestException();
505 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
507 Logger::log('Message did not verify. Discarding.');
511 throw new \Friendica\Network\HTTPException\BadRequestException();
515 return ['message' => (string)Strings::base64UrlDecode($base->data),
516 'author' => XML::unescape($author_addr),
517 'key' => (string)$key];
521 * Decodes incoming Diaspora message in the deprecated format
523 * @param string $xml urldecoded Diaspora salmon
524 * @param string $privKey The private key of the importer
527 * 'message' -> decoded Diaspora XML message
528 * 'author' -> author diaspora handle
529 * 'key' -> author public key (converted to pkcs#8)
530 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
531 * @throws \ImagickException
533 public static function decode(string $xml, string $privKey = '')
536 $basedom = XML::parseString($xml);
538 if (!is_object($basedom)) {
539 Logger::log("XML is not parseable.");
542 $children = $basedom->children('https://joindiaspora.com/protocol');
544 $inner_aes_key = null;
547 if ($children->header) {
549 $author_link = str_replace('acct:', '', $children->header->author_id);
551 // This happens with posts from a relais
552 if (empty($privKey)) {
553 Logger::log("This is no private post in the old format", Logger::DEBUG);
557 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
559 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
560 $ciphertext = base64_decode($encrypted_header->ciphertext);
562 $outer_key_bundle = '';
563 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
565 $j_outer_key_bundle = json_decode($outer_key_bundle);
567 $outer_iv = base64_decode($j_outer_key_bundle->iv);
568 $outer_key = base64_decode($j_outer_key_bundle->key);
570 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
572 Logger::log('decrypted: '.$decrypted, Logger::DEBUG);
573 $idom = XML::parseString($decrypted);
575 $inner_iv = base64_decode($idom->iv);
576 $inner_aes_key = base64_decode($idom->aes_key);
578 $author_link = str_replace('acct:', '', $idom->author_id);
581 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
583 // figure out where in the DOM tree our data is hiding
586 if ($dom->provenance->data) {
587 $base = $dom->provenance;
588 } elseif ($dom->env->data) {
590 } elseif ($dom->data) {
595 Logger::log('unable to locate salmon data in xml');
596 throw new \Friendica\Network\HTTPException\BadRequestException();
600 // Stash the signature away for now. We have to find their key or it won't be good for anything.
601 $signature = Strings::base64UrlDecode($base->sig);
605 // strip whitespace so our data element will return to one big base64 blob
606 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
609 // stash away some other stuff for later
611 $type = $base->data[0]->attributes()->type[0];
612 $keyhash = $base->sig[0]->attributes()->keyhash[0];
613 $encoding = $base->encoding;
617 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
621 $data = Strings::base64UrlDecode($data);
625 $inner_decrypted = $data;
627 // Decode the encrypted blob
628 $inner_encrypted = base64_decode($data);
629 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
633 Logger::log('Could not retrieve author URI.');
634 throw new \Friendica\Network\HTTPException\BadRequestException();
636 // Once we have the author URI, go to the web and try to find their public key
637 // (first this will look it up locally if it is in the fcontact cache)
638 // This will also convert diaspora public key from pkcs#1 to pkcs#8
640 Logger::log('Fetching key for '.$author_link);
641 $key = self::key($author_link);
644 Logger::log('Could not retrieve author key.');
645 throw new \Friendica\Network\HTTPException\BadRequestException();
648 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
651 Logger::log('Message did not verify. Discarding.');
652 throw new \Friendica\Network\HTTPException\BadRequestException();
655 Logger::log('Message verified.');
657 return ['message' => (string)$inner_decrypted,
658 'author' => XML::unescape($author_link),
659 'key' => (string)$key];
664 * Dispatches public messages and find the fitting receivers
666 * @param array $msg The post that will be dispatched
668 * @return int The message id of the generated message, "true" or "false" if there was an error
669 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
670 * @throws \ImagickException
672 public static function dispatchPublic($msg)
674 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
676 Logger::log("diaspora is disabled");
680 if (!($fields = self::validPosting($msg))) {
681 Logger::log("Invalid posting");
685 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
686 $success = self::dispatch($importer, $msg, $fields);
692 * Dispatches the different message types to the different functions
694 * @param array $importer Array of the importer user
695 * @param array $msg The post that will be dispatched
696 * @param SimpleXMLElement $fields SimpleXML object that contains the message
698 * @return int The message id of the generated message, "true" or "false" if there was an error
699 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
700 * @throws \ImagickException
702 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
704 // The sender is the handle of the contact that sent the message.
705 // This will often be different with relayed messages (for example "like" and "comment")
706 $sender = $msg["author"];
708 // This is only needed for private postings since this is already done for public ones before
709 if (is_null($fields)) {
711 if (!($fields = self::validPosting($msg))) {
712 Logger::log("Invalid posting");
719 $type = $fields->getName();
721 Logger::log("Received message type ".$type." from ".$sender." for user ".$importer["uid"], Logger::DEBUG);
724 case "account_migration":
726 Logger::log('Message with type ' . $type . ' is not private, quitting.');
729 return self::receiveAccountMigration($importer, $fields);
731 case "account_deletion":
732 return self::receiveAccountDeletion($fields);
735 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
739 Logger::log('Message with type ' . $type . ' is not private, quitting.');
742 return self::receiveContactRequest($importer, $fields);
746 Logger::log('Message with type ' . $type . ' is not private, quitting.');
749 return self::receiveConversation($importer, $msg, $fields);
752 return self::receiveLike($importer, $sender, $fields);
756 Logger::log('Message with type ' . $type . ' is not private, quitting.');
759 return self::receiveMessage($importer, $fields);
761 case "participation":
763 Logger::log('Message with type ' . $type . ' is not private, quitting.');
766 return self::receiveParticipation($importer, $fields);
768 case "photo": // Not implemented
769 return self::receivePhoto($importer, $fields);
771 case "poll_participation": // Not implemented
772 return self::receivePollParticipation($importer, $fields);
776 Logger::log('Message with type ' . $type . ' is not private, quitting.');
779 return self::receiveProfile($importer, $fields);
782 return self::receiveReshare($importer, $fields, $msg["message"]);
785 return self::receiveRetraction($importer, $sender, $fields);
787 case "status_message":
788 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
791 Logger::log("Unknown message type ".$type);
797 * Checks if a posting is valid and fetches the data fields.
799 * This function does not only check the signature.
800 * It also does the conversion between the old and the new diaspora format.
802 * @param array $msg Array with the XML, the sender handle and the sender signature
804 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
805 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
806 * @throws \ImagickException
808 private static function validPosting($msg)
810 $data = XML::parseString($msg["message"]);
812 if (!is_object($data)) {
813 Logger::log("No valid XML ".$msg["message"], Logger::DEBUG);
817 // Is this the new or the old version?
818 if ($data->getName() == "XML") {
820 foreach ($data->post->children() as $child) {
828 $type = $element->getName();
831 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
833 // All retractions are handled identically from now on.
834 // In the new version there will only be "retraction".
835 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
836 $type = "retraction";
838 if ($type == "request") {
842 $fields = new SimpleXMLElement("<".$type."/>");
845 $author_signature = null;
846 $parent_author_signature = null;
848 foreach ($element->children() as $fieldname => $entry) {
850 // Translation for the old XML structure
851 if ($fieldname == "diaspora_handle") {
852 $fieldname = "author";
854 if ($fieldname == "participant_handles") {
855 $fieldname = "participants";
857 if (in_array($type, ["like", "participation"])) {
858 if ($fieldname == "target_type") {
859 $fieldname = "parent_type";
862 if ($fieldname == "sender_handle") {
863 $fieldname = "author";
865 if ($fieldname == "recipient_handle") {
866 $fieldname = "recipient";
868 if ($fieldname == "root_diaspora_id") {
869 $fieldname = "root_author";
871 if ($type == "status_message") {
872 if ($fieldname == "raw_message") {
876 if ($type == "retraction") {
877 if ($fieldname == "post_guid") {
878 $fieldname = "target_guid";
880 if ($fieldname == "type") {
881 $fieldname = "target_type";
886 if (($fieldname == "author_signature") && ($entry != "")) {
887 $author_signature = base64_decode($entry);
888 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
889 $parent_author_signature = base64_decode($entry);
890 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
891 if ($signed_data != "") {
895 $signed_data .= $entry;
897 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
898 || ($orig_type == "relayable_retraction")
900 XML::copy($entry, $fields, $fieldname);
904 // This is something that shouldn't happen at all.
905 if (in_array($type, ["status_message", "reshare", "profile"])) {
906 if ($msg["author"] != $fields->author) {
907 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
912 // Only some message types have signatures. So we quit here for the other types.
913 if (!in_array($type, ["comment", "like"])) {
916 // No author_signature? This is a must, so we quit.
917 if (!isset($author_signature)) {
918 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
922 if (isset($parent_author_signature)) {
923 $key = self::key($msg["author"]);
925 Logger::log("No key found for parent author ".$msg["author"], Logger::DEBUG);
929 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
930 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);
935 $key = self::key($fields->author);
937 Logger::log("No key found for author ".$fields->author, Logger::DEBUG);
941 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
942 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);
950 * Fetches the public key for a given handle
952 * @param string $handle The handle
954 * @return string The public key
955 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
956 * @throws \ImagickException
958 private static function key($handle)
960 $handle = strval($handle);
962 Logger::log("Fetching diaspora key for: ".$handle);
964 $r = self::personByHandle($handle);
973 * Fetches data for a given handle
975 * @param string $handle The handle
976 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
978 * @return array the queried data
979 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
980 * @throws \ImagickException
982 public static function personByHandle($handle, $update = null)
984 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
985 if (!DBA::isResult($person)) {
986 $urls = [$handle, str_replace('http://', 'https://', $handle), Strings::normaliseLink($handle)];
987 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'url' => $urls]);
990 if (DBA::isResult($person)) {
991 Logger::debug("In cache " . print_r($person, true));
993 if (is_null($update)) {
994 // update record occasionally so it doesn't get stale
995 $d = strtotime($person["updated"]." +00:00");
996 if ($d < strtotime("now - 14 days")) {
1000 if ($person["guid"] == "") {
1004 } elseif (is_null($update)) {
1005 $update = !DBA::isResult($person);
1011 Logger::log("create or refresh", Logger::DEBUG);
1012 $r = Probe::uri($handle, Protocol::DIASPORA);
1014 // Note that Friendica contacts will return a "Diaspora person"
1015 // if Diaspora connectivity is enabled on their server
1016 if ($r && ($r["network"] === Protocol::DIASPORA)) {
1017 self::updateFContact($r);
1019 $person = self::personByHandle($handle, false);
1027 * Updates the fcontact table
1029 * @param array $arr The fcontact data
1030 * @throws \Exception
1032 private static function updateFContact($arr)
1034 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
1035 'request' => $arr["request"], 'nick' => $arr["nick"],
1036 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
1037 'batch' => $arr["batch"], 'notify' => $arr["notify"],
1038 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
1039 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
1040 'updated' => DateTimeFormat::utcNow()];
1042 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
1044 DBA::update('fcontact', $fields, $condition, true);
1048 * get a handle (user@domain.tld) from a given contact id
1050 * @param int $contact_id The id in the contact table
1051 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1053 * @return string the handle
1054 * @throws \Exception
1056 private static function handleFromContact($contact_id, $pcontact_id = 0)
1060 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
1062 if ($pcontact_id != 0) {
1063 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
1065 if (DBA::isResult($contact) && !empty($contact["addr"])) {
1066 return strtolower($contact["addr"]);
1071 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1075 if (DBA::isResult($r)) {
1078 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1080 if ($contact['addr'] != "") {
1081 $handle = $contact['addr'];
1083 $baseurl_start = strpos($contact['url'], '://') + 3;
1084 // allows installations in a subdirectory--not sure how Diaspora will handle
1085 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1086 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1087 $handle = $contact['nick'].'@'.$baseurl;
1091 return strtolower($handle);
1095 * get a url (scheme://domain.tld/u/user) from a given Diaspora*
1098 * @param mixed $fcontact_guid Hexadecimal string guid
1100 * @return string the contact url or null
1101 * @throws \Exception
1103 public static function urlFromContactGuid($fcontact_guid)
1105 Logger::log("fcontact guid is ".$fcontact_guid, Logger::DEBUG);
1108 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1109 DBA::escape(Protocol::DIASPORA),
1110 DBA::escape($fcontact_guid)
1113 if (DBA::isResult($r)) {
1114 return $r[0]['url'];
1121 * Get a contact id for a given handle
1123 * @todo Move to Friendica\Model\Contact
1125 * @param int $uid The user id
1126 * @param string $handle The handle in the format user@domain.tld
1128 * @return array Contact data
1129 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1130 * @throws \ImagickException
1132 private static function contactByHandle($uid, $handle)
1134 $cid = Contact::getIdForURL($handle, $uid);
1136 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1140 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1141 if (!DBA::isResult($contact)) {
1142 // This here shouldn't happen at all
1143 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1151 * Checks if the given contact url does support ActivityPub
1153 * @param string $url profile url
1154 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1156 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1157 * @throws \ImagickException
1159 public static function isSupportedByContactUrl($url, $update = null)
1161 return !empty(self::personByHandle($url, $update));
1165 * Check if posting is allowed for this contact
1167 * @param array $importer Array of the importer user
1168 * @param array $contact The contact that is checked
1169 * @param bool $is_comment Is the check for a comment?
1171 * @return bool is the contact allowed to post?
1173 private static function postAllow(array $importer, array $contact, $is_comment = false)
1176 * Perhaps we were already sharing with this person. Now they're sharing with us.
1177 * That makes us friends.
1178 * Normally this should have handled by getting a request - but this could get lost
1180 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1181 // It is not removed by now. Possibly the code is needed?
1182 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1185 // array('rel' => Contact::FRIEND, 'writable' => true),
1186 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1189 // $contact["rel"] = Contact::FRIEND;
1190 // Logger::log("defining user ".$contact["nick"]." as friend");
1193 // Contact server is blocked
1194 if (Network::isUrlBlocked($contact['url'])) {
1196 // We don't seem to like that person
1197 } elseif ($contact["blocked"]) {
1198 // Maybe blocked, don't accept.
1200 // We are following this person?
1201 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1202 // Yes, then it is fine.
1204 // Is it a post to a community?
1205 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1208 // Is the message a global user or a comment?
1209 } elseif (($importer["uid"] == 0) || $is_comment) {
1210 // Messages for the global users and comments are always accepted
1218 * Fetches the contact id for a handle and checks if posting is allowed
1220 * @param array $importer Array of the importer user
1221 * @param string $handle The checked handle in the format user@domain.tld
1222 * @param bool $is_comment Is the check for a comment?
1224 * @return array The contact data
1225 * @throws \Exception
1227 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1229 $contact = self::contactByHandle($importer["uid"], $handle);
1231 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1232 // If a contact isn't found, we accept it anyway if it is a comment
1233 if ($is_comment && ($importer["uid"] != 0)) {
1234 return self::contactByHandle(0, $handle);
1235 } elseif ($is_comment) {
1242 if (!self::postAllow($importer, $contact, $is_comment)) {
1243 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1250 * Does the message already exists on the system?
1252 * @param int $uid The user id
1253 * @param string $guid The guid of the message
1255 * @return int|bool message id if the message already was stored into the system - or false.
1256 * @throws \Exception
1258 private static function messageExists($uid, $guid)
1260 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1261 if (DBA::isResult($item)) {
1262 Logger::log("message ".$guid." already exists for user ".$uid);
1270 * Checks for links to posts in a message
1272 * @param array $item The item array
1275 private static function fetchGuid(array $item)
1277 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1278 preg_replace_callback(
1280 function ($match) use ($item) {
1281 self::fetchGuidSub($match, $item);
1286 preg_replace_callback(
1287 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1288 function ($match) use ($item) {
1289 self::fetchGuidSub($match, $item);
1296 * Checks for relative /people/* links in an item body to match local
1297 * contacts or prepends the remote host taken from the author link.
1299 * @param string $body The item body to replace links from
1300 * @param string $author_link The author link for missing local contact fallback
1302 * @return string the replaced string
1304 public static function replacePeopleGuid($body, $author_link)
1306 $return = preg_replace_callback(
1307 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1308 function ($match) use ($author_link) {
1310 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1311 // 1 => '0123456789abcdef'
1313 $handle = self::urlFromContactGuid($match[1]);
1316 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1318 // No local match, restoring absolute remote URL from author scheme and host
1319 $author_url = parse_url($author_link);
1320 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1332 * sub function of "fetchGuid" which checks for links in messages
1334 * @param array $match array containing a link that has to be checked for a message link
1335 * @param array $item The item array
1337 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1338 * @throws \ImagickException
1340 private static function fetchGuidSub($match, $item)
1342 if (!self::storeByGuid($match[1], $item["author-link"])) {
1343 self::storeByGuid($match[1], $item["owner-link"]);
1348 * Fetches an item with a given guid from a given server
1350 * @param string $guid the message guid
1351 * @param string $server The server address
1352 * @param int $uid The user id of the user
1354 * @return int the message id of the stored message or false
1355 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1356 * @throws \ImagickException
1358 private static function storeByGuid($guid, $server, $uid = 0)
1360 $serverparts = parse_url($server);
1362 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1366 $server = $serverparts["scheme"]."://".$serverparts["host"];
1368 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1370 $msg = self::message($guid, $server);
1376 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1378 // Now call the dispatcher
1379 return self::dispatchPublic($msg);
1383 * Fetches a message from a server
1385 * @param string $guid message guid
1386 * @param string $server The url of the server
1387 * @param int $level Endless loop prevention
1390 * 'message' => The message XML
1391 * 'author' => The author handle
1392 * 'key' => The public key of the author
1393 * @throws \Exception
1395 private static function message($guid, $server, $level = 0)
1401 // This will work for new Diaspora servers and Friendica servers from 3.5
1402 $source_url = $server."/fetch/post/".urlencode($guid);
1404 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1406 $envelope = Network::fetchUrl($source_url);
1408 Logger::log("Envelope was fetched.", Logger::DEBUG);
1409 $x = self::verifyMagicEnvelope($envelope);
1411 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1413 Logger::log("Envelope was verified.", Logger::DEBUG);
1423 $source_xml = XML::parseString($x);
1425 if (!is_object($source_xml)) {
1429 if ($source_xml->post->reshare) {
1430 // Reshare of a reshare - old Diaspora version
1431 Logger::log("Message is a reshare", Logger::DEBUG);
1432 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1433 } elseif ($source_xml->getName() == "reshare") {
1434 // Reshare of a reshare - new Diaspora version
1435 Logger::log("Message is a new reshare", Logger::DEBUG);
1436 return self::message($source_xml->root_guid, $server, ++$level);
1441 // Fetch the author - for the old and the new Diaspora version
1442 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1443 $author = (string)$source_xml->post->status_message->diaspora_handle;
1444 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1445 $author = (string)$source_xml->author;
1448 // If this isn't a "status_message" then quit
1450 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1454 $msg = ["message" => $x, "author" => $author];
1456 $msg["key"] = self::key($msg["author"]);
1462 * Fetches an item with a given URL
1464 * @param string $url the message url
1466 * @return int the message id of the stored message or false
1467 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1468 * @throws \ImagickException
1470 public static function fetchByURL($url, $uid = 0)
1472 // Check for Diaspora (and Friendica) typical paths
1473 if (!preg_match("=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1474 Logger::info('Invalid url', ['url' => $url]);
1478 $guid = urldecode($matches[2]);
1480 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1481 if (DBA::isResult($item)) {
1482 Logger::info('Found', ['id' => $item['id']]);
1486 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1487 $ret = self::storeByGuid($guid, $matches[1], $uid);
1488 Logger::info('Result', ['ret' => $ret]);
1490 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1491 if (DBA::isResult($item)) {
1492 Logger::info('Found', ['id' => $item['id']]);
1495 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1501 * Fetches the item record of a given guid
1503 * @param int $uid The user id
1504 * @param string $guid message guid
1505 * @param string $author The handle of the item
1506 * @param array $contact The contact of the item owner
1508 * @return array the item record
1509 * @throws \Exception
1511 private static function parentItem($uid, $guid, $author, array $contact)
1513 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1514 'author-name', 'author-link', 'author-avatar',
1515 'owner-name', 'owner-link', 'owner-avatar'];
1516 $condition = ['uid' => $uid, 'guid' => $guid];
1517 $item = Item::selectFirst($fields, $condition);
1519 if (!DBA::isResult($item)) {
1520 $person = self::personByHandle($author);
1521 $result = self::storeByGuid($guid, $person["url"], $uid);
1523 // We don't have an url for items that arrived at the public dispatcher
1524 if (!$result && !empty($contact["url"])) {
1525 $result = self::storeByGuid($guid, $contact["url"], $uid);
1529 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1531 $item = Item::selectFirst($fields, $condition);
1535 if (!DBA::isResult($item)) {
1536 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1539 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1545 * returns contact details
1547 * @param array $def_contact The default contact if the person isn't found
1548 * @param array $person The record of the person
1549 * @param int $uid The user id
1552 * 'cid' => contact id
1553 * 'network' => network type
1554 * @throws \Exception
1556 private static function authorContactByUrl($def_contact, $person, $uid)
1558 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1559 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1560 if (DBA::isResult($contact)) {
1561 $cid = $contact["id"];
1562 $network = $contact["network"];
1564 $cid = $def_contact["id"];
1565 $network = Protocol::DIASPORA;
1568 return ["cid" => $cid, "network" => $network];
1572 * Is the profile a hubzilla profile?
1574 * @param string $url The profile link
1576 * @return bool is it a hubzilla server?
1578 private static function isHubzilla($url)
1580 return(strstr($url, '/channel/'));
1584 * Generate a post link with a given handle and message guid
1586 * @param string $addr The user handle
1587 * @param string $guid message guid
1588 * @param string $parent_guid optional parent guid
1590 * @return string the post link
1591 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1592 * @throws \ImagickException
1594 private static function plink($addr, $guid, $parent_guid = '')
1596 $contact = Contact::getDetailsByAddr($addr);
1597 if (empty($contact)) {
1598 Logger::info('No contact data for address', ['addr' => $addr]);
1602 if (empty($contact['baseurl'])) {
1603 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1604 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1608 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1609 if (!empty($gserver['platform'])) {
1610 $platform = strtolower($gserver['platform']);
1611 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1614 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1615 if (self::isHubzilla($contact['url'])) {
1616 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1617 $platform = 'hubzilla';
1618 } elseif ($contact['network'] == Protocol::DFRN) {
1619 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1620 $platform = 'friendica';
1624 if ($platform == 'friendica') {
1625 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1628 if ($platform == 'hubzilla') {
1629 return $contact['baseurl'] . '/item/' . $guid;
1632 if ($platform == 'socialhome') {
1633 return $contact['baseurl'] . '/content/' . $guid;
1636 if ($platform != 'diaspora') {
1637 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1641 if ($parent_guid != '') {
1642 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1644 return $contact['baseurl'] . '/posts/' . $guid;
1649 * Receives account migration
1651 * @param array $importer Array of the importer user
1652 * @param object $data The message object
1654 * @return bool Success
1655 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1656 * @throws \ImagickException
1658 private static function receiveAccountMigration(array $importer, $data)
1660 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1661 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1662 $signature = Strings::escapeTags(XML::unescape($data->signature));
1664 $contact = self::contactByHandle($importer["uid"], $old_handle);
1666 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1670 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1673 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1674 $key = self::key($old_handle);
1675 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1676 Logger::log('No valid signature for migration.');
1680 // Update the profile
1681 self::receiveProfile($importer, $data->profile);
1683 // change the technical stuff in contact and gcontact
1684 $data = Probe::uri($new_handle);
1685 if ($data['network'] == Protocol::PHANTOM) {
1686 Logger::log('Account for '.$new_handle." couldn't be probed.");
1690 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1691 'name' => $data['name'], 'nick' => $data['nick'],
1692 'addr' => $data['addr'], 'batch' => $data['batch'],
1693 'notify' => $data['notify'], 'poll' => $data['poll'],
1694 'network' => $data['network']];
1696 DBA::update('contact', $fields, ['addr' => $old_handle]);
1698 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1699 'name' => $data['name'], 'nick' => $data['nick'],
1700 'addr' => $data['addr'], 'connect' => $data['addr'],
1701 'notify' => $data['notify'], 'photo' => $data['photo'],
1702 'server_url' => $data['baseurl'], 'network' => $data['network']];
1704 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1706 Logger::log('Contacts are updated.');
1712 * Processes an account deletion
1714 * @param object $data The message object
1716 * @return bool Success
1717 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1719 private static function receiveAccountDeletion($data)
1721 $author = Strings::escapeTags(XML::unescape($data->author));
1723 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1724 while ($contact = DBA::fetch($contacts)) {
1725 Contact::remove($contact["id"]);
1727 DBA::close($contacts);
1729 DBA::delete('gcontact', ['addr' => $author]);
1731 Logger::log('Removed contacts for ' . $author);
1737 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1739 * @param string $author Author handle
1740 * @param string $guid Message guid
1741 * @param boolean $onlyfound Only return uri when found in the database
1743 * @return string The constructed uri or the one from our database
1744 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1745 * @throws \ImagickException
1747 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1749 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1750 if (DBA::isResult($item)) {
1751 return $item["uri"];
1752 } elseif (!$onlyfound) {
1753 $person = self::personByHandle($author);
1755 $parts = parse_url($person['url']);
1756 unset($parts['path']);
1757 $host_url = Network::unparseURL($parts);
1759 return $host_url . '/objects/' . $guid;
1766 * Fetch the guid from our database with a given uri
1768 * @param string $uri Message uri
1769 * @param string $uid Author handle
1771 * @return string The post guid
1772 * @throws \Exception
1774 private static function getGuidFromUri($uri, $uid)
1776 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1777 if (DBA::isResult($item)) {
1778 return $item["guid"];
1785 * Find the best importer for a comment, like, ...
1787 * @param string $guid The guid of the item
1789 * @return array|boolean the origin owner of that post - or false
1790 * @throws \Exception
1792 private static function importerForGuid($guid)
1794 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1795 if (DBA::isResult($item)) {
1796 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1797 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1798 if (DBA::isResult($contact)) {
1806 * Store the mentions in the tag table
1808 * @param integer $uriid
1809 * @param string $text
1811 private static function storeMentions(int $uriid, string $text)
1813 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1814 if (empty($matches)) {
1819 * Matching values for the preg match
1820 * [1] = mention type (@ or !)
1821 * [2] = name (optional)
1825 foreach ($matches as $match) {
1826 if (empty($match)) {
1830 $person = self::personByHandle($match[3]);
1831 if (empty($person)) {
1835 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1840 * Processes an incoming comment
1842 * @param array $importer Array of the importer user
1843 * @param string $sender The sender of the message
1844 * @param object $data The message object
1845 * @param string $xml The original XML of the message
1847 * @return int The message id of the generated comment or "false" if there was an error
1848 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1849 * @throws \ImagickException
1851 private static function receiveComment(array $importer, $sender, $data, $xml)
1853 $author = Strings::escapeTags(XML::unescape($data->author));
1854 $guid = Strings::escapeTags(XML::unescape($data->guid));
1855 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1856 $text = XML::unescape($data->text);
1858 if (isset($data->created_at)) {
1859 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1861 $created_at = DateTimeFormat::utcNow();
1864 if (isset($data->thread_parent_guid)) {
1865 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1866 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1871 $contact = self::allowedContactByHandle($importer, $sender, true);
1876 $message_id = self::messageExists($importer["uid"], $guid);
1881 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1882 if (!$parent_item) {
1886 $person = self::personByHandle($author);
1887 if (!is_array($person)) {
1888 Logger::log("unable to find author details");
1892 // Fetch the contact id - if we know this contact
1893 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1897 $datarray["uid"] = $importer["uid"];
1898 $datarray["contact-id"] = $author_contact["cid"];
1899 $datarray["network"] = $author_contact["network"];
1901 $datarray["author-link"] = $person["url"];
1902 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1904 $datarray["owner-link"] = $contact["url"];
1905 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1907 $datarray["guid"] = $guid;
1908 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1909 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1911 $datarray["verb"] = Activity::POST;
1912 $datarray["gravity"] = GRAVITY_COMMENT;
1914 if ($thr_uri != "") {
1915 $datarray["parent-uri"] = $thr_uri;
1917 $datarray["parent-uri"] = $parent_item["uri"];
1920 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1922 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1923 $datarray["source"] = $xml;
1925 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1927 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1928 $body = Markdown::toBBCode($text);
1930 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1932 self::storeMentions($datarray['uri-id'], $text);
1933 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
1935 self::fetchGuid($datarray);
1937 // If we are the origin of the parent we store the original data.
1938 // We notify our followers during the item storage.
1939 if ($parent_item["origin"]) {
1940 $datarray['diaspora_signed_text'] = json_encode($data);
1943 $message_id = Item::insert($datarray);
1945 if ($message_id <= 0) {
1950 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1951 if ($datarray['uid'] == 0) {
1952 Item::distribute($message_id, json_encode($data));
1960 * processes and stores private messages
1962 * @param array $importer Array of the importer user
1963 * @param array $contact The contact of the message
1964 * @param object $data The message object
1965 * @param array $msg Array of the processed message, author handle and key
1966 * @param object $mesg The private message
1967 * @param array $conversation The conversation record to which this message belongs
1969 * @return bool "true" if it was successful
1970 * @throws \Exception
1972 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1974 $author = Strings::escapeTags(XML::unescape($data->author));
1975 $guid = Strings::escapeTags(XML::unescape($data->guid));
1976 $subject = Strings::escapeTags(XML::unescape($data->subject));
1978 // "diaspora_handle" is the element name from the old version
1979 // "author" is the element name from the new version
1980 if ($mesg->author) {
1981 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1982 } elseif ($mesg->diaspora_handle) {
1983 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1988 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1989 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1990 $msg_text = XML::unescape($mesg->text);
1991 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1993 if ($msg_conversation_guid != $guid) {
1994 Logger::log("message conversation guid does not belong to the current conversation.");
1998 $body = Markdown::toBBCode($msg_text);
1999 $message_uri = $msg_author.":".$msg_guid;
2001 $person = self::personByHandle($msg_author);
2003 return Mail::insert([
2004 'uid' => $importer['uid'],
2005 'guid' => $msg_guid,
2006 'convid' => $conversation['id'],
2007 'from-name' => $person['name'],
2008 'from-photo' => $person['photo'],
2009 'from-url' => $person['url'],
2010 'contact-id' => $contact['id'],
2011 'title' => $subject,
2013 'uri' => $message_uri,
2014 'parent-uri' => $author . ':' . $guid,
2015 'created' => $msg_created_at
2020 * Processes new private messages (answers to private messages are processed elsewhere)
2022 * @param array $importer Array of the importer user
2023 * @param array $msg Array of the processed message, author handle and key
2024 * @param object $data The message object
2026 * @return bool Success
2027 * @throws \Exception
2029 private static function receiveConversation(array $importer, $msg, $data)
2031 $author = Strings::escapeTags(XML::unescape($data->author));
2032 $guid = Strings::escapeTags(XML::unescape($data->guid));
2033 $subject = Strings::escapeTags(XML::unescape($data->subject));
2034 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2035 $participants = Strings::escapeTags(XML::unescape($data->participants));
2037 $messages = $data->message;
2039 if (!count($messages)) {
2040 Logger::log("empty conversation");
2044 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
2049 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2050 if (!DBA::isResult($conversation)) {
2052 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
2053 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
2054 intval($importer["uid"]),
2056 DBA::escape($author),
2057 DBA::escape($created_at),
2058 DBA::escape(DateTimeFormat::utcNow()),
2059 DBA::escape($subject),
2060 DBA::escape($participants)
2063 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2066 if (!$conversation) {
2067 Logger::log("unable to create conversation.");
2071 foreach ($messages as $mesg) {
2072 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
2079 * Processes "like" messages
2081 * @param array $importer Array of the importer user
2082 * @param string $sender The sender of the message
2083 * @param object $data The message object
2085 * @return int The message id of the generated like or "false" if there was an error
2086 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2087 * @throws \ImagickException
2089 private static function receiveLike(array $importer, $sender, $data)
2091 $author = Strings::escapeTags(XML::unescape($data->author));
2092 $guid = Strings::escapeTags(XML::unescape($data->guid));
2093 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2094 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
2095 $positive = Strings::escapeTags(XML::unescape($data->positive));
2097 // likes on comments aren't supported by Diaspora - only on posts
2098 // But maybe this will be supported in the future, so we will accept it.
2099 if (!in_array($parent_type, ["Post", "Comment"])) {
2103 $contact = self::allowedContactByHandle($importer, $sender, true);
2108 $message_id = self::messageExists($importer["uid"], $guid);
2113 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2114 if (!$parent_item) {
2118 $person = self::personByHandle($author);
2119 if (!is_array($person)) {
2120 Logger::log("unable to find author details");
2124 // Fetch the contact id - if we know this contact
2125 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2127 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2128 // We would accept this anyhow.
2129 if ($positive == "true") {
2130 $verb = Activity::LIKE;
2132 $verb = Activity::DISLIKE;
2137 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2139 $datarray["uid"] = $importer["uid"];
2140 $datarray["contact-id"] = $author_contact["cid"];
2141 $datarray["network"] = $author_contact["network"];
2143 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2144 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2146 $datarray["guid"] = $guid;
2147 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2149 $datarray["verb"] = $verb;
2150 $datarray["gravity"] = GRAVITY_ACTIVITY;
2151 $datarray["parent-uri"] = $parent_item["uri"];
2153 $datarray["object-type"] = Activity\ObjectType::NOTE;
2155 $datarray["body"] = $verb;
2157 // Diaspora doesn't provide a date for likes
2158 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2160 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2161 if ($parent_item["id"] != $parent_item["parent"]) {
2162 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
2163 $origin = $toplevel["origin"];
2165 $origin = $parent_item["origin"];
2168 // If we are the origin of the parent we store the original data.
2169 // We notify our followers during the item storage.
2171 $datarray['diaspora_signed_text'] = json_encode($data);
2174 $message_id = Item::insert($datarray);
2176 if ($message_id <= 0) {
2181 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2182 if ($datarray['uid'] == 0) {
2183 Item::distribute($message_id, json_encode($data));
2191 * Processes private messages
2193 * @param array $importer Array of the importer user
2194 * @param object $data The message object
2196 * @return bool Success?
2197 * @throws \Exception
2199 private static function receiveMessage(array $importer, $data)
2201 $author = Strings::escapeTags(XML::unescape($data->author));
2202 $guid = Strings::escapeTags(XML::unescape($data->guid));
2203 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2204 $text = XML::unescape($data->text);
2205 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2207 $contact = self::allowedContactByHandle($importer, $author, true);
2212 $conversation = null;
2214 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2215 $conversation = DBA::selectFirst('conv', [], $condition);
2217 if (!DBA::isResult($conversation)) {
2218 Logger::log("conversation not available.");
2222 $message_uri = $author.":".$guid;
2224 $person = self::personByHandle($author);
2226 Logger::log("unable to find author details");
2230 $body = Markdown::toBBCode($text);
2232 $body = self::replacePeopleGuid($body, $person["url"]);
2234 return Mail::insert([
2235 'uid' => $importer['uid'],
2237 'convid' => $conversation['id'],
2238 'from-name' => $person['name'],
2239 'from-photo' => $person['photo'],
2240 'from-url' => $person['url'],
2241 'contact-id' => $contact['id'],
2242 'title' => $conversation['subject'],
2245 'uri' => $message_uri,
2246 'parent-uri' => $author.":".$conversation['guid'],
2247 'created' => $created_at
2252 * Processes participations - unsupported by now
2254 * @param array $importer Array of the importer user
2255 * @param object $data The message object
2257 * @return bool always true
2258 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2259 * @throws \ImagickException
2261 private static function receiveParticipation(array $importer, $data)
2263 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2264 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2266 $contact_id = Contact::getIdForURL($author);
2268 Logger::log('Contact not found: '.$author);
2272 $person = self::personByHandle($author);
2273 if (!is_array($person)) {
2274 Logger::log("Person not found: ".$author);
2278 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2279 if (!DBA::isResult($item)) {
2280 Logger::log('Item not found, no origin or private: '.$parent_guid);
2284 $author_parts = explode('@', $author);
2285 if (isset($author_parts[1])) {
2286 $server = $author_parts[1];
2288 // Should never happen
2292 Logger::log('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, Logger::DEBUG);
2294 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2295 DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2298 // Send all existing comments and likes to the requesting server
2299 $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2300 while ($comment = Item::fetch($comments)) {
2301 if ($comment['id'] == $comment['parent']) {
2305 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $contact_id]);
2306 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $contact_id)) {
2307 ItemDeliveryData::incrementQueueCount($comment['id'], 1);
2310 DBA::close($comments);
2316 * Processes photos - unneeded
2318 * @param array $importer Array of the importer user
2319 * @param object $data The message object
2321 * @return bool always true
2323 private static function receivePhoto(array $importer, $data)
2325 // There doesn't seem to be a reason for this function,
2326 // since the photo data is transmitted in the status message as well
2331 * Processes poll participations - unssupported
2333 * @param array $importer Array of the importer user
2334 * @param object $data The message object
2336 * @return bool always true
2338 private static function receivePollParticipation(array $importer, $data)
2340 // We don't support polls by now
2345 * Processes incoming profile updates
2347 * @param array $importer Array of the importer user
2348 * @param object $data The message object
2350 * @return bool Success
2351 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2352 * @throws \ImagickException
2354 private static function receiveProfile(array $importer, $data)
2356 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2358 $contact = self::contactByHandle($importer["uid"], $author);
2363 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2364 $image_url = XML::unescape($data->image_url);
2365 $birthday = XML::unescape($data->birthday);
2366 $about = Markdown::toBBCode(XML::unescape($data->bio));
2367 $location = Markdown::toBBCode(XML::unescape($data->location));
2368 $searchable = (XML::unescape($data->searchable) == "true");
2369 $nsfw = (XML::unescape($data->nsfw) == "true");
2370 $tags = XML::unescape($data->tag_string);
2372 $tags = explode("#", $tags);
2375 foreach ($tags as $tag) {
2376 $tag = trim(strtolower($tag));
2382 $keywords = implode(", ", $keywords);
2384 $handle_parts = explode("@", $author);
2385 $nick = $handle_parts[0];
2388 $name = $handle_parts[0];
2391 if (preg_match("|^https?://|", $image_url) === 0) {
2392 $image_url = "http://".$handle_parts[1].$image_url;
2395 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2397 // Generic birthday. We don't know the timezone. The year is irrelevant.
2399 $birthday = str_replace("1000", "1901", $birthday);
2401 if ($birthday != "") {
2402 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2405 // this is to prevent multiple birthday notifications in a single year
2406 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2408 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2409 $birthday = $contact["bd"];
2412 $fields = ['name' => $name, 'location' => $location,
2413 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2414 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2415 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2417 if (!empty($birthday)) {
2418 $fields['bd'] = $birthday;
2421 DBA::update('contact', $fields, ['id' => $contact['id']]);
2423 // @todo Update the public contact, then update the gcontact from that
2425 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2426 "photo" => $image_url, "name" => $name, "location" => $location,
2427 "about" => $about, "birthday" => $birthday,
2428 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2429 "hide" => !$searchable, "nsfw" => $nsfw];
2431 $gcid = GContact::update($gcontact);
2433 GContact::link($gcid, $importer["uid"], $contact["id"]);
2435 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2441 * Processes incoming friend requests
2443 * @param array $importer Array of the importer user
2444 * @param array $contact The contact that send the request
2446 * @throws \Exception
2448 private static function receiveRequestMakeFriend(array $importer, array $contact)
2450 if ($contact["rel"] == Contact::SHARING) {
2453 ['rel' => Contact::FRIEND, 'writable' => true],
2454 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2460 * Processes incoming sharing notification
2462 * @param array $importer Array of the importer user
2463 * @param object $data The message object
2465 * @return bool Success
2466 * @throws \Exception
2468 private static function receiveContactRequest(array $importer, $data)
2470 $author = XML::unescape($data->author);
2471 $recipient = XML::unescape($data->recipient);
2473 if (!$author || !$recipient) {
2477 // the current protocol version doesn't know these fields
2478 // That means that we will assume their existance
2479 if (isset($data->following)) {
2480 $following = (XML::unescape($data->following) == "true");
2485 if (isset($data->sharing)) {
2486 $sharing = (XML::unescape($data->sharing) == "true");
2491 $contact = self::contactByHandle($importer["uid"], $author);
2493 // perhaps we were already sharing with this person. Now they're sharing with us.
2494 // That makes us friends.
2497 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2498 self::receiveRequestMakeFriend($importer, $contact);
2500 // refetch the contact array
2501 $contact = self::contactByHandle($importer["uid"], $author);
2503 // If we are now friends, we are sending a share message.
2504 // Normally we needn't to do so, but the first message could have been vanished.
2505 if (in_array($contact["rel"], [Contact::FRIEND])) {
2506 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2507 if (DBA::isResult($user)) {
2508 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2509 self::sendShare($user, $contact);
2514 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2515 Contact::removeFollower($importer, $contact);
2520 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2521 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2523 } elseif (!$following && !$sharing) {
2524 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2526 } elseif (!$following && $sharing) {
2527 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2528 } elseif ($following && $sharing) {
2529 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2530 } elseif ($following && !$sharing) {
2531 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2534 $ret = self::personByHandle($author);
2536 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2537 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2541 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2543 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2548 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2549 'author-link' => $ret['url']];
2551 $result = Contact::addRelationship($importer, $contact, $item, false);
2552 if ($result === true) {
2553 $contact_record = self::contactByHandle($importer['uid'], $author);
2554 if (!$contact_record) {
2555 Logger::info('unable to locate newly created contact record.');
2559 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2560 if (DBA::isResult($user)) {
2561 self::sendShare($user, $contact_record);
2563 // Send the profile data, maybe it weren't transmitted before
2564 self::sendProfile($importer['uid'], [$contact_record]);
2572 * Fetches a message with a given guid
2574 * @param string $guid message guid
2575 * @param string $orig_author handle of the original post
2576 * @return array The fetched item
2577 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2578 * @throws \ImagickException
2580 public static function originalItem($guid, $orig_author)
2583 Logger::log('Empty guid. Quitting.');
2587 // Do we already have this item?
2588 $fields = ['body', 'title', 'attach', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2589 'author-name', 'author-link', 'author-avatar'];
2590 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2591 $item = Item::selectFirst($fields, $condition);
2593 if (DBA::isResult($item)) {
2594 Logger::log("reshared message ".$guid." already exists on system.");
2596 // Maybe it is already a reshared item?
2597 // Then refetch the content, if it is a reshare from a reshare.
2598 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2599 if (self::isReshare($item["body"], true)) {
2601 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2602 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2604 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2606 // Add OEmbed and other information to the body
2607 $item["body"] = add_page_info_to_body($item["body"], false, true);
2615 if (!DBA::isResult($item)) {
2616 if (empty($orig_author)) {
2617 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2621 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2622 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2623 $stored = self::storeByGuid($guid, $server);
2626 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2627 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2628 $stored = self::storeByGuid($guid, $server);
2632 $fields = ['body', 'title', 'attach', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2633 'author-name', 'author-link', 'author-avatar'];
2634 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2635 $item = Item::selectFirst($fields, $condition);
2637 if (DBA::isResult($item)) {
2638 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2639 if (self::isReshare($item["body"], false)) {
2640 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2641 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2652 * Stores a reshare activity
2654 * @param array $item Array of reshare post
2655 * @param integer $parent_message_id Id of the parent post
2656 * @param string $guid GUID string of reshare action
2657 * @param string $author Author handle
2659 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2661 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2665 $datarray['uid'] = $item['uid'];
2666 $datarray['contact-id'] = $item['contact-id'];
2667 $datarray['network'] = $item['network'];
2669 $datarray['author-link'] = $item['author-link'];
2670 $datarray['author-id'] = $item['author-id'];
2672 $datarray['owner-link'] = $datarray['author-link'];
2673 $datarray['owner-id'] = $datarray['author-id'];
2675 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2676 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2677 $datarray['parent-uri'] = $parent['uri'];
2679 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2680 $datarray['gravity'] = GRAVITY_ACTIVITY;
2681 $datarray['object-type'] = Activity\ObjectType::NOTE;
2683 $datarray['protocol'] = $item['protocol'];
2685 $datarray['plink'] = self::plink($author, $datarray['guid']);
2686 $datarray['private'] = $item['private'];
2687 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2689 $message_id = Item::insert($datarray);
2692 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2693 if ($datarray['uid'] == 0) {
2694 Item::distribute($message_id);
2700 * Processes a reshare message
2702 * @param array $importer Array of the importer user
2703 * @param object $data The message object
2704 * @param string $xml The original XML of the message
2706 * @return int the message id
2707 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2708 * @throws \ImagickException
2710 private static function receiveReshare(array $importer, $data, $xml)
2712 $author = Strings::escapeTags(XML::unescape($data->author));
2713 $guid = Strings::escapeTags(XML::unescape($data->guid));
2714 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2715 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2716 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2717 /// @todo handle unprocessed property "provider_display_name"
2718 $public = Strings::escapeTags(XML::unescape($data->public));
2720 $contact = self::allowedContactByHandle($importer, $author, false);
2725 $message_id = self::messageExists($importer["uid"], $guid);
2730 $original_item = self::originalItem($root_guid, $root_author);
2731 if (!$original_item) {
2735 $orig_url = DI::baseUrl()."/display/".$original_item["guid"];
2739 $datarray["uid"] = $importer["uid"];
2740 $datarray["contact-id"] = $contact["id"];
2741 $datarray["network"] = Protocol::DIASPORA;
2743 $datarray["author-link"] = $contact["url"];
2744 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2746 $datarray["owner-link"] = $datarray["author-link"];
2747 $datarray["owner-id"] = $datarray["author-id"];
2749 $datarray["guid"] = $guid;
2750 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2751 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2753 $datarray["verb"] = Activity::POST;
2754 $datarray["gravity"] = GRAVITY_PARENT;
2756 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2757 $datarray["source"] = $xml;
2759 /// @todo Copy tag data from original post
2761 $prefix = share_header(
2762 $original_item["author-name"],
2763 $original_item["author-link"],
2764 $original_item["author-avatar"],
2765 $original_item["guid"],
2766 $original_item["created"],
2770 if (!empty($original_item['title'])) {
2771 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2774 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2776 Tag::storeFromBody($datarray['uri-id'], $datarray["body"]);
2778 $datarray["tag"] = $original_item["tag"];
2779 $datarray["attach"] = $original_item["attach"];
2780 $datarray["app"] = $original_item["app"];
2782 $datarray["plink"] = self::plink($author, $guid);
2783 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2784 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2786 $datarray["object-type"] = $original_item["object-type"];
2788 self::fetchGuid($datarray);
2789 $message_id = Item::insert($datarray);
2791 self::sendParticipation($contact, $datarray);
2793 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2794 if ($root_message_id) {
2795 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2799 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2800 if ($datarray['uid'] == 0) {
2801 Item::distribute($message_id);
2810 * Processes retractions
2812 * @param array $importer Array of the importer user
2813 * @param array $contact The contact of the item owner
2814 * @param object $data The message object
2816 * @return bool success
2817 * @throws \Exception
2819 private static function itemRetraction(array $importer, array $contact, $data)
2821 $author = Strings::escapeTags(XML::unescape($data->author));
2822 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2823 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2825 $person = self::personByHandle($author);
2826 if (!is_array($person)) {
2827 Logger::log("unable to find author detail for ".$author);
2831 if (empty($contact["url"])) {
2832 $contact["url"] = $person["url"];
2835 // Fetch items that are about to be deleted
2836 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2838 // When we receive a public retraction, we delete every item that we find.
2839 if ($importer['uid'] == 0) {
2840 $condition = ['guid' => $target_guid, 'deleted' => false];
2842 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2845 $r = Item::select($fields, $condition);
2846 if (!DBA::isResult($r)) {
2847 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2851 while ($item = Item::fetch($r)) {
2852 if (strstr($item['file'], '[')) {
2853 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2857 // Fetch the parent item
2858 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2860 // Only delete it if the parent author really fits
2861 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2862 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2866 Item::markForDeletion(['id' => $item['id']]);
2868 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], Logger::DEBUG);
2875 * Receives retraction messages
2877 * @param array $importer Array of the importer user
2878 * @param string $sender The sender of the message
2879 * @param object $data The message object
2881 * @return bool Success
2882 * @throws \Exception
2884 private static function receiveRetraction(array $importer, $sender, $data)
2886 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2888 $contact = self::contactByHandle($importer["uid"], $sender);
2889 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2890 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2898 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2900 switch ($target_type) {
2905 case "StatusMessage":
2906 return self::itemRetraction($importer, $contact, $data);
2908 case "PollParticipation":
2910 // Currently unsupported
2914 Logger::log("Unknown target type ".$target_type);
2921 * Receives status messages
2923 * @param array $importer Array of the importer user
2924 * @param SimpleXMLElement $data The message object
2925 * @param string $xml The original XML of the message
2927 * @return int The message id of the newly created item
2928 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2929 * @throws \ImagickException
2931 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2933 $author = Strings::escapeTags(XML::unescape($data->author));
2934 $guid = Strings::escapeTags(XML::unescape($data->guid));
2935 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2936 $public = Strings::escapeTags(XML::unescape($data->public));
2937 $text = XML::unescape($data->text);
2938 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2940 $contact = self::allowedContactByHandle($importer, $author, false);
2945 $message_id = self::messageExists($importer["uid"], $guid);
2951 if ($data->location) {
2952 foreach ($data->location->children() as $fieldname => $data) {
2953 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2957 $body = Markdown::toBBCode($text);
2961 // Attach embedded pictures to the body
2963 foreach ($data->photo as $photo) {
2964 $body = "[img]".XML::unescape($photo->remote_photo_path).
2965 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2968 $datarray["object-type"] = Activity\ObjectType::IMAGE;
2970 $datarray["object-type"] = Activity\ObjectType::NOTE;
2972 // Add OEmbed and other information to the body
2973 if (!self::isHubzilla($contact["url"])) {
2974 $body = add_page_info_to_body($body, false, true);
2978 /// @todo enable support for polls
2979 //if ($data->poll) {
2980 // foreach ($data->poll AS $poll)
2985 /// @todo enable support for events
2987 $datarray["uid"] = $importer["uid"];
2988 $datarray["contact-id"] = $contact["id"];
2989 $datarray["network"] = Protocol::DIASPORA;
2991 $datarray["author-link"] = $contact["url"];
2992 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2994 $datarray["owner-link"] = $datarray["author-link"];
2995 $datarray["owner-id"] = $datarray["author-id"];
2997 $datarray["guid"] = $guid;
2998 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2999 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
3001 $datarray["verb"] = Activity::POST;
3002 $datarray["gravity"] = GRAVITY_PARENT;
3004 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
3005 $datarray["source"] = $xml;
3007 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3009 self::storeMentions($datarray['uri-id'], $text);
3010 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
3012 if ($provider_display_name != "") {
3013 $datarray["app"] = $provider_display_name;
3016 $datarray["plink"] = self::plink($author, $guid);
3017 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
3018 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3020 if (isset($address["address"])) {
3021 $datarray["location"] = $address["address"];
3024 if (isset($address["lat"]) && isset($address["lng"])) {
3025 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3028 self::fetchGuid($datarray);
3029 $message_id = Item::insert($datarray);
3031 self::sendParticipation($contact, $datarray);
3034 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
3035 if ($datarray['uid'] == 0) {
3036 Item::distribute($message_id);
3044 /* ************************************************************************************** *
3045 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3046 * ************************************************************************************** */
3049 * returnes the handle of a contact
3051 * @param array $contact contact array
3053 * @return string the handle in the format user@domain.tld
3054 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3056 private static function myHandle(array $contact)
3058 if (!empty($contact["addr"])) {
3059 return $contact["addr"];
3062 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3063 // So - just in case - we build the the address here.
3064 if ($contact["nickname"] != "") {
3065 $nick = $contact["nickname"];
3067 $nick = $contact["nick"];
3070 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
3075 * Creates the data for a private message in the new format
3077 * @param string $msg The message that is to be transmitted
3078 * @param array $user The record of the sender
3079 * @param array $contact Target of the communication
3080 * @param string $prvkey The private key of the sender
3081 * @param string $pubkey The public key of the receiver
3083 * @return string The encrypted data
3084 * @throws \Exception
3086 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
3088 Logger::log("Message: ".$msg, Logger::DATA);
3090 // without a public key nothing will work
3092 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3096 $aes_key = openssl_random_pseudo_bytes(32);
3097 $b_aes_key = base64_encode($aes_key);
3098 $iv = openssl_random_pseudo_bytes(16);
3099 $b_iv = base64_encode($iv);
3101 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3103 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3105 $encrypted_key_bundle = "";
3106 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3108 $json_object = json_encode(
3109 ["aes_key" => base64_encode($encrypted_key_bundle),
3110 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3113 return $json_object;
3117 * Creates the envelope for the "fetch" endpoint and for the new format
3119 * @param string $msg The message that is to be transmitted
3120 * @param array $user The record of the sender
3122 * @return string The envelope
3123 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3125 public static function buildMagicEnvelope($msg, array $user)
3127 $b64url_data = Strings::base64UrlEncode($msg);
3128 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3130 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3131 $type = "application/xml";
3132 $encoding = "base64url";
3133 $alg = "RSA-SHA256";
3134 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3136 // Fallback if the private key wasn't transmitted in the expected field
3137 if ($user['uprvkey'] == "") {
3138 $user['uprvkey'] = $user['prvkey'];
3141 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3142 $sig = Strings::base64UrlEncode($signature);
3144 $xmldata = ["me:env" => ["me:data" => $data,
3145 "@attributes" => ["type" => $type],
3146 "me:encoding" => $encoding,
3149 "@attributes2" => ["key_id" => $key_id]]];
3151 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3153 return XML::fromArray($xmldata, $xml, false, $namespaces);
3157 * Create the envelope for a message
3159 * @param string $msg The message that is to be transmitted
3160 * @param array $user The record of the sender
3161 * @param array $contact Target of the communication
3162 * @param string $prvkey The private key of the sender
3163 * @param string $pubkey The public key of the receiver
3164 * @param bool $public Is the message public?
3166 * @return string The message that will be transmitted to other servers
3167 * @throws \Exception
3169 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3171 // The message is put into an envelope with the sender's signature
3172 $envelope = self::buildMagicEnvelope($msg, $user);
3174 // Private messages are put into a second envelope, encrypted with the receivers public key
3176 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3183 * Creates a signature for a message
3185 * @param array $owner the array of the owner of the message
3186 * @param array $message The message that is to be signed
3188 * @return string The signature
3190 private static function signature($owner, $message)
3193 unset($sigmsg["author_signature"]);
3194 unset($sigmsg["parent_author_signature"]);
3196 $signed_text = implode(";", $sigmsg);
3198 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3202 * Transmit a message to a target server
3204 * @param array $owner the array of the item owner
3205 * @param array $contact Target of the communication
3206 * @param string $envelope The message that is to be transmitted
3207 * @param bool $public_batch Is it a public post?
3208 * @param string $guid message guid
3210 * @return int Result of the transmission
3211 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3212 * @throws \ImagickException
3214 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3216 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
3221 $logid = Strings::getRandomHex(4);
3223 // We always try to use the data from the fcontact table.
3224 // This is important for transmitting data to Friendica servers.
3225 if (!empty($contact['addr'])) {
3226 $fcontact = self::personByHandle($contact['addr']);
3227 if (!empty($fcontact)) {
3228 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3232 if (empty($dest_url)) {
3233 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3237 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3241 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3243 if (!intval(DI::config()->get("system", "diaspora_test"))) {
3244 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3246 $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3247 $return_code = $postResult->getReturnCode();
3249 Logger::log("test_mode");
3253 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3255 return $return_code ? $return_code : -1;
3260 * Build the post xml
3262 * @param string $type The message type
3263 * @param array $message The message data
3265 * @return string The post XML
3267 public static function buildPostXml($type, $message)
3269 $data = [$type => $message];
3271 return XML::fromArray($data, $xml);
3275 * Builds and transmit messages
3277 * @param array $owner the array of the item owner
3278 * @param array $contact Target of the communication
3279 * @param string $type The message type
3280 * @param array $message The message data
3281 * @param bool $public_batch Is it a public post?
3282 * @param string $guid message guid
3284 * @return int Result of the transmission
3285 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3286 * @throws \ImagickException
3288 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3290 $msg = self::buildPostXml($type, $message);
3292 Logger::log('message: '.$msg, Logger::DATA);
3293 Logger::log('send guid '.$guid, Logger::DEBUG);
3295 // Fallback if the private key wasn't transmitted in the expected field
3296 if (empty($owner['uprvkey'])) {
3297 $owner['uprvkey'] = $owner['prvkey'];
3300 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3302 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3304 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3306 return $return_code;
3310 * sends a participation (Used to get all further updates)
3312 * @param array $contact Target of the communication
3313 * @param array $item Item array
3315 * @return int The result of the transmission
3316 * @throws \Exception
3318 private static function sendParticipation(array $contact, array $item)
3320 // Don't send notifications for private postings
3321 if ($item['private'] == Item::PRIVATE) {
3325 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3327 $result = DI::cache()->get($cachekey);
3328 if (!is_null($result)) {
3332 // Fetch some user id to have a valid handle to transmit the participation.
3333 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3334 // If the item belongs to a user, we take this user id.
3335 if ($item['uid'] == 0) {
3336 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3337 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3338 $owner = User::getOwnerDataById($first_user['uid']);
3340 $owner = User::getOwnerDataById($item['uid']);
3343 $author = self::myHandle($owner);
3345 $message = ["author" => $author,
3346 "guid" => System::createUUID(),
3347 "parent_type" => "Post",
3348 "parent_guid" => $item["guid"]];
3350 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3352 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3353 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3355 return self::buildAndTransmit($owner, $contact, "participation", $message);
3359 * sends an account migration
3361 * @param array $owner the array of the item owner
3362 * @param array $contact Target of the communication
3363 * @param int $uid User ID
3365 * @return int The result of the transmission
3366 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3367 * @throws \ImagickException
3369 public static function sendAccountMigration(array $owner, array $contact, $uid)
3371 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3372 $profile = self::createProfileData($uid);
3374 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3375 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3377 $message = ["author" => $old_handle,
3378 "profile" => $profile,
3379 "signature" => $signature];
3381 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3383 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3387 * Sends a "share" message
3389 * @param array $owner the array of the item owner
3390 * @param array $contact Target of the communication
3392 * @return int The result of the transmission
3393 * @throws \Exception
3395 public static function sendShare(array $owner, array $contact)
3398 * @todo support the different possible combinations of "following" and "sharing"
3399 * Currently, Diaspora only interprets the "sharing" field
3401 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3405 switch ($contact["rel"]) {
3406 case Contact::FRIEND:
3410 case Contact::SHARING:
3414 case Contact::FOLLOWER:
3420 $message = ["author" => self::myHandle($owner),
3421 "recipient" => $contact["addr"],
3422 "following" => "true",
3423 "sharing" => "true"];
3425 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3427 return self::buildAndTransmit($owner, $contact, "contact", $message);
3431 * sends an "unshare"
3433 * @param array $owner the array of the item owner
3434 * @param array $contact Target of the communication
3436 * @return int The result of the transmission
3437 * @throws \Exception
3439 public static function sendUnshare(array $owner, array $contact)
3441 $message = ["author" => self::myHandle($owner),
3442 "recipient" => $contact["addr"],
3443 "following" => "false",
3444 "sharing" => "false"];
3446 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3448 return self::buildAndTransmit($owner, $contact, "contact", $message);
3452 * Checks a message body if it is a reshare
3454 * @param string $body The message body that is to be check
3455 * @param bool $complete Should it be a complete check or a simple check?
3457 * @return array|bool Reshare details or "false" if no reshare
3458 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3459 * @throws \ImagickException
3461 public static function isReshare($body, $complete = true)
3463 $body = trim($body);
3465 $reshared = Item::getShareArray(['body' => $body]);
3466 if (empty($reshared)) {
3470 // Skip if it isn't a pure repeated messages
3471 // Does it start with a share?
3472 if (!empty($reshared['comment']) && $complete) {
3476 if (!empty($reshared['guid']) && $complete) {
3477 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3478 $item = Item::selectFirst(['contact-id'], $condition);
3479 if (DBA::isResult($item)) {
3481 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3482 $ret["root_guid"] = $reshared['guid'];
3484 } elseif ($complete) {
3485 // We are resharing something that isn't a DFRN or Diaspora post.
3486 // So we have to return "false" on "$complete" to not trigger a reshare.
3489 } elseif (empty($reshared['guid']) && $complete) {
3495 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3496 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3497 if (!empty($contact['addr'])) {
3498 $ret['root_handle'] = $contact['addr'];
3502 if (empty($ret) && !$complete) {
3510 * Create an event array
3512 * @param integer $event_id The id of the event
3514 * @return array with event data
3515 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3517 private static function buildEvent($event_id)
3519 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3520 if (!DBA::isResult($r)) {
3528 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3529 if (!DBA::isResult($r)) {
3535 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3536 if (!DBA::isResult($r)) {
3542 $eventdata['author'] = self::myHandle($owner);
3544 if ($event['guid']) {
3545 $eventdata['guid'] = $event['guid'];
3548 $mask = DateTimeFormat::ATOM;
3550 /// @todo - establish "all day" events in Friendica
3551 $eventdata["all_day"] = "false";
3553 $eventdata['timezone'] = 'UTC';
3554 if (!$event['adjust'] && $user['timezone']) {
3555 $eventdata['timezone'] = $user['timezone'];
3558 if ($event['start']) {
3559 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3561 if ($event['finish'] && !$event['nofinish']) {
3562 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3564 if ($event['summary']) {
3565 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3567 if ($event['desc']) {
3568 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3570 if ($event['location']) {
3571 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3572 $coord = Map::getCoordinates($event['location']);
3575 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3576 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3577 $location["lat"] = $coord['lat'];
3578 $location["lng"] = $coord['lon'];
3580 $location["lat"] = 0;
3581 $location["lng"] = 0;
3583 $eventdata['location'] = $location;
3590 * Create a post (status message or reshare)
3592 * @param array $item The item that will be exported
3593 * @param array $owner the array of the item owner
3596 * 'type' -> Message type ("status_message" or "reshare")
3597 * 'message' -> Array of XML elements of the status
3598 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3599 * @throws \ImagickException
3601 public static function buildStatus(array $item, array $owner)
3603 $cachekey = "diaspora:buildStatus:".$item['guid'];
3605 $result = DI::cache()->get($cachekey);
3606 if (!is_null($result)) {
3610 $myaddr = self::myHandle($owner);
3612 $public = ($item["private"] == Item::PRIVATE ? "false" : "true");
3613 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3614 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3616 // Detect a share element and do a reshare
3617 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) {
3618 $message = ["author" => $myaddr,
3619 "guid" => $item["guid"],
3620 "created_at" => $created,
3621 "root_author" => $ret["root_handle"],
3622 "root_guid" => $ret["root_guid"],
3623 "provider_display_name" => $item["app"],
3624 "public" => $public];
3628 $title = $item["title"];
3629 $body = $item["body"];
3631 // Fetch the title from an attached link - if there is one
3632 if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3633 $page_data = BBCode::getAttachmentData($item['body']);
3634 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3635 $title = $page_data['title'];
3639 if ($item['author-link'] != $item['owner-link']) {
3640 require_once 'mod/share.php';
3641 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3642 "", $item['created'], $item['plink']) . $body . '[/share]';
3645 // convert to markdown
3646 $body = html_entity_decode(BBCode::toMarkdown($body));
3649 if (strlen($title)) {
3650 $body = "### ".html_entity_decode($title)."\n\n".$body;
3653 if ($item["attach"]) {
3654 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3656 $body .= "\n".DI::l10n()->t("Attachments:")."\n";
3657 foreach ($matches as $mtch) {
3658 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3665 if ($item["location"] != "")
3666 $location["address"] = $item["location"];
3668 if ($item["coord"] != "") {
3669 $coord = explode(" ", $item["coord"]);
3670 $location["lat"] = $coord[0];
3671 $location["lng"] = $coord[1];
3674 $message = ["author" => $myaddr,
3675 "guid" => $item["guid"],
3676 "created_at" => $created,
3677 "edited_at" => $edited,
3678 "public" => $public,
3680 "provider_display_name" => $item["app"],
3681 "location" => $location];
3683 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3684 if (!isset($location["lat"]) || !isset($location["lng"])) {
3685 unset($message["location"]);
3688 if ($item['event-id'] > 0) {
3689 $event = self::buildEvent($item['event-id']);
3690 if (count($event)) {
3691 $message['event'] = $event;
3693 if (!empty($event['location']['address']) &&
3694 !empty($event['location']['lat']) &&
3695 !empty($event['location']['lng'])) {
3696 $message['location'] = $event['location'];
3699 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3700 // $message['text'] = '';
3704 $type = "status_message";
3707 $msg = ["type" => $type, "message" => $message];
3709 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3714 private static function prependParentAuthorMention($body, $profile_url)
3716 $profile = Contact::getDetailsByURL($profile_url);
3717 if (!empty($profile['addr'])
3718 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3719 && !strstr($body, $profile['addr'])
3720 && !strstr($body, $profile_url)
3722 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3731 * @param array $item The item that will be exported
3732 * @param array $owner the array of the item owner
3733 * @param array $contact Target of the communication
3734 * @param bool $public_batch Is it a public post?
3736 * @return int The result of the transmission
3737 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3738 * @throws \ImagickException
3740 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3742 $status = self::buildStatus($item, $owner);
3744 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3748 * Creates a "like" object
3750 * @param array $item The item that will be exported
3751 * @param array $owner the array of the item owner
3753 * @return array The data for a "like"
3754 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3756 private static function constructLike(array $item, array $owner)
3758 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3759 if (!DBA::isResult($parent)) {
3763 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3765 if ($item['verb'] === Activity::LIKE) {
3767 } elseif ($item['verb'] === Activity::DISLIKE) {
3768 $positive = "false";
3771 return(["author" => self::myHandle($owner),
3772 "guid" => $item["guid"],
3773 "parent_guid" => $parent["guid"],
3774 "parent_type" => $target_type,
3775 "positive" => $positive,
3776 "author_signature" => ""]);
3780 * Creates an "EventParticipation" object
3782 * @param array $item The item that will be exported
3783 * @param array $owner the array of the item owner
3785 * @return array The data for an "EventParticipation"
3786 * @throws \Exception
3788 private static function constructAttend(array $item, array $owner)
3790 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3791 if (!DBA::isResult($parent)) {
3795 switch ($item['verb']) {
3796 case Activity::ATTEND:
3797 $attend_answer = 'accepted';
3799 case Activity::ATTENDNO:
3800 $attend_answer = 'declined';
3802 case Activity::ATTENDMAYBE:
3803 $attend_answer = 'tentative';
3806 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3810 return(["author" => self::myHandle($owner),
3811 "guid" => $item["guid"],
3812 "parent_guid" => $parent["guid"],
3813 "status" => $attend_answer,
3814 "author_signature" => ""]);
3818 * Creates the object for a comment
3820 * @param array $item The item that will be exported
3821 * @param array $owner the array of the item owner
3823 * @return array|false The data for a comment
3824 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3826 private static function constructComment(array $item, array $owner)
3828 $cachekey = "diaspora:constructComment:".$item['guid'];
3830 $result = DI::cache()->get($cachekey);
3831 if (!is_null($result)) {
3835 $toplevel_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3836 if (!DBA::isResult($toplevel_item)) {
3837 Logger::error('Missing parent conversation item', ['parent' => $item["parent"]]);
3841 $thread_parent_item = $toplevel_item;
3842 if ($item['thr-parent'] != $item['parent-uri']) {
3843 $thread_parent_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3846 $body = $item["body"];
3848 // The replied to autor mention is prepended for clarity if:
3849 // - Item replied isn't yours
3850 // - Item is public or explicit mentions are disabled
3851 // - Implicit mentions are enabled
3853 $item['author-id'] != $thread_parent_item['author-id']
3854 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3855 && !DI::config()->get('system', 'disable_implicit_mentions')
3857 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3860 $text = html_entity_decode(BBCode::toMarkdown($body));
3861 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3862 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3865 "author" => self::myHandle($owner),
3866 "guid" => $item["guid"],
3867 "created_at" => $created,
3868 "edited_at" => $edited,
3869 "parent_guid" => $toplevel_item["guid"],
3871 "author_signature" => ""
3874 // Send the thread parent guid only if it is a threaded comment
3875 if ($item['thr-parent'] != $item['parent-uri']) {
3876 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3879 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3885 * Send a like or a comment
3887 * @param array $item The item that will be exported
3888 * @param array $owner the array of the item owner
3889 * @param array $contact Target of the communication
3890 * @param bool $public_batch Is it a public post?
3892 * @return int The result of the transmission
3893 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3894 * @throws \ImagickException
3896 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3898 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3899 $message = self::constructAttend($item, $owner);
3900 $type = "event_participation";
3901 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3902 $message = self::constructLike($item, $owner);
3904 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3905 $message = self::constructComment($item, $owner);
3909 if (empty($message)) {
3913 $message["author_signature"] = self::signature($owner, $message);
3915 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3919 * Creates a message from a signature record entry
3921 * @param array $item The item that will be exported
3922 * @return array The message
3924 private static function messageFromSignature(array $item)
3926 // Split the signed text
3927 $signed_parts = explode(";", $item['signed_text']);
3929 if ($item["deleted"]) {
3930 $message = ["author" => $item['signer'],
3931 "target_guid" => $signed_parts[0],
3932 "target_type" => $signed_parts[1]];
3933 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3934 $message = ["author" => $signed_parts[4],
3935 "guid" => $signed_parts[1],
3936 "parent_guid" => $signed_parts[3],
3937 "parent_type" => $signed_parts[2],
3938 "positive" => $signed_parts[0],
3939 "author_signature" => $item['signature'],
3940 "parent_author_signature" => ""];
3942 // Remove the comment guid
3943 $guid = array_shift($signed_parts);
3945 // Remove the parent guid
3946 $parent_guid = array_shift($signed_parts);
3948 // Remove the handle
3949 $handle = array_pop($signed_parts);
3952 "author" => $handle,
3954 "parent_guid" => $parent_guid,
3955 "text" => implode(";", $signed_parts),
3956 "author_signature" => $item['signature'],
3957 "parent_author_signature" => ""
3964 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3966 * @param array $item The item that will be exported
3967 * @param array $owner the array of the item owner
3968 * @param array $contact Target of the communication
3969 * @param bool $public_batch Is it a public post?
3971 * @return int The result of the transmission
3972 * @throws \Exception
3974 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3976 if ($item["deleted"]) {
3977 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3978 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3984 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3986 $msg = json_decode($item['signed_text'], true);
3989 if (is_array($msg)) {
3990 foreach ($msg as $field => $data) {
3991 if (!$item["deleted"]) {
3992 if ($field == "diaspora_handle") {
3995 if ($field == "target_type") {
3996 $field = "parent_type";
4000 $message[$field] = $data;
4003 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
4006 $message["parent_author_signature"] = self::signature($owner, $message);
4008 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
4010 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4014 * Sends a retraction (deletion) of a message, like or comment
4016 * @param array $item The item that will be exported
4017 * @param array $owner the array of the item owner
4018 * @param array $contact Target of the communication
4019 * @param bool $public_batch Is it a public post?
4020 * @param bool $relay Is the retraction transmitted from a relay?
4022 * @return int The result of the transmission
4023 * @throws \Exception
4025 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
4027 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4029 $msg_type = "retraction";
4031 if ($item['id'] == $item['parent']) {
4032 $target_type = "Post";
4033 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4034 $target_type = "Like";
4036 $target_type = "Comment";
4039 $message = ["author" => $itemaddr,
4040 "target_guid" => $item['guid'],
4041 "target_type" => $target_type];
4043 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
4045 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4051 * @param array $item The item that will be exported
4052 * @param array $owner The owner
4053 * @param array $contact Target of the communication
4055 * @return int The result of the transmission
4056 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4057 * @throws \ImagickException
4059 public static function sendMail(array $item, array $owner, array $contact)
4061 $myaddr = self::myHandle($owner);
4063 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
4064 if (!DBA::isResult($cnv)) {
4065 Logger::log("conversation not found.");
4069 $body = BBCode::toMarkdown($item["body"]);
4070 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4073 "author" => $myaddr,
4074 "guid" => $item["guid"],
4075 "conversation_guid" => $cnv["guid"],
4077 "created_at" => $created,
4080 if ($item["reply"]) {
4085 "author" => $cnv["creator"],
4086 "guid" => $cnv["guid"],
4087 "subject" => $cnv["subject"],
4088 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4089 "participants" => $cnv["recips"],
4093 $type = "conversation";
4096 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4100 * Split a name into first name and last name
4102 * @param string $name The name
4104 * @return array The array with "first" and "last"
4106 public static function splitName($name) {
4107 $name = trim($name);
4109 // Is the name longer than 64 characters? Then cut the rest of it.
4110 if (strlen($name) > 64) {
4111 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4112 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4114 $name = substr($name, 0, 64);
4118 // Take the first word as first name
4119 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4120 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4121 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4122 return ['first' => $first, 'last' => $last];
4125 // Take the last word as last name
4126 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4127 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4129 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4130 return ['first' => $first, 'last' => $last];
4133 // Take the first 32 characters if there is no space in the first 32 characters
4134 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4135 $first = substr($name, 0, 32);
4136 $last = substr($name, 32);
4137 return ['first' => $first, 'last' => $last];
4140 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4141 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4143 // Check if the last name is longer than 32 characters
4144 if (strlen($last) > 32) {
4145 if (strpos($last, ' ') <= 32) {
4146 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4148 $last = substr($last, 0, 32);
4152 return ['first' => $first, 'last' => $last];
4156 * Create profile data
4158 * @param int $uid The user id
4160 * @return array The profile data
4161 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4163 private static function createProfileData($uid)
4165 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
4166 if (!DBA::isResult($profile)) {
4170 $handle = $profile["addr"];
4172 $split_name = self::splitName($profile['name']);
4173 $first = $split_name['first'];
4174 $last = $split_name['last'];
4176 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4177 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4178 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4179 $searchable = ($profile['net-publish'] ? 'true' : 'false');
4185 if ($searchable === 'true') {
4188 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4189 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4193 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4196 $about = BBCode::toMarkdown($profile['about']);
4198 $location = $profile['location'];
4200 if ($profile['pub_keywords']) {
4201 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4202 $kw = str_replace(' ', ' ', $kw);
4203 $arr = explode(' ', $kw);
4205 for ($x = 0; $x < 5; $x ++) {
4206 if (!empty($arr[$x])) {
4207 $tags .= '#'. trim($arr[$x]) .' ';
4212 $tags = trim($tags);
4215 return ["author" => $handle,
4216 "first_name" => $first,
4217 "last_name" => $last,
4218 "image_url" => $large,
4219 "image_url_medium" => $medium,
4220 "image_url_small" => $small,
4223 "location" => $location,
4224 "searchable" => $searchable,
4226 "tag_string" => $tags];
4230 * Sends profile data
4232 * @param int $uid The user id
4233 * @param bool $recips optional, default false
4235 * @throws \Exception
4237 public static function sendProfile($uid, $recips = false)
4243 $owner = User::getOwnerDataById($uid);
4250 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4251 AND `uid` = %d AND `rel` != %d",
4252 DBA::escape(Protocol::DIASPORA),
4254 intval(Contact::SHARING)
4262 $message = self::createProfileData($uid);
4264 // @ToDo Split this into single worker jobs
4265 foreach ($recips as $recip) {
4266 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4267 self::buildAndTransmit($owner, $recip, "profile", $message);
4272 * Creates the signature for likes that are created on our system
4274 * @param integer $uid The user of that comment
4275 * @param array $item Item array
4277 * @return array Signed content
4278 * @throws \Exception
4280 public static function createLikeSignature($uid, array $item)
4282 $owner = User::getOwnerDataById($uid);
4283 if (empty($owner)) {
4284 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4288 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4292 $message = self::constructLike($item, $owner);
4293 if ($message === false) {
4297 $message["author_signature"] = self::signature($owner, $message);
4303 * Creates the signature for Comments that are created on our system
4305 * @param integer $uid The user of that comment
4306 * @param array $item Item array
4308 * @return array Signed content
4309 * @throws \Exception
4311 public static function createCommentSignature($uid, array $item)
4313 $owner = User::getOwnerDataById($uid);
4314 if (empty($owner)) {
4315 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4319 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4320 $item['thr-parent'] = $item['parent-uri'];
4322 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4323 if (!DBA::isResult($parent)) {
4327 $item['parent-uri'] = $parent['parent-uri'];
4329 $message = self::constructComment($item, $owner);
4330 if ($message === false) {
4334 $message["author_signature"] = self::signature($owner, $message);