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\Protocol\ActivityNamespace;
36 use Friendica\Util\Crypto;
37 use Friendica\Util\DateTimeFormat;
38 use Friendica\Util\Map;
39 use Friendica\Util\Network;
40 use Friendica\Util\Strings;
41 use Friendica\Util\XML;
42 use Friendica\Worker\Delivery;
46 * @brief This class contain functions to create and send Diaspora XML files
52 * Mark the relay contact of the given contact for archival
53 * This is called whenever there is a communication issue with the server.
54 * It avoids sending stuff to servers who don't exist anymore.
55 * The relay contact is a technical contact entry that exists once per server.
57 * @param array $contact of the relay contact
59 public static function markRelayForArchival(array $contact)
61 if (!empty($contact['contact-type']) && ($contact['contact-type'] == Contact::TYPE_RELAY)) {
62 // This is already the relay contact, we don't need to fetch it
63 $relay_contact = $contact;
64 } elseif (empty($contact['baseurl'])) {
65 if (!empty($contact['batch'])) {
66 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => Contact::TYPE_RELAY];
67 $relay_contact = DBA::selectFirst('contact', [], $condition);
72 $relay_contact = self::getRelayContact($contact['baseurl'], []);
75 if (!empty($relay_contact)) {
76 Logger::info('Relay contact will be marked for archival', ['id' => $relay_contact['id'], 'url' => $relay_contact['url']]);
77 Contact::markForArchival($relay_contact);
82 * @brief Return a list of relay servers
84 * The list contains not only the official relays but also servers that we serve directly
86 * @param integer $item_id The id of the item that is sent
87 * @param array $contacts The previously fetched contacts
89 * @return array of relay servers
90 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
92 public static function relayList($item_id, array $contacts = [])
96 // Fetching relay servers
97 $serverdata = Config::get("system", "relay_server");
99 if (!empty($serverdata)) {
100 $servers = explode(",", $serverdata);
101 foreach ($servers as $server) {
102 $serverlist[$server] = trim($server);
106 if (Config::get("system", "relay_directly", false)) {
107 // We distribute our stuff based on the parent to ensure that the thread will be complete
108 $parent = Item::selectFirst(['parent'], ['id' => $item_id]);
109 if (!DBA::isResult($parent)) {
113 // Servers that want to get all content
114 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
115 while ($server = DBA::fetch($servers)) {
116 $serverlist[$server['url']] = $server['url'];
119 // All tags of the current post
120 $condition = ['otype' => TERM_OBJ_POST, 'type' => TERM_HASHTAG, 'oid' => $parent['parent']];
121 $tags = DBA::select('term', ['term'], $condition);
123 while ($tag = DBA::fetch($tags)) {
124 $taglist[] = $tag['term'];
127 // All servers who wants content with this tag
129 if (!empty($taglist)) {
130 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
131 while ($server = DBA::fetch($tagserver)) {
132 $tagserverlist[] = $server['gserver-id'];
136 // All adresses with the given id
137 if (!empty($tagserverlist)) {
138 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
139 while ($server = DBA::fetch($servers)) {
140 $serverlist[$server['url']] = $server['url'];
145 // Now we are collecting all relay contacts
146 foreach ($serverlist as $server_url) {
147 // We don't send messages to ourselves
148 if (Strings::compareLink($server_url, System::baseUrl())) {
151 $contact = self::getRelayContact($server_url);
152 if (is_bool($contact)) {
157 foreach ($contacts as $entry) {
158 if ($entry['batch'] == $contact['batch']) {
164 $contacts[] = $contact;
172 * @brief Return a contact for a given server address or creates a dummy entry
174 * @param string $server_url The url of the server
175 * @param array $fields Fieldlist
176 * @return array with the contact
179 private static function getRelayContact(string $server_url, array $fields = ['batch', 'id', 'url', 'name', 'network', 'protocol', 'archive', 'blocked'])
181 // Fetch the relay contact
182 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
183 'contact-type' => Contact::TYPE_RELAY];
184 $contact = DBA::selectFirst('contact', $fields, $condition);
186 if (DBA::isResult($contact)) {
187 if ($contact['archive'] || $contact['blocked']) {
192 self::setRelayContact($server_url);
194 $contact = DBA::selectFirst('contact', $fields, $condition);
195 if (DBA::isResult($contact)) {
200 // It should never happen that we arrive here
205 * @brief Update or insert a relay contact
207 * @param string $server_url The url of the server
208 * @param array $network_fields Optional network specific fields
211 public static function setRelayContact($server_url, array $network_fields = [])
213 $fields = ['created' => DateTimeFormat::utcNow(),
214 'name' => 'relay', 'nick' => 'relay', 'url' => $server_url,
215 'nurl' => Strings::normaliseLink($server_url),
216 'network' => Protocol::DIASPORA, 'uid' => 0,
217 'batch' => $server_url . '/receive/public',
218 'rel' => Contact::FOLLOWER, 'blocked' => false,
219 'pending' => false, 'writable' => true,
220 'baseurl' => $server_url, 'contact-type' => Contact::TYPE_RELAY];
222 $fields = array_merge($fields, $network_fields);
224 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url)];
225 $old = DBA::selectFirst('contact', [], $condition);
226 if (DBA::isResult($old)) {
227 unset($fields['created']);
228 $condition = ['id' => $old['id']];
230 Logger::info('Update relay contact', ['fields' => $fields, 'condition' => $condition]);
231 DBA::update('contact', $fields, $condition, $old);
233 Logger::info('Create relay contact', ['fields' => $fields]);
234 Contact::insert($fields);
239 * @brief Return a list of participating contacts for a thread
241 * This is used for the participation feature.
242 * One of the parameters is a contact array.
243 * This is done to avoid duplicates.
245 * @param integer $thread The id of the thread
246 * @param array $contacts The previously fetched contacts
248 * @return array of relay servers
251 public static function participantsForThread($thread, array $contacts)
253 $r = DBA::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`url`, `contact`.`name`, `contact`.`network`, `contact`.`protocol`,
254 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
255 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
256 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
257 WHERE `participation`.`iid` = ? AND NOT `contact`.`archive`", $thread);
259 while ($contact = DBA::fetch($r)) {
260 if (!empty($contact['fnetwork'])) {
261 $contact['network'] = $contact['fnetwork'];
263 unset($contact['fnetwork']);
265 if (empty($contact['protocol'])) {
266 $contact['protocol'] = $contact['network'];
269 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
270 $contact['batch'] = $contact['fbatch'];
272 unset($contact['fbatch']);
275 foreach ($contacts as $entry) {
276 if ($entry['batch'] == $contact['batch']) {
282 $contacts[] = $contact;
291 * @brief repairs a signature that was double encoded
293 * The function is unused at the moment. It was copied from the old implementation.
295 * @param string $signature The signature
296 * @param string $handle The handle of the signature owner
297 * @param integer $level This value is only set inside this function to avoid endless loops
299 * @return string the repaired signature
302 private static function repairSignature($signature, $handle = "", $level = 1)
304 if ($signature == "") {
308 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
309 $signature = base64_decode($signature);
310 Logger::log("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, Logger::DEBUG);
312 // Do a recursive call to be able to fix even multiple levels
314 $signature = self::repairSignature($signature, $handle, ++$level);
322 * @brief verify the envelope and return the verified data
324 * @param string $envelope The magic envelope
326 * @return string verified data
327 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
328 * @throws \ImagickException
330 private static function verifyMagicEnvelope($envelope)
332 $basedom = XML::parseString($envelope);
334 if (!is_object($basedom)) {
335 Logger::log("Envelope is no XML file");
339 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
341 if (sizeof($children) == 0) {
342 Logger::log("XML has no children");
348 $data = Strings::base64UrlDecode($children->data);
349 $type = $children->data->attributes()->type[0];
351 $encoding = $children->encoding;
353 $alg = $children->alg;
355 $sig = Strings::base64UrlDecode($children->sig);
356 $key_id = $children->sig->attributes()->key_id[0];
358 $handle = Strings::base64UrlDecode($key_id);
361 $b64url_data = Strings::base64UrlEncode($data);
362 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
364 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
367 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
371 $key = self::key($handle);
373 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
377 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
379 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
387 * @brief encrypts data via AES
389 * @param string $key The AES key
390 * @param string $iv The IV (is used for CBC encoding)
391 * @param string $data The data that is to be encrypted
393 * @return string encrypted data
395 private static function aesEncrypt($key, $iv, $data)
397 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
401 * @brief decrypts data via AES
403 * @param string $key The AES key
404 * @param string $iv The IV (is used for CBC encoding)
405 * @param string $encrypted The encrypted data
407 * @return string decrypted data
409 private static function aesDecrypt($key, $iv, $encrypted)
411 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
415 * @brief: Decodes incoming Diaspora message in the new format
417 * @param string $raw raw post message
418 * @param string $privKey The private key of the importer
419 * @param boolean $no_exit Don't do an http exit on error
422 * 'message' -> decoded Diaspora XML message
423 * 'author' -> author diaspora handle
424 * 'key' -> author public key (converted to pkcs#8)
425 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
426 * @throws \ImagickException
428 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
430 $data = json_decode($raw);
432 // Is it a private post? Then decrypt the outer Salmon
433 if (is_object($data)) {
434 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
435 $ciphertext = base64_decode($data->encrypted_magic_envelope);
437 $outer_key_bundle = '';
438 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
439 $j_outer_key_bundle = json_decode($outer_key_bundle);
441 if (!is_object($j_outer_key_bundle)) {
442 Logger::log('Outer Salmon did not verify. Discarding.');
446 throw new \Friendica\Network\HTTPException\BadRequestException();
450 $outer_iv = base64_decode($j_outer_key_bundle->iv);
451 $outer_key = base64_decode($j_outer_key_bundle->key);
453 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
458 $basedom = XML::parseString($xml);
460 if (!is_object($basedom)) {
461 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
465 throw new \Friendica\Network\HTTPException\BadRequestException();
469 $base = $basedom->children(ActivityNamespace::SALMON_ME);
471 // Not sure if this cleaning is needed
472 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
474 // Build the signed data
475 $type = $base->data[0]->attributes()->type[0];
476 $encoding = $base->encoding;
478 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
480 // This is the signature
481 $signature = Strings::base64UrlDecode($base->sig);
483 // Get the senders' public key
484 $key_id = $base->sig[0]->attributes()->key_id[0];
485 $author_addr = base64_decode($key_id);
486 if ($author_addr == '') {
487 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
491 throw new \Friendica\Network\HTTPException\BadRequestException();
495 $key = self::key($author_addr);
497 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
501 throw new \Friendica\Network\HTTPException\BadRequestException();
505 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
507 Logger::log('Message did not verify. Discarding.');
511 throw new \Friendica\Network\HTTPException\BadRequestException();
515 return ['message' => (string)Strings::base64UrlDecode($base->data),
516 'author' => XML::unescape($author_addr),
517 'key' => (string)$key];
521 * @brief: Decodes incoming Diaspora message in the deprecated format
523 * @param string $xml urldecoded Diaspora salmon
524 * @param string $privKey The private key of the importer
527 * 'message' -> decoded Diaspora XML message
528 * 'author' -> author diaspora handle
529 * 'key' -> author public key (converted to pkcs#8)
530 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
531 * @throws \ImagickException
533 public static function decode(string $xml, string $privKey = '')
536 $basedom = XML::parseString($xml);
538 if (!is_object($basedom)) {
539 Logger::log("XML is not parseable.");
542 $children = $basedom->children('https://joindiaspora.com/protocol');
544 $inner_aes_key = null;
547 if ($children->header) {
549 $author_link = str_replace('acct:', '', $children->header->author_id);
551 // This happens with posts from a relais
552 if (empty($privKey)) {
553 Logger::log("This is no private post in the old format", Logger::DEBUG);
557 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
559 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
560 $ciphertext = base64_decode($encrypted_header->ciphertext);
562 $outer_key_bundle = '';
563 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
565 $j_outer_key_bundle = json_decode($outer_key_bundle);
567 $outer_iv = base64_decode($j_outer_key_bundle->iv);
568 $outer_key = base64_decode($j_outer_key_bundle->key);
570 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
572 Logger::log('decrypted: '.$decrypted, Logger::DEBUG);
573 $idom = XML::parseString($decrypted);
575 $inner_iv = base64_decode($idom->iv);
576 $inner_aes_key = base64_decode($idom->aes_key);
578 $author_link = str_replace('acct:', '', $idom->author_id);
581 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
583 // figure out where in the DOM tree our data is hiding
586 if ($dom->provenance->data) {
587 $base = $dom->provenance;
588 } elseif ($dom->env->data) {
590 } elseif ($dom->data) {
595 Logger::log('unable to locate salmon data in xml');
596 throw new \Friendica\Network\HTTPException\BadRequestException();
600 // Stash the signature away for now. We have to find their key or it won't be good for anything.
601 $signature = Strings::base64UrlDecode($base->sig);
605 // strip whitespace so our data element will return to one big base64 blob
606 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
609 // stash away some other stuff for later
611 $type = $base->data[0]->attributes()->type[0];
612 $keyhash = $base->sig[0]->attributes()->keyhash[0];
613 $encoding = $base->encoding;
617 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
621 $data = Strings::base64UrlDecode($data);
625 $inner_decrypted = $data;
627 // Decode the encrypted blob
628 $inner_encrypted = base64_decode($data);
629 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
633 Logger::log('Could not retrieve author URI.');
634 throw new \Friendica\Network\HTTPException\BadRequestException();
636 // Once we have the author URI, go to the web and try to find their public key
637 // (first this will look it up locally if it is in the fcontact cache)
638 // This will also convert diaspora public key from pkcs#1 to pkcs#8
640 Logger::log('Fetching key for '.$author_link);
641 $key = self::key($author_link);
644 Logger::log('Could not retrieve author key.');
645 throw new \Friendica\Network\HTTPException\BadRequestException();
648 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
651 Logger::log('Message did not verify. Discarding.');
652 throw new \Friendica\Network\HTTPException\BadRequestException();
655 Logger::log('Message verified.');
657 return ['message' => (string)$inner_decrypted,
658 'author' => XML::unescape($author_link),
659 'key' => (string)$key];
664 * @brief Dispatches public messages and find the fitting receivers
666 * @param array $msg The post that will be dispatched
668 * @return int The message id of the generated message, "true" or "false" if there was an error
669 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
670 * @throws \ImagickException
672 public static function dispatchPublic($msg)
674 $enabled = intval(Config::get("system", "diaspora_enabled"));
676 Logger::log("diaspora is disabled");
680 if (!($fields = self::validPosting($msg))) {
681 Logger::log("Invalid posting");
685 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
686 $success = self::dispatch($importer, $msg, $fields);
692 * @brief Dispatches the different message types to the different functions
694 * @param array $importer Array of the importer user
695 * @param array $msg The post that will be dispatched
696 * @param SimpleXMLElement $fields SimpleXML object that contains the message
698 * @return int The message id of the generated message, "true" or "false" if there was an error
699 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
700 * @throws \ImagickException
702 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
704 // The sender is the handle of the contact that sent the message.
705 // This will often be different with relayed messages (for example "like" and "comment")
706 $sender = $msg["author"];
708 // This is only needed for private postings since this is already done for public ones before
709 if (is_null($fields)) {
711 if (!($fields = self::validPosting($msg))) {
712 Logger::log("Invalid posting");
719 $type = $fields->getName();
721 Logger::log("Received message type ".$type." from ".$sender." for user ".$importer["uid"], Logger::DEBUG);
724 case "account_migration":
726 Logger::log('Message with type ' . $type . ' is not private, quitting.');
729 return self::receiveAccountMigration($importer, $fields);
731 case "account_deletion":
732 return self::receiveAccountDeletion($fields);
735 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
739 Logger::log('Message with type ' . $type . ' is not private, quitting.');
742 return self::receiveContactRequest($importer, $fields);
746 Logger::log('Message with type ' . $type . ' is not private, quitting.');
749 return self::receiveConversation($importer, $msg, $fields);
752 return self::receiveLike($importer, $sender, $fields);
756 Logger::log('Message with type ' . $type . ' is not private, quitting.');
759 return self::receiveMessage($importer, $fields);
761 case "participation":
763 Logger::log('Message with type ' . $type . ' is not private, quitting.');
766 return self::receiveParticipation($importer, $fields);
768 case "photo": // Not implemented
769 return self::receivePhoto($importer, $fields);
771 case "poll_participation": // Not implemented
772 return self::receivePollParticipation($importer, $fields);
776 Logger::log('Message with type ' . $type . ' is not private, quitting.');
779 return self::receiveProfile($importer, $fields);
782 return self::receiveReshare($importer, $fields, $msg["message"]);
785 return self::receiveRetraction($importer, $sender, $fields);
787 case "status_message":
788 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
791 Logger::log("Unknown message type ".$type);
797 * @brief Checks if a posting is valid and fetches the data fields.
799 * This function does not only check the signature.
800 * It also does the conversion between the old and the new diaspora format.
802 * @param array $msg Array with the XML, the sender handle and the sender signature
804 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
805 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
806 * @throws \ImagickException
808 private static function validPosting($msg)
810 $data = XML::parseString($msg["message"]);
812 if (!is_object($data)) {
813 Logger::log("No valid XML ".$msg["message"], Logger::DEBUG);
817 // Is this the new or the old version?
818 if ($data->getName() == "XML") {
820 foreach ($data->post->children() as $child) {
828 $type = $element->getName();
831 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
833 // All retractions are handled identically from now on.
834 // In the new version there will only be "retraction".
835 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
836 $type = "retraction";
838 if ($type == "request") {
842 $fields = new SimpleXMLElement("<".$type."/>");
845 $author_signature = null;
846 $parent_author_signature = null;
848 foreach ($element->children() as $fieldname => $entry) {
850 // Translation for the old XML structure
851 if ($fieldname == "diaspora_handle") {
852 $fieldname = "author";
854 if ($fieldname == "participant_handles") {
855 $fieldname = "participants";
857 if (in_array($type, ["like", "participation"])) {
858 if ($fieldname == "target_type") {
859 $fieldname = "parent_type";
862 if ($fieldname == "sender_handle") {
863 $fieldname = "author";
865 if ($fieldname == "recipient_handle") {
866 $fieldname = "recipient";
868 if ($fieldname == "root_diaspora_id") {
869 $fieldname = "root_author";
871 if ($type == "status_message") {
872 if ($fieldname == "raw_message") {
876 if ($type == "retraction") {
877 if ($fieldname == "post_guid") {
878 $fieldname = "target_guid";
880 if ($fieldname == "type") {
881 $fieldname = "target_type";
886 if (($fieldname == "author_signature") && ($entry != "")) {
887 $author_signature = base64_decode($entry);
888 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
889 $parent_author_signature = base64_decode($entry);
890 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
891 if ($signed_data != "") {
895 $signed_data .= $entry;
897 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
898 || ($orig_type == "relayable_retraction")
900 XML::copy($entry, $fields, $fieldname);
904 // This is something that shouldn't happen at all.
905 if (in_array($type, ["status_message", "reshare", "profile"])) {
906 if ($msg["author"] != $fields->author) {
907 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
912 // Only some message types have signatures. So we quit here for the other types.
913 if (!in_array($type, ["comment", "like"])) {
916 // No author_signature? This is a must, so we quit.
917 if (!isset($author_signature)) {
918 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
922 if (isset($parent_author_signature)) {
923 $key = self::key($msg["author"]);
925 Logger::log("No key found for parent author ".$msg["author"], Logger::DEBUG);
929 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
930 Logger::log("No valid parent author signature for parent author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$parent_author_signature, Logger::DEBUG);
935 $key = self::key($fields->author);
937 Logger::log("No key found for author ".$fields->author, Logger::DEBUG);
941 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
942 Logger::log("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, Logger::DEBUG);
950 * @brief Fetches the public key for a given handle
952 * @param string $handle The handle
954 * @return string The public key
955 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
956 * @throws \ImagickException
958 private static function key($handle)
960 $handle = strval($handle);
962 Logger::log("Fetching diaspora key for: ".$handle);
964 $r = self::personByHandle($handle);
973 * @brief Fetches data for a given handle
975 * @param string $handle The handle
976 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
978 * @return array the queried data
979 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
980 * @throws \ImagickException
982 public static function personByHandle($handle, $update = null)
984 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
985 if (!DBA::isResult($person)) {
986 $urls = [$handle, str_replace('http://', 'https://', $handle), Strings::normaliseLink($handle)];
987 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'url' => $urls]);
990 if (DBA::isResult($person)) {
991 Logger::debug("In cache " . print_r($person, true));
993 if (is_null($update)) {
994 // update record occasionally so it doesn't get stale
995 $d = strtotime($person["updated"]." +00:00");
996 if ($d < strtotime("now - 14 days")) {
1000 if ($person["guid"] == "") {
1004 } elseif (is_null($update)) {
1005 $update = !DBA::isResult($person);
1011 Logger::log("create or refresh", Logger::DEBUG);
1012 $r = Probe::uri($handle, Protocol::DIASPORA);
1014 // Note that Friendica contacts will return a "Diaspora person"
1015 // if Diaspora connectivity is enabled on their server
1016 if ($r && ($r["network"] === Protocol::DIASPORA)) {
1017 self::updateFContact($r);
1019 $person = self::personByHandle($handle, false);
1027 * @brief Updates the fcontact table
1029 * @param array $arr The fcontact data
1030 * @throws \Exception
1032 private static function updateFContact($arr)
1034 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
1035 'request' => $arr["request"], 'nick' => $arr["nick"],
1036 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
1037 'batch' => $arr["batch"], 'notify' => $arr["notify"],
1038 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
1039 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
1040 'updated' => DateTimeFormat::utcNow()];
1042 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
1044 DBA::update('fcontact', $fields, $condition, true);
1048 * @brief get a handle (user@domain.tld) from a given contact id
1050 * @param int $contact_id The id in the contact table
1051 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1053 * @return string the handle
1054 * @throws \Exception
1056 private static function handleFromContact($contact_id, $pcontact_id = 0)
1060 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
1062 if ($pcontact_id != 0) {
1063 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
1065 if (DBA::isResult($contact) && !empty($contact["addr"])) {
1066 return strtolower($contact["addr"]);
1071 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1075 if (DBA::isResult($r)) {
1078 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1080 if ($contact['addr'] != "") {
1081 $handle = $contact['addr'];
1083 $baseurl_start = strpos($contact['url'], '://') + 3;
1084 // allows installations in a subdirectory--not sure how Diaspora will handle
1085 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1086 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1087 $handle = $contact['nick'].'@'.$baseurl;
1091 return strtolower($handle);
1095 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
1098 * @param mixed $fcontact_guid Hexadecimal string guid
1100 * @return string the contact url or null
1101 * @throws \Exception
1103 public static function urlFromContactGuid($fcontact_guid)
1105 Logger::log("fcontact guid is ".$fcontact_guid, Logger::DEBUG);
1108 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1109 DBA::escape(Protocol::DIASPORA),
1110 DBA::escape($fcontact_guid)
1113 if (DBA::isResult($r)) {
1114 return $r[0]['url'];
1121 * @brief Get a contact id for a given handle
1123 * @todo Move to Friendica\Model\Contact
1125 * @param int $uid The user id
1126 * @param string $handle The handle in the format user@domain.tld
1128 * @return array Contact data
1129 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1130 * @throws \ImagickException
1132 private static function contactByHandle($uid, $handle)
1134 $cid = Contact::getIdForURL($handle, $uid);
1136 $handle_parts = explode("@", $handle);
1137 $nurl_sql = "%%://" . $handle_parts[1] . "%%/profile/" . $handle_parts[0];
1138 $cid = Contact::getIdForURL($nurl_sql, $uid);
1142 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1146 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1147 if (!DBA::isResult($contact)) {
1148 // This here shouldn't happen at all
1149 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1157 * Checks if the given contact url does support ActivityPub
1159 * @param string $url profile url
1160 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1162 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1163 * @throws \ImagickException
1165 public static function isSupportedByContactUrl($url, $update = null)
1167 return !empty(self::personByHandle($url, $update));
1171 * @brief Check if posting is allowed for this contact
1173 * @param array $importer Array of the importer user
1174 * @param array $contact The contact that is checked
1175 * @param bool $is_comment Is the check for a comment?
1177 * @return bool is the contact allowed to post?
1179 private static function postAllow(array $importer, array $contact, $is_comment = false)
1182 * Perhaps we were already sharing with this person. Now they're sharing with us.
1183 * That makes us friends.
1184 * Normally this should have handled by getting a request - but this could get lost
1186 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1187 // It is not removed by now. Possibly the code is needed?
1188 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1191 // array('rel' => Contact::FRIEND, 'writable' => true),
1192 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1195 // $contact["rel"] = Contact::FRIEND;
1196 // Logger::log("defining user ".$contact["nick"]." as friend");
1199 // Contact server is blocked
1200 if (Network::isUrlBlocked($contact['url'])) {
1202 // We don't seem to like that person
1203 } elseif ($contact["blocked"]) {
1204 // Maybe blocked, don't accept.
1206 // We are following this person?
1207 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1208 // Yes, then it is fine.
1210 // Is it a post to a community?
1211 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1214 // Is the message a global user or a comment?
1215 } elseif (($importer["uid"] == 0) || $is_comment) {
1216 // Messages for the global users and comments are always accepted
1224 * @brief Fetches the contact id for a handle and checks if posting is allowed
1226 * @param array $importer Array of the importer user
1227 * @param string $handle The checked handle in the format user@domain.tld
1228 * @param bool $is_comment Is the check for a comment?
1230 * @return array The contact data
1231 * @throws \Exception
1233 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1235 $contact = self::contactByHandle($importer["uid"], $handle);
1237 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1238 // If a contact isn't found, we accept it anyway if it is a comment
1239 if ($is_comment && ($importer["uid"] != 0)) {
1240 return self::contactByHandle(0, $handle);
1241 } elseif ($is_comment) {
1248 if (!self::postAllow($importer, $contact, $is_comment)) {
1249 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1256 * @brief Does the message already exists on the system?
1258 * @param int $uid The user id
1259 * @param string $guid The guid of the message
1261 * @return int|bool message id if the message already was stored into the system - or false.
1262 * @throws \Exception
1264 private static function messageExists($uid, $guid)
1266 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1267 if (DBA::isResult($item)) {
1268 Logger::log("message ".$guid." already exists for user ".$uid);
1276 * @brief Checks for links to posts in a message
1278 * @param array $item The item array
1281 private static function fetchGuid(array $item)
1283 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1284 preg_replace_callback(
1286 function ($match) use ($item) {
1287 self::fetchGuidSub($match, $item);
1292 preg_replace_callback(
1293 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1294 function ($match) use ($item) {
1295 self::fetchGuidSub($match, $item);
1302 * @brief Checks for relative /people/* links in an item body to match local
1303 * contacts or prepends the remote host taken from the author link.
1305 * @param string $body The item body to replace links from
1306 * @param string $author_link The author link for missing local contact fallback
1308 * @return string the replaced string
1310 public static function replacePeopleGuid($body, $author_link)
1312 $return = preg_replace_callback(
1313 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1314 function ($match) use ($author_link) {
1316 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1317 // 1 => '0123456789abcdef'
1319 $handle = self::urlFromContactGuid($match[1]);
1322 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1324 // No local match, restoring absolute remote URL from author scheme and host
1325 $author_url = parse_url($author_link);
1326 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1338 * @brief sub function of "fetchGuid" which checks for links in messages
1340 * @param array $match array containing a link that has to be checked for a message link
1341 * @param array $item The item array
1343 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1344 * @throws \ImagickException
1346 private static function fetchGuidSub($match, $item)
1348 if (!self::storeByGuid($match[1], $item["author-link"])) {
1349 self::storeByGuid($match[1], $item["owner-link"]);
1354 * @brief Fetches an item with a given guid from a given server
1356 * @param string $guid the message guid
1357 * @param string $server The server address
1358 * @param int $uid The user id of the user
1360 * @return int the message id of the stored message or false
1361 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1362 * @throws \ImagickException
1364 private static function storeByGuid($guid, $server, $uid = 0)
1366 $serverparts = parse_url($server);
1368 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1372 $server = $serverparts["scheme"]."://".$serverparts["host"];
1374 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1376 $msg = self::message($guid, $server);
1382 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1384 // Now call the dispatcher
1385 return self::dispatchPublic($msg);
1389 * @brief Fetches a message from a server
1391 * @param string $guid message guid
1392 * @param string $server The url of the server
1393 * @param int $level Endless loop prevention
1396 * 'message' => The message XML
1397 * 'author' => The author handle
1398 * 'key' => The public key of the author
1399 * @throws \Exception
1401 private static function message($guid, $server, $level = 0)
1407 // This will work for new Diaspora servers and Friendica servers from 3.5
1408 $source_url = $server."/fetch/post/".urlencode($guid);
1410 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1412 $envelope = Network::fetchUrl($source_url);
1414 Logger::log("Envelope was fetched.", Logger::DEBUG);
1415 $x = self::verifyMagicEnvelope($envelope);
1417 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1419 Logger::log("Envelope was verified.", Logger::DEBUG);
1429 $source_xml = XML::parseString($x);
1431 if (!is_object($source_xml)) {
1435 if ($source_xml->post->reshare) {
1436 // Reshare of a reshare - old Diaspora version
1437 Logger::log("Message is a reshare", Logger::DEBUG);
1438 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1439 } elseif ($source_xml->getName() == "reshare") {
1440 // Reshare of a reshare - new Diaspora version
1441 Logger::log("Message is a new reshare", Logger::DEBUG);
1442 return self::message($source_xml->root_guid, $server, ++$level);
1447 // Fetch the author - for the old and the new Diaspora version
1448 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1449 $author = (string)$source_xml->post->status_message->diaspora_handle;
1450 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1451 $author = (string)$source_xml->author;
1454 // If this isn't a "status_message" then quit
1456 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1460 $msg = ["message" => $x, "author" => $author];
1462 $msg["key"] = self::key($msg["author"]);
1468 * @brief Fetches an item with a given URL
1470 * @param string $url the message url
1472 * @return int the message id of the stored message or false
1473 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1474 * @throws \ImagickException
1476 public static function fetchByURL($url, $uid = 0)
1478 // Check for Diaspora (and Friendica) typical paths
1479 if (!preg_match("=(https?://.+)/(?:posts|display)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1483 $guid = urldecode($matches[2]);
1485 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1486 if (DBA::isResult($item)) {
1490 self::storeByGuid($guid, $matches[1], $uid);
1492 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1493 if (DBA::isResult($item)) {
1501 * @brief Fetches the item record of a given guid
1503 * @param int $uid The user id
1504 * @param string $guid message guid
1505 * @param string $author The handle of the item
1506 * @param array $contact The contact of the item owner
1508 * @return array the item record
1509 * @throws \Exception
1511 private static function parentItem($uid, $guid, $author, array $contact)
1513 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1514 'author-name', 'author-link', 'author-avatar',
1515 'owner-name', 'owner-link', 'owner-avatar'];
1516 $condition = ['uid' => $uid, 'guid' => $guid];
1517 $item = Item::selectFirst($fields, $condition);
1519 if (!DBA::isResult($item)) {
1520 $person = self::personByHandle($author);
1521 $result = self::storeByGuid($guid, $person["url"], $uid);
1523 // We don't have an url for items that arrived at the public dispatcher
1524 if (!$result && !empty($contact["url"])) {
1525 $result = self::storeByGuid($guid, $contact["url"], $uid);
1529 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1531 $item = Item::selectFirst($fields, $condition);
1535 if (!DBA::isResult($item)) {
1536 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1539 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1545 * @brief returns contact details
1547 * @param array $def_contact The default contact if the person isn't found
1548 * @param array $person The record of the person
1549 * @param int $uid The user id
1552 * 'cid' => contact id
1553 * 'network' => network type
1554 * @throws \Exception
1556 private static function authorContactByUrl($def_contact, $person, $uid)
1558 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1559 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1560 if (DBA::isResult($contact)) {
1561 $cid = $contact["id"];
1562 $network = $contact["network"];
1564 $cid = $def_contact["id"];
1565 $network = Protocol::DIASPORA;
1568 return ["cid" => $cid, "network" => $network];
1572 * @brief Is the profile a hubzilla profile?
1574 * @param string $url The profile link
1576 * @return bool is it a hubzilla server?
1578 public static function isRedmatrix($url)
1580 return(strstr($url, "/channel/"));
1584 * @brief Generate a post link with a given handle and message guid
1586 * @param string $addr The user handle
1587 * @param string $guid message guid
1588 * @param string $parent_guid optional parent guid
1590 * @return string the post link
1591 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1592 * @throws \ImagickException
1594 private static function plink($addr, $guid, $parent_guid = '')
1596 $contact = Contact::getDetailsByAddr($addr);
1600 if ($parent_guid != '') {
1601 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1603 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1607 if ($contact["network"] == Protocol::DFRN) {
1608 return str_replace("/profile/" . $contact["nick"] . "/", "/display/" . $guid, $contact["url"] . "/");
1611 if (self::isRedmatrix($contact["url"])) {
1612 return $contact["url"] . "/?mid=" . $guid;
1615 if ($parent_guid != '') {
1616 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1618 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1623 * @brief Receives account migration
1625 * @param array $importer Array of the importer user
1626 * @param object $data The message object
1628 * @return bool Success
1629 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1630 * @throws \ImagickException
1632 private static function receiveAccountMigration(array $importer, $data)
1634 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1635 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1636 $signature = Strings::escapeTags(XML::unescape($data->signature));
1638 $contact = self::contactByHandle($importer["uid"], $old_handle);
1640 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1644 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1647 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1648 $key = self::key($old_handle);
1649 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1650 Logger::log('No valid signature for migration.');
1654 // Update the profile
1655 self::receiveProfile($importer, $data->profile);
1657 // change the technical stuff in contact and gcontact
1658 $data = Probe::uri($new_handle);
1659 if ($data['network'] == Protocol::PHANTOM) {
1660 Logger::log('Account for '.$new_handle." couldn't be probed.");
1664 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1665 'name' => $data['name'], 'nick' => $data['nick'],
1666 'addr' => $data['addr'], 'batch' => $data['batch'],
1667 'notify' => $data['notify'], 'poll' => $data['poll'],
1668 'network' => $data['network']];
1670 DBA::update('contact', $fields, ['addr' => $old_handle]);
1672 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1673 'name' => $data['name'], 'nick' => $data['nick'],
1674 'addr' => $data['addr'], 'connect' => $data['addr'],
1675 'notify' => $data['notify'], 'photo' => $data['photo'],
1676 'server_url' => $data['baseurl'], 'network' => $data['network']];
1678 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1680 Logger::log('Contacts are updated.');
1686 * @brief Processes an account deletion
1688 * @param object $data The message object
1690 * @return bool Success
1691 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1693 private static function receiveAccountDeletion($data)
1695 $author = Strings::escapeTags(XML::unescape($data->author));
1697 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1698 while ($contact = DBA::fetch($contacts)) {
1699 Contact::remove($contact["id"]);
1702 DBA::delete('gcontact', ['addr' => $author]);
1704 Logger::log('Removed contacts for ' . $author);
1710 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1712 * @param string $author Author handle
1713 * @param string $guid Message guid
1714 * @param boolean $onlyfound Only return uri when found in the database
1716 * @return string The constructed uri or the one from our database
1717 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1718 * @throws \ImagickException
1720 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1722 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1723 if (DBA::isResult($item)) {
1724 return $item["uri"];
1725 } elseif (!$onlyfound) {
1726 $person = self::personByHandle($author);
1728 $parts = parse_url($person['url']);
1729 unset($parts['path']);
1730 $host_url = Network::unparseURL($parts);
1732 return $host_url . '/objects/' . $guid;
1739 * @brief Fetch the guid from our database with a given uri
1741 * @param string $uri Message uri
1742 * @param string $uid Author handle
1744 * @return string The post guid
1745 * @throws \Exception
1747 private static function getGuidFromUri($uri, $uid)
1749 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1750 if (DBA::isResult($item)) {
1751 return $item["guid"];
1758 * @brief Find the best importer for a comment, like, ...
1760 * @param string $guid The guid of the item
1762 * @return array|boolean the origin owner of that post - or false
1763 * @throws \Exception
1765 private static function importerForGuid($guid)
1767 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1768 if (DBA::isResult($item)) {
1769 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1770 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1771 if (DBA::isResult($contact)) {
1779 * @brief Processes an incoming comment
1781 * @param array $importer Array of the importer user
1782 * @param string $sender The sender of the message
1783 * @param object $data The message object
1784 * @param string $xml The original XML of the message
1786 * @return int The message id of the generated comment or "false" if there was an error
1787 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1788 * @throws \ImagickException
1790 private static function receiveComment(array $importer, $sender, $data, $xml)
1792 $author = Strings::escapeTags(XML::unescape($data->author));
1793 $guid = Strings::escapeTags(XML::unescape($data->guid));
1794 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1795 $text = XML::unescape($data->text);
1797 if (isset($data->created_at)) {
1798 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1800 $created_at = DateTimeFormat::utcNow();
1803 if (isset($data->thread_parent_guid)) {
1804 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1805 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1810 $contact = self::allowedContactByHandle($importer, $sender, true);
1815 $message_id = self::messageExists($importer["uid"], $guid);
1820 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1821 if (!$parent_item) {
1825 $person = self::personByHandle($author);
1826 if (!is_array($person)) {
1827 Logger::log("unable to find author details");
1831 // Fetch the contact id - if we know this contact
1832 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1836 $datarray["uid"] = $importer["uid"];
1837 $datarray["contact-id"] = $author_contact["cid"];
1838 $datarray["network"] = $author_contact["network"];
1840 $datarray["author-link"] = $person["url"];
1841 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1843 $datarray["owner-link"] = $contact["url"];
1844 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1846 $datarray["guid"] = $guid;
1847 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1849 $datarray["verb"] = Activity::POST;
1850 $datarray["gravity"] = GRAVITY_COMMENT;
1852 if ($thr_uri != "") {
1853 $datarray["parent-uri"] = $thr_uri;
1855 $datarray["parent-uri"] = $parent_item["uri"];
1858 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1860 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1861 $datarray["source"] = $xml;
1863 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1865 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1867 $body = Markdown::toBBCode($text);
1869 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1871 self::fetchGuid($datarray);
1873 // If we are the origin of the parent we store the original data.
1874 // We notify our followers during the item storage.
1875 if ($parent_item["origin"]) {
1876 $datarray['diaspora_signed_text'] = json_encode($data);
1879 $message_id = Item::insert($datarray);
1881 if ($message_id <= 0) {
1886 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1887 if ($datarray['uid'] == 0) {
1888 Item::distribute($message_id, json_encode($data));
1896 * @brief processes and stores private messages
1898 * @param array $importer Array of the importer user
1899 * @param array $contact The contact of the message
1900 * @param object $data The message object
1901 * @param array $msg Array of the processed message, author handle and key
1902 * @param object $mesg The private message
1903 * @param array $conversation The conversation record to which this message belongs
1905 * @return bool "true" if it was successful
1906 * @throws \Exception
1908 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1910 $author = Strings::escapeTags(XML::unescape($data->author));
1911 $guid = Strings::escapeTags(XML::unescape($data->guid));
1912 $subject = Strings::escapeTags(XML::unescape($data->subject));
1914 // "diaspora_handle" is the element name from the old version
1915 // "author" is the element name from the new version
1916 if ($mesg->author) {
1917 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1918 } elseif ($mesg->diaspora_handle) {
1919 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1924 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1925 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1926 $msg_text = XML::unescape($mesg->text);
1927 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1929 if ($msg_conversation_guid != $guid) {
1930 Logger::log("message conversation guid does not belong to the current conversation.");
1934 $body = Markdown::toBBCode($msg_text);
1935 $message_uri = $msg_author.":".$msg_guid;
1937 $person = self::personByHandle($msg_author);
1939 return Mail::insert([
1940 'uid' => $importer['uid'],
1941 'guid' => $msg_guid,
1942 'convid' => $conversation['id'],
1943 'from-name' => $person['name'],
1944 'from-photo' => $person['photo'],
1945 'from-url' => $person['url'],
1946 'contact-id' => $contact['id'],
1947 'title' => $subject,
1949 'uri' => $message_uri,
1950 'parent-uri' => $author . ':' . $guid,
1951 'created' => $msg_created_at
1956 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1958 * @param array $importer Array of the importer user
1959 * @param array $msg Array of the processed message, author handle and key
1960 * @param object $data The message object
1962 * @return bool Success
1963 * @throws \Exception
1965 private static function receiveConversation(array $importer, $msg, $data)
1967 $author = Strings::escapeTags(XML::unescape($data->author));
1968 $guid = Strings::escapeTags(XML::unescape($data->guid));
1969 $subject = Strings::escapeTags(XML::unescape($data->subject));
1970 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1971 $participants = Strings::escapeTags(XML::unescape($data->participants));
1973 $messages = $data->message;
1975 if (!count($messages)) {
1976 Logger::log("empty conversation");
1980 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1985 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1986 if (!DBA::isResult($conversation)) {
1988 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1989 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1990 intval($importer["uid"]),
1992 DBA::escape($author),
1993 DBA::escape($created_at),
1994 DBA::escape(DateTimeFormat::utcNow()),
1995 DBA::escape($subject),
1996 DBA::escape($participants)
1999 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2002 if (!$conversation) {
2003 Logger::log("unable to create conversation.");
2007 foreach ($messages as $mesg) {
2008 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
2015 * @brief Processes "like" messages
2017 * @param array $importer Array of the importer user
2018 * @param string $sender The sender of the message
2019 * @param object $data The message object
2021 * @return int The message id of the generated like or "false" if there was an error
2022 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2023 * @throws \ImagickException
2025 private static function receiveLike(array $importer, $sender, $data)
2027 $author = Strings::escapeTags(XML::unescape($data->author));
2028 $guid = Strings::escapeTags(XML::unescape($data->guid));
2029 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2030 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
2031 $positive = Strings::escapeTags(XML::unescape($data->positive));
2033 // likes on comments aren't supported by Diaspora - only on posts
2034 // But maybe this will be supported in the future, so we will accept it.
2035 if (!in_array($parent_type, ["Post", "Comment"])) {
2039 $contact = self::allowedContactByHandle($importer, $sender, true);
2044 $message_id = self::messageExists($importer["uid"], $guid);
2049 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2050 if (!$parent_item) {
2054 $person = self::personByHandle($author);
2055 if (!is_array($person)) {
2056 Logger::log("unable to find author details");
2060 // Fetch the contact id - if we know this contact
2061 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2063 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2064 // We would accept this anyhow.
2065 if ($positive == "true") {
2066 $verb = Activity::LIKE;
2068 $verb = Activity::DISLIKE;
2073 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2075 $datarray["uid"] = $importer["uid"];
2076 $datarray["contact-id"] = $author_contact["cid"];
2077 $datarray["network"] = $author_contact["network"];
2079 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2080 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2082 $datarray["guid"] = $guid;
2083 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2085 $datarray["verb"] = $verb;
2086 $datarray["gravity"] = GRAVITY_ACTIVITY;
2087 $datarray["parent-uri"] = $parent_item["uri"];
2089 $datarray["object-type"] = Activity\ObjectType::NOTE;
2091 $datarray["body"] = $verb;
2093 // Diaspora doesn't provide a date for likes
2094 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2096 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2097 if ($parent_item["id"] != $parent_item["parent"]) {
2098 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
2099 $origin = $toplevel["origin"];
2101 $origin = $parent_item["origin"];
2104 // If we are the origin of the parent we store the original data.
2105 // We notify our followers during the item storage.
2107 $datarray['diaspora_signed_text'] = json_encode($data);
2110 $message_id = Item::insert($datarray);
2112 if ($message_id <= 0) {
2117 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2118 if ($datarray['uid'] == 0) {
2119 Item::distribute($message_id, json_encode($data));
2127 * @brief Processes private messages
2129 * @param array $importer Array of the importer user
2130 * @param object $data The message object
2132 * @return bool Success?
2133 * @throws \Exception
2135 private static function receiveMessage(array $importer, $data)
2137 $author = Strings::escapeTags(XML::unescape($data->author));
2138 $guid = Strings::escapeTags(XML::unescape($data->guid));
2139 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2140 $text = XML::unescape($data->text);
2141 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2143 $contact = self::allowedContactByHandle($importer, $author, true);
2148 $conversation = null;
2150 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2151 $conversation = DBA::selectFirst('conv', [], $condition);
2153 if (!DBA::isResult($conversation)) {
2154 Logger::log("conversation not available.");
2158 $message_uri = $author.":".$guid;
2160 $person = self::personByHandle($author);
2162 Logger::log("unable to find author details");
2166 $body = Markdown::toBBCode($text);
2168 $body = self::replacePeopleGuid($body, $person["url"]);
2170 return Mail::insert([
2171 'uid' => $importer['uid'],
2173 'convid' => $conversation['id'],
2174 'from-name' => $person['name'],
2175 'from-photo' => $person['photo'],
2176 'from-url' => $person['url'],
2177 'contact-id' => $contact['id'],
2178 'title' => $conversation['subject'],
2181 'uri' => $message_uri,
2182 'parent-uri' => $author.":".$conversation['guid'],
2183 'created' => $created_at
2188 * @brief Processes participations - unsupported by now
2190 * @param array $importer Array of the importer user
2191 * @param object $data The message object
2193 * @return bool always true
2194 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2195 * @throws \ImagickException
2197 private static function receiveParticipation(array $importer, $data)
2199 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2200 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2202 $contact_id = Contact::getIdForURL($author);
2204 Logger::log('Contact not found: '.$author);
2208 $person = self::personByHandle($author);
2209 if (!is_array($person)) {
2210 Logger::log("Person not found: ".$author);
2214 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2215 if (!DBA::isResult($item)) {
2216 Logger::log('Item not found, no origin or private: '.$parent_guid);
2220 $author_parts = explode('@', $author);
2221 if (isset($author_parts[1])) {
2222 $server = $author_parts[1];
2224 // Should never happen
2228 Logger::log('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, Logger::DEBUG);
2230 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2231 DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2234 // Send all existing comments and likes to the requesting server
2235 $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2236 while ($comment = Item::fetch($comments)) {
2237 if ($comment['id'] == $comment['parent']) {
2241 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $contact_id]);
2242 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $contact_id)) {
2243 ItemDeliveryData::incrementQueueCount($comment['id'], 1);
2246 DBA::close($comments);
2252 * @brief Processes photos - unneeded
2254 * @param array $importer Array of the importer user
2255 * @param object $data The message object
2257 * @return bool always true
2259 private static function receivePhoto(array $importer, $data)
2261 // There doesn't seem to be a reason for this function,
2262 // since the photo data is transmitted in the status message as well
2267 * @brief Processes poll participations - unssupported
2269 * @param array $importer Array of the importer user
2270 * @param object $data The message object
2272 * @return bool always true
2274 private static function receivePollParticipation(array $importer, $data)
2276 // We don't support polls by now
2281 * @brief Processes incoming profile updates
2283 * @param array $importer Array of the importer user
2284 * @param object $data The message object
2286 * @return bool Success
2287 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2288 * @throws \ImagickException
2290 private static function receiveProfile(array $importer, $data)
2292 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2294 $contact = self::contactByHandle($importer["uid"], $author);
2299 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2300 $image_url = XML::unescape($data->image_url);
2301 $birthday = XML::unescape($data->birthday);
2302 $gender = XML::unescape($data->gender);
2303 $about = Markdown::toBBCode(XML::unescape($data->bio));
2304 $location = Markdown::toBBCode(XML::unescape($data->location));
2305 $searchable = (XML::unescape($data->searchable) == "true");
2306 $nsfw = (XML::unescape($data->nsfw) == "true");
2307 $tags = XML::unescape($data->tag_string);
2309 $tags = explode("#", $tags);
2312 foreach ($tags as $tag) {
2313 $tag = trim(strtolower($tag));
2319 $keywords = implode(", ", $keywords);
2321 $handle_parts = explode("@", $author);
2322 $nick = $handle_parts[0];
2325 $name = $handle_parts[0];
2328 if (preg_match("|^https?://|", $image_url) === 0) {
2329 $image_url = "http://".$handle_parts[1].$image_url;
2332 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2334 // Generic birthday. We don't know the timezone. The year is irrelevant.
2336 $birthday = str_replace("1000", "1901", $birthday);
2338 if ($birthday != "") {
2339 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2342 // this is to prevent multiple birthday notifications in a single year
2343 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2345 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2346 $birthday = $contact["bd"];
2349 $fields = ['name' => $name, 'location' => $location,
2350 'name-date' => DateTimeFormat::utcNow(),
2351 'about' => $about, 'gender' => $gender,
2352 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2353 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2355 if (!empty($birthday)) {
2356 $fields['bd'] = $birthday;
2359 DBA::update('contact', $fields, ['id' => $contact['id']]);
2361 // @todo Update the public contact, then update the gcontact from that
2363 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2364 "photo" => $image_url, "name" => $name, "location" => $location,
2365 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2366 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2367 "hide" => !$searchable, "nsfw" => $nsfw];
2369 $gcid = GContact::update($gcontact);
2371 GContact::link($gcid, $importer["uid"], $contact["id"]);
2373 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2379 * @brief Processes incoming friend requests
2381 * @param array $importer Array of the importer user
2382 * @param array $contact The contact that send the request
2384 * @throws \Exception
2386 private static function receiveRequestMakeFriend(array $importer, array $contact)
2388 if ($contact["rel"] == Contact::SHARING) {
2391 ['rel' => Contact::FRIEND, 'writable' => true],
2392 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2398 * @brief Processes incoming sharing notification
2400 * @param array $importer Array of the importer user
2401 * @param object $data The message object
2403 * @return bool Success
2404 * @throws \Exception
2406 private static function receiveContactRequest(array $importer, $data)
2408 $author = XML::unescape($data->author);
2409 $recipient = XML::unescape($data->recipient);
2411 if (!$author || !$recipient) {
2415 // the current protocol version doesn't know these fields
2416 // That means that we will assume their existance
2417 if (isset($data->following)) {
2418 $following = (XML::unescape($data->following) == "true");
2423 if (isset($data->sharing)) {
2424 $sharing = (XML::unescape($data->sharing) == "true");
2429 $contact = self::contactByHandle($importer["uid"], $author);
2431 // perhaps we were already sharing with this person. Now they're sharing with us.
2432 // That makes us friends.
2435 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2436 self::receiveRequestMakeFriend($importer, $contact);
2438 // refetch the contact array
2439 $contact = self::contactByHandle($importer["uid"], $author);
2441 // If we are now friends, we are sending a share message.
2442 // Normally we needn't to do so, but the first message could have been vanished.
2443 if (in_array($contact["rel"], [Contact::FRIEND])) {
2444 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2445 if (DBA::isResult($user)) {
2446 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2447 self::sendShare($user, $contact);
2452 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2453 Contact::removeFollower($importer, $contact);
2458 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2459 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2461 } elseif (!$following && !$sharing) {
2462 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2464 } elseif (!$following && $sharing) {
2465 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2466 } elseif ($following && $sharing) {
2467 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2468 } elseif ($following && !$sharing) {
2469 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2472 $ret = self::personByHandle($author);
2474 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2475 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2479 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2482 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2483 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2484 intval($importer["uid"]),
2485 DBA::escape($ret["network"]),
2486 DBA::escape($ret["addr"]),
2487 DateTimeFormat::utcNow(),
2488 DBA::escape($ret["url"]),
2489 DBA::escape(Strings::normaliseLink($ret["url"])),
2490 DBA::escape($batch),
2491 DBA::escape($ret["name"]),
2492 DBA::escape($ret["nick"]),
2493 DBA::escape($ret["photo"]),
2494 DBA::escape($ret["pubkey"]),
2495 DBA::escape($ret["notify"]),
2496 DBA::escape($ret["poll"]),
2501 // find the contact record we just created
2503 $contact_record = self::contactByHandle($importer["uid"], $author);
2505 if (!$contact_record) {
2506 Logger::log("unable to locate newly created contact record.");
2510 Logger::log("Author ".$author." was added as contact number ".$contact_record["id"].".", Logger::DEBUG);
2512 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2514 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2516 if (in_array($importer["page-flags"], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])) {
2517 Logger::log("Sending intra message for author ".$author.".", Logger::DEBUG);
2519 $hash = Strings::getRandomHex().(string)time(); // Generate a confirm_key
2522 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2523 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2524 intval($importer["uid"]),
2525 intval($contact_record["id"]),
2528 DBA::escape(L10n::t("Sharing notification from Diaspora network")),
2530 DBA::escape(DateTimeFormat::utcNow())
2533 // automatic friend approval
2535 Logger::log("Does an automatic friend approval for author ".$author.".", Logger::DEBUG);
2537 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2540 * technically they are sharing with us (Contact::SHARING),
2541 * but if our page-type is Profile::PAGE_COMMUNITY or Profile::PAGE_SOAPBOX
2542 * we are going to change the relationship and make them a follower.
2544 if (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing && $following) {
2545 $new_relation = Contact::FRIEND;
2546 } elseif (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing) {
2547 $new_relation = Contact::SHARING;
2549 $new_relation = Contact::FOLLOWER;
2553 "UPDATE `contact` SET `rel` = %d,
2561 intval($new_relation),
2562 DBA::escape(DateTimeFormat::utcNow()),
2563 DBA::escape(DateTimeFormat::utcNow()),
2564 intval($contact_record["id"])
2567 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2568 if (DBA::isResult($user)) {
2569 Logger::log("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2570 self::sendShare($user, $contact_record);
2572 // Send the profile data, maybe it weren't transmitted before
2573 self::sendProfile($importer["uid"], [$contact_record]);
2581 * @brief Fetches a message with a given guid
2583 * @param string $guid message guid
2584 * @param string $orig_author handle of the original post
2585 * @return array The fetched item
2586 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2587 * @throws \ImagickException
2589 public static function originalItem($guid, $orig_author)
2592 Logger::log('Empty guid. Quitting.');
2596 // Do we already have this item?
2597 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2598 'author-name', 'author-link', 'author-avatar'];
2599 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2600 $item = Item::selectFirst($fields, $condition);
2602 if (DBA::isResult($item)) {
2603 Logger::log("reshared message ".$guid." already exists on system.");
2605 // Maybe it is already a reshared item?
2606 // Then refetch the content, if it is a reshare from a reshare.
2607 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2608 if (self::isReshare($item["body"], true)) {
2610 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2611 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2613 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2615 // Add OEmbed and other information to the body
2616 $item["body"] = add_page_info_to_body($item["body"], false, true);
2624 if (!DBA::isResult($item)) {
2625 if (empty($orig_author)) {
2626 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2630 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2631 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2632 $stored = self::storeByGuid($guid, $server);
2635 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2636 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2637 $stored = self::storeByGuid($guid, $server);
2641 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2642 'author-name', 'author-link', 'author-avatar'];
2643 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2644 $item = Item::selectFirst($fields, $condition);
2646 if (DBA::isResult($item)) {
2647 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2648 if (self::isReshare($item["body"], false)) {
2649 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2650 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2661 * @brief Stores a reshare activity
2663 * @param array $item Array of reshare post
2664 * @param integer $parent_message_id Id of the parent post
2665 * @param string $guid GUID string of reshare action
2666 * @param string $author Author handle
2668 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2670 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2674 $datarray['uid'] = $item['uid'];
2675 $datarray['contact-id'] = $item['contact-id'];
2676 $datarray['network'] = $item['network'];
2678 $datarray['author-link'] = $item['author-link'];
2679 $datarray['author-id'] = $item['author-id'];
2681 $datarray['owner-link'] = $datarray['author-link'];
2682 $datarray['owner-id'] = $datarray['author-id'];
2684 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2685 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2686 $datarray['parent-uri'] = $parent['uri'];
2688 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2689 $datarray['gravity'] = GRAVITY_ACTIVITY;
2690 $datarray['object-type'] = Activity\ObjectType::NOTE;
2692 $datarray['protocol'] = $item['protocol'];
2694 $datarray['plink'] = self::plink($author, $datarray['guid']);
2695 $datarray['private'] = $item['private'];
2696 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2698 $message_id = Item::insert($datarray);
2701 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2702 if ($datarray['uid'] == 0) {
2703 Item::distribute($message_id);
2709 * @brief Processes a reshare message
2711 * @param array $importer Array of the importer user
2712 * @param object $data The message object
2713 * @param string $xml The original XML of the message
2715 * @return int the message id
2716 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2717 * @throws \ImagickException
2719 private static function receiveReshare(array $importer, $data, $xml)
2721 $author = Strings::escapeTags(XML::unescape($data->author));
2722 $guid = Strings::escapeTags(XML::unescape($data->guid));
2723 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2724 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2725 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2726 /// @todo handle unprocessed property "provider_display_name"
2727 $public = Strings::escapeTags(XML::unescape($data->public));
2729 $contact = self::allowedContactByHandle($importer, $author, false);
2734 $message_id = self::messageExists($importer["uid"], $guid);
2739 $original_item = self::originalItem($root_guid, $root_author);
2740 if (!$original_item) {
2744 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2748 $datarray["uid"] = $importer["uid"];
2749 $datarray["contact-id"] = $contact["id"];
2750 $datarray["network"] = Protocol::DIASPORA;
2752 $datarray["author-link"] = $contact["url"];
2753 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2755 $datarray["owner-link"] = $datarray["author-link"];
2756 $datarray["owner-id"] = $datarray["author-id"];
2758 $datarray["guid"] = $guid;
2759 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2761 $datarray["verb"] = Activity::POST;
2762 $datarray["gravity"] = GRAVITY_PARENT;
2764 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2765 $datarray["source"] = $xml;
2767 $prefix = share_header(
2768 $original_item["author-name"],
2769 $original_item["author-link"],
2770 $original_item["author-avatar"],
2771 $original_item["guid"],
2772 $original_item["created"],
2775 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2777 $datarray["tag"] = $original_item["tag"];
2778 $datarray["app"] = $original_item["app"];
2780 $datarray["plink"] = self::plink($author, $guid);
2781 $datarray["private"] = (($public == "false") ? 1 : 0);
2782 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2784 $datarray["object-type"] = $original_item["object-type"];
2786 self::fetchGuid($datarray);
2787 $message_id = Item::insert($datarray);
2789 self::sendParticipation($contact, $datarray);
2791 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2792 if ($root_message_id) {
2793 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2797 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2798 if ($datarray['uid'] == 0) {
2799 Item::distribute($message_id);
2808 * @brief Processes retractions
2810 * @param array $importer Array of the importer user
2811 * @param array $contact The contact of the item owner
2812 * @param object $data The message object
2814 * @return bool success
2815 * @throws \Exception
2817 private static function itemRetraction(array $importer, array $contact, $data)
2819 $author = Strings::escapeTags(XML::unescape($data->author));
2820 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2821 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2823 $person = self::personByHandle($author);
2824 if (!is_array($person)) {
2825 Logger::log("unable to find author detail for ".$author);
2829 if (empty($contact["url"])) {
2830 $contact["url"] = $person["url"];
2833 // Fetch items that are about to be deleted
2834 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2836 // When we receive a public retraction, we delete every item that we find.
2837 if ($importer['uid'] == 0) {
2838 $condition = ['guid' => $target_guid, 'deleted' => false];
2840 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2843 $r = Item::select($fields, $condition);
2844 if (!DBA::isResult($r)) {
2845 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2849 while ($item = Item::fetch($r)) {
2850 if (strstr($item['file'], '[')) {
2851 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2855 // Fetch the parent item
2856 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2858 // Only delete it if the parent author really fits
2859 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2860 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2864 Item::delete(['id' => $item['id']]);
2866 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], Logger::DEBUG);
2873 * @brief Receives retraction messages
2875 * @param array $importer Array of the importer user
2876 * @param string $sender The sender of the message
2877 * @param object $data The message object
2879 * @return bool Success
2880 * @throws \Exception
2882 private static function receiveRetraction(array $importer, $sender, $data)
2884 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2886 $contact = self::contactByHandle($importer["uid"], $sender);
2887 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2888 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2896 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2898 switch ($target_type) {
2903 case "StatusMessage":
2904 return self::itemRetraction($importer, $contact, $data);
2906 case "PollParticipation":
2908 // Currently unsupported
2912 Logger::log("Unknown target type ".$target_type);
2919 * @brief Receives status messages
2921 * @param array $importer Array of the importer user
2922 * @param SimpleXMLElement $data The message object
2923 * @param string $xml The original XML of the message
2925 * @return int The message id of the newly created item
2926 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2927 * @throws \ImagickException
2929 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2931 $author = Strings::escapeTags(XML::unescape($data->author));
2932 $guid = Strings::escapeTags(XML::unescape($data->guid));
2933 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2934 $public = Strings::escapeTags(XML::unescape($data->public));
2935 $text = XML::unescape($data->text);
2936 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2938 $contact = self::allowedContactByHandle($importer, $author, false);
2943 $message_id = self::messageExists($importer["uid"], $guid);
2949 if ($data->location) {
2950 foreach ($data->location->children() as $fieldname => $data) {
2951 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2955 $body = Markdown::toBBCode($text);
2959 // Attach embedded pictures to the body
2961 foreach ($data->photo as $photo) {
2962 $body = "[img]".XML::unescape($photo->remote_photo_path).
2963 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2966 $datarray["object-type"] = Activity\ObjectType::IMAGE;
2968 $datarray["object-type"] = Activity\ObjectType::NOTE;
2970 // Add OEmbed and other information to the body
2971 if (!self::isRedmatrix($contact["url"])) {
2972 $body = add_page_info_to_body($body, false, true);
2976 /// @todo enable support for polls
2977 //if ($data->poll) {
2978 // foreach ($data->poll AS $poll)
2983 /// @todo enable support for events
2985 $datarray["uid"] = $importer["uid"];
2986 $datarray["contact-id"] = $contact["id"];
2987 $datarray["network"] = Protocol::DIASPORA;
2989 $datarray["author-link"] = $contact["url"];
2990 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2992 $datarray["owner-link"] = $datarray["author-link"];
2993 $datarray["owner-id"] = $datarray["author-id"];
2995 $datarray["guid"] = $guid;
2996 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2998 $datarray["verb"] = Activity::POST;
2999 $datarray["gravity"] = GRAVITY_PARENT;
3001 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
3002 $datarray["source"] = $xml;
3004 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3006 if ($provider_display_name != "") {
3007 $datarray["app"] = $provider_display_name;
3010 $datarray["plink"] = self::plink($author, $guid);
3011 $datarray["private"] = (($public == "false") ? 1 : 0);
3012 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3014 if (isset($address["address"])) {
3015 $datarray["location"] = $address["address"];
3018 if (isset($address["lat"]) && isset($address["lng"])) {
3019 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3022 self::fetchGuid($datarray);
3023 $message_id = Item::insert($datarray);
3025 self::sendParticipation($contact, $datarray);
3028 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
3029 if ($datarray['uid'] == 0) {
3030 Item::distribute($message_id);
3038 /* ************************************************************************************** *
3039 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3040 * ************************************************************************************** */
3043 * @brief returnes the handle of a contact
3045 * @param array $contact contact array
3047 * @return string the handle in the format user@domain.tld
3048 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3050 private static function myHandle(array $contact)
3052 if (!empty($contact["addr"])) {
3053 return $contact["addr"];
3056 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3057 // So - just in case - we build the the address here.
3058 if ($contact["nickname"] != "") {
3059 $nick = $contact["nickname"];
3061 $nick = $contact["nick"];
3064 return $nick . "@" . substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
3069 * @brief Creates the data for a private message in the new format
3071 * @param string $msg The message that is to be transmitted
3072 * @param array $user The record of the sender
3073 * @param array $contact Target of the communication
3074 * @param string $prvkey The private key of the sender
3075 * @param string $pubkey The public key of the receiver
3077 * @return string The encrypted data
3078 * @throws \Exception
3080 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
3082 Logger::log("Message: ".$msg, Logger::DATA);
3084 // without a public key nothing will work
3086 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3090 $aes_key = openssl_random_pseudo_bytes(32);
3091 $b_aes_key = base64_encode($aes_key);
3092 $iv = openssl_random_pseudo_bytes(16);
3093 $b_iv = base64_encode($iv);
3095 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3097 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3099 $encrypted_key_bundle = "";
3100 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3102 $json_object = json_encode(
3103 ["aes_key" => base64_encode($encrypted_key_bundle),
3104 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3107 return $json_object;
3111 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3113 * @param string $msg The message that is to be transmitted
3114 * @param array $user The record of the sender
3116 * @return string The envelope
3117 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3119 public static function buildMagicEnvelope($msg, array $user)
3121 $b64url_data = Strings::base64UrlEncode($msg);
3122 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3124 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3125 $type = "application/xml";
3126 $encoding = "base64url";
3127 $alg = "RSA-SHA256";
3128 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3130 // Fallback if the private key wasn't transmitted in the expected field
3131 if ($user['uprvkey'] == "") {
3132 $user['uprvkey'] = $user['prvkey'];
3135 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3136 $sig = Strings::base64UrlEncode($signature);
3138 $xmldata = ["me:env" => ["me:data" => $data,
3139 "@attributes" => ["type" => $type],
3140 "me:encoding" => $encoding,
3143 "@attributes2" => ["key_id" => $key_id]]];
3145 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3147 return XML::fromArray($xmldata, $xml, false, $namespaces);
3151 * @brief Create the envelope for a message
3153 * @param string $msg The message that is to be transmitted
3154 * @param array $user The record of the sender
3155 * @param array $contact Target of the communication
3156 * @param string $prvkey The private key of the sender
3157 * @param string $pubkey The public key of the receiver
3158 * @param bool $public Is the message public?
3160 * @return string The message that will be transmitted to other servers
3161 * @throws \Exception
3163 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3165 // The message is put into an envelope with the sender's signature
3166 $envelope = self::buildMagicEnvelope($msg, $user);
3168 // Private messages are put into a second envelope, encrypted with the receivers public key
3170 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3177 * @brief Creates a signature for a message
3179 * @param array $owner the array of the owner of the message
3180 * @param array $message The message that is to be signed
3182 * @return string The signature
3184 private static function signature($owner, $message)
3187 unset($sigmsg["author_signature"]);
3188 unset($sigmsg["parent_author_signature"]);
3190 $signed_text = implode(";", $sigmsg);
3192 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3196 * @brief Transmit a message to a target server
3198 * @param array $owner the array of the item owner
3199 * @param array $contact Target of the communication
3200 * @param string $envelope The message that is to be transmitted
3201 * @param bool $public_batch Is it a public post?
3202 * @param string $guid message guid
3204 * @return int Result of the transmission
3205 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3206 * @throws \ImagickException
3208 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3210 $enabled = intval(Config::get("system", "diaspora_enabled"));
3215 $logid = Strings::getRandomHex(4);
3217 // We always try to use the data from the fcontact table.
3218 // This is important for transmitting data to Friendica servers.
3219 if (!empty($contact['addr'])) {
3220 $fcontact = self::personByHandle($contact['addr']);
3221 if (!empty($fcontact)) {
3222 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3226 if (empty($dest_url)) {
3227 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3231 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3235 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3237 if (!intval(Config::get("system", "diaspora_test"))) {
3238 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3240 $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3241 $return_code = $postResult->getReturnCode();
3243 Logger::log("test_mode");
3247 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3249 return $return_code ? $return_code : -1;
3254 * @brief Build the post xml
3256 * @param string $type The message type
3257 * @param array $message The message data
3259 * @return string The post XML
3261 public static function buildPostXml($type, $message)
3263 $data = [$type => $message];
3265 return XML::fromArray($data, $xml);
3269 * @brief Builds and transmit messages
3271 * @param array $owner the array of the item owner
3272 * @param array $contact Target of the communication
3273 * @param string $type The message type
3274 * @param array $message The message data
3275 * @param bool $public_batch Is it a public post?
3276 * @param string $guid message guid
3278 * @return int Result of the transmission
3279 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3280 * @throws \ImagickException
3282 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3284 $msg = self::buildPostXml($type, $message);
3286 Logger::log('message: '.$msg, Logger::DATA);
3287 Logger::log('send guid '.$guid, Logger::DEBUG);
3289 // Fallback if the private key wasn't transmitted in the expected field
3290 if (empty($owner['uprvkey'])) {
3291 $owner['uprvkey'] = $owner['prvkey'];
3294 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3296 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3298 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3300 return $return_code;
3304 * @brief sends a participation (Used to get all further updates)
3306 * @param array $contact Target of the communication
3307 * @param array $item Item array
3309 * @return int The result of the transmission
3310 * @throws \Exception
3312 private static function sendParticipation(array $contact, array $item)
3314 // Don't send notifications for private postings
3315 if ($item['private']) {
3319 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3321 $result = Cache::get($cachekey);
3322 if (!is_null($result)) {
3326 // Fetch some user id to have a valid handle to transmit the participation.
3327 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3328 // If the item belongs to a user, we take this user id.
3329 if ($item['uid'] == 0) {
3330 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3331 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3332 $owner = User::getOwnerDataById($first_user['uid']);
3334 $owner = User::getOwnerDataById($item['uid']);
3337 $author = self::myHandle($owner);
3339 $message = ["author" => $author,
3340 "guid" => System::createUUID(),
3341 "parent_type" => "Post",
3342 "parent_guid" => $item["guid"]];
3344 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3346 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3347 Cache::set($cachekey, $item["guid"], Cache::QUARTER_HOUR);
3349 return self::buildAndTransmit($owner, $contact, "participation", $message);
3353 * @brief sends an account migration
3355 * @param array $owner the array of the item owner
3356 * @param array $contact Target of the communication
3357 * @param int $uid User ID
3359 * @return int The result of the transmission
3360 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3361 * @throws \ImagickException
3363 public static function sendAccountMigration(array $owner, array $contact, $uid)
3365 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3366 $profile = self::createProfileData($uid);
3368 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3369 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3371 $message = ["author" => $old_handle,
3372 "profile" => $profile,
3373 "signature" => $signature];
3375 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3377 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3381 * @brief Sends a "share" message
3383 * @param array $owner the array of the item owner
3384 * @param array $contact Target of the communication
3386 * @return int The result of the transmission
3387 * @throws \Exception
3389 public static function sendShare(array $owner, array $contact)
3392 * @todo support the different possible combinations of "following" and "sharing"
3393 * Currently, Diaspora only interprets the "sharing" field
3395 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3399 switch ($contact["rel"]) {
3400 case Contact::FRIEND:
3404 case Contact::SHARING:
3408 case Contact::FOLLOWER:
3414 $message = ["author" => self::myHandle($owner),
3415 "recipient" => $contact["addr"],
3416 "following" => "true",
3417 "sharing" => "true"];
3419 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3421 return self::buildAndTransmit($owner, $contact, "contact", $message);
3425 * @brief sends an "unshare"
3427 * @param array $owner the array of the item owner
3428 * @param array $contact Target of the communication
3430 * @return int The result of the transmission
3431 * @throws \Exception
3433 public static function sendUnshare(array $owner, array $contact)
3435 $message = ["author" => self::myHandle($owner),
3436 "recipient" => $contact["addr"],
3437 "following" => "false",
3438 "sharing" => "false"];
3440 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3442 return self::buildAndTransmit($owner, $contact, "contact", $message);
3446 * @brief Checks a message body if it is a reshare
3448 * @param string $body The message body that is to be check
3449 * @param bool $complete Should it be a complete check or a simple check?
3451 * @return array|bool Reshare details or "false" if no reshare
3452 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3453 * @throws \ImagickException
3455 public static function isReshare($body, $complete = true)
3457 $body = trim($body);
3459 // Skip if it isn't a pure repeated messages
3460 // Does it start with a share?
3461 if ((strpos($body, "[share") > 0) && $complete) {
3465 // Does it end with a share?
3466 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3470 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3471 // Skip if there is no shared message in there
3472 if ($body == $attributes) {
3476 // If we don't do the complete check we quit here
3479 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3480 if (!empty($matches[1])) {
3481 $guid = $matches[1];
3484 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3485 if (!empty($matches[1])) {
3486 $guid = $matches[1];
3489 if (($guid != "") && $complete) {
3490 $condition = ['guid' => $guid, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3491 $item = Item::selectFirst(['contact-id'], $condition);
3492 if (DBA::isResult($item)) {
3494 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3495 $ret["root_guid"] = $guid;
3497 } elseif ($complete) {
3498 // We are resharing something that isn't a DFRN or Diaspora post.
3499 // So we have to return "false" on "$complete" to not trigger a reshare.
3502 } elseif (($guid == "") && $complete) {
3506 $ret["root_guid"] = $guid;
3509 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3510 if (!empty($matches[1])) {
3511 $profile = $matches[1];
3514 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3515 if (!empty($matches[1])) {
3516 $profile = $matches[1];
3521 if ($profile != "") {
3522 if (Contact::getIdForURL($profile)) {
3523 $author = Contact::getDetailsByURL($profile);
3524 $ret["root_handle"] = $author['addr'];
3528 if (empty($ret) && !$complete) {
3536 * @brief Create an event array
3538 * @param integer $event_id The id of the event
3540 * @return array with event data
3541 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3543 private static function buildEvent($event_id)
3545 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3546 if (!DBA::isResult($r)) {
3554 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3555 if (!DBA::isResult($r)) {
3561 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3562 if (!DBA::isResult($r)) {
3568 $eventdata['author'] = self::myHandle($owner);
3570 if ($event['guid']) {
3571 $eventdata['guid'] = $event['guid'];
3574 $mask = DateTimeFormat::ATOM;
3576 /// @todo - establish "all day" events in Friendica
3577 $eventdata["all_day"] = "false";
3579 $eventdata['timezone'] = 'UTC';
3580 if (!$event['adjust'] && $user['timezone']) {
3581 $eventdata['timezone'] = $user['timezone'];
3584 if ($event['start']) {
3585 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3587 if ($event['finish'] && !$event['nofinish']) {
3588 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3590 if ($event['summary']) {
3591 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3593 if ($event['desc']) {
3594 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3596 if ($event['location']) {
3597 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3598 $coord = Map::getCoordinates($event['location']);
3601 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3602 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3603 $location["lat"] = $coord['lat'];
3604 $location["lng"] = $coord['lon'];
3606 $location["lat"] = 0;
3607 $location["lng"] = 0;
3609 $eventdata['location'] = $location;
3616 * @brief Create a post (status message or reshare)
3618 * @param array $item The item that will be exported
3619 * @param array $owner the array of the item owner
3622 * 'type' -> Message type ("status_message" or "reshare")
3623 * 'message' -> Array of XML elements of the status
3624 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3625 * @throws \ImagickException
3627 public static function buildStatus(array $item, array $owner)
3629 $cachekey = "diaspora:buildStatus:".$item['guid'];
3631 $result = Cache::get($cachekey);
3632 if (!is_null($result)) {
3636 $myaddr = self::myHandle($owner);
3638 $public = ($item["private"] ? "false" : "true");
3640 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3641 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3643 // Detect a share element and do a reshare
3644 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3645 $message = ["author" => $myaddr,
3646 "guid" => $item["guid"],
3647 "created_at" => $created,
3648 "root_author" => $ret["root_handle"],
3649 "root_guid" => $ret["root_guid"],
3650 "provider_display_name" => $item["app"],
3651 "public" => $public];
3655 $title = $item["title"];
3656 $body = $item["body"];
3658 if ($item['author-link'] != $item['owner-link']) {
3659 require_once 'mod/share.php';
3660 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3661 "", $item['created'], $item['plink']) . $body . '[/share]';
3664 // convert to markdown
3665 $body = html_entity_decode(BBCode::toMarkdown($body));
3668 if (strlen($title)) {
3669 $body = "## ".html_entity_decode($title)."\n\n".$body;
3672 if ($item["attach"]) {
3673 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3675 $body .= "\n".L10n::t("Attachments:")."\n";
3676 foreach ($matches as $mtch) {
3677 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3684 if ($item["location"] != "")
3685 $location["address"] = $item["location"];
3687 if ($item["coord"] != "") {
3688 $coord = explode(" ", $item["coord"]);
3689 $location["lat"] = $coord[0];
3690 $location["lng"] = $coord[1];
3693 $message = ["author" => $myaddr,
3694 "guid" => $item["guid"],
3695 "created_at" => $created,
3696 "edited_at" => $edited,
3697 "public" => $public,
3699 "provider_display_name" => $item["app"],
3700 "location" => $location];
3702 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3703 if (!isset($location["lat"]) || !isset($location["lng"])) {
3704 unset($message["location"]);
3707 if ($item['event-id'] > 0) {
3708 $event = self::buildEvent($item['event-id']);
3709 if (count($event)) {
3710 $message['event'] = $event;
3712 if (!empty($event['location']['address']) &&
3713 !empty($event['location']['lat']) &&
3714 !empty($event['location']['lng'])) {
3715 $message['location'] = $event['location'];
3718 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3719 // $message['text'] = '';
3723 $type = "status_message";
3726 $msg = ["type" => $type, "message" => $message];
3728 Cache::set($cachekey, $msg, Cache::QUARTER_HOUR);
3733 private static function prependParentAuthorMention($body, $profile_url)
3735 $profile = Contact::getDetailsByURL($profile_url);
3736 if (!empty($profile['addr'])
3737 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3738 && !strstr($body, $profile['addr'])
3739 && !strstr($body, $profile_url)
3741 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3748 * @brief Sends a post
3750 * @param array $item The item that will be exported
3751 * @param array $owner the array of the item owner
3752 * @param array $contact Target of the communication
3753 * @param bool $public_batch Is it a public post?
3755 * @return int The result of the transmission
3756 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3757 * @throws \ImagickException
3759 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3761 $status = self::buildStatus($item, $owner);
3763 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3767 * @brief Creates a "like" object
3769 * @param array $item The item that will be exported
3770 * @param array $owner the array of the item owner
3772 * @return array The data for a "like"
3773 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3775 private static function constructLike(array $item, array $owner)
3777 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3778 if (!DBA::isResult($parent)) {
3782 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3784 if ($item['verb'] === Activity::LIKE) {
3786 } elseif ($item['verb'] === Activity::DISLIKE) {
3787 $positive = "false";
3790 return(["author" => self::myHandle($owner),
3791 "guid" => $item["guid"],
3792 "parent_guid" => $parent["guid"],
3793 "parent_type" => $target_type,
3794 "positive" => $positive,
3795 "author_signature" => ""]);
3799 * @brief Creates an "EventParticipation" object
3801 * @param array $item The item that will be exported
3802 * @param array $owner the array of the item owner
3804 * @return array The data for an "EventParticipation"
3805 * @throws \Exception
3807 private static function constructAttend(array $item, array $owner)
3809 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3810 if (!DBA::isResult($parent)) {
3814 switch ($item['verb']) {
3815 case Activity::ATTEND:
3816 $attend_answer = 'accepted';
3818 case Activity::ATTENDNO:
3819 $attend_answer = 'declined';
3821 case Activity::ATTENDMAYBE:
3822 $attend_answer = 'tentative';
3825 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3829 return(["author" => self::myHandle($owner),
3830 "guid" => $item["guid"],
3831 "parent_guid" => $parent["guid"],
3832 "status" => $attend_answer,
3833 "author_signature" => ""]);
3837 * @brief Creates the object for a comment
3839 * @param array $item The item that will be exported
3840 * @param array $owner the array of the item owner
3842 * @return array|false The data for a comment
3843 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3845 private static function constructComment(array $item, array $owner)
3847 $cachekey = "diaspora:constructComment:".$item['guid'];
3849 $result = Cache::get($cachekey);
3850 if (!is_null($result)) {
3854 $toplevel_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3855 if (!DBA::isResult($toplevel_item)) {
3856 Logger::error('Missing parent conversation item', ['parent' => $item["parent"]]);
3860 $thread_parent_item = $toplevel_item;
3861 if ($item['thr-parent'] != $item['parent-uri']) {
3862 $thread_parent_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3865 $body = $item["body"];
3867 // The replied to autor mention is prepended for clarity if:
3868 // - Item replied isn't yours
3869 // - Item is public or explicit mentions are disabled
3870 // - Implicit mentions are enabled
3872 $item['author-id'] != $thread_parent_item['author-id']
3873 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3874 && !Config::get('system', 'disable_implicit_mentions')
3876 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3879 $text = html_entity_decode(BBCode::toMarkdown($body));
3880 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3881 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3884 "author" => self::myHandle($owner),
3885 "guid" => $item["guid"],
3886 "created_at" => $created,
3887 "edited_at" => $edited,
3888 "parent_guid" => $toplevel_item["guid"],
3890 "author_signature" => ""
3893 // Send the thread parent guid only if it is a threaded comment
3894 if ($item['thr-parent'] != $item['parent-uri']) {
3895 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3898 Cache::set($cachekey, $comment, Cache::QUARTER_HOUR);
3904 * @brief Send a like or a comment
3906 * @param array $item The item that will be exported
3907 * @param array $owner the array of the item owner
3908 * @param array $contact Target of the communication
3909 * @param bool $public_batch Is it a public post?
3911 * @return int The result of the transmission
3912 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3913 * @throws \ImagickException
3915 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3917 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3918 $message = self::constructAttend($item, $owner);
3919 $type = "event_participation";
3920 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3921 $message = self::constructLike($item, $owner);
3923 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3924 $message = self::constructComment($item, $owner);
3928 if (empty($message)) {
3932 $message["author_signature"] = self::signature($owner, $message);
3934 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3938 * @brief Creates a message from a signature record entry
3940 * @param array $item The item that will be exported
3941 * @return array The message
3943 private static function messageFromSignature(array $item)
3945 // Split the signed text
3946 $signed_parts = explode(";", $item['signed_text']);
3948 if ($item["deleted"]) {
3949 $message = ["author" => $item['signer'],
3950 "target_guid" => $signed_parts[0],
3951 "target_type" => $signed_parts[1]];
3952 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3953 $message = ["author" => $signed_parts[4],
3954 "guid" => $signed_parts[1],
3955 "parent_guid" => $signed_parts[3],
3956 "parent_type" => $signed_parts[2],
3957 "positive" => $signed_parts[0],
3958 "author_signature" => $item['signature'],
3959 "parent_author_signature" => ""];
3961 // Remove the comment guid
3962 $guid = array_shift($signed_parts);
3964 // Remove the parent guid
3965 $parent_guid = array_shift($signed_parts);
3967 // Remove the handle
3968 $handle = array_pop($signed_parts);
3971 "author" => $handle,
3973 "parent_guid" => $parent_guid,
3974 "text" => implode(";", $signed_parts),
3975 "author_signature" => $item['signature'],
3976 "parent_author_signature" => ""
3983 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3985 * @param array $item The item that will be exported
3986 * @param array $owner the array of the item owner
3987 * @param array $contact Target of the communication
3988 * @param bool $public_batch Is it a public post?
3990 * @return int The result of the transmission
3991 * @throws \Exception
3993 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3995 if ($item["deleted"]) {
3996 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3997 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4003 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
4005 // Old way - is used by the internal Friendica functions
4006 /// @todo Change all signatur storing functions to the new format
4007 if ($item['signed_text'] && $item['signature'] && $item['signer']) {
4008 $message = self::messageFromSignature($item);
4010 $msg = json_decode($item['signed_text'], true);
4013 if (is_array($msg)) {
4014 foreach ($msg as $field => $data) {
4015 if (!$item["deleted"]) {
4016 if ($field == "diaspora_handle") {
4019 if ($field == "target_type") {
4020 $field = "parent_type";
4024 $message[$field] = $data;
4027 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
4031 $message["parent_author_signature"] = self::signature($owner, $message);
4033 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
4035 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4039 * @brief Sends a retraction (deletion) of a message, like or comment
4041 * @param array $item The item that will be exported
4042 * @param array $owner the array of the item owner
4043 * @param array $contact Target of the communication
4044 * @param bool $public_batch Is it a public post?
4045 * @param bool $relay Is the retraction transmitted from a relay?
4047 * @return int The result of the transmission
4048 * @throws \Exception
4050 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
4052 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4054 $msg_type = "retraction";
4056 if ($item['id'] == $item['parent']) {
4057 $target_type = "Post";
4058 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4059 $target_type = "Like";
4061 $target_type = "Comment";
4064 $message = ["author" => $itemaddr,
4065 "target_guid" => $item['guid'],
4066 "target_type" => $target_type];
4068 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
4070 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4074 * @brief Sends a mail
4076 * @param array $item The item that will be exported
4077 * @param array $owner The owner
4078 * @param array $contact Target of the communication
4080 * @return int The result of the transmission
4081 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4082 * @throws \ImagickException
4084 public static function sendMail(array $item, array $owner, array $contact)
4086 $myaddr = self::myHandle($owner);
4088 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
4089 if (!DBA::isResult($cnv)) {
4090 Logger::log("conversation not found.");
4094 $body = BBCode::toMarkdown($item["body"]);
4095 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4098 "author" => $myaddr,
4099 "guid" => $item["guid"],
4100 "conversation_guid" => $cnv["guid"],
4102 "created_at" => $created,
4105 if ($item["reply"]) {
4110 "author" => $cnv["creator"],
4111 "guid" => $cnv["guid"],
4112 "subject" => $cnv["subject"],
4113 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4114 "participants" => $cnv["recips"],
4118 $type = "conversation";
4121 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4125 * @brief Split a name into first name and last name
4127 * @param string $name The name
4129 * @return array The array with "first" and "last"
4131 public static function splitName($name) {
4132 $name = trim($name);
4134 // Is the name longer than 64 characters? Then cut the rest of it.
4135 if (strlen($name) > 64) {
4136 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4137 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4139 $name = substr($name, 0, 64);
4143 // Take the first word as first name
4144 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4145 $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 last word as last name
4151 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4152 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4154 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4155 return ['first' => $first, 'last' => $last];
4158 // Take the first 32 characters if there is no space in the first 32 characters
4159 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4160 $first = substr($name, 0, 32);
4161 $last = substr($name, 32);
4162 return ['first' => $first, 'last' => $last];
4165 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4166 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4168 // Check if the last name is longer than 32 characters
4169 if (strlen($last) > 32) {
4170 if (strpos($last, ' ') <= 32) {
4171 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4173 $last = substr($last, 0, 32);
4177 return ['first' => $first, 'last' => $last];
4181 * @brief Create profile data
4183 * @param int $uid The user id
4185 * @return array The profile data
4186 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4188 private static function createProfileData($uid)
4191 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4193 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4194 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4195 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4204 $handle = $profile["addr"];
4206 $split_name = self::splitName($profile['name']);
4207 $first = $split_name['first'];
4208 $last = $split_name['last'];
4210 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4211 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4212 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4213 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4219 if ($searchable === 'true') {
4222 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4223 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4227 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4230 $about = $profile['about'];
4231 $about = strip_tags(BBCode::convert($about));
4233 $location = Profile::formatLocation($profile);
4235 if ($profile['pub_keywords']) {
4236 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4237 $kw = str_replace(' ', ' ', $kw);
4238 $arr = explode(' ', $kw);
4240 for ($x = 0; $x < 5; $x ++) {
4241 if (!empty($arr[$x])) {
4242 $tags .= '#'. trim($arr[$x]) .' ';
4247 $tags = trim($tags);
4250 return ["author" => $handle,
4251 "first_name" => $first,
4252 "last_name" => $last,
4253 "image_url" => $large,
4254 "image_url_medium" => $medium,
4255 "image_url_small" => $small,
4257 "gender" => $profile['gender'],
4259 "location" => $location,
4260 "searchable" => $searchable,
4262 "tag_string" => $tags];
4266 * @brief Sends profile data
4268 * @param int $uid The user id
4269 * @param bool $recips optional, default false
4271 * @throws \Exception
4273 public static function sendProfile($uid, $recips = false)
4279 $owner = User::getOwnerDataById($uid);
4286 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4287 AND `uid` = %d AND `rel` != %d",
4288 DBA::escape(Protocol::DIASPORA),
4290 intval(Contact::SHARING)
4298 $message = self::createProfileData($uid);
4300 // @ToDo Split this into single worker jobs
4301 foreach ($recips as $recip) {
4302 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4303 self::buildAndTransmit($owner, $recip, "profile", $message);
4308 * @brief Creates the signature for likes that are created on our system
4310 * @param integer $uid The user of that comment
4311 * @param array $item Item array
4313 * @return array Signed content
4314 * @throws \Exception
4316 public static function createLikeSignature($uid, array $item)
4318 $owner = User::getOwnerDataById($uid);
4319 if (empty($owner)) {
4320 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4324 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4328 $message = self::constructLike($item, $owner);
4329 if ($message === false) {
4333 $message["author_signature"] = self::signature($owner, $message);
4339 * @brief Creates the signature for Comments that are created on our system
4341 * @param integer $uid The user of that comment
4342 * @param array $item Item array
4344 * @return array Signed content
4345 * @throws \Exception
4347 public static function createCommentSignature($uid, array $item)
4349 $owner = User::getOwnerDataById($uid);
4350 if (empty($owner)) {
4351 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4355 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4356 $item['thr-parent'] = $item['parent-uri'];
4358 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4359 if (!DBA::isResult($parent)) {
4363 $item['parent-uri'] = $parent['parent-uri'];
4365 $message = self::constructComment($item, $owner);
4366 if ($message === false) {
4370 $message["author_signature"] = self::signature($owner, $message);