3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol;
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\Markdown;
27 use Friendica\Core\Cache\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\GContact;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\ItemDeliveryData;
40 use Friendica\Model\Mail;
41 use Friendica\Model\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'];
126 // All tags of the current post
127 $tags = DBA::select('tag-view', ['term'], ['uri-id' => $parent['uri-id'], 'type' => Tag::HASHTAG]);
129 while ($tag = DBA::fetch($tags)) {
130 $taglist[] = $tag['name'];
134 // All servers who wants content with this tag
136 if (!empty($taglist)) {
137 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
138 while ($server = DBA::fetch($tagserver)) {
139 $tagserverlist[] = $server['gserver-id'];
143 // All adresses with the given id
144 if (!empty($tagserverlist)) {
145 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
146 while ($server = DBA::fetch($servers)) {
147 $serverlist[$server['url']] = $server['url'];
152 // Now we are collecting all relay contacts
153 foreach ($serverlist as $server_url) {
154 // We don't send messages to ourselves
155 if (Strings::compareLink($server_url, DI::baseUrl())) {
158 $contact = self::getRelayContact($server_url);
159 if (is_bool($contact)) {
164 foreach ($contacts as $entry) {
165 if ($entry['batch'] == $contact['batch']) {
171 $contacts[] = $contact;
179 * Return a contact for a given server address or creates a dummy entry
181 * @param string $server_url The url of the server
182 * @param array $fields Fieldlist
183 * @return array with the contact
186 private static function getRelayContact(string $server_url, array $fields = ['batch', 'id', 'url', 'name', 'network', 'protocol', 'archive', 'blocked'])
188 // Fetch the relay contact
189 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
190 'contact-type' => Contact::TYPE_RELAY];
191 $contact = DBA::selectFirst('contact', $fields, $condition);
193 if (DBA::isResult($contact)) {
194 if ($contact['archive'] || $contact['blocked']) {
199 self::setRelayContact($server_url);
201 $contact = DBA::selectFirst('contact', $fields, $condition);
202 if (DBA::isResult($contact)) {
207 // It should never happen that we arrive here
212 * Update or insert a relay contact
214 * @param string $server_url The url of the server
215 * @param array $network_fields Optional network specific fields
218 public static function setRelayContact($server_url, array $network_fields = [])
220 $fields = ['created' => DateTimeFormat::utcNow(),
221 'name' => 'relay', 'nick' => 'relay', 'url' => $server_url,
222 'nurl' => Strings::normaliseLink($server_url),
223 'network' => Protocol::DIASPORA, 'uid' => 0,
224 'batch' => $server_url . '/receive/public',
225 'rel' => Contact::FOLLOWER, 'blocked' => false,
226 'pending' => false, 'writable' => true,
227 'baseurl' => $server_url, 'contact-type' => Contact::TYPE_RELAY];
229 $fields = array_merge($fields, $network_fields);
231 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url)];
232 $old = DBA::selectFirst('contact', [], $condition);
233 if (DBA::isResult($old)) {
234 unset($fields['created']);
235 $condition = ['id' => $old['id']];
237 Logger::info('Update relay contact', ['fields' => $fields, 'condition' => $condition]);
238 DBA::update('contact', $fields, $condition, $old);
240 Logger::info('Create relay contact', ['fields' => $fields]);
241 Contact::insert($fields);
246 * Return a list of participating contacts for a thread
248 * This is used for the participation feature.
249 * One of the parameters is a contact array.
250 * This is done to avoid duplicates.
252 * @param integer $thread The id of the thread
253 * @param array $contacts The previously fetched contacts
255 * @return array of relay servers
258 public static function participantsForThread($thread, array $contacts)
260 $participation = DBA::select('participation-view', [], ['iid' => $thread]);
262 while ($contact = DBA::fetch($participation)) {
263 if (empty($contact['protocol'])) {
264 $contact['protocol'] = $contact['network'];
268 foreach ($contacts as $entry) {
269 if ($entry['batch'] == $contact['batch']) {
275 $contacts[] = $contact;
279 DBA::close($participation);
285 * repairs a signature that was double encoded
287 * The function is unused at the moment. It was copied from the old implementation.
289 * @param string $signature The signature
290 * @param string $handle The handle of the signature owner
291 * @param integer $level This value is only set inside this function to avoid endless loops
293 * @return string the repaired signature
296 private static function repairSignature($signature, $handle = "", $level = 1)
298 if ($signature == "") {
302 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
303 $signature = base64_decode($signature);
304 Logger::log("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, Logger::DEBUG);
306 // Do a recursive call to be able to fix even multiple levels
308 $signature = self::repairSignature($signature, $handle, ++$level);
316 * verify the envelope and return the verified data
318 * @param string $envelope The magic envelope
320 * @return string verified data
321 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
322 * @throws \ImagickException
324 private static function verifyMagicEnvelope($envelope)
326 $basedom = XML::parseString($envelope);
328 if (!is_object($basedom)) {
329 Logger::log("Envelope is no XML file");
333 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
335 if (sizeof($children) == 0) {
336 Logger::log("XML has no children");
342 $data = Strings::base64UrlDecode($children->data);
343 $type = $children->data->attributes()->type[0];
345 $encoding = $children->encoding;
347 $alg = $children->alg;
349 $sig = Strings::base64UrlDecode($children->sig);
350 $key_id = $children->sig->attributes()->key_id[0];
352 $handle = Strings::base64UrlDecode($key_id);
355 $b64url_data = Strings::base64UrlEncode($data);
356 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
358 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
361 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
365 $key = self::key($handle);
367 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
371 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
373 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
381 * encrypts data via AES
383 * @param string $key The AES key
384 * @param string $iv The IV (is used for CBC encoding)
385 * @param string $data The data that is to be encrypted
387 * @return string encrypted data
389 private static function aesEncrypt($key, $iv, $data)
391 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
395 * decrypts data via AES
397 * @param string $key The AES key
398 * @param string $iv The IV (is used for CBC encoding)
399 * @param string $encrypted The encrypted data
401 * @return string decrypted data
403 private static function aesDecrypt($key, $iv, $encrypted)
405 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
409 * Decodes incoming Diaspora message in the new format
411 * @param string $raw raw post message
412 * @param string $privKey The private key of the importer
413 * @param boolean $no_exit Don't do an http exit on error
416 * 'message' -> decoded Diaspora XML message
417 * 'author' -> author diaspora handle
418 * 'key' -> author public key (converted to pkcs#8)
419 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
420 * @throws \ImagickException
422 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
424 $data = json_decode($raw);
426 // Is it a private post? Then decrypt the outer Salmon
427 if (is_object($data)) {
428 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
429 $ciphertext = base64_decode($data->encrypted_magic_envelope);
431 $outer_key_bundle = '';
432 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
433 $j_outer_key_bundle = json_decode($outer_key_bundle);
435 if (!is_object($j_outer_key_bundle)) {
436 Logger::log('Outer Salmon did not verify. Discarding.');
440 throw new \Friendica\Network\HTTPException\BadRequestException();
444 $outer_iv = base64_decode($j_outer_key_bundle->iv);
445 $outer_key = base64_decode($j_outer_key_bundle->key);
447 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
452 $basedom = XML::parseString($xml);
454 if (!is_object($basedom)) {
455 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
459 throw new \Friendica\Network\HTTPException\BadRequestException();
463 $base = $basedom->children(ActivityNamespace::SALMON_ME);
465 // Not sure if this cleaning is needed
466 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
468 // Build the signed data
469 $type = $base->data[0]->attributes()->type[0];
470 $encoding = $base->encoding;
472 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
474 // This is the signature
475 $signature = Strings::base64UrlDecode($base->sig);
477 // Get the senders' public key
478 $key_id = $base->sig[0]->attributes()->key_id[0];
479 $author_addr = base64_decode($key_id);
480 if ($author_addr == '') {
481 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
485 throw new \Friendica\Network\HTTPException\BadRequestException();
489 $key = self::key($author_addr);
491 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
495 throw new \Friendica\Network\HTTPException\BadRequestException();
499 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
501 Logger::log('Message did not verify. Discarding.');
505 throw new \Friendica\Network\HTTPException\BadRequestException();
509 return ['message' => (string)Strings::base64UrlDecode($base->data),
510 'author' => XML::unescape($author_addr),
511 'key' => (string)$key];
515 * Decodes incoming Diaspora message in the deprecated format
517 * @param string $xml urldecoded Diaspora salmon
518 * @param string $privKey The private key of the importer
521 * 'message' -> decoded Diaspora XML message
522 * 'author' -> author diaspora handle
523 * 'key' -> author public key (converted to pkcs#8)
524 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
525 * @throws \ImagickException
527 public static function decode(string $xml, string $privKey = '')
530 $basedom = XML::parseString($xml);
532 if (!is_object($basedom)) {
533 Logger::log("XML is not parseable.");
536 $children = $basedom->children('https://joindiaspora.com/protocol');
538 $inner_aes_key = null;
541 if ($children->header) {
543 $author_link = str_replace('acct:', '', $children->header->author_id);
545 // This happens with posts from a relais
546 if (empty($privKey)) {
547 Logger::log("This is no private post in the old format", Logger::DEBUG);
551 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
553 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
554 $ciphertext = base64_decode($encrypted_header->ciphertext);
556 $outer_key_bundle = '';
557 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
559 $j_outer_key_bundle = json_decode($outer_key_bundle);
561 $outer_iv = base64_decode($j_outer_key_bundle->iv);
562 $outer_key = base64_decode($j_outer_key_bundle->key);
564 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
566 Logger::log('decrypted: '.$decrypted, Logger::DEBUG);
567 $idom = XML::parseString($decrypted);
569 $inner_iv = base64_decode($idom->iv);
570 $inner_aes_key = base64_decode($idom->aes_key);
572 $author_link = str_replace('acct:', '', $idom->author_id);
575 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
577 // figure out where in the DOM tree our data is hiding
580 if ($dom->provenance->data) {
581 $base = $dom->provenance;
582 } elseif ($dom->env->data) {
584 } elseif ($dom->data) {
589 Logger::log('unable to locate salmon data in xml');
590 throw new \Friendica\Network\HTTPException\BadRequestException();
594 // Stash the signature away for now. We have to find their key or it won't be good for anything.
595 $signature = Strings::base64UrlDecode($base->sig);
599 // strip whitespace so our data element will return to one big base64 blob
600 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
603 // stash away some other stuff for later
605 $type = $base->data[0]->attributes()->type[0];
606 $keyhash = $base->sig[0]->attributes()->keyhash[0];
607 $encoding = $base->encoding;
611 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
615 $data = Strings::base64UrlDecode($data);
619 $inner_decrypted = $data;
621 // Decode the encrypted blob
622 $inner_encrypted = base64_decode($data);
623 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
627 Logger::log('Could not retrieve author URI.');
628 throw new \Friendica\Network\HTTPException\BadRequestException();
630 // Once we have the author URI, go to the web and try to find their public key
631 // (first this will look it up locally if it is in the fcontact cache)
632 // This will also convert diaspora public key from pkcs#1 to pkcs#8
634 Logger::log('Fetching key for '.$author_link);
635 $key = self::key($author_link);
638 Logger::log('Could not retrieve author key.');
639 throw new \Friendica\Network\HTTPException\BadRequestException();
642 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
645 Logger::log('Message did not verify. Discarding.');
646 throw new \Friendica\Network\HTTPException\BadRequestException();
649 Logger::log('Message verified.');
651 return ['message' => (string)$inner_decrypted,
652 'author' => XML::unescape($author_link),
653 'key' => (string)$key];
658 * Dispatches public messages and find the fitting receivers
660 * @param array $msg The post that will be dispatched
662 * @return int The message id of the generated message, "true" or "false" if there was an error
663 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
664 * @throws \ImagickException
666 public static function dispatchPublic($msg)
668 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
670 Logger::log("diaspora is disabled");
674 if (!($fields = self::validPosting($msg))) {
675 Logger::log("Invalid posting");
679 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
680 $success = self::dispatch($importer, $msg, $fields);
686 * Dispatches the different message types to the different functions
688 * @param array $importer Array of the importer user
689 * @param array $msg The post that will be dispatched
690 * @param SimpleXMLElement $fields SimpleXML object that contains the message
692 * @return int The message id of the generated message, "true" or "false" if there was an error
693 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
694 * @throws \ImagickException
696 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
698 // The sender is the handle of the contact that sent the message.
699 // This will often be different with relayed messages (for example "like" and "comment")
700 $sender = $msg["author"];
702 // This is only needed for private postings since this is already done for public ones before
703 if (is_null($fields)) {
705 if (!($fields = self::validPosting($msg))) {
706 Logger::log("Invalid posting");
713 $type = $fields->getName();
715 Logger::log("Received message type ".$type." from ".$sender." for user ".$importer["uid"], Logger::DEBUG);
718 case "account_migration":
720 Logger::log('Message with type ' . $type . ' is not private, quitting.');
723 return self::receiveAccountMigration($importer, $fields);
725 case "account_deletion":
726 return self::receiveAccountDeletion($fields);
729 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
733 Logger::log('Message with type ' . $type . ' is not private, quitting.');
736 return self::receiveContactRequest($importer, $fields);
740 Logger::log('Message with type ' . $type . ' is not private, quitting.');
743 return self::receiveConversation($importer, $msg, $fields);
746 return self::receiveLike($importer, $sender, $fields);
750 Logger::log('Message with type ' . $type . ' is not private, quitting.');
753 return self::receiveMessage($importer, $fields);
755 case "participation":
757 Logger::log('Message with type ' . $type . ' is not private, quitting.');
760 return self::receiveParticipation($importer, $fields);
762 case "photo": // Not implemented
763 return self::receivePhoto($importer, $fields);
765 case "poll_participation": // Not implemented
766 return self::receivePollParticipation($importer, $fields);
770 Logger::log('Message with type ' . $type . ' is not private, quitting.');
773 return self::receiveProfile($importer, $fields);
776 return self::receiveReshare($importer, $fields, $msg["message"]);
779 return self::receiveRetraction($importer, $sender, $fields);
781 case "status_message":
782 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
785 Logger::log("Unknown message type ".$type);
791 * Checks if a posting is valid and fetches the data fields.
793 * This function does not only check the signature.
794 * It also does the conversion between the old and the new diaspora format.
796 * @param array $msg Array with the XML, the sender handle and the sender signature
798 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
799 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
800 * @throws \ImagickException
802 private static function validPosting($msg)
804 $data = XML::parseString($msg["message"]);
806 if (!is_object($data)) {
807 Logger::log("No valid XML ".$msg["message"], Logger::DEBUG);
811 // Is this the new or the old version?
812 if ($data->getName() == "XML") {
814 foreach ($data->post->children() as $child) {
822 $type = $element->getName();
825 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
827 // All retractions are handled identically from now on.
828 // In the new version there will only be "retraction".
829 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
830 $type = "retraction";
832 if ($type == "request") {
836 $fields = new SimpleXMLElement("<".$type."/>");
839 $author_signature = null;
840 $parent_author_signature = null;
842 foreach ($element->children() as $fieldname => $entry) {
844 // Translation for the old XML structure
845 if ($fieldname == "diaspora_handle") {
846 $fieldname = "author";
848 if ($fieldname == "participant_handles") {
849 $fieldname = "participants";
851 if (in_array($type, ["like", "participation"])) {
852 if ($fieldname == "target_type") {
853 $fieldname = "parent_type";
856 if ($fieldname == "sender_handle") {
857 $fieldname = "author";
859 if ($fieldname == "recipient_handle") {
860 $fieldname = "recipient";
862 if ($fieldname == "root_diaspora_id") {
863 $fieldname = "root_author";
865 if ($type == "status_message") {
866 if ($fieldname == "raw_message") {
870 if ($type == "retraction") {
871 if ($fieldname == "post_guid") {
872 $fieldname = "target_guid";
874 if ($fieldname == "type") {
875 $fieldname = "target_type";
880 if (($fieldname == "author_signature") && ($entry != "")) {
881 $author_signature = base64_decode($entry);
882 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
883 $parent_author_signature = base64_decode($entry);
884 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
885 if ($signed_data != "") {
889 $signed_data .= $entry;
891 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
892 || ($orig_type == "relayable_retraction")
894 XML::copy($entry, $fields, $fieldname);
898 // This is something that shouldn't happen at all.
899 if (in_array($type, ["status_message", "reshare", "profile"])) {
900 if ($msg["author"] != $fields->author) {
901 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
906 // Only some message types have signatures. So we quit here for the other types.
907 if (!in_array($type, ["comment", "like"])) {
910 // No author_signature? This is a must, so we quit.
911 if (!isset($author_signature)) {
912 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
916 if (isset($parent_author_signature)) {
917 $key = self::key($msg["author"]);
919 Logger::log("No key found for parent author ".$msg["author"], Logger::DEBUG);
923 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
924 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);
929 $key = self::key($fields->author);
931 Logger::log("No key found for author ".$fields->author, Logger::DEBUG);
935 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
936 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);
944 * Fetches the public key for a given handle
946 * @param string $handle The handle
948 * @return string The public key
949 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
950 * @throws \ImagickException
952 private static function key($handle)
954 $handle = strval($handle);
956 Logger::log("Fetching diaspora key for: ".$handle);
958 $r = self::personByHandle($handle);
967 * Fetches data for a given handle
969 * @param string $handle The handle
970 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
972 * @return array the queried data
973 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
974 * @throws \ImagickException
976 public static function personByHandle($handle, $update = null)
978 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
979 if (!DBA::isResult($person)) {
980 $urls = [$handle, str_replace('http://', 'https://', $handle), Strings::normaliseLink($handle)];
981 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'url' => $urls]);
984 if (DBA::isResult($person)) {
985 Logger::debug("In cache " . print_r($person, true));
987 if (is_null($update)) {
988 // update record occasionally so it doesn't get stale
989 $d = strtotime($person["updated"]." +00:00");
990 if ($d < strtotime("now - 14 days")) {
994 if ($person["guid"] == "") {
998 } elseif (is_null($update)) {
999 $update = !DBA::isResult($person);
1005 Logger::log("create or refresh", Logger::DEBUG);
1006 $r = Probe::uri($handle, Protocol::DIASPORA);
1008 // Note that Friendica contacts will return a "Diaspora person"
1009 // if Diaspora connectivity is enabled on their server
1010 if ($r && ($r["network"] === Protocol::DIASPORA)) {
1011 self::updateFContact($r);
1013 $person = self::personByHandle($handle, false);
1021 * Updates the fcontact table
1023 * @param array $arr The fcontact data
1024 * @throws \Exception
1026 private static function updateFContact($arr)
1028 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
1029 'request' => $arr["request"], 'nick' => $arr["nick"],
1030 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
1031 'batch' => $arr["batch"], 'notify' => $arr["notify"],
1032 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
1033 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
1034 'updated' => DateTimeFormat::utcNow()];
1036 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
1038 DBA::update('fcontact', $fields, $condition, true);
1042 * get a handle (user@domain.tld) from a given contact id
1044 * @param int $contact_id The id in the contact table
1045 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1047 * @return string the handle
1048 * @throws \Exception
1050 private static function handleFromContact($contact_id, $pcontact_id = 0)
1054 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
1056 if ($pcontact_id != 0) {
1057 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
1059 if (DBA::isResult($contact) && !empty($contact["addr"])) {
1060 return strtolower($contact["addr"]);
1065 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1069 if (DBA::isResult($r)) {
1072 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1074 if ($contact['addr'] != "") {
1075 $handle = $contact['addr'];
1077 $baseurl_start = strpos($contact['url'], '://') + 3;
1078 // allows installations in a subdirectory--not sure how Diaspora will handle
1079 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1080 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1081 $handle = $contact['nick'].'@'.$baseurl;
1085 return strtolower($handle);
1089 * get a url (scheme://domain.tld/u/user) from a given Diaspora*
1092 * @param mixed $fcontact_guid Hexadecimal string guid
1094 * @return string the contact url or null
1095 * @throws \Exception
1097 public static function urlFromContactGuid($fcontact_guid)
1099 Logger::log("fcontact guid is ".$fcontact_guid, Logger::DEBUG);
1102 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1103 DBA::escape(Protocol::DIASPORA),
1104 DBA::escape($fcontact_guid)
1107 if (DBA::isResult($r)) {
1108 return $r[0]['url'];
1115 * Get a contact id for a given handle
1117 * @todo Move to Friendica\Model\Contact
1119 * @param int $uid The user id
1120 * @param string $handle The handle in the format user@domain.tld
1122 * @return array Contact data
1123 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1124 * @throws \ImagickException
1126 private static function contactByHandle($uid, $handle)
1128 $cid = Contact::getIdForURL($handle, $uid);
1130 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1134 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1135 if (!DBA::isResult($contact)) {
1136 // This here shouldn't happen at all
1137 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1145 * Checks if the given contact url does support ActivityPub
1147 * @param string $url profile url
1148 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1150 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1151 * @throws \ImagickException
1153 public static function isSupportedByContactUrl($url, $update = null)
1155 return !empty(self::personByHandle($url, $update));
1159 * Check if posting is allowed for this contact
1161 * @param array $importer Array of the importer user
1162 * @param array $contact The contact that is checked
1163 * @param bool $is_comment Is the check for a comment?
1165 * @return bool is the contact allowed to post?
1167 private static function postAllow(array $importer, array $contact, $is_comment = false)
1170 * Perhaps we were already sharing with this person. Now they're sharing with us.
1171 * That makes us friends.
1172 * Normally this should have handled by getting a request - but this could get lost
1174 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1175 // It is not removed by now. Possibly the code is needed?
1176 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1179 // array('rel' => Contact::FRIEND, 'writable' => true),
1180 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1183 // $contact["rel"] = Contact::FRIEND;
1184 // Logger::log("defining user ".$contact["nick"]." as friend");
1187 // Contact server is blocked
1188 if (Network::isUrlBlocked($contact['url'])) {
1190 // We don't seem to like that person
1191 } elseif ($contact["blocked"]) {
1192 // Maybe blocked, don't accept.
1194 // We are following this person?
1195 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1196 // Yes, then it is fine.
1198 // Is it a post to a community?
1199 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1202 // Is the message a global user or a comment?
1203 } elseif (($importer["uid"] == 0) || $is_comment) {
1204 // Messages for the global users and comments are always accepted
1212 * Fetches the contact id for a handle and checks if posting is allowed
1214 * @param array $importer Array of the importer user
1215 * @param string $handle The checked handle in the format user@domain.tld
1216 * @param bool $is_comment Is the check for a comment?
1218 * @return array The contact data
1219 * @throws \Exception
1221 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1223 $contact = self::contactByHandle($importer["uid"], $handle);
1225 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1226 // If a contact isn't found, we accept it anyway if it is a comment
1227 if ($is_comment && ($importer["uid"] != 0)) {
1228 return self::contactByHandle(0, $handle);
1229 } elseif ($is_comment) {
1236 if (!self::postAllow($importer, $contact, $is_comment)) {
1237 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1244 * Does the message already exists on the system?
1246 * @param int $uid The user id
1247 * @param string $guid The guid of the message
1249 * @return int|bool message id if the message already was stored into the system - or false.
1250 * @throws \Exception
1252 private static function messageExists($uid, $guid)
1254 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1255 if (DBA::isResult($item)) {
1256 Logger::log("message ".$guid." already exists for user ".$uid);
1264 * Checks for links to posts in a message
1266 * @param array $item The item array
1269 private static function fetchGuid(array $item)
1271 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1272 preg_replace_callback(
1274 function ($match) use ($item) {
1275 self::fetchGuidSub($match, $item);
1280 preg_replace_callback(
1281 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1282 function ($match) use ($item) {
1283 self::fetchGuidSub($match, $item);
1290 * Checks for relative /people/* links in an item body to match local
1291 * contacts or prepends the remote host taken from the author link.
1293 * @param string $body The item body to replace links from
1294 * @param string $author_link The author link for missing local contact fallback
1296 * @return string the replaced string
1298 public static function replacePeopleGuid($body, $author_link)
1300 $return = preg_replace_callback(
1301 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1302 function ($match) use ($author_link) {
1304 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1305 // 1 => '0123456789abcdef'
1307 $handle = self::urlFromContactGuid($match[1]);
1310 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1312 // No local match, restoring absolute remote URL from author scheme and host
1313 $author_url = parse_url($author_link);
1314 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1326 * sub function of "fetchGuid" which checks for links in messages
1328 * @param array $match array containing a link that has to be checked for a message link
1329 * @param array $item The item array
1331 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1332 * @throws \ImagickException
1334 private static function fetchGuidSub($match, $item)
1336 if (!self::storeByGuid($match[1], $item["author-link"])) {
1337 self::storeByGuid($match[1], $item["owner-link"]);
1342 * Fetches an item with a given guid from a given server
1344 * @param string $guid the message guid
1345 * @param string $server The server address
1346 * @param int $uid The user id of the user
1348 * @return int the message id of the stored message or false
1349 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1350 * @throws \ImagickException
1352 private static function storeByGuid($guid, $server, $uid = 0)
1354 $serverparts = parse_url($server);
1356 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1360 $server = $serverparts["scheme"]."://".$serverparts["host"];
1362 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1364 $msg = self::message($guid, $server);
1370 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1372 // Now call the dispatcher
1373 return self::dispatchPublic($msg);
1377 * Fetches a message from a server
1379 * @param string $guid message guid
1380 * @param string $server The url of the server
1381 * @param int $level Endless loop prevention
1384 * 'message' => The message XML
1385 * 'author' => The author handle
1386 * 'key' => The public key of the author
1387 * @throws \Exception
1389 private static function message($guid, $server, $level = 0)
1395 // This will work for new Diaspora servers and Friendica servers from 3.5
1396 $source_url = $server."/fetch/post/".urlencode($guid);
1398 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1400 $envelope = Network::fetchUrl($source_url);
1402 Logger::log("Envelope was fetched.", Logger::DEBUG);
1403 $x = self::verifyMagicEnvelope($envelope);
1405 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1407 Logger::log("Envelope was verified.", Logger::DEBUG);
1417 $source_xml = XML::parseString($x);
1419 if (!is_object($source_xml)) {
1423 if ($source_xml->post->reshare) {
1424 // Reshare of a reshare - old Diaspora version
1425 Logger::log("Message is a reshare", Logger::DEBUG);
1426 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1427 } elseif ($source_xml->getName() == "reshare") {
1428 // Reshare of a reshare - new Diaspora version
1429 Logger::log("Message is a new reshare", Logger::DEBUG);
1430 return self::message($source_xml->root_guid, $server, ++$level);
1435 // Fetch the author - for the old and the new Diaspora version
1436 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1437 $author = (string)$source_xml->post->status_message->diaspora_handle;
1438 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1439 $author = (string)$source_xml->author;
1442 // If this isn't a "status_message" then quit
1444 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1448 $msg = ["message" => $x, "author" => $author];
1450 $msg["key"] = self::key($msg["author"]);
1456 * Fetches an item with a given URL
1458 * @param string $url the message url
1460 * @return int the message id of the stored message or false
1461 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1462 * @throws \ImagickException
1464 public static function fetchByURL($url, $uid = 0)
1466 // Check for Diaspora (and Friendica) typical paths
1467 if (!preg_match("=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1468 Logger::info('Invalid url', ['url' => $url]);
1472 $guid = urldecode($matches[2]);
1474 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1475 if (DBA::isResult($item)) {
1476 Logger::info('Found', ['id' => $item['id']]);
1480 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1481 $ret = self::storeByGuid($guid, $matches[1], $uid);
1482 Logger::info('Result', ['ret' => $ret]);
1484 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1485 if (DBA::isResult($item)) {
1486 Logger::info('Found', ['id' => $item['id']]);
1489 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1495 * Fetches the item record of a given guid
1497 * @param int $uid The user id
1498 * @param string $guid message guid
1499 * @param string $author The handle of the item
1500 * @param array $contact The contact of the item owner
1502 * @return array the item record
1503 * @throws \Exception
1505 private static function parentItem($uid, $guid, $author, array $contact)
1507 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1508 'author-name', 'author-link', 'author-avatar',
1509 'owner-name', 'owner-link', 'owner-avatar'];
1510 $condition = ['uid' => $uid, 'guid' => $guid];
1511 $item = Item::selectFirst($fields, $condition);
1513 if (!DBA::isResult($item)) {
1514 $person = self::personByHandle($author);
1515 $result = self::storeByGuid($guid, $person["url"], $uid);
1517 // We don't have an url for items that arrived at the public dispatcher
1518 if (!$result && !empty($contact["url"])) {
1519 $result = self::storeByGuid($guid, $contact["url"], $uid);
1523 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1525 $item = Item::selectFirst($fields, $condition);
1529 if (!DBA::isResult($item)) {
1530 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1533 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1539 * returns contact details
1541 * @param array $def_contact The default contact if the person isn't found
1542 * @param array $person The record of the person
1543 * @param int $uid The user id
1546 * 'cid' => contact id
1547 * 'network' => network type
1548 * @throws \Exception
1550 private static function authorContactByUrl($def_contact, $person, $uid)
1552 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1553 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1554 if (DBA::isResult($contact)) {
1555 $cid = $contact["id"];
1556 $network = $contact["network"];
1558 $cid = $def_contact["id"];
1559 $network = Protocol::DIASPORA;
1562 return ["cid" => $cid, "network" => $network];
1566 * Is the profile a hubzilla profile?
1568 * @param string $url The profile link
1570 * @return bool is it a hubzilla server?
1572 private static function isHubzilla($url)
1574 return(strstr($url, '/channel/'));
1578 * Generate a post link with a given handle and message guid
1580 * @param string $addr The user handle
1581 * @param string $guid message guid
1582 * @param string $parent_guid optional parent guid
1584 * @return string the post link
1585 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1586 * @throws \ImagickException
1588 private static function plink($addr, $guid, $parent_guid = '')
1590 $contact = Contact::getDetailsByAddr($addr);
1591 if (empty($contact)) {
1592 Logger::info('No contact data for address', ['addr' => $addr]);
1596 if (empty($contact['baseurl'])) {
1597 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1598 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1602 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1603 if (!empty($gserver['platform'])) {
1604 $platform = strtolower($gserver['platform']);
1605 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1608 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1609 if (self::isHubzilla($contact['url'])) {
1610 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1611 $platform = 'hubzilla';
1612 } elseif ($contact['network'] == Protocol::DFRN) {
1613 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1614 $platform = 'friendica';
1618 if ($platform == 'friendica') {
1619 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1622 if ($platform == 'hubzilla') {
1623 return $contact['baseurl'] . '/item/' . $guid;
1626 if ($platform == 'socialhome') {
1627 return $contact['baseurl'] . '/content/' . $guid;
1630 if ($platform != 'diaspora') {
1631 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1635 if ($parent_guid != '') {
1636 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1638 return $contact['baseurl'] . '/posts/' . $guid;
1643 * Receives account migration
1645 * @param array $importer Array of the importer user
1646 * @param object $data The message object
1648 * @return bool Success
1649 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1650 * @throws \ImagickException
1652 private static function receiveAccountMigration(array $importer, $data)
1654 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1655 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1656 $signature = Strings::escapeTags(XML::unescape($data->signature));
1658 $contact = self::contactByHandle($importer["uid"], $old_handle);
1660 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1664 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1667 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1668 $key = self::key($old_handle);
1669 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1670 Logger::log('No valid signature for migration.');
1674 // Update the profile
1675 self::receiveProfile($importer, $data->profile);
1677 // change the technical stuff in contact and gcontact
1678 $data = Probe::uri($new_handle);
1679 if ($data['network'] == Protocol::PHANTOM) {
1680 Logger::log('Account for '.$new_handle." couldn't be probed.");
1684 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1685 'name' => $data['name'], 'nick' => $data['nick'],
1686 'addr' => $data['addr'], 'batch' => $data['batch'],
1687 'notify' => $data['notify'], 'poll' => $data['poll'],
1688 'network' => $data['network']];
1690 DBA::update('contact', $fields, ['addr' => $old_handle]);
1692 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1693 'name' => $data['name'], 'nick' => $data['nick'],
1694 'addr' => $data['addr'], 'connect' => $data['addr'],
1695 'notify' => $data['notify'], 'photo' => $data['photo'],
1696 'server_url' => $data['baseurl'], 'network' => $data['network']];
1698 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1700 Logger::log('Contacts are updated.');
1706 * Processes an account deletion
1708 * @param object $data The message object
1710 * @return bool Success
1711 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1713 private static function receiveAccountDeletion($data)
1715 $author = Strings::escapeTags(XML::unescape($data->author));
1717 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1718 while ($contact = DBA::fetch($contacts)) {
1719 Contact::remove($contact["id"]);
1722 DBA::delete('gcontact', ['addr' => $author]);
1724 Logger::log('Removed contacts for ' . $author);
1730 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1732 * @param string $author Author handle
1733 * @param string $guid Message guid
1734 * @param boolean $onlyfound Only return uri when found in the database
1736 * @return string The constructed uri or the one from our database
1737 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1738 * @throws \ImagickException
1740 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1742 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1743 if (DBA::isResult($item)) {
1744 return $item["uri"];
1745 } elseif (!$onlyfound) {
1746 $person = self::personByHandle($author);
1748 $parts = parse_url($person['url']);
1749 unset($parts['path']);
1750 $host_url = Network::unparseURL($parts);
1752 return $host_url . '/objects/' . $guid;
1759 * Fetch the guid from our database with a given uri
1761 * @param string $uri Message uri
1762 * @param string $uid Author handle
1764 * @return string The post guid
1765 * @throws \Exception
1767 private static function getGuidFromUri($uri, $uid)
1769 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1770 if (DBA::isResult($item)) {
1771 return $item["guid"];
1778 * Find the best importer for a comment, like, ...
1780 * @param string $guid The guid of the item
1782 * @return array|boolean the origin owner of that post - or false
1783 * @throws \Exception
1785 private static function importerForGuid($guid)
1787 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1788 if (DBA::isResult($item)) {
1789 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1790 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1791 if (DBA::isResult($contact)) {
1799 * Store the mentions in the tag table
1801 * @param integer $uriid
1802 * @param string $text
1804 private static function storeMentions(int $uriid, string $text)
1806 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1807 if (empty($matches)) {
1812 * Matching values for the preg match
1813 * [1] = mention type (@ or !)
1814 * [2] = name (optional)
1818 foreach ($matches as $match) {
1819 if (empty($match)) {
1823 $person = self::personByHandle($match[3]);
1824 if (empty($person)) {
1828 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1833 * Processes an incoming comment
1835 * @param array $importer Array of the importer user
1836 * @param string $sender The sender of the message
1837 * @param object $data The message object
1838 * @param string $xml The original XML of the message
1840 * @return int The message id of the generated comment or "false" if there was an error
1841 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1842 * @throws \ImagickException
1844 private static function receiveComment(array $importer, $sender, $data, $xml)
1846 $author = Strings::escapeTags(XML::unescape($data->author));
1847 $guid = Strings::escapeTags(XML::unescape($data->guid));
1848 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1849 $text = XML::unescape($data->text);
1851 if (isset($data->created_at)) {
1852 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1854 $created_at = DateTimeFormat::utcNow();
1857 if (isset($data->thread_parent_guid)) {
1858 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1859 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1864 $contact = self::allowedContactByHandle($importer, $sender, true);
1869 $message_id = self::messageExists($importer["uid"], $guid);
1874 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1875 if (!$parent_item) {
1879 $person = self::personByHandle($author);
1880 if (!is_array($person)) {
1881 Logger::log("unable to find author details");
1885 // Fetch the contact id - if we know this contact
1886 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1890 $datarray["uid"] = $importer["uid"];
1891 $datarray["contact-id"] = $author_contact["cid"];
1892 $datarray["network"] = $author_contact["network"];
1894 $datarray["author-link"] = $person["url"];
1895 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1897 $datarray["owner-link"] = $contact["url"];
1898 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1900 $datarray["guid"] = $guid;
1901 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1902 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1904 $datarray["verb"] = Activity::POST;
1905 $datarray["gravity"] = GRAVITY_COMMENT;
1907 if ($thr_uri != "") {
1908 $datarray["parent-uri"] = $thr_uri;
1910 $datarray["parent-uri"] = $parent_item["uri"];
1913 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1915 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1916 $datarray["source"] = $xml;
1918 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1920 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1921 $body = Markdown::toBBCode($text);
1923 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1925 self::storeMentions($datarray['uri-id'], $text);
1926 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
1928 self::fetchGuid($datarray);
1930 // If we are the origin of the parent we store the original data.
1931 // We notify our followers during the item storage.
1932 if ($parent_item["origin"]) {
1933 $datarray['diaspora_signed_text'] = json_encode($data);
1936 $message_id = Item::insert($datarray);
1938 if ($message_id <= 0) {
1943 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1944 if ($datarray['uid'] == 0) {
1945 Item::distribute($message_id, json_encode($data));
1953 * processes and stores private messages
1955 * @param array $importer Array of the importer user
1956 * @param array $contact The contact of the message
1957 * @param object $data The message object
1958 * @param array $msg Array of the processed message, author handle and key
1959 * @param object $mesg The private message
1960 * @param array $conversation The conversation record to which this message belongs
1962 * @return bool "true" if it was successful
1963 * @throws \Exception
1965 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1967 $author = Strings::escapeTags(XML::unescape($data->author));
1968 $guid = Strings::escapeTags(XML::unescape($data->guid));
1969 $subject = Strings::escapeTags(XML::unescape($data->subject));
1971 // "diaspora_handle" is the element name from the old version
1972 // "author" is the element name from the new version
1973 if ($mesg->author) {
1974 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1975 } elseif ($mesg->diaspora_handle) {
1976 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1981 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1982 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1983 $msg_text = XML::unescape($mesg->text);
1984 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1986 if ($msg_conversation_guid != $guid) {
1987 Logger::log("message conversation guid does not belong to the current conversation.");
1991 $body = Markdown::toBBCode($msg_text);
1992 $message_uri = $msg_author.":".$msg_guid;
1994 $person = self::personByHandle($msg_author);
1996 return Mail::insert([
1997 'uid' => $importer['uid'],
1998 'guid' => $msg_guid,
1999 'convid' => $conversation['id'],
2000 'from-name' => $person['name'],
2001 'from-photo' => $person['photo'],
2002 'from-url' => $person['url'],
2003 'contact-id' => $contact['id'],
2004 'title' => $subject,
2006 'uri' => $message_uri,
2007 'parent-uri' => $author . ':' . $guid,
2008 'created' => $msg_created_at
2013 * Processes new private messages (answers to private messages are processed elsewhere)
2015 * @param array $importer Array of the importer user
2016 * @param array $msg Array of the processed message, author handle and key
2017 * @param object $data The message object
2019 * @return bool Success
2020 * @throws \Exception
2022 private static function receiveConversation(array $importer, $msg, $data)
2024 $author = Strings::escapeTags(XML::unescape($data->author));
2025 $guid = Strings::escapeTags(XML::unescape($data->guid));
2026 $subject = Strings::escapeTags(XML::unescape($data->subject));
2027 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2028 $participants = Strings::escapeTags(XML::unescape($data->participants));
2030 $messages = $data->message;
2032 if (!count($messages)) {
2033 Logger::log("empty conversation");
2037 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
2042 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2043 if (!DBA::isResult($conversation)) {
2045 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
2046 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
2047 intval($importer["uid"]),
2049 DBA::escape($author),
2050 DBA::escape($created_at),
2051 DBA::escape(DateTimeFormat::utcNow()),
2052 DBA::escape($subject),
2053 DBA::escape($participants)
2056 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2059 if (!$conversation) {
2060 Logger::log("unable to create conversation.");
2064 foreach ($messages as $mesg) {
2065 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
2072 * Processes "like" messages
2074 * @param array $importer Array of the importer user
2075 * @param string $sender The sender of the message
2076 * @param object $data The message object
2078 * @return int The message id of the generated like or "false" if there was an error
2079 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2080 * @throws \ImagickException
2082 private static function receiveLike(array $importer, $sender, $data)
2084 $author = Strings::escapeTags(XML::unescape($data->author));
2085 $guid = Strings::escapeTags(XML::unescape($data->guid));
2086 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2087 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
2088 $positive = Strings::escapeTags(XML::unescape($data->positive));
2090 // likes on comments aren't supported by Diaspora - only on posts
2091 // But maybe this will be supported in the future, so we will accept it.
2092 if (!in_array($parent_type, ["Post", "Comment"])) {
2096 $contact = self::allowedContactByHandle($importer, $sender, true);
2101 $message_id = self::messageExists($importer["uid"], $guid);
2106 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2107 if (!$parent_item) {
2111 $person = self::personByHandle($author);
2112 if (!is_array($person)) {
2113 Logger::log("unable to find author details");
2117 // Fetch the contact id - if we know this contact
2118 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2120 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2121 // We would accept this anyhow.
2122 if ($positive == "true") {
2123 $verb = Activity::LIKE;
2125 $verb = Activity::DISLIKE;
2130 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2132 $datarray["uid"] = $importer["uid"];
2133 $datarray["contact-id"] = $author_contact["cid"];
2134 $datarray["network"] = $author_contact["network"];
2136 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2137 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2139 $datarray["guid"] = $guid;
2140 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2142 $datarray["verb"] = $verb;
2143 $datarray["gravity"] = GRAVITY_ACTIVITY;
2144 $datarray["parent-uri"] = $parent_item["uri"];
2146 $datarray["object-type"] = Activity\ObjectType::NOTE;
2148 $datarray["body"] = $verb;
2150 // Diaspora doesn't provide a date for likes
2151 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2153 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2154 if ($parent_item["id"] != $parent_item["parent"]) {
2155 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
2156 $origin = $toplevel["origin"];
2158 $origin = $parent_item["origin"];
2161 // If we are the origin of the parent we store the original data.
2162 // We notify our followers during the item storage.
2164 $datarray['diaspora_signed_text'] = json_encode($data);
2167 $message_id = Item::insert($datarray);
2169 if ($message_id <= 0) {
2174 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2175 if ($datarray['uid'] == 0) {
2176 Item::distribute($message_id, json_encode($data));
2184 * Processes private messages
2186 * @param array $importer Array of the importer user
2187 * @param object $data The message object
2189 * @return bool Success?
2190 * @throws \Exception
2192 private static function receiveMessage(array $importer, $data)
2194 $author = Strings::escapeTags(XML::unescape($data->author));
2195 $guid = Strings::escapeTags(XML::unescape($data->guid));
2196 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2197 $text = XML::unescape($data->text);
2198 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2200 $contact = self::allowedContactByHandle($importer, $author, true);
2205 $conversation = null;
2207 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2208 $conversation = DBA::selectFirst('conv', [], $condition);
2210 if (!DBA::isResult($conversation)) {
2211 Logger::log("conversation not available.");
2215 $message_uri = $author.":".$guid;
2217 $person = self::personByHandle($author);
2219 Logger::log("unable to find author details");
2223 $body = Markdown::toBBCode($text);
2225 $body = self::replacePeopleGuid($body, $person["url"]);
2227 return Mail::insert([
2228 'uid' => $importer['uid'],
2230 'convid' => $conversation['id'],
2231 'from-name' => $person['name'],
2232 'from-photo' => $person['photo'],
2233 'from-url' => $person['url'],
2234 'contact-id' => $contact['id'],
2235 'title' => $conversation['subject'],
2238 'uri' => $message_uri,
2239 'parent-uri' => $author.":".$conversation['guid'],
2240 'created' => $created_at
2245 * Processes participations - unsupported by now
2247 * @param array $importer Array of the importer user
2248 * @param object $data The message object
2250 * @return bool always true
2251 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2252 * @throws \ImagickException
2254 private static function receiveParticipation(array $importer, $data)
2256 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2257 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2259 $contact_id = Contact::getIdForURL($author);
2261 Logger::log('Contact not found: '.$author);
2265 $person = self::personByHandle($author);
2266 if (!is_array($person)) {
2267 Logger::log("Person not found: ".$author);
2271 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2272 if (!DBA::isResult($item)) {
2273 Logger::log('Item not found, no origin or private: '.$parent_guid);
2277 $author_parts = explode('@', $author);
2278 if (isset($author_parts[1])) {
2279 $server = $author_parts[1];
2281 // Should never happen
2285 Logger::log('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, Logger::DEBUG);
2287 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2288 DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2291 // Send all existing comments and likes to the requesting server
2292 $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2293 while ($comment = Item::fetch($comments)) {
2294 if ($comment['id'] == $comment['parent']) {
2298 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $contact_id]);
2299 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $contact_id)) {
2300 ItemDeliveryData::incrementQueueCount($comment['id'], 1);
2303 DBA::close($comments);
2309 * Processes photos - unneeded
2311 * @param array $importer Array of the importer user
2312 * @param object $data The message object
2314 * @return bool always true
2316 private static function receivePhoto(array $importer, $data)
2318 // There doesn't seem to be a reason for this function,
2319 // since the photo data is transmitted in the status message as well
2324 * Processes poll participations - unssupported
2326 * @param array $importer Array of the importer user
2327 * @param object $data The message object
2329 * @return bool always true
2331 private static function receivePollParticipation(array $importer, $data)
2333 // We don't support polls by now
2338 * Processes incoming profile updates
2340 * @param array $importer Array of the importer user
2341 * @param object $data The message object
2343 * @return bool Success
2344 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2345 * @throws \ImagickException
2347 private static function receiveProfile(array $importer, $data)
2349 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2351 $contact = self::contactByHandle($importer["uid"], $author);
2356 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2357 $image_url = XML::unescape($data->image_url);
2358 $birthday = XML::unescape($data->birthday);
2359 $about = Markdown::toBBCode(XML::unescape($data->bio));
2360 $location = Markdown::toBBCode(XML::unescape($data->location));
2361 $searchable = (XML::unescape($data->searchable) == "true");
2362 $nsfw = (XML::unescape($data->nsfw) == "true");
2363 $tags = XML::unescape($data->tag_string);
2365 $tags = explode("#", $tags);
2368 foreach ($tags as $tag) {
2369 $tag = trim(strtolower($tag));
2375 $keywords = implode(", ", $keywords);
2377 $handle_parts = explode("@", $author);
2378 $nick = $handle_parts[0];
2381 $name = $handle_parts[0];
2384 if (preg_match("|^https?://|", $image_url) === 0) {
2385 $image_url = "http://".$handle_parts[1].$image_url;
2388 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2390 // Generic birthday. We don't know the timezone. The year is irrelevant.
2392 $birthday = str_replace("1000", "1901", $birthday);
2394 if ($birthday != "") {
2395 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2398 // this is to prevent multiple birthday notifications in a single year
2399 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2401 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2402 $birthday = $contact["bd"];
2405 $fields = ['name' => $name, 'location' => $location,
2406 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2407 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2408 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2410 if (!empty($birthday)) {
2411 $fields['bd'] = $birthday;
2414 DBA::update('contact', $fields, ['id' => $contact['id']]);
2416 // @todo Update the public contact, then update the gcontact from that
2418 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2419 "photo" => $image_url, "name" => $name, "location" => $location,
2420 "about" => $about, "birthday" => $birthday,
2421 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2422 "hide" => !$searchable, "nsfw" => $nsfw];
2424 $gcid = GContact::update($gcontact);
2426 GContact::link($gcid, $importer["uid"], $contact["id"]);
2428 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2434 * Processes incoming friend requests
2436 * @param array $importer Array of the importer user
2437 * @param array $contact The contact that send the request
2439 * @throws \Exception
2441 private static function receiveRequestMakeFriend(array $importer, array $contact)
2443 if ($contact["rel"] == Contact::SHARING) {
2446 ['rel' => Contact::FRIEND, 'writable' => true],
2447 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2453 * Processes incoming sharing notification
2455 * @param array $importer Array of the importer user
2456 * @param object $data The message object
2458 * @return bool Success
2459 * @throws \Exception
2461 private static function receiveContactRequest(array $importer, $data)
2463 $author = XML::unescape($data->author);
2464 $recipient = XML::unescape($data->recipient);
2466 if (!$author || !$recipient) {
2470 // the current protocol version doesn't know these fields
2471 // That means that we will assume their existance
2472 if (isset($data->following)) {
2473 $following = (XML::unescape($data->following) == "true");
2478 if (isset($data->sharing)) {
2479 $sharing = (XML::unescape($data->sharing) == "true");
2484 $contact = self::contactByHandle($importer["uid"], $author);
2486 // perhaps we were already sharing with this person. Now they're sharing with us.
2487 // That makes us friends.
2490 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2491 self::receiveRequestMakeFriend($importer, $contact);
2493 // refetch the contact array
2494 $contact = self::contactByHandle($importer["uid"], $author);
2496 // If we are now friends, we are sending a share message.
2497 // Normally we needn't to do so, but the first message could have been vanished.
2498 if (in_array($contact["rel"], [Contact::FRIEND])) {
2499 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2500 if (DBA::isResult($user)) {
2501 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2502 self::sendShare($user, $contact);
2507 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2508 Contact::removeFollower($importer, $contact);
2513 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2514 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2516 } elseif (!$following && !$sharing) {
2517 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2519 } elseif (!$following && $sharing) {
2520 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2521 } elseif ($following && $sharing) {
2522 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2523 } elseif ($following && !$sharing) {
2524 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2527 $ret = self::personByHandle($author);
2529 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2530 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2534 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2536 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2541 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2542 'author-link' => $ret['url']];
2544 $result = Contact::addRelationship($importer, $contact, $item, false);
2545 if ($result === true) {
2546 $contact_record = self::contactByHandle($importer['uid'], $author);
2547 if (!$contact_record) {
2548 Logger::info('unable to locate newly created contact record.');
2552 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2553 if (DBA::isResult($user)) {
2554 self::sendShare($user, $contact_record);
2556 // Send the profile data, maybe it weren't transmitted before
2557 self::sendProfile($importer['uid'], [$contact_record]);
2565 * Fetches a message with a given guid
2567 * @param string $guid message guid
2568 * @param string $orig_author handle of the original post
2569 * @return array The fetched item
2570 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2571 * @throws \ImagickException
2573 public static function originalItem($guid, $orig_author)
2576 Logger::log('Empty guid. Quitting.');
2580 // Do we already have this item?
2581 $fields = ['body', 'title', 'attach', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2582 'author-name', 'author-link', 'author-avatar'];
2583 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2584 $item = Item::selectFirst($fields, $condition);
2586 if (DBA::isResult($item)) {
2587 Logger::log("reshared message ".$guid." already exists on system.");
2589 // Maybe it is already a reshared item?
2590 // Then refetch the content, if it is a reshare from a reshare.
2591 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2592 if (self::isReshare($item["body"], true)) {
2594 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2595 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2597 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2599 // Add OEmbed and other information to the body
2600 $item["body"] = add_page_info_to_body($item["body"], false, true);
2608 if (!DBA::isResult($item)) {
2609 if (empty($orig_author)) {
2610 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2614 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2615 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2616 $stored = self::storeByGuid($guid, $server);
2619 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2620 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2621 $stored = self::storeByGuid($guid, $server);
2625 $fields = ['body', 'title', 'attach', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2626 'author-name', 'author-link', 'author-avatar'];
2627 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2628 $item = Item::selectFirst($fields, $condition);
2630 if (DBA::isResult($item)) {
2631 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2632 if (self::isReshare($item["body"], false)) {
2633 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2634 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2645 * Stores a reshare activity
2647 * @param array $item Array of reshare post
2648 * @param integer $parent_message_id Id of the parent post
2649 * @param string $guid GUID string of reshare action
2650 * @param string $author Author handle
2652 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2654 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2658 $datarray['uid'] = $item['uid'];
2659 $datarray['contact-id'] = $item['contact-id'];
2660 $datarray['network'] = $item['network'];
2662 $datarray['author-link'] = $item['author-link'];
2663 $datarray['author-id'] = $item['author-id'];
2665 $datarray['owner-link'] = $datarray['author-link'];
2666 $datarray['owner-id'] = $datarray['author-id'];
2668 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2669 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2670 $datarray['parent-uri'] = $parent['uri'];
2672 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2673 $datarray['gravity'] = GRAVITY_ACTIVITY;
2674 $datarray['object-type'] = Activity\ObjectType::NOTE;
2676 $datarray['protocol'] = $item['protocol'];
2678 $datarray['plink'] = self::plink($author, $datarray['guid']);
2679 $datarray['private'] = $item['private'];
2680 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2682 $message_id = Item::insert($datarray);
2685 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2686 if ($datarray['uid'] == 0) {
2687 Item::distribute($message_id);
2693 * Processes a reshare message
2695 * @param array $importer Array of the importer user
2696 * @param object $data The message object
2697 * @param string $xml The original XML of the message
2699 * @return int the message id
2700 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2701 * @throws \ImagickException
2703 private static function receiveReshare(array $importer, $data, $xml)
2705 $author = Strings::escapeTags(XML::unescape($data->author));
2706 $guid = Strings::escapeTags(XML::unescape($data->guid));
2707 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2708 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2709 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2710 /// @todo handle unprocessed property "provider_display_name"
2711 $public = Strings::escapeTags(XML::unescape($data->public));
2713 $contact = self::allowedContactByHandle($importer, $author, false);
2718 $message_id = self::messageExists($importer["uid"], $guid);
2723 $original_item = self::originalItem($root_guid, $root_author);
2724 if (!$original_item) {
2728 $orig_url = DI::baseUrl()."/display/".$original_item["guid"];
2732 $datarray["uid"] = $importer["uid"];
2733 $datarray["contact-id"] = $contact["id"];
2734 $datarray["network"] = Protocol::DIASPORA;
2736 $datarray["author-link"] = $contact["url"];
2737 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2739 $datarray["owner-link"] = $datarray["author-link"];
2740 $datarray["owner-id"] = $datarray["author-id"];
2742 $datarray["guid"] = $guid;
2743 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2744 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2746 $datarray["verb"] = Activity::POST;
2747 $datarray["gravity"] = GRAVITY_PARENT;
2749 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2750 $datarray["source"] = $xml;
2752 /// @todo Copy tag data from original post
2754 $prefix = share_header(
2755 $original_item["author-name"],
2756 $original_item["author-link"],
2757 $original_item["author-avatar"],
2758 $original_item["guid"],
2759 $original_item["created"],
2763 if (!empty($original_item['title'])) {
2764 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2767 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2769 Tag::storeFromBody($datarray['uri-id'], $datarray["body"]);
2771 $datarray["tag"] = $original_item["tag"];
2772 $datarray["attach"] = $original_item["attach"];
2773 $datarray["app"] = $original_item["app"];
2775 $datarray["plink"] = self::plink($author, $guid);
2776 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2777 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2779 $datarray["object-type"] = $original_item["object-type"];
2781 self::fetchGuid($datarray);
2782 $message_id = Item::insert($datarray);
2784 self::sendParticipation($contact, $datarray);
2786 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2787 if ($root_message_id) {
2788 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2792 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2793 if ($datarray['uid'] == 0) {
2794 Item::distribute($message_id);
2803 * Processes retractions
2805 * @param array $importer Array of the importer user
2806 * @param array $contact The contact of the item owner
2807 * @param object $data The message object
2809 * @return bool success
2810 * @throws \Exception
2812 private static function itemRetraction(array $importer, array $contact, $data)
2814 $author = Strings::escapeTags(XML::unescape($data->author));
2815 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2816 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2818 $person = self::personByHandle($author);
2819 if (!is_array($person)) {
2820 Logger::log("unable to find author detail for ".$author);
2824 if (empty($contact["url"])) {
2825 $contact["url"] = $person["url"];
2828 // Fetch items that are about to be deleted
2829 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2831 // When we receive a public retraction, we delete every item that we find.
2832 if ($importer['uid'] == 0) {
2833 $condition = ['guid' => $target_guid, 'deleted' => false];
2835 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2838 $r = Item::select($fields, $condition);
2839 if (!DBA::isResult($r)) {
2840 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2844 while ($item = Item::fetch($r)) {
2845 if (strstr($item['file'], '[')) {
2846 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2850 // Fetch the parent item
2851 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2853 // Only delete it if the parent author really fits
2854 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2855 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2859 Item::markForDeletion(['id' => $item['id']]);
2861 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], Logger::DEBUG);
2868 * Receives retraction messages
2870 * @param array $importer Array of the importer user
2871 * @param string $sender The sender of the message
2872 * @param object $data The message object
2874 * @return bool Success
2875 * @throws \Exception
2877 private static function receiveRetraction(array $importer, $sender, $data)
2879 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2881 $contact = self::contactByHandle($importer["uid"], $sender);
2882 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2883 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2891 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2893 switch ($target_type) {
2898 case "StatusMessage":
2899 return self::itemRetraction($importer, $contact, $data);
2901 case "PollParticipation":
2903 // Currently unsupported
2907 Logger::log("Unknown target type ".$target_type);
2914 * Receives status messages
2916 * @param array $importer Array of the importer user
2917 * @param SimpleXMLElement $data The message object
2918 * @param string $xml The original XML of the message
2920 * @return int The message id of the newly created item
2921 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2922 * @throws \ImagickException
2924 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2926 $author = Strings::escapeTags(XML::unescape($data->author));
2927 $guid = Strings::escapeTags(XML::unescape($data->guid));
2928 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2929 $public = Strings::escapeTags(XML::unescape($data->public));
2930 $text = XML::unescape($data->text);
2931 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2933 $contact = self::allowedContactByHandle($importer, $author, false);
2938 $message_id = self::messageExists($importer["uid"], $guid);
2944 if ($data->location) {
2945 foreach ($data->location->children() as $fieldname => $data) {
2946 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2950 $body = Markdown::toBBCode($text);
2954 // Attach embedded pictures to the body
2956 foreach ($data->photo as $photo) {
2957 $body = "[img]".XML::unescape($photo->remote_photo_path).
2958 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2961 $datarray["object-type"] = Activity\ObjectType::IMAGE;
2963 $datarray["object-type"] = Activity\ObjectType::NOTE;
2965 // Add OEmbed and other information to the body
2966 if (!self::isHubzilla($contact["url"])) {
2967 $body = add_page_info_to_body($body, false, true);
2971 /// @todo enable support for polls
2972 //if ($data->poll) {
2973 // foreach ($data->poll AS $poll)
2978 /// @todo enable support for events
2980 $datarray["uid"] = $importer["uid"];
2981 $datarray["contact-id"] = $contact["id"];
2982 $datarray["network"] = Protocol::DIASPORA;
2984 $datarray["author-link"] = $contact["url"];
2985 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2987 $datarray["owner-link"] = $datarray["author-link"];
2988 $datarray["owner-id"] = $datarray["author-id"];
2990 $datarray["guid"] = $guid;
2991 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2992 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2994 $datarray["verb"] = Activity::POST;
2995 $datarray["gravity"] = GRAVITY_PARENT;
2997 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2998 $datarray["source"] = $xml;
3000 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3002 self::storeMentions($datarray['uri-id'], $text);
3003 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
3005 if ($provider_display_name != "") {
3006 $datarray["app"] = $provider_display_name;
3009 $datarray["plink"] = self::plink($author, $guid);
3010 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
3011 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3013 if (isset($address["address"])) {
3014 $datarray["location"] = $address["address"];
3017 if (isset($address["lat"]) && isset($address["lng"])) {
3018 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3021 self::fetchGuid($datarray);
3022 $message_id = Item::insert($datarray);
3024 self::sendParticipation($contact, $datarray);
3027 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
3028 if ($datarray['uid'] == 0) {
3029 Item::distribute($message_id);
3037 /* ************************************************************************************** *
3038 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3039 * ************************************************************************************** */
3042 * returnes the handle of a contact
3044 * @param array $contact contact array
3046 * @return string the handle in the format user@domain.tld
3047 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3049 private static function myHandle(array $contact)
3051 if (!empty($contact["addr"])) {
3052 return $contact["addr"];
3055 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3056 // So - just in case - we build the the address here.
3057 if ($contact["nickname"] != "") {
3058 $nick = $contact["nickname"];
3060 $nick = $contact["nick"];
3063 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
3068 * Creates the data for a private message in the new format
3070 * @param string $msg The message that is to be transmitted
3071 * @param array $user The record of the sender
3072 * @param array $contact Target of the communication
3073 * @param string $prvkey The private key of the sender
3074 * @param string $pubkey The public key of the receiver
3076 * @return string The encrypted data
3077 * @throws \Exception
3079 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
3081 Logger::log("Message: ".$msg, Logger::DATA);
3083 // without a public key nothing will work
3085 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3089 $aes_key = openssl_random_pseudo_bytes(32);
3090 $b_aes_key = base64_encode($aes_key);
3091 $iv = openssl_random_pseudo_bytes(16);
3092 $b_iv = base64_encode($iv);
3094 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3096 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3098 $encrypted_key_bundle = "";
3099 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3101 $json_object = json_encode(
3102 ["aes_key" => base64_encode($encrypted_key_bundle),
3103 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3106 return $json_object;
3110 * Creates the envelope for the "fetch" endpoint and for the new format
3112 * @param string $msg The message that is to be transmitted
3113 * @param array $user The record of the sender
3115 * @return string The envelope
3116 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3118 public static function buildMagicEnvelope($msg, array $user)
3120 $b64url_data = Strings::base64UrlEncode($msg);
3121 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3123 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3124 $type = "application/xml";
3125 $encoding = "base64url";
3126 $alg = "RSA-SHA256";
3127 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3129 // Fallback if the private key wasn't transmitted in the expected field
3130 if ($user['uprvkey'] == "") {
3131 $user['uprvkey'] = $user['prvkey'];
3134 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3135 $sig = Strings::base64UrlEncode($signature);
3137 $xmldata = ["me:env" => ["me:data" => $data,
3138 "@attributes" => ["type" => $type],
3139 "me:encoding" => $encoding,
3142 "@attributes2" => ["key_id" => $key_id]]];
3144 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3146 return XML::fromArray($xmldata, $xml, false, $namespaces);
3150 * Create the envelope for a message
3152 * @param string $msg The message that is to be transmitted
3153 * @param array $user The record of the sender
3154 * @param array $contact Target of the communication
3155 * @param string $prvkey The private key of the sender
3156 * @param string $pubkey The public key of the receiver
3157 * @param bool $public Is the message public?
3159 * @return string The message that will be transmitted to other servers
3160 * @throws \Exception
3162 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3164 // The message is put into an envelope with the sender's signature
3165 $envelope = self::buildMagicEnvelope($msg, $user);
3167 // Private messages are put into a second envelope, encrypted with the receivers public key
3169 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3176 * Creates a signature for a message
3178 * @param array $owner the array of the owner of the message
3179 * @param array $message The message that is to be signed
3181 * @return string The signature
3183 private static function signature($owner, $message)
3186 unset($sigmsg["author_signature"]);
3187 unset($sigmsg["parent_author_signature"]);
3189 $signed_text = implode(";", $sigmsg);
3191 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3195 * Transmit a message to a target server
3197 * @param array $owner the array of the item owner
3198 * @param array $contact Target of the communication
3199 * @param string $envelope The message that is to be transmitted
3200 * @param bool $public_batch Is it a public post?
3201 * @param string $guid message guid
3203 * @return int Result of the transmission
3204 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3205 * @throws \ImagickException
3207 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3209 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
3214 $logid = Strings::getRandomHex(4);
3216 // We always try to use the data from the fcontact table.
3217 // This is important for transmitting data to Friendica servers.
3218 if (!empty($contact['addr'])) {
3219 $fcontact = self::personByHandle($contact['addr']);
3220 if (!empty($fcontact)) {
3221 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3225 if (empty($dest_url)) {
3226 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3230 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3234 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3236 if (!intval(DI::config()->get("system", "diaspora_test"))) {
3237 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3239 $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3240 $return_code = $postResult->getReturnCode();
3242 Logger::log("test_mode");
3246 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3248 return $return_code ? $return_code : -1;
3253 * Build the post xml
3255 * @param string $type The message type
3256 * @param array $message The message data
3258 * @return string The post XML
3260 public static function buildPostXml($type, $message)
3262 $data = [$type => $message];
3264 return XML::fromArray($data, $xml);
3268 * Builds and transmit messages
3270 * @param array $owner the array of the item owner
3271 * @param array $contact Target of the communication
3272 * @param string $type The message type
3273 * @param array $message The message data
3274 * @param bool $public_batch Is it a public post?
3275 * @param string $guid message guid
3277 * @return int Result of the transmission
3278 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3279 * @throws \ImagickException
3281 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3283 $msg = self::buildPostXml($type, $message);
3285 Logger::log('message: '.$msg, Logger::DATA);
3286 Logger::log('send guid '.$guid, Logger::DEBUG);
3288 // Fallback if the private key wasn't transmitted in the expected field
3289 if (empty($owner['uprvkey'])) {
3290 $owner['uprvkey'] = $owner['prvkey'];
3293 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3295 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3297 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3299 return $return_code;
3303 * sends a participation (Used to get all further updates)
3305 * @param array $contact Target of the communication
3306 * @param array $item Item array
3308 * @return int The result of the transmission
3309 * @throws \Exception
3311 private static function sendParticipation(array $contact, array $item)
3313 // Don't send notifications for private postings
3314 if ($item['private'] == Item::PRIVATE) {
3318 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3320 $result = DI::cache()->get($cachekey);
3321 if (!is_null($result)) {
3325 // Fetch some user id to have a valid handle to transmit the participation.
3326 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3327 // If the item belongs to a user, we take this user id.
3328 if ($item['uid'] == 0) {
3329 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3330 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3331 $owner = User::getOwnerDataById($first_user['uid']);
3333 $owner = User::getOwnerDataById($item['uid']);
3336 $author = self::myHandle($owner);
3338 $message = ["author" => $author,
3339 "guid" => System::createUUID(),
3340 "parent_type" => "Post",
3341 "parent_guid" => $item["guid"]];
3343 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3345 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3346 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3348 return self::buildAndTransmit($owner, $contact, "participation", $message);
3352 * sends an account migration
3354 * @param array $owner the array of the item owner
3355 * @param array $contact Target of the communication
3356 * @param int $uid User ID
3358 * @return int The result of the transmission
3359 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3360 * @throws \ImagickException
3362 public static function sendAccountMigration(array $owner, array $contact, $uid)
3364 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3365 $profile = self::createProfileData($uid);
3367 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3368 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3370 $message = ["author" => $old_handle,
3371 "profile" => $profile,
3372 "signature" => $signature];
3374 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3376 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3380 * Sends a "share" message
3382 * @param array $owner the array of the item owner
3383 * @param array $contact Target of the communication
3385 * @return int The result of the transmission
3386 * @throws \Exception
3388 public static function sendShare(array $owner, array $contact)
3391 * @todo support the different possible combinations of "following" and "sharing"
3392 * Currently, Diaspora only interprets the "sharing" field
3394 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3398 switch ($contact["rel"]) {
3399 case Contact::FRIEND:
3403 case Contact::SHARING:
3407 case Contact::FOLLOWER:
3413 $message = ["author" => self::myHandle($owner),
3414 "recipient" => $contact["addr"],
3415 "following" => "true",
3416 "sharing" => "true"];
3418 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3420 return self::buildAndTransmit($owner, $contact, "contact", $message);
3424 * sends an "unshare"
3426 * @param array $owner the array of the item owner
3427 * @param array $contact Target of the communication
3429 * @return int The result of the transmission
3430 * @throws \Exception
3432 public static function sendUnshare(array $owner, array $contact)
3434 $message = ["author" => self::myHandle($owner),
3435 "recipient" => $contact["addr"],
3436 "following" => "false",
3437 "sharing" => "false"];
3439 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3441 return self::buildAndTransmit($owner, $contact, "contact", $message);
3445 * Checks a message body if it is a reshare
3447 * @param string $body The message body that is to be check
3448 * @param bool $complete Should it be a complete check or a simple check?
3450 * @return array|bool Reshare details or "false" if no reshare
3451 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3452 * @throws \ImagickException
3454 public static function isReshare($body, $complete = true)
3456 $body = trim($body);
3458 $reshared = Item::getShareArray(['body' => $body]);
3459 if (empty($reshared)) {
3463 // Skip if it isn't a pure repeated messages
3464 // Does it start with a share?
3465 if (!empty($reshared['comment']) && $complete) {
3469 if (!empty($reshared['guid']) && $complete) {
3470 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3471 $item = Item::selectFirst(['contact-id'], $condition);
3472 if (DBA::isResult($item)) {
3474 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3475 $ret["root_guid"] = $reshared['guid'];
3477 } elseif ($complete) {
3478 // We are resharing something that isn't a DFRN or Diaspora post.
3479 // So we have to return "false" on "$complete" to not trigger a reshare.
3482 } elseif (empty($reshared['guid']) && $complete) {
3488 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3489 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3490 if (!empty($contact['addr'])) {
3491 $ret['root_handle'] = $contact['addr'];
3495 if (empty($ret) && !$complete) {
3503 * Create an event array
3505 * @param integer $event_id The id of the event
3507 * @return array with event data
3508 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3510 private static function buildEvent($event_id)
3512 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3513 if (!DBA::isResult($r)) {
3521 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3522 if (!DBA::isResult($r)) {
3528 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3529 if (!DBA::isResult($r)) {
3535 $eventdata['author'] = self::myHandle($owner);
3537 if ($event['guid']) {
3538 $eventdata['guid'] = $event['guid'];
3541 $mask = DateTimeFormat::ATOM;
3543 /// @todo - establish "all day" events in Friendica
3544 $eventdata["all_day"] = "false";
3546 $eventdata['timezone'] = 'UTC';
3547 if (!$event['adjust'] && $user['timezone']) {
3548 $eventdata['timezone'] = $user['timezone'];
3551 if ($event['start']) {
3552 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3554 if ($event['finish'] && !$event['nofinish']) {
3555 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3557 if ($event['summary']) {
3558 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3560 if ($event['desc']) {
3561 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3563 if ($event['location']) {
3564 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3565 $coord = Map::getCoordinates($event['location']);
3568 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3569 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3570 $location["lat"] = $coord['lat'];
3571 $location["lng"] = $coord['lon'];
3573 $location["lat"] = 0;
3574 $location["lng"] = 0;
3576 $eventdata['location'] = $location;
3583 * Create a post (status message or reshare)
3585 * @param array $item The item that will be exported
3586 * @param array $owner the array of the item owner
3589 * 'type' -> Message type ("status_message" or "reshare")
3590 * 'message' -> Array of XML elements of the status
3591 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3592 * @throws \ImagickException
3594 public static function buildStatus(array $item, array $owner)
3596 $cachekey = "diaspora:buildStatus:".$item['guid'];
3598 $result = DI::cache()->get($cachekey);
3599 if (!is_null($result)) {
3603 $myaddr = self::myHandle($owner);
3605 $public = ($item["private"] == Item::PRIVATE ? "false" : "true");
3606 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3607 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3609 // Detect a share element and do a reshare
3610 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) {
3611 $message = ["author" => $myaddr,
3612 "guid" => $item["guid"],
3613 "created_at" => $created,
3614 "root_author" => $ret["root_handle"],
3615 "root_guid" => $ret["root_guid"],
3616 "provider_display_name" => $item["app"],
3617 "public" => $public];
3621 $title = $item["title"];
3622 $body = $item["body"];
3624 // Fetch the title from an attached link - if there is one
3625 if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3626 $page_data = BBCode::getAttachmentData($item['body']);
3627 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3628 $title = $page_data['title'];
3632 if ($item['author-link'] != $item['owner-link']) {
3633 require_once 'mod/share.php';
3634 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3635 "", $item['created'], $item['plink']) . $body . '[/share]';
3638 // convert to markdown
3639 $body = html_entity_decode(BBCode::toMarkdown($body));
3642 if (strlen($title)) {
3643 $body = "### ".html_entity_decode($title)."\n\n".$body;
3646 if ($item["attach"]) {
3647 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3649 $body .= "\n".DI::l10n()->t("Attachments:")."\n";
3650 foreach ($matches as $mtch) {
3651 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3658 if ($item["location"] != "")
3659 $location["address"] = $item["location"];
3661 if ($item["coord"] != "") {
3662 $coord = explode(" ", $item["coord"]);
3663 $location["lat"] = $coord[0];
3664 $location["lng"] = $coord[1];
3667 $message = ["author" => $myaddr,
3668 "guid" => $item["guid"],
3669 "created_at" => $created,
3670 "edited_at" => $edited,
3671 "public" => $public,
3673 "provider_display_name" => $item["app"],
3674 "location" => $location];
3676 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3677 if (!isset($location["lat"]) || !isset($location["lng"])) {
3678 unset($message["location"]);
3681 if ($item['event-id'] > 0) {
3682 $event = self::buildEvent($item['event-id']);
3683 if (count($event)) {
3684 $message['event'] = $event;
3686 if (!empty($event['location']['address']) &&
3687 !empty($event['location']['lat']) &&
3688 !empty($event['location']['lng'])) {
3689 $message['location'] = $event['location'];
3692 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3693 // $message['text'] = '';
3697 $type = "status_message";
3700 $msg = ["type" => $type, "message" => $message];
3702 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3707 private static function prependParentAuthorMention($body, $profile_url)
3709 $profile = Contact::getDetailsByURL($profile_url);
3710 if (!empty($profile['addr'])
3711 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3712 && !strstr($body, $profile['addr'])
3713 && !strstr($body, $profile_url)
3715 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3724 * @param array $item The item that will be exported
3725 * @param array $owner the array of the item owner
3726 * @param array $contact Target of the communication
3727 * @param bool $public_batch Is it a public post?
3729 * @return int The result of the transmission
3730 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3731 * @throws \ImagickException
3733 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3735 $status = self::buildStatus($item, $owner);
3737 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3741 * Creates a "like" object
3743 * @param array $item The item that will be exported
3744 * @param array $owner the array of the item owner
3746 * @return array The data for a "like"
3747 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3749 private static function constructLike(array $item, array $owner)
3751 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3752 if (!DBA::isResult($parent)) {
3756 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3758 if ($item['verb'] === Activity::LIKE) {
3760 } elseif ($item['verb'] === Activity::DISLIKE) {
3761 $positive = "false";
3764 return(["author" => self::myHandle($owner),
3765 "guid" => $item["guid"],
3766 "parent_guid" => $parent["guid"],
3767 "parent_type" => $target_type,
3768 "positive" => $positive,
3769 "author_signature" => ""]);
3773 * Creates an "EventParticipation" object
3775 * @param array $item The item that will be exported
3776 * @param array $owner the array of the item owner
3778 * @return array The data for an "EventParticipation"
3779 * @throws \Exception
3781 private static function constructAttend(array $item, array $owner)
3783 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3784 if (!DBA::isResult($parent)) {
3788 switch ($item['verb']) {
3789 case Activity::ATTEND:
3790 $attend_answer = 'accepted';
3792 case Activity::ATTENDNO:
3793 $attend_answer = 'declined';
3795 case Activity::ATTENDMAYBE:
3796 $attend_answer = 'tentative';
3799 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3803 return(["author" => self::myHandle($owner),
3804 "guid" => $item["guid"],
3805 "parent_guid" => $parent["guid"],
3806 "status" => $attend_answer,
3807 "author_signature" => ""]);
3811 * Creates the object for a comment
3813 * @param array $item The item that will be exported
3814 * @param array $owner the array of the item owner
3816 * @return array|false The data for a comment
3817 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3819 private static function constructComment(array $item, array $owner)
3821 $cachekey = "diaspora:constructComment:".$item['guid'];
3823 $result = DI::cache()->get($cachekey);
3824 if (!is_null($result)) {
3828 $toplevel_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3829 if (!DBA::isResult($toplevel_item)) {
3830 Logger::error('Missing parent conversation item', ['parent' => $item["parent"]]);
3834 $thread_parent_item = $toplevel_item;
3835 if ($item['thr-parent'] != $item['parent-uri']) {
3836 $thread_parent_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3839 $body = $item["body"];
3841 // The replied to autor mention is prepended for clarity if:
3842 // - Item replied isn't yours
3843 // - Item is public or explicit mentions are disabled
3844 // - Implicit mentions are enabled
3846 $item['author-id'] != $thread_parent_item['author-id']
3847 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3848 && !DI::config()->get('system', 'disable_implicit_mentions')
3850 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3853 $text = html_entity_decode(BBCode::toMarkdown($body));
3854 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3855 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3858 "author" => self::myHandle($owner),
3859 "guid" => $item["guid"],
3860 "created_at" => $created,
3861 "edited_at" => $edited,
3862 "parent_guid" => $toplevel_item["guid"],
3864 "author_signature" => ""
3867 // Send the thread parent guid only if it is a threaded comment
3868 if ($item['thr-parent'] != $item['parent-uri']) {
3869 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3872 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3878 * Send a like or a comment
3880 * @param array $item The item that will be exported
3881 * @param array $owner the array of the item owner
3882 * @param array $contact Target of the communication
3883 * @param bool $public_batch Is it a public post?
3885 * @return int The result of the transmission
3886 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3887 * @throws \ImagickException
3889 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3891 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3892 $message = self::constructAttend($item, $owner);
3893 $type = "event_participation";
3894 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3895 $message = self::constructLike($item, $owner);
3897 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3898 $message = self::constructComment($item, $owner);
3902 if (empty($message)) {
3906 $message["author_signature"] = self::signature($owner, $message);
3908 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3912 * Creates a message from a signature record entry
3914 * @param array $item The item that will be exported
3915 * @return array The message
3917 private static function messageFromSignature(array $item)
3919 // Split the signed text
3920 $signed_parts = explode(";", $item['signed_text']);
3922 if ($item["deleted"]) {
3923 $message = ["author" => $item['signer'],
3924 "target_guid" => $signed_parts[0],
3925 "target_type" => $signed_parts[1]];
3926 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3927 $message = ["author" => $signed_parts[4],
3928 "guid" => $signed_parts[1],
3929 "parent_guid" => $signed_parts[3],
3930 "parent_type" => $signed_parts[2],
3931 "positive" => $signed_parts[0],
3932 "author_signature" => $item['signature'],
3933 "parent_author_signature" => ""];
3935 // Remove the comment guid
3936 $guid = array_shift($signed_parts);
3938 // Remove the parent guid
3939 $parent_guid = array_shift($signed_parts);
3941 // Remove the handle
3942 $handle = array_pop($signed_parts);
3945 "author" => $handle,
3947 "parent_guid" => $parent_guid,
3948 "text" => implode(";", $signed_parts),
3949 "author_signature" => $item['signature'],
3950 "parent_author_signature" => ""
3957 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3959 * @param array $item The item that will be exported
3960 * @param array $owner the array of the item owner
3961 * @param array $contact Target of the communication
3962 * @param bool $public_batch Is it a public post?
3964 * @return int The result of the transmission
3965 * @throws \Exception
3967 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3969 if ($item["deleted"]) {
3970 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3971 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3977 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3979 $msg = json_decode($item['signed_text'], true);
3982 if (is_array($msg)) {
3983 foreach ($msg as $field => $data) {
3984 if (!$item["deleted"]) {
3985 if ($field == "diaspora_handle") {
3988 if ($field == "target_type") {
3989 $field = "parent_type";
3993 $message[$field] = $data;
3996 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
3999 $message["parent_author_signature"] = self::signature($owner, $message);
4001 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
4003 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4007 * Sends a retraction (deletion) of a message, like or comment
4009 * @param array $item The item that will be exported
4010 * @param array $owner the array of the item owner
4011 * @param array $contact Target of the communication
4012 * @param bool $public_batch Is it a public post?
4013 * @param bool $relay Is the retraction transmitted from a relay?
4015 * @return int The result of the transmission
4016 * @throws \Exception
4018 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
4020 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4022 $msg_type = "retraction";
4024 if ($item['id'] == $item['parent']) {
4025 $target_type = "Post";
4026 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4027 $target_type = "Like";
4029 $target_type = "Comment";
4032 $message = ["author" => $itemaddr,
4033 "target_guid" => $item['guid'],
4034 "target_type" => $target_type];
4036 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
4038 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4044 * @param array $item The item that will be exported
4045 * @param array $owner The owner
4046 * @param array $contact Target of the communication
4048 * @return int The result of the transmission
4049 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4050 * @throws \ImagickException
4052 public static function sendMail(array $item, array $owner, array $contact)
4054 $myaddr = self::myHandle($owner);
4056 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
4057 if (!DBA::isResult($cnv)) {
4058 Logger::log("conversation not found.");
4062 $body = BBCode::toMarkdown($item["body"]);
4063 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4066 "author" => $myaddr,
4067 "guid" => $item["guid"],
4068 "conversation_guid" => $cnv["guid"],
4070 "created_at" => $created,
4073 if ($item["reply"]) {
4078 "author" => $cnv["creator"],
4079 "guid" => $cnv["guid"],
4080 "subject" => $cnv["subject"],
4081 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4082 "participants" => $cnv["recips"],
4086 $type = "conversation";
4089 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4093 * Split a name into first name and last name
4095 * @param string $name The name
4097 * @return array The array with "first" and "last"
4099 public static function splitName($name) {
4100 $name = trim($name);
4102 // Is the name longer than 64 characters? Then cut the rest of it.
4103 if (strlen($name) > 64) {
4104 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4105 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4107 $name = substr($name, 0, 64);
4111 // Take the first word as first name
4112 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4113 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4114 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4115 return ['first' => $first, 'last' => $last];
4118 // Take the last word as last name
4119 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4120 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4122 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4123 return ['first' => $first, 'last' => $last];
4126 // Take the first 32 characters if there is no space in the first 32 characters
4127 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4128 $first = substr($name, 0, 32);
4129 $last = substr($name, 32);
4130 return ['first' => $first, 'last' => $last];
4133 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4134 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4136 // Check if the last name is longer than 32 characters
4137 if (strlen($last) > 32) {
4138 if (strpos($last, ' ') <= 32) {
4139 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4141 $last = substr($last, 0, 32);
4145 return ['first' => $first, 'last' => $last];
4149 * Create profile data
4151 * @param int $uid The user id
4153 * @return array The profile data
4154 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4156 private static function createProfileData($uid)
4158 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
4159 if (!DBA::isResult($profile)) {
4163 $handle = $profile["addr"];
4165 $split_name = self::splitName($profile['name']);
4166 $first = $split_name['first'];
4167 $last = $split_name['last'];
4169 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4170 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4171 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4172 $searchable = ($profile['net-publish'] ? 'true' : 'false');
4178 if ($searchable === 'true') {
4181 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4182 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4186 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4189 $about = BBCode::toMarkdown($profile['about']);
4191 $location = $profile['location'];
4193 if ($profile['pub_keywords']) {
4194 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4195 $kw = str_replace(' ', ' ', $kw);
4196 $arr = explode(' ', $kw);
4198 for ($x = 0; $x < 5; $x ++) {
4199 if (!empty($arr[$x])) {
4200 $tags .= '#'. trim($arr[$x]) .' ';
4205 $tags = trim($tags);
4208 return ["author" => $handle,
4209 "first_name" => $first,
4210 "last_name" => $last,
4211 "image_url" => $large,
4212 "image_url_medium" => $medium,
4213 "image_url_small" => $small,
4216 "location" => $location,
4217 "searchable" => $searchable,
4219 "tag_string" => $tags];
4223 * Sends profile data
4225 * @param int $uid The user id
4226 * @param bool $recips optional, default false
4228 * @throws \Exception
4230 public static function sendProfile($uid, $recips = false)
4236 $owner = User::getOwnerDataById($uid);
4243 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4244 AND `uid` = %d AND `rel` != %d",
4245 DBA::escape(Protocol::DIASPORA),
4247 intval(Contact::SHARING)
4255 $message = self::createProfileData($uid);
4257 // @ToDo Split this into single worker jobs
4258 foreach ($recips as $recip) {
4259 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4260 self::buildAndTransmit($owner, $recip, "profile", $message);
4265 * Creates the signature for likes that are created on our system
4267 * @param integer $uid The user of that comment
4268 * @param array $item Item array
4270 * @return array Signed content
4271 * @throws \Exception
4273 public static function createLikeSignature($uid, array $item)
4275 $owner = User::getOwnerDataById($uid);
4276 if (empty($owner)) {
4277 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4281 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4285 $message = self::constructLike($item, $owner);
4286 if ($message === false) {
4290 $message["author_signature"] = self::signature($owner, $message);
4296 * Creates the signature for Comments that are created on our system
4298 * @param integer $uid The user of that comment
4299 * @param array $item Item array
4301 * @return array Signed content
4302 * @throws \Exception
4304 public static function createCommentSignature($uid, array $item)
4306 $owner = User::getOwnerDataById($uid);
4307 if (empty($owner)) {
4308 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4312 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4313 $item['thr-parent'] = $item['parent-uri'];
4315 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4316 if (!DBA::isResult($parent)) {
4320 $item['parent-uri'] = $parent['parent-uri'];
4322 $message = self::constructComment($item, $owner);
4323 if ($message === false) {
4327 $message["author_signature"] = self::signature($owner, $message);