3 * @file src/Protocol/diaspora.php
4 * @brief The implementation of the diaspora protocol
6 * The new protocol is described here: http://diaspora.github.io/diaspora_federation/index.html
7 * This implementation here interprets the old and the new protocol and sends the new one.
8 * In the future we will remove most stuff from "validPosting" and interpret only the new protocol.
11 namespace Friendica\Protocol;
13 use Friendica\Content\Feature;
14 use Friendica\Content\Text\BBCode;
15 use Friendica\Content\Text\Markdown;
16 use Friendica\Core\Cache;
17 use Friendica\Core\Config;
18 use Friendica\Core\L10n;
19 use Friendica\Core\Logger;
20 use Friendica\Core\PConfig;
21 use Friendica\Core\Protocol;
22 use Friendica\Core\System;
23 use Friendica\Core\Worker;
24 use Friendica\Database\DBA;
25 use Friendica\Model\Contact;
26 use Friendica\Model\Conversation;
27 use Friendica\Model\GContact;
28 use Friendica\Model\Group;
29 use Friendica\Model\Item;
30 use Friendica\Model\ItemDeliveryData;
31 use Friendica\Model\Mail;
32 use Friendica\Model\Profile;
33 use Friendica\Model\User;
34 use Friendica\Network\Probe;
35 use Friendica\Util\Crypto;
36 use Friendica\Util\DateTimeFormat;
37 use Friendica\Util\Map;
38 use Friendica\Util\Network;
39 use Friendica\Util\Strings;
40 use Friendica\Util\XML;
41 use Friendica\Worker\Delivery;
45 * @brief This class contain functions to create and send Diaspora XML files
51 * Mark the relay contact of the given contact for archival
52 * This is called whenever there is a communication issue with the server.
53 * It avoids sending stuff to servers who don't exist anymore.
54 * The relay contact is a technical contact entry that exists once per server.
56 * @param array $contact of the relay contact
58 public static function markRelayForArchival($contact)
60 if (!empty($contact['contact-type']) && ($contact['contact-type'] == Contact::TYPE_RELAY)) {
61 // This is already the relay contact, we don't need to fetch it
62 $relay_contact = $contact;
63 } elseif (empty($contact['baseurl'])) {
64 if (!empty($contact['batch'])) {
65 $relay_contact = DBA::selectFirst('contact', [], ['batch' => $contact['batch'], 'contact-type' => Contact::TYPE_RELAY, 'uid' => 0]);
70 $relay_contact = self::getRelayContact($contact['baseurl'], []);
73 if (!empty($relay_contact)) {
74 Logger::info('Relay contact will be marked for archival', ['id' => $relay_contact['id'], 'url' => $relay_contact['url']]);
75 Contact::markForArchival($relay_contact);
80 * @brief Return a list of relay servers
82 * The list contains not only the official relays but also servers that we serve directly
84 * @param integer $item_id The id of the item that is sent
85 * @param array $contacts The previously fetched contacts
87 * @return array of relay servers
88 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
90 public static function relayList($item_id, array $contacts = [])
94 // Fetching relay servers
95 $serverdata = Config::get("system", "relay_server");
97 if (!empty($serverdata)) {
98 $servers = explode(",", $serverdata);
99 foreach ($servers as $server) {
100 $serverlist[$server] = trim($server);
104 if (Config::get("system", "relay_directly", false)) {
105 // We distribute our stuff based on the parent to ensure that the thread will be complete
106 $parent = Item::selectFirst(['parent'], ['id' => $item_id]);
107 if (!DBA::isResult($parent)) {
111 // Servers that want to get all content
112 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
113 while ($server = DBA::fetch($servers)) {
114 $serverlist[$server['url']] = $server['url'];
117 // All tags of the current post
118 $condition = ['otype' => TERM_OBJ_POST, 'type' => TERM_HASHTAG, 'oid' => $parent['parent']];
119 $tags = DBA::select('term', ['term'], $condition);
121 while ($tag = DBA::fetch($tags)) {
122 $taglist[] = $tag['term'];
125 // All servers who wants content with this tag
127 if (!empty($taglist)) {
128 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
129 while ($server = DBA::fetch($tagserver)) {
130 $tagserverlist[] = $server['gserver-id'];
134 // All adresses with the given id
135 if (!empty($tagserverlist)) {
136 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
137 while ($server = DBA::fetch($servers)) {
138 $serverlist[$server['url']] = $server['url'];
143 // Now we are collecting all relay contacts
144 foreach ($serverlist as $server_url) {
145 // We don't send messages to ourselves
146 if (Strings::compareLink($server_url, System::baseUrl())) {
149 $contact = self::getRelayContact($server_url);
150 if (is_bool($contact)) {
155 foreach ($contacts as $entry) {
156 if ($entry['batch'] == $contact['batch']) {
162 $contacts[] = $contact;
170 * @brief Return a contact for a given server address or creates a dummy entry
172 * @param string $server_url The url of the server
173 * @param array $fields Fieldlist
174 * @return array with the contact
177 private static function getRelayContact($server_url, $fields = ['batch', 'id', 'name', 'network', 'protocol', 'archive', 'blocked'])
179 // Fetch the relay contact
180 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
181 'contact-type' => Contact::TYPE_RELAY];
182 $contact = DBA::selectFirst('contact', $fields, $condition);
184 if (DBA::isResult($contact)) {
185 if ($contact['archive'] || $contact['blocked']) {
190 self::setRelayContact($server_url);
192 $contact = DBA::selectFirst('contact', $fields, $condition);
193 if (DBA::isResult($contact)) {
198 // It should never happen that we arrive here
203 * @brief Update or insert a relay contact
205 * @param string $server_url The url of the server
206 * @param array $network_fields Optional network specific fields
209 public static function setRelayContact($server_url, array $network_fields = [])
211 $fields = ['created' => DateTimeFormat::utcNow(),
212 'name' => 'relay', 'nick' => 'relay', 'url' => $server_url,
213 'nurl' => Strings::normaliseLink($server_url),
214 'network' => Protocol::DIASPORA, 'uid' => 0,
215 'batch' => $server_url . '/receive/public',
216 'rel' => Contact::FOLLOWER, 'blocked' => false,
217 'pending' => false, 'writable' => true,
218 'baseurl' => $server_url, 'contact-type' => Contact::TYPE_RELAY];
220 $fields = array_merge($fields, $network_fields);
222 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url)];
223 $old = DBA::selectFirst('contact', [], $condition);
224 if (DBA::isResult($old)) {
225 unset($fields['created']);
226 $condition = ['id' => $old['id']];
228 Logger::info('Update relay contact', ['fields' => $fields, 'condition' => $condition]);
229 DBA::update('contact', $fields, $condition, $old);
231 Logger::info('Create relay contact', ['fields' => $fields]);
232 Contact::insert($fields);
237 * @brief Return a list of participating contacts for a thread
239 * This is used for the participation feature.
240 * One of the parameters is a contact array.
241 * This is done to avoid duplicates.
243 * @param integer $thread The id of the thread
244 * @param array $contacts The previously fetched contacts
246 * @return array of relay servers
249 public static function participantsForThread($thread, array $contacts)
251 $r = DBA::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`, `contact`.`protocol`,
252 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
253 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
254 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
255 WHERE `participation`.`iid` = ? AND NOT `contact`.`archive`", $thread);
257 while ($contact = DBA::fetch($r)) {
258 if (!empty($contact['fnetwork'])) {
259 $contact['network'] = $contact['fnetwork'];
261 unset($contact['fnetwork']);
263 if (empty($contact['protocol'])) {
264 $contact['protocol'] = $contact['network'];
267 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
268 $contact['batch'] = $contact['fbatch'];
270 unset($contact['fbatch']);
273 foreach ($contacts as $entry) {
274 if ($entry['batch'] == $contact['batch']) {
280 $contacts[] = $contact;
289 * @brief repairs a signature that was double encoded
291 * The function is unused at the moment. It was copied from the old implementation.
293 * @param string $signature The signature
294 * @param string $handle The handle of the signature owner
295 * @param integer $level This value is only set inside this function to avoid endless loops
297 * @return string the repaired signature
300 private static function repairSignature($signature, $handle = "", $level = 1)
302 if ($signature == "") {
306 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
307 $signature = base64_decode($signature);
308 Logger::log("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, Logger::DEBUG);
310 // Do a recursive call to be able to fix even multiple levels
312 $signature = self::repairSignature($signature, $handle, ++$level);
320 * @brief verify the envelope and return the verified data
322 * @param string $envelope The magic envelope
324 * @return string verified data
325 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
326 * @throws \ImagickException
328 private static function verifyMagicEnvelope($envelope)
330 $basedom = XML::parseString($envelope);
332 if (!is_object($basedom)) {
333 Logger::log("Envelope is no XML file");
337 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
339 if (sizeof($children) == 0) {
340 Logger::log("XML has no children");
346 $data = Strings::base64UrlDecode($children->data);
347 $type = $children->data->attributes()->type[0];
349 $encoding = $children->encoding;
351 $alg = $children->alg;
353 $sig = Strings::base64UrlDecode($children->sig);
354 $key_id = $children->sig->attributes()->key_id[0];
356 $handle = Strings::base64UrlDecode($key_id);
359 $b64url_data = Strings::base64UrlEncode($data);
360 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
362 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
365 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
369 $key = self::key($handle);
371 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
375 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
377 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
385 * @brief encrypts data via AES
387 * @param string $key The AES key
388 * @param string $iv The IV (is used for CBC encoding)
389 * @param string $data The data that is to be encrypted
391 * @return string encrypted data
393 private static function aesEncrypt($key, $iv, $data)
395 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
399 * @brief decrypts data via AES
401 * @param string $key The AES key
402 * @param string $iv The IV (is used for CBC encoding)
403 * @param string $encrypted The encrypted data
405 * @return string decrypted data
407 private static function aesDecrypt($key, $iv, $encrypted)
409 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
413 * @brief: Decodes incoming Diaspora message in the new format
415 * @param array $importer Array of the importer user
416 * @param string $raw raw post message
417 * @param boolean $no_exit Don't do an http exit on error
420 * 'message' -> decoded Diaspora XML message
421 * 'author' -> author diaspora handle
422 * 'key' -> author public key (converted to pkcs#8)
423 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
424 * @throws \ImagickException
426 public static function decodeRaw(array $importer, $raw, $no_exit = false)
428 $data = json_decode($raw);
430 // Is it a private post? Then decrypt the outer Salmon
431 if (is_object($data)) {
432 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
433 $ciphertext = base64_decode($data->encrypted_magic_envelope);
435 $outer_key_bundle = '';
436 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
437 $j_outer_key_bundle = json_decode($outer_key_bundle);
439 if (!is_object($j_outer_key_bundle)) {
440 Logger::log('Outer Salmon did not verify. Discarding.');
444 throw new \Friendica\Network\HTTPException\BadRequestException();
448 $outer_iv = base64_decode($j_outer_key_bundle->iv);
449 $outer_key = base64_decode($j_outer_key_bundle->key);
451 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
456 $basedom = XML::parseString($xml);
458 if (!is_object($basedom)) {
459 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
463 throw new \Friendica\Network\HTTPException\BadRequestException();
467 $base = $basedom->children(NAMESPACE_SALMON_ME);
469 // Not sure if this cleaning is needed
470 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
472 // Build the signed data
473 $type = $base->data[0]->attributes()->type[0];
474 $encoding = $base->encoding;
476 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
478 // This is the signature
479 $signature = Strings::base64UrlDecode($base->sig);
481 // Get the senders' public key
482 $key_id = $base->sig[0]->attributes()->key_id[0];
483 $author_addr = base64_decode($key_id);
484 if ($author_addr == '') {
485 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
489 throw new \Friendica\Network\HTTPException\BadRequestException();
493 $key = self::key($author_addr);
495 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
499 throw new \Friendica\Network\HTTPException\BadRequestException();
503 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
505 Logger::log('Message did not verify. Discarding.');
509 throw new \Friendica\Network\HTTPException\BadRequestException();
513 return ['message' => (string)Strings::base64UrlDecode($base->data),
514 'author' => XML::unescape($author_addr),
515 'key' => (string)$key];
519 * @brief: Decodes incoming Diaspora message in the deprecated format
521 * @param array $importer Array of the importer user
522 * @param string $xml urldecoded Diaspora salmon
525 * 'message' -> decoded Diaspora XML message
526 * 'author' -> author diaspora handle
527 * 'key' -> author public key (converted to pkcs#8)
528 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
529 * @throws \ImagickException
531 public static function decode(array $importer, $xml)
534 $basedom = XML::parseString($xml);
536 if (!is_object($basedom)) {
537 Logger::log("XML is not parseable.");
540 $children = $basedom->children('https://joindiaspora.com/protocol');
542 $inner_aes_key = null;
545 if ($children->header) {
547 $author_link = str_replace('acct:', '', $children->header->author_id);
549 // This happens with posts from a relais
551 Logger::log("This is no private post in the old format", Logger::DEBUG);
555 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
557 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
558 $ciphertext = base64_decode($encrypted_header->ciphertext);
560 $outer_key_bundle = '';
561 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
563 $j_outer_key_bundle = json_decode($outer_key_bundle);
565 $outer_iv = base64_decode($j_outer_key_bundle->iv);
566 $outer_key = base64_decode($j_outer_key_bundle->key);
568 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
570 Logger::log('decrypted: '.$decrypted, Logger::DEBUG);
571 $idom = XML::parseString($decrypted);
573 $inner_iv = base64_decode($idom->iv);
574 $inner_aes_key = base64_decode($idom->aes_key);
576 $author_link = str_replace('acct:', '', $idom->author_id);
579 $dom = $basedom->children(NAMESPACE_SALMON_ME);
581 // figure out where in the DOM tree our data is hiding
584 if ($dom->provenance->data) {
585 $base = $dom->provenance;
586 } elseif ($dom->env->data) {
588 } elseif ($dom->data) {
593 Logger::log('unable to locate salmon data in xml');
594 throw new \Friendica\Network\HTTPException\BadRequestException();
598 // Stash the signature away for now. We have to find their key or it won't be good for anything.
599 $signature = Strings::base64UrlDecode($base->sig);
603 // strip whitespace so our data element will return to one big base64 blob
604 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
607 // stash away some other stuff for later
609 $type = $base->data[0]->attributes()->type[0];
610 $keyhash = $base->sig[0]->attributes()->keyhash[0];
611 $encoding = $base->encoding;
615 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
619 $data = Strings::base64UrlDecode($data);
623 $inner_decrypted = $data;
625 // Decode the encrypted blob
626 $inner_encrypted = base64_decode($data);
627 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
631 Logger::log('Could not retrieve author URI.');
632 throw new \Friendica\Network\HTTPException\BadRequestException();
634 // Once we have the author URI, go to the web and try to find their public key
635 // (first this will look it up locally if it is in the fcontact cache)
636 // This will also convert diaspora public key from pkcs#1 to pkcs#8
638 Logger::log('Fetching key for '.$author_link);
639 $key = self::key($author_link);
642 Logger::log('Could not retrieve author key.');
643 throw new \Friendica\Network\HTTPException\BadRequestException();
646 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
649 Logger::log('Message did not verify. Discarding.');
650 throw new \Friendica\Network\HTTPException\BadRequestException();
653 Logger::log('Message verified.');
655 return ['message' => (string)$inner_decrypted,
656 'author' => XML::unescape($author_link),
657 'key' => (string)$key];
662 * @brief Dispatches public messages and find the fitting receivers
664 * @param array $msg The post that will be dispatched
666 * @return int The message id of the generated message, "true" or "false" if there was an error
667 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
668 * @throws \ImagickException
670 public static function dispatchPublic($msg)
672 $enabled = intval(Config::get("system", "diaspora_enabled"));
674 Logger::log("diaspora is disabled");
678 if (!($fields = self::validPosting($msg))) {
679 Logger::log("Invalid posting");
683 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
684 $success = self::dispatch($importer, $msg, $fields);
690 * @brief Dispatches the different message types to the different functions
692 * @param array $importer Array of the importer user
693 * @param array $msg The post that will be dispatched
694 * @param SimpleXMLElement $fields SimpleXML object that contains the message
696 * @return int The message id of the generated message, "true" or "false" if there was an error
697 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
698 * @throws \ImagickException
700 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
702 // The sender is the handle of the contact that sent the message.
703 // This will often be different with relayed messages (for example "like" and "comment")
704 $sender = $msg["author"];
706 // This is only needed for private postings since this is already done for public ones before
707 if (is_null($fields)) {
709 if (!($fields = self::validPosting($msg))) {
710 Logger::log("Invalid posting");
717 $type = $fields->getName();
719 Logger::log("Received message type ".$type." from ".$sender." for user ".$importer["uid"], Logger::DEBUG);
722 case "account_migration":
724 Logger::log('Message with type ' . $type . ' is not private, quitting.');
727 return self::receiveAccountMigration($importer, $fields);
729 case "account_deletion":
730 return self::receiveAccountDeletion($fields);
733 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
737 Logger::log('Message with type ' . $type . ' is not private, quitting.');
740 return self::receiveContactRequest($importer, $fields);
744 Logger::log('Message with type ' . $type . ' is not private, quitting.');
747 return self::receiveConversation($importer, $msg, $fields);
750 return self::receiveLike($importer, $sender, $fields);
754 Logger::log('Message with type ' . $type . ' is not private, quitting.');
757 return self::receiveMessage($importer, $fields);
759 case "participation":
761 Logger::log('Message with type ' . $type . ' is not private, quitting.');
764 return self::receiveParticipation($importer, $fields);
766 case "photo": // Not implemented
767 return self::receivePhoto($importer, $fields);
769 case "poll_participation": // Not implemented
770 return self::receivePollParticipation($importer, $fields);
774 Logger::log('Message with type ' . $type . ' is not private, quitting.');
777 return self::receiveProfile($importer, $fields);
780 return self::receiveReshare($importer, $fields, $msg["message"]);
783 return self::receiveRetraction($importer, $sender, $fields);
785 case "status_message":
786 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
789 Logger::log("Unknown message type ".$type);
795 * @brief Checks if a posting is valid and fetches the data fields.
797 * This function does not only check the signature.
798 * It also does the conversion between the old and the new diaspora format.
800 * @param array $msg Array with the XML, the sender handle and the sender signature
802 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
803 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
804 * @throws \ImagickException
806 private static function validPosting($msg)
808 $data = XML::parseString($msg["message"]);
810 if (!is_object($data)) {
811 Logger::log("No valid XML ".$msg["message"], Logger::DEBUG);
815 // Is this the new or the old version?
816 if ($data->getName() == "XML") {
818 foreach ($data->post->children() as $child) {
826 $type = $element->getName();
829 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
831 // All retractions are handled identically from now on.
832 // In the new version there will only be "retraction".
833 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
834 $type = "retraction";
836 if ($type == "request") {
840 $fields = new SimpleXMLElement("<".$type."/>");
843 $author_signature = null;
844 $parent_author_signature = null;
846 foreach ($element->children() as $fieldname => $entry) {
848 // Translation for the old XML structure
849 if ($fieldname == "diaspora_handle") {
850 $fieldname = "author";
852 if ($fieldname == "participant_handles") {
853 $fieldname = "participants";
855 if (in_array($type, ["like", "participation"])) {
856 if ($fieldname == "target_type") {
857 $fieldname = "parent_type";
860 if ($fieldname == "sender_handle") {
861 $fieldname = "author";
863 if ($fieldname == "recipient_handle") {
864 $fieldname = "recipient";
866 if ($fieldname == "root_diaspora_id") {
867 $fieldname = "root_author";
869 if ($type == "status_message") {
870 if ($fieldname == "raw_message") {
874 if ($type == "retraction") {
875 if ($fieldname == "post_guid") {
876 $fieldname = "target_guid";
878 if ($fieldname == "type") {
879 $fieldname = "target_type";
884 if (($fieldname == "author_signature") && ($entry != "")) {
885 $author_signature = base64_decode($entry);
886 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
887 $parent_author_signature = base64_decode($entry);
888 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
889 if ($signed_data != "") {
893 $signed_data .= $entry;
895 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
896 || ($orig_type == "relayable_retraction")
898 XML::copy($entry, $fields, $fieldname);
902 // This is something that shouldn't happen at all.
903 if (in_array($type, ["status_message", "reshare", "profile"])) {
904 if ($msg["author"] != $fields->author) {
905 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
910 // Only some message types have signatures. So we quit here for the other types.
911 if (!in_array($type, ["comment", "like"])) {
914 // No author_signature? This is a must, so we quit.
915 if (!isset($author_signature)) {
916 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
920 if (isset($parent_author_signature)) {
921 $key = self::key($msg["author"]);
923 Logger::log("No key found for parent author ".$msg["author"], Logger::DEBUG);
927 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
928 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);
933 $key = self::key($fields->author);
935 Logger::log("No key found for author ".$fields->author, Logger::DEBUG);
939 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
940 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);
948 * @brief Fetches the public key for a given handle
950 * @param string $handle The handle
952 * @return string The public key
953 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
954 * @throws \ImagickException
956 private static function key($handle)
958 $handle = strval($handle);
960 Logger::log("Fetching diaspora key for: ".$handle);
962 $r = self::personByHandle($handle);
971 * @brief Fetches data for a given handle
973 * @param string $handle The handle
974 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
976 * @return array the queried data
977 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
978 * @throws \ImagickException
980 public static function personByHandle($handle, $update = null)
982 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
983 if (!DBA::isResult($person)) {
984 $urls = [$handle, str_replace('http://', 'https://', $handle), Strings::normaliseLink($handle)];
985 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'url' => $urls]);
988 if (DBA::isResult($person)) {
989 Logger::debug("In cache " . print_r($person, true));
991 if (is_null($update)) {
992 // update record occasionally so it doesn't get stale
993 $d = strtotime($person["updated"]." +00:00");
994 if ($d < strtotime("now - 14 days")) {
998 if ($person["guid"] == "") {
1002 } elseif (is_null($update)) {
1003 $update = !DBA::isResult($person);
1009 Logger::log("create or refresh", Logger::DEBUG);
1010 $r = Probe::uri($handle, Protocol::DIASPORA);
1012 // Note that Friendica contacts will return a "Diaspora person"
1013 // if Diaspora connectivity is enabled on their server
1014 if ($r && ($r["network"] === Protocol::DIASPORA)) {
1015 self::updateFContact($r);
1017 $person = self::personByHandle($handle, false);
1025 * @brief Updates the fcontact table
1027 * @param array $arr The fcontact data
1028 * @throws \Exception
1030 private static function updateFContact($arr)
1032 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
1033 'request' => $arr["request"], 'nick' => $arr["nick"],
1034 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
1035 'batch' => $arr["batch"], 'notify' => $arr["notify"],
1036 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
1037 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
1038 'updated' => DateTimeFormat::utcNow()];
1040 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
1042 DBA::update('fcontact', $fields, $condition, true);
1046 * @brief get a handle (user@domain.tld) from a given contact id
1048 * @param int $contact_id The id in the contact table
1049 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1051 * @return string the handle
1052 * @throws \Exception
1054 private static function handleFromContact($contact_id, $pcontact_id = 0)
1058 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
1060 if ($pcontact_id != 0) {
1061 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
1063 if (DBA::isResult($contact) && !empty($contact["addr"])) {
1064 return strtolower($contact["addr"]);
1069 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1073 if (DBA::isResult($r)) {
1076 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1078 if ($contact['addr'] != "") {
1079 $handle = $contact['addr'];
1081 $baseurl_start = strpos($contact['url'], '://') + 3;
1082 // allows installations in a subdirectory--not sure how Diaspora will handle
1083 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1084 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1085 $handle = $contact['nick'].'@'.$baseurl;
1089 return strtolower($handle);
1093 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
1096 * @param mixed $fcontact_guid Hexadecimal string guid
1098 * @return string the contact url or null
1099 * @throws \Exception
1101 public static function urlFromContactGuid($fcontact_guid)
1103 Logger::log("fcontact guid is ".$fcontact_guid, Logger::DEBUG);
1106 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1107 DBA::escape(Protocol::DIASPORA),
1108 DBA::escape($fcontact_guid)
1111 if (DBA::isResult($r)) {
1112 return $r[0]['url'];
1119 * @brief Get a contact id for a given handle
1121 * @todo Move to Friendica\Model\Contact
1123 * @param int $uid The user id
1124 * @param string $handle The handle in the format user@domain.tld
1126 * @return array Contact data
1127 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1128 * @throws \ImagickException
1130 private static function contactByHandle($uid, $handle)
1132 $cid = Contact::getIdForURL($handle, $uid);
1134 $handle_parts = explode("@", $handle);
1135 $nurl_sql = "%%://" . $handle_parts[1] . "%%/profile/" . $handle_parts[0];
1136 $cid = Contact::getIdForURL($nurl_sql, $uid);
1140 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1144 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1145 if (!DBA::isResult($contact)) {
1146 // This here shouldn't happen at all
1147 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1155 * Checks if the given contact url does support ActivityPub
1157 * @param string $url profile url
1158 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1160 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1161 * @throws \ImagickException
1163 public static function isSupportedByContactUrl($url, $update = null)
1165 return !empty(self::personByHandle($url, $update));
1169 * @brief Check if posting is allowed for this contact
1171 * @param array $importer Array of the importer user
1172 * @param array $contact The contact that is checked
1173 * @param bool $is_comment Is the check for a comment?
1175 * @return bool is the contact allowed to post?
1177 private static function postAllow(array $importer, array $contact, $is_comment = false)
1180 * Perhaps we were already sharing with this person. Now they're sharing with us.
1181 * That makes us friends.
1182 * Normally this should have handled by getting a request - but this could get lost
1184 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1185 // It is not removed by now. Possibly the code is needed?
1186 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1189 // array('rel' => Contact::FRIEND, 'writable' => true),
1190 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1193 // $contact["rel"] = Contact::FRIEND;
1194 // Logger::log("defining user ".$contact["nick"]." as friend");
1197 // Contact server is blocked
1198 if (Network::isUrlBlocked($contact['url'])) {
1200 // We don't seem to like that person
1201 } elseif ($contact["blocked"]) {
1202 // Maybe blocked, don't accept.
1204 // We are following this person?
1205 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1206 // Yes, then it is fine.
1208 // Is it a post to a community?
1209 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1212 // Is the message a global user or a comment?
1213 } elseif (($importer["uid"] == 0) || $is_comment) {
1214 // Messages for the global users and comments are always accepted
1222 * @brief Fetches the contact id for a handle and checks if posting is allowed
1224 * @param array $importer Array of the importer user
1225 * @param string $handle The checked handle in the format user@domain.tld
1226 * @param bool $is_comment Is the check for a comment?
1228 * @return array The contact data
1229 * @throws \Exception
1231 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1233 $contact = self::contactByHandle($importer["uid"], $handle);
1235 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1236 // If a contact isn't found, we accept it anyway if it is a comment
1237 if ($is_comment && ($importer["uid"] != 0)) {
1238 return self::contactByHandle(0, $handle);
1239 } elseif ($is_comment) {
1246 if (!self::postAllow($importer, $contact, $is_comment)) {
1247 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1254 * @brief Does the message already exists on the system?
1256 * @param int $uid The user id
1257 * @param string $guid The guid of the message
1259 * @return int|bool message id if the message already was stored into the system - or false.
1260 * @throws \Exception
1262 private static function messageExists($uid, $guid)
1264 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1265 if (DBA::isResult($item)) {
1266 Logger::log("message ".$guid." already exists for user ".$uid);
1274 * @brief Checks for links to posts in a message
1276 * @param array $item The item array
1279 private static function fetchGuid(array $item)
1281 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1282 preg_replace_callback(
1284 function ($match) use ($item) {
1285 self::fetchGuidSub($match, $item);
1290 preg_replace_callback(
1291 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1292 function ($match) use ($item) {
1293 self::fetchGuidSub($match, $item);
1300 * @brief Checks for relative /people/* links in an item body to match local
1301 * contacts or prepends the remote host taken from the author link.
1303 * @param string $body The item body to replace links from
1304 * @param string $author_link The author link for missing local contact fallback
1306 * @return string the replaced string
1308 public static function replacePeopleGuid($body, $author_link)
1310 $return = preg_replace_callback(
1311 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1312 function ($match) use ($author_link) {
1314 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1315 // 1 => '0123456789abcdef'
1317 $handle = self::urlFromContactGuid($match[1]);
1320 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1322 // No local match, restoring absolute remote URL from author scheme and host
1323 $author_url = parse_url($author_link);
1324 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1336 * @brief sub function of "fetchGuid" which checks for links in messages
1338 * @param array $match array containing a link that has to be checked for a message link
1339 * @param array $item The item array
1341 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1342 * @throws \ImagickException
1344 private static function fetchGuidSub($match, $item)
1346 if (!self::storeByGuid($match[1], $item["author-link"])) {
1347 self::storeByGuid($match[1], $item["owner-link"]);
1352 * @brief Fetches an item with a given guid from a given server
1354 * @param string $guid the message guid
1355 * @param string $server The server address
1356 * @param int $uid The user id of the user
1358 * @return int the message id of the stored message or false
1359 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1360 * @throws \ImagickException
1362 private static function storeByGuid($guid, $server, $uid = 0)
1364 $serverparts = parse_url($server);
1366 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1370 $server = $serverparts["scheme"]."://".$serverparts["host"];
1372 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1374 $msg = self::message($guid, $server);
1380 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1382 // Now call the dispatcher
1383 return self::dispatchPublic($msg);
1387 * @brief Fetches a message from a server
1389 * @param string $guid message guid
1390 * @param string $server The url of the server
1391 * @param int $level Endless loop prevention
1394 * 'message' => The message XML
1395 * 'author' => The author handle
1396 * 'key' => The public key of the author
1397 * @throws \Exception
1399 private static function message($guid, $server, $level = 0)
1405 // This will work for new Diaspora servers and Friendica servers from 3.5
1406 $source_url = $server."/fetch/post/".urlencode($guid);
1408 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1410 $envelope = Network::fetchUrl($source_url);
1412 Logger::log("Envelope was fetched.", Logger::DEBUG);
1413 $x = self::verifyMagicEnvelope($envelope);
1415 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1417 Logger::log("Envelope was verified.", Logger::DEBUG);
1427 $source_xml = XML::parseString($x);
1429 if (!is_object($source_xml)) {
1433 if ($source_xml->post->reshare) {
1434 // Reshare of a reshare - old Diaspora version
1435 Logger::log("Message is a reshare", Logger::DEBUG);
1436 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1437 } elseif ($source_xml->getName() == "reshare") {
1438 // Reshare of a reshare - new Diaspora version
1439 Logger::log("Message is a new reshare", Logger::DEBUG);
1440 return self::message($source_xml->root_guid, $server, ++$level);
1445 // Fetch the author - for the old and the new Diaspora version
1446 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1447 $author = (string)$source_xml->post->status_message->diaspora_handle;
1448 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1449 $author = (string)$source_xml->author;
1452 // If this isn't a "status_message" then quit
1454 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1458 $msg = ["message" => $x, "author" => $author];
1460 $msg["key"] = self::key($msg["author"]);
1466 * @brief Fetches an item with a given URL
1468 * @param string $url the message url
1470 * @return int the message id of the stored message or false
1471 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1472 * @throws \ImagickException
1474 public static function fetchByURL($url, $uid = 0)
1476 // Check for Diaspora (and Friendica) typical paths
1477 if (!preg_match("=(https?://.+)/(?:posts|display)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1481 $guid = urldecode($matches[2]);
1483 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1484 if (DBA::isResult($item)) {
1488 self::storeByGuid($guid, $matches[1], $uid);
1490 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1491 if (DBA::isResult($item)) {
1499 * @brief Fetches the item record of a given guid
1501 * @param int $uid The user id
1502 * @param string $guid message guid
1503 * @param string $author The handle of the item
1504 * @param array $contact The contact of the item owner
1506 * @return array the item record
1507 * @throws \Exception
1509 private static function parentItem($uid, $guid, $author, array $contact)
1511 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1512 'author-name', 'author-link', 'author-avatar',
1513 'owner-name', 'owner-link', 'owner-avatar'];
1514 $condition = ['uid' => $uid, 'guid' => $guid];
1515 $item = Item::selectFirst($fields, $condition);
1517 if (!DBA::isResult($item)) {
1518 $person = self::personByHandle($author);
1519 $result = self::storeByGuid($guid, $person["url"], $uid);
1521 // We don't have an url for items that arrived at the public dispatcher
1522 if (!$result && !empty($contact["url"])) {
1523 $result = self::storeByGuid($guid, $contact["url"], $uid);
1527 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1529 $item = Item::selectFirst($fields, $condition);
1533 if (!DBA::isResult($item)) {
1534 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1537 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1543 * @brief returns contact details
1545 * @param array $def_contact The default contact if the person isn't found
1546 * @param array $person The record of the person
1547 * @param int $uid The user id
1550 * 'cid' => contact id
1551 * 'network' => network type
1552 * @throws \Exception
1554 private static function authorContactByUrl($def_contact, $person, $uid)
1556 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1557 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1558 if (DBA::isResult($contact)) {
1559 $cid = $contact["id"];
1560 $network = $contact["network"];
1562 $cid = $def_contact["id"];
1563 $network = Protocol::DIASPORA;
1566 return ["cid" => $cid, "network" => $network];
1570 * @brief Is the profile a hubzilla profile?
1572 * @param string $url The profile link
1574 * @return bool is it a hubzilla server?
1576 public static function isRedmatrix($url)
1578 return(strstr($url, "/channel/"));
1582 * @brief Generate a post link with a given handle and message guid
1584 * @param string $addr The user handle
1585 * @param string $guid message guid
1586 * @param string $parent_guid optional parent guid
1588 * @return string the post link
1589 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1590 * @throws \ImagickException
1592 private static function plink($addr, $guid, $parent_guid = '')
1594 $contact = Contact::getDetailsByAddr($addr);
1598 if ($parent_guid != '') {
1599 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1601 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1605 if ($contact["network"] == Protocol::DFRN) {
1606 return str_replace("/profile/" . $contact["nick"] . "/", "/display/" . $guid, $contact["url"] . "/");
1609 if (self::isRedmatrix($contact["url"])) {
1610 return $contact["url"] . "/?f=&mid=" . $guid;
1613 if ($parent_guid != '') {
1614 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1616 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1621 * @brief Receives account migration
1623 * @param array $importer Array of the importer user
1624 * @param object $data The message object
1626 * @return bool Success
1627 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1628 * @throws \ImagickException
1630 private static function receiveAccountMigration(array $importer, $data)
1632 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1633 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1634 $signature = Strings::escapeTags(XML::unescape($data->signature));
1636 $contact = self::contactByHandle($importer["uid"], $old_handle);
1638 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1642 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1645 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1646 $key = self::key($old_handle);
1647 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1648 Logger::log('No valid signature for migration.');
1652 // Update the profile
1653 self::receiveProfile($importer, $data->profile);
1655 // change the technical stuff in contact and gcontact
1656 $data = Probe::uri($new_handle);
1657 if ($data['network'] == Protocol::PHANTOM) {
1658 Logger::log('Account for '.$new_handle." couldn't be probed.");
1662 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1663 'name' => $data['name'], 'nick' => $data['nick'],
1664 'addr' => $data['addr'], 'batch' => $data['batch'],
1665 'notify' => $data['notify'], 'poll' => $data['poll'],
1666 'network' => $data['network']];
1668 DBA::update('contact', $fields, ['addr' => $old_handle]);
1670 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1671 'name' => $data['name'], 'nick' => $data['nick'],
1672 'addr' => $data['addr'], 'connect' => $data['addr'],
1673 'notify' => $data['notify'], 'photo' => $data['photo'],
1674 'server_url' => $data['baseurl'], 'network' => $data['network']];
1676 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1678 Logger::log('Contacts are updated.');
1684 * @brief Processes an account deletion
1686 * @param object $data The message object
1688 * @return bool Success
1689 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1691 private static function receiveAccountDeletion($data)
1693 $author = Strings::escapeTags(XML::unescape($data->author));
1695 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1696 while ($contact = DBA::fetch($contacts)) {
1697 Contact::remove($contact["id"]);
1700 DBA::delete('gcontact', ['addr' => $author]);
1702 Logger::log('Removed contacts for ' . $author);
1708 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1710 * @param string $author Author handle
1711 * @param string $guid Message guid
1712 * @param boolean $onlyfound Only return uri when found in the database
1714 * @return string The constructed uri or the one from our database
1715 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1716 * @throws \ImagickException
1718 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1720 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1721 if (DBA::isResult($item)) {
1722 return $item["uri"];
1723 } elseif (!$onlyfound) {
1724 $person = self::personByHandle($author);
1726 $parts = parse_url($person['url']);
1727 unset($parts['path']);
1728 $host_url = Network::unparseURL($parts);
1730 return $host_url . '/objects/' . $guid;
1737 * @brief Fetch the guid from our database with a given uri
1739 * @param string $uri Message uri
1740 * @param string $uid Author handle
1742 * @return string The post guid
1743 * @throws \Exception
1745 private static function getGuidFromUri($uri, $uid)
1747 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1748 if (DBA::isResult($item)) {
1749 return $item["guid"];
1756 * @brief Find the best importer for a comment, like, ...
1758 * @param string $guid The guid of the item
1760 * @return array|boolean the origin owner of that post - or false
1761 * @throws \Exception
1763 private static function importerForGuid($guid)
1765 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1766 if (DBA::isResult($item)) {
1767 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1768 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1769 if (DBA::isResult($contact)) {
1777 * @brief Processes an incoming comment
1779 * @param array $importer Array of the importer user
1780 * @param string $sender The sender of the message
1781 * @param object $data The message object
1782 * @param string $xml The original XML of the message
1784 * @return int The message id of the generated comment or "false" if there was an error
1785 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1786 * @throws \ImagickException
1788 private static function receiveComment(array $importer, $sender, $data, $xml)
1790 $author = Strings::escapeTags(XML::unescape($data->author));
1791 $guid = Strings::escapeTags(XML::unescape($data->guid));
1792 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1793 $text = XML::unescape($data->text);
1795 if (isset($data->created_at)) {
1796 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1798 $created_at = DateTimeFormat::utcNow();
1801 if (isset($data->thread_parent_guid)) {
1802 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1803 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1808 $contact = self::allowedContactByHandle($importer, $sender, true);
1813 $message_id = self::messageExists($importer["uid"], $guid);
1818 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1819 if (!$parent_item) {
1823 $person = self::personByHandle($author);
1824 if (!is_array($person)) {
1825 Logger::log("unable to find author details");
1829 // Fetch the contact id - if we know this contact
1830 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1834 $datarray["uid"] = $importer["uid"];
1835 $datarray["contact-id"] = $author_contact["cid"];
1836 $datarray["network"] = $author_contact["network"];
1838 $datarray["author-link"] = $person["url"];
1839 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1841 $datarray["owner-link"] = $contact["url"];
1842 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1844 $datarray["guid"] = $guid;
1845 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1847 $datarray["verb"] = ACTIVITY_POST;
1848 $datarray["gravity"] = GRAVITY_COMMENT;
1850 if ($thr_uri != "") {
1851 $datarray["parent-uri"] = $thr_uri;
1853 $datarray["parent-uri"] = $parent_item["uri"];
1856 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1858 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1859 $datarray["source"] = $xml;
1861 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1863 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1865 $body = Markdown::toBBCode($text);
1867 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1869 self::fetchGuid($datarray);
1871 // If we are the origin of the parent we store the original data.
1872 // We notify our followers during the item storage.
1873 if ($parent_item["origin"]) {
1874 $datarray['diaspora_signed_text'] = json_encode($data);
1877 $message_id = Item::insert($datarray);
1879 if ($message_id <= 0) {
1884 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1885 if ($datarray['uid'] == 0) {
1886 Item::distribute($message_id, json_encode($data));
1894 * @brief processes and stores private messages
1896 * @param array $importer Array of the importer user
1897 * @param array $contact The contact of the message
1898 * @param object $data The message object
1899 * @param array $msg Array of the processed message, author handle and key
1900 * @param object $mesg The private message
1901 * @param array $conversation The conversation record to which this message belongs
1903 * @return bool "true" if it was successful
1904 * @throws \Exception
1906 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1908 $author = Strings::escapeTags(XML::unescape($data->author));
1909 $guid = Strings::escapeTags(XML::unescape($data->guid));
1910 $subject = Strings::escapeTags(XML::unescape($data->subject));
1912 // "diaspora_handle" is the element name from the old version
1913 // "author" is the element name from the new version
1914 if ($mesg->author) {
1915 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1916 } elseif ($mesg->diaspora_handle) {
1917 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1922 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1923 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1924 $msg_text = XML::unescape($mesg->text);
1925 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1927 if ($msg_conversation_guid != $guid) {
1928 Logger::log("message conversation guid does not belong to the current conversation.");
1932 $body = Markdown::toBBCode($msg_text);
1933 $message_uri = $msg_author.":".$msg_guid;
1935 $person = self::personByHandle($msg_author);
1937 return Mail::insert([
1938 'uid' => $importer['uid'],
1939 'guid' => $msg_guid,
1940 'convid' => $conversation['id'],
1941 'from-name' => $person['name'],
1942 'from-photo' => $person['photo'],
1943 'from-url' => $person['url'],
1944 'contact-id' => $contact['id'],
1945 'title' => $subject,
1947 'uri' => $message_uri,
1948 'parent-uri' => $author . ':' . $guid,
1949 'created' => $msg_created_at
1954 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1956 * @param array $importer Array of the importer user
1957 * @param array $msg Array of the processed message, author handle and key
1958 * @param object $data The message object
1960 * @return bool Success
1961 * @throws \Exception
1963 private static function receiveConversation(array $importer, $msg, $data)
1965 $author = Strings::escapeTags(XML::unescape($data->author));
1966 $guid = Strings::escapeTags(XML::unescape($data->guid));
1967 $subject = Strings::escapeTags(XML::unescape($data->subject));
1968 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1969 $participants = Strings::escapeTags(XML::unescape($data->participants));
1971 $messages = $data->message;
1973 if (!count($messages)) {
1974 Logger::log("empty conversation");
1978 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1983 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1984 if (!DBA::isResult($conversation)) {
1986 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1987 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1988 intval($importer["uid"]),
1990 DBA::escape($author),
1991 DBA::escape($created_at),
1992 DBA::escape(DateTimeFormat::utcNow()),
1993 DBA::escape($subject),
1994 DBA::escape($participants)
1997 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2000 if (!$conversation) {
2001 Logger::log("unable to create conversation.");
2005 foreach ($messages as $mesg) {
2006 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
2013 * @brief Processes "like" messages
2015 * @param array $importer Array of the importer user
2016 * @param string $sender The sender of the message
2017 * @param object $data The message object
2019 * @return int The message id of the generated like or "false" if there was an error
2020 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2021 * @throws \ImagickException
2023 private static function receiveLike(array $importer, $sender, $data)
2025 $author = Strings::escapeTags(XML::unescape($data->author));
2026 $guid = Strings::escapeTags(XML::unescape($data->guid));
2027 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2028 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
2029 $positive = Strings::escapeTags(XML::unescape($data->positive));
2031 // likes on comments aren't supported by Diaspora - only on posts
2032 // But maybe this will be supported in the future, so we will accept it.
2033 if (!in_array($parent_type, ["Post", "Comment"])) {
2037 $contact = self::allowedContactByHandle($importer, $sender, true);
2042 $message_id = self::messageExists($importer["uid"], $guid);
2047 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2048 if (!$parent_item) {
2052 $person = self::personByHandle($author);
2053 if (!is_array($person)) {
2054 Logger::log("unable to find author details");
2058 // Fetch the contact id - if we know this contact
2059 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2061 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2062 // We would accept this anyhow.
2063 if ($positive == "true") {
2064 $verb = ACTIVITY_LIKE;
2066 $verb = ACTIVITY_DISLIKE;
2071 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2073 $datarray["uid"] = $importer["uid"];
2074 $datarray["contact-id"] = $author_contact["cid"];
2075 $datarray["network"] = $author_contact["network"];
2077 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2078 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2080 $datarray["guid"] = $guid;
2081 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2083 $datarray["verb"] = $verb;
2084 $datarray["gravity"] = GRAVITY_ACTIVITY;
2085 $datarray["parent-uri"] = $parent_item["uri"];
2087 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2089 $datarray["body"] = $verb;
2091 // Diaspora doesn't provide a date for likes
2092 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2094 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2095 if ($parent_item["id"] != $parent_item["parent"]) {
2096 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
2097 $origin = $toplevel["origin"];
2099 $origin = $parent_item["origin"];
2102 // If we are the origin of the parent we store the original data.
2103 // We notify our followers during the item storage.
2105 $datarray['diaspora_signed_text'] = json_encode($data);
2108 $message_id = Item::insert($datarray);
2110 if ($message_id <= 0) {
2115 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2116 if ($datarray['uid'] == 0) {
2117 Item::distribute($message_id, json_encode($data));
2125 * @brief Processes private messages
2127 * @param array $importer Array of the importer user
2128 * @param object $data The message object
2130 * @return bool Success?
2131 * @throws \Exception
2133 private static function receiveMessage(array $importer, $data)
2135 $author = Strings::escapeTags(XML::unescape($data->author));
2136 $guid = Strings::escapeTags(XML::unescape($data->guid));
2137 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2138 $text = XML::unescape($data->text);
2139 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2141 $contact = self::allowedContactByHandle($importer, $author, true);
2146 $conversation = null;
2148 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2149 $conversation = DBA::selectFirst('conv', [], $condition);
2151 if (!DBA::isResult($conversation)) {
2152 Logger::log("conversation not available.");
2156 $message_uri = $author.":".$guid;
2158 $person = self::personByHandle($author);
2160 Logger::log("unable to find author details");
2164 $body = Markdown::toBBCode($text);
2166 $body = self::replacePeopleGuid($body, $person["url"]);
2168 return Mail::insert([
2169 'uid' => $importer['uid'],
2171 'convid' => $conversation['id'],
2172 'from-name' => $person['name'],
2173 'from-photo' => $person['photo'],
2174 'from-url' => $person['url'],
2175 'contact-id' => $contact['id'],
2176 'title' => $conversation['subject'],
2179 'uri' => $message_uri,
2180 'parent-uri' => $author.":".$conversation['guid'],
2181 'created' => $created_at
2186 * @brief Processes participations - unsupported by now
2188 * @param array $importer Array of the importer user
2189 * @param object $data The message object
2191 * @return bool always true
2192 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2193 * @throws \ImagickException
2195 private static function receiveParticipation(array $importer, $data)
2197 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2198 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2200 $contact_id = Contact::getIdForURL($author);
2202 Logger::log('Contact not found: '.$author);
2206 $person = self::personByHandle($author);
2207 if (!is_array($person)) {
2208 Logger::log("Person not found: ".$author);
2212 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2213 if (!DBA::isResult($item)) {
2214 Logger::log('Item not found, no origin or private: '.$parent_guid);
2218 $author_parts = explode('@', $author);
2219 if (isset($author_parts[1])) {
2220 $server = $author_parts[1];
2222 // Should never happen
2226 Logger::log('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, Logger::DEBUG);
2228 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2229 DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2232 // Send all existing comments and likes to the requesting server
2233 $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2234 while ($comment = Item::fetch($comments)) {
2235 if ($comment['id'] == $comment['parent']) {
2239 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $contact_id]);
2240 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $contact_id)) {
2241 ItemDeliveryData::incrementQueueCount($comment['id'], 1);
2244 DBA::close($comments);
2250 * @brief Processes photos - unneeded
2252 * @param array $importer Array of the importer user
2253 * @param object $data The message object
2255 * @return bool always true
2257 private static function receivePhoto(array $importer, $data)
2259 // There doesn't seem to be a reason for this function,
2260 // since the photo data is transmitted in the status message as well
2265 * @brief Processes poll participations - unssupported
2267 * @param array $importer Array of the importer user
2268 * @param object $data The message object
2270 * @return bool always true
2272 private static function receivePollParticipation(array $importer, $data)
2274 // We don't support polls by now
2279 * @brief Processes incoming profile updates
2281 * @param array $importer Array of the importer user
2282 * @param object $data The message object
2284 * @return bool Success
2285 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2286 * @throws \ImagickException
2288 private static function receiveProfile(array $importer, $data)
2290 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2292 $contact = self::contactByHandle($importer["uid"], $author);
2297 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2298 $image_url = XML::unescape($data->image_url);
2299 $birthday = XML::unescape($data->birthday);
2300 $gender = XML::unescape($data->gender);
2301 $about = Markdown::toBBCode(XML::unescape($data->bio));
2302 $location = Markdown::toBBCode(XML::unescape($data->location));
2303 $searchable = (XML::unescape($data->searchable) == "true");
2304 $nsfw = (XML::unescape($data->nsfw) == "true");
2305 $tags = XML::unescape($data->tag_string);
2307 $tags = explode("#", $tags);
2310 foreach ($tags as $tag) {
2311 $tag = trim(strtolower($tag));
2317 $keywords = implode(", ", $keywords);
2319 $handle_parts = explode("@", $author);
2320 $nick = $handle_parts[0];
2323 $name = $handle_parts[0];
2326 if (preg_match("|^https?://|", $image_url) === 0) {
2327 $image_url = "http://".$handle_parts[1].$image_url;
2330 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2332 // Generic birthday. We don't know the timezone. The year is irrelevant.
2334 $birthday = str_replace("1000", "1901", $birthday);
2336 if ($birthday != "") {
2337 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2340 // this is to prevent multiple birthday notifications in a single year
2341 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2343 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2344 $birthday = $contact["bd"];
2347 $fields = ['name' => $name, 'location' => $location,
2348 'name-date' => DateTimeFormat::utcNow(),
2349 'about' => $about, 'gender' => $gender,
2350 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2351 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2353 if (!empty($birthday)) {
2354 $fields['bd'] = $birthday;
2357 DBA::update('contact', $fields, ['id' => $contact['id']]);
2359 // @todo Update the public contact, then update the gcontact from that
2361 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2362 "photo" => $image_url, "name" => $name, "location" => $location,
2363 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2364 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2365 "hide" => !$searchable, "nsfw" => $nsfw];
2367 $gcid = GContact::update($gcontact);
2369 GContact::link($gcid, $importer["uid"], $contact["id"]);
2371 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2377 * @brief Processes incoming friend requests
2379 * @param array $importer Array of the importer user
2380 * @param array $contact The contact that send the request
2382 * @throws \Exception
2384 private static function receiveRequestMakeFriend(array $importer, array $contact)
2386 if ($contact["rel"] == Contact::SHARING) {
2389 ['rel' => Contact::FRIEND, 'writable' => true],
2390 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2396 * @brief Processes incoming sharing notification
2398 * @param array $importer Array of the importer user
2399 * @param object $data The message object
2401 * @return bool Success
2402 * @throws \Exception
2404 private static function receiveContactRequest(array $importer, $data)
2406 $author = XML::unescape($data->author);
2407 $recipient = XML::unescape($data->recipient);
2409 if (!$author || !$recipient) {
2413 // the current protocol version doesn't know these fields
2414 // That means that we will assume their existance
2415 if (isset($data->following)) {
2416 $following = (XML::unescape($data->following) == "true");
2421 if (isset($data->sharing)) {
2422 $sharing = (XML::unescape($data->sharing) == "true");
2427 $contact = self::contactByHandle($importer["uid"], $author);
2429 // perhaps we were already sharing with this person. Now they're sharing with us.
2430 // That makes us friends.
2433 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2434 self::receiveRequestMakeFriend($importer, $contact);
2436 // refetch the contact array
2437 $contact = self::contactByHandle($importer["uid"], $author);
2439 // If we are now friends, we are sending a share message.
2440 // Normally we needn't to do so, but the first message could have been vanished.
2441 if (in_array($contact["rel"], [Contact::FRIEND])) {
2442 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2443 if (DBA::isResult($user)) {
2444 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2445 self::sendShare($user, $contact);
2450 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2451 Contact::removeFollower($importer, $contact);
2456 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2457 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2459 } elseif (!$following && !$sharing) {
2460 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2462 } elseif (!$following && $sharing) {
2463 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2464 } elseif ($following && $sharing) {
2465 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2466 } elseif ($following && !$sharing) {
2467 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2470 $ret = self::personByHandle($author);
2472 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2473 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2477 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2480 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2481 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2482 intval($importer["uid"]),
2483 DBA::escape($ret["network"]),
2484 DBA::escape($ret["addr"]),
2485 DateTimeFormat::utcNow(),
2486 DBA::escape($ret["url"]),
2487 DBA::escape(Strings::normaliseLink($ret["url"])),
2488 DBA::escape($batch),
2489 DBA::escape($ret["name"]),
2490 DBA::escape($ret["nick"]),
2491 DBA::escape($ret["photo"]),
2492 DBA::escape($ret["pubkey"]),
2493 DBA::escape($ret["notify"]),
2494 DBA::escape($ret["poll"]),
2499 // find the contact record we just created
2501 $contact_record = self::contactByHandle($importer["uid"], $author);
2503 if (!$contact_record) {
2504 Logger::log("unable to locate newly created contact record.");
2508 Logger::log("Author ".$author." was added as contact number ".$contact_record["id"].".", Logger::DEBUG);
2510 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2512 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2514 if (in_array($importer["page-flags"], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])) {
2515 Logger::log("Sending intra message for author ".$author.".", Logger::DEBUG);
2517 $hash = Strings::getRandomHex().(string)time(); // Generate a confirm_key
2520 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2521 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2522 intval($importer["uid"]),
2523 intval($contact_record["id"]),
2526 DBA::escape(L10n::t("Sharing notification from Diaspora network")),
2528 DBA::escape(DateTimeFormat::utcNow())
2531 // automatic friend approval
2533 Logger::log("Does an automatic friend approval for author ".$author.".", Logger::DEBUG);
2535 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2538 * technically they are sharing with us (Contact::SHARING),
2539 * but if our page-type is Profile::PAGE_COMMUNITY or Profile::PAGE_SOAPBOX
2540 * we are going to change the relationship and make them a follower.
2542 if (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing && $following) {
2543 $new_relation = Contact::FRIEND;
2544 } elseif (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing) {
2545 $new_relation = Contact::SHARING;
2547 $new_relation = Contact::FOLLOWER;
2551 "UPDATE `contact` SET `rel` = %d,
2559 intval($new_relation),
2560 DBA::escape(DateTimeFormat::utcNow()),
2561 DBA::escape(DateTimeFormat::utcNow()),
2562 intval($contact_record["id"])
2565 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2566 if (DBA::isResult($user)) {
2567 Logger::log("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2568 self::sendShare($user, $contact_record);
2570 // Send the profile data, maybe it weren't transmitted before
2571 self::sendProfile($importer["uid"], [$contact_record]);
2579 * @brief Fetches a message with a given guid
2581 * @param string $guid message guid
2582 * @param string $orig_author handle of the original post
2583 * @return array The fetched item
2584 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2585 * @throws \ImagickException
2587 public static function originalItem($guid, $orig_author)
2590 Logger::log('Empty guid. Quitting.');
2594 // Do we already have this item?
2595 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2596 'author-name', 'author-link', 'author-avatar'];
2597 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2598 $item = Item::selectFirst($fields, $condition);
2600 if (DBA::isResult($item)) {
2601 Logger::log("reshared message ".$guid." already exists on system.");
2603 // Maybe it is already a reshared item?
2604 // Then refetch the content, if it is a reshare from a reshare.
2605 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2606 if (self::isReshare($item["body"], true)) {
2608 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2609 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2611 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2613 // Add OEmbed and other information to the body
2614 $item["body"] = add_page_info_to_body($item["body"], false, true);
2622 if (!DBA::isResult($item)) {
2623 if (empty($orig_author)) {
2624 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2628 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2629 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2630 $stored = self::storeByGuid($guid, $server);
2633 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2634 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2635 $stored = self::storeByGuid($guid, $server);
2639 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2640 'author-name', 'author-link', 'author-avatar'];
2641 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2642 $item = Item::selectFirst($fields, $condition);
2644 if (DBA::isResult($item)) {
2645 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2646 if (self::isReshare($item["body"], false)) {
2647 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2648 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2659 * @brief Stores a reshare activity
2661 * @param array $item Array of reshare post
2662 * @param integer $parent_message_id Id of the parent post
2663 * @param string $guid GUID string of reshare action
2664 * @param string $author Author handle
2666 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2668 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2672 $datarray['uid'] = $item['uid'];
2673 $datarray['contact-id'] = $item['contact-id'];
2674 $datarray['network'] = $item['network'];
2676 $datarray['author-link'] = $item['author-link'];
2677 $datarray['author-id'] = $item['author-id'];
2679 $datarray['owner-link'] = $datarray['author-link'];
2680 $datarray['owner-id'] = $datarray['author-id'];
2682 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2683 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2684 $datarray['parent-uri'] = $parent['uri'];
2686 $datarray['verb'] = $datarray['body'] = ACTIVITY2_ANNOUNCE;
2687 $datarray['gravity'] = GRAVITY_ACTIVITY;
2688 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
2690 $datarray['protocol'] = $item['protocol'];
2692 $datarray['plink'] = self::plink($author, $datarray['guid']);
2693 $datarray['private'] = $item['private'];
2694 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2696 $message_id = Item::insert($datarray);
2699 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2700 if ($datarray['uid'] == 0) {
2701 Item::distribute($message_id);
2707 * @brief Processes a reshare message
2709 * @param array $importer Array of the importer user
2710 * @param object $data The message object
2711 * @param string $xml The original XML of the message
2713 * @return int the message id
2714 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2715 * @throws \ImagickException
2717 private static function receiveReshare(array $importer, $data, $xml)
2719 $author = Strings::escapeTags(XML::unescape($data->author));
2720 $guid = Strings::escapeTags(XML::unescape($data->guid));
2721 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2722 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2723 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2724 /// @todo handle unprocessed property "provider_display_name"
2725 $public = Strings::escapeTags(XML::unescape($data->public));
2727 $contact = self::allowedContactByHandle($importer, $author, false);
2732 $message_id = self::messageExists($importer["uid"], $guid);
2737 $original_item = self::originalItem($root_guid, $root_author);
2738 if (!$original_item) {
2742 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2746 $datarray["uid"] = $importer["uid"];
2747 $datarray["contact-id"] = $contact["id"];
2748 $datarray["network"] = Protocol::DIASPORA;
2750 $datarray["author-link"] = $contact["url"];
2751 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2753 $datarray["owner-link"] = $datarray["author-link"];
2754 $datarray["owner-id"] = $datarray["author-id"];
2756 $datarray["guid"] = $guid;
2757 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2759 $datarray["verb"] = ACTIVITY_POST;
2760 $datarray["gravity"] = GRAVITY_PARENT;
2762 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2763 $datarray["source"] = $xml;
2765 $prefix = share_header(
2766 $original_item["author-name"],
2767 $original_item["author-link"],
2768 $original_item["author-avatar"],
2769 $original_item["guid"],
2770 $original_item["created"],
2773 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2775 $datarray["tag"] = $original_item["tag"];
2776 $datarray["app"] = $original_item["app"];
2778 $datarray["plink"] = self::plink($author, $guid);
2779 $datarray["private"] = (($public == "false") ? 1 : 0);
2780 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2782 $datarray["object-type"] = $original_item["object-type"];
2784 self::fetchGuid($datarray);
2785 $message_id = Item::insert($datarray);
2787 self::sendParticipation($contact, $datarray);
2789 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2790 if ($root_message_id) {
2791 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2795 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2796 if ($datarray['uid'] == 0) {
2797 Item::distribute($message_id);
2806 * @brief Processes retractions
2808 * @param array $importer Array of the importer user
2809 * @param array $contact The contact of the item owner
2810 * @param object $data The message object
2812 * @return bool success
2813 * @throws \Exception
2815 private static function itemRetraction(array $importer, array $contact, $data)
2817 $author = Strings::escapeTags(XML::unescape($data->author));
2818 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2819 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2821 $person = self::personByHandle($author);
2822 if (!is_array($person)) {
2823 Logger::log("unable to find author detail for ".$author);
2827 if (empty($contact["url"])) {
2828 $contact["url"] = $person["url"];
2831 // Fetch items that are about to be deleted
2832 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2834 // When we receive a public retraction, we delete every item that we find.
2835 if ($importer['uid'] == 0) {
2836 $condition = ['guid' => $target_guid, 'deleted' => false];
2838 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2841 $r = Item::select($fields, $condition);
2842 if (!DBA::isResult($r)) {
2843 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2847 while ($item = Item::fetch($r)) {
2848 if (strstr($item['file'], '[')) {
2849 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2853 // Fetch the parent item
2854 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2856 // Only delete it if the parent author really fits
2857 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2858 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2862 Item::delete(['id' => $item['id']]);
2864 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], Logger::DEBUG);
2871 * @brief Receives retraction messages
2873 * @param array $importer Array of the importer user
2874 * @param string $sender The sender of the message
2875 * @param object $data The message object
2877 * @return bool Success
2878 * @throws \Exception
2880 private static function receiveRetraction(array $importer, $sender, $data)
2882 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2884 $contact = self::contactByHandle($importer["uid"], $sender);
2885 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2886 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2894 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2896 switch ($target_type) {
2901 case "StatusMessage":
2902 return self::itemRetraction($importer, $contact, $data);
2904 case "PollParticipation":
2906 // Currently unsupported
2910 Logger::log("Unknown target type ".$target_type);
2917 * @brief Receives status messages
2919 * @param array $importer Array of the importer user
2920 * @param SimpleXMLElement $data The message object
2921 * @param string $xml The original XML of the message
2923 * @return int The message id of the newly created item
2924 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2925 * @throws \ImagickException
2927 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2929 $author = Strings::escapeTags(XML::unescape($data->author));
2930 $guid = Strings::escapeTags(XML::unescape($data->guid));
2931 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2932 $public = Strings::escapeTags(XML::unescape($data->public));
2933 $text = XML::unescape($data->text);
2934 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2936 $contact = self::allowedContactByHandle($importer, $author, false);
2941 $message_id = self::messageExists($importer["uid"], $guid);
2947 if ($data->location) {
2948 foreach ($data->location->children() as $fieldname => $data) {
2949 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2953 $body = Markdown::toBBCode($text);
2957 // Attach embedded pictures to the body
2959 foreach ($data->photo as $photo) {
2960 $body = "[img]".XML::unescape($photo->remote_photo_path).
2961 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2964 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2966 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2968 // Add OEmbed and other information to the body
2969 if (!self::isRedmatrix($contact["url"])) {
2970 $body = add_page_info_to_body($body, false, true);
2974 /// @todo enable support for polls
2975 //if ($data->poll) {
2976 // foreach ($data->poll AS $poll)
2981 /// @todo enable support for events
2983 $datarray["uid"] = $importer["uid"];
2984 $datarray["contact-id"] = $contact["id"];
2985 $datarray["network"] = Protocol::DIASPORA;
2987 $datarray["author-link"] = $contact["url"];
2988 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2990 $datarray["owner-link"] = $datarray["author-link"];
2991 $datarray["owner-id"] = $datarray["author-id"];
2993 $datarray["guid"] = $guid;
2994 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2996 $datarray["verb"] = ACTIVITY_POST;
2997 $datarray["gravity"] = GRAVITY_PARENT;
2999 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
3000 $datarray["source"] = $xml;
3002 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3004 if ($provider_display_name != "") {
3005 $datarray["app"] = $provider_display_name;
3008 $datarray["plink"] = self::plink($author, $guid);
3009 $datarray["private"] = (($public == "false") ? 1 : 0);
3010 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3012 if (isset($address["address"])) {
3013 $datarray["location"] = $address["address"];
3016 if (isset($address["lat"]) && isset($address["lng"])) {
3017 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3020 self::fetchGuid($datarray);
3021 $message_id = Item::insert($datarray);
3023 self::sendParticipation($contact, $datarray);
3026 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
3027 if ($datarray['uid'] == 0) {
3028 Item::distribute($message_id);
3036 /* ************************************************************************************** *
3037 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3038 * ************************************************************************************** */
3041 * @brief returnes the handle of a contact
3043 * @param array $contact contact array
3045 * @return string the handle in the format user@domain.tld
3046 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3048 private static function myHandle(array $contact)
3050 if (!empty($contact["addr"])) {
3051 return $contact["addr"];
3054 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3055 // So - just in case - we build the the address here.
3056 if ($contact["nickname"] != "") {
3057 $nick = $contact["nickname"];
3059 $nick = $contact["nick"];
3062 return $nick . "@" . substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
3067 * @brief Creates the data for a private message in the new format
3069 * @param string $msg The message that is to be transmitted
3070 * @param array $user The record of the sender
3071 * @param array $contact Target of the communication
3072 * @param string $prvkey The private key of the sender
3073 * @param string $pubkey The public key of the receiver
3075 * @return string The encrypted data
3076 * @throws \Exception
3078 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
3080 Logger::log("Message: ".$msg, Logger::DATA);
3082 // without a public key nothing will work
3084 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3088 $aes_key = openssl_random_pseudo_bytes(32);
3089 $b_aes_key = base64_encode($aes_key);
3090 $iv = openssl_random_pseudo_bytes(16);
3091 $b_iv = base64_encode($iv);
3093 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3095 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3097 $encrypted_key_bundle = "";
3098 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3100 $json_object = json_encode(
3101 ["aes_key" => base64_encode($encrypted_key_bundle),
3102 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3105 return $json_object;
3109 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3111 * @param string $msg The message that is to be transmitted
3112 * @param array $user The record of the sender
3114 * @return string The envelope
3115 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3117 public static function buildMagicEnvelope($msg, array $user)
3119 $b64url_data = Strings::base64UrlEncode($msg);
3120 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3122 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3123 $type = "application/xml";
3124 $encoding = "base64url";
3125 $alg = "RSA-SHA256";
3126 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3128 // Fallback if the private key wasn't transmitted in the expected field
3129 if ($user['uprvkey'] == "") {
3130 $user['uprvkey'] = $user['prvkey'];
3133 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3134 $sig = Strings::base64UrlEncode($signature);
3136 $xmldata = ["me:env" => ["me:data" => $data,
3137 "@attributes" => ["type" => $type],
3138 "me:encoding" => $encoding,
3141 "@attributes2" => ["key_id" => $key_id]]];
3143 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3145 return XML::fromArray($xmldata, $xml, false, $namespaces);
3149 * @brief Create the envelope for a message
3151 * @param string $msg The message that is to be transmitted
3152 * @param array $user The record of the sender
3153 * @param array $contact Target of the communication
3154 * @param string $prvkey The private key of the sender
3155 * @param string $pubkey The public key of the receiver
3156 * @param bool $public Is the message public?
3158 * @return string The message that will be transmitted to other servers
3159 * @throws \Exception
3161 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3163 // The message is put into an envelope with the sender's signature
3164 $envelope = self::buildMagicEnvelope($msg, $user);
3166 // Private messages are put into a second envelope, encrypted with the receivers public key
3168 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3175 * @brief Creates a signature for a message
3177 * @param array $owner the array of the owner of the message
3178 * @param array $message The message that is to be signed
3180 * @return string The signature
3182 private static function signature($owner, $message)
3185 unset($sigmsg["author_signature"]);
3186 unset($sigmsg["parent_author_signature"]);
3188 $signed_text = implode(";", $sigmsg);
3190 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3194 * @brief Transmit a message to a target server
3196 * @param array $owner the array of the item owner
3197 * @param array $contact Target of the communication
3198 * @param string $envelope The message that is to be transmitted
3199 * @param bool $public_batch Is it a public post?
3200 * @param string $guid message guid
3202 * @return int Result of the transmission
3203 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3204 * @throws \ImagickException
3206 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3208 $enabled = intval(Config::get("system", "diaspora_enabled"));
3213 $logid = Strings::getRandomHex(4);
3215 // We always try to use the data from the fcontact table.
3216 // This is important for transmitting data to Friendica servers.
3217 if (!empty($contact['addr'])) {
3218 $fcontact = self::personByHandle($contact['addr']);
3219 if (!empty($fcontact)) {
3220 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3224 if (empty($dest_url)) {
3225 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3229 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3233 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3235 if (!intval(Config::get("system", "diaspora_test"))) {
3236 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3238 $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3239 $return_code = $postResult->getReturnCode();
3241 Logger::log("test_mode");
3245 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3247 return $return_code ? $return_code : -1;
3252 * @brief Build the post xml
3254 * @param string $type The message type
3255 * @param array $message The message data
3257 * @return string The post XML
3259 public static function buildPostXml($type, $message)
3261 $data = [$type => $message];
3263 return XML::fromArray($data, $xml);
3267 * @brief Builds and transmit messages
3269 * @param array $owner the array of the item owner
3270 * @param array $contact Target of the communication
3271 * @param string $type The message type
3272 * @param array $message The message data
3273 * @param bool $public_batch Is it a public post?
3274 * @param string $guid message guid
3276 * @return int Result of the transmission
3277 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3278 * @throws \ImagickException
3280 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3282 $msg = self::buildPostXml($type, $message);
3284 Logger::log('message: '.$msg, Logger::DATA);
3285 Logger::log('send guid '.$guid, Logger::DEBUG);
3287 // Fallback if the private key wasn't transmitted in the expected field
3288 if (empty($owner['uprvkey'])) {
3289 $owner['uprvkey'] = $owner['prvkey'];
3292 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3294 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3296 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3298 return $return_code;
3302 * @brief sends a participation (Used to get all further updates)
3304 * @param array $contact Target of the communication
3305 * @param array $item Item array
3307 * @return int The result of the transmission
3308 * @throws \Exception
3310 private static function sendParticipation(array $contact, array $item)
3312 // Don't send notifications for private postings
3313 if ($item['private']) {
3317 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3319 $result = Cache::get($cachekey);
3320 if (!is_null($result)) {
3324 // Fetch some user id to have a valid handle to transmit the participation.
3325 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3326 // If the item belongs to a user, we take this user id.
3327 if ($item['uid'] == 0) {
3328 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3329 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3330 $owner = User::getOwnerDataById($first_user['uid']);
3332 $owner = User::getOwnerDataById($item['uid']);
3335 $author = self::myHandle($owner);
3337 $message = ["author" => $author,
3338 "guid" => System::createUUID(),
3339 "parent_type" => "Post",
3340 "parent_guid" => $item["guid"]];
3342 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3344 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3345 Cache::set($cachekey, $item["guid"], Cache::QUARTER_HOUR);
3347 return self::buildAndTransmit($owner, $contact, "participation", $message);
3351 * @brief sends an account migration
3353 * @param array $owner the array of the item owner
3354 * @param array $contact Target of the communication
3355 * @param int $uid User ID
3357 * @return int The result of the transmission
3358 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3359 * @throws \ImagickException
3361 public static function sendAccountMigration(array $owner, array $contact, $uid)
3363 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3364 $profile = self::createProfileData($uid);
3366 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3367 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3369 $message = ["author" => $old_handle,
3370 "profile" => $profile,
3371 "signature" => $signature];
3373 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3375 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3379 * @brief Sends a "share" message
3381 * @param array $owner the array of the item owner
3382 * @param array $contact Target of the communication
3384 * @return int The result of the transmission
3385 * @throws \Exception
3387 public static function sendShare(array $owner, array $contact)
3390 * @todo support the different possible combinations of "following" and "sharing"
3391 * Currently, Diaspora only interprets the "sharing" field
3393 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3397 switch ($contact["rel"]) {
3398 case Contact::FRIEND:
3402 case Contact::SHARING:
3406 case Contact::FOLLOWER:
3412 $message = ["author" => self::myHandle($owner),
3413 "recipient" => $contact["addr"],
3414 "following" => "true",
3415 "sharing" => "true"];
3417 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3419 return self::buildAndTransmit($owner, $contact, "contact", $message);
3423 * @brief sends an "unshare"
3425 * @param array $owner the array of the item owner
3426 * @param array $contact Target of the communication
3428 * @return int The result of the transmission
3429 * @throws \Exception
3431 public static function sendUnshare(array $owner, array $contact)
3433 $message = ["author" => self::myHandle($owner),
3434 "recipient" => $contact["addr"],
3435 "following" => "false",
3436 "sharing" => "false"];
3438 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3440 return self::buildAndTransmit($owner, $contact, "contact", $message);
3444 * @brief Checks a message body if it is a reshare
3446 * @param string $body The message body that is to be check
3447 * @param bool $complete Should it be a complete check or a simple check?
3449 * @return array|bool Reshare details or "false" if no reshare
3450 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3451 * @throws \ImagickException
3453 public static function isReshare($body, $complete = true)
3455 $body = trim($body);
3457 // Skip if it isn't a pure repeated messages
3458 // Does it start with a share?
3459 if ((strpos($body, "[share") > 0) && $complete) {
3463 // Does it end with a share?
3464 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3468 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3469 // Skip if there is no shared message in there
3470 if ($body == $attributes) {
3474 // If we don't do the complete check we quit here
3477 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3478 if (!empty($matches[1])) {
3479 $guid = $matches[1];
3482 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3483 if (!empty($matches[1])) {
3484 $guid = $matches[1];
3487 if (($guid != "") && $complete) {
3488 $condition = ['guid' => $guid, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3489 $item = Item::selectFirst(['contact-id'], $condition);
3490 if (DBA::isResult($item)) {
3492 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3493 $ret["root_guid"] = $guid;
3495 } elseif ($complete) {
3496 // We are resharing something that isn't a DFRN or Diaspora post.
3497 // So we have to return "false" on "$complete" to not trigger a reshare.
3500 } elseif (($guid == "") && $complete) {
3504 $ret["root_guid"] = $guid;
3507 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3508 if (!empty($matches[1])) {
3509 $profile = $matches[1];
3512 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3513 if (!empty($matches[1])) {
3514 $profile = $matches[1];
3519 if ($profile != "") {
3520 if (Contact::getIdForURL($profile)) {
3521 $author = Contact::getDetailsByURL($profile);
3522 $ret["root_handle"] = $author['addr'];
3526 if (empty($ret) && !$complete) {
3534 * @brief Create an event array
3536 * @param integer $event_id The id of the event
3538 * @return array with event data
3539 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3541 private static function buildEvent($event_id)
3543 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3544 if (!DBA::isResult($r)) {
3552 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3553 if (!DBA::isResult($r)) {
3559 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3560 if (!DBA::isResult($r)) {
3566 $eventdata['author'] = self::myHandle($owner);
3568 if ($event['guid']) {
3569 $eventdata['guid'] = $event['guid'];
3572 $mask = DateTimeFormat::ATOM;
3574 /// @todo - establish "all day" events in Friendica
3575 $eventdata["all_day"] = "false";
3577 $eventdata['timezone'] = 'UTC';
3578 if (!$event['adjust'] && $user['timezone']) {
3579 $eventdata['timezone'] = $user['timezone'];
3582 if ($event['start']) {
3583 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3585 if ($event['finish'] && !$event['nofinish']) {
3586 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3588 if ($event['summary']) {
3589 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3591 if ($event['desc']) {
3592 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3594 if ($event['location']) {
3595 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3596 $coord = Map::getCoordinates($event['location']);
3599 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3600 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3601 $location["lat"] = $coord['lat'];
3602 $location["lng"] = $coord['lon'];
3604 $location["lat"] = 0;
3605 $location["lng"] = 0;
3607 $eventdata['location'] = $location;
3614 * @brief Create a post (status message or reshare)
3616 * @param array $item The item that will be exported
3617 * @param array $owner the array of the item owner
3620 * 'type' -> Message type ("status_message" or "reshare")
3621 * 'message' -> Array of XML elements of the status
3622 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3623 * @throws \ImagickException
3625 public static function buildStatus(array $item, array $owner)
3627 $cachekey = "diaspora:buildStatus:".$item['guid'];
3629 $result = Cache::get($cachekey);
3630 if (!is_null($result)) {
3634 $myaddr = self::myHandle($owner);
3636 $public = ($item["private"] ? "false" : "true");
3638 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3639 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3641 // Detect a share element and do a reshare
3642 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3643 $message = ["author" => $myaddr,
3644 "guid" => $item["guid"],
3645 "created_at" => $created,
3646 "root_author" => $ret["root_handle"],
3647 "root_guid" => $ret["root_guid"],
3648 "provider_display_name" => $item["app"],
3649 "public" => $public];
3653 $title = $item["title"];
3654 $body = $item["body"];
3656 if ($item['author-link'] != $item['owner-link']) {
3657 require_once 'mod/share.php';
3658 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3659 "", $item['created'], $item['plink']) . $body . '[/share]';
3662 // convert to markdown
3663 $body = html_entity_decode(BBCode::toMarkdown($body));
3666 if (strlen($title)) {
3667 $body = "## ".html_entity_decode($title)."\n\n".$body;
3670 if ($item["attach"]) {
3671 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3673 $body .= "\n".L10n::t("Attachments:")."\n";
3674 foreach ($matches as $mtch) {
3675 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3682 if ($item["location"] != "")
3683 $location["address"] = $item["location"];
3685 if ($item["coord"] != "") {
3686 $coord = explode(" ", $item["coord"]);
3687 $location["lat"] = $coord[0];
3688 $location["lng"] = $coord[1];
3691 $message = ["author" => $myaddr,
3692 "guid" => $item["guid"],
3693 "created_at" => $created,
3694 "edited_at" => $edited,
3695 "public" => $public,
3697 "provider_display_name" => $item["app"],
3698 "location" => $location];
3700 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3701 if (!isset($location["lat"]) || !isset($location["lng"])) {
3702 unset($message["location"]);
3705 if ($item['event-id'] > 0) {
3706 $event = self::buildEvent($item['event-id']);
3707 if (count($event)) {
3708 $message['event'] = $event;
3710 if (!empty($event['location']['address']) &&
3711 !empty($event['location']['lat']) &&
3712 !empty($event['location']['lng'])) {
3713 $message['location'] = $event['location'];
3716 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3717 // $message['text'] = '';
3721 $type = "status_message";
3724 $msg = ["type" => $type, "message" => $message];
3726 Cache::set($cachekey, $msg, Cache::QUARTER_HOUR);
3731 private static function prependParentAuthorMention($body, $profile_url)
3733 $profile = Contact::getDetailsByURL($profile_url);
3734 if (!empty($profile['addr'])
3735 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3736 && !strstr($body, $profile['addr'])
3737 && !strstr($body, $profile_url)
3739 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3746 * @brief Sends a post
3748 * @param array $item The item that will be exported
3749 * @param array $owner the array of the item owner
3750 * @param array $contact Target of the communication
3751 * @param bool $public_batch Is it a public post?
3753 * @return int The result of the transmission
3754 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3755 * @throws \ImagickException
3757 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3759 $status = self::buildStatus($item, $owner);
3761 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3765 * @brief Creates a "like" object
3767 * @param array $item The item that will be exported
3768 * @param array $owner the array of the item owner
3770 * @return array The data for a "like"
3771 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3773 private static function constructLike(array $item, array $owner)
3775 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3776 if (!DBA::isResult($parent)) {
3780 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3782 if ($item['verb'] === ACTIVITY_LIKE) {
3784 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3785 $positive = "false";
3788 return(["author" => self::myHandle($owner),
3789 "guid" => $item["guid"],
3790 "parent_guid" => $parent["guid"],
3791 "parent_type" => $target_type,
3792 "positive" => $positive,
3793 "author_signature" => ""]);
3797 * @brief Creates an "EventParticipation" object
3799 * @param array $item The item that will be exported
3800 * @param array $owner the array of the item owner
3802 * @return array The data for an "EventParticipation"
3803 * @throws \Exception
3805 private static function constructAttend(array $item, array $owner)
3807 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3808 if (!DBA::isResult($parent)) {
3812 switch ($item['verb']) {
3813 case ACTIVITY_ATTEND:
3814 $attend_answer = 'accepted';
3816 case ACTIVITY_ATTENDNO:
3817 $attend_answer = 'declined';
3819 case ACTIVITY_ATTENDMAYBE:
3820 $attend_answer = 'tentative';
3823 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3827 return(["author" => self::myHandle($owner),
3828 "guid" => $item["guid"],
3829 "parent_guid" => $parent["guid"],
3830 "status" => $attend_answer,
3831 "author_signature" => ""]);
3835 * @brief Creates the object for a comment
3837 * @param array $item The item that will be exported
3838 * @param array $owner the array of the item owner
3840 * @return array|false The data for a comment
3841 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3843 private static function constructComment(array $item, array $owner)
3845 $cachekey = "diaspora:constructComment:".$item['guid'];
3847 $result = Cache::get($cachekey);
3848 if (!is_null($result)) {
3852 $toplevel_item = Item::selectFirst(['guid', 'author-link'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3853 if (!DBA::isResult($toplevel_item)) {
3854 Logger::error('Missing parent conversation item', ['parent' => $item["parent"]]);
3858 $thread_parent_item = $toplevel_item;
3859 if ($item['thr-parent'] != $item['parent-uri']) {
3860 $thread_parent_item = Item::selectFirst(['guid', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3863 $body = $item["body"];
3865 if ((empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3866 && !Config::get('system', 'disable_implicit_mentions')
3868 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3871 $text = html_entity_decode(BBCode::toMarkdown($body));
3872 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3873 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3876 "author" => self::myHandle($owner),
3877 "guid" => $item["guid"],
3878 "created_at" => $created,
3879 "edited_at" => $edited,
3880 "parent_guid" => $toplevel_item["guid"],
3882 "author_signature" => ""
3885 // Send the thread parent guid only if it is a threaded comment
3886 if ($item['thr-parent'] != $item['parent-uri']) {
3887 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3890 Cache::set($cachekey, $comment, Cache::QUARTER_HOUR);
3896 * @brief Send a like or a comment
3898 * @param array $item The item that will be exported
3899 * @param array $owner the array of the item owner
3900 * @param array $contact Target of the communication
3901 * @param bool $public_batch Is it a public post?
3903 * @return int The result of the transmission
3904 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3905 * @throws \ImagickException
3907 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3909 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3910 $message = self::constructAttend($item, $owner);
3911 $type = "event_participation";
3912 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3913 $message = self::constructLike($item, $owner);
3915 } elseif (!in_array($item["verb"], [ACTIVITY_FOLLOW, ACTIVITY_TAG])) {
3916 $message = self::constructComment($item, $owner);
3920 if (empty($message)) {
3924 $message["author_signature"] = self::signature($owner, $message);
3926 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3930 * @brief Creates a message from a signature record entry
3932 * @param array $item The item that will be exported
3933 * @return array The message
3935 private static function messageFromSignature(array $item)
3937 // Split the signed text
3938 $signed_parts = explode(";", $item['signed_text']);
3940 if ($item["deleted"]) {
3941 $message = ["author" => $item['signer'],
3942 "target_guid" => $signed_parts[0],
3943 "target_type" => $signed_parts[1]];
3944 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3945 $message = ["author" => $signed_parts[4],
3946 "guid" => $signed_parts[1],
3947 "parent_guid" => $signed_parts[3],
3948 "parent_type" => $signed_parts[2],
3949 "positive" => $signed_parts[0],
3950 "author_signature" => $item['signature'],
3951 "parent_author_signature" => ""];
3953 // Remove the comment guid
3954 $guid = array_shift($signed_parts);
3956 // Remove the parent guid
3957 $parent_guid = array_shift($signed_parts);
3959 // Remove the handle
3960 $handle = array_pop($signed_parts);
3963 "author" => $handle,
3965 "parent_guid" => $parent_guid,
3966 "text" => implode(";", $signed_parts),
3967 "author_signature" => $item['signature'],
3968 "parent_author_signature" => ""
3975 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3977 * @param array $item The item that will be exported
3978 * @param array $owner the array of the item owner
3979 * @param array $contact Target of the communication
3980 * @param bool $public_batch Is it a public post?
3982 * @return int The result of the transmission
3983 * @throws \Exception
3985 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3987 if ($item["deleted"]) {
3988 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3989 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3995 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3997 // Old way - is used by the internal Friendica functions
3998 /// @todo Change all signatur storing functions to the new format
3999 if ($item['signed_text'] && $item['signature'] && $item['signer']) {
4000 $message = self::messageFromSignature($item);
4002 $msg = json_decode($item['signed_text'], true);
4005 if (is_array($msg)) {
4006 foreach ($msg as $field => $data) {
4007 if (!$item["deleted"]) {
4008 if ($field == "diaspora_handle") {
4011 if ($field == "target_type") {
4012 $field = "parent_type";
4016 $message[$field] = $data;
4019 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
4023 $message["parent_author_signature"] = self::signature($owner, $message);
4025 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
4027 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4031 * @brief Sends a retraction (deletion) of a message, like or comment
4033 * @param array $item The item that will be exported
4034 * @param array $owner the array of the item owner
4035 * @param array $contact Target of the communication
4036 * @param bool $public_batch Is it a public post?
4037 * @param bool $relay Is the retraction transmitted from a relay?
4039 * @return int The result of the transmission
4040 * @throws \Exception
4042 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
4044 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4046 $msg_type = "retraction";
4048 if ($item['id'] == $item['parent']) {
4049 $target_type = "Post";
4050 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4051 $target_type = "Like";
4053 $target_type = "Comment";
4056 $message = ["author" => $itemaddr,
4057 "target_guid" => $item['guid'],
4058 "target_type" => $target_type];
4060 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
4062 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4066 * @brief Sends a mail
4068 * @param array $item The item that will be exported
4069 * @param array $owner The owner
4070 * @param array $contact Target of the communication
4072 * @return int The result of the transmission
4073 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4074 * @throws \ImagickException
4076 public static function sendMail(array $item, array $owner, array $contact)
4078 $myaddr = self::myHandle($owner);
4080 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
4081 if (!DBA::isResult($cnv)) {
4082 Logger::log("conversation not found.");
4086 $body = BBCode::toMarkdown($item["body"]);
4087 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4090 "author" => $myaddr,
4091 "guid" => $item["guid"],
4092 "conversation_guid" => $cnv["guid"],
4094 "created_at" => $created,
4097 if ($item["reply"]) {
4102 "author" => $cnv["creator"],
4103 "guid" => $cnv["guid"],
4104 "subject" => $cnv["subject"],
4105 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4106 "participants" => $cnv["recips"],
4110 $type = "conversation";
4113 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4117 * @brief Split a name into first name and last name
4119 * @param string $name The name
4121 * @return array The array with "first" and "last"
4123 public static function splitName($name) {
4124 $name = trim($name);
4126 // Is the name longer than 64 characters? Then cut the rest of it.
4127 if (strlen($name) > 64) {
4128 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4129 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4131 $name = substr($name, 0, 64);
4135 // Take the first word as first name
4136 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4137 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4138 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4139 return ['first' => $first, 'last' => $last];
4142 // Take the last word as last name
4143 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4144 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4146 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4147 return ['first' => $first, 'last' => $last];
4150 // Take the first 32 characters if there is no space in the first 32 characters
4151 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4152 $first = substr($name, 0, 32);
4153 $last = substr($name, 32);
4154 return ['first' => $first, 'last' => $last];
4157 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4158 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4160 // Check if the last name is longer than 32 characters
4161 if (strlen($last) > 32) {
4162 if (strpos($last, ' ') <= 32) {
4163 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4165 $last = substr($last, 0, 32);
4169 return ['first' => $first, 'last' => $last];
4173 * @brief Create profile data
4175 * @param int $uid The user id
4177 * @return array The profile data
4178 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4180 private static function createProfileData($uid)
4183 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4185 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4186 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4187 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4196 $handle = $profile["addr"];
4198 $split_name = self::splitName($profile['name']);
4199 $first = $split_name['first'];
4200 $last = $split_name['last'];
4202 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4203 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4204 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4205 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4211 if ($searchable === 'true') {
4214 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4215 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4219 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4222 $about = $profile['about'];
4223 $about = strip_tags(BBCode::convert($about));
4225 $location = Profile::formatLocation($profile);
4227 if ($profile['pub_keywords']) {
4228 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4229 $kw = str_replace(' ', ' ', $kw);
4230 $arr = explode(' ', $kw);
4232 for ($x = 0; $x < 5; $x ++) {
4233 if (!empty($arr[$x])) {
4234 $tags .= '#'. trim($arr[$x]) .' ';
4239 $tags = trim($tags);
4242 return ["author" => $handle,
4243 "first_name" => $first,
4244 "last_name" => $last,
4245 "image_url" => $large,
4246 "image_url_medium" => $medium,
4247 "image_url_small" => $small,
4249 "gender" => $profile['gender'],
4251 "location" => $location,
4252 "searchable" => $searchable,
4254 "tag_string" => $tags];
4258 * @brief Sends profile data
4260 * @param int $uid The user id
4261 * @param bool $recips optional, default false
4263 * @throws \Exception
4265 public static function sendProfile($uid, $recips = false)
4271 $owner = User::getOwnerDataById($uid);
4278 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4279 AND `uid` = %d AND `rel` != %d",
4280 DBA::escape(Protocol::DIASPORA),
4282 intval(Contact::SHARING)
4290 $message = self::createProfileData($uid);
4292 // @ToDo Split this into single worker jobs
4293 foreach ($recips as $recip) {
4294 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4295 self::buildAndTransmit($owner, $recip, "profile", $message);
4300 * @brief Creates the signature for likes that are created on our system
4302 * @param integer $uid The user of that comment
4303 * @param array $item Item array
4305 * @return array Signed content
4306 * @throws \Exception
4308 public static function createLikeSignature($uid, array $item)
4310 $owner = User::getOwnerDataById($uid);
4311 if (empty($owner)) {
4312 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4316 if (!in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4320 $message = self::constructLike($item, $owner);
4321 if ($message === false) {
4325 $message["author_signature"] = self::signature($owner, $message);
4331 * @brief Creates the signature for Comments that are created on our system
4333 * @param integer $uid The user of that comment
4334 * @param array $item Item array
4336 * @return array Signed content
4337 * @throws \Exception
4339 public static function createCommentSignature($uid, array $item)
4341 $owner = User::getOwnerDataById($uid);
4342 if (empty($owner)) {
4343 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4347 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4348 $item['thr-parent'] = $item['parent-uri'];
4350 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4351 if (!DBA::isResult($parent)) {
4355 $item['parent-uri'] = $parent['parent-uri'];
4357 $message = self::constructComment($item, $owner);
4358 if ($message === false) {
4362 $message["author_signature"] = self::signature($owner, $message);