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\Text\BBCode;
14 use Friendica\Content\Text\Markdown;
15 use Friendica\Core\Cache;
16 use Friendica\Core\Config;
17 use Friendica\Core\L10n;
18 use Friendica\Core\PConfig;
19 use Friendica\Core\System;
20 use Friendica\Core\Worker;
21 use Friendica\Database\DBM;
22 use Friendica\Model\Contact;
23 use Friendica\Model\GContact;
24 use Friendica\Model\Group;
25 use Friendica\Model\Item;
26 use Friendica\Model\Profile;
27 use Friendica\Model\Queue;
28 use Friendica\Model\User;
29 use Friendica\Network\Probe;
30 use Friendica\Util\Crypto;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Network;
33 use Friendica\Util\XML;
34 use Friendica\Util\Map;
38 require_once 'include/dba.php';
39 require_once 'include/items.php';
42 * @brief This class contain functions to create and send Diaspora XML files
48 * @brief Return a list of relay servers
50 * The list contains not only the official relays but also servers that we serve directly
52 * @param integer $item_id The id of the item that is sent
53 * @param array $contacts The previously fetched contacts
55 * @return array of relay servers
57 public static function relayList($item_id, $contacts = [])
61 // Fetching relay servers
62 $serverdata = Config::get("system", "relay_server");
63 if ($serverdata != "") {
64 $servers = explode(",", $serverdata);
65 foreach ($servers as $server) {
66 $serverlist[$server] = trim($server);
70 if (Config::get("system", "relay_directly", false)) {
71 // We distribute our stuff based on the parent to ensure that the thread will be complete
72 $parent = Item::selectFirst(0, ['parent'], ['id' => $item_id]);
73 if (!DBM::is_result($parent)) {
77 // Servers that want to get all content
78 $servers = dba::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
79 while ($server = dba::fetch($servers)) {
80 $serverlist[$server['url']] = $server['url'];
83 // All tags of the current post
84 $condition = ['otype' => TERM_OBJ_POST, 'type' => TERM_HASHTAG, 'oid' => $parent['parent']];
85 $tags = dba::select('term', ['term'], $condition);
87 while ($tag = dba::fetch($tags)) {
88 $taglist[] = $tag['term'];
91 // All servers who wants content with this tag
93 if (!empty($taglist)) {
94 $tagserver = dba::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
95 while ($server = dba::fetch($tagserver)) {
96 $tagserverlist[] = $server['gserver-id'];
100 // All adresses with the given id
101 if (!empty($tagserverlist)) {
102 $servers = dba::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
103 while ($server = dba::fetch($servers)) {
104 $serverlist[$server['url']] = $server['url'];
109 // Now we are collecting all relay contacts
110 foreach ($serverlist as $server_url) {
111 // We don't send messages to ourselves
112 if (link_compare($server_url, System::baseUrl())) {
115 $contact = self::getRelayContact($server_url);
116 if (is_bool($contact)) {
121 foreach ($contacts as $entry) {
122 if ($entry['batch'] == $contact['batch']) {
128 $contacts[] = $contact;
136 * @brief Return a contact for a given server address or creates a dummy entry
138 * @param string $server_url The url of the server
139 * @return array with the contact
141 private static function getRelayContact($server_url)
143 $fields = ['batch', 'id', 'name', 'network', 'archive', 'blocked'];
145 // Fetch the relay contact
146 $condition = ['uid' => 0, 'nurl' => normalise_link($server_url),
147 'contact-type' => ACCOUNT_TYPE_RELAY];
148 $contact = dba::selectFirst('contact', $fields, $condition);
150 if (DBM::is_result($contact)) {
151 if ($contact['archive'] || $contact['blocked']) {
156 self::setRelayContact($server_url);
158 $contact = dba::selectFirst('contact', $fields, $condition);
159 if (DBM::is_result($contact)) {
164 // It should never happen that we arrive here
169 * @brief Update or insert a relay contact
171 * @param string $server_url The url of the server
172 * @param array $network_fields Optional network specific fields
174 public static function setRelayContact($server_url, $network_fields = [])
176 $fields = ['created' => DateTimeFormat::utcNow(),
177 'name' => 'relay', 'nick' => 'relay',
178 'url' => $server_url, 'network' => NETWORK_DIASPORA,
179 'batch' => $server_url . '/receive/public',
180 'rel' => CONTACT_IS_FOLLOWER, 'blocked' => false,
181 'pending' => false, 'writable' => true];
183 $fields = array_merge($fields, $network_fields);
185 $condition = ['uid' => 0, 'nurl' => normalise_link($server_url),
186 'contact-type' => ACCOUNT_TYPE_RELAY];
188 if (dba::exists('contact', $condition)) {
189 unset($fields['created']);
192 dba::update('contact', $fields, $condition, true);
196 * @brief Return a list of participating contacts for a thread
198 * This is used for the participation feature.
199 * One of the parameters is a contact array.
200 * This is done to avoid duplicates.
202 * @param integer $thread The id of the thread
203 * @param array $contacts The previously fetched contacts
205 * @return array of relay servers
207 public static function participantsForThread($thread, $contacts)
209 $r = dba::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`,
210 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
211 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
212 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
213 WHERE `participation`.`iid` = ?", $thread);
215 while ($contact = dba::fetch($r)) {
216 if (!empty($contact['fnetwork'])) {
217 $contact['network'] = $contact['fnetwork'];
219 unset($contact['fnetwork']);
221 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
222 $contact['batch'] = $contact['fbatch'];
224 unset($contact['fbatch']);
227 foreach ($contacts as $entry) {
228 if ($entry['batch'] == $contact['batch']) {
234 $contacts[] = $contact;
243 * @brief repairs a signature that was double encoded
245 * The function is unused at the moment. It was copied from the old implementation.
247 * @param string $signature The signature
248 * @param string $handle The handle of the signature owner
249 * @param integer $level This value is only set inside this function to avoid endless loops
251 * @return string the repaired signature
253 private static function repairSignature($signature, $handle = "", $level = 1)
255 if ($signature == "") {
259 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
260 $signature = base64_decode($signature);
261 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
263 // Do a recursive call to be able to fix even multiple levels
265 $signature = self::repairSignature($signature, $handle, ++$level);
273 * @brief verify the envelope and return the verified data
275 * @param string $envelope The magic envelope
277 * @return string verified data
279 private static function verifyMagicEnvelope($envelope)
281 $basedom = XML::parseString($envelope);
283 if (!is_object($basedom)) {
284 logger("Envelope is no XML file");
288 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
290 if (sizeof($children) == 0) {
291 logger("XML has no children");
297 $data = base64url_decode($children->data);
298 $type = $children->data->attributes()->type[0];
300 $encoding = $children->encoding;
302 $alg = $children->alg;
304 $sig = base64url_decode($children->sig);
305 $key_id = $children->sig->attributes()->key_id[0];
307 $handle = base64url_decode($key_id);
310 $b64url_data = base64url_encode($data);
311 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
313 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
316 logger('No author could be decoded. Discarding. Message: ' . $envelope);
320 $key = self::key($handle);
322 logger("Couldn't get a key for handle " . $handle . ". Discarding.");
326 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
328 logger('Message from ' . $handle . ' did not verify. Discarding.');
336 * @brief encrypts data via AES
338 * @param string $key The AES key
339 * @param string $iv The IV (is used for CBC encoding)
340 * @param string $data The data that is to be encrypted
342 * @return string encrypted data
344 private static function aesEncrypt($key, $iv, $data)
346 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
350 * @brief decrypts data via AES
352 * @param string $key The AES key
353 * @param string $iv The IV (is used for CBC encoding)
354 * @param string $encrypted The encrypted data
356 * @return string decrypted data
358 private static function aesDecrypt($key, $iv, $encrypted)
360 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
364 * @brief: Decodes incoming Diaspora message in the new format
366 * @param array $importer Array of the importer user
367 * @param string $raw raw post message
370 * 'message' -> decoded Diaspora XML message
371 * 'author' -> author diaspora handle
372 * 'key' -> author public key (converted to pkcs#8)
374 public static function decodeRaw($importer, $raw)
376 $data = json_decode($raw);
378 // Is it a private post? Then decrypt the outer Salmon
379 if (is_object($data)) {
380 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
381 $ciphertext = base64_decode($data->encrypted_magic_envelope);
383 $outer_key_bundle = '';
384 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
385 $j_outer_key_bundle = json_decode($outer_key_bundle);
387 if (!is_object($j_outer_key_bundle)) {
388 logger('Outer Salmon did not verify. Discarding.');
389 System::httpExit(400);
392 $outer_iv = base64_decode($j_outer_key_bundle->iv);
393 $outer_key = base64_decode($j_outer_key_bundle->key);
395 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
400 $basedom = XML::parseString($xml);
402 if (!is_object($basedom)) {
403 logger('Received data does not seem to be an XML. Discarding. '.$xml);
404 System::httpExit(400);
407 $base = $basedom->children(NAMESPACE_SALMON_ME);
409 // Not sure if this cleaning is needed
410 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
412 // Build the signed data
413 $type = $base->data[0]->attributes()->type[0];
414 $encoding = $base->encoding;
416 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
418 // This is the signature
419 $signature = base64url_decode($base->sig);
421 // Get the senders' public key
422 $key_id = $base->sig[0]->attributes()->key_id[0];
423 $author_addr = base64_decode($key_id);
424 if ($author_addr == '') {
425 logger('No author could be decoded. Discarding. Message: ' . $xml);
426 System::httpExit(400);
429 $key = self::key($author_addr);
431 logger("Couldn't get a key for handle " . $author_addr . ". Discarding.");
432 System::httpExit(400);
435 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
437 logger('Message did not verify. Discarding.');
438 System::httpExit(400);
441 return ['message' => (string)base64url_decode($base->data),
442 'author' => unxmlify($author_addr),
443 'key' => (string)$key];
447 * @brief: Decodes incoming Diaspora message in the deprecated format
449 * @param array $importer Array of the importer user
450 * @param string $xml urldecoded Diaspora salmon
453 * 'message' -> decoded Diaspora XML message
454 * 'author' -> author diaspora handle
455 * 'key' -> author public key (converted to pkcs#8)
457 public static function decode($importer, $xml)
460 $basedom = XML::parseString($xml);
462 if (!is_object($basedom)) {
463 logger("XML is not parseable.");
466 $children = $basedom->children('https://joindiaspora.com/protocol');
468 $inner_aes_key = null;
471 if ($children->header) {
473 $author_link = str_replace('acct:', '', $children->header->author_id);
475 // This happens with posts from a relais
477 logger("This is no private post in the old format", LOGGER_DEBUG);
481 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
483 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
484 $ciphertext = base64_decode($encrypted_header->ciphertext);
486 $outer_key_bundle = '';
487 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
489 $j_outer_key_bundle = json_decode($outer_key_bundle);
491 $outer_iv = base64_decode($j_outer_key_bundle->iv);
492 $outer_key = base64_decode($j_outer_key_bundle->key);
494 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
496 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
497 $idom = XML::parseString($decrypted);
499 $inner_iv = base64_decode($idom->iv);
500 $inner_aes_key = base64_decode($idom->aes_key);
502 $author_link = str_replace('acct:', '', $idom->author_id);
505 $dom = $basedom->children(NAMESPACE_SALMON_ME);
507 // figure out where in the DOM tree our data is hiding
510 if ($dom->provenance->data) {
511 $base = $dom->provenance;
512 } elseif ($dom->env->data) {
514 } elseif ($dom->data) {
519 logger('unable to locate salmon data in xml');
520 System::httpExit(400);
524 // Stash the signature away for now. We have to find their key or it won't be good for anything.
525 $signature = base64url_decode($base->sig);
529 // strip whitespace so our data element will return to one big base64 blob
530 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
533 // stash away some other stuff for later
535 $type = $base->data[0]->attributes()->type[0];
536 $keyhash = $base->sig[0]->attributes()->keyhash[0];
537 $encoding = $base->encoding;
541 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
545 $data = base64url_decode($data);
549 $inner_decrypted = $data;
551 // Decode the encrypted blob
552 $inner_encrypted = base64_decode($data);
553 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
557 logger('Could not retrieve author URI.');
558 System::httpExit(400);
560 // Once we have the author URI, go to the web and try to find their public key
561 // (first this will look it up locally if it is in the fcontact cache)
562 // This will also convert diaspora public key from pkcs#1 to pkcs#8
564 logger('Fetching key for '.$author_link);
565 $key = self::key($author_link);
568 logger('Could not retrieve author key.');
569 System::httpExit(400);
572 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
575 logger('Message did not verify. Discarding.');
576 System::httpExit(400);
579 logger('Message verified.');
581 return ['message' => (string)$inner_decrypted,
582 'author' => unxmlify($author_link),
583 'key' => (string)$key];
588 * @brief Dispatches public messages and find the fitting receivers
590 * @param array $msg The post that will be dispatched
592 * @return int The message id of the generated message, "true" or "false" if there was an error
594 public static function dispatchPublic($msg)
596 $enabled = intval(Config::get("system", "diaspora_enabled"));
598 logger("diaspora is disabled");
602 if (!($fields = self::validPosting($msg))) {
603 logger("Invalid posting");
607 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
608 $success = self::dispatch($importer, $msg, $fields);
614 * @brief Dispatches the different message types to the different functions
616 * @param array $importer Array of the importer user
617 * @param array $msg The post that will be dispatched
618 * @param object $fields SimpleXML object that contains the message
620 * @return int The message id of the generated message, "true" or "false" if there was an error
622 public static function dispatch($importer, $msg, $fields = null)
624 // The sender is the handle of the contact that sent the message.
625 // This will often be different with relayed messages (for example "like" and "comment")
626 $sender = $msg["author"];
628 // This is only needed for private postings since this is already done for public ones before
629 if (is_null($fields)) {
631 if (!($fields = self::validPosting($msg))) {
632 logger("Invalid posting");
639 $type = $fields->getName();
641 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
644 case "account_migration":
646 logger('Message with type ' . $type . ' is not private, quitting.');
649 return self::receiveAccountMigration($importer, $fields);
651 case "account_deletion":
652 return self::receiveAccountDeletion($fields);
655 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
659 logger('Message with type ' . $type . ' is not private, quitting.');
662 return self::receiveContactRequest($importer, $fields);
666 logger('Message with type ' . $type . ' is not private, quitting.');
669 return self::receiveConversation($importer, $msg, $fields);
672 return self::receiveLike($importer, $sender, $fields);
676 logger('Message with type ' . $type . ' is not private, quitting.');
679 return self::receiveMessage($importer, $fields);
681 case "participation":
683 logger('Message with type ' . $type . ' is not private, quitting.');
686 return self::receiveParticipation($importer, $fields);
688 case "photo": // Not implemented
689 return self::receivePhoto($importer, $fields);
691 case "poll_participation": // Not implemented
692 return self::receivePollParticipation($importer, $fields);
696 logger('Message with type ' . $type . ' is not private, quitting.');
699 return self::receiveProfile($importer, $fields);
702 return self::receiveReshare($importer, $fields, $msg["message"]);
705 return self::receiveRetraction($importer, $sender, $fields);
707 case "status_message":
708 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
711 logger("Unknown message type ".$type);
719 * @brief Checks if a posting is valid and fetches the data fields.
721 * This function does not only check the signature.
722 * It also does the conversion between the old and the new diaspora format.
724 * @param array $msg Array with the XML, the sender handle and the sender signature
726 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
728 private static function validPosting($msg)
730 $data = XML::parseString($msg["message"]);
732 if (!is_object($data)) {
733 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
737 // Is this the new or the old version?
738 if ($data->getName() == "XML") {
740 foreach ($data->post->children() as $child) {
748 $type = $element->getName();
751 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
753 // All retractions are handled identically from now on.
754 // In the new version there will only be "retraction".
755 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
756 $type = "retraction";
758 if ($type == "request") {
762 $fields = new SimpleXMLElement("<".$type."/>");
765 $author_signature = null;
766 $parent_author_signature = null;
768 foreach ($element->children() as $fieldname => $entry) {
770 // Translation for the old XML structure
771 if ($fieldname == "diaspora_handle") {
772 $fieldname = "author";
774 if ($fieldname == "participant_handles") {
775 $fieldname = "participants";
777 if (in_array($type, ["like", "participation"])) {
778 if ($fieldname == "target_type") {
779 $fieldname = "parent_type";
782 if ($fieldname == "sender_handle") {
783 $fieldname = "author";
785 if ($fieldname == "recipient_handle") {
786 $fieldname = "recipient";
788 if ($fieldname == "root_diaspora_id") {
789 $fieldname = "root_author";
791 if ($type == "status_message") {
792 if ($fieldname == "raw_message") {
796 if ($type == "retraction") {
797 if ($fieldname == "post_guid") {
798 $fieldname = "target_guid";
800 if ($fieldname == "type") {
801 $fieldname = "target_type";
806 if (($fieldname == "author_signature") && ($entry != "")) {
807 $author_signature = base64_decode($entry);
808 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
809 $parent_author_signature = base64_decode($entry);
810 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
811 if ($signed_data != "") {
815 $signed_data .= $entry;
817 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
818 || ($orig_type == "relayable_retraction")
820 XML::copy($entry, $fields, $fieldname);
824 // This is something that shouldn't happen at all.
825 if (in_array($type, ["status_message", "reshare", "profile"])) {
826 if ($msg["author"] != $fields->author) {
827 logger("Message handle is not the same as envelope sender. Quitting this message.");
832 // Only some message types have signatures. So we quit here for the other types.
833 if (!in_array($type, ["comment", "like"])) {
836 // No author_signature? This is a must, so we quit.
837 if (!isset($author_signature)) {
838 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
842 if (isset($parent_author_signature)) {
843 $key = self::key($msg["author"]);
845 logger("No key found for parent author ".$msg["author"], LOGGER_DEBUG);
849 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
850 logger("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);
855 $key = self::key($fields->author);
857 logger("No key found for author ".$fields->author, LOGGER_DEBUG);
861 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
862 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
870 * @brief Fetches the public key for a given handle
872 * @param string $handle The handle
874 * @return string The public key
876 private static function key($handle)
878 $handle = strval($handle);
880 logger("Fetching diaspora key for: ".$handle);
882 $r = self::personByHandle($handle);
891 * @brief Fetches data for a given handle
893 * @param string $handle The handle
895 * @return array the queried data
897 public static function personByHandle($handle)
901 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
902 if (DBM::is_result($person)) {
903 logger("In cache " . print_r($person, true), LOGGER_DEBUG);
905 // update record occasionally so it doesn't get stale
906 $d = strtotime($person["updated"]." +00:00");
907 if ($d < strtotime("now - 14 days")) {
911 if ($person["guid"] == "") {
916 if (!DBM::is_result($person) || $update) {
917 logger("create or refresh", LOGGER_DEBUG);
918 $r = Probe::uri($handle, NETWORK_DIASPORA);
920 // Note that Friendica contacts will return a "Diaspora person"
921 // if Diaspora connectivity is enabled on their server
922 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
923 self::updateFContact($r);
925 // Fetch the updated or added contact
926 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
927 if (!DBM::is_result($person)) {
937 * @brief Updates the fcontact table
939 * @param array $arr The fcontact data
941 private static function updateFContact($arr)
943 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
944 'request' => $arr["request"], 'nick' => $arr["nick"],
945 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
946 'batch' => $arr["batch"], 'notify' => $arr["notify"],
947 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
948 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
949 'updated' => DateTimeFormat::utcNow()];
951 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
953 dba::update('fcontact', $fields, $condition, true);
957 * @brief get a handle (user@domain.tld) from a given contact id
959 * @param int $contact_id The id in the contact table
960 * @param int $pcontact_id The id in the contact table (Used for the public contact)
962 * @return string the handle
964 private static function handleFromContact($contact_id, $pcontact_id = 0)
968 logger("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, LOGGER_DEBUG);
970 if ($pcontact_id != 0) {
972 "SELECT `addr` FROM `contact` WHERE `id` = %d AND `addr` != ''",
976 if (DBM::is_result($r)) {
977 return strtolower($r[0]["addr"]);
982 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
986 if (DBM::is_result($r)) {
989 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
991 if ($contact['addr'] != "") {
992 $handle = $contact['addr'];
994 $baseurl_start = strpos($contact['url'], '://') + 3;
995 // allows installations in a subdirectory--not sure how Diaspora will handle
996 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
997 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
998 $handle = $contact['nick'].'@'.$baseurl;
1002 return strtolower($handle);
1006 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
1009 * @param mixed $fcontact_guid Hexadecimal string guid
1011 * @return string the contact url or null
1013 public static function urlFromContactGuid($fcontact_guid)
1015 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
1018 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1019 dbesc(NETWORK_DIASPORA),
1020 dbesc($fcontact_guid)
1023 if (DBM::is_result($r)) {
1024 return $r[0]['url'];
1031 * @brief Get a contact id for a given handle
1033 * @todo Move to Friendica\Model\Contact
1035 * @param int $uid The user id
1036 * @param string $handle The handle in the format user@domain.tld
1038 * @return int Contact id
1040 private static function contactByHandle($uid, $handle)
1042 // First do a direct search on the contact table
1044 "SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
1049 if (DBM::is_result($r)) {
1053 * We haven't found it?
1054 * We use another function for it that will possibly create a contact entry.
1056 $cid = Contact::getIdForURL($handle, $uid);
1059 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
1060 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
1062 if (DBM::is_result($r)) {
1068 $handle_parts = explode("@", $handle);
1069 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
1071 "SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
1072 dbesc(NETWORK_DFRN),
1076 if (DBM::is_result($r)) {
1080 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
1085 * @brief Check if posting is allowed for this contact
1087 * @param array $importer Array of the importer user
1088 * @param array $contact The contact that is checked
1089 * @param bool $is_comment Is the check for a comment?
1091 * @return bool is the contact allowed to post?
1093 private static function postAllow($importer, $contact, $is_comment = false)
1096 * Perhaps we were already sharing with this person. Now they're sharing with us.
1097 * That makes us friends.
1098 * Normally this should have handled by getting a request - but this could get lost
1100 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1101 // It is not removed by now. Possibly the code is needed?
1102 //if (!$is_comment && $contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1105 // array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
1106 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1109 // $contact["rel"] = CONTACT_IS_FRIEND;
1110 // logger("defining user ".$contact["nick"]." as friend");
1113 // We don't seem to like that person
1114 if ($contact["blocked"]) {
1115 // Maybe blocked, don't accept.
1117 // We are following this person?
1118 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
1119 // Yes, then it is fine.
1121 // Is it a post to a community?
1122 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && in_array($importer["page-flags"], [PAGE_COMMUNITY, PAGE_PRVGROUP])) {
1125 // Is the message a global user or a comment?
1126 } elseif (($importer["uid"] == 0) || $is_comment) {
1127 // Messages for the global users and comments are always accepted
1135 * @brief Fetches the contact id for a handle and checks if posting is allowed
1137 * @param array $importer Array of the importer user
1138 * @param string $handle The checked handle in the format user@domain.tld
1139 * @param bool $is_comment Is the check for a comment?
1141 * @return array The contact data
1143 private static function allowedContactByHandle($importer, $handle, $is_comment = false)
1145 $contact = self::contactByHandle($importer["uid"], $handle);
1147 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1148 // If a contact isn't found, we accept it anyway if it is a comment
1156 if (!self::postAllow($importer, $contact, $is_comment)) {
1157 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1164 * @brief Does the message already exists on the system?
1166 * @param int $uid The user id
1167 * @param string $guid The guid of the message
1169 * @return int|bool message id if the message already was stored into the system - or false.
1171 private static function messageExists($uid, $guid)
1173 $item = Item::selectFirst($uid, ['id'], ['uid' => $uid, 'guid' => $guid]);
1174 if (DBM::is_result($item)) {
1175 logger("message ".$guid." already exists for user ".$uid);
1183 * @brief Checks for links to posts in a message
1185 * @param array $item The item array
1188 private static function fetchGuid($item)
1190 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1191 preg_replace_callback(
1193 function ($match) use ($item) {
1194 self::fetchGuidSub($match, $item);
1199 preg_replace_callback(
1200 "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1201 function ($match) use ($item) {
1202 self::fetchGuidSub($match, $item);
1209 * @brief Checks for relative /people/* links in an item body to match local
1210 * contacts or prepends the remote host taken from the author link.
1212 * @param string $body The item body to replace links from
1213 * @param string $author_link The author link for missing local contact fallback
1215 * @return string the replaced string
1217 public static function replacePeopleGuid($body, $author_link)
1219 $return = preg_replace_callback(
1220 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1221 function ($match) use ($author_link) {
1223 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1224 // 1 => '0123456789abcdef'
1226 $handle = self::urlFromContactGuid($match[1]);
1229 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1231 // No local match, restoring absolute remote URL from author scheme and host
1232 $author_url = parse_url($author_link);
1233 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1245 * @brief sub function of "fetchGuid" which checks for links in messages
1247 * @param array $match array containing a link that has to be checked for a message link
1248 * @param array $item The item array
1251 private static function fetchGuidSub($match, $item)
1253 if (!self::storeByGuid($match[1], $item["author-link"])) {
1254 self::storeByGuid($match[1], $item["owner-link"]);
1259 * @brief Fetches an item with a given guid from a given server
1261 * @param string $guid the message guid
1262 * @param string $server The server address
1263 * @param int $uid The user id of the user
1265 * @return int the message id of the stored message or false
1267 private static function storeByGuid($guid, $server, $uid = 0)
1269 $serverparts = parse_url($server);
1270 $server = $serverparts["scheme"]."://".$serverparts["host"];
1272 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1274 $msg = self::message($guid, $server);
1280 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1282 // Now call the dispatcher
1283 return self::dispatchPublic($msg);
1287 * @brief Fetches a message from a server
1289 * @param string $guid message guid
1290 * @param string $server The url of the server
1291 * @param int $level Endless loop prevention
1294 * 'message' => The message XML
1295 * 'author' => The author handle
1296 * 'key' => The public key of the author
1298 private static function message($guid, $server, $level = 0)
1304 // This will work for new Diaspora servers and Friendica servers from 3.5
1305 $source_url = $server."/fetch/post/".urlencode($guid);
1307 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1309 $envelope = Network::fetchUrl($source_url);
1311 logger("Envelope was fetched.", LOGGER_DEBUG);
1312 $x = self::verifyMagicEnvelope($envelope);
1314 logger("Envelope could not be verified.", LOGGER_DEBUG);
1316 logger("Envelope was verified.", LOGGER_DEBUG);
1322 // This will work for older Diaspora and Friendica servers
1324 $source_url = $server."/p/".urlencode($guid).".xml";
1325 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1327 $x = Network::fetchUrl($source_url);
1333 $source_xml = XML::parseString($x);
1335 if (!is_object($source_xml)) {
1339 if ($source_xml->post->reshare) {
1340 // Reshare of a reshare - old Diaspora version
1341 logger("Message is a reshare", LOGGER_DEBUG);
1342 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1343 } elseif ($source_xml->getName() == "reshare") {
1344 // Reshare of a reshare - new Diaspora version
1345 logger("Message is a new reshare", LOGGER_DEBUG);
1346 return self::message($source_xml->root_guid, $server, ++$level);
1351 // Fetch the author - for the old and the new Diaspora version
1352 if ($source_xml->post->status_message->diaspora_handle) {
1353 $author = (string)$source_xml->post->status_message->diaspora_handle;
1354 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1355 $author = (string)$source_xml->author;
1358 // If this isn't a "status_message" then quit
1360 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1364 $msg = ["message" => $x, "author" => $author];
1366 $msg["key"] = self::key($msg["author"]);
1372 * @brief Fetches the item record of a given guid
1374 * @param int $uid The user id
1375 * @param string $guid message guid
1376 * @param string $author The handle of the item
1377 * @param array $contact The contact of the item owner
1379 * @return array the item record
1381 private static function parentItem($uid, $guid, $author, $contact)
1383 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1384 'author-name', 'author-link', 'author-avatar',
1385 'owner-name', 'owner-link', 'owner-avatar'];
1386 $condition = ['uid' => $uid, 'guid' => $guid];
1387 $item = Item::selectFirst($uid, $fields, $condition);
1389 if (!DBM::is_result($item)) {
1390 $result = self::storeByGuid($guid, $contact["url"], $uid);
1393 $person = self::personByHandle($author);
1394 $result = self::storeByGuid($guid, $person["url"], $uid);
1398 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1400 $item = Item::selectFirst($uid, $fields, $condition);
1404 if (!DBM::is_result($item)) {
1405 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1408 logger("parent item found: parent: ".$guid." - user: ".$uid);
1414 * @brief returns contact details
1416 * @param array $def_contact The default contact if the person isn't found
1417 * @param array $person The record of the person
1418 * @param int $uid The user id
1421 * 'cid' => contact id
1422 * 'network' => network type
1424 private static function authorContactByUrl($def_contact, $person, $uid)
1426 $condition = ['nurl' => normalise_link($person["url"]), 'uid' => $uid];
1427 $contact = dba::selectFirst('contact', ['id', 'network'], $condition);
1428 if (DBM::is_result($contact)) {
1429 $cid = $contact["id"];
1430 $network = $contact["network"];
1432 $cid = $def_contact["id"];
1433 $network = NETWORK_DIASPORA;
1436 return ["cid" => $cid, "network" => $network];
1440 * @brief Is the profile a hubzilla profile?
1442 * @param string $url The profile link
1444 * @return bool is it a hubzilla server?
1446 public static function isRedmatrix($url)
1448 return(strstr($url, "/channel/"));
1452 * @brief Generate a post link with a given handle and message guid
1454 * @param string $addr The user handle
1455 * @param string $guid message guid
1456 * @param string $parent_guid optional parent guid
1458 * @return string the post link
1460 private static function plink($addr, $guid, $parent_guid = '')
1462 $contact = Contact::getDetailsByAddr($addr);
1466 if ($parent_guid != '') {
1467 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1469 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1473 if ($contact["network"] == NETWORK_DFRN) {
1474 return str_replace("/profile/" . $contact["nick"] . "/", "/display/" . $guid, $contact["url"] . "/");
1477 if (self::isRedmatrix($contact["url"])) {
1478 return $contact["url"] . "/?f=&mid=" . $guid;
1481 if ($parent_guid != '') {
1482 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1484 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1489 * @brief Receives account migration
1491 * @param array $importer Array of the importer user
1492 * @param object $data The message object
1494 * @return bool Success
1496 private static function receiveAccountMigration($importer, $data)
1498 $old_handle = notags(unxmlify($data->author));
1499 $new_handle = notags(unxmlify($data->profile->author));
1500 $signature = notags(unxmlify($data->signature));
1502 $contact = self::contactByHandle($importer["uid"], $old_handle);
1504 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1508 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1511 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1512 $key = self::key($old_handle);
1513 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1514 logger('No valid signature for migration.');
1518 // Update the profile
1519 self::receiveProfile($importer, $data->profile);
1521 // change the technical stuff in contact and gcontact
1522 $data = Probe::uri($new_handle);
1523 if ($data['network'] == NETWORK_PHANTOM) {
1524 logger('Account for '.$new_handle." couldn't be probed.");
1528 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1529 'name' => $data['name'], 'nick' => $data['nick'],
1530 'addr' => $data['addr'], 'batch' => $data['batch'],
1531 'notify' => $data['notify'], 'poll' => $data['poll'],
1532 'network' => $data['network']];
1534 dba::update('contact', $fields, ['addr' => $old_handle]);
1536 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1537 'name' => $data['name'], 'nick' => $data['nick'],
1538 'addr' => $data['addr'], 'connect' => $data['addr'],
1539 'notify' => $data['notify'], 'photo' => $data['photo'],
1540 'server_url' => $data['baseurl'], 'network' => $data['network']];
1542 dba::update('gcontact', $fields, ['addr' => $old_handle]);
1544 logger('Contacts are updated.');
1547 // This is an extreme performance killer
1548 Item::update(['owner-link' => $data["url"]], ['owner-link' => $contact["url"], 'uid' => $importer["uid"]]);
1549 Item::update(['author-link' => $data["url"]], ['author-link' => $contact["url"], 'uid' => $importer["uid"]]);
1551 logger('Items are updated.');
1557 * @brief Processes an account deletion
1559 * @param object $data The message object
1561 * @return bool Success
1563 private static function receiveAccountDeletion($data)
1565 $author = notags(unxmlify($data->author));
1567 $contacts = dba::select('contact', ['id'], ['addr' => $author]);
1568 while ($contact = dba::fetch($contacts)) {
1569 Contact::remove($contact["id"]);
1572 dba::delete('gcontact', ['addr' => $author]);
1574 logger('Removed contacts for ' . $author);
1580 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1582 * @param string $author Author handle
1583 * @param string $guid Message guid
1584 * @param boolean $onlyfound Only return uri when found in the database
1586 * @return string The constructed uri or the one from our database
1588 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1590 $item = Item::selectFirst(0, ['uri'], ['guid' => $guid]);
1591 if (DBM::is_result($item)) {
1592 return $item["uri"];
1593 } elseif (!$onlyfound) {
1594 $contact = Contact::getDetailsByAddr($author, 0);
1595 if (!empty($contact['network'])) {
1596 $prefix = 'urn:X-' . $contact['network'] . ':';
1598 // This fallback should happen most unlikely
1599 $prefix = 'urn:X-dspr:';
1602 $author_parts = explode('@', $author);
1604 return $prefix . $author_parts[1] . ':' . $author_parts[0] . ':'. $guid;
1611 * @brief Fetch the guid from our database with a given uri
1613 * @param string $uri Message uri
1614 * @param string $uid Author handle
1616 * @return string The post guid
1618 private static function getGuidFromUri($uri, $uid)
1620 $item = Item::selectFirst($uid, ['guid'], ['uri' => $uri, 'uid' => $uid]);
1621 if (DBM::is_result($item)) {
1622 return $item["guid"];
1629 * @brief Find the best importer for a comment, like, ...
1631 * @param string $guid The guid of the item
1633 * @return array|boolean the origin owner of that post - or false
1635 private static function importerForGuid($guid)
1637 $item = Item::selectFirst(0, ['uid'], ['origin' => true, 'guid' => $guid]);
1638 if (DBM::is_result($item)) {
1639 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1640 $contact = dba::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1641 if (DBM::is_result($contact)) {
1649 * @brief Processes an incoming comment
1651 * @param array $importer Array of the importer user
1652 * @param string $sender The sender of the message
1653 * @param object $data The message object
1654 * @param string $xml The original XML of the message
1656 * @return int The message id of the generated comment or "false" if there was an error
1658 private static function receiveComment($importer, $sender, $data, $xml)
1660 $author = notags(unxmlify($data->author));
1661 $guid = notags(unxmlify($data->guid));
1662 $parent_guid = notags(unxmlify($data->parent_guid));
1663 $text = unxmlify($data->text);
1665 if (isset($data->created_at)) {
1666 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1668 $created_at = DateTimeFormat::utcNow();
1671 if (isset($data->thread_parent_guid)) {
1672 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1673 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1678 $contact = self::allowedContactByHandle($importer, $sender, true);
1683 $message_id = self::messageExists($importer["uid"], $guid);
1688 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1689 if (!$parent_item) {
1693 $person = self::personByHandle($author);
1694 if (!is_array($person)) {
1695 logger("unable to find author details");
1699 // Fetch the contact id - if we know this contact
1700 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1704 $datarray["uid"] = $importer["uid"];
1705 $datarray["contact-id"] = $author_contact["cid"];
1706 $datarray["network"] = $author_contact["network"];
1708 $datarray["author-link"] = $person["url"];
1709 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1711 $datarray["owner-link"] = $contact["url"];
1712 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1714 $datarray["guid"] = $guid;
1715 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1717 $datarray["type"] = "remote-comment";
1718 $datarray["verb"] = ACTIVITY_POST;
1719 $datarray["gravity"] = GRAVITY_COMMENT;
1721 if ($thr_uri != "") {
1722 $datarray["parent-uri"] = $thr_uri;
1724 $datarray["parent-uri"] = $parent_item["uri"];
1727 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1729 $datarray["protocol"] = PROTOCOL_DIASPORA;
1730 $datarray["source"] = $xml;
1732 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1734 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1736 $body = Markdown::toBBCode($text);
1738 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1740 self::fetchGuid($datarray);
1742 // If we are the origin of the parent we store the original data.
1743 // We notify our followers during the item storage.
1744 if ($parent_item["origin"]) {
1745 $datarray['diaspora_signed_text'] = json_encode($data);
1748 $message_id = Item::insert($datarray);
1750 if ($message_id <= 0) {
1755 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1756 if ($datarray['uid'] == 0) {
1757 Item::distribute($message_id, json_encode($data));
1765 * @brief processes and stores private messages
1767 * @param array $importer Array of the importer user
1768 * @param array $contact The contact of the message
1769 * @param object $data The message object
1770 * @param array $msg Array of the processed message, author handle and key
1771 * @param object $mesg The private message
1772 * @param array $conversation The conversation record to which this message belongs
1774 * @return bool "true" if it was successful
1776 private static function receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation)
1778 $author = notags(unxmlify($data->author));
1779 $guid = notags(unxmlify($data->guid));
1780 $subject = notags(unxmlify($data->subject));
1782 // "diaspora_handle" is the element name from the old version
1783 // "author" is the element name from the new version
1784 if ($mesg->author) {
1785 $msg_author = notags(unxmlify($mesg->author));
1786 } elseif ($mesg->diaspora_handle) {
1787 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1792 $msg_guid = notags(unxmlify($mesg->guid));
1793 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1794 $msg_text = unxmlify($mesg->text);
1795 $msg_created_at = DateTimeFormat::utc(notags(unxmlify($mesg->created_at)));
1797 if ($msg_conversation_guid != $guid) {
1798 logger("message conversation guid does not belong to the current conversation.");
1802 $body = Markdown::toBBCode($msg_text);
1803 $message_uri = $msg_author.":".$msg_guid;
1805 $person = self::personByHandle($msg_author);
1810 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1812 intval($importer["uid"])
1814 if (DBM::is_result($r)) {
1815 logger("duplicate message already delivered.", LOGGER_DEBUG);
1820 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1821 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1822 intval($importer["uid"]),
1824 intval($conversation["id"]),
1825 dbesc($person["name"]),
1826 dbesc($person["photo"]),
1827 dbesc($person["url"]),
1828 intval($contact["id"]),
1833 dbesc($message_uri),
1834 dbesc($author.":".$guid),
1835 dbesc($msg_created_at)
1840 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
1844 "type" => NOTIFY_MAIL,
1845 "notify_flags" => $importer["notify-flags"],
1846 "language" => $importer["language"],
1847 "to_name" => $importer["username"],
1848 "to_email" => $importer["email"],
1849 "uid" =>$importer["uid"],
1850 "item" => ["subject" => $subject, "body" => $body],
1851 "source_name" => $person["name"],
1852 "source_link" => $person["url"],
1853 "source_photo" => $person["thumb"],
1854 "verb" => ACTIVITY_POST,
1861 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1863 * @param array $importer Array of the importer user
1864 * @param array $msg Array of the processed message, author handle and key
1865 * @param object $data The message object
1867 * @return bool Success
1869 private static function receiveConversation($importer, $msg, $data)
1871 $author = notags(unxmlify($data->author));
1872 $guid = notags(unxmlify($data->guid));
1873 $subject = notags(unxmlify($data->subject));
1874 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1875 $participants = notags(unxmlify($data->participants));
1877 $messages = $data->message;
1879 if (!count($messages)) {
1880 logger("empty conversation");
1884 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1889 $conversation = null;
1892 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1893 intval($importer["uid"]),
1897 $conversation = $c[0];
1900 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1901 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1902 intval($importer["uid"]),
1906 dbesc(DateTimeFormat::utcNow()),
1908 dbesc($participants)
1912 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1913 intval($importer["uid"]),
1919 $conversation = $c[0];
1922 if (!$conversation) {
1923 logger("unable to create conversation.");
1927 foreach ($messages as $mesg) {
1928 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1935 * @brief Creates the body for a "like" message
1937 * @param array $contact The contact that send us the "like"
1938 * @param array $parent_item The item array of the parent item
1939 * @param string $guid message guid
1941 * @return string the body
1943 private static function constructLikeBody($contact, $parent_item, $guid)
1945 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
1947 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1948 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1949 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".L10n::t("status")."[/url]";
1951 return sprintf($bodyverb, $ulink, $alink, $plink);
1955 * @brief Creates a XML object for a "like"
1957 * @param array $importer Array of the importer user
1958 * @param array $parent_item The item array of the parent item
1960 * @return string The XML
1962 private static function constructLikeObject($importer, $parent_item)
1964 $objtype = ACTIVITY_OBJ_NOTE;
1965 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1966 $parent_body = $parent_item["body"];
1968 $xmldata = ["object" => ["type" => $objtype,
1970 "id" => $parent_item["uri"],
1973 "content" => $parent_body]];
1975 return XML::fromArray($xmldata, $xml, true);
1979 * @brief Processes "like" messages
1981 * @param array $importer Array of the importer user
1982 * @param string $sender The sender of the message
1983 * @param object $data The message object
1985 * @return int The message id of the generated like or "false" if there was an error
1987 private static function receiveLike($importer, $sender, $data)
1989 $author = notags(unxmlify($data->author));
1990 $guid = notags(unxmlify($data->guid));
1991 $parent_guid = notags(unxmlify($data->parent_guid));
1992 $parent_type = notags(unxmlify($data->parent_type));
1993 $positive = notags(unxmlify($data->positive));
1995 // likes on comments aren't supported by Diaspora - only on posts
1996 // But maybe this will be supported in the future, so we will accept it.
1997 if (!in_array($parent_type, ["Post", "Comment"])) {
2001 $contact = self::allowedContactByHandle($importer, $sender, true);
2006 $message_id = self::messageExists($importer["uid"], $guid);
2011 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2012 if (!$parent_item) {
2016 $person = self::personByHandle($author);
2017 if (!is_array($person)) {
2018 logger("unable to find author details");
2022 // Fetch the contact id - if we know this contact
2023 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2025 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2026 // We would accept this anyhow.
2027 if ($positive == "true") {
2028 $verb = ACTIVITY_LIKE;
2030 $verb = ACTIVITY_DISLIKE;
2035 $datarray["protocol"] = PROTOCOL_DIASPORA;
2037 $datarray["uid"] = $importer["uid"];
2038 $datarray["contact-id"] = $author_contact["cid"];
2039 $datarray["network"] = $author_contact["network"];
2041 $datarray["author-link"] = $person["url"];
2042 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2044 $datarray["owner-link"] = $contact["url"];
2045 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
2047 $datarray["guid"] = $guid;
2048 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2050 $datarray["type"] = "activity";
2051 $datarray["verb"] = $verb;
2052 $datarray["gravity"] = GRAVITY_LIKE;
2053 $datarray["parent-uri"] = $parent_item["uri"];
2055 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2056 $datarray["object"] = self::constructLikeObject($importer, $parent_item);
2058 $datarray["body"] = self::constructLikeBody($contact, $parent_item, $guid);
2060 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2061 if ($parent_item["id"] != $parent_item["parent"]) {
2062 $toplevel = Item::selectFirst($importer["uid"], ['origin'], ['id' => $parent_item["parent"]]);
2063 $origin = $toplevel["origin"];
2065 $origin = $parent_item["origin"];
2068 // If we are the origin of the parent we store the original data.
2069 // We notify our followers during the item storage.
2071 $datarray['diaspora_signed_text'] = json_encode($data);
2074 $message_id = Item::insert($datarray);
2076 if ($message_id <= 0) {
2081 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2082 if ($datarray['uid'] == 0) {
2083 Item::distribute($message_id, json_encode($data));
2091 * @brief Processes private messages
2093 * @param array $importer Array of the importer user
2094 * @param object $data The message object
2096 * @return bool Success?
2098 private static function receiveMessage($importer, $data)
2100 $author = notags(unxmlify($data->author));
2101 $guid = notags(unxmlify($data->guid));
2102 $conversation_guid = notags(unxmlify($data->conversation_guid));
2103 $text = unxmlify($data->text);
2104 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2106 $contact = self::allowedContactByHandle($importer, $author, true);
2111 $conversation = null;
2114 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2115 intval($importer["uid"]),
2116 dbesc($conversation_guid)
2119 $conversation = $c[0];
2121 logger("conversation not available.");
2125 $message_uri = $author.":".$guid;
2127 $person = self::personByHandle($author);
2129 logger("unable to find author details");
2133 $body = Markdown::toBBCode($text);
2135 $body = self::replacePeopleGuid($body, $person["url"]);
2140 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2142 intval($importer["uid"])
2144 if (DBM::is_result($r)) {
2145 logger("duplicate message already delivered.", LOGGER_DEBUG);
2150 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2151 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2152 intval($importer["uid"]),
2154 intval($conversation["id"]),
2155 dbesc($person["name"]),
2156 dbesc($person["photo"]),
2157 dbesc($person["url"]),
2158 intval($contact["id"]),
2159 dbesc($conversation["subject"]),
2163 dbesc($message_uri),
2164 dbesc($author.":".$conversation["guid"]),
2170 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
2175 * @brief Processes participations - unsupported by now
2177 * @param array $importer Array of the importer user
2178 * @param object $data The message object
2180 * @return bool always true
2182 private static function receiveParticipation($importer, $data)
2184 $author = strtolower(notags(unxmlify($data->author)));
2185 $parent_guid = notags(unxmlify($data->parent_guid));
2187 $contact_id = Contact::getIdForURL($author);
2189 logger('Contact not found: '.$author);
2193 $person = self::personByHandle($author);
2194 if (!is_array($person)) {
2195 logger("Person not found: ".$author);
2199 $item = Item::selectFirst(0, ['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2200 if (!DBM::is_result($item)) {
2201 logger('Item not found, no origin or private: '.$parent_guid);
2205 $author_parts = explode('@', $author);
2206 if (isset($author_parts[1])) {
2207 $server = $author_parts[1];
2209 // Should never happen
2213 logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
2215 if (!dba::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2216 dba::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2219 // Send all existing comments and likes to the requesting server
2220 $comments = Item::select(0, ['id', 'verb', 'self'], ['parent' => $item['id']]);
2221 while ($comment = dba::fetch($comments)) {
2222 if ($comment['id'] == $comment['parent']) {
2225 if ($comment['verb'] == ACTIVITY_POST) {
2226 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2228 $cmd = $comment['self'] ? 'like' : 'comment-import';
2230 logger("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, LOGGER_DEBUG);
2231 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2233 dba::close($comments);
2239 * @brief Processes photos - unneeded
2241 * @param array $importer Array of the importer user
2242 * @param object $data The message object
2244 * @return bool always true
2246 private static function receivePhoto($importer, $data)
2248 // There doesn't seem to be a reason for this function,
2249 // since the photo data is transmitted in the status message as well
2254 * @brief Processes poll participations - unssupported
2256 * @param array $importer Array of the importer user
2257 * @param object $data The message object
2259 * @return bool always true
2261 private static function receivePollParticipation($importer, $data)
2263 // We don't support polls by now
2268 * @brief Processes incoming profile updates
2270 * @param array $importer Array of the importer user
2271 * @param object $data The message object
2273 * @return bool Success
2275 private static function receiveProfile($importer, $data)
2277 $author = strtolower(notags(unxmlify($data->author)));
2279 $contact = self::contactByHandle($importer["uid"], $author);
2284 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2285 $image_url = unxmlify($data->image_url);
2286 $birthday = unxmlify($data->birthday);
2287 $gender = unxmlify($data->gender);
2288 $about = Markdown::toBBCode(unxmlify($data->bio));
2289 $location = Markdown::toBBCode(unxmlify($data->location));
2290 $searchable = (unxmlify($data->searchable) == "true");
2291 $nsfw = (unxmlify($data->nsfw) == "true");
2292 $tags = unxmlify($data->tag_string);
2294 $tags = explode("#", $tags);
2297 foreach ($tags as $tag) {
2298 $tag = trim(strtolower($tag));
2304 $keywords = implode(", ", $keywords);
2306 $handle_parts = explode("@", $author);
2307 $nick = $handle_parts[0];
2310 $name = $handle_parts[0];
2313 if (preg_match("|^https?://|", $image_url) === 0) {
2314 $image_url = "http://".$handle_parts[1].$image_url;
2317 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2319 // Generic birthday. We don't know the timezone. The year is irrelevant.
2321 $birthday = str_replace("1000", "1901", $birthday);
2323 if ($birthday != "") {
2324 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2327 // this is to prevent multiple birthday notifications in a single year
2328 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2330 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2331 $birthday = $contact["bd"];
2334 $fields = ['name' => $name, 'location' => $location,
2335 'name-date' => DateTimeFormat::utcNow(),
2336 'about' => $about, 'gender' => $gender,
2337 'addr' => $author, 'nick' => $nick,
2338 'keywords' => $keywords];
2340 if (!empty($birthday)) {
2341 $fields['bd'] = $birthday;
2344 dba::update('contact', $fields, ['id' => $contact['id']]);
2346 $gcontact = ["url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2347 "photo" => $image_url, "name" => $name, "location" => $location,
2348 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2349 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2350 "hide" => !$searchable, "nsfw" => $nsfw];
2352 $gcid = GContact::update($gcontact);
2354 GContact::link($gcid, $importer["uid"], $contact["id"]);
2356 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2362 * @brief Processes incoming friend requests
2364 * @param array $importer Array of the importer user
2365 * @param array $contact The contact that send the request
2368 private static function receiveRequestMakeFriend($importer, $contact)
2372 if ($contact["rel"] == CONTACT_IS_SHARING) {
2375 ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
2376 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2382 * @brief Processes incoming sharing notification
2384 * @param array $importer Array of the importer user
2385 * @param object $data The message object
2387 * @return bool Success
2389 private static function receiveContactRequest($importer, $data)
2391 $author = unxmlify($data->author);
2392 $recipient = unxmlify($data->recipient);
2394 if (!$author || !$recipient) {
2398 // the current protocol version doesn't know these fields
2399 // That means that we will assume their existance
2400 if (isset($data->following)) {
2401 $following = (unxmlify($data->following) == "true");
2406 if (isset($data->sharing)) {
2407 $sharing = (unxmlify($data->sharing) == "true");
2412 $contact = self::contactByHandle($importer["uid"], $author);
2414 // perhaps we were already sharing with this person. Now they're sharing with us.
2415 // That makes us friends.
2418 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2419 self::receiveRequestMakeFriend($importer, $contact);
2421 // refetch the contact array
2422 $contact = self::contactByHandle($importer["uid"], $author);
2424 // If we are now friends, we are sending a share message.
2425 // Normally we needn't to do so, but the first message could have been vanished.
2426 if (in_array($contact["rel"], [CONTACT_IS_FRIEND])) {
2427 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2429 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2430 $ret = self::sendShare($u[0], $contact);
2435 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2436 Contact::removeFollower($importer, $contact);
2441 if (!$following && $sharing && in_array($importer["page-flags"], [PAGE_SOAPBOX, PAGE_NORMAL])) {
2442 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2444 } elseif (!$following && !$sharing) {
2445 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2447 } elseif (!$following && $sharing) {
2448 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2449 } elseif ($following && $sharing) {
2450 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2451 } elseif ($following && !$sharing) {
2452 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2455 $ret = self::personByHandle($author);
2457 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2458 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2462 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2465 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2466 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2467 intval($importer["uid"]),
2468 dbesc($ret["network"]),
2469 dbesc($ret["addr"]),
2470 DateTimeFormat::utcNow(),
2472 dbesc(normalise_link($ret["url"])),
2474 dbesc($ret["name"]),
2475 dbesc($ret["nick"]),
2476 dbesc($ret["photo"]),
2477 dbesc($ret["pubkey"]),
2478 dbesc($ret["notify"]),
2479 dbesc($ret["poll"]),
2484 // find the contact record we just created
2486 $contact_record = self::contactByHandle($importer["uid"], $author);
2488 if (!$contact_record) {
2489 logger("unable to locate newly created contact record.");
2493 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2495 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2497 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2499 if (in_array($importer["page-flags"], [PAGE_NORMAL, PAGE_PRVGROUP])) {
2500 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2502 $hash = random_string().(string)time(); // Generate a confirm_key
2505 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2506 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2507 intval($importer["uid"]),
2508 intval($contact_record["id"]),
2511 dbesc(L10n::t("Sharing notification from Diaspora network")),
2513 dbesc(DateTimeFormat::utcNow())
2516 // automatic friend approval
2518 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2520 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2522 // technically they are sharing with us (CONTACT_IS_SHARING),
2523 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2524 // we are going to change the relationship and make them a follower.
2526 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following) {
2527 $new_relation = CONTACT_IS_FRIEND;
2528 } elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing) {
2529 $new_relation = CONTACT_IS_SHARING;
2531 $new_relation = CONTACT_IS_FOLLOWER;
2535 "UPDATE `contact` SET `rel` = %d,
2543 intval($new_relation),
2544 dbesc(DateTimeFormat::utcNow()),
2545 dbesc(DateTimeFormat::utcNow()),
2546 intval($contact_record["id"])
2549 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2551 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2552 $ret = self::sendShare($u[0], $contact_record);
2554 // Send the profile data, maybe it weren't transmitted before
2555 self::sendProfile($importer["uid"], [$contact_record]);
2563 * @brief Fetches a message with a given guid
2565 * @param string $guid message guid
2566 * @param string $orig_author handle of the original post
2567 * @param string $author handle of the sharer
2569 * @return array The fetched item
2571 public static function originalItem($guid, $orig_author)
2574 logger('Empty guid. Quitting.');
2578 // Do we already have this item?
2579 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2580 'author-name', 'author-link', 'author-avatar'];
2581 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2582 $item = Item::selectFirst(0, $fields, $condition);
2584 if (DBM::is_result($item)) {
2585 logger("reshared message ".$guid." already exists on system.");
2587 // Maybe it is already a reshared item?
2588 // Then refetch the content, if it is a reshare from a reshare.
2589 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2590 if (self::isReshare($item["body"], true)) {
2592 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2593 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2595 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2597 // Add OEmbed and other information to the body
2598 $item["body"] = add_page_info_to_body($item["body"], false, true);
2606 if (!DBM::is_result($item)) {
2607 if (empty($orig_author)) {
2608 logger('Empty author for guid ' . $guid . '. Quitting.');
2612 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2613 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2614 $stored = self::storeByGuid($guid, $server);
2617 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2618 logger("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2619 $stored = self::storeByGuid($guid, $server);
2623 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2624 'author-name', 'author-link', 'author-avatar'];
2625 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2626 $item = Item::selectFirst(0, $fields, $condition);
2628 if (DBM::is_result($item)) {
2629 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2630 if (self::isReshare($item["body"], false)) {
2631 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2632 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2643 * @brief Processes a reshare message
2645 * @param array $importer Array of the importer user
2646 * @param object $data The message object
2647 * @param string $xml The original XML of the message
2649 * @return int the message id
2651 private static function receiveReshare($importer, $data, $xml)
2653 $author = notags(unxmlify($data->author));
2654 $guid = notags(unxmlify($data->guid));
2655 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2656 $root_author = notags(unxmlify($data->root_author));
2657 $root_guid = notags(unxmlify($data->root_guid));
2658 /// @todo handle unprocessed property "provider_display_name"
2659 $public = notags(unxmlify($data->public));
2661 $contact = self::allowedContactByHandle($importer, $author, false);
2666 $message_id = self::messageExists($importer["uid"], $guid);
2671 $original_item = self::originalItem($root_guid, $root_author);
2672 if (!$original_item) {
2676 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2680 $datarray["uid"] = $importer["uid"];
2681 $datarray["contact-id"] = $contact["id"];
2682 $datarray["network"] = NETWORK_DIASPORA;
2684 $datarray["author-link"] = $contact["url"];
2685 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2687 $datarray["owner-link"] = $datarray["author-link"];
2688 $datarray["owner-id"] = $datarray["author-id"];
2690 $datarray["guid"] = $guid;
2691 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2693 $datarray["verb"] = ACTIVITY_POST;
2694 $datarray["gravity"] = GRAVITY_PARENT;
2696 $datarray["protocol"] = PROTOCOL_DIASPORA;
2697 $datarray["source"] = $xml;
2699 $prefix = share_header(
2700 $original_item["author-name"],
2701 $original_item["author-link"],
2702 $original_item["author-avatar"],
2703 $original_item["guid"],
2704 $original_item["created"],
2707 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2709 $datarray["tag"] = $original_item["tag"];
2710 $datarray["app"] = $original_item["app"];
2712 $datarray["plink"] = self::plink($author, $guid);
2713 $datarray["private"] = (($public == "false") ? 1 : 0);
2714 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2716 $datarray["object-type"] = $original_item["object-type"];
2718 self::fetchGuid($datarray);
2719 $message_id = Item::insert($datarray);
2721 self::sendParticipation($contact, $datarray);
2724 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2725 if ($datarray['uid'] == 0) {
2726 Item::distribute($message_id);
2735 * @brief Processes retractions
2737 * @param array $importer Array of the importer user
2738 * @param array $contact The contact of the item owner
2739 * @param object $data The message object
2741 * @return bool success
2743 private static function itemRetraction($importer, $contact, $data)
2745 $author = notags(unxmlify($data->author));
2746 $target_guid = notags(unxmlify($data->target_guid));
2747 $target_type = notags(unxmlify($data->target_type));
2749 $person = self::personByHandle($author);
2750 if (!is_array($person)) {
2751 logger("unable to find author detail for ".$author);
2755 if (empty($contact["url"])) {
2756 $contact["url"] = $person["url"];
2759 // Fetch items that are about to be deleted
2760 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link'];
2762 // When we receive a public retraction, we delete every item that we find.
2763 if ($importer['uid'] == 0) {
2764 $condition = ["`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid];
2766 $condition = ["`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']];
2768 $r = Item::select($importer['uid'], $fields, $condition);
2769 if (!DBM::is_result($r)) {
2770 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2774 while ($item = dba::fetch($r)) {
2775 // Fetch the parent item
2776 $parent = Item::selectFirst(0, ['author-link'], ['id' => $item["parent"]]);
2778 // Only delete it if the parent author really fits
2779 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2780 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2784 Item::delete(['id' => $item['id']]);
2786 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2793 * @brief Receives retraction messages
2795 * @param array $importer Array of the importer user
2796 * @param string $sender The sender of the message
2797 * @param object $data The message object
2799 * @return bool Success
2801 private static function receiveRetraction($importer, $sender, $data)
2803 $target_type = notags(unxmlify($data->target_type));
2805 $contact = self::contactByHandle($importer["uid"], $sender);
2806 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2807 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2811 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2813 switch ($target_type) {
2818 case "StatusMessage":
2819 return self::itemRetraction($importer, $contact, $data);
2821 case "PollParticipation":
2823 // Currently unsupported
2827 logger("Unknown target type ".$target_type);
2834 * @brief Receives status messages
2836 * @param array $importer Array of the importer user
2837 * @param object $data The message object
2838 * @param string $xml The original XML of the message
2840 * @return int The message id of the newly created item
2842 private static function receiveStatusMessage($importer, $data, $xml)
2844 $author = notags(unxmlify($data->author));
2845 $guid = notags(unxmlify($data->guid));
2846 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2847 $public = notags(unxmlify($data->public));
2848 $text = unxmlify($data->text);
2849 $provider_display_name = notags(unxmlify($data->provider_display_name));
2851 $contact = self::allowedContactByHandle($importer, $author, false);
2856 $message_id = self::messageExists($importer["uid"], $guid);
2862 if ($data->location) {
2863 foreach ($data->location->children() as $fieldname => $data) {
2864 $address[$fieldname] = notags(unxmlify($data));
2868 $body = Markdown::toBBCode($text);
2872 // Attach embedded pictures to the body
2874 foreach ($data->photo as $photo) {
2875 $body = "[img]".unxmlify($photo->remote_photo_path).
2876 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2879 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2881 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2883 // Add OEmbed and other information to the body
2884 if (!self::isRedmatrix($contact["url"])) {
2885 $body = add_page_info_to_body($body, false, true);
2889 /// @todo enable support for polls
2890 //if ($data->poll) {
2891 // foreach ($data->poll AS $poll)
2896 /// @todo enable support for events
2898 $datarray["uid"] = $importer["uid"];
2899 $datarray["contact-id"] = $contact["id"];
2900 $datarray["network"] = NETWORK_DIASPORA;
2902 $datarray["author-link"] = $contact["url"];
2903 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2905 $datarray["owner-link"] = $datarray["author-link"];
2906 $datarray["owner-id"] = $datarray["author-id"];
2908 $datarray["guid"] = $guid;
2909 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2911 $datarray["verb"] = ACTIVITY_POST;
2912 $datarray["gravity"] = GRAVITY_PARENT;
2914 $datarray["protocol"] = PROTOCOL_DIASPORA;
2915 $datarray["source"] = $xml;
2917 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2919 if ($provider_display_name != "") {
2920 $datarray["app"] = $provider_display_name;
2923 $datarray["plink"] = self::plink($author, $guid);
2924 $datarray["private"] = (($public == "false") ? 1 : 0);
2925 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2927 if (isset($address["address"])) {
2928 $datarray["location"] = $address["address"];
2931 if (isset($address["lat"]) && isset($address["lng"])) {
2932 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2935 self::fetchGuid($datarray);
2936 $message_id = Item::insert($datarray);
2938 self::sendParticipation($contact, $datarray);
2941 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2942 if ($datarray['uid'] == 0) {
2943 Item::distribute($message_id);
2951 /* ************************************************************************************** *
2952 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2953 * ************************************************************************************** */
2956 * @brief returnes the handle of a contact
2958 * @param array $contact contact array
2960 * @return string the handle in the format user@domain.tld
2962 private static function myHandle($contact)
2964 if ($contact["addr"] != "") {
2965 return $contact["addr"];
2968 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2969 // So - just in case - we build the the address here.
2970 if ($contact["nickname"] != "") {
2971 $nick = $contact["nickname"];
2973 $nick = $contact["nick"];
2976 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
2981 * @brief Creates the data for a private message in the new format
2983 * @param string $msg The message that is to be transmitted
2984 * @param array $user The record of the sender
2985 * @param array $contact Target of the communication
2986 * @param string $prvkey The private key of the sender
2987 * @param string $pubkey The public key of the receiver
2989 * @return string The encrypted data
2991 public static function encodePrivateData($msg, $user, $contact, $prvkey, $pubkey)
2993 logger("Message: ".$msg, LOGGER_DATA);
2995 // without a public key nothing will work
2997 logger("pubkey missing: contact id: ".$contact["id"]);
3001 $aes_key = openssl_random_pseudo_bytes(32);
3002 $b_aes_key = base64_encode($aes_key);
3003 $iv = openssl_random_pseudo_bytes(16);
3004 $b_iv = base64_encode($iv);
3006 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3008 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3010 $encrypted_key_bundle = "";
3011 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3013 $json_object = json_encode(
3014 ["aes_key" => base64_encode($encrypted_key_bundle),
3015 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3018 return $json_object;
3022 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3024 * @param string $msg The message that is to be transmitted
3025 * @param array $user The record of the sender
3027 * @return string The envelope
3029 public static function buildMagicEnvelope($msg, $user)
3031 $b64url_data = base64url_encode($msg);
3032 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3034 $key_id = base64url_encode(self::myHandle($user));
3035 $type = "application/xml";
3036 $encoding = "base64url";
3037 $alg = "RSA-SHA256";
3038 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
3040 // Fallback if the private key wasn't transmitted in the expected field
3041 if ($user['uprvkey'] == "") {
3042 $user['uprvkey'] = $user['prvkey'];
3045 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3046 $sig = base64url_encode($signature);
3048 $xmldata = ["me:env" => ["me:data" => $data,
3049 "@attributes" => ["type" => $type],
3050 "me:encoding" => $encoding,
3053 "@attributes2" => ["key_id" => $key_id]]];
3055 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3057 return XML::fromArray($xmldata, $xml, false, $namespaces);
3061 * @brief Create the envelope for a message
3063 * @param string $msg The message that is to be transmitted
3064 * @param array $user The record of the sender
3065 * @param array $contact Target of the communication
3066 * @param string $prvkey The private key of the sender
3067 * @param string $pubkey The public key of the receiver
3068 * @param bool $public Is the message public?
3070 * @return string The message that will be transmitted to other servers
3072 public static function buildMessage($msg, $user, $contact, $prvkey, $pubkey, $public = false)
3074 // The message is put into an envelope with the sender's signature
3075 $envelope = self::buildMagicEnvelope($msg, $user);
3077 // Private messages are put into a second envelope, encrypted with the receivers public key
3079 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3086 * @brief Creates a signature for a message
3088 * @param array $owner the array of the owner of the message
3089 * @param array $message The message that is to be signed
3091 * @return string The signature
3093 private static function signature($owner, $message)
3096 unset($sigmsg["author_signature"]);
3097 unset($sigmsg["parent_author_signature"]);
3099 $signed_text = implode(";", $sigmsg);
3101 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3105 * @brief Transmit a message to a target server
3107 * @param array $owner the array of the item owner
3108 * @param array $contact Target of the communication
3109 * @param string $envelope The message that is to be transmitted
3110 * @param bool $public_batch Is it a public post?
3111 * @param bool $queue_run Is the transmission called from the queue?
3112 * @param string $guid message guid
3114 * @return int Result of the transmission
3116 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
3120 $enabled = intval(Config::get("system", "diaspora_enabled"));
3125 $logid = random_string(4);
3127 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3129 // We always try to use the data from the fcontact table.
3130 // This is important for transmitting data to Friendica servers.
3131 if (!empty($contact['addr'])) {
3132 $fcontact = self::personByHandle($contact['addr']);
3133 if (!empty($fcontact)) {
3134 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3139 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3143 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3145 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3148 if (!intval(Config::get("system", "diaspora_test"))) {
3149 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3151 Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3152 $return_code = $a->get_curl_code();
3154 logger("test_mode");
3159 logger("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3161 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3162 if (!$no_queue && ($contact['contact-type'] != ACCOUNT_TYPE_RELAY)) {
3163 logger("queue message");
3164 // queue message for redelivery
3165 Queue::add($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3168 // The message could not be delivered. We mark the contact as "dead"
3169 Contact::markForArchival($contact);
3170 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3171 // We successfully delivered a message, the contact is alive
3172 Contact::unmarkForArchival($contact);
3175 return $return_code ? $return_code : -1;
3180 * @brief Build the post xml
3182 * @param string $type The message type
3183 * @param array $message The message data
3185 * @return string The post XML
3187 public static function buildPostXml($type, $message)
3189 $data = [$type => $message];
3191 return XML::fromArray($data, $xml);
3195 * @brief Builds and transmit messages
3197 * @param array $owner the array of the item owner
3198 * @param array $contact Target of the communication
3199 * @param string $type The message type
3200 * @param array $message The message data
3201 * @param bool $public_batch Is it a public post?
3202 * @param string $guid message guid
3203 * @param bool $spool Should the transmission be spooled or transmitted?
3205 * @return int Result of the transmission
3207 private static function buildAndTransmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3209 $msg = self::buildPostXml($type, $message);
3211 logger('message: '.$msg, LOGGER_DATA);
3212 logger('send guid '.$guid, LOGGER_DEBUG);
3214 // Fallback if the private key wasn't transmitted in the expected field
3215 if ($owner['uprvkey'] == "") {
3216 $owner['uprvkey'] = $owner['prvkey'];
3219 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3222 Queue::add($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3225 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3228 logger("guid: ".$guid." result ".$return_code, LOGGER_DEBUG);
3230 return $return_code;
3234 * @brief sends a participation (Used to get all further updates)
3236 * @param array $contact Target of the communication
3237 * @param array $item Item array
3239 * @return int The result of the transmission
3241 private static function sendParticipation($contact, $item)
3243 // Don't send notifications for private postings
3244 if ($item['private']) {
3248 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3250 $result = Cache::get($cachekey);
3251 if (!is_null($result)) {
3255 // Fetch some user id to have a valid handle to transmit the participation.
3256 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3257 // If the item belongs to a user, we take this user id.
3258 if ($item['uid'] == 0) {
3259 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3260 $first_user = dba::selectFirst('user', ['uid'], $condition);
3261 $owner = User::getOwnerDataById($first_user['uid']);
3263 $owner = User::getOwnerDataById($item['uid']);
3266 $author = self::myHandle($owner);
3268 $message = ["author" => $author,
3269 "guid" => get_guid(32),
3270 "parent_type" => "Post",
3271 "parent_guid" => $item["guid"]];
3273 logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
3275 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3276 Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
3278 return self::buildAndTransmit($owner, $contact, "participation", $message);
3282 * @brief sends an account migration
3284 * @param array $owner the array of the item owner
3285 * @param array $contact Target of the communication
3286 * @param int $uid User ID
3288 * @return int The result of the transmission
3290 public static function sendAccountMigration($owner, $contact, $uid)
3292 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3293 $profile = self::createProfileData($uid);
3295 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3296 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3298 $message = ["author" => $old_handle,
3299 "profile" => $profile,
3300 "signature" => $signature];
3302 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3304 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3308 * @brief Sends a "share" message
3310 * @param array $owner the array of the item owner
3311 * @param array $contact Target of the communication
3313 * @return int The result of the transmission
3315 public static function sendShare($owner, $contact)
3318 * @todo support the different possible combinations of "following" and "sharing"
3319 * Currently, Diaspora only interprets the "sharing" field
3321 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3325 switch ($contact["rel"]) {
3326 case CONTACT_IS_FRIEND:
3329 case CONTACT_IS_SHARING:
3332 case CONTACT_IS_FOLLOWER:
3338 $message = ["author" => self::myHandle($owner),
3339 "recipient" => $contact["addr"],
3340 "following" => "true",
3341 "sharing" => "true"];
3343 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3345 return self::buildAndTransmit($owner, $contact, "contact", $message);
3349 * @brief sends an "unshare"
3351 * @param array $owner the array of the item owner
3352 * @param array $contact Target of the communication
3354 * @return int The result of the transmission
3356 public static function sendUnshare($owner, $contact)
3358 $message = ["author" => self::myHandle($owner),
3359 "recipient" => $contact["addr"],
3360 "following" => "false",
3361 "sharing" => "false"];
3363 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3365 return self::buildAndTransmit($owner, $contact, "contact", $message);
3369 * @brief Checks a message body if it is a reshare
3371 * @param string $body The message body that is to be check
3372 * @param bool $complete Should it be a complete check or a simple check?
3374 * @return array|bool Reshare details or "false" if no reshare
3376 public static function isReshare($body, $complete = true)
3378 $body = trim($body);
3380 // Skip if it isn't a pure repeated messages
3381 // Does it start with a share?
3382 if ((strpos($body, "[share") > 0) && $complete) {
3386 // Does it end with a share?
3387 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3391 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3392 // Skip if there is no shared message in there
3393 if ($body == $attributes) {
3397 // If we don't do the complete check we quit here
3400 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3401 if ($matches[1] != "") {
3402 $guid = $matches[1];
3405 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3406 if ($matches[1] != "") {
3407 $guid = $matches[1];
3410 if (($guid != "") && $complete) {
3411 $condition = ['guid' => $guid, 'network' => [NETWORK_DFRN, NETWORK_DIASPORA]];
3412 $item = Item::selectFirst(0, ['contact-id'], $condition);
3413 if (DBM::is_result($item)) {
3415 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3416 $ret["root_guid"] = $guid;
3418 } elseif ($complete) {
3419 // We are resharing something that isn't a DFRN or Diaspora post.
3420 // So we have to return "false" on "$complete" to not trigger a reshare.
3423 } elseif (($guid == "") && $complete) {
3427 $ret["root_guid"] = $guid;
3430 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3431 if ($matches[1] != "") {
3432 $profile = $matches[1];
3435 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3436 if ($matches[1] != "") {
3437 $profile = $matches[1];
3442 if ($profile != "") {
3443 if (Contact::getIdForURL($profile)) {
3444 $author = Contact::getDetailsByURL($profile);
3445 $ret["root_handle"] = $author['addr'];
3449 if (empty($ret) && !$complete) {
3457 * @brief Create an event array
3459 * @param integer $event_id The id of the event
3461 * @return array with event data
3463 private static function buildEvent($event_id)
3465 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3466 if (!DBM::is_result($r)) {
3474 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3475 if (!DBM::is_result($r)) {
3481 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3482 if (!DBM::is_result($r)) {
3488 $eventdata['author'] = self::myHandle($owner);
3490 if ($event['guid']) {
3491 $eventdata['guid'] = $event['guid'];
3494 $mask = DateTimeFormat::ATOM;
3496 /// @todo - establish "all day" events in Friendica
3497 $eventdata["all_day"] = "false";
3499 if (!$event['adjust']) {
3500 $eventdata['timezone'] = $user['timezone'];
3502 if ($eventdata['timezone'] == "") {
3503 $eventdata['timezone'] = 'UTC';
3507 if ($event['start']) {
3508 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3510 if ($event['finish'] && !$event['nofinish']) {
3511 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3513 if ($event['summary']) {
3514 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3516 if ($event['desc']) {
3517 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3519 if ($event['location']) {
3520 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3521 $coord = Map::getCoordinates($event['location']);
3524 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3525 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3526 $location["lat"] = $coord['lat'];
3527 $location["lng"] = $coord['lon'];
3529 $location["lat"] = 0;
3530 $location["lng"] = 0;
3532 $eventdata['location'] = $location;
3539 * @brief Create a post (status message or reshare)
3541 * @param array $item The item that will be exported
3542 * @param array $owner the array of the item owner
3545 * 'type' -> Message type ("status_message" or "reshare")
3546 * 'message' -> Array of XML elements of the status
3548 public static function buildStatus($item, $owner)
3550 $cachekey = "diaspora:buildStatus:".$item['guid'];
3552 $result = Cache::get($cachekey);
3553 if (!is_null($result)) {
3557 $myaddr = self::myHandle($owner);
3559 $public = (($item["private"]) ? "false" : "true");
3561 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3563 // Detect a share element and do a reshare
3564 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3565 $message = ["author" => $myaddr,
3566 "guid" => $item["guid"],
3567 "created_at" => $created,
3568 "root_author" => $ret["root_handle"],
3569 "root_guid" => $ret["root_guid"],
3570 "provider_display_name" => $item["app"],
3571 "public" => $public];
3575 $title = $item["title"];
3576 $body = $item["body"];
3578 if ($item['author-link'] != $item['owner-link']) {
3579 require_once 'mod/share.php';
3580 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3581 "", $item['created'], $item['plink']) . $body . '[/share]';
3584 // convert to markdown
3585 $body = html_entity_decode(BBCode::toMarkdown($body));
3588 if (strlen($title)) {
3589 $body = "## ".html_entity_decode($title)."\n\n".$body;
3592 if ($item["attach"]) {
3593 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3595 $body .= "\n".L10n::t("Attachments:")."\n";
3596 foreach ($matches as $mtch) {
3597 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3604 if ($item["location"] != "")
3605 $location["address"] = $item["location"];
3607 if ($item["coord"] != "") {
3608 $coord = explode(" ", $item["coord"]);
3609 $location["lat"] = $coord[0];
3610 $location["lng"] = $coord[1];
3613 $message = ["author" => $myaddr,
3614 "guid" => $item["guid"],
3615 "created_at" => $created,
3616 "public" => $public,
3618 "provider_display_name" => $item["app"],
3619 "location" => $location];
3621 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3622 if (!isset($location["lat"]) || !isset($location["lng"])) {
3623 unset($message["location"]);
3626 if ($item['event-id'] > 0) {
3627 $event = self::buildEvent($item['event-id']);
3628 if (count($event)) {
3629 $message['event'] = $event;
3631 if (!empty($event['location']['address']) &&
3632 !empty($event['location']['lat']) &&
3633 !empty($event['location']['lng'])) {
3634 $message['location'] = $event['location'];
3637 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3638 // $message['text'] = '';
3642 $type = "status_message";
3645 $msg = ["type" => $type, "message" => $message];
3647 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3653 * @brief Sends a post
3655 * @param array $item The item that will be exported
3656 * @param array $owner the array of the item owner
3657 * @param array $contact Target of the communication
3658 * @param bool $public_batch Is it a public post?
3660 * @return int The result of the transmission
3662 public static function sendStatus($item, $owner, $contact, $public_batch = false)
3664 $status = self::buildStatus($item, $owner);
3666 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3670 * @brief Creates a "like" object
3672 * @param array $item The item that will be exported
3673 * @param array $owner the array of the item owner
3675 * @return array The data for a "like"
3677 private static function constructLike($item, $owner)
3679 $parent = Item::selectFirst(0, ['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3680 if (!DBM::is_result($parent)) {
3684 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3686 if ($item['verb'] === ACTIVITY_LIKE) {
3688 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3689 $positive = "false";
3692 return(["author" => self::myHandle($owner),
3693 "guid" => $item["guid"],
3694 "parent_guid" => $parent["guid"],
3695 "parent_type" => $target_type,
3696 "positive" => $positive,
3697 "author_signature" => ""]);
3701 * @brief Creates an "EventParticipation" object
3703 * @param array $item The item that will be exported
3704 * @param array $owner the array of the item owner
3706 * @return array The data for an "EventParticipation"
3708 private static function constructAttend($item, $owner)
3710 $parent = Item::selectFirst(0, ['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3711 if (!DBM::is_result($parent)) {
3715 switch ($item['verb']) {
3716 case ACTIVITY_ATTEND:
3717 $attend_answer = 'accepted';
3719 case ACTIVITY_ATTENDNO:
3720 $attend_answer = 'declined';
3722 case ACTIVITY_ATTENDMAYBE:
3723 $attend_answer = 'tentative';
3726 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3730 return(["author" => self::myHandle($owner),
3731 "guid" => $item["guid"],
3732 "parent_guid" => $parent["guid"],
3733 "status" => $attend_answer,
3734 "author_signature" => ""]);
3738 * @brief Creates the object for a comment
3740 * @param array $item The item that will be exported
3741 * @param array $owner the array of the item owner
3743 * @return array The data for a comment
3745 private static function constructComment($item, $owner)
3747 $cachekey = "diaspora:constructComment:".$item['guid'];
3749 $result = Cache::get($cachekey);
3750 if (!is_null($result)) {
3754 $parent = Item::selectFirst(0, ['guid'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3755 if (!DBM::is_result($parent)) {
3759 $text = html_entity_decode(BBCode::toMarkdown($item["body"]));
3760 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3762 $comment = ["author" => self::myHandle($owner),
3763 "guid" => $item["guid"],
3764 "created_at" => $created,
3765 "parent_guid" => $parent["guid"],
3767 "author_signature" => ""];
3769 // Send the thread parent guid only if it is a threaded comment
3770 if ($item['thr-parent'] != $item['parent-uri']) {
3771 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3774 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3780 * @brief Send a like or a comment
3782 * @param array $item The item that will be exported
3783 * @param array $owner the array of the item owner
3784 * @param array $contact Target of the communication
3785 * @param bool $public_batch Is it a public post?
3787 * @return int The result of the transmission
3789 public static function sendFollowup($item, $owner, $contact, $public_batch = false)
3791 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3792 $message = self::constructAttend($item, $owner);
3793 $type = "event_participation";
3794 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3795 $message = self::constructLike($item, $owner);
3798 $message = self::constructComment($item, $owner);
3806 $message["author_signature"] = self::signature($owner, $message);
3808 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3812 * @brief Creates a message from a signature record entry
3814 * @param array $item The item that will be exported
3815 * @param array $signature The entry of the "sign" record
3817 * @return string The message
3819 private static function messageFromSignature($item, $signature)
3821 // Split the signed text
3822 $signed_parts = explode(";", $signature['signed_text']);
3824 if ($item["deleted"]) {
3825 $message = ["author" => $signature['signer'],
3826 "target_guid" => $signed_parts[0],
3827 "target_type" => $signed_parts[1]];
3828 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3829 $message = ["author" => $signed_parts[4],
3830 "guid" => $signed_parts[1],
3831 "parent_guid" => $signed_parts[3],
3832 "parent_type" => $signed_parts[2],
3833 "positive" => $signed_parts[0],
3834 "author_signature" => $signature['signature'],
3835 "parent_author_signature" => ""];
3837 // Remove the comment guid
3838 $guid = array_shift($signed_parts);
3840 // Remove the parent guid
3841 $parent_guid = array_shift($signed_parts);
3843 // Remove the handle
3844 $handle = array_pop($signed_parts);
3846 // Glue the parts together
3847 $text = implode(";", $signed_parts);
3849 $message = ["author" => $handle,
3851 "parent_guid" => $parent_guid,
3852 "text" => implode(";", $signed_parts),
3853 "author_signature" => $signature['signature'],
3854 "parent_author_signature" => ""];
3860 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3862 * @param array $item The item that will be exported
3863 * @param array $owner the array of the item owner
3864 * @param array $contact Target of the communication
3865 * @param bool $public_batch Is it a public post?
3867 * @return int The result of the transmission
3869 public static function sendRelay($item, $owner, $contact, $public_batch = false)
3871 if ($item["deleted"]) {
3872 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3873 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3879 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3881 // fetch the original signature
3884 "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3889 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3895 // Old way - is used by the internal Friendica functions
3896 /// @todo Change all signatur storing functions to the new format
3897 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
3898 $message = self::messageFromSignature($item, $signature);
3900 $msg = json_decode($signature['signed_text'], true);
3903 if (is_array($msg)) {
3904 foreach ($msg as $field => $data) {
3905 if (!$item["deleted"]) {
3906 if ($field == "diaspora_handle") {
3909 if ($field == "target_type") {
3910 $field = "parent_type";
3914 $message[$field] = $data;
3917 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3921 $message["parent_author_signature"] = self::signature($owner, $message);
3923 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3925 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3929 * @brief Sends a retraction (deletion) of a message, like or comment
3931 * @param array $item The item that will be exported
3932 * @param array $owner the array of the item owner
3933 * @param array $contact Target of the communication
3934 * @param bool $public_batch Is it a public post?
3935 * @param bool $relay Is the retraction transmitted from a relay?
3937 * @return int The result of the transmission
3939 public static function sendRetraction($item, $owner, $contact, $public_batch = false, $relay = false)
3941 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3943 $msg_type = "retraction";
3945 if ($item['id'] == $item['parent']) {
3946 $target_type = "Post";
3947 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3948 $target_type = "Like";
3950 $target_type = "Comment";
3953 $message = ["author" => $itemaddr,
3954 "target_guid" => $item['guid'],
3955 "target_type" => $target_type];
3957 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3959 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3963 * @brief Sends a mail
3965 * @param array $item The item that will be exported
3966 * @param array $owner The owner
3967 * @param array $contact Target of the communication
3969 * @return int The result of the transmission
3971 public static function sendMail($item, $owner, $contact)
3973 $myaddr = self::myHandle($owner);
3976 "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3977 intval($item["convid"]),
3978 intval($item["uid"])
3981 if (!DBM::is_result($r)) {
3982 logger("conversation not found.");
3988 "author" => $cnv["creator"],
3989 "guid" => $cnv["guid"],
3990 "subject" => $cnv["subject"],
3991 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3992 "participants" => $cnv["recips"]
3995 $body = BBCode::toMarkdown($item["body"]);
3996 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3999 "author" => $myaddr,
4000 "guid" => $item["guid"],
4001 "conversation_guid" => $cnv["guid"],
4003 "created_at" => $created,
4006 if ($item["reply"]) {
4011 "author" => $cnv["creator"],
4012 "guid" => $cnv["guid"],
4013 "subject" => $cnv["subject"],
4014 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4015 "participants" => $cnv["recips"],
4018 $type = "conversation";
4021 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4025 * @brief Split a name into first name and last name
4027 * @param string $name The name
4029 * @return array The array with "first" and "last"
4031 public static function splitName($name) {
4032 $name = trim($name);
4034 // Is the name longer than 64 characters? Then cut the rest of it.
4035 if (strlen($name) > 64) {
4036 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4037 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4039 $name = substr($name, 0, 64);
4043 // Take the first word as first name
4044 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4045 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4046 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4047 return ['first' => $first, 'last' => $last];
4050 // Take the last word as last name
4051 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4052 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4054 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4055 return ['first' => $first, 'last' => $last];
4058 // Take the first 32 characters if there is no space in the first 32 characters
4059 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4060 $first = substr($name, 0, 32);
4061 $last = substr($name, 32);
4062 return ['first' => $first, 'last' => $last];
4065 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4066 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4068 // Check if the last name is longer than 32 characters
4069 if (strlen($last) > 32) {
4070 if (strpos($last, ' ') <= 32) {
4071 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4073 $last = substr($last, 0, 32);
4077 return ['first' => $first, 'last' => $last];
4081 * @brief Create profile data
4083 * @param int $uid The user id
4085 * @return array The profile data
4087 private static function createProfileData($uid)
4090 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4092 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4093 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4094 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4103 $handle = $profile["addr"];
4105 $split_name = self::splitName($profile['name']);
4106 $first = $split_name['first'];
4107 $last = $split_name['last'];
4109 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4110 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4111 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4112 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4118 if ($searchable === 'true') {
4121 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4122 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4126 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4129 $about = $profile['about'];
4130 $about = strip_tags(BBCode::convert($about));
4132 $location = Profile::formatLocation($profile);
4134 if ($profile['pub_keywords']) {
4135 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4136 $kw = str_replace(' ', ' ', $kw);
4137 $arr = explode(' ', $profile['pub_keywords']);
4139 for ($x = 0; $x < 5; $x ++) {
4140 if (trim($arr[$x])) {
4141 $tags .= '#'. trim($arr[$x]) .' ';
4146 $tags = trim($tags);
4149 return ["author" => $handle,
4150 "first_name" => $first,
4151 "last_name" => $last,
4152 "image_url" => $large,
4153 "image_url_medium" => $medium,
4154 "image_url_small" => $small,
4156 "gender" => $profile['gender'],
4158 "location" => $location,
4159 "searchable" => $searchable,
4161 "tag_string" => $tags];
4165 * @brief Sends profile data
4167 * @param int $uid The user id
4168 * @param bool $recips optional, default false
4171 public static function sendProfile($uid, $recips = false)
4177 $owner = User::getOwnerDataById($uid);
4184 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4185 AND `uid` = %d AND `rel` != %d",
4186 dbesc(NETWORK_DIASPORA),
4188 intval(CONTACT_IS_SHARING)
4196 $message = self::createProfileData($uid);
4198 foreach ($recips as $recip) {
4199 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4200 self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4205 * @brief Stores the signature for likes that are created on our system
4207 * @param array $contact The contact array of the "like"
4208 * @param int $post_id The post id of the "like"
4210 * @return bool Success
4212 public static function storeLikeSignature($contact, $post_id)
4214 // Is the contact the owner? Then fetch the private key
4215 if (!$contact['self'] || ($contact['uid'] == 0)) {
4216 logger("No owner post, so not storing signature", LOGGER_DEBUG);
4220 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4221 if (!DBM::is_result($r)) {
4225 $contact["uprvkey"] = $r[0]['prvkey'];
4227 $item = Item::selectFirst(0, [], ['id' => $post_id]);
4228 if (!DBM::is_result($item)) {
4232 if (!in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4236 $message = self::constructLike($item, $contact);
4237 if ($message === false) {
4241 $message["author_signature"] = self::signature($contact, $message);
4244 * Now store the signature more flexible to dynamically support new fields.
4245 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4247 dba::insert('sign', ['iid' => $post_id, 'signed_text' => json_encode($message)]);
4249 logger('Stored diaspora like signature');
4254 * @brief Stores the signature for comments that are created on our system
4256 * @param array $item The item array of the comment
4257 * @param array $contact The contact array of the item owner
4258 * @param string $uprvkey The private key of the sender
4259 * @param int $message_id The message id of the comment
4261 * @return bool Success
4263 public static function storeCommentSignature($item, $contact, $uprvkey, $message_id)
4265 if ($uprvkey == "") {
4266 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4270 $contact["uprvkey"] = $uprvkey;
4272 $message = self::constructComment($item, $contact);
4273 if ($message === false) {
4277 $message["author_signature"] = self::signature($contact, $message);
4280 * Now store the signature more flexible to dynamically support new fields.
4281 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4283 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($message)]);
4285 logger('Stored diaspora comment signature');