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\Mail;
40 use Friendica\Model\Post;
41 use Friendica\Model\Tag;
42 use Friendica\Model\User;
43 use Friendica\Network\Probe;
44 use Friendica\Util\Crypto;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Map;
47 use Friendica\Util\Network;
48 use Friendica\Util\Strings;
49 use Friendica\Util\XML;
50 use Friendica\Worker\Delivery;
54 * This class contain functions to create and send Diaspora XML files
59 * Mark the relay contact of the given contact for archival
60 * This is called whenever there is a communication issue with the server.
61 * It avoids sending stuff to servers who don't exist anymore.
62 * The relay contact is a technical contact entry that exists once per server.
64 * @param array $contact of the relay contact
66 public static function markRelayForArchival(array $contact)
68 if (!empty($contact['contact-type']) && ($contact['contact-type'] == Contact::TYPE_RELAY)) {
69 // This is already the relay contact, we don't need to fetch it
70 $relay_contact = $contact;
71 } elseif (empty($contact['baseurl'])) {
72 if (!empty($contact['batch'])) {
73 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => Contact::TYPE_RELAY];
74 $relay_contact = DBA::selectFirst('contact', [], $condition);
79 $relay_contact = self::getRelayContact($contact['baseurl'], []);
82 if (!empty($relay_contact)) {
83 Logger::info('Relay contact will be marked for archival', ['id' => $relay_contact['id'], 'url' => $relay_contact['url']]);
84 Contact::markForArchival($relay_contact);
89 * Return a list of relay servers
91 * The list contains not only the official relays but also servers that we serve directly
93 * @param integer $item_id The id of the item that is sent
94 * @param array $contacts The previously fetched contacts
96 * @return array of relay servers
97 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
99 public static function relayList($item_id, array $contacts = [])
103 // Fetching relay servers
104 $serverdata = DI::config()->get("system", "relay_server");
106 if (!empty($serverdata)) {
107 $servers = explode(",", $serverdata);
108 foreach ($servers as $server) {
109 $serverlist[$server] = trim($server);
113 if (DI::config()->get("system", "relay_directly", false)) {
114 // We distribute our stuff based on the parent to ensure that the thread will be complete
115 $parent = Item::selectFirst(['uri-id'], ['id' => $item_id]);
116 if (!DBA::isResult($parent)) {
120 // Servers that want to get all content
121 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
122 while ($server = DBA::fetch($servers)) {
123 $serverlist[$server['url']] = $server['url'];
125 DBA::close($servers);
127 // All tags of the current post
128 $tags = DBA::select('tag-view', ['name'], ['uri-id' => $parent['uri-id'], 'type' => Tag::HASHTAG]);
130 while ($tag = DBA::fetch($tags)) {
131 $taglist[] = $tag['name'];
135 // All servers who wants content with this tag
137 if (!empty($taglist)) {
138 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
139 while ($server = DBA::fetch($tagserver)) {
140 $tagserverlist[] = $server['gserver-id'];
142 DBA::close($tagserver);
145 // All adresses with the given id
146 if (!empty($tagserverlist)) {
147 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
148 while ($server = DBA::fetch($servers)) {
149 $serverlist[$server['url']] = $server['url'];
151 DBA::close($servers);
155 // Now we are collecting all relay contacts
156 foreach ($serverlist as $server_url) {
157 // We don't send messages to ourselves
158 if (Strings::compareLink($server_url, DI::baseUrl())) {
161 $contact = self::getRelayContact($server_url);
162 if (is_bool($contact)) {
167 foreach ($contacts as $entry) {
168 if ($entry['batch'] == $contact['batch']) {
174 $contacts[] = $contact;
182 * Return a contact for a given server address or creates a dummy entry
184 * @param string $server_url The url of the server
185 * @param array $fields Fieldlist
186 * @return array with the contact
189 private static function getRelayContact(string $server_url, array $fields = ['batch', 'id', 'url', 'name', 'network', 'protocol', 'archive', 'blocked'])
191 // Fetch the relay contact
192 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
193 'contact-type' => Contact::TYPE_RELAY];
194 $contact = DBA::selectFirst('contact', $fields, $condition);
196 if (DBA::isResult($contact)) {
197 if ($contact['archive'] || $contact['blocked']) {
202 self::setRelayContact($server_url);
204 $contact = DBA::selectFirst('contact', $fields, $condition);
205 if (DBA::isResult($contact)) {
210 // It should never happen that we arrive here
215 * Update or insert a relay contact
217 * @param string $server_url The url of the server
218 * @param array $network_fields Optional network specific fields
221 public static function setRelayContact($server_url, array $network_fields = [])
223 $fields = ['created' => DateTimeFormat::utcNow(),
224 'name' => 'relay', 'nick' => 'relay', 'url' => $server_url,
225 'nurl' => Strings::normaliseLink($server_url),
226 'network' => Protocol::DIASPORA, 'uid' => 0,
227 'batch' => $server_url . '/receive/public',
228 'rel' => Contact::FOLLOWER, 'blocked' => false,
229 'pending' => false, 'writable' => true,
230 'baseurl' => $server_url, 'contact-type' => Contact::TYPE_RELAY];
232 $fields = array_merge($fields, $network_fields);
234 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url)];
235 $old = DBA::selectFirst('contact', [], $condition);
236 if (DBA::isResult($old)) {
237 unset($fields['created']);
238 $condition = ['id' => $old['id']];
240 Logger::info('Update relay contact', ['fields' => $fields, 'condition' => $condition]);
241 DBA::update('contact', $fields, $condition, $old);
243 Logger::info('Create relay contact', ['fields' => $fields]);
244 Contact::insert($fields);
249 * Return a list of participating contacts for a thread
251 * This is used for the participation feature.
252 * One of the parameters is a contact array.
253 * This is done to avoid duplicates.
255 * @param array $parent The parent post
256 * @param array $contacts The previously fetched contacts
258 * @return array of relay servers
261 public static function participantsForThread(array $parent, array $contacts)
263 if (!in_array($parent['private'], [Item::PUBLIC, Item::UNLISTED])) {
267 $items = Item::select(['author-id'], ['parent' => $parent['id']], ['group_by' => ['author-id']]);
268 while ($item = DBA::fetch($items)) {
269 $contact = DBA::selectFirst('contact', ['id', 'url', 'name', 'protocol', 'batch', 'network'],
270 ['id' => $item['author-id']]);
271 if (!DBA::isResult($contact)) {
277 foreach ($contacts as $entry) {
278 if ($entry['batch'] == $contact['batch']) {
284 Logger::info('Add participant to receiver list', ['item' => $parent['guid'], 'participant' => $contact['url']]);
285 $contacts[] = $contact;
294 * repairs a signature that was double encoded
296 * The function is unused at the moment. It was copied from the old implementation.
298 * @param string $signature The signature
299 * @param string $handle The handle of the signature owner
300 * @param integer $level This value is only set inside this function to avoid endless loops
302 * @return string the repaired signature
305 private static function repairSignature($signature, $handle = "", $level = 1)
307 if ($signature == "") {
311 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
312 $signature = base64_decode($signature);
313 Logger::log("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, Logger::DEBUG);
315 // Do a recursive call to be able to fix even multiple levels
317 $signature = self::repairSignature($signature, $handle, ++$level);
325 * verify the envelope and return the verified data
327 * @param string $envelope The magic envelope
329 * @return string verified data
330 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
331 * @throws \ImagickException
333 private static function verifyMagicEnvelope($envelope)
335 $basedom = XML::parseString($envelope, true);
337 if (!is_object($basedom)) {
338 Logger::log("Envelope is no XML file");
342 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
344 if (sizeof($children) == 0) {
345 Logger::log("XML has no children");
351 $data = Strings::base64UrlDecode($children->data);
352 $type = $children->data->attributes()->type[0];
354 $encoding = $children->encoding;
356 $alg = $children->alg;
358 $sig = Strings::base64UrlDecode($children->sig);
359 $key_id = $children->sig->attributes()->key_id[0];
361 $handle = Strings::base64UrlDecode($key_id);
364 $b64url_data = Strings::base64UrlEncode($data);
365 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
367 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
370 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
374 $key = self::key($handle);
376 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
380 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
382 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
390 * encrypts data via AES
392 * @param string $key The AES key
393 * @param string $iv The IV (is used for CBC encoding)
394 * @param string $data The data that is to be encrypted
396 * @return string encrypted data
398 private static function aesEncrypt($key, $iv, $data)
400 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
404 * decrypts data via AES
406 * @param string $key The AES key
407 * @param string $iv The IV (is used for CBC encoding)
408 * @param string $encrypted The encrypted data
410 * @return string decrypted data
412 private static function aesDecrypt($key, $iv, $encrypted)
414 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
418 * Decodes incoming Diaspora message in the new format
420 * @param string $raw raw post message
421 * @param string $privKey The private key of the importer
422 * @param boolean $no_exit Don't do an http exit on error
425 * 'message' -> decoded Diaspora XML message
426 * 'author' -> author diaspora handle
427 * 'key' -> author public key (converted to pkcs#8)
428 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
429 * @throws \ImagickException
431 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
433 $data = json_decode($raw);
435 // Is it a private post? Then decrypt the outer Salmon
436 if (is_object($data)) {
437 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
438 $ciphertext = base64_decode($data->encrypted_magic_envelope);
440 $outer_key_bundle = '';
441 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
442 $j_outer_key_bundle = json_decode($outer_key_bundle);
444 if (!is_object($j_outer_key_bundle)) {
445 Logger::log('Outer Salmon did not verify. Discarding.');
449 throw new \Friendica\Network\HTTPException\BadRequestException();
453 $outer_iv = base64_decode($j_outer_key_bundle->iv);
454 $outer_key = base64_decode($j_outer_key_bundle->key);
456 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
461 $basedom = XML::parseString($xml, true);
463 if (!is_object($basedom)) {
464 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
468 throw new \Friendica\Network\HTTPException\BadRequestException();
472 $base = $basedom->children(ActivityNamespace::SALMON_ME);
474 // Not sure if this cleaning is needed
475 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
477 // Build the signed data
478 $type = $base->data[0]->attributes()->type[0];
479 $encoding = $base->encoding;
481 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
483 // This is the signature
484 $signature = Strings::base64UrlDecode($base->sig);
486 // Get the senders' public key
487 $key_id = $base->sig[0]->attributes()->key_id[0];
488 $author_addr = base64_decode($key_id);
489 if ($author_addr == '') {
490 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
494 throw new \Friendica\Network\HTTPException\BadRequestException();
498 $key = self::key($author_addr);
500 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
504 throw new \Friendica\Network\HTTPException\BadRequestException();
508 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
510 Logger::log('Message did not verify. Discarding.');
514 throw new \Friendica\Network\HTTPException\BadRequestException();
518 return ['message' => (string)Strings::base64UrlDecode($base->data),
519 'author' => XML::unescape($author_addr),
520 'key' => (string)$key];
524 * Decodes incoming Diaspora message in the deprecated format
526 * @param string $xml urldecoded Diaspora salmon
527 * @param string $privKey The private key of the importer
530 * 'message' -> decoded Diaspora XML message
531 * 'author' -> author diaspora handle
532 * 'key' -> author public key (converted to pkcs#8)
533 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
534 * @throws \ImagickException
536 public static function decode(string $xml, string $privKey = '')
539 $basedom = XML::parseString($xml);
541 if (!is_object($basedom)) {
542 Logger::log("XML is not parseable.");
545 $children = $basedom->children('https://joindiaspora.com/protocol');
547 $inner_aes_key = null;
550 if ($children->header) {
552 $author_link = str_replace('acct:', '', $children->header->author_id);
554 // This happens with posts from a relais
555 if (empty($privKey)) {
556 Logger::log("This is no private post in the old format", Logger::DEBUG);
560 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
562 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
563 $ciphertext = base64_decode($encrypted_header->ciphertext);
565 $outer_key_bundle = '';
566 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
568 $j_outer_key_bundle = json_decode($outer_key_bundle);
570 $outer_iv = base64_decode($j_outer_key_bundle->iv);
571 $outer_key = base64_decode($j_outer_key_bundle->key);
573 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
575 Logger::log('decrypted: '.$decrypted, Logger::DEBUG);
576 $idom = XML::parseString($decrypted);
578 $inner_iv = base64_decode($idom->iv);
579 $inner_aes_key = base64_decode($idom->aes_key);
581 $author_link = str_replace('acct:', '', $idom->author_id);
584 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
586 // figure out where in the DOM tree our data is hiding
589 if ($dom->provenance->data) {
590 $base = $dom->provenance;
591 } elseif ($dom->env->data) {
593 } elseif ($dom->data) {
598 Logger::log('unable to locate salmon data in xml');
599 throw new \Friendica\Network\HTTPException\BadRequestException();
603 // Stash the signature away for now. We have to find their key or it won't be good for anything.
604 $signature = Strings::base64UrlDecode($base->sig);
608 // strip whitespace so our data element will return to one big base64 blob
609 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
612 // stash away some other stuff for later
614 $type = $base->data[0]->attributes()->type[0];
615 $keyhash = $base->sig[0]->attributes()->keyhash[0];
616 $encoding = $base->encoding;
620 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
624 $data = Strings::base64UrlDecode($data);
628 $inner_decrypted = $data;
630 // Decode the encrypted blob
631 $inner_encrypted = base64_decode($data);
632 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
636 Logger::log('Could not retrieve author URI.');
637 throw new \Friendica\Network\HTTPException\BadRequestException();
639 // Once we have the author URI, go to the web and try to find their public key
640 // (first this will look it up locally if it is in the fcontact cache)
641 // This will also convert diaspora public key from pkcs#1 to pkcs#8
643 Logger::log('Fetching key for '.$author_link);
644 $key = self::key($author_link);
647 Logger::log('Could not retrieve author key.');
648 throw new \Friendica\Network\HTTPException\BadRequestException();
651 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
654 Logger::log('Message did not verify. Discarding.');
655 throw new \Friendica\Network\HTTPException\BadRequestException();
658 Logger::log('Message verified.');
660 return ['message' => (string)$inner_decrypted,
661 'author' => XML::unescape($author_link),
662 'key' => (string)$key];
667 * Dispatches public messages and find the fitting receivers
669 * @param array $msg The post that will be dispatched
671 * @return int The message id of the generated message, "true" or "false" if there was an error
672 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
673 * @throws \ImagickException
675 public static function dispatchPublic($msg)
677 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
679 Logger::log("diaspora is disabled");
683 if (!($fields = self::validPosting($msg))) {
684 Logger::log("Invalid posting");
688 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
689 $success = self::dispatch($importer, $msg, $fields);
695 * Dispatches the different message types to the different functions
697 * @param array $importer Array of the importer user
698 * @param array $msg The post that will be dispatched
699 * @param SimpleXMLElement $fields SimpleXML object that contains the message
701 * @return int The message id of the generated message, "true" or "false" if there was an error
702 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
703 * @throws \ImagickException
705 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
707 // The sender is the handle of the contact that sent the message.
708 // This will often be different with relayed messages (for example "like" and "comment")
709 $sender = $msg["author"];
711 // This is only needed for private postings since this is already done for public ones before
712 if (is_null($fields)) {
714 if (!($fields = self::validPosting($msg))) {
715 Logger::log("Invalid posting");
722 $type = $fields->getName();
724 Logger::log("Received message type ".$type." from ".$sender." for user ".$importer["uid"], Logger::DEBUG);
727 case "account_migration":
729 Logger::log('Message with type ' . $type . ' is not private, quitting.');
732 return self::receiveAccountMigration($importer, $fields);
734 case "account_deletion":
735 return self::receiveAccountDeletion($fields);
738 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
742 Logger::log('Message with type ' . $type . ' is not private, quitting.');
745 return self::receiveContactRequest($importer, $fields);
749 Logger::log('Message with type ' . $type . ' is not private, quitting.');
752 return self::receiveConversation($importer, $msg, $fields);
755 return self::receiveLike($importer, $sender, $fields);
759 Logger::log('Message with type ' . $type . ' is not private, quitting.');
762 return self::receiveMessage($importer, $fields);
764 case "participation":
766 Logger::log('Message with type ' . $type . ' is not private, quitting.');
769 return self::receiveParticipation($importer, $fields);
771 case "photo": // Not implemented
772 return self::receivePhoto($importer, $fields);
774 case "poll_participation": // Not implemented
775 return self::receivePollParticipation($importer, $fields);
779 Logger::log('Message with type ' . $type . ' is not private, quitting.');
782 return self::receiveProfile($importer, $fields);
785 return self::receiveReshare($importer, $fields, $msg["message"]);
788 return self::receiveRetraction($importer, $sender, $fields);
790 case "status_message":
791 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
794 Logger::log("Unknown message type ".$type);
800 * Checks if a posting is valid and fetches the data fields.
802 * This function does not only check the signature.
803 * It also does the conversion between the old and the new diaspora format.
805 * @param array $msg Array with the XML, the sender handle and the sender signature
807 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
808 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
809 * @throws \ImagickException
811 private static function validPosting($msg)
813 $data = XML::parseString($msg["message"]);
815 if (!is_object($data)) {
816 Logger::log("No valid XML ".$msg["message"], Logger::DEBUG);
820 // Is this the new or the old version?
821 if ($data->getName() == "XML") {
823 foreach ($data->post->children() as $child) {
831 $type = $element->getName();
834 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
836 // All retractions are handled identically from now on.
837 // In the new version there will only be "retraction".
838 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
839 $type = "retraction";
841 if ($type == "request") {
845 $fields = new SimpleXMLElement("<".$type."/>");
848 $author_signature = null;
849 $parent_author_signature = null;
851 foreach ($element->children() as $fieldname => $entry) {
853 // Translation for the old XML structure
854 if ($fieldname == "diaspora_handle") {
855 $fieldname = "author";
857 if ($fieldname == "participant_handles") {
858 $fieldname = "participants";
860 if (in_array($type, ["like", "participation"])) {
861 if ($fieldname == "target_type") {
862 $fieldname = "parent_type";
865 if ($fieldname == "sender_handle") {
866 $fieldname = "author";
868 if ($fieldname == "recipient_handle") {
869 $fieldname = "recipient";
871 if ($fieldname == "root_diaspora_id") {
872 $fieldname = "root_author";
874 if ($type == "status_message") {
875 if ($fieldname == "raw_message") {
879 if ($type == "retraction") {
880 if ($fieldname == "post_guid") {
881 $fieldname = "target_guid";
883 if ($fieldname == "type") {
884 $fieldname = "target_type";
889 if (($fieldname == "author_signature") && ($entry != "")) {
890 $author_signature = base64_decode($entry);
891 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
892 $parent_author_signature = base64_decode($entry);
893 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
894 if ($signed_data != "") {
898 $signed_data .= $entry;
900 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
901 || ($orig_type == "relayable_retraction")
903 XML::copy($entry, $fields, $fieldname);
907 // This is something that shouldn't happen at all.
908 if (in_array($type, ["status_message", "reshare", "profile"])) {
909 if ($msg["author"] != $fields->author) {
910 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
915 // Only some message types have signatures. So we quit here for the other types.
916 if (!in_array($type, ["comment", "like"])) {
919 // No author_signature? This is a must, so we quit.
920 if (!isset($author_signature)) {
921 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
925 if (isset($parent_author_signature)) {
926 $key = self::key($msg["author"]);
928 Logger::log("No key found for parent author ".$msg["author"], Logger::DEBUG);
932 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
933 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);
938 $key = self::key($fields->author);
940 Logger::log("No key found for author ".$fields->author, Logger::DEBUG);
944 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
945 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);
953 * Fetches the public key for a given handle
955 * @param string $handle The handle
957 * @return string The public key
958 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
959 * @throws \ImagickException
961 private static function key($handle)
963 $handle = strval($handle);
965 Logger::log("Fetching diaspora key for: ".$handle);
967 $r = self::personByHandle($handle);
976 * Fetches data for a given handle
978 * @param string $handle The handle
979 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
981 * @return array the queried data
982 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
983 * @throws \ImagickException
985 public static function personByHandle($handle, $update = null)
987 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
988 if (!DBA::isResult($person)) {
989 $urls = [$handle, str_replace('http://', 'https://', $handle), Strings::normaliseLink($handle)];
990 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'url' => $urls]);
993 if (DBA::isResult($person)) {
994 Logger::debug("In cache " . print_r($person, true));
996 if (is_null($update)) {
997 // update record occasionally so it doesn't get stale
998 $d = strtotime($person["updated"]." +00:00");
999 if ($d < strtotime("now - 14 days")) {
1003 if ($person["guid"] == "") {
1007 } elseif (is_null($update)) {
1008 $update = !DBA::isResult($person);
1014 Logger::log("create or refresh", Logger::DEBUG);
1015 $r = Probe::uri($handle, Protocol::DIASPORA);
1017 // Note that Friendica contacts will return a "Diaspora person"
1018 // if Diaspora connectivity is enabled on their server
1019 if ($r && ($r["network"] === Protocol::DIASPORA)) {
1020 self::updateFContact($r);
1022 $person = self::personByHandle($handle, false);
1030 * Updates the fcontact table
1032 * @param array $arr The fcontact data
1033 * @throws \Exception
1035 private static function updateFContact($arr)
1037 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
1038 'request' => $arr["request"], 'nick' => $arr["nick"],
1039 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
1040 'batch' => $arr["batch"], 'notify' => $arr["notify"],
1041 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
1042 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
1043 'updated' => DateTimeFormat::utcNow()];
1045 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
1047 DBA::update('fcontact', $fields, $condition, true);
1051 * get a handle (user@domain.tld) from a given contact id
1053 * @param int $contact_id The id in the contact table
1054 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1056 * @return string the handle
1057 * @throws \Exception
1059 private static function handleFromContact($contact_id, $pcontact_id = 0)
1063 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
1065 if ($pcontact_id != 0) {
1066 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
1068 if (DBA::isResult($contact) && !empty($contact["addr"])) {
1069 return strtolower($contact["addr"]);
1074 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1078 if (DBA::isResult($r)) {
1081 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1083 if ($contact['addr'] != "") {
1084 $handle = $contact['addr'];
1086 $baseurl_start = strpos($contact['url'], '://') + 3;
1087 // allows installations in a subdirectory--not sure how Diaspora will handle
1088 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1089 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1090 $handle = $contact['nick'].'@'.$baseurl;
1094 return strtolower($handle);
1098 * get a url (scheme://domain.tld/u/user) from a given Diaspora*
1101 * @param mixed $fcontact_guid Hexadecimal string guid
1103 * @return string the contact url or null
1104 * @throws \Exception
1106 public static function urlFromContactGuid($fcontact_guid)
1108 Logger::log("fcontact guid is ".$fcontact_guid, Logger::DEBUG);
1111 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1112 DBA::escape(Protocol::DIASPORA),
1113 DBA::escape($fcontact_guid)
1116 if (DBA::isResult($r)) {
1117 return $r[0]['url'];
1124 * Get a contact id for a given handle
1126 * @todo Move to Friendica\Model\Contact
1128 * @param int $uid The user id
1129 * @param string $handle The handle in the format user@domain.tld
1131 * @return array Contact data
1132 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1133 * @throws \ImagickException
1135 private static function contactByHandle($uid, $handle)
1137 $cid = Contact::getIdForURL($handle, $uid);
1139 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1143 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1144 if (!DBA::isResult($contact)) {
1145 // This here shouldn't happen at all
1146 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1154 * Checks if the given contact url does support ActivityPub
1156 * @param string $url profile url
1157 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1159 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1160 * @throws \ImagickException
1162 public static function isSupportedByContactUrl($url, $update = null)
1164 return !empty(self::personByHandle($url, $update));
1168 * Check if posting is allowed for this contact
1170 * @param array $importer Array of the importer user
1171 * @param array $contact The contact that is checked
1172 * @param bool $is_comment Is the check for a comment?
1174 * @return bool is the contact allowed to post?
1176 private static function postAllow(array $importer, array $contact, $is_comment = false)
1179 * Perhaps we were already sharing with this person. Now they're sharing with us.
1180 * That makes us friends.
1181 * Normally this should have handled by getting a request - but this could get lost
1183 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1184 // It is not removed by now. Possibly the code is needed?
1185 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1188 // array('rel' => Contact::FRIEND, 'writable' => true),
1189 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1192 // $contact["rel"] = Contact::FRIEND;
1193 // Logger::log("defining user ".$contact["nick"]." as friend");
1196 // Contact server is blocked
1197 if (Network::isUrlBlocked($contact['url'])) {
1199 // We don't seem to like that person
1200 } elseif ($contact["blocked"]) {
1201 // Maybe blocked, don't accept.
1203 // We are following this person?
1204 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1205 // Yes, then it is fine.
1207 // Is it a post to a community?
1208 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1211 // Is the message a global user or a comment?
1212 } elseif (($importer["uid"] == 0) || $is_comment) {
1213 // Messages for the global users and comments are always accepted
1221 * Fetches the contact id for a handle and checks if posting is allowed
1223 * @param array $importer Array of the importer user
1224 * @param string $handle The checked handle in the format user@domain.tld
1225 * @param bool $is_comment Is the check for a comment?
1227 * @return array The contact data
1228 * @throws \Exception
1230 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1232 $contact = self::contactByHandle($importer["uid"], $handle);
1234 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1235 // If a contact isn't found, we accept it anyway if it is a comment
1236 if ($is_comment && ($importer["uid"] != 0)) {
1237 return self::contactByHandle(0, $handle);
1238 } elseif ($is_comment) {
1245 if (!self::postAllow($importer, $contact, $is_comment)) {
1246 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1253 * Does the message already exists on the system?
1255 * @param int $uid The user id
1256 * @param string $guid The guid of the message
1258 * @return int|bool message id if the message already was stored into the system - or false.
1259 * @throws \Exception
1261 private static function messageExists($uid, $guid)
1263 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1264 if (DBA::isResult($item)) {
1265 Logger::log("message ".$guid." already exists for user ".$uid);
1273 * Checks for links to posts in a message
1275 * @param array $item The item array
1278 private static function fetchGuid(array $item)
1280 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1281 preg_replace_callback(
1283 function ($match) use ($item) {
1284 self::fetchGuidSub($match, $item);
1289 preg_replace_callback(
1290 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1291 function ($match) use ($item) {
1292 self::fetchGuidSub($match, $item);
1299 * Checks for relative /people/* links in an item body to match local
1300 * contacts or prepends the remote host taken from the author link.
1302 * @param string $body The item body to replace links from
1303 * @param string $author_link The author link for missing local contact fallback
1305 * @return string the replaced string
1307 public static function replacePeopleGuid($body, $author_link)
1309 $return = preg_replace_callback(
1310 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1311 function ($match) use ($author_link) {
1313 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1314 // 1 => '0123456789abcdef'
1316 $handle = self::urlFromContactGuid($match[1]);
1319 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1321 // No local match, restoring absolute remote URL from author scheme and host
1322 $author_url = parse_url($author_link);
1323 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1335 * sub function of "fetchGuid" which checks for links in messages
1337 * @param array $match array containing a link that has to be checked for a message link
1338 * @param array $item The item array
1340 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1341 * @throws \ImagickException
1343 private static function fetchGuidSub($match, $item)
1345 if (!self::storeByGuid($match[1], $item["author-link"])) {
1346 self::storeByGuid($match[1], $item["owner-link"]);
1351 * Fetches an item with a given guid from a given server
1353 * @param string $guid the message guid
1354 * @param string $server The server address
1355 * @param int $uid The user id of the user
1357 * @return int the message id of the stored message or false
1358 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1359 * @throws \ImagickException
1361 private static function storeByGuid($guid, $server, $uid = 0)
1363 $serverparts = parse_url($server);
1365 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1369 $server = $serverparts["scheme"]."://".$serverparts["host"];
1371 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1373 $msg = self::message($guid, $server);
1379 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1381 // Now call the dispatcher
1382 return self::dispatchPublic($msg);
1386 * Fetches a message from a server
1388 * @param string $guid message guid
1389 * @param string $server The url of the server
1390 * @param int $level Endless loop prevention
1393 * 'message' => The message XML
1394 * 'author' => The author handle
1395 * 'key' => The public key of the author
1396 * @throws \Exception
1398 private static function message($guid, $server, $level = 0)
1404 // This will work for new Diaspora servers and Friendica servers from 3.5
1405 $source_url = $server."/fetch/post/".urlencode($guid);
1407 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1409 $envelope = Network::fetchUrl($source_url);
1411 Logger::log("Envelope was fetched.", Logger::DEBUG);
1412 $x = self::verifyMagicEnvelope($envelope);
1414 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1416 Logger::log("Envelope was verified.", Logger::DEBUG);
1426 $source_xml = XML::parseString($x);
1428 if (!is_object($source_xml)) {
1432 if ($source_xml->post->reshare) {
1433 // Reshare of a reshare - old Diaspora version
1434 Logger::log("Message is a reshare", Logger::DEBUG);
1435 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1436 } elseif ($source_xml->getName() == "reshare") {
1437 // Reshare of a reshare - new Diaspora version
1438 Logger::log("Message is a new reshare", Logger::DEBUG);
1439 return self::message($source_xml->root_guid, $server, ++$level);
1444 // Fetch the author - for the old and the new Diaspora version
1445 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1446 $author = (string)$source_xml->post->status_message->diaspora_handle;
1447 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1448 $author = (string)$source_xml->author;
1451 // If this isn't a "status_message" then quit
1453 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1457 $msg = ["message" => $x, "author" => $author];
1459 $msg["key"] = self::key($msg["author"]);
1465 * Fetches an item with a given URL
1467 * @param string $url the message url
1469 * @return int the message id of the stored message or false
1470 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1471 * @throws \ImagickException
1473 public static function fetchByURL($url, $uid = 0)
1475 // Check for Diaspora (and Friendica) typical paths
1476 if (!preg_match("=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1477 Logger::info('Invalid url', ['url' => $url]);
1481 $guid = urldecode($matches[2]);
1483 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1484 if (DBA::isResult($item)) {
1485 Logger::info('Found', ['id' => $item['id']]);
1489 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1490 $ret = self::storeByGuid($guid, $matches[1], $uid);
1491 Logger::info('Result', ['ret' => $ret]);
1493 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1494 if (DBA::isResult($item)) {
1495 Logger::info('Found', ['id' => $item['id']]);
1498 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1504 * Fetches the item record of a given guid
1506 * @param int $uid The user id
1507 * @param string $guid message guid
1508 * @param string $author The handle of the item
1509 * @param array $contact The contact of the item owner
1511 * @return array the item record
1512 * @throws \Exception
1514 private static function parentItem($uid, $guid, $author, array $contact)
1516 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1517 'author-name', 'author-link', 'author-avatar',
1518 'owner-name', 'owner-link', 'owner-avatar'];
1519 $condition = ['uid' => $uid, 'guid' => $guid];
1520 $item = Item::selectFirst($fields, $condition);
1522 if (!DBA::isResult($item)) {
1523 $person = self::personByHandle($author);
1524 $result = self::storeByGuid($guid, $person["url"], $uid);
1526 // We don't have an url for items that arrived at the public dispatcher
1527 if (!$result && !empty($contact["url"])) {
1528 $result = self::storeByGuid($guid, $contact["url"], $uid);
1532 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1534 $item = Item::selectFirst($fields, $condition);
1538 if (!DBA::isResult($item)) {
1539 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1542 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1548 * returns contact details
1550 * @param array $def_contact The default contact if the person isn't found
1551 * @param array $person The record of the person
1552 * @param int $uid The user id
1555 * 'cid' => contact id
1556 * 'network' => network type
1557 * @throws \Exception
1559 private static function authorContactByUrl($def_contact, $person, $uid)
1561 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1562 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1563 if (DBA::isResult($contact)) {
1564 $cid = $contact["id"];
1565 $network = $contact["network"];
1567 $cid = $def_contact["id"];
1568 $network = Protocol::DIASPORA;
1571 return ["cid" => $cid, "network" => $network];
1575 * Is the profile a hubzilla profile?
1577 * @param string $url The profile link
1579 * @return bool is it a hubzilla server?
1581 private static function isHubzilla($url)
1583 return(strstr($url, '/channel/'));
1587 * Generate a post link with a given handle and message guid
1589 * @param string $addr The user handle
1590 * @param string $guid message guid
1591 * @param string $parent_guid optional parent guid
1593 * @return string the post link
1594 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1595 * @throws \ImagickException
1597 private static function plink($addr, $guid, $parent_guid = '')
1599 $contact = Contact::getDetailsByAddr($addr);
1600 if (empty($contact)) {
1601 Logger::info('No contact data for address', ['addr' => $addr]);
1605 if (empty($contact['baseurl'])) {
1606 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1607 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1611 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1612 if (!empty($gserver['platform'])) {
1613 $platform = strtolower($gserver['platform']);
1614 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1617 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1618 if (self::isHubzilla($contact['url'])) {
1619 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1620 $platform = 'hubzilla';
1621 } elseif ($contact['network'] == Protocol::DFRN) {
1622 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1623 $platform = 'friendica';
1627 if ($platform == 'friendica') {
1628 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1631 if ($platform == 'hubzilla') {
1632 return $contact['baseurl'] . '/item/' . $guid;
1635 if ($platform == 'socialhome') {
1636 return $contact['baseurl'] . '/content/' . $guid;
1639 if ($platform != 'diaspora') {
1640 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1644 if ($parent_guid != '') {
1645 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1647 return $contact['baseurl'] . '/posts/' . $guid;
1652 * Receives account migration
1654 * @param array $importer Array of the importer user
1655 * @param object $data The message object
1657 * @return bool Success
1658 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1659 * @throws \ImagickException
1661 private static function receiveAccountMigration(array $importer, $data)
1663 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1664 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1665 $signature = Strings::escapeTags(XML::unescape($data->signature));
1667 $contact = self::contactByHandle($importer["uid"], $old_handle);
1669 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1673 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1676 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1677 $key = self::key($old_handle);
1678 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1679 Logger::log('No valid signature for migration.');
1683 // Update the profile
1684 self::receiveProfile($importer, $data->profile);
1686 // change the technical stuff in contact and gcontact
1687 $data = Probe::uri($new_handle);
1688 if ($data['network'] == Protocol::PHANTOM) {
1689 Logger::log('Account for '.$new_handle." couldn't be probed.");
1693 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1694 'name' => $data['name'], 'nick' => $data['nick'],
1695 'addr' => $data['addr'], 'batch' => $data['batch'],
1696 'notify' => $data['notify'], 'poll' => $data['poll'],
1697 'network' => $data['network']];
1699 DBA::update('contact', $fields, ['addr' => $old_handle]);
1701 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1702 'name' => $data['name'], 'nick' => $data['nick'],
1703 'addr' => $data['addr'], 'connect' => $data['addr'],
1704 'notify' => $data['notify'], 'photo' => $data['photo'],
1705 'server_url' => $data['baseurl'], 'network' => $data['network']];
1707 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1709 Logger::log('Contacts are updated.');
1715 * Processes an account deletion
1717 * @param object $data The message object
1719 * @return bool Success
1720 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1722 private static function receiveAccountDeletion($data)
1724 $author = Strings::escapeTags(XML::unescape($data->author));
1726 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1727 while ($contact = DBA::fetch($contacts)) {
1728 Contact::remove($contact["id"]);
1730 DBA::close($contacts);
1732 DBA::delete('gcontact', ['addr' => $author]);
1734 Logger::log('Removed contacts for ' . $author);
1740 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1742 * @param string $author Author handle
1743 * @param string $guid Message guid
1744 * @param boolean $onlyfound Only return uri when found in the database
1746 * @return string The constructed uri or the one from our database
1747 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1748 * @throws \ImagickException
1750 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1752 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1753 if (DBA::isResult($item)) {
1754 return $item["uri"];
1755 } elseif (!$onlyfound) {
1756 $person = self::personByHandle($author);
1758 $parts = parse_url($person['url']);
1759 unset($parts['path']);
1760 $host_url = Network::unparseURL($parts);
1762 return $host_url . '/objects/' . $guid;
1769 * Fetch the guid from our database with a given uri
1771 * @param string $uri Message uri
1772 * @param string $uid Author handle
1774 * @return string The post guid
1775 * @throws \Exception
1777 private static function getGuidFromUri($uri, $uid)
1779 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1780 if (DBA::isResult($item)) {
1781 return $item["guid"];
1788 * Find the best importer for a comment, like, ...
1790 * @param string $guid The guid of the item
1792 * @return array|boolean the origin owner of that post - or false
1793 * @throws \Exception
1795 private static function importerForGuid($guid)
1797 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1798 if (DBA::isResult($item)) {
1799 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1800 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1801 if (DBA::isResult($contact)) {
1809 * Store the mentions in the tag table
1811 * @param integer $uriid
1812 * @param string $text
1814 private static function storeMentions(int $uriid, string $text)
1816 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1817 if (empty($matches)) {
1822 * Matching values for the preg match
1823 * [1] = mention type (@ or !)
1824 * [2] = name (optional)
1828 foreach ($matches as $match) {
1829 if (empty($match)) {
1833 $person = self::personByHandle($match[3]);
1834 if (empty($person)) {
1838 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1843 * Processes an incoming comment
1845 * @param array $importer Array of the importer user
1846 * @param string $sender The sender of the message
1847 * @param object $data The message object
1848 * @param string $xml The original XML of the message
1850 * @return int The message id of the generated comment or "false" if there was an error
1851 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1852 * @throws \ImagickException
1854 private static function receiveComment(array $importer, $sender, $data, $xml)
1856 $author = Strings::escapeTags(XML::unescape($data->author));
1857 $guid = Strings::escapeTags(XML::unescape($data->guid));
1858 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1859 $text = XML::unescape($data->text);
1861 if (isset($data->created_at)) {
1862 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1864 $created_at = DateTimeFormat::utcNow();
1867 if (isset($data->thread_parent_guid)) {
1868 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1869 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1874 $contact = self::allowedContactByHandle($importer, $sender, true);
1879 $message_id = self::messageExists($importer["uid"], $guid);
1884 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1885 if (!$parent_item) {
1889 $person = self::personByHandle($author);
1890 if (!is_array($person)) {
1891 Logger::log("unable to find author details");
1895 // Fetch the contact id - if we know this contact
1896 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1900 $datarray["uid"] = $importer["uid"];
1901 $datarray["contact-id"] = $author_contact["cid"];
1902 $datarray["network"] = $author_contact["network"];
1904 $datarray["author-link"] = $person["url"];
1905 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1907 $datarray["owner-link"] = $contact["url"];
1908 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1910 $datarray["guid"] = $guid;
1911 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1912 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1914 $datarray["verb"] = Activity::POST;
1915 $datarray["gravity"] = GRAVITY_COMMENT;
1917 if ($thr_uri != "") {
1918 $datarray["parent-uri"] = $thr_uri;
1920 $datarray["parent-uri"] = $parent_item["uri"];
1923 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1925 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1926 $datarray["source"] = $xml;
1928 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1930 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1931 $body = Markdown::toBBCode($text);
1933 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1935 self::storeMentions($datarray['uri-id'], $text);
1936 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
1938 self::fetchGuid($datarray);
1940 // If we are the origin of the parent we store the original data.
1941 // We notify our followers during the item storage.
1942 if ($parent_item["origin"]) {
1943 $datarray['diaspora_signed_text'] = json_encode($data);
1946 $message_id = Item::insert($datarray);
1948 if ($message_id <= 0) {
1953 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1954 if ($datarray['uid'] == 0) {
1955 Item::distribute($message_id, json_encode($data));
1963 * processes and stores private messages
1965 * @param array $importer Array of the importer user
1966 * @param array $contact The contact of the message
1967 * @param object $data The message object
1968 * @param array $msg Array of the processed message, author handle and key
1969 * @param object $mesg The private message
1970 * @param array $conversation The conversation record to which this message belongs
1972 * @return bool "true" if it was successful
1973 * @throws \Exception
1975 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1977 $author = Strings::escapeTags(XML::unescape($data->author));
1978 $guid = Strings::escapeTags(XML::unescape($data->guid));
1979 $subject = Strings::escapeTags(XML::unescape($data->subject));
1981 // "diaspora_handle" is the element name from the old version
1982 // "author" is the element name from the new version
1983 if ($mesg->author) {
1984 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1985 } elseif ($mesg->diaspora_handle) {
1986 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1991 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1992 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1993 $msg_text = XML::unescape($mesg->text);
1994 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1996 if ($msg_conversation_guid != $guid) {
1997 Logger::log("message conversation guid does not belong to the current conversation.");
2001 $body = Markdown::toBBCode($msg_text);
2002 $message_uri = $msg_author.":".$msg_guid;
2004 $person = self::personByHandle($msg_author);
2006 return Mail::insert([
2007 'uid' => $importer['uid'],
2008 'guid' => $msg_guid,
2009 'convid' => $conversation['id'],
2010 'from-name' => $person['name'],
2011 'from-photo' => $person['photo'],
2012 'from-url' => $person['url'],
2013 'contact-id' => $contact['id'],
2014 'title' => $subject,
2016 'uri' => $message_uri,
2017 'parent-uri' => $author . ':' . $guid,
2018 'created' => $msg_created_at
2023 * Processes new private messages (answers to private messages are processed elsewhere)
2025 * @param array $importer Array of the importer user
2026 * @param array $msg Array of the processed message, author handle and key
2027 * @param object $data The message object
2029 * @return bool Success
2030 * @throws \Exception
2032 private static function receiveConversation(array $importer, $msg, $data)
2034 $author = Strings::escapeTags(XML::unescape($data->author));
2035 $guid = Strings::escapeTags(XML::unescape($data->guid));
2036 $subject = Strings::escapeTags(XML::unescape($data->subject));
2037 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2038 $participants = Strings::escapeTags(XML::unescape($data->participants));
2040 $messages = $data->message;
2042 if (!count($messages)) {
2043 Logger::log("empty conversation");
2047 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
2052 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2053 if (!DBA::isResult($conversation)) {
2055 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
2056 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
2057 intval($importer["uid"]),
2059 DBA::escape($author),
2060 DBA::escape($created_at),
2061 DBA::escape(DateTimeFormat::utcNow()),
2062 DBA::escape($subject),
2063 DBA::escape($participants)
2066 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2069 if (!$conversation) {
2070 Logger::log("unable to create conversation.");
2074 foreach ($messages as $mesg) {
2075 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
2082 * Processes "like" messages
2084 * @param array $importer Array of the importer user
2085 * @param string $sender The sender of the message
2086 * @param object $data The message object
2088 * @return int The message id of the generated like or "false" if there was an error
2089 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2090 * @throws \ImagickException
2092 private static function receiveLike(array $importer, $sender, $data)
2094 $author = Strings::escapeTags(XML::unescape($data->author));
2095 $guid = Strings::escapeTags(XML::unescape($data->guid));
2096 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2097 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
2098 $positive = Strings::escapeTags(XML::unescape($data->positive));
2100 // likes on comments aren't supported by Diaspora - only on posts
2101 // But maybe this will be supported in the future, so we will accept it.
2102 if (!in_array($parent_type, ["Post", "Comment"])) {
2106 $contact = self::allowedContactByHandle($importer, $sender, true);
2111 $message_id = self::messageExists($importer["uid"], $guid);
2116 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2117 if (!$parent_item) {
2121 $person = self::personByHandle($author);
2122 if (!is_array($person)) {
2123 Logger::log("unable to find author details");
2127 // Fetch the contact id - if we know this contact
2128 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2130 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2131 // We would accept this anyhow.
2132 if ($positive == "true") {
2133 $verb = Activity::LIKE;
2135 $verb = Activity::DISLIKE;
2140 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2142 $datarray["uid"] = $importer["uid"];
2143 $datarray["contact-id"] = $author_contact["cid"];
2144 $datarray["network"] = $author_contact["network"];
2146 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2147 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2149 $datarray["guid"] = $guid;
2150 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2152 $datarray["verb"] = $verb;
2153 $datarray["gravity"] = GRAVITY_ACTIVITY;
2154 $datarray["parent-uri"] = $parent_item["uri"];
2156 $datarray["object-type"] = Activity\ObjectType::NOTE;
2158 $datarray["body"] = $verb;
2160 // Diaspora doesn't provide a date for likes
2161 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2163 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2164 if ($parent_item["id"] != $parent_item["parent"]) {
2165 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
2166 $origin = $toplevel["origin"];
2168 $origin = $parent_item["origin"];
2171 // If we are the origin of the parent we store the original data.
2172 // We notify our followers during the item storage.
2174 $datarray['diaspora_signed_text'] = json_encode($data);
2177 $message_id = Item::insert($datarray);
2179 if ($message_id <= 0) {
2184 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2185 if ($datarray['uid'] == 0) {
2186 Item::distribute($message_id, json_encode($data));
2194 * Processes private messages
2196 * @param array $importer Array of the importer user
2197 * @param object $data The message object
2199 * @return bool Success?
2200 * @throws \Exception
2202 private static function receiveMessage(array $importer, $data)
2204 $author = Strings::escapeTags(XML::unescape($data->author));
2205 $guid = Strings::escapeTags(XML::unescape($data->guid));
2206 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2207 $text = XML::unescape($data->text);
2208 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2210 $contact = self::allowedContactByHandle($importer, $author, true);
2215 $conversation = null;
2217 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2218 $conversation = DBA::selectFirst('conv', [], $condition);
2220 if (!DBA::isResult($conversation)) {
2221 Logger::log("conversation not available.");
2225 $message_uri = $author.":".$guid;
2227 $person = self::personByHandle($author);
2229 Logger::log("unable to find author details");
2233 $body = Markdown::toBBCode($text);
2235 $body = self::replacePeopleGuid($body, $person["url"]);
2237 return Mail::insert([
2238 'uid' => $importer['uid'],
2240 'convid' => $conversation['id'],
2241 'from-name' => $person['name'],
2242 'from-photo' => $person['photo'],
2243 'from-url' => $person['url'],
2244 'contact-id' => $contact['id'],
2245 'title' => $conversation['subject'],
2248 'uri' => $message_uri,
2249 'parent-uri' => $author.":".$conversation['guid'],
2250 'created' => $created_at
2255 * Processes participations - unsupported by now
2257 * @param array $importer Array of the importer user
2258 * @param object $data The message object
2260 * @return bool success
2261 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2262 * @throws \ImagickException
2264 private static function receiveParticipation(array $importer, $data)
2266 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2267 $guid = Strings::escapeTags(XML::unescape($data->guid));
2268 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2270 $contact = self::allowedContactByHandle($importer, $author, true);
2275 if (self::messageExists($importer["uid"], $guid)) {
2279 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2280 if (!$parent_item) {
2284 if (!in_array($parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
2285 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
2289 $person = self::personByHandle($author);
2290 if (!is_array($person)) {
2291 Logger::log("Person not found: ".$author);
2295 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2297 // Store participation
2300 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2302 $datarray["uid"] = $importer["uid"];
2303 $datarray["contact-id"] = $author_contact["cid"];
2304 $datarray["network"] = $author_contact["network"];
2306 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2307 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2309 $datarray["guid"] = $guid;
2310 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2312 $datarray["verb"] = Activity::FOLLOW;
2313 $datarray["gravity"] = GRAVITY_ACTIVITY;
2314 $datarray["parent-uri"] = $parent_item["uri"];
2316 $datarray["object-type"] = Activity\ObjectType::NOTE;
2318 $datarray["body"] = Activity::FOLLOW;
2320 // Diaspora doesn't provide a date for a participation
2321 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2323 $message_id = Item::insert($datarray);
2325 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
2327 // Send all existing comments and likes to the requesting server
2328 $comments = Item::select(['id', 'uri-id', 'parent'], ['parent' => $parent_item['id']]);
2329 while ($comment = Item::fetch($comments)) {
2330 if ($comment['id'] == $comment['parent']) {
2334 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact["cid"]]);
2335 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $author_contact["cid"])) {
2336 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2339 DBA::close($comments);
2345 * Processes photos - unneeded
2347 * @param array $importer Array of the importer user
2348 * @param object $data The message object
2350 * @return bool always true
2352 private static function receivePhoto(array $importer, $data)
2354 // There doesn't seem to be a reason for this function,
2355 // since the photo data is transmitted in the status message as well
2360 * Processes poll participations - unssupported
2362 * @param array $importer Array of the importer user
2363 * @param object $data The message object
2365 * @return bool always true
2367 private static function receivePollParticipation(array $importer, $data)
2369 // We don't support polls by now
2374 * Processes incoming profile updates
2376 * @param array $importer Array of the importer user
2377 * @param object $data The message object
2379 * @return bool Success
2380 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2381 * @throws \ImagickException
2383 private static function receiveProfile(array $importer, $data)
2385 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2387 $contact = self::contactByHandle($importer["uid"], $author);
2392 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2393 $image_url = XML::unescape($data->image_url);
2394 $birthday = XML::unescape($data->birthday);
2395 $about = Markdown::toBBCode(XML::unescape($data->bio));
2396 $location = Markdown::toBBCode(XML::unescape($data->location));
2397 $searchable = (XML::unescape($data->searchable) == "true");
2398 $nsfw = (XML::unescape($data->nsfw) == "true");
2399 $tags = XML::unescape($data->tag_string);
2401 $tags = explode("#", $tags);
2404 foreach ($tags as $tag) {
2405 $tag = trim(strtolower($tag));
2411 $keywords = implode(", ", $keywords);
2413 $handle_parts = explode("@", $author);
2414 $nick = $handle_parts[0];
2417 $name = $handle_parts[0];
2420 if (preg_match("|^https?://|", $image_url) === 0) {
2421 $image_url = "http://".$handle_parts[1].$image_url;
2424 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2426 // Generic birthday. We don't know the timezone. The year is irrelevant.
2428 $birthday = str_replace("1000", "1901", $birthday);
2430 if ($birthday != "") {
2431 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2434 // this is to prevent multiple birthday notifications in a single year
2435 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2437 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2438 $birthday = $contact["bd"];
2441 $fields = ['name' => $name, 'location' => $location,
2442 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2443 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2444 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2446 if (!empty($birthday)) {
2447 $fields['bd'] = $birthday;
2450 DBA::update('contact', $fields, ['id' => $contact['id']]);
2452 // @todo Update the public contact, then update the gcontact from that
2454 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2455 "photo" => $image_url, "name" => $name, "location" => $location,
2456 "about" => $about, "birthday" => $birthday,
2457 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2458 "hide" => !$searchable, "nsfw" => $nsfw];
2460 $gcid = GContact::update($gcontact);
2462 GContact::link($gcid, $importer["uid"], $contact["id"]);
2464 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2470 * Processes incoming friend requests
2472 * @param array $importer Array of the importer user
2473 * @param array $contact The contact that send the request
2475 * @throws \Exception
2477 private static function receiveRequestMakeFriend(array $importer, array $contact)
2479 if ($contact["rel"] == Contact::SHARING) {
2482 ['rel' => Contact::FRIEND, 'writable' => true],
2483 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2489 * Processes incoming sharing notification
2491 * @param array $importer Array of the importer user
2492 * @param object $data The message object
2494 * @return bool Success
2495 * @throws \Exception
2497 private static function receiveContactRequest(array $importer, $data)
2499 $author = XML::unescape($data->author);
2500 $recipient = XML::unescape($data->recipient);
2502 if (!$author || !$recipient) {
2506 // the current protocol version doesn't know these fields
2507 // That means that we will assume their existance
2508 if (isset($data->following)) {
2509 $following = (XML::unescape($data->following) == "true");
2514 if (isset($data->sharing)) {
2515 $sharing = (XML::unescape($data->sharing) == "true");
2520 $contact = self::contactByHandle($importer["uid"], $author);
2522 // perhaps we were already sharing with this person. Now they're sharing with us.
2523 // That makes us friends.
2526 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2527 self::receiveRequestMakeFriend($importer, $contact);
2529 // refetch the contact array
2530 $contact = self::contactByHandle($importer["uid"], $author);
2532 // If we are now friends, we are sending a share message.
2533 // Normally we needn't to do so, but the first message could have been vanished.
2534 if (in_array($contact["rel"], [Contact::FRIEND])) {
2535 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2536 if (DBA::isResult($user)) {
2537 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2538 self::sendShare($user, $contact);
2543 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2544 Contact::removeFollower($importer, $contact);
2549 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2550 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2552 } elseif (!$following && !$sharing) {
2553 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2555 } elseif (!$following && $sharing) {
2556 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2557 } elseif ($following && $sharing) {
2558 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2559 } elseif ($following && !$sharing) {
2560 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2563 $ret = self::personByHandle($author);
2565 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2566 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2570 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2572 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2577 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2578 'author-link' => $ret['url']];
2580 $result = Contact::addRelationship($importer, $contact, $item, false);
2581 if ($result === true) {
2582 $contact_record = self::contactByHandle($importer['uid'], $author);
2583 if (!$contact_record) {
2584 Logger::info('unable to locate newly created contact record.');
2588 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2589 if (DBA::isResult($user)) {
2590 self::sendShare($user, $contact_record);
2592 // Send the profile data, maybe it weren't transmitted before
2593 self::sendProfile($importer['uid'], [$contact_record]);
2601 * Fetches a message with a given guid
2603 * @param string $guid message guid
2604 * @param string $orig_author handle of the original post
2605 * @return array The fetched item
2606 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2607 * @throws \ImagickException
2609 public static function originalItem($guid, $orig_author)
2612 Logger::log('Empty guid. Quitting.');
2616 // Do we already have this item?
2617 $fields = ['body', 'title', 'attach', 'app', 'created', 'object-type', 'uri', 'guid',
2618 'author-name', 'author-link', 'author-avatar'];
2619 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2620 $item = Item::selectFirst($fields, $condition);
2622 if (DBA::isResult($item)) {
2623 Logger::log("reshared message ".$guid." already exists on system.");
2625 // Maybe it is already a reshared item?
2626 // Then refetch the content, if it is a reshare from a reshare.
2627 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2628 if (self::isReshare($item["body"], true)) {
2630 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2631 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2633 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2635 // Add OEmbed and other information to the body
2636 $item["body"] = add_page_info_to_body($item["body"], false, true);
2644 if (!DBA::isResult($item)) {
2645 if (empty($orig_author)) {
2646 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2650 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2651 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2652 $stored = self::storeByGuid($guid, $server);
2655 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2656 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2657 $stored = self::storeByGuid($guid, $server);
2661 $fields = ['body', 'title', 'attach', 'app', 'created', 'object-type', 'uri', 'guid',
2662 'author-name', 'author-link', 'author-avatar'];
2663 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2664 $item = Item::selectFirst($fields, $condition);
2666 if (DBA::isResult($item)) {
2667 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2668 if (self::isReshare($item["body"], false)) {
2669 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2670 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2681 * Stores a reshare activity
2683 * @param array $item Array of reshare post
2684 * @param integer $parent_message_id Id of the parent post
2685 * @param string $guid GUID string of reshare action
2686 * @param string $author Author handle
2688 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2690 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2694 $datarray['uid'] = $item['uid'];
2695 $datarray['contact-id'] = $item['contact-id'];
2696 $datarray['network'] = $item['network'];
2698 $datarray['author-link'] = $item['author-link'];
2699 $datarray['author-id'] = $item['author-id'];
2701 $datarray['owner-link'] = $datarray['author-link'];
2702 $datarray['owner-id'] = $datarray['author-id'];
2704 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2705 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2706 $datarray['parent-uri'] = $parent['uri'];
2708 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2709 $datarray['gravity'] = GRAVITY_ACTIVITY;
2710 $datarray['object-type'] = Activity\ObjectType::NOTE;
2712 $datarray['protocol'] = $item['protocol'];
2714 $datarray['plink'] = self::plink($author, $datarray['guid']);
2715 $datarray['private'] = $item['private'];
2716 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2718 $message_id = Item::insert($datarray);
2721 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2722 if ($datarray['uid'] == 0) {
2723 Item::distribute($message_id);
2729 * Processes a reshare message
2731 * @param array $importer Array of the importer user
2732 * @param object $data The message object
2733 * @param string $xml The original XML of the message
2735 * @return int the message id
2736 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2737 * @throws \ImagickException
2739 private static function receiveReshare(array $importer, $data, $xml)
2741 $author = Strings::escapeTags(XML::unescape($data->author));
2742 $guid = Strings::escapeTags(XML::unescape($data->guid));
2743 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2744 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2745 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2746 /// @todo handle unprocessed property "provider_display_name"
2747 $public = Strings::escapeTags(XML::unescape($data->public));
2749 $contact = self::allowedContactByHandle($importer, $author, false);
2754 $message_id = self::messageExists($importer["uid"], $guid);
2759 $original_item = self::originalItem($root_guid, $root_author);
2760 if (!$original_item) {
2764 $orig_url = DI::baseUrl()."/display/".$original_item["guid"];
2768 $datarray["uid"] = $importer["uid"];
2769 $datarray["contact-id"] = $contact["id"];
2770 $datarray["network"] = Protocol::DIASPORA;
2772 $datarray["author-link"] = $contact["url"];
2773 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2775 $datarray["owner-link"] = $datarray["author-link"];
2776 $datarray["owner-id"] = $datarray["author-id"];
2778 $datarray["guid"] = $guid;
2779 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2780 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2782 $datarray["verb"] = Activity::POST;
2783 $datarray["gravity"] = GRAVITY_PARENT;
2785 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2786 $datarray["source"] = $xml;
2788 /// @todo Copy tag data from original post
2790 $prefix = share_header(
2791 $original_item["author-name"],
2792 $original_item["author-link"],
2793 $original_item["author-avatar"],
2794 $original_item["guid"],
2795 $original_item["created"],
2799 if (!empty($original_item['title'])) {
2800 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2803 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2805 Tag::storeFromBody($datarray['uri-id'], $datarray["body"]);
2807 $datarray["attach"] = $original_item["attach"];
2808 $datarray["app"] = $original_item["app"];
2810 $datarray["plink"] = self::plink($author, $guid);
2811 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2812 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2814 $datarray["object-type"] = $original_item["object-type"];
2816 self::fetchGuid($datarray);
2817 $message_id = Item::insert($datarray);
2819 self::sendParticipation($contact, $datarray);
2821 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2822 if ($root_message_id) {
2823 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2827 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2828 if ($datarray['uid'] == 0) {
2829 Item::distribute($message_id);
2838 * Processes retractions
2840 * @param array $importer Array of the importer user
2841 * @param array $contact The contact of the item owner
2842 * @param object $data The message object
2844 * @return bool success
2845 * @throws \Exception
2847 private static function itemRetraction(array $importer, array $contact, $data)
2849 $author = Strings::escapeTags(XML::unescape($data->author));
2850 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2851 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2853 $person = self::personByHandle($author);
2854 if (!is_array($person)) {
2855 Logger::log("unable to find author detail for ".$author);
2859 if (empty($contact["url"])) {
2860 $contact["url"] = $person["url"];
2863 // Fetch items that are about to be deleted
2864 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2866 // When we receive a public retraction, we delete every item that we find.
2867 if ($importer['uid'] == 0) {
2868 $condition = ['guid' => $target_guid, 'deleted' => false];
2870 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2873 $r = Item::select($fields, $condition);
2874 if (!DBA::isResult($r)) {
2875 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2879 while ($item = Item::fetch($r)) {
2880 if (strstr($item['file'], '[')) {
2881 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2885 // Fetch the parent item
2886 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2888 // Only delete it if the parent author really fits
2889 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2890 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2894 Item::markForDeletion(['id' => $item['id']]);
2896 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], Logger::DEBUG);
2903 * Receives retraction messages
2905 * @param array $importer Array of the importer user
2906 * @param string $sender The sender of the message
2907 * @param object $data The message object
2909 * @return bool Success
2910 * @throws \Exception
2912 private static function receiveRetraction(array $importer, $sender, $data)
2914 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2916 $contact = self::contactByHandle($importer["uid"], $sender);
2917 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2918 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2926 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2928 switch ($target_type) {
2933 case "StatusMessage":
2934 return self::itemRetraction($importer, $contact, $data);
2936 case "PollParticipation":
2938 // Currently unsupported
2942 Logger::log("Unknown target type ".$target_type);
2949 * Receives status messages
2951 * @param array $importer Array of the importer user
2952 * @param SimpleXMLElement $data The message object
2953 * @param string $xml The original XML of the message
2955 * @return int The message id of the newly created item
2956 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2957 * @throws \ImagickException
2959 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2961 $author = Strings::escapeTags(XML::unescape($data->author));
2962 $guid = Strings::escapeTags(XML::unescape($data->guid));
2963 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2964 $public = Strings::escapeTags(XML::unescape($data->public));
2965 $text = XML::unescape($data->text);
2966 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2968 $contact = self::allowedContactByHandle($importer, $author, false);
2973 $message_id = self::messageExists($importer["uid"], $guid);
2979 if ($data->location) {
2980 foreach ($data->location->children() as $fieldname => $data) {
2981 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2985 $body = Markdown::toBBCode($text);
2989 // Attach embedded pictures to the body
2991 foreach ($data->photo as $photo) {
2992 $body = "[img]".XML::unescape($photo->remote_photo_path).
2993 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2996 $datarray["object-type"] = Activity\ObjectType::IMAGE;
2998 $datarray["object-type"] = Activity\ObjectType::NOTE;
3000 // Add OEmbed and other information to the body
3001 if (!self::isHubzilla($contact["url"])) {
3002 $body = add_page_info_to_body($body, false, true);
3006 /// @todo enable support for polls
3007 //if ($data->poll) {
3008 // foreach ($data->poll AS $poll)
3013 /// @todo enable support for events
3015 $datarray["uid"] = $importer["uid"];
3016 $datarray["contact-id"] = $contact["id"];
3017 $datarray["network"] = Protocol::DIASPORA;
3019 $datarray["author-link"] = $contact["url"];
3020 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
3022 $datarray["owner-link"] = $datarray["author-link"];
3023 $datarray["owner-id"] = $datarray["author-id"];
3025 $datarray["guid"] = $guid;
3026 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
3027 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
3029 $datarray["verb"] = Activity::POST;
3030 $datarray["gravity"] = GRAVITY_PARENT;
3032 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
3033 $datarray["source"] = $xml;
3035 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3037 self::storeMentions($datarray['uri-id'], $text);
3038 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
3040 if ($provider_display_name != "") {
3041 $datarray["app"] = $provider_display_name;
3044 $datarray["plink"] = self::plink($author, $guid);
3045 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
3046 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3048 if (isset($address["address"])) {
3049 $datarray["location"] = $address["address"];
3052 if (isset($address["lat"]) && isset($address["lng"])) {
3053 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3056 self::fetchGuid($datarray);
3057 $message_id = Item::insert($datarray);
3059 self::sendParticipation($contact, $datarray);
3062 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
3063 if ($datarray['uid'] == 0) {
3064 Item::distribute($message_id);
3072 /* ************************************************************************************** *
3073 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3074 * ************************************************************************************** */
3077 * returnes the handle of a contact
3079 * @param array $contact contact array
3081 * @return string the handle in the format user@domain.tld
3082 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3084 private static function myHandle(array $contact)
3086 if (!empty($contact["addr"])) {
3087 return $contact["addr"];
3090 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3091 // So - just in case - we build the the address here.
3092 if ($contact["nickname"] != "") {
3093 $nick = $contact["nickname"];
3095 $nick = $contact["nick"];
3098 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
3103 * Creates the data for a private message in the new format
3105 * @param string $msg The message that is to be transmitted
3106 * @param array $user The record of the sender
3107 * @param array $contact Target of the communication
3108 * @param string $prvkey The private key of the sender
3109 * @param string $pubkey The public key of the receiver
3111 * @return string The encrypted data
3112 * @throws \Exception
3114 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
3116 Logger::log("Message: ".$msg, Logger::DATA);
3118 // without a public key nothing will work
3120 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3124 $aes_key = openssl_random_pseudo_bytes(32);
3125 $b_aes_key = base64_encode($aes_key);
3126 $iv = openssl_random_pseudo_bytes(16);
3127 $b_iv = base64_encode($iv);
3129 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3131 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3133 $encrypted_key_bundle = "";
3134 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3136 $json_object = json_encode(
3137 ["aes_key" => base64_encode($encrypted_key_bundle),
3138 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3141 return $json_object;
3145 * Creates the envelope for the "fetch" endpoint and for the new format
3147 * @param string $msg The message that is to be transmitted
3148 * @param array $user The record of the sender
3150 * @return string The envelope
3151 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3153 public static function buildMagicEnvelope($msg, array $user)
3155 $b64url_data = Strings::base64UrlEncode($msg);
3156 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3158 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3159 $type = "application/xml";
3160 $encoding = "base64url";
3161 $alg = "RSA-SHA256";
3162 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3164 // Fallback if the private key wasn't transmitted in the expected field
3165 if ($user['uprvkey'] == "") {
3166 $user['uprvkey'] = $user['prvkey'];
3169 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3170 $sig = Strings::base64UrlEncode($signature);
3172 $xmldata = ["me:env" => ["me:data" => $data,
3173 "@attributes" => ["type" => $type],
3174 "me:encoding" => $encoding,
3177 "@attributes2" => ["key_id" => $key_id]]];
3179 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3181 return XML::fromArray($xmldata, $xml, false, $namespaces);
3185 * Create the envelope for a message
3187 * @param string $msg The message that is to be transmitted
3188 * @param array $user The record of the sender
3189 * @param array $contact Target of the communication
3190 * @param string $prvkey The private key of the sender
3191 * @param string $pubkey The public key of the receiver
3192 * @param bool $public Is the message public?
3194 * @return string The message that will be transmitted to other servers
3195 * @throws \Exception
3197 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3199 // The message is put into an envelope with the sender's signature
3200 $envelope = self::buildMagicEnvelope($msg, $user);
3202 // Private messages are put into a second envelope, encrypted with the receivers public key
3204 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3211 * Creates a signature for a message
3213 * @param array $owner the array of the owner of the message
3214 * @param array $message The message that is to be signed
3216 * @return string The signature
3218 private static function signature($owner, $message)
3221 unset($sigmsg["author_signature"]);
3222 unset($sigmsg["parent_author_signature"]);
3224 $signed_text = implode(";", $sigmsg);
3226 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3230 * Transmit a message to a target server
3232 * @param array $owner the array of the item owner
3233 * @param array $contact Target of the communication
3234 * @param string $envelope The message that is to be transmitted
3235 * @param bool $public_batch Is it a public post?
3236 * @param string $guid message guid
3238 * @return int Result of the transmission
3239 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3240 * @throws \ImagickException
3242 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3244 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
3249 $logid = Strings::getRandomHex(4);
3251 // We always try to use the data from the fcontact table.
3252 // This is important for transmitting data to Friendica servers.
3253 if (!empty($contact['addr'])) {
3254 $fcontact = self::personByHandle($contact['addr']);
3255 if (!empty($fcontact)) {
3256 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3260 if (empty($dest_url)) {
3261 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3265 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3269 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3271 if (!intval(DI::config()->get("system", "diaspora_test"))) {
3272 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3274 $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3275 $return_code = $postResult->getReturnCode();
3277 Logger::log("test_mode");
3281 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3283 return $return_code ? $return_code : -1;
3288 * Build the post xml
3290 * @param string $type The message type
3291 * @param array $message The message data
3293 * @return string The post XML
3295 public static function buildPostXml($type, $message)
3297 $data = [$type => $message];
3299 return XML::fromArray($data, $xml);
3303 * Builds and transmit messages
3305 * @param array $owner the array of the item owner
3306 * @param array $contact Target of the communication
3307 * @param string $type The message type
3308 * @param array $message The message data
3309 * @param bool $public_batch Is it a public post?
3310 * @param string $guid message guid
3312 * @return int Result of the transmission
3313 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3314 * @throws \ImagickException
3316 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3318 $msg = self::buildPostXml($type, $message);
3320 Logger::log('message: '.$msg, Logger::DATA);
3321 Logger::log('send guid '.$guid, Logger::DEBUG);
3323 // Fallback if the private key wasn't transmitted in the expected field
3324 if (empty($owner['uprvkey'])) {
3325 $owner['uprvkey'] = $owner['prvkey'];
3328 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3330 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3332 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3334 return $return_code;
3338 * sends a participation (Used to get all further updates)
3340 * @param array $contact Target of the communication
3341 * @param array $item Item array
3343 * @return int The result of the transmission
3344 * @throws \Exception
3346 private static function sendParticipation(array $contact, array $item)
3348 // Don't send notifications for private postings
3349 if ($item['private'] == Item::PRIVATE) {
3353 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3355 $result = DI::cache()->get($cachekey);
3356 if (!is_null($result)) {
3360 // Fetch some user id to have a valid handle to transmit the participation.
3361 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3362 // If the item belongs to a user, we take this user id.
3363 if ($item['uid'] == 0) {
3364 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3365 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3366 $owner = User::getOwnerDataById($first_user['uid']);
3368 $owner = User::getOwnerDataById($item['uid']);
3371 $author = self::myHandle($owner);
3373 $message = ["author" => $author,
3374 "guid" => System::createUUID(),
3375 "parent_type" => "Post",
3376 "parent_guid" => $item["guid"]];
3378 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3380 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3381 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3383 return self::buildAndTransmit($owner, $contact, "participation", $message);
3387 * sends an account migration
3389 * @param array $owner the array of the item owner
3390 * @param array $contact Target of the communication
3391 * @param int $uid User ID
3393 * @return int The result of the transmission
3394 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3395 * @throws \ImagickException
3397 public static function sendAccountMigration(array $owner, array $contact, $uid)
3399 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3400 $profile = self::createProfileData($uid);
3402 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3403 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3405 $message = ["author" => $old_handle,
3406 "profile" => $profile,
3407 "signature" => $signature];
3409 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3411 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3415 * Sends a "share" message
3417 * @param array $owner the array of the item owner
3418 * @param array $contact Target of the communication
3420 * @return int The result of the transmission
3421 * @throws \Exception
3423 public static function sendShare(array $owner, array $contact)
3426 * @todo support the different possible combinations of "following" and "sharing"
3427 * Currently, Diaspora only interprets the "sharing" field
3429 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3433 switch ($contact["rel"]) {
3434 case Contact::FRIEND:
3438 case Contact::SHARING:
3442 case Contact::FOLLOWER:
3448 $message = ["author" => self::myHandle($owner),
3449 "recipient" => $contact["addr"],
3450 "following" => "true",
3451 "sharing" => "true"];
3453 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3455 return self::buildAndTransmit($owner, $contact, "contact", $message);
3459 * sends an "unshare"
3461 * @param array $owner the array of the item owner
3462 * @param array $contact Target of the communication
3464 * @return int The result of the transmission
3465 * @throws \Exception
3467 public static function sendUnshare(array $owner, array $contact)
3469 $message = ["author" => self::myHandle($owner),
3470 "recipient" => $contact["addr"],
3471 "following" => "false",
3472 "sharing" => "false"];
3474 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3476 return self::buildAndTransmit($owner, $contact, "contact", $message);
3480 * Checks a message body if it is a reshare
3482 * @param string $body The message body that is to be check
3483 * @param bool $complete Should it be a complete check or a simple check?
3485 * @return array|bool Reshare details or "false" if no reshare
3486 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3487 * @throws \ImagickException
3489 public static function isReshare($body, $complete = true)
3491 $body = trim($body);
3493 $reshared = Item::getShareArray(['body' => $body]);
3494 if (empty($reshared)) {
3498 // Skip if it isn't a pure repeated messages
3499 // Does it start with a share?
3500 if (!empty($reshared['comment']) && $complete) {
3504 if (!empty($reshared['guid']) && $complete) {
3505 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3506 $item = Item::selectFirst(['contact-id'], $condition);
3507 if (DBA::isResult($item)) {
3509 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3510 $ret["root_guid"] = $reshared['guid'];
3512 } elseif ($complete) {
3513 // We are resharing something that isn't a DFRN or Diaspora post.
3514 // So we have to return "false" on "$complete" to not trigger a reshare.
3517 } elseif (empty($reshared['guid']) && $complete) {
3523 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3524 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3525 if (!empty($contact['addr'])) {
3526 $ret['root_handle'] = $contact['addr'];
3530 if (empty($ret) && !$complete) {
3538 * Create an event array
3540 * @param integer $event_id The id of the event
3542 * @return array with event data
3543 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3545 private static function buildEvent($event_id)
3547 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3548 if (!DBA::isResult($r)) {
3556 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3557 if (!DBA::isResult($r)) {
3563 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3564 if (!DBA::isResult($r)) {
3570 $eventdata['author'] = self::myHandle($owner);
3572 if ($event['guid']) {
3573 $eventdata['guid'] = $event['guid'];
3576 $mask = DateTimeFormat::ATOM;
3578 /// @todo - establish "all day" events in Friendica
3579 $eventdata["all_day"] = "false";
3581 $eventdata['timezone'] = 'UTC';
3582 if (!$event['adjust'] && $user['timezone']) {
3583 $eventdata['timezone'] = $user['timezone'];
3586 if ($event['start']) {
3587 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3589 if ($event['finish'] && !$event['nofinish']) {
3590 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3592 if ($event['summary']) {
3593 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3595 if ($event['desc']) {
3596 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3598 if ($event['location']) {
3599 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3600 $coord = Map::getCoordinates($event['location']);
3603 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3604 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3605 $location["lat"] = $coord['lat'];
3606 $location["lng"] = $coord['lon'];
3608 $location["lat"] = 0;
3609 $location["lng"] = 0;
3611 $eventdata['location'] = $location;
3618 * Create a post (status message or reshare)
3620 * @param array $item The item that will be exported
3621 * @param array $owner the array of the item owner
3624 * 'type' -> Message type ("status_message" or "reshare")
3625 * 'message' -> Array of XML elements of the status
3626 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3627 * @throws \ImagickException
3629 public static function buildStatus(array $item, array $owner)
3631 $cachekey = "diaspora:buildStatus:".$item['guid'];
3633 $result = DI::cache()->get($cachekey);
3634 if (!is_null($result)) {
3638 $myaddr = self::myHandle($owner);
3640 $public = ($item["private"] == Item::PRIVATE ? "false" : "true");
3641 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3642 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3644 // Detect a share element and do a reshare
3645 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) {
3646 $message = ["author" => $myaddr,
3647 "guid" => $item["guid"],
3648 "created_at" => $created,
3649 "root_author" => $ret["root_handle"],
3650 "root_guid" => $ret["root_guid"],
3651 "provider_display_name" => $item["app"],
3652 "public" => $public];
3656 $title = $item["title"];
3657 $body = $item["body"];
3659 // Fetch the title from an attached link - if there is one
3660 if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3661 $page_data = BBCode::getAttachmentData($item['body']);
3662 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3663 $title = $page_data['title'];
3667 if ($item['author-link'] != $item['owner-link']) {
3668 require_once 'mod/share.php';
3669 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3670 "", $item['created'], $item['plink']) . $body . '[/share]';
3673 // convert to markdown
3674 $body = html_entity_decode(BBCode::toMarkdown($body));
3677 if (strlen($title)) {
3678 $body = "### ".html_entity_decode($title)."\n\n".$body;
3681 if ($item["attach"]) {
3682 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3684 $body .= "\n".DI::l10n()->t("Attachments:")."\n";
3685 foreach ($matches as $mtch) {
3686 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3693 if ($item["location"] != "")
3694 $location["address"] = $item["location"];
3696 if ($item["coord"] != "") {
3697 $coord = explode(" ", $item["coord"]);
3698 $location["lat"] = $coord[0];
3699 $location["lng"] = $coord[1];
3702 $message = ["author" => $myaddr,
3703 "guid" => $item["guid"],
3704 "created_at" => $created,
3705 "edited_at" => $edited,
3706 "public" => $public,
3708 "provider_display_name" => $item["app"],
3709 "location" => $location];
3711 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3712 if (!isset($location["lat"]) || !isset($location["lng"])) {
3713 unset($message["location"]);
3716 if ($item['event-id'] > 0) {
3717 $event = self::buildEvent($item['event-id']);
3718 if (count($event)) {
3719 $message['event'] = $event;
3721 if (!empty($event['location']['address']) &&
3722 !empty($event['location']['lat']) &&
3723 !empty($event['location']['lng'])) {
3724 $message['location'] = $event['location'];
3727 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3728 // $message['text'] = '';
3732 $type = "status_message";
3735 $msg = ["type" => $type, "message" => $message];
3737 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3742 private static function prependParentAuthorMention($body, $profile_url)
3744 $profile = Contact::getDetailsByURL($profile_url);
3745 if (!empty($profile['addr'])
3746 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3747 && !strstr($body, $profile['addr'])
3748 && !strstr($body, $profile_url)
3750 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3759 * @param array $item The item that will be exported
3760 * @param array $owner the array of the item owner
3761 * @param array $contact Target of the communication
3762 * @param bool $public_batch Is it a public post?
3764 * @return int The result of the transmission
3765 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3766 * @throws \ImagickException
3768 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3770 $status = self::buildStatus($item, $owner);
3772 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3776 * Creates a "like" object
3778 * @param array $item The item that will be exported
3779 * @param array $owner the array of the item owner
3781 * @return array The data for a "like"
3782 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3784 private static function constructLike(array $item, array $owner)
3786 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3787 if (!DBA::isResult($parent)) {
3791 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3793 if ($item['verb'] === Activity::LIKE) {
3795 } elseif ($item['verb'] === Activity::DISLIKE) {
3796 $positive = "false";
3799 return(["author" => self::myHandle($owner),
3800 "guid" => $item["guid"],
3801 "parent_guid" => $parent["guid"],
3802 "parent_type" => $target_type,
3803 "positive" => $positive,
3804 "author_signature" => ""]);
3808 * Creates an "EventParticipation" object
3810 * @param array $item The item that will be exported
3811 * @param array $owner the array of the item owner
3813 * @return array The data for an "EventParticipation"
3814 * @throws \Exception
3816 private static function constructAttend(array $item, array $owner)
3818 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3819 if (!DBA::isResult($parent)) {
3823 switch ($item['verb']) {
3824 case Activity::ATTEND:
3825 $attend_answer = 'accepted';
3827 case Activity::ATTENDNO:
3828 $attend_answer = 'declined';
3830 case Activity::ATTENDMAYBE:
3831 $attend_answer = 'tentative';
3834 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3838 return(["author" => self::myHandle($owner),
3839 "guid" => $item["guid"],
3840 "parent_guid" => $parent["guid"],
3841 "status" => $attend_answer,
3842 "author_signature" => ""]);
3846 * Creates the object for a comment
3848 * @param array $item The item that will be exported
3849 * @param array $owner the array of the item owner
3851 * @return array|false The data for a comment
3852 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3854 private static function constructComment(array $item, array $owner)
3856 $cachekey = "diaspora:constructComment:".$item['guid'];
3858 $result = DI::cache()->get($cachekey);
3859 if (!is_null($result)) {
3863 $toplevel_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3864 if (!DBA::isResult($toplevel_item)) {
3865 Logger::error('Missing parent conversation item', ['parent' => $item["parent"]]);
3869 $thread_parent_item = $toplevel_item;
3870 if ($item['thr-parent'] != $item['parent-uri']) {
3871 $thread_parent_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3874 $body = $item["body"];
3876 // The replied to autor mention is prepended for clarity if:
3877 // - Item replied isn't yours
3878 // - Item is public or explicit mentions are disabled
3879 // - Implicit mentions are enabled
3881 $item['author-id'] != $thread_parent_item['author-id']
3882 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3883 && !DI::config()->get('system', 'disable_implicit_mentions')
3885 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3888 $text = html_entity_decode(BBCode::toMarkdown($body));
3889 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3890 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3893 "author" => self::myHandle($owner),
3894 "guid" => $item["guid"],
3895 "created_at" => $created,
3896 "edited_at" => $edited,
3897 "parent_guid" => $toplevel_item["guid"],
3899 "author_signature" => ""
3902 // Send the thread parent guid only if it is a threaded comment
3903 if ($item['thr-parent'] != $item['parent-uri']) {
3904 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3907 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3913 * Send a like or a comment
3915 * @param array $item The item that will be exported
3916 * @param array $owner the array of the item owner
3917 * @param array $contact Target of the communication
3918 * @param bool $public_batch Is it a public post?
3920 * @return int The result of the transmission
3921 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3922 * @throws \ImagickException
3924 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3926 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3927 $message = self::constructAttend($item, $owner);
3928 $type = "event_participation";
3929 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3930 $message = self::constructLike($item, $owner);
3932 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3933 $message = self::constructComment($item, $owner);
3937 if (empty($message)) {
3941 $message["author_signature"] = self::signature($owner, $message);
3943 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3947 * Creates a message from a signature record entry
3949 * @param array $item The item that will be exported
3950 * @return array The message
3952 private static function messageFromSignature(array $item)
3954 // Split the signed text
3955 $signed_parts = explode(";", $item['signed_text']);
3957 if ($item["deleted"]) {
3958 $message = ["author" => $item['signer'],
3959 "target_guid" => $signed_parts[0],
3960 "target_type" => $signed_parts[1]];
3961 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3962 $message = ["author" => $signed_parts[4],
3963 "guid" => $signed_parts[1],
3964 "parent_guid" => $signed_parts[3],
3965 "parent_type" => $signed_parts[2],
3966 "positive" => $signed_parts[0],
3967 "author_signature" => $item['signature'],
3968 "parent_author_signature" => ""];
3970 // Remove the comment guid
3971 $guid = array_shift($signed_parts);
3973 // Remove the parent guid
3974 $parent_guid = array_shift($signed_parts);
3976 // Remove the handle
3977 $handle = array_pop($signed_parts);
3980 "author" => $handle,
3982 "parent_guid" => $parent_guid,
3983 "text" => implode(";", $signed_parts),
3984 "author_signature" => $item['signature'],
3985 "parent_author_signature" => ""
3992 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3994 * @param array $item The item that will be exported
3995 * @param array $owner the array of the item owner
3996 * @param array $contact Target of the communication
3997 * @param bool $public_batch Is it a public post?
3999 * @return int The result of the transmission
4000 * @throws \Exception
4002 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
4004 if ($item["deleted"]) {
4005 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
4006 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4012 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
4014 $msg = json_decode($item['signed_text'], true);
4017 if (is_array($msg)) {
4018 foreach ($msg as $field => $data) {
4019 if (!$item["deleted"]) {
4020 if ($field == "diaspora_handle") {
4023 if ($field == "target_type") {
4024 $field = "parent_type";
4028 $message[$field] = $data;
4031 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
4034 $message["parent_author_signature"] = self::signature($owner, $message);
4036 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
4038 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4042 * Sends a retraction (deletion) of a message, like or comment
4044 * @param array $item The item that will be exported
4045 * @param array $owner the array of the item owner
4046 * @param array $contact Target of the communication
4047 * @param bool $public_batch Is it a public post?
4048 * @param bool $relay Is the retraction transmitted from a relay?
4050 * @return int The result of the transmission
4051 * @throws \Exception
4053 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
4055 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4057 $msg_type = "retraction";
4059 if ($item['id'] == $item['parent']) {
4060 $target_type = "Post";
4061 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4062 $target_type = "Like";
4064 $target_type = "Comment";
4067 $message = ["author" => $itemaddr,
4068 "target_guid" => $item['guid'],
4069 "target_type" => $target_type];
4071 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
4073 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4079 * @param array $item The item that will be exported
4080 * @param array $owner The owner
4081 * @param array $contact Target of the communication
4083 * @return int The result of the transmission
4084 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4085 * @throws \ImagickException
4087 public static function sendMail(array $item, array $owner, array $contact)
4089 $myaddr = self::myHandle($owner);
4091 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
4092 if (!DBA::isResult($cnv)) {
4093 Logger::log("conversation not found.");
4097 $body = BBCode::toMarkdown($item["body"]);
4098 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4101 "author" => $myaddr,
4102 "guid" => $item["guid"],
4103 "conversation_guid" => $cnv["guid"],
4105 "created_at" => $created,
4108 if ($item["reply"]) {
4113 "author" => $cnv["creator"],
4114 "guid" => $cnv["guid"],
4115 "subject" => $cnv["subject"],
4116 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4117 "participants" => $cnv["recips"],
4121 $type = "conversation";
4124 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4128 * Split a name into first name and last name
4130 * @param string $name The name
4132 * @return array The array with "first" and "last"
4134 public static function splitName($name) {
4135 $name = trim($name);
4137 // Is the name longer than 64 characters? Then cut the rest of it.
4138 if (strlen($name) > 64) {
4139 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4140 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4142 $name = substr($name, 0, 64);
4146 // Take the first word as first name
4147 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4148 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4149 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4150 return ['first' => $first, 'last' => $last];
4153 // Take the last word as last name
4154 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4155 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4157 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4158 return ['first' => $first, 'last' => $last];
4161 // Take the first 32 characters if there is no space in the first 32 characters
4162 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4163 $first = substr($name, 0, 32);
4164 $last = substr($name, 32);
4165 return ['first' => $first, 'last' => $last];
4168 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4169 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4171 // Check if the last name is longer than 32 characters
4172 if (strlen($last) > 32) {
4173 if (strpos($last, ' ') <= 32) {
4174 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4176 $last = substr($last, 0, 32);
4180 return ['first' => $first, 'last' => $last];
4184 * Create profile data
4186 * @param int $uid The user id
4188 * @return array The profile data
4189 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4191 private static function createProfileData($uid)
4193 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
4194 if (!DBA::isResult($profile)) {
4198 $handle = $profile["addr"];
4200 $split_name = self::splitName($profile['name']);
4201 $first = $split_name['first'];
4202 $last = $split_name['last'];
4204 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4205 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4206 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4207 $searchable = ($profile['net-publish'] ? 'true' : 'false');
4213 if ($searchable === 'true') {
4216 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4217 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4221 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4224 $about = BBCode::toMarkdown($profile['about']);
4226 $location = $profile['location'];
4228 if ($profile['pub_keywords']) {
4229 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4230 $kw = str_replace(' ', ' ', $kw);
4231 $arr = explode(' ', $kw);
4233 for ($x = 0; $x < 5; $x ++) {
4234 if (!empty($arr[$x])) {
4235 $tags .= '#'. trim($arr[$x]) .' ';
4240 $tags = trim($tags);
4243 return ["author" => $handle,
4244 "first_name" => $first,
4245 "last_name" => $last,
4246 "image_url" => $large,
4247 "image_url_medium" => $medium,
4248 "image_url_small" => $small,
4251 "location" => $location,
4252 "searchable" => $searchable,
4254 "tag_string" => $tags];
4258 * Sends profile data
4260 * @param int $uid The user id
4261 * @param bool $recips optional, default false
4263 * @throws \Exception
4265 public static function sendProfile($uid, $recips = false)
4271 $owner = User::getOwnerDataById($uid);
4278 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4279 AND `uid` = %d AND `rel` != %d",
4280 DBA::escape(Protocol::DIASPORA),
4282 intval(Contact::SHARING)
4290 $message = self::createProfileData($uid);
4292 // @ToDo Split this into single worker jobs
4293 foreach ($recips as $recip) {
4294 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4295 self::buildAndTransmit($owner, $recip, "profile", $message);
4300 * Creates the signature for likes that are created on our system
4302 * @param integer $uid The user of that comment
4303 * @param array $item Item array
4305 * @return array Signed content
4306 * @throws \Exception
4308 public static function createLikeSignature($uid, array $item)
4310 $owner = User::getOwnerDataById($uid);
4311 if (empty($owner)) {
4312 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4316 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4320 $message = self::constructLike($item, $owner);
4321 if ($message === false) {
4325 $message["author_signature"] = self::signature($owner, $message);
4331 * Creates the signature for Comments that are created on our system
4333 * @param integer $uid The user of that comment
4334 * @param array $item Item array
4336 * @return array Signed content
4337 * @throws \Exception
4339 public static function createCommentSignature($uid, array $item)
4341 $owner = User::getOwnerDataById($uid);
4342 if (empty($owner)) {
4343 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4347 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4348 $item['thr-parent'] = $item['parent-uri'];
4350 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4351 if (!DBA::isResult($parent)) {
4355 $item['parent-uri'] = $parent['parent-uri'];
4357 $message = self::constructComment($item, $owner);
4358 if ($message === false) {
4362 $message["author_signature"] = self::signature($owner, $message);