3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol;
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\Markdown;
27 use Friendica\Core\Cache\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\GContact;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\ItemDeliveryData;
40 use Friendica\Model\Mail;
41 use Friendica\Model\Profile;
42 use Friendica\Model\Tag;
43 use Friendica\Model\Term;
44 use Friendica\Model\User;
45 use Friendica\Network\Probe;
46 use Friendica\Util\Crypto;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Map;
49 use Friendica\Util\Network;
50 use Friendica\Util\Strings;
51 use Friendica\Util\XML;
52 use Friendica\Worker\Delivery;
56 * This class contain functions to create and send Diaspora XML files
61 * Mark the relay contact of the given contact for archival
62 * This is called whenever there is a communication issue with the server.
63 * It avoids sending stuff to servers who don't exist anymore.
64 * The relay contact is a technical contact entry that exists once per server.
66 * @param array $contact of the relay contact
68 public static function markRelayForArchival(array $contact)
70 if (!empty($contact['contact-type']) && ($contact['contact-type'] == Contact::TYPE_RELAY)) {
71 // This is already the relay contact, we don't need to fetch it
72 $relay_contact = $contact;
73 } elseif (empty($contact['baseurl'])) {
74 if (!empty($contact['batch'])) {
75 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => Contact::TYPE_RELAY];
76 $relay_contact = DBA::selectFirst('contact', [], $condition);
81 $relay_contact = self::getRelayContact($contact['baseurl'], []);
84 if (!empty($relay_contact)) {
85 Logger::info('Relay contact will be marked for archival', ['id' => $relay_contact['id'], 'url' => $relay_contact['url']]);
86 Contact::markForArchival($relay_contact);
91 * Return a list of relay servers
93 * The list contains not only the official relays but also servers that we serve directly
95 * @param integer $item_id The id of the item that is sent
96 * @param array $contacts The previously fetched contacts
98 * @return array of relay servers
99 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
101 public static function relayList($item_id, array $contacts = [])
105 // Fetching relay servers
106 $serverdata = DI::config()->get("system", "relay_server");
108 if (!empty($serverdata)) {
109 $servers = explode(",", $serverdata);
110 foreach ($servers as $server) {
111 $serverlist[$server] = trim($server);
115 if (DI::config()->get("system", "relay_directly", false)) {
116 // We distribute our stuff based on the parent to ensure that the thread will be complete
117 $parent = Item::selectFirst(['parent'], ['id' => $item_id]);
118 if (!DBA::isResult($parent)) {
122 // Servers that want to get all content
123 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
124 while ($server = DBA::fetch($servers)) {
125 $serverlist[$server['url']] = $server['url'];
128 // All tags of the current post
129 $condition = ['otype' => Term::OBJECT_TYPE_POST, 'type' => Term::HASHTAG, 'oid' => $parent['parent']];
130 $tags = DBA::select('term', ['term'], $condition);
132 while ($tag = DBA::fetch($tags)) {
133 $taglist[] = $tag['term'];
136 // All servers who wants content with this tag
138 if (!empty($taglist)) {
139 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
140 while ($server = DBA::fetch($tagserver)) {
141 $tagserverlist[] = $server['gserver-id'];
145 // All adresses with the given id
146 if (!empty($tagserverlist)) {
147 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
148 while ($server = DBA::fetch($servers)) {
149 $serverlist[$server['url']] = $server['url'];
154 // Now we are collecting all relay contacts
155 foreach ($serverlist as $server_url) {
156 // We don't send messages to ourselves
157 if (Strings::compareLink($server_url, DI::baseUrl())) {
160 $contact = self::getRelayContact($server_url);
161 if (is_bool($contact)) {
166 foreach ($contacts as $entry) {
167 if ($entry['batch'] == $contact['batch']) {
173 $contacts[] = $contact;
181 * Return a contact for a given server address or creates a dummy entry
183 * @param string $server_url The url of the server
184 * @param array $fields Fieldlist
185 * @return array with the contact
188 private static function getRelayContact(string $server_url, array $fields = ['batch', 'id', 'url', 'name', 'network', 'protocol', 'archive', 'blocked'])
190 // Fetch the relay contact
191 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
192 'contact-type' => Contact::TYPE_RELAY];
193 $contact = DBA::selectFirst('contact', $fields, $condition);
195 if (DBA::isResult($contact)) {
196 if ($contact['archive'] || $contact['blocked']) {
201 self::setRelayContact($server_url);
203 $contact = DBA::selectFirst('contact', $fields, $condition);
204 if (DBA::isResult($contact)) {
209 // It should never happen that we arrive here
214 * Update or insert a relay contact
216 * @param string $server_url The url of the server
217 * @param array $network_fields Optional network specific fields
220 public static function setRelayContact($server_url, array $network_fields = [])
222 $fields = ['created' => DateTimeFormat::utcNow(),
223 'name' => 'relay', 'nick' => 'relay', 'url' => $server_url,
224 'nurl' => Strings::normaliseLink($server_url),
225 'network' => Protocol::DIASPORA, 'uid' => 0,
226 'batch' => $server_url . '/receive/public',
227 'rel' => Contact::FOLLOWER, 'blocked' => false,
228 'pending' => false, 'writable' => true,
229 'baseurl' => $server_url, 'contact-type' => Contact::TYPE_RELAY];
231 $fields = array_merge($fields, $network_fields);
233 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url)];
234 $old = DBA::selectFirst('contact', [], $condition);
235 if (DBA::isResult($old)) {
236 unset($fields['created']);
237 $condition = ['id' => $old['id']];
239 Logger::info('Update relay contact', ['fields' => $fields, 'condition' => $condition]);
240 DBA::update('contact', $fields, $condition, $old);
242 Logger::info('Create relay contact', ['fields' => $fields]);
243 Contact::insert($fields);
248 * Return a list of participating contacts for a thread
250 * This is used for the participation feature.
251 * One of the parameters is a contact array.
252 * This is done to avoid duplicates.
254 * @param integer $thread The id of the thread
255 * @param array $contacts The previously fetched contacts
257 * @return array of relay servers
260 public static function participantsForThread($thread, array $contacts)
262 $r = DBA::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`url`, `contact`.`name`, `contact`.`network`, `contact`.`protocol`,
263 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
264 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
265 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
266 WHERE `participation`.`iid` = ? AND NOT `contact`.`archive`", $thread);
268 while ($contact = DBA::fetch($r)) {
269 if (!empty($contact['fnetwork'])) {
270 $contact['network'] = $contact['fnetwork'];
272 unset($contact['fnetwork']);
274 if (empty($contact['protocol'])) {
275 $contact['protocol'] = $contact['network'];
278 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
279 $contact['batch'] = $contact['fbatch'];
281 unset($contact['fbatch']);
284 foreach ($contacts as $entry) {
285 if ($entry['batch'] == $contact['batch']) {
291 $contacts[] = $contact;
300 * repairs a signature that was double encoded
302 * The function is unused at the moment. It was copied from the old implementation.
304 * @param string $signature The signature
305 * @param string $handle The handle of the signature owner
306 * @param integer $level This value is only set inside this function to avoid endless loops
308 * @return string the repaired signature
311 private static function repairSignature($signature, $handle = "", $level = 1)
313 if ($signature == "") {
317 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
318 $signature = base64_decode($signature);
319 Logger::log("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, Logger::DEBUG);
321 // Do a recursive call to be able to fix even multiple levels
323 $signature = self::repairSignature($signature, $handle, ++$level);
331 * verify the envelope and return the verified data
333 * @param string $envelope The magic envelope
335 * @return string verified data
336 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
337 * @throws \ImagickException
339 private static function verifyMagicEnvelope($envelope)
341 $basedom = XML::parseString($envelope);
343 if (!is_object($basedom)) {
344 Logger::log("Envelope is no XML file");
348 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
350 if (sizeof($children) == 0) {
351 Logger::log("XML has no children");
357 $data = Strings::base64UrlDecode($children->data);
358 $type = $children->data->attributes()->type[0];
360 $encoding = $children->encoding;
362 $alg = $children->alg;
364 $sig = Strings::base64UrlDecode($children->sig);
365 $key_id = $children->sig->attributes()->key_id[0];
367 $handle = Strings::base64UrlDecode($key_id);
370 $b64url_data = Strings::base64UrlEncode($data);
371 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
373 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
376 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
380 $key = self::key($handle);
382 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
386 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
388 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
396 * encrypts data via AES
398 * @param string $key The AES key
399 * @param string $iv The IV (is used for CBC encoding)
400 * @param string $data The data that is to be encrypted
402 * @return string encrypted data
404 private static function aesEncrypt($key, $iv, $data)
406 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
410 * decrypts data via AES
412 * @param string $key The AES key
413 * @param string $iv The IV (is used for CBC encoding)
414 * @param string $encrypted The encrypted data
416 * @return string decrypted data
418 private static function aesDecrypt($key, $iv, $encrypted)
420 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
424 * Decodes incoming Diaspora message in the new format
426 * @param string $raw raw post message
427 * @param string $privKey The private key of the importer
428 * @param boolean $no_exit Don't do an http exit on error
431 * 'message' -> decoded Diaspora XML message
432 * 'author' -> author diaspora handle
433 * 'key' -> author public key (converted to pkcs#8)
434 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
435 * @throws \ImagickException
437 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
439 $data = json_decode($raw);
441 // Is it a private post? Then decrypt the outer Salmon
442 if (is_object($data)) {
443 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
444 $ciphertext = base64_decode($data->encrypted_magic_envelope);
446 $outer_key_bundle = '';
447 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
448 $j_outer_key_bundle = json_decode($outer_key_bundle);
450 if (!is_object($j_outer_key_bundle)) {
451 Logger::log('Outer Salmon did not verify. Discarding.');
455 throw new \Friendica\Network\HTTPException\BadRequestException();
459 $outer_iv = base64_decode($j_outer_key_bundle->iv);
460 $outer_key = base64_decode($j_outer_key_bundle->key);
462 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
467 $basedom = XML::parseString($xml);
469 if (!is_object($basedom)) {
470 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
474 throw new \Friendica\Network\HTTPException\BadRequestException();
478 $base = $basedom->children(ActivityNamespace::SALMON_ME);
480 // Not sure if this cleaning is needed
481 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
483 // Build the signed data
484 $type = $base->data[0]->attributes()->type[0];
485 $encoding = $base->encoding;
487 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
489 // This is the signature
490 $signature = Strings::base64UrlDecode($base->sig);
492 // Get the senders' public key
493 $key_id = $base->sig[0]->attributes()->key_id[0];
494 $author_addr = base64_decode($key_id);
495 if ($author_addr == '') {
496 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
500 throw new \Friendica\Network\HTTPException\BadRequestException();
504 $key = self::key($author_addr);
506 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
510 throw new \Friendica\Network\HTTPException\BadRequestException();
514 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
516 Logger::log('Message did not verify. Discarding.');
520 throw new \Friendica\Network\HTTPException\BadRequestException();
524 return ['message' => (string)Strings::base64UrlDecode($base->data),
525 'author' => XML::unescape($author_addr),
526 'key' => (string)$key];
530 * Decodes incoming Diaspora message in the deprecated format
532 * @param string $xml urldecoded Diaspora salmon
533 * @param string $privKey The private key of the importer
536 * 'message' -> decoded Diaspora XML message
537 * 'author' -> author diaspora handle
538 * 'key' -> author public key (converted to pkcs#8)
539 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
540 * @throws \ImagickException
542 public static function decode(string $xml, string $privKey = '')
545 $basedom = XML::parseString($xml);
547 if (!is_object($basedom)) {
548 Logger::log("XML is not parseable.");
551 $children = $basedom->children('https://joindiaspora.com/protocol');
553 $inner_aes_key = null;
556 if ($children->header) {
558 $author_link = str_replace('acct:', '', $children->header->author_id);
560 // This happens with posts from a relais
561 if (empty($privKey)) {
562 Logger::log("This is no private post in the old format", Logger::DEBUG);
566 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
568 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
569 $ciphertext = base64_decode($encrypted_header->ciphertext);
571 $outer_key_bundle = '';
572 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
574 $j_outer_key_bundle = json_decode($outer_key_bundle);
576 $outer_iv = base64_decode($j_outer_key_bundle->iv);
577 $outer_key = base64_decode($j_outer_key_bundle->key);
579 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
581 Logger::log('decrypted: '.$decrypted, Logger::DEBUG);
582 $idom = XML::parseString($decrypted);
584 $inner_iv = base64_decode($idom->iv);
585 $inner_aes_key = base64_decode($idom->aes_key);
587 $author_link = str_replace('acct:', '', $idom->author_id);
590 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
592 // figure out where in the DOM tree our data is hiding
595 if ($dom->provenance->data) {
596 $base = $dom->provenance;
597 } elseif ($dom->env->data) {
599 } elseif ($dom->data) {
604 Logger::log('unable to locate salmon data in xml');
605 throw new \Friendica\Network\HTTPException\BadRequestException();
609 // Stash the signature away for now. We have to find their key or it won't be good for anything.
610 $signature = Strings::base64UrlDecode($base->sig);
614 // strip whitespace so our data element will return to one big base64 blob
615 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
618 // stash away some other stuff for later
620 $type = $base->data[0]->attributes()->type[0];
621 $keyhash = $base->sig[0]->attributes()->keyhash[0];
622 $encoding = $base->encoding;
626 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
630 $data = Strings::base64UrlDecode($data);
634 $inner_decrypted = $data;
636 // Decode the encrypted blob
637 $inner_encrypted = base64_decode($data);
638 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
642 Logger::log('Could not retrieve author URI.');
643 throw new \Friendica\Network\HTTPException\BadRequestException();
645 // Once we have the author URI, go to the web and try to find their public key
646 // (first this will look it up locally if it is in the fcontact cache)
647 // This will also convert diaspora public key from pkcs#1 to pkcs#8
649 Logger::log('Fetching key for '.$author_link);
650 $key = self::key($author_link);
653 Logger::log('Could not retrieve author key.');
654 throw new \Friendica\Network\HTTPException\BadRequestException();
657 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
660 Logger::log('Message did not verify. Discarding.');
661 throw new \Friendica\Network\HTTPException\BadRequestException();
664 Logger::log('Message verified.');
666 return ['message' => (string)$inner_decrypted,
667 'author' => XML::unescape($author_link),
668 'key' => (string)$key];
673 * Dispatches public messages and find the fitting receivers
675 * @param array $msg The post that will be dispatched
677 * @return int The message id of the generated message, "true" or "false" if there was an error
678 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
679 * @throws \ImagickException
681 public static function dispatchPublic($msg)
683 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
685 Logger::log("diaspora is disabled");
689 if (!($fields = self::validPosting($msg))) {
690 Logger::log("Invalid posting");
694 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
695 $success = self::dispatch($importer, $msg, $fields);
701 * Dispatches the different message types to the different functions
703 * @param array $importer Array of the importer user
704 * @param array $msg The post that will be dispatched
705 * @param SimpleXMLElement $fields SimpleXML object that contains the message
707 * @return int The message id of the generated message, "true" or "false" if there was an error
708 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
709 * @throws \ImagickException
711 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
713 // The sender is the handle of the contact that sent the message.
714 // This will often be different with relayed messages (for example "like" and "comment")
715 $sender = $msg["author"];
717 // This is only needed for private postings since this is already done for public ones before
718 if (is_null($fields)) {
720 if (!($fields = self::validPosting($msg))) {
721 Logger::log("Invalid posting");
728 $type = $fields->getName();
730 Logger::log("Received message type ".$type." from ".$sender." for user ".$importer["uid"], Logger::DEBUG);
733 case "account_migration":
735 Logger::log('Message with type ' . $type . ' is not private, quitting.');
738 return self::receiveAccountMigration($importer, $fields);
740 case "account_deletion":
741 return self::receiveAccountDeletion($fields);
744 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
748 Logger::log('Message with type ' . $type . ' is not private, quitting.');
751 return self::receiveContactRequest($importer, $fields);
755 Logger::log('Message with type ' . $type . ' is not private, quitting.');
758 return self::receiveConversation($importer, $msg, $fields);
761 return self::receiveLike($importer, $sender, $fields);
765 Logger::log('Message with type ' . $type . ' is not private, quitting.');
768 return self::receiveMessage($importer, $fields);
770 case "participation":
772 Logger::log('Message with type ' . $type . ' is not private, quitting.');
775 return self::receiveParticipation($importer, $fields);
777 case "photo": // Not implemented
778 return self::receivePhoto($importer, $fields);
780 case "poll_participation": // Not implemented
781 return self::receivePollParticipation($importer, $fields);
785 Logger::log('Message with type ' . $type . ' is not private, quitting.');
788 return self::receiveProfile($importer, $fields);
791 return self::receiveReshare($importer, $fields, $msg["message"]);
794 return self::receiveRetraction($importer, $sender, $fields);
796 case "status_message":
797 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
800 Logger::log("Unknown message type ".$type);
806 * Checks if a posting is valid and fetches the data fields.
808 * This function does not only check the signature.
809 * It also does the conversion between the old and the new diaspora format.
811 * @param array $msg Array with the XML, the sender handle and the sender signature
813 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
814 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
815 * @throws \ImagickException
817 private static function validPosting($msg)
819 $data = XML::parseString($msg["message"]);
821 if (!is_object($data)) {
822 Logger::log("No valid XML ".$msg["message"], Logger::DEBUG);
826 // Is this the new or the old version?
827 if ($data->getName() == "XML") {
829 foreach ($data->post->children() as $child) {
837 $type = $element->getName();
840 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
842 // All retractions are handled identically from now on.
843 // In the new version there will only be "retraction".
844 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
845 $type = "retraction";
847 if ($type == "request") {
851 $fields = new SimpleXMLElement("<".$type."/>");
854 $author_signature = null;
855 $parent_author_signature = null;
857 foreach ($element->children() as $fieldname => $entry) {
859 // Translation for the old XML structure
860 if ($fieldname == "diaspora_handle") {
861 $fieldname = "author";
863 if ($fieldname == "participant_handles") {
864 $fieldname = "participants";
866 if (in_array($type, ["like", "participation"])) {
867 if ($fieldname == "target_type") {
868 $fieldname = "parent_type";
871 if ($fieldname == "sender_handle") {
872 $fieldname = "author";
874 if ($fieldname == "recipient_handle") {
875 $fieldname = "recipient";
877 if ($fieldname == "root_diaspora_id") {
878 $fieldname = "root_author";
880 if ($type == "status_message") {
881 if ($fieldname == "raw_message") {
885 if ($type == "retraction") {
886 if ($fieldname == "post_guid") {
887 $fieldname = "target_guid";
889 if ($fieldname == "type") {
890 $fieldname = "target_type";
895 if (($fieldname == "author_signature") && ($entry != "")) {
896 $author_signature = base64_decode($entry);
897 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
898 $parent_author_signature = base64_decode($entry);
899 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
900 if ($signed_data != "") {
904 $signed_data .= $entry;
906 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
907 || ($orig_type == "relayable_retraction")
909 XML::copy($entry, $fields, $fieldname);
913 // This is something that shouldn't happen at all.
914 if (in_array($type, ["status_message", "reshare", "profile"])) {
915 if ($msg["author"] != $fields->author) {
916 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
921 // Only some message types have signatures. So we quit here for the other types.
922 if (!in_array($type, ["comment", "like"])) {
925 // No author_signature? This is a must, so we quit.
926 if (!isset($author_signature)) {
927 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
931 if (isset($parent_author_signature)) {
932 $key = self::key($msg["author"]);
934 Logger::log("No key found for parent author ".$msg["author"], Logger::DEBUG);
938 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
939 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);
944 $key = self::key($fields->author);
946 Logger::log("No key found for author ".$fields->author, Logger::DEBUG);
950 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
951 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);
959 * Fetches the public key for a given handle
961 * @param string $handle The handle
963 * @return string The public key
964 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
965 * @throws \ImagickException
967 private static function key($handle)
969 $handle = strval($handle);
971 Logger::log("Fetching diaspora key for: ".$handle);
973 $r = self::personByHandle($handle);
982 * Fetches data for a given handle
984 * @param string $handle The handle
985 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
987 * @return array the queried data
988 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
989 * @throws \ImagickException
991 public static function personByHandle($handle, $update = null)
993 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
994 if (!DBA::isResult($person)) {
995 $urls = [$handle, str_replace('http://', 'https://', $handle), Strings::normaliseLink($handle)];
996 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'url' => $urls]);
999 if (DBA::isResult($person)) {
1000 Logger::debug("In cache " . print_r($person, true));
1002 if (is_null($update)) {
1003 // update record occasionally so it doesn't get stale
1004 $d = strtotime($person["updated"]." +00:00");
1005 if ($d < strtotime("now - 14 days")) {
1009 if ($person["guid"] == "") {
1013 } elseif (is_null($update)) {
1014 $update = !DBA::isResult($person);
1020 Logger::log("create or refresh", Logger::DEBUG);
1021 $r = Probe::uri($handle, Protocol::DIASPORA);
1023 // Note that Friendica contacts will return a "Diaspora person"
1024 // if Diaspora connectivity is enabled on their server
1025 if ($r && ($r["network"] === Protocol::DIASPORA)) {
1026 self::updateFContact($r);
1028 $person = self::personByHandle($handle, false);
1036 * Updates the fcontact table
1038 * @param array $arr The fcontact data
1039 * @throws \Exception
1041 private static function updateFContact($arr)
1043 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
1044 'request' => $arr["request"], 'nick' => $arr["nick"],
1045 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
1046 'batch' => $arr["batch"], 'notify' => $arr["notify"],
1047 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
1048 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
1049 'updated' => DateTimeFormat::utcNow()];
1051 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
1053 DBA::update('fcontact', $fields, $condition, true);
1057 * get a handle (user@domain.tld) from a given contact id
1059 * @param int $contact_id The id in the contact table
1060 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1062 * @return string the handle
1063 * @throws \Exception
1065 private static function handleFromContact($contact_id, $pcontact_id = 0)
1069 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
1071 if ($pcontact_id != 0) {
1072 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
1074 if (DBA::isResult($contact) && !empty($contact["addr"])) {
1075 return strtolower($contact["addr"]);
1080 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1084 if (DBA::isResult($r)) {
1087 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1089 if ($contact['addr'] != "") {
1090 $handle = $contact['addr'];
1092 $baseurl_start = strpos($contact['url'], '://') + 3;
1093 // allows installations in a subdirectory--not sure how Diaspora will handle
1094 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1095 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1096 $handle = $contact['nick'].'@'.$baseurl;
1100 return strtolower($handle);
1104 * get a url (scheme://domain.tld/u/user) from a given Diaspora*
1107 * @param mixed $fcontact_guid Hexadecimal string guid
1109 * @return string the contact url or null
1110 * @throws \Exception
1112 public static function urlFromContactGuid($fcontact_guid)
1114 Logger::log("fcontact guid is ".$fcontact_guid, Logger::DEBUG);
1117 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1118 DBA::escape(Protocol::DIASPORA),
1119 DBA::escape($fcontact_guid)
1122 if (DBA::isResult($r)) {
1123 return $r[0]['url'];
1130 * Get a contact id for a given handle
1132 * @todo Move to Friendica\Model\Contact
1134 * @param int $uid The user id
1135 * @param string $handle The handle in the format user@domain.tld
1137 * @return array Contact data
1138 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1139 * @throws \ImagickException
1141 private static function contactByHandle($uid, $handle)
1143 $cid = Contact::getIdForURL($handle, $uid);
1145 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1149 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1150 if (!DBA::isResult($contact)) {
1151 // This here shouldn't happen at all
1152 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1160 * Checks if the given contact url does support ActivityPub
1162 * @param string $url profile url
1163 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1165 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1166 * @throws \ImagickException
1168 public static function isSupportedByContactUrl($url, $update = null)
1170 return !empty(self::personByHandle($url, $update));
1174 * Check if posting is allowed for this contact
1176 * @param array $importer Array of the importer user
1177 * @param array $contact The contact that is checked
1178 * @param bool $is_comment Is the check for a comment?
1180 * @return bool is the contact allowed to post?
1182 private static function postAllow(array $importer, array $contact, $is_comment = false)
1185 * Perhaps we were already sharing with this person. Now they're sharing with us.
1186 * That makes us friends.
1187 * Normally this should have handled by getting a request - but this could get lost
1189 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1190 // It is not removed by now. Possibly the code is needed?
1191 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1194 // array('rel' => Contact::FRIEND, 'writable' => true),
1195 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1198 // $contact["rel"] = Contact::FRIEND;
1199 // Logger::log("defining user ".$contact["nick"]." as friend");
1202 // Contact server is blocked
1203 if (Network::isUrlBlocked($contact['url'])) {
1205 // We don't seem to like that person
1206 } elseif ($contact["blocked"]) {
1207 // Maybe blocked, don't accept.
1209 // We are following this person?
1210 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1211 // Yes, then it is fine.
1213 // Is it a post to a community?
1214 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1217 // Is the message a global user or a comment?
1218 } elseif (($importer["uid"] == 0) || $is_comment) {
1219 // Messages for the global users and comments are always accepted
1227 * Fetches the contact id for a handle and checks if posting is allowed
1229 * @param array $importer Array of the importer user
1230 * @param string $handle The checked handle in the format user@domain.tld
1231 * @param bool $is_comment Is the check for a comment?
1233 * @return array The contact data
1234 * @throws \Exception
1236 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1238 $contact = self::contactByHandle($importer["uid"], $handle);
1240 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1241 // If a contact isn't found, we accept it anyway if it is a comment
1242 if ($is_comment && ($importer["uid"] != 0)) {
1243 return self::contactByHandle(0, $handle);
1244 } elseif ($is_comment) {
1251 if (!self::postAllow($importer, $contact, $is_comment)) {
1252 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1259 * Does the message already exists on the system?
1261 * @param int $uid The user id
1262 * @param string $guid The guid of the message
1264 * @return int|bool message id if the message already was stored into the system - or false.
1265 * @throws \Exception
1267 private static function messageExists($uid, $guid)
1269 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1270 if (DBA::isResult($item)) {
1271 Logger::log("message ".$guid." already exists for user ".$uid);
1279 * Checks for links to posts in a message
1281 * @param array $item The item array
1284 private static function fetchGuid(array $item)
1286 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1287 preg_replace_callback(
1289 function ($match) use ($item) {
1290 self::fetchGuidSub($match, $item);
1295 preg_replace_callback(
1296 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1297 function ($match) use ($item) {
1298 self::fetchGuidSub($match, $item);
1305 * Checks for relative /people/* links in an item body to match local
1306 * contacts or prepends the remote host taken from the author link.
1308 * @param string $body The item body to replace links from
1309 * @param string $author_link The author link for missing local contact fallback
1311 * @return string the replaced string
1313 public static function replacePeopleGuid($body, $author_link)
1315 $return = preg_replace_callback(
1316 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1317 function ($match) use ($author_link) {
1319 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1320 // 1 => '0123456789abcdef'
1322 $handle = self::urlFromContactGuid($match[1]);
1325 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1327 // No local match, restoring absolute remote URL from author scheme and host
1328 $author_url = parse_url($author_link);
1329 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1341 * sub function of "fetchGuid" which checks for links in messages
1343 * @param array $match array containing a link that has to be checked for a message link
1344 * @param array $item The item array
1346 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1347 * @throws \ImagickException
1349 private static function fetchGuidSub($match, $item)
1351 if (!self::storeByGuid($match[1], $item["author-link"])) {
1352 self::storeByGuid($match[1], $item["owner-link"]);
1357 * Fetches an item with a given guid from a given server
1359 * @param string $guid the message guid
1360 * @param string $server The server address
1361 * @param int $uid The user id of the user
1363 * @return int the message id of the stored message or false
1364 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1365 * @throws \ImagickException
1367 private static function storeByGuid($guid, $server, $uid = 0)
1369 $serverparts = parse_url($server);
1371 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1375 $server = $serverparts["scheme"]."://".$serverparts["host"];
1377 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1379 $msg = self::message($guid, $server);
1385 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1387 // Now call the dispatcher
1388 return self::dispatchPublic($msg);
1392 * Fetches a message from a server
1394 * @param string $guid message guid
1395 * @param string $server The url of the server
1396 * @param int $level Endless loop prevention
1399 * 'message' => The message XML
1400 * 'author' => The author handle
1401 * 'key' => The public key of the author
1402 * @throws \Exception
1404 private static function message($guid, $server, $level = 0)
1410 // This will work for new Diaspora servers and Friendica servers from 3.5
1411 $source_url = $server."/fetch/post/".urlencode($guid);
1413 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1415 $envelope = Network::fetchUrl($source_url);
1417 Logger::log("Envelope was fetched.", Logger::DEBUG);
1418 $x = self::verifyMagicEnvelope($envelope);
1420 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1422 Logger::log("Envelope was verified.", Logger::DEBUG);
1432 $source_xml = XML::parseString($x);
1434 if (!is_object($source_xml)) {
1438 if ($source_xml->post->reshare) {
1439 // Reshare of a reshare - old Diaspora version
1440 Logger::log("Message is a reshare", Logger::DEBUG);
1441 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1442 } elseif ($source_xml->getName() == "reshare") {
1443 // Reshare of a reshare - new Diaspora version
1444 Logger::log("Message is a new reshare", Logger::DEBUG);
1445 return self::message($source_xml->root_guid, $server, ++$level);
1450 // Fetch the author - for the old and the new Diaspora version
1451 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1452 $author = (string)$source_xml->post->status_message->diaspora_handle;
1453 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1454 $author = (string)$source_xml->author;
1457 // If this isn't a "status_message" then quit
1459 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1463 $msg = ["message" => $x, "author" => $author];
1465 $msg["key"] = self::key($msg["author"]);
1471 * Fetches an item with a given URL
1473 * @param string $url the message url
1475 * @return int the message id of the stored message or false
1476 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1477 * @throws \ImagickException
1479 public static function fetchByURL($url, $uid = 0)
1481 // Check for Diaspora (and Friendica) typical paths
1482 if (!preg_match("=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1483 Logger::info('Invalid url', ['url' => $url]);
1487 $guid = urldecode($matches[2]);
1489 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1490 if (DBA::isResult($item)) {
1491 Logger::info('Found', ['id' => $item['id']]);
1495 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1496 $ret = self::storeByGuid($guid, $matches[1], $uid);
1497 Logger::info('Result', ['ret' => $ret]);
1499 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1500 if (DBA::isResult($item)) {
1501 Logger::info('Found', ['id' => $item['id']]);
1504 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1510 * Fetches the item record of a given guid
1512 * @param int $uid The user id
1513 * @param string $guid message guid
1514 * @param string $author The handle of the item
1515 * @param array $contact The contact of the item owner
1517 * @return array the item record
1518 * @throws \Exception
1520 private static function parentItem($uid, $guid, $author, array $contact)
1522 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1523 'author-name', 'author-link', 'author-avatar',
1524 'owner-name', 'owner-link', 'owner-avatar'];
1525 $condition = ['uid' => $uid, 'guid' => $guid];
1526 $item = Item::selectFirst($fields, $condition);
1528 if (!DBA::isResult($item)) {
1529 $person = self::personByHandle($author);
1530 $result = self::storeByGuid($guid, $person["url"], $uid);
1532 // We don't have an url for items that arrived at the public dispatcher
1533 if (!$result && !empty($contact["url"])) {
1534 $result = self::storeByGuid($guid, $contact["url"], $uid);
1538 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1540 $item = Item::selectFirst($fields, $condition);
1544 if (!DBA::isResult($item)) {
1545 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1548 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1554 * returns contact details
1556 * @param array $def_contact The default contact if the person isn't found
1557 * @param array $person The record of the person
1558 * @param int $uid The user id
1561 * 'cid' => contact id
1562 * 'network' => network type
1563 * @throws \Exception
1565 private static function authorContactByUrl($def_contact, $person, $uid)
1567 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1568 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1569 if (DBA::isResult($contact)) {
1570 $cid = $contact["id"];
1571 $network = $contact["network"];
1573 $cid = $def_contact["id"];
1574 $network = Protocol::DIASPORA;
1577 return ["cid" => $cid, "network" => $network];
1581 * Is the profile a hubzilla profile?
1583 * @param string $url The profile link
1585 * @return bool is it a hubzilla server?
1587 private static function isHubzilla($url)
1589 return(strstr($url, '/channel/'));
1593 * Generate a post link with a given handle and message guid
1595 * @param string $addr The user handle
1596 * @param string $guid message guid
1597 * @param string $parent_guid optional parent guid
1599 * @return string the post link
1600 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1601 * @throws \ImagickException
1603 private static function plink($addr, $guid, $parent_guid = '')
1605 $contact = Contact::getDetailsByAddr($addr);
1606 if (empty($contact)) {
1607 Logger::info('No contact data for address', ['addr' => $addr]);
1611 if (empty($contact['baseurl'])) {
1612 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1613 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1617 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1618 if (!empty($gserver['platform'])) {
1619 $platform = strtolower($gserver['platform']);
1620 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1623 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1624 if (self::isHubzilla($contact['url'])) {
1625 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1626 $platform = 'hubzilla';
1627 } elseif ($contact['network'] == Protocol::DFRN) {
1628 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1629 $platform = 'friendica';
1633 if ($platform == 'friendica') {
1634 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1637 if ($platform == 'hubzilla') {
1638 return $contact['baseurl'] . '/item/' . $guid;
1641 if ($platform == 'socialhome') {
1642 return $contact['baseurl'] . '/content/' . $guid;
1645 if ($platform != 'diaspora') {
1646 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1650 if ($parent_guid != '') {
1651 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1653 return $contact['baseurl'] . '/posts/' . $guid;
1658 * Receives account migration
1660 * @param array $importer Array of the importer user
1661 * @param object $data The message object
1663 * @return bool Success
1664 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1665 * @throws \ImagickException
1667 private static function receiveAccountMigration(array $importer, $data)
1669 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1670 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1671 $signature = Strings::escapeTags(XML::unescape($data->signature));
1673 $contact = self::contactByHandle($importer["uid"], $old_handle);
1675 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1679 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1682 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1683 $key = self::key($old_handle);
1684 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1685 Logger::log('No valid signature for migration.');
1689 // Update the profile
1690 self::receiveProfile($importer, $data->profile);
1692 // change the technical stuff in contact and gcontact
1693 $data = Probe::uri($new_handle);
1694 if ($data['network'] == Protocol::PHANTOM) {
1695 Logger::log('Account for '.$new_handle." couldn't be probed.");
1699 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1700 'name' => $data['name'], 'nick' => $data['nick'],
1701 'addr' => $data['addr'], 'batch' => $data['batch'],
1702 'notify' => $data['notify'], 'poll' => $data['poll'],
1703 'network' => $data['network']];
1705 DBA::update('contact', $fields, ['addr' => $old_handle]);
1707 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1708 'name' => $data['name'], 'nick' => $data['nick'],
1709 'addr' => $data['addr'], 'connect' => $data['addr'],
1710 'notify' => $data['notify'], 'photo' => $data['photo'],
1711 'server_url' => $data['baseurl'], 'network' => $data['network']];
1713 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1715 Logger::log('Contacts are updated.');
1721 * Processes an account deletion
1723 * @param object $data The message object
1725 * @return bool Success
1726 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1728 private static function receiveAccountDeletion($data)
1730 $author = Strings::escapeTags(XML::unescape($data->author));
1732 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1733 while ($contact = DBA::fetch($contacts)) {
1734 Contact::remove($contact["id"]);
1737 DBA::delete('gcontact', ['addr' => $author]);
1739 Logger::log('Removed contacts for ' . $author);
1745 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1747 * @param string $author Author handle
1748 * @param string $guid Message guid
1749 * @param boolean $onlyfound Only return uri when found in the database
1751 * @return string The constructed uri or the one from our database
1752 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1753 * @throws \ImagickException
1755 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1757 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1758 if (DBA::isResult($item)) {
1759 return $item["uri"];
1760 } elseif (!$onlyfound) {
1761 $person = self::personByHandle($author);
1763 $parts = parse_url($person['url']);
1764 unset($parts['path']);
1765 $host_url = Network::unparseURL($parts);
1767 return $host_url . '/objects/' . $guid;
1774 * Fetch the guid from our database with a given uri
1776 * @param string $uri Message uri
1777 * @param string $uid Author handle
1779 * @return string The post guid
1780 * @throws \Exception
1782 private static function getGuidFromUri($uri, $uid)
1784 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1785 if (DBA::isResult($item)) {
1786 return $item["guid"];
1793 * Find the best importer for a comment, like, ...
1795 * @param string $guid The guid of the item
1797 * @return array|boolean the origin owner of that post - or false
1798 * @throws \Exception
1800 private static function importerForGuid($guid)
1802 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1803 if (DBA::isResult($item)) {
1804 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1805 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1806 if (DBA::isResult($contact)) {
1814 * Store the mentions in the tag table
1816 * @param integer $uriid
1817 * @param string $text
1819 private static function storeMentions(int $uriid, string $text)
1821 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1822 if (empty($matches)) {
1827 * Matching values for the preg match
1828 * [1] = mention type (@ or !)
1829 * [2] = name (optional)
1833 foreach ($matches as $match) {
1834 if (empty($match)) {
1838 $person = self::personByHandle($match[3]);
1839 if (empty($person)) {
1843 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1848 * Processes an incoming comment
1850 * @param array $importer Array of the importer user
1851 * @param string $sender The sender of the message
1852 * @param object $data The message object
1853 * @param string $xml The original XML of the message
1855 * @return int The message id of the generated comment or "false" if there was an error
1856 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1857 * @throws \ImagickException
1859 private static function receiveComment(array $importer, $sender, $data, $xml)
1861 $author = Strings::escapeTags(XML::unescape($data->author));
1862 $guid = Strings::escapeTags(XML::unescape($data->guid));
1863 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1864 $text = XML::unescape($data->text);
1866 if (isset($data->created_at)) {
1867 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1869 $created_at = DateTimeFormat::utcNow();
1872 if (isset($data->thread_parent_guid)) {
1873 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1874 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1879 $contact = self::allowedContactByHandle($importer, $sender, true);
1884 $message_id = self::messageExists($importer["uid"], $guid);
1889 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1890 if (!$parent_item) {
1894 $person = self::personByHandle($author);
1895 if (!is_array($person)) {
1896 Logger::log("unable to find author details");
1900 // Fetch the contact id - if we know this contact
1901 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1905 $datarray["uid"] = $importer["uid"];
1906 $datarray["contact-id"] = $author_contact["cid"];
1907 $datarray["network"] = $author_contact["network"];
1909 $datarray["author-link"] = $person["url"];
1910 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1912 $datarray["owner-link"] = $contact["url"];
1913 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1915 $datarray["guid"] = $guid;
1916 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1917 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1919 $datarray["verb"] = Activity::POST;
1920 $datarray["gravity"] = GRAVITY_COMMENT;
1922 if ($thr_uri != "") {
1923 $datarray["parent-uri"] = $thr_uri;
1925 $datarray["parent-uri"] = $parent_item["uri"];
1928 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1930 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1931 $datarray["source"] = $xml;
1933 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1935 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1936 $body = Markdown::toBBCode($text);
1938 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1940 self::storeMentions($datarray['uri-id'], $text);
1941 Tag::storeFromBody($datarray['uri-id'], $datarray["body"]);
1943 self::fetchGuid($datarray);
1945 // If we are the origin of the parent we store the original data.
1946 // We notify our followers during the item storage.
1947 if ($parent_item["origin"]) {
1948 $datarray['diaspora_signed_text'] = json_encode($data);
1951 $message_id = Item::insert($datarray);
1953 if ($message_id <= 0) {
1958 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1959 if ($datarray['uid'] == 0) {
1960 Item::distribute($message_id, json_encode($data));
1968 * processes and stores private messages
1970 * @param array $importer Array of the importer user
1971 * @param array $contact The contact of the message
1972 * @param object $data The message object
1973 * @param array $msg Array of the processed message, author handle and key
1974 * @param object $mesg The private message
1975 * @param array $conversation The conversation record to which this message belongs
1977 * @return bool "true" if it was successful
1978 * @throws \Exception
1980 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1982 $author = Strings::escapeTags(XML::unescape($data->author));
1983 $guid = Strings::escapeTags(XML::unescape($data->guid));
1984 $subject = Strings::escapeTags(XML::unescape($data->subject));
1986 // "diaspora_handle" is the element name from the old version
1987 // "author" is the element name from the new version
1988 if ($mesg->author) {
1989 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1990 } elseif ($mesg->diaspora_handle) {
1991 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1996 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1997 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1998 $msg_text = XML::unescape($mesg->text);
1999 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
2001 if ($msg_conversation_guid != $guid) {
2002 Logger::log("message conversation guid does not belong to the current conversation.");
2006 $body = Markdown::toBBCode($msg_text);
2007 $message_uri = $msg_author.":".$msg_guid;
2009 $person = self::personByHandle($msg_author);
2011 return Mail::insert([
2012 'uid' => $importer['uid'],
2013 'guid' => $msg_guid,
2014 'convid' => $conversation['id'],
2015 'from-name' => $person['name'],
2016 'from-photo' => $person['photo'],
2017 'from-url' => $person['url'],
2018 'contact-id' => $contact['id'],
2019 'title' => $subject,
2021 'uri' => $message_uri,
2022 'parent-uri' => $author . ':' . $guid,
2023 'created' => $msg_created_at
2028 * Processes new private messages (answers to private messages are processed elsewhere)
2030 * @param array $importer Array of the importer user
2031 * @param array $msg Array of the processed message, author handle and key
2032 * @param object $data The message object
2034 * @return bool Success
2035 * @throws \Exception
2037 private static function receiveConversation(array $importer, $msg, $data)
2039 $author = Strings::escapeTags(XML::unescape($data->author));
2040 $guid = Strings::escapeTags(XML::unescape($data->guid));
2041 $subject = Strings::escapeTags(XML::unescape($data->subject));
2042 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2043 $participants = Strings::escapeTags(XML::unescape($data->participants));
2045 $messages = $data->message;
2047 if (!count($messages)) {
2048 Logger::log("empty conversation");
2052 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
2057 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2058 if (!DBA::isResult($conversation)) {
2060 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
2061 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
2062 intval($importer["uid"]),
2064 DBA::escape($author),
2065 DBA::escape($created_at),
2066 DBA::escape(DateTimeFormat::utcNow()),
2067 DBA::escape($subject),
2068 DBA::escape($participants)
2071 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2074 if (!$conversation) {
2075 Logger::log("unable to create conversation.");
2079 foreach ($messages as $mesg) {
2080 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
2087 * Processes "like" messages
2089 * @param array $importer Array of the importer user
2090 * @param string $sender The sender of the message
2091 * @param object $data The message object
2093 * @return int The message id of the generated like or "false" if there was an error
2094 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2095 * @throws \ImagickException
2097 private static function receiveLike(array $importer, $sender, $data)
2099 $author = Strings::escapeTags(XML::unescape($data->author));
2100 $guid = Strings::escapeTags(XML::unescape($data->guid));
2101 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2102 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
2103 $positive = Strings::escapeTags(XML::unescape($data->positive));
2105 // likes on comments aren't supported by Diaspora - only on posts
2106 // But maybe this will be supported in the future, so we will accept it.
2107 if (!in_array($parent_type, ["Post", "Comment"])) {
2111 $contact = self::allowedContactByHandle($importer, $sender, true);
2116 $message_id = self::messageExists($importer["uid"], $guid);
2121 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2122 if (!$parent_item) {
2126 $person = self::personByHandle($author);
2127 if (!is_array($person)) {
2128 Logger::log("unable to find author details");
2132 // Fetch the contact id - if we know this contact
2133 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2135 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2136 // We would accept this anyhow.
2137 if ($positive == "true") {
2138 $verb = Activity::LIKE;
2140 $verb = Activity::DISLIKE;
2145 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2147 $datarray["uid"] = $importer["uid"];
2148 $datarray["contact-id"] = $author_contact["cid"];
2149 $datarray["network"] = $author_contact["network"];
2151 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2152 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2154 $datarray["guid"] = $guid;
2155 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2157 $datarray["verb"] = $verb;
2158 $datarray["gravity"] = GRAVITY_ACTIVITY;
2159 $datarray["parent-uri"] = $parent_item["uri"];
2161 $datarray["object-type"] = Activity\ObjectType::NOTE;
2163 $datarray["body"] = $verb;
2165 // Diaspora doesn't provide a date for likes
2166 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2168 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2169 if ($parent_item["id"] != $parent_item["parent"]) {
2170 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
2171 $origin = $toplevel["origin"];
2173 $origin = $parent_item["origin"];
2176 // If we are the origin of the parent we store the original data.
2177 // We notify our followers during the item storage.
2179 $datarray['diaspora_signed_text'] = json_encode($data);
2182 $message_id = Item::insert($datarray);
2184 if ($message_id <= 0) {
2189 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2190 if ($datarray['uid'] == 0) {
2191 Item::distribute($message_id, json_encode($data));
2199 * Processes private messages
2201 * @param array $importer Array of the importer user
2202 * @param object $data The message object
2204 * @return bool Success?
2205 * @throws \Exception
2207 private static function receiveMessage(array $importer, $data)
2209 $author = Strings::escapeTags(XML::unescape($data->author));
2210 $guid = Strings::escapeTags(XML::unescape($data->guid));
2211 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2212 $text = XML::unescape($data->text);
2213 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2215 $contact = self::allowedContactByHandle($importer, $author, true);
2220 $conversation = null;
2222 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2223 $conversation = DBA::selectFirst('conv', [], $condition);
2225 if (!DBA::isResult($conversation)) {
2226 Logger::log("conversation not available.");
2230 $message_uri = $author.":".$guid;
2232 $person = self::personByHandle($author);
2234 Logger::log("unable to find author details");
2238 $body = Markdown::toBBCode($text);
2240 $body = self::replacePeopleGuid($body, $person["url"]);
2242 return Mail::insert([
2243 'uid' => $importer['uid'],
2245 'convid' => $conversation['id'],
2246 'from-name' => $person['name'],
2247 'from-photo' => $person['photo'],
2248 'from-url' => $person['url'],
2249 'contact-id' => $contact['id'],
2250 'title' => $conversation['subject'],
2253 'uri' => $message_uri,
2254 'parent-uri' => $author.":".$conversation['guid'],
2255 'created' => $created_at
2260 * Processes participations - unsupported by now
2262 * @param array $importer Array of the importer user
2263 * @param object $data The message object
2265 * @return bool always true
2266 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2267 * @throws \ImagickException
2269 private static function receiveParticipation(array $importer, $data)
2271 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2272 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2274 $contact_id = Contact::getIdForURL($author);
2276 Logger::log('Contact not found: '.$author);
2280 $person = self::personByHandle($author);
2281 if (!is_array($person)) {
2282 Logger::log("Person not found: ".$author);
2286 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2287 if (!DBA::isResult($item)) {
2288 Logger::log('Item not found, no origin or private: '.$parent_guid);
2292 $author_parts = explode('@', $author);
2293 if (isset($author_parts[1])) {
2294 $server = $author_parts[1];
2296 // Should never happen
2300 Logger::log('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, Logger::DEBUG);
2302 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2303 DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2306 // Send all existing comments and likes to the requesting server
2307 $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2308 while ($comment = Item::fetch($comments)) {
2309 if ($comment['id'] == $comment['parent']) {
2313 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $contact_id]);
2314 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $contact_id)) {
2315 ItemDeliveryData::incrementQueueCount($comment['id'], 1);
2318 DBA::close($comments);
2324 * Processes photos - unneeded
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 receivePhoto(array $importer, $data)
2333 // There doesn't seem to be a reason for this function,
2334 // since the photo data is transmitted in the status message as well
2339 * Processes poll participations - unssupported
2341 * @param array $importer Array of the importer user
2342 * @param object $data The message object
2344 * @return bool always true
2346 private static function receivePollParticipation(array $importer, $data)
2348 // We don't support polls by now
2353 * Processes incoming profile updates
2355 * @param array $importer Array of the importer user
2356 * @param object $data The message object
2358 * @return bool Success
2359 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2360 * @throws \ImagickException
2362 private static function receiveProfile(array $importer, $data)
2364 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2366 $contact = self::contactByHandle($importer["uid"], $author);
2371 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2372 $image_url = XML::unescape($data->image_url);
2373 $birthday = XML::unescape($data->birthday);
2374 $about = Markdown::toBBCode(XML::unescape($data->bio));
2375 $location = Markdown::toBBCode(XML::unescape($data->location));
2376 $searchable = (XML::unescape($data->searchable) == "true");
2377 $nsfw = (XML::unescape($data->nsfw) == "true");
2378 $tags = XML::unescape($data->tag_string);
2380 $tags = explode("#", $tags);
2383 foreach ($tags as $tag) {
2384 $tag = trim(strtolower($tag));
2390 $keywords = implode(", ", $keywords);
2392 $handle_parts = explode("@", $author);
2393 $nick = $handle_parts[0];
2396 $name = $handle_parts[0];
2399 if (preg_match("|^https?://|", $image_url) === 0) {
2400 $image_url = "http://".$handle_parts[1].$image_url;
2403 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2405 // Generic birthday. We don't know the timezone. The year is irrelevant.
2407 $birthday = str_replace("1000", "1901", $birthday);
2409 if ($birthday != "") {
2410 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2413 // this is to prevent multiple birthday notifications in a single year
2414 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2416 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2417 $birthday = $contact["bd"];
2420 $fields = ['name' => $name, 'location' => $location,
2421 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2422 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2423 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2425 if (!empty($birthday)) {
2426 $fields['bd'] = $birthday;
2429 DBA::update('contact', $fields, ['id' => $contact['id']]);
2431 // @todo Update the public contact, then update the gcontact from that
2433 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2434 "photo" => $image_url, "name" => $name, "location" => $location,
2435 "about" => $about, "birthday" => $birthday,
2436 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2437 "hide" => !$searchable, "nsfw" => $nsfw];
2439 $gcid = GContact::update($gcontact);
2441 GContact::link($gcid, $importer["uid"], $contact["id"]);
2443 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2449 * Processes incoming friend requests
2451 * @param array $importer Array of the importer user
2452 * @param array $contact The contact that send the request
2454 * @throws \Exception
2456 private static function receiveRequestMakeFriend(array $importer, array $contact)
2458 if ($contact["rel"] == Contact::SHARING) {
2461 ['rel' => Contact::FRIEND, 'writable' => true],
2462 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2468 * Processes incoming sharing notification
2470 * @param array $importer Array of the importer user
2471 * @param object $data The message object
2473 * @return bool Success
2474 * @throws \Exception
2476 private static function receiveContactRequest(array $importer, $data)
2478 $author = XML::unescape($data->author);
2479 $recipient = XML::unescape($data->recipient);
2481 if (!$author || !$recipient) {
2485 // the current protocol version doesn't know these fields
2486 // That means that we will assume their existance
2487 if (isset($data->following)) {
2488 $following = (XML::unescape($data->following) == "true");
2493 if (isset($data->sharing)) {
2494 $sharing = (XML::unescape($data->sharing) == "true");
2499 $contact = self::contactByHandle($importer["uid"], $author);
2501 // perhaps we were already sharing with this person. Now they're sharing with us.
2502 // That makes us friends.
2505 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2506 self::receiveRequestMakeFriend($importer, $contact);
2508 // refetch the contact array
2509 $contact = self::contactByHandle($importer["uid"], $author);
2511 // If we are now friends, we are sending a share message.
2512 // Normally we needn't to do so, but the first message could have been vanished.
2513 if (in_array($contact["rel"], [Contact::FRIEND])) {
2514 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2515 if (DBA::isResult($user)) {
2516 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2517 self::sendShare($user, $contact);
2522 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2523 Contact::removeFollower($importer, $contact);
2528 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2529 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2531 } elseif (!$following && !$sharing) {
2532 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2534 } elseif (!$following && $sharing) {
2535 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2536 } elseif ($following && $sharing) {
2537 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2538 } elseif ($following && !$sharing) {
2539 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2542 $ret = self::personByHandle($author);
2544 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2545 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2549 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2551 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2556 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2557 'author-link' => $ret['url']];
2559 $result = Contact::addRelationship($importer, $contact, $item, false);
2560 if ($result === true) {
2561 $contact_record = self::contactByHandle($importer['uid'], $author);
2562 if (!$contact_record) {
2563 Logger::info('unable to locate newly created contact record.');
2567 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2568 if (DBA::isResult($user)) {
2569 self::sendShare($user, $contact_record);
2571 // Send the profile data, maybe it weren't transmitted before
2572 self::sendProfile($importer['uid'], [$contact_record]);
2580 * Fetches a message with a given guid
2582 * @param string $guid message guid
2583 * @param string $orig_author handle of the original post
2584 * @return array The fetched item
2585 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2586 * @throws \ImagickException
2588 public static function originalItem($guid, $orig_author)
2591 Logger::log('Empty guid. Quitting.');
2595 // Do we already have this item?
2596 $fields = ['body', 'title', 'attach', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2597 'author-name', 'author-link', 'author-avatar'];
2598 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2599 $item = Item::selectFirst($fields, $condition);
2601 if (DBA::isResult($item)) {
2602 Logger::log("reshared message ".$guid." already exists on system.");
2604 // Maybe it is already a reshared item?
2605 // Then refetch the content, if it is a reshare from a reshare.
2606 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2607 if (self::isReshare($item["body"], true)) {
2609 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2610 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2612 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2614 // Add OEmbed and other information to the body
2615 $item["body"] = add_page_info_to_body($item["body"], false, true);
2623 if (!DBA::isResult($item)) {
2624 if (empty($orig_author)) {
2625 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2629 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2630 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2631 $stored = self::storeByGuid($guid, $server);
2634 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2635 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2636 $stored = self::storeByGuid($guid, $server);
2640 $fields = ['body', 'title', 'attach', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2641 'author-name', 'author-link', 'author-avatar'];
2642 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2643 $item = Item::selectFirst($fields, $condition);
2645 if (DBA::isResult($item)) {
2646 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2647 if (self::isReshare($item["body"], false)) {
2648 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2649 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2660 * Stores a reshare activity
2662 * @param array $item Array of reshare post
2663 * @param integer $parent_message_id Id of the parent post
2664 * @param string $guid GUID string of reshare action
2665 * @param string $author Author handle
2667 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2669 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2673 $datarray['uid'] = $item['uid'];
2674 $datarray['contact-id'] = $item['contact-id'];
2675 $datarray['network'] = $item['network'];
2677 $datarray['author-link'] = $item['author-link'];
2678 $datarray['author-id'] = $item['author-id'];
2680 $datarray['owner-link'] = $datarray['author-link'];
2681 $datarray['owner-id'] = $datarray['author-id'];
2683 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2684 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2685 $datarray['parent-uri'] = $parent['uri'];
2687 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2688 $datarray['gravity'] = GRAVITY_ACTIVITY;
2689 $datarray['object-type'] = Activity\ObjectType::NOTE;
2691 $datarray['protocol'] = $item['protocol'];
2693 $datarray['plink'] = self::plink($author, $datarray['guid']);
2694 $datarray['private'] = $item['private'];
2695 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2697 $message_id = Item::insert($datarray);
2700 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2701 if ($datarray['uid'] == 0) {
2702 Item::distribute($message_id);
2708 * Processes a reshare message
2710 * @param array $importer Array of the importer user
2711 * @param object $data The message object
2712 * @param string $xml The original XML of the message
2714 * @return int the message id
2715 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2716 * @throws \ImagickException
2718 private static function receiveReshare(array $importer, $data, $xml)
2720 $author = Strings::escapeTags(XML::unescape($data->author));
2721 $guid = Strings::escapeTags(XML::unescape($data->guid));
2722 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2723 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2724 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2725 /// @todo handle unprocessed property "provider_display_name"
2726 $public = Strings::escapeTags(XML::unescape($data->public));
2728 $contact = self::allowedContactByHandle($importer, $author, false);
2733 $message_id = self::messageExists($importer["uid"], $guid);
2738 $original_item = self::originalItem($root_guid, $root_author);
2739 if (!$original_item) {
2743 $orig_url = DI::baseUrl()."/display/".$original_item["guid"];
2747 $datarray["uid"] = $importer["uid"];
2748 $datarray["contact-id"] = $contact["id"];
2749 $datarray["network"] = Protocol::DIASPORA;
2751 $datarray["author-link"] = $contact["url"];
2752 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2754 $datarray["owner-link"] = $datarray["author-link"];
2755 $datarray["owner-id"] = $datarray["author-id"];
2757 $datarray["guid"] = $guid;
2758 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2759 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2761 $datarray["verb"] = Activity::POST;
2762 $datarray["gravity"] = GRAVITY_PARENT;
2764 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2765 $datarray["source"] = $xml;
2767 /// @todo Copy tag data from original post
2769 $prefix = share_header(
2770 $original_item["author-name"],
2771 $original_item["author-link"],
2772 $original_item["author-avatar"],
2773 $original_item["guid"],
2774 $original_item["created"],
2778 if (!empty($original_item['title'])) {
2779 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2782 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2784 $datarray["tag"] = $original_item["tag"];
2785 $datarray["attach"] = $original_item["attach"];
2786 $datarray["app"] = $original_item["app"];
2788 $datarray["plink"] = self::plink($author, $guid);
2789 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2790 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2792 $datarray["object-type"] = $original_item["object-type"];
2794 self::fetchGuid($datarray);
2795 $message_id = Item::insert($datarray);
2797 self::sendParticipation($contact, $datarray);
2799 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2800 if ($root_message_id) {
2801 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2805 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2806 if ($datarray['uid'] == 0) {
2807 Item::distribute($message_id);
2816 * Processes retractions
2818 * @param array $importer Array of the importer user
2819 * @param array $contact The contact of the item owner
2820 * @param object $data The message object
2822 * @return bool success
2823 * @throws \Exception
2825 private static function itemRetraction(array $importer, array $contact, $data)
2827 $author = Strings::escapeTags(XML::unescape($data->author));
2828 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2829 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2831 $person = self::personByHandle($author);
2832 if (!is_array($person)) {
2833 Logger::log("unable to find author detail for ".$author);
2837 if (empty($contact["url"])) {
2838 $contact["url"] = $person["url"];
2841 // Fetch items that are about to be deleted
2842 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2844 // When we receive a public retraction, we delete every item that we find.
2845 if ($importer['uid'] == 0) {
2846 $condition = ['guid' => $target_guid, 'deleted' => false];
2848 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2851 $r = Item::select($fields, $condition);
2852 if (!DBA::isResult($r)) {
2853 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2857 while ($item = Item::fetch($r)) {
2858 if (strstr($item['file'], '[')) {
2859 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2863 // Fetch the parent item
2864 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2866 // Only delete it if the parent author really fits
2867 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2868 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2872 Item::markForDeletion(['id' => $item['id']]);
2874 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], Logger::DEBUG);
2881 * Receives retraction messages
2883 * @param array $importer Array of the importer user
2884 * @param string $sender The sender of the message
2885 * @param object $data The message object
2887 * @return bool Success
2888 * @throws \Exception
2890 private static function receiveRetraction(array $importer, $sender, $data)
2892 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2894 $contact = self::contactByHandle($importer["uid"], $sender);
2895 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2896 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2904 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2906 switch ($target_type) {
2911 case "StatusMessage":
2912 return self::itemRetraction($importer, $contact, $data);
2914 case "PollParticipation":
2916 // Currently unsupported
2920 Logger::log("Unknown target type ".$target_type);
2927 * Receives status messages
2929 * @param array $importer Array of the importer user
2930 * @param SimpleXMLElement $data The message object
2931 * @param string $xml The original XML of the message
2933 * @return int The message id of the newly created item
2934 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2935 * @throws \ImagickException
2937 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2939 $author = Strings::escapeTags(XML::unescape($data->author));
2940 $guid = Strings::escapeTags(XML::unescape($data->guid));
2941 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2942 $public = Strings::escapeTags(XML::unescape($data->public));
2943 $text = XML::unescape($data->text);
2944 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2946 $contact = self::allowedContactByHandle($importer, $author, false);
2951 $message_id = self::messageExists($importer["uid"], $guid);
2957 if ($data->location) {
2958 foreach ($data->location->children() as $fieldname => $data) {
2959 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2963 $body = Markdown::toBBCode($text);
2967 // Attach embedded pictures to the body
2969 foreach ($data->photo as $photo) {
2970 $body = "[img]".XML::unescape($photo->remote_photo_path).
2971 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2974 $datarray["object-type"] = Activity\ObjectType::IMAGE;
2976 $datarray["object-type"] = Activity\ObjectType::NOTE;
2978 // Add OEmbed and other information to the body
2979 if (!self::isHubzilla($contact["url"])) {
2980 $body = add_page_info_to_body($body, false, true);
2984 /// @todo enable support for polls
2985 //if ($data->poll) {
2986 // foreach ($data->poll AS $poll)
2991 /// @todo enable support for events
2993 $datarray["uid"] = $importer["uid"];
2994 $datarray["contact-id"] = $contact["id"];
2995 $datarray["network"] = Protocol::DIASPORA;
2997 $datarray["author-link"] = $contact["url"];
2998 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
3000 $datarray["owner-link"] = $datarray["author-link"];
3001 $datarray["owner-id"] = $datarray["author-id"];
3003 $datarray["guid"] = $guid;
3004 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
3005 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
3007 $datarray["verb"] = Activity::POST;
3008 $datarray["gravity"] = GRAVITY_PARENT;
3010 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
3011 $datarray["source"] = $xml;
3013 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3015 self::storeMentions($datarray['uri-id'], $text);
3016 Tag::storeFromBody($datarray['uri-id'], $datarray["body"]);
3018 if ($provider_display_name != "") {
3019 $datarray["app"] = $provider_display_name;
3022 $datarray["plink"] = self::plink($author, $guid);
3023 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
3024 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3026 if (isset($address["address"])) {
3027 $datarray["location"] = $address["address"];
3030 if (isset($address["lat"]) && isset($address["lng"])) {
3031 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3034 self::fetchGuid($datarray);
3035 $message_id = Item::insert($datarray);
3037 self::sendParticipation($contact, $datarray);
3040 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
3041 if ($datarray['uid'] == 0) {
3042 Item::distribute($message_id);
3050 /* ************************************************************************************** *
3051 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3052 * ************************************************************************************** */
3055 * returnes the handle of a contact
3057 * @param array $contact contact array
3059 * @return string the handle in the format user@domain.tld
3060 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3062 private static function myHandle(array $contact)
3064 if (!empty($contact["addr"])) {
3065 return $contact["addr"];
3068 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3069 // So - just in case - we build the the address here.
3070 if ($contact["nickname"] != "") {
3071 $nick = $contact["nickname"];
3073 $nick = $contact["nick"];
3076 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
3081 * Creates the data for a private message in the new format
3083 * @param string $msg The message that is to be transmitted
3084 * @param array $user The record of the sender
3085 * @param array $contact Target of the communication
3086 * @param string $prvkey The private key of the sender
3087 * @param string $pubkey The public key of the receiver
3089 * @return string The encrypted data
3090 * @throws \Exception
3092 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
3094 Logger::log("Message: ".$msg, Logger::DATA);
3096 // without a public key nothing will work
3098 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3102 $aes_key = openssl_random_pseudo_bytes(32);
3103 $b_aes_key = base64_encode($aes_key);
3104 $iv = openssl_random_pseudo_bytes(16);
3105 $b_iv = base64_encode($iv);
3107 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3109 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3111 $encrypted_key_bundle = "";
3112 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3114 $json_object = json_encode(
3115 ["aes_key" => base64_encode($encrypted_key_bundle),
3116 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3119 return $json_object;
3123 * Creates the envelope for the "fetch" endpoint and for the new format
3125 * @param string $msg The message that is to be transmitted
3126 * @param array $user The record of the sender
3128 * @return string The envelope
3129 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3131 public static function buildMagicEnvelope($msg, array $user)
3133 $b64url_data = Strings::base64UrlEncode($msg);
3134 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3136 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3137 $type = "application/xml";
3138 $encoding = "base64url";
3139 $alg = "RSA-SHA256";
3140 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3142 // Fallback if the private key wasn't transmitted in the expected field
3143 if ($user['uprvkey'] == "") {
3144 $user['uprvkey'] = $user['prvkey'];
3147 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3148 $sig = Strings::base64UrlEncode($signature);
3150 $xmldata = ["me:env" => ["me:data" => $data,
3151 "@attributes" => ["type" => $type],
3152 "me:encoding" => $encoding,
3155 "@attributes2" => ["key_id" => $key_id]]];
3157 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3159 return XML::fromArray($xmldata, $xml, false, $namespaces);
3163 * Create the envelope for a message
3165 * @param string $msg The message that is to be transmitted
3166 * @param array $user The record of the sender
3167 * @param array $contact Target of the communication
3168 * @param string $prvkey The private key of the sender
3169 * @param string $pubkey The public key of the receiver
3170 * @param bool $public Is the message public?
3172 * @return string The message that will be transmitted to other servers
3173 * @throws \Exception
3175 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3177 // The message is put into an envelope with the sender's signature
3178 $envelope = self::buildMagicEnvelope($msg, $user);
3180 // Private messages are put into a second envelope, encrypted with the receivers public key
3182 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3189 * Creates a signature for a message
3191 * @param array $owner the array of the owner of the message
3192 * @param array $message The message that is to be signed
3194 * @return string The signature
3196 private static function signature($owner, $message)
3199 unset($sigmsg["author_signature"]);
3200 unset($sigmsg["parent_author_signature"]);
3202 $signed_text = implode(";", $sigmsg);
3204 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3208 * Transmit a message to a target server
3210 * @param array $owner the array of the item owner
3211 * @param array $contact Target of the communication
3212 * @param string $envelope The message that is to be transmitted
3213 * @param bool $public_batch Is it a public post?
3214 * @param string $guid message guid
3216 * @return int Result of the transmission
3217 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3218 * @throws \ImagickException
3220 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3222 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
3227 $logid = Strings::getRandomHex(4);
3229 // We always try to use the data from the fcontact table.
3230 // This is important for transmitting data to Friendica servers.
3231 if (!empty($contact['addr'])) {
3232 $fcontact = self::personByHandle($contact['addr']);
3233 if (!empty($fcontact)) {
3234 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3238 if (empty($dest_url)) {
3239 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3243 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3247 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3249 if (!intval(DI::config()->get("system", "diaspora_test"))) {
3250 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3252 $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3253 $return_code = $postResult->getReturnCode();
3255 Logger::log("test_mode");
3259 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3261 return $return_code ? $return_code : -1;
3266 * Build the post xml
3268 * @param string $type The message type
3269 * @param array $message The message data
3271 * @return string The post XML
3273 public static function buildPostXml($type, $message)
3275 $data = [$type => $message];
3277 return XML::fromArray($data, $xml);
3281 * Builds and transmit messages
3283 * @param array $owner the array of the item owner
3284 * @param array $contact Target of the communication
3285 * @param string $type The message type
3286 * @param array $message The message data
3287 * @param bool $public_batch Is it a public post?
3288 * @param string $guid message guid
3290 * @return int Result of the transmission
3291 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3292 * @throws \ImagickException
3294 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3296 $msg = self::buildPostXml($type, $message);
3298 Logger::log('message: '.$msg, Logger::DATA);
3299 Logger::log('send guid '.$guid, Logger::DEBUG);
3301 // Fallback if the private key wasn't transmitted in the expected field
3302 if (empty($owner['uprvkey'])) {
3303 $owner['uprvkey'] = $owner['prvkey'];
3306 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3308 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3310 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3312 return $return_code;
3316 * sends a participation (Used to get all further updates)
3318 * @param array $contact Target of the communication
3319 * @param array $item Item array
3321 * @return int The result of the transmission
3322 * @throws \Exception
3324 private static function sendParticipation(array $contact, array $item)
3326 // Don't send notifications for private postings
3327 if ($item['private'] == Item::PRIVATE) {
3331 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3333 $result = DI::cache()->get($cachekey);
3334 if (!is_null($result)) {
3338 // Fetch some user id to have a valid handle to transmit the participation.
3339 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3340 // If the item belongs to a user, we take this user id.
3341 if ($item['uid'] == 0) {
3342 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3343 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3344 $owner = User::getOwnerDataById($first_user['uid']);
3346 $owner = User::getOwnerDataById($item['uid']);
3349 $author = self::myHandle($owner);
3351 $message = ["author" => $author,
3352 "guid" => System::createUUID(),
3353 "parent_type" => "Post",
3354 "parent_guid" => $item["guid"]];
3356 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3358 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3359 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3361 return self::buildAndTransmit($owner, $contact, "participation", $message);
3365 * sends an account migration
3367 * @param array $owner the array of the item owner
3368 * @param array $contact Target of the communication
3369 * @param int $uid User ID
3371 * @return int The result of the transmission
3372 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3373 * @throws \ImagickException
3375 public static function sendAccountMigration(array $owner, array $contact, $uid)
3377 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3378 $profile = self::createProfileData($uid);
3380 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3381 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3383 $message = ["author" => $old_handle,
3384 "profile" => $profile,
3385 "signature" => $signature];
3387 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3389 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3393 * Sends a "share" message
3395 * @param array $owner the array of the item owner
3396 * @param array $contact Target of the communication
3398 * @return int The result of the transmission
3399 * @throws \Exception
3401 public static function sendShare(array $owner, array $contact)
3404 * @todo support the different possible combinations of "following" and "sharing"
3405 * Currently, Diaspora only interprets the "sharing" field
3407 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3411 switch ($contact["rel"]) {
3412 case Contact::FRIEND:
3416 case Contact::SHARING:
3420 case Contact::FOLLOWER:
3426 $message = ["author" => self::myHandle($owner),
3427 "recipient" => $contact["addr"],
3428 "following" => "true",
3429 "sharing" => "true"];
3431 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3433 return self::buildAndTransmit($owner, $contact, "contact", $message);
3437 * sends an "unshare"
3439 * @param array $owner the array of the item owner
3440 * @param array $contact Target of the communication
3442 * @return int The result of the transmission
3443 * @throws \Exception
3445 public static function sendUnshare(array $owner, array $contact)
3447 $message = ["author" => self::myHandle($owner),
3448 "recipient" => $contact["addr"],
3449 "following" => "false",
3450 "sharing" => "false"];
3452 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3454 return self::buildAndTransmit($owner, $contact, "contact", $message);
3458 * Checks a message body if it is a reshare
3460 * @param string $body The message body that is to be check
3461 * @param bool $complete Should it be a complete check or a simple check?
3463 * @return array|bool Reshare details or "false" if no reshare
3464 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3465 * @throws \ImagickException
3467 public static function isReshare($body, $complete = true)
3469 $body = trim($body);
3471 $reshared = Item::getShareArray(['body' => $body]);
3472 if (empty($reshared)) {
3476 // Skip if it isn't a pure repeated messages
3477 // Does it start with a share?
3478 if (!empty($reshared['comment']) && $complete) {
3482 if (!empty($reshared['guid']) && $complete) {
3483 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3484 $item = Item::selectFirst(['contact-id'], $condition);
3485 if (DBA::isResult($item)) {
3487 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3488 $ret["root_guid"] = $reshared['guid'];
3490 } elseif ($complete) {
3491 // We are resharing something that isn't a DFRN or Diaspora post.
3492 // So we have to return "false" on "$complete" to not trigger a reshare.
3495 } elseif (empty($reshared['guid']) && $complete) {
3501 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3502 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3503 if (!empty($contact['addr'])) {
3504 $ret['root_handle'] = $contact['addr'];
3508 if (empty($ret) && !$complete) {
3516 * Create an event array
3518 * @param integer $event_id The id of the event
3520 * @return array with event data
3521 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3523 private static function buildEvent($event_id)
3525 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3526 if (!DBA::isResult($r)) {
3534 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3535 if (!DBA::isResult($r)) {
3541 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3542 if (!DBA::isResult($r)) {
3548 $eventdata['author'] = self::myHandle($owner);
3550 if ($event['guid']) {
3551 $eventdata['guid'] = $event['guid'];
3554 $mask = DateTimeFormat::ATOM;
3556 /// @todo - establish "all day" events in Friendica
3557 $eventdata["all_day"] = "false";
3559 $eventdata['timezone'] = 'UTC';
3560 if (!$event['adjust'] && $user['timezone']) {
3561 $eventdata['timezone'] = $user['timezone'];
3564 if ($event['start']) {
3565 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3567 if ($event['finish'] && !$event['nofinish']) {
3568 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3570 if ($event['summary']) {
3571 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3573 if ($event['desc']) {
3574 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3576 if ($event['location']) {
3577 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3578 $coord = Map::getCoordinates($event['location']);
3581 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3582 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3583 $location["lat"] = $coord['lat'];
3584 $location["lng"] = $coord['lon'];
3586 $location["lat"] = 0;
3587 $location["lng"] = 0;
3589 $eventdata['location'] = $location;
3596 * Create a post (status message or reshare)
3598 * @param array $item The item that will be exported
3599 * @param array $owner the array of the item owner
3602 * 'type' -> Message type ("status_message" or "reshare")
3603 * 'message' -> Array of XML elements of the status
3604 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3605 * @throws \ImagickException
3607 public static function buildStatus(array $item, array $owner)
3609 $cachekey = "diaspora:buildStatus:".$item['guid'];
3611 $result = DI::cache()->get($cachekey);
3612 if (!is_null($result)) {
3616 $myaddr = self::myHandle($owner);
3618 $public = ($item["private"] == Item::PRIVATE ? "false" : "true");
3619 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3620 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3622 // Detect a share element and do a reshare
3623 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) {
3624 $message = ["author" => $myaddr,
3625 "guid" => $item["guid"],
3626 "created_at" => $created,
3627 "root_author" => $ret["root_handle"],
3628 "root_guid" => $ret["root_guid"],
3629 "provider_display_name" => $item["app"],
3630 "public" => $public];
3634 $title = $item["title"];
3635 $body = $item["body"];
3637 // Fetch the title from an attached link - if there is one
3638 if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3639 $page_data = BBCode::getAttachmentData($item['body']);
3640 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3641 $title = $page_data['title'];
3645 if ($item['author-link'] != $item['owner-link']) {
3646 require_once 'mod/share.php';
3647 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3648 "", $item['created'], $item['plink']) . $body . '[/share]';
3651 // convert to markdown
3652 $body = html_entity_decode(BBCode::toMarkdown($body));
3655 if (strlen($title)) {
3656 $body = "### ".html_entity_decode($title)."\n\n".$body;
3659 if ($item["attach"]) {
3660 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3662 $body .= "\n".DI::l10n()->t("Attachments:")."\n";
3663 foreach ($matches as $mtch) {
3664 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3671 if ($item["location"] != "")
3672 $location["address"] = $item["location"];
3674 if ($item["coord"] != "") {
3675 $coord = explode(" ", $item["coord"]);
3676 $location["lat"] = $coord[0];
3677 $location["lng"] = $coord[1];
3680 $message = ["author" => $myaddr,
3681 "guid" => $item["guid"],
3682 "created_at" => $created,
3683 "edited_at" => $edited,
3684 "public" => $public,
3686 "provider_display_name" => $item["app"],
3687 "location" => $location];
3689 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3690 if (!isset($location["lat"]) || !isset($location["lng"])) {
3691 unset($message["location"]);
3694 if ($item['event-id'] > 0) {
3695 $event = self::buildEvent($item['event-id']);
3696 if (count($event)) {
3697 $message['event'] = $event;
3699 if (!empty($event['location']['address']) &&
3700 !empty($event['location']['lat']) &&
3701 !empty($event['location']['lng'])) {
3702 $message['location'] = $event['location'];
3705 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3706 // $message['text'] = '';
3710 $type = "status_message";
3713 $msg = ["type" => $type, "message" => $message];
3715 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3720 private static function prependParentAuthorMention($body, $profile_url)
3722 $profile = Contact::getDetailsByURL($profile_url);
3723 if (!empty($profile['addr'])
3724 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3725 && !strstr($body, $profile['addr'])
3726 && !strstr($body, $profile_url)
3728 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3737 * @param array $item The item that will be exported
3738 * @param array $owner the array of the item owner
3739 * @param array $contact Target of the communication
3740 * @param bool $public_batch Is it a public post?
3742 * @return int The result of the transmission
3743 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3744 * @throws \ImagickException
3746 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3748 $status = self::buildStatus($item, $owner);
3750 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3754 * Creates a "like" object
3756 * @param array $item The item that will be exported
3757 * @param array $owner the array of the item owner
3759 * @return array The data for a "like"
3760 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3762 private static function constructLike(array $item, array $owner)
3764 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3765 if (!DBA::isResult($parent)) {
3769 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3771 if ($item['verb'] === Activity::LIKE) {
3773 } elseif ($item['verb'] === Activity::DISLIKE) {
3774 $positive = "false";
3777 return(["author" => self::myHandle($owner),
3778 "guid" => $item["guid"],
3779 "parent_guid" => $parent["guid"],
3780 "parent_type" => $target_type,
3781 "positive" => $positive,
3782 "author_signature" => ""]);
3786 * Creates an "EventParticipation" object
3788 * @param array $item The item that will be exported
3789 * @param array $owner the array of the item owner
3791 * @return array The data for an "EventParticipation"
3792 * @throws \Exception
3794 private static function constructAttend(array $item, array $owner)
3796 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3797 if (!DBA::isResult($parent)) {
3801 switch ($item['verb']) {
3802 case Activity::ATTEND:
3803 $attend_answer = 'accepted';
3805 case Activity::ATTENDNO:
3806 $attend_answer = 'declined';
3808 case Activity::ATTENDMAYBE:
3809 $attend_answer = 'tentative';
3812 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3816 return(["author" => self::myHandle($owner),
3817 "guid" => $item["guid"],
3818 "parent_guid" => $parent["guid"],
3819 "status" => $attend_answer,
3820 "author_signature" => ""]);
3824 * Creates the object for a comment
3826 * @param array $item The item that will be exported
3827 * @param array $owner the array of the item owner
3829 * @return array|false The data for a comment
3830 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3832 private static function constructComment(array $item, array $owner)
3834 $cachekey = "diaspora:constructComment:".$item['guid'];
3836 $result = DI::cache()->get($cachekey);
3837 if (!is_null($result)) {
3841 $toplevel_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3842 if (!DBA::isResult($toplevel_item)) {
3843 Logger::error('Missing parent conversation item', ['parent' => $item["parent"]]);
3847 $thread_parent_item = $toplevel_item;
3848 if ($item['thr-parent'] != $item['parent-uri']) {
3849 $thread_parent_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3852 $body = $item["body"];
3854 // The replied to autor mention is prepended for clarity if:
3855 // - Item replied isn't yours
3856 // - Item is public or explicit mentions are disabled
3857 // - Implicit mentions are enabled
3859 $item['author-id'] != $thread_parent_item['author-id']
3860 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3861 && !DI::config()->get('system', 'disable_implicit_mentions')
3863 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3866 $text = html_entity_decode(BBCode::toMarkdown($body));
3867 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3868 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3871 "author" => self::myHandle($owner),
3872 "guid" => $item["guid"],
3873 "created_at" => $created,
3874 "edited_at" => $edited,
3875 "parent_guid" => $toplevel_item["guid"],
3877 "author_signature" => ""
3880 // Send the thread parent guid only if it is a threaded comment
3881 if ($item['thr-parent'] != $item['parent-uri']) {
3882 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3885 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3891 * Send a like or a comment
3893 * @param array $item The item that will be exported
3894 * @param array $owner the array of the item owner
3895 * @param array $contact Target of the communication
3896 * @param bool $public_batch Is it a public post?
3898 * @return int The result of the transmission
3899 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3900 * @throws \ImagickException
3902 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3904 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3905 $message = self::constructAttend($item, $owner);
3906 $type = "event_participation";
3907 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3908 $message = self::constructLike($item, $owner);
3910 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3911 $message = self::constructComment($item, $owner);
3915 if (empty($message)) {
3919 $message["author_signature"] = self::signature($owner, $message);
3921 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3925 * Creates a message from a signature record entry
3927 * @param array $item The item that will be exported
3928 * @return array The message
3930 private static function messageFromSignature(array $item)
3932 // Split the signed text
3933 $signed_parts = explode(";", $item['signed_text']);
3935 if ($item["deleted"]) {
3936 $message = ["author" => $item['signer'],
3937 "target_guid" => $signed_parts[0],
3938 "target_type" => $signed_parts[1]];
3939 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3940 $message = ["author" => $signed_parts[4],
3941 "guid" => $signed_parts[1],
3942 "parent_guid" => $signed_parts[3],
3943 "parent_type" => $signed_parts[2],
3944 "positive" => $signed_parts[0],
3945 "author_signature" => $item['signature'],
3946 "parent_author_signature" => ""];
3948 // Remove the comment guid
3949 $guid = array_shift($signed_parts);
3951 // Remove the parent guid
3952 $parent_guid = array_shift($signed_parts);
3954 // Remove the handle
3955 $handle = array_pop($signed_parts);
3958 "author" => $handle,
3960 "parent_guid" => $parent_guid,
3961 "text" => implode(";", $signed_parts),
3962 "author_signature" => $item['signature'],
3963 "parent_author_signature" => ""
3970 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3972 * @param array $item The item that will be exported
3973 * @param array $owner the array of the item owner
3974 * @param array $contact Target of the communication
3975 * @param bool $public_batch Is it a public post?
3977 * @return int The result of the transmission
3978 * @throws \Exception
3980 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3982 if ($item["deleted"]) {
3983 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3984 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3990 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3992 $msg = json_decode($item['signed_text'], true);
3995 if (is_array($msg)) {
3996 foreach ($msg as $field => $data) {
3997 if (!$item["deleted"]) {
3998 if ($field == "diaspora_handle") {
4001 if ($field == "target_type") {
4002 $field = "parent_type";
4006 $message[$field] = $data;
4009 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
4012 $message["parent_author_signature"] = self::signature($owner, $message);
4014 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
4016 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4020 * Sends a retraction (deletion) of a message, like or comment
4022 * @param array $item The item that will be exported
4023 * @param array $owner the array of the item owner
4024 * @param array $contact Target of the communication
4025 * @param bool $public_batch Is it a public post?
4026 * @param bool $relay Is the retraction transmitted from a relay?
4028 * @return int The result of the transmission
4029 * @throws \Exception
4031 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
4033 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4035 $msg_type = "retraction";
4037 if ($item['id'] == $item['parent']) {
4038 $target_type = "Post";
4039 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4040 $target_type = "Like";
4042 $target_type = "Comment";
4045 $message = ["author" => $itemaddr,
4046 "target_guid" => $item['guid'],
4047 "target_type" => $target_type];
4049 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
4051 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4057 * @param array $item The item that will be exported
4058 * @param array $owner The owner
4059 * @param array $contact Target of the communication
4061 * @return int The result of the transmission
4062 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4063 * @throws \ImagickException
4065 public static function sendMail(array $item, array $owner, array $contact)
4067 $myaddr = self::myHandle($owner);
4069 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
4070 if (!DBA::isResult($cnv)) {
4071 Logger::log("conversation not found.");
4075 $body = BBCode::toMarkdown($item["body"]);
4076 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4079 "author" => $myaddr,
4080 "guid" => $item["guid"],
4081 "conversation_guid" => $cnv["guid"],
4083 "created_at" => $created,
4086 if ($item["reply"]) {
4091 "author" => $cnv["creator"],
4092 "guid" => $cnv["guid"],
4093 "subject" => $cnv["subject"],
4094 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4095 "participants" => $cnv["recips"],
4099 $type = "conversation";
4102 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4106 * Split a name into first name and last name
4108 * @param string $name The name
4110 * @return array The array with "first" and "last"
4112 public static function splitName($name) {
4113 $name = trim($name);
4115 // Is the name longer than 64 characters? Then cut the rest of it.
4116 if (strlen($name) > 64) {
4117 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4118 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4120 $name = substr($name, 0, 64);
4124 // Take the first word as first name
4125 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4126 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4127 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4128 return ['first' => $first, 'last' => $last];
4131 // Take the last word as last name
4132 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4133 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4135 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4136 return ['first' => $first, 'last' => $last];
4139 // Take the first 32 characters if there is no space in the first 32 characters
4140 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4141 $first = substr($name, 0, 32);
4142 $last = substr($name, 32);
4143 return ['first' => $first, 'last' => $last];
4146 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4147 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4149 // Check if the last name is longer than 32 characters
4150 if (strlen($last) > 32) {
4151 if (strpos($last, ' ') <= 32) {
4152 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4154 $last = substr($last, 0, 32);
4158 return ['first' => $first, 'last' => $last];
4162 * Create profile data
4164 * @param int $uid The user id
4166 * @return array The profile data
4167 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4169 private static function createProfileData($uid)
4172 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4174 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4175 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4176 WHERE `user`.`uid` = %d AND `contact`.`self` LIMIT 1",
4185 $handle = $profile["addr"];
4187 $split_name = self::splitName($profile['name']);
4188 $first = $split_name['first'];
4189 $last = $split_name['last'];
4191 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4192 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4193 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4194 $searchable = ($profile['net-publish'] ? 'true' : 'false');
4200 if ($searchable === 'true') {
4203 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4204 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4208 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4211 $about = BBCode::toMarkdown($profile['about']);
4213 $location = Profile::formatLocation($profile);
4215 if ($profile['pub_keywords']) {
4216 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4217 $kw = str_replace(' ', ' ', $kw);
4218 $arr = explode(' ', $kw);
4220 for ($x = 0; $x < 5; $x ++) {
4221 if (!empty($arr[$x])) {
4222 $tags .= '#'. trim($arr[$x]) .' ';
4227 $tags = trim($tags);
4230 return ["author" => $handle,
4231 "first_name" => $first,
4232 "last_name" => $last,
4233 "image_url" => $large,
4234 "image_url_medium" => $medium,
4235 "image_url_small" => $small,
4238 "location" => $location,
4239 "searchable" => $searchable,
4241 "tag_string" => $tags];
4245 * Sends profile data
4247 * @param int $uid The user id
4248 * @param bool $recips optional, default false
4250 * @throws \Exception
4252 public static function sendProfile($uid, $recips = false)
4258 $owner = User::getOwnerDataById($uid);
4265 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4266 AND `uid` = %d AND `rel` != %d",
4267 DBA::escape(Protocol::DIASPORA),
4269 intval(Contact::SHARING)
4277 $message = self::createProfileData($uid);
4279 // @ToDo Split this into single worker jobs
4280 foreach ($recips as $recip) {
4281 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4282 self::buildAndTransmit($owner, $recip, "profile", $message);
4287 * Creates the signature for likes that are created on our system
4289 * @param integer $uid The user of that comment
4290 * @param array $item Item array
4292 * @return array Signed content
4293 * @throws \Exception
4295 public static function createLikeSignature($uid, array $item)
4297 $owner = User::getOwnerDataById($uid);
4298 if (empty($owner)) {
4299 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4303 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4307 $message = self::constructLike($item, $owner);
4308 if ($message === false) {
4312 $message["author_signature"] = self::signature($owner, $message);
4318 * Creates the signature for Comments that are created on our system
4320 * @param integer $uid The user of that comment
4321 * @param array $item Item array
4323 * @return array Signed content
4324 * @throws \Exception
4326 public static function createCommentSignature($uid, array $item)
4328 $owner = User::getOwnerDataById($uid);
4329 if (empty($owner)) {
4330 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4334 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4335 $item['thr-parent'] = $item['parent-uri'];
4337 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4338 if (!DBA::isResult($parent)) {
4342 $item['parent-uri'] = $parent['parent-uri'];
4344 $message = self::constructComment($item, $owner);
4345 if ($message === false) {
4349 $message["author_signature"] = self::signature($owner, $message);