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\DBA;
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\Map;
33 use Friendica\Util\Network;
34 use Friendica\Util\XML;
37 require_once 'include/dba.php';
38 require_once 'include/items.php';
41 * @brief This class contain functions to create and send Diaspora XML files
47 * @brief Return a list of relay servers
49 * The list contains not only the official relays but also servers that we serve directly
51 * @param integer $item_id The id of the item that is sent
52 * @param array $contacts The previously fetched contacts
54 * @return array of relay servers
56 public static function relayList($item_id, array $contacts = [])
60 // Fetching relay servers
61 $serverdata = Config::get("system", "relay_server");
63 if (!empty($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(['parent'], ['id' => $item_id]);
73 if (!DBA::isResult($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' => Contact::ACCOUNT_TYPE_RELAY];
148 $contact = DBA::selectFirst('contact', $fields, $condition);
150 if (DBA::isResult($contact)) {
151 if ($contact['archive'] || $contact['blocked']) {
156 self::setRelayContact($server_url);
158 $contact = DBA::selectFirst('contact', $fields, $condition);
159 if (DBA::isResult($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, array $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::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' => Contact::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, array $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(array $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(array $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" => Contact::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(array $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 (DBA::isResult($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 (!DBA::isResult($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 (!DBA::isResult($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 (DBA::isResult($r)) {
977 return strtolower($r[0]["addr"]);
982 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
986 if (DBA::isResult($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 DBA::escape(NETWORK_DIASPORA),
1020 DBA::escape($fcontact_guid)
1023 if (DBA::isResult($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 $cid = Contact::getIdForURL($handle, $uid);
1044 $handle_parts = explode("@", $handle);
1045 $nurl_sql = "%%://" . $handle_parts[1] . "%%/profile/" . $handle_parts[0];
1046 $cid = Contact::getIdForURL($nurl_sql, $uid);
1050 logger("Haven't found a contact for user " . $uid . " and handle " . $handle, LOGGER_DEBUG);
1054 $contact = dba::selectFirst('contact', [], ['id' => $cid]);
1055 if (!DBA::isResult($contact)) {
1056 // This here shouldn't happen at all
1057 logger("Haven't found a contact for user " . $uid . " and handle " . $handle, LOGGER_DEBUG);
1065 * @brief Check if posting is allowed for this contact
1067 * @param array $importer Array of the importer user
1068 * @param array $contact The contact that is checked
1069 * @param bool $is_comment Is the check for a comment?
1071 * @return bool is the contact allowed to post?
1073 private static function postAllow(array $importer, array $contact, $is_comment = false)
1076 * Perhaps we were already sharing with this person. Now they're sharing with us.
1077 * That makes us friends.
1078 * Normally this should have handled by getting a request - but this could get lost
1080 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1081 // It is not removed by now. Possibly the code is needed?
1082 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(Contact::PAGE_FREELOVE))) {
1085 // array('rel' => Contact::FRIEND, 'writable' => true),
1086 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1089 // $contact["rel"] = Contact::FRIEND;
1090 // logger("defining user ".$contact["nick"]." as friend");
1093 // We don't seem to like that person
1094 if ($contact["blocked"]) {
1095 // Maybe blocked, don't accept.
1097 // We are following this person?
1098 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1099 // Yes, then it is fine.
1101 // Is it a post to a community?
1102 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [Contact::PAGE_COMMUNITY, Contact::PAGE_PRVGROUP])) {
1105 // Is the message a global user or a comment?
1106 } elseif (($importer["uid"] == 0) || $is_comment) {
1107 // Messages for the global users and comments are always accepted
1115 * @brief Fetches the contact id for a handle and checks if posting is allowed
1117 * @param array $importer Array of the importer user
1118 * @param string $handle The checked handle in the format user@domain.tld
1119 * @param bool $is_comment Is the check for a comment?
1121 * @return array The contact data
1123 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1125 $contact = self::contactByHandle($importer["uid"], $handle);
1127 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1128 // If a contact isn't found, we accept it anyway if it is a comment
1129 if ($is_comment && ($importer["uid"] != 0)) {
1130 return self::contactByHandle(0, $handle);
1131 } elseif ($is_comment) {
1138 if (!self::postAllow($importer, $contact, $is_comment)) {
1139 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1146 * @brief Does the message already exists on the system?
1148 * @param int $uid The user id
1149 * @param string $guid The guid of the message
1151 * @return int|bool message id if the message already was stored into the system - or false.
1153 private static function messageExists($uid, $guid)
1155 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1156 if (DBA::isResult($item)) {
1157 logger("message ".$guid." already exists for user ".$uid);
1165 * @brief Checks for links to posts in a message
1167 * @param array $item The item array
1170 private static function fetchGuid(array $item)
1172 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1173 preg_replace_callback(
1175 function ($match) use ($item) {
1176 self::fetchGuidSub($match, $item);
1181 preg_replace_callback(
1182 "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1183 function ($match) use ($item) {
1184 self::fetchGuidSub($match, $item);
1191 * @brief Checks for relative /people/* links in an item body to match local
1192 * contacts or prepends the remote host taken from the author link.
1194 * @param string $body The item body to replace links from
1195 * @param string $author_link The author link for missing local contact fallback
1197 * @return string the replaced string
1199 public static function replacePeopleGuid($body, $author_link)
1201 $return = preg_replace_callback(
1202 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1203 function ($match) use ($author_link) {
1205 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1206 // 1 => '0123456789abcdef'
1208 $handle = self::urlFromContactGuid($match[1]);
1211 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1213 // No local match, restoring absolute remote URL from author scheme and host
1214 $author_url = parse_url($author_link);
1215 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1227 * @brief sub function of "fetchGuid" which checks for links in messages
1229 * @param array $match array containing a link that has to be checked for a message link
1230 * @param array $item The item array
1233 private static function fetchGuidSub($match, $item)
1235 if (!self::storeByGuid($match[1], $item["author-link"])) {
1236 self::storeByGuid($match[1], $item["owner-link"]);
1241 * @brief Fetches an item with a given guid from a given server
1243 * @param string $guid the message guid
1244 * @param string $server The server address
1245 * @param int $uid The user id of the user
1247 * @return int the message id of the stored message or false
1249 private static function storeByGuid($guid, $server, $uid = 0)
1251 $serverparts = parse_url($server);
1253 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1257 $server = $serverparts["scheme"]."://".$serverparts["host"];
1259 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1261 $msg = self::message($guid, $server);
1267 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1269 // Now call the dispatcher
1270 return self::dispatchPublic($msg);
1274 * @brief Fetches a message from a server
1276 * @param string $guid message guid
1277 * @param string $server The url of the server
1278 * @param int $level Endless loop prevention
1281 * 'message' => The message XML
1282 * 'author' => The author handle
1283 * 'key' => The public key of the author
1285 private static function message($guid, $server, $level = 0)
1291 // This will work for new Diaspora servers and Friendica servers from 3.5
1292 $source_url = $server."/fetch/post/".urlencode($guid);
1294 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1296 $envelope = Network::fetchUrl($source_url);
1298 logger("Envelope was fetched.", LOGGER_DEBUG);
1299 $x = self::verifyMagicEnvelope($envelope);
1301 logger("Envelope could not be verified.", LOGGER_DEBUG);
1303 logger("Envelope was verified.", LOGGER_DEBUG);
1309 // This will work for older Diaspora and Friendica servers
1311 $source_url = $server."/p/".urlencode($guid).".xml";
1312 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1314 $x = Network::fetchUrl($source_url);
1320 $source_xml = XML::parseString($x);
1322 if (!is_object($source_xml)) {
1326 if ($source_xml->post->reshare) {
1327 // Reshare of a reshare - old Diaspora version
1328 logger("Message is a reshare", LOGGER_DEBUG);
1329 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1330 } elseif ($source_xml->getName() == "reshare") {
1331 // Reshare of a reshare - new Diaspora version
1332 logger("Message is a new reshare", LOGGER_DEBUG);
1333 return self::message($source_xml->root_guid, $server, ++$level);
1338 // Fetch the author - for the old and the new Diaspora version
1339 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1340 $author = (string)$source_xml->post->status_message->diaspora_handle;
1341 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1342 $author = (string)$source_xml->author;
1345 // If this isn't a "status_message" then quit
1347 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1351 $msg = ["message" => $x, "author" => $author];
1353 $msg["key"] = self::key($msg["author"]);
1359 * @brief Fetches the item record of a given guid
1361 * @param int $uid The user id
1362 * @param string $guid message guid
1363 * @param string $author The handle of the item
1364 * @param array $contact The contact of the item owner
1366 * @return array the item record
1368 private static function parentItem($uid, $guid, $author, array $contact)
1370 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1371 'author-name', 'author-link', 'author-avatar',
1372 'owner-name', 'owner-link', 'owner-avatar'];
1373 $condition = ['uid' => $uid, 'guid' => $guid];
1374 $item = Item::selectFirst($fields, $condition);
1376 if (!DBA::isResult($item)) {
1377 $result = self::storeByGuid($guid, $contact["url"], $uid);
1380 $person = self::personByHandle($author);
1381 $result = self::storeByGuid($guid, $person["url"], $uid);
1385 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1387 $item = Item::selectFirst($fields, $condition);
1391 if (!DBA::isResult($item)) {
1392 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1395 logger("parent item found: parent: ".$guid." - user: ".$uid);
1401 * @brief returns contact details
1403 * @param array $def_contact The default contact if the person isn't found
1404 * @param array $person The record of the person
1405 * @param int $uid The user id
1408 * 'cid' => contact id
1409 * 'network' => network type
1411 private static function authorContactByUrl($def_contact, $person, $uid)
1413 $condition = ['nurl' => normalise_link($person["url"]), 'uid' => $uid];
1414 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1415 if (DBA::isResult($contact)) {
1416 $cid = $contact["id"];
1417 $network = $contact["network"];
1419 $cid = $def_contact["id"];
1420 $network = NETWORK_DIASPORA;
1423 return ["cid" => $cid, "network" => $network];
1427 * @brief Is the profile a hubzilla profile?
1429 * @param string $url The profile link
1431 * @return bool is it a hubzilla server?
1433 public static function isRedmatrix($url)
1435 return(strstr($url, "/channel/"));
1439 * @brief Generate a post link with a given handle and message guid
1441 * @param string $addr The user handle
1442 * @param string $guid message guid
1443 * @param string $parent_guid optional parent guid
1445 * @return string the post link
1447 private static function plink($addr, $guid, $parent_guid = '')
1449 $contact = Contact::getDetailsByAddr($addr);
1453 if ($parent_guid != '') {
1454 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1456 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1460 if ($contact["network"] == NETWORK_DFRN) {
1461 return str_replace("/profile/" . $contact["nick"] . "/", "/display/" . $guid, $contact["url"] . "/");
1464 if (self::isRedmatrix($contact["url"])) {
1465 return $contact["url"] . "/?f=&mid=" . $guid;
1468 if ($parent_guid != '') {
1469 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1471 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1476 * @brief Receives account migration
1478 * @param array $importer Array of the importer user
1479 * @param object $data The message object
1481 * @return bool Success
1483 private static function receiveAccountMigration(array $importer, $data)
1485 $old_handle = notags(unxmlify($data->author));
1486 $new_handle = notags(unxmlify($data->profile->author));
1487 $signature = notags(unxmlify($data->signature));
1489 $contact = self::contactByHandle($importer["uid"], $old_handle);
1491 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1495 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1498 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1499 $key = self::key($old_handle);
1500 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1501 logger('No valid signature for migration.');
1505 // Update the profile
1506 self::receiveProfile($importer, $data->profile);
1508 // change the technical stuff in contact and gcontact
1509 $data = Probe::uri($new_handle);
1510 if ($data['network'] == NETWORK_PHANTOM) {
1511 logger('Account for '.$new_handle." couldn't be probed.");
1515 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1516 'name' => $data['name'], 'nick' => $data['nick'],
1517 'addr' => $data['addr'], 'batch' => $data['batch'],
1518 'notify' => $data['notify'], 'poll' => $data['poll'],
1519 'network' => $data['network']];
1521 DBA::update('contact', $fields, ['addr' => $old_handle]);
1523 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1524 'name' => $data['name'], 'nick' => $data['nick'],
1525 'addr' => $data['addr'], 'connect' => $data['addr'],
1526 'notify' => $data['notify'], 'photo' => $data['photo'],
1527 'server_url' => $data['baseurl'], 'network' => $data['network']];
1529 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1531 logger('Contacts are updated.');
1537 * @brief Processes an account deletion
1539 * @param object $data The message object
1541 * @return bool Success
1543 private static function receiveAccountDeletion($data)
1545 $author = notags(unxmlify($data->author));
1547 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1548 while ($contact = DBA::fetch($contacts)) {
1549 Contact::remove($contact["id"]);
1552 DBA::delete('gcontact', ['addr' => $author]);
1554 logger('Removed contacts for ' . $author);
1560 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1562 * @param string $author Author handle
1563 * @param string $guid Message guid
1564 * @param boolean $onlyfound Only return uri when found in the database
1566 * @return string The constructed uri or the one from our database
1568 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1570 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1571 if (DBA::isResult($item)) {
1572 return $item["uri"];
1573 } elseif (!$onlyfound) {
1574 $contact = Contact::getDetailsByAddr($author, 0);
1575 if (!empty($contact['network'])) {
1576 $prefix = 'urn:X-' . $contact['network'] . ':';
1578 // This fallback should happen most unlikely
1579 $prefix = 'urn:X-dspr:';
1582 $author_parts = explode('@', $author);
1584 return $prefix . $author_parts[1] . ':' . $author_parts[0] . ':'. $guid;
1591 * @brief Fetch the guid from our database with a given uri
1593 * @param string $uri Message uri
1594 * @param string $uid Author handle
1596 * @return string The post guid
1598 private static function getGuidFromUri($uri, $uid)
1600 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1601 if (DBA::isResult($item)) {
1602 return $item["guid"];
1609 * @brief Find the best importer for a comment, like, ...
1611 * @param string $guid The guid of the item
1613 * @return array|boolean the origin owner of that post - or false
1615 private static function importerForGuid($guid)
1617 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1618 if (DBA::isResult($item)) {
1619 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1620 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1621 if (DBA::isResult($contact)) {
1629 * @brief Processes an incoming comment
1631 * @param array $importer Array of the importer user
1632 * @param string $sender The sender of the message
1633 * @param object $data The message object
1634 * @param string $xml The original XML of the message
1636 * @return int The message id of the generated comment or "false" if there was an error
1638 private static function receiveComment(array $importer, $sender, $data, $xml)
1640 $author = notags(unxmlify($data->author));
1641 $guid = notags(unxmlify($data->guid));
1642 $parent_guid = notags(unxmlify($data->parent_guid));
1643 $text = unxmlify($data->text);
1645 if (isset($data->created_at)) {
1646 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1648 $created_at = DateTimeFormat::utcNow();
1651 if (isset($data->thread_parent_guid)) {
1652 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1653 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1658 $contact = self::allowedContactByHandle($importer, $sender, true);
1663 $message_id = self::messageExists($importer["uid"], $guid);
1668 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1669 if (!$parent_item) {
1673 $person = self::personByHandle($author);
1674 if (!is_array($person)) {
1675 logger("unable to find author details");
1679 // Fetch the contact id - if we know this contact
1680 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1684 $datarray["uid"] = $importer["uid"];
1685 $datarray["contact-id"] = $author_contact["cid"];
1686 $datarray["network"] = $author_contact["network"];
1688 $datarray["author-link"] = $person["url"];
1689 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1691 $datarray["owner-link"] = $contact["url"];
1692 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1694 $datarray["guid"] = $guid;
1695 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1697 $datarray["verb"] = ACTIVITY_POST;
1698 $datarray["gravity"] = GRAVITY_COMMENT;
1700 if ($thr_uri != "") {
1701 $datarray["parent-uri"] = $thr_uri;
1703 $datarray["parent-uri"] = $parent_item["uri"];
1706 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1708 $datarray["protocol"] = PROTOCOL_DIASPORA;
1709 $datarray["source"] = $xml;
1711 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1713 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1715 $body = Markdown::toBBCode($text);
1717 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1719 self::fetchGuid($datarray);
1721 // If we are the origin of the parent we store the original data.
1722 // We notify our followers during the item storage.
1723 if ($parent_item["origin"]) {
1724 $datarray['diaspora_signed_text'] = json_encode($data);
1727 $message_id = Item::insert($datarray);
1729 if ($message_id <= 0) {
1734 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1735 if ($datarray['uid'] == 0) {
1736 Item::distribute($message_id, json_encode($data));
1744 * @brief processes and stores private messages
1746 * @param array $importer Array of the importer user
1747 * @param array $contact The contact of the message
1748 * @param object $data The message object
1749 * @param array $msg Array of the processed message, author handle and key
1750 * @param object $mesg The private message
1751 * @param array $conversation The conversation record to which this message belongs
1753 * @return bool "true" if it was successful
1755 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1757 $author = notags(unxmlify($data->author));
1758 $guid = notags(unxmlify($data->guid));
1759 $subject = notags(unxmlify($data->subject));
1761 // "diaspora_handle" is the element name from the old version
1762 // "author" is the element name from the new version
1763 if ($mesg->author) {
1764 $msg_author = notags(unxmlify($mesg->author));
1765 } elseif ($mesg->diaspora_handle) {
1766 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1771 $msg_guid = notags(unxmlify($mesg->guid));
1772 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1773 $msg_text = unxmlify($mesg->text);
1774 $msg_created_at = DateTimeFormat::utc(notags(unxmlify($mesg->created_at)));
1776 if ($msg_conversation_guid != $guid) {
1777 logger("message conversation guid does not belong to the current conversation.");
1781 $body = Markdown::toBBCode($msg_text);
1782 $message_uri = $msg_author.":".$msg_guid;
1784 $person = self::personByHandle($msg_author);
1789 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1790 DBA::escape($msg_guid),
1791 intval($importer["uid"])
1793 if (DBA::isResult($r)) {
1794 logger("duplicate message already delivered.", LOGGER_DEBUG);
1799 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1800 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1801 intval($importer["uid"]),
1802 DBA::escape($msg_guid),
1803 intval($conversation["id"]),
1804 DBA::escape($person["name"]),
1805 DBA::escape($person["photo"]),
1806 DBA::escape($person["url"]),
1807 intval($contact["id"]),
1808 DBA::escape($subject),
1812 DBA::escape($message_uri),
1813 DBA::escape($author.":".$guid),
1814 DBA::escape($msg_created_at)
1819 DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
1823 "type" => NOTIFY_MAIL,
1824 "notify_flags" => $importer["notify-flags"],
1825 "language" => $importer["language"],
1826 "to_name" => $importer["username"],
1827 "to_email" => $importer["email"],
1828 "uid" =>$importer["uid"],
1829 "item" => ["subject" => $subject, "body" => $body],
1830 "source_name" => $person["name"],
1831 "source_link" => $person["url"],
1832 "source_photo" => $person["thumb"],
1833 "verb" => ACTIVITY_POST,
1840 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1842 * @param array $importer Array of the importer user
1843 * @param array $msg Array of the processed message, author handle and key
1844 * @param object $data The message object
1846 * @return bool Success
1848 private static function receiveConversation(array $importer, $msg, $data)
1850 $author = notags(unxmlify($data->author));
1851 $guid = notags(unxmlify($data->guid));
1852 $subject = notags(unxmlify($data->subject));
1853 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1854 $participants = notags(unxmlify($data->participants));
1856 $messages = $data->message;
1858 if (!count($messages)) {
1859 logger("empty conversation");
1863 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1868 $conversation = null;
1871 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1872 intval($importer["uid"]),
1876 $conversation = $c[0];
1879 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1880 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1881 intval($importer["uid"]),
1883 DBA::escape($author),
1884 DBA::escape($created_at),
1885 DBA::escape(DateTimeFormat::utcNow()),
1886 DBA::escape($subject),
1887 DBA::escape($participants)
1891 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1892 intval($importer["uid"]),
1898 $conversation = $c[0];
1901 if (!$conversation) {
1902 logger("unable to create conversation.");
1906 foreach ($messages as $mesg) {
1907 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1914 * @brief Processes "like" messages
1916 * @param array $importer Array of the importer user
1917 * @param string $sender The sender of the message
1918 * @param object $data The message object
1920 * @return int The message id of the generated like or "false" if there was an error
1922 private static function receiveLike(array $importer, $sender, $data)
1924 $author = notags(unxmlify($data->author));
1925 $guid = notags(unxmlify($data->guid));
1926 $parent_guid = notags(unxmlify($data->parent_guid));
1927 $parent_type = notags(unxmlify($data->parent_type));
1928 $positive = notags(unxmlify($data->positive));
1930 // likes on comments aren't supported by Diaspora - only on posts
1931 // But maybe this will be supported in the future, so we will accept it.
1932 if (!in_array($parent_type, ["Post", "Comment"])) {
1936 $contact = self::allowedContactByHandle($importer, $sender, true);
1941 $message_id = self::messageExists($importer["uid"], $guid);
1946 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1947 if (!$parent_item) {
1951 $person = self::personByHandle($author);
1952 if (!is_array($person)) {
1953 logger("unable to find author details");
1957 // Fetch the contact id - if we know this contact
1958 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1960 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1961 // We would accept this anyhow.
1962 if ($positive == "true") {
1963 $verb = ACTIVITY_LIKE;
1965 $verb = ACTIVITY_DISLIKE;
1970 $datarray["protocol"] = PROTOCOL_DIASPORA;
1972 $datarray["uid"] = $importer["uid"];
1973 $datarray["contact-id"] = $author_contact["cid"];
1974 $datarray["network"] = $author_contact["network"];
1976 $datarray["author-link"] = $person["url"];
1977 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1979 $datarray["owner-link"] = $contact["url"];
1980 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1982 $datarray["guid"] = $guid;
1983 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1985 $datarray["verb"] = $verb;
1986 $datarray["gravity"] = GRAVITY_ACTIVITY;
1987 $datarray["parent-uri"] = $parent_item["uri"];
1989 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1991 $datarray["body"] = $verb;
1993 // Diaspora doesn't provide a date for likes
1994 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
1996 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1997 if ($parent_item["id"] != $parent_item["parent"]) {
1998 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
1999 $origin = $toplevel["origin"];
2001 $origin = $parent_item["origin"];
2004 // If we are the origin of the parent we store the original data.
2005 // We notify our followers during the item storage.
2007 $datarray['diaspora_signed_text'] = json_encode($data);
2010 $message_id = Item::insert($datarray);
2012 if ($message_id <= 0) {
2017 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2018 if ($datarray['uid'] == 0) {
2019 Item::distribute($message_id, json_encode($data));
2027 * @brief Processes private messages
2029 * @param array $importer Array of the importer user
2030 * @param object $data The message object
2032 * @return bool Success?
2034 private static function receiveMessage(array $importer, $data)
2036 $author = notags(unxmlify($data->author));
2037 $guid = notags(unxmlify($data->guid));
2038 $conversation_guid = notags(unxmlify($data->conversation_guid));
2039 $text = unxmlify($data->text);
2040 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2042 $contact = self::allowedContactByHandle($importer, $author, true);
2047 $conversation = null;
2050 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2051 intval($importer["uid"]),
2052 DBA::escape($conversation_guid)
2055 $conversation = $c[0];
2057 logger("conversation not available.");
2061 $message_uri = $author.":".$guid;
2063 $person = self::personByHandle($author);
2065 logger("unable to find author details");
2069 $body = Markdown::toBBCode($text);
2071 $body = self::replacePeopleGuid($body, $person["url"]);
2076 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2078 intval($importer["uid"])
2080 if (DBA::isResult($r)) {
2081 logger("duplicate message already delivered.", LOGGER_DEBUG);
2086 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2087 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2088 intval($importer["uid"]),
2090 intval($conversation["id"]),
2091 DBA::escape($person["name"]),
2092 DBA::escape($person["photo"]),
2093 DBA::escape($person["url"]),
2094 intval($contact["id"]),
2095 DBA::escape($conversation["subject"]),
2099 DBA::escape($message_uri),
2100 DBA::escape($author.":".$conversation["guid"]),
2101 DBA::escape($created_at)
2106 DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
2111 * @brief Processes participations - unsupported by now
2113 * @param array $importer Array of the importer user
2114 * @param object $data The message object
2116 * @return bool always true
2118 private static function receiveParticipation(array $importer, $data)
2120 $author = strtolower(notags(unxmlify($data->author)));
2121 $parent_guid = notags(unxmlify($data->parent_guid));
2123 $contact_id = Contact::getIdForURL($author);
2125 logger('Contact not found: '.$author);
2129 $person = self::personByHandle($author);
2130 if (!is_array($person)) {
2131 logger("Person not found: ".$author);
2135 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2136 if (!DBA::isResult($item)) {
2137 logger('Item not found, no origin or private: '.$parent_guid);
2141 $author_parts = explode('@', $author);
2142 if (isset($author_parts[1])) {
2143 $server = $author_parts[1];
2145 // Should never happen
2149 logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
2151 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2152 DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2155 // Send all existing comments and likes to the requesting server
2156 $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2157 while ($comment = Item::fetch($comments)) {
2158 if ($comment['id'] == $comment['parent']) {
2161 if ($comment['verb'] == ACTIVITY_POST) {
2162 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2164 $cmd = $comment['self'] ? 'like' : 'comment-import';
2166 logger("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, LOGGER_DEBUG);
2167 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2169 DBA::close($comments);
2175 * @brief Processes photos - unneeded
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 receivePhoto(array $importer, $data)
2184 // There doesn't seem to be a reason for this function,
2185 // since the photo data is transmitted in the status message as well
2190 * @brief Processes poll participations - unssupported
2192 * @param array $importer Array of the importer user
2193 * @param object $data The message object
2195 * @return bool always true
2197 private static function receivePollParticipation(array $importer, $data)
2199 // We don't support polls by now
2204 * @brief Processes incoming profile updates
2206 * @param array $importer Array of the importer user
2207 * @param object $data The message object
2209 * @return bool Success
2211 private static function receiveProfile(array $importer, $data)
2213 $author = strtolower(notags(unxmlify($data->author)));
2215 $contact = self::contactByHandle($importer["uid"], $author);
2220 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2221 $image_url = unxmlify($data->image_url);
2222 $birthday = unxmlify($data->birthday);
2223 $gender = unxmlify($data->gender);
2224 $about = Markdown::toBBCode(unxmlify($data->bio));
2225 $location = Markdown::toBBCode(unxmlify($data->location));
2226 $searchable = (unxmlify($data->searchable) == "true");
2227 $nsfw = (unxmlify($data->nsfw) == "true");
2228 $tags = unxmlify($data->tag_string);
2230 $tags = explode("#", $tags);
2233 foreach ($tags as $tag) {
2234 $tag = trim(strtolower($tag));
2240 $keywords = implode(", ", $keywords);
2242 $handle_parts = explode("@", $author);
2243 $nick = $handle_parts[0];
2246 $name = $handle_parts[0];
2249 if (preg_match("|^https?://|", $image_url) === 0) {
2250 $image_url = "http://".$handle_parts[1].$image_url;
2253 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2255 // Generic birthday. We don't know the timezone. The year is irrelevant.
2257 $birthday = str_replace("1000", "1901", $birthday);
2259 if ($birthday != "") {
2260 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2263 // this is to prevent multiple birthday notifications in a single year
2264 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2266 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2267 $birthday = $contact["bd"];
2270 $fields = ['name' => $name, 'location' => $location,
2271 'name-date' => DateTimeFormat::utcNow(),
2272 'about' => $about, 'gender' => $gender,
2273 'addr' => $author, 'nick' => $nick,
2274 'keywords' => $keywords];
2276 if (!empty($birthday)) {
2277 $fields['bd'] = $birthday;
2280 DBA::update('contact', $fields, ['id' => $contact['id']]);
2282 $gcontact = ["url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2283 "photo" => $image_url, "name" => $name, "location" => $location,
2284 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2285 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2286 "hide" => !$searchable, "nsfw" => $nsfw];
2288 $gcid = GContact::update($gcontact);
2290 GContact::link($gcid, $importer["uid"], $contact["id"]);
2292 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2298 * @brief Processes incoming friend requests
2300 * @param array $importer Array of the importer user
2301 * @param array $contact The contact that send the request
2304 private static function receiveRequestMakeFriend(array $importer, array $contact)
2308 if ($contact["rel"] == Contact::SHARING) {
2311 ['rel' => Contact::FRIEND, 'writable' => true],
2312 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2318 * @brief Processes incoming sharing notification
2320 * @param array $importer Array of the importer user
2321 * @param object $data The message object
2323 * @return bool Success
2325 private static function receiveContactRequest(array $importer, $data)
2327 $author = unxmlify($data->author);
2328 $recipient = unxmlify($data->recipient);
2330 if (!$author || !$recipient) {
2334 // the current protocol version doesn't know these fields
2335 // That means that we will assume their existance
2336 if (isset($data->following)) {
2337 $following = (unxmlify($data->following) == "true");
2342 if (isset($data->sharing)) {
2343 $sharing = (unxmlify($data->sharing) == "true");
2348 $contact = self::contactByHandle($importer["uid"], $author);
2350 // perhaps we were already sharing with this person. Now they're sharing with us.
2351 // That makes us friends.
2354 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2355 self::receiveRequestMakeFriend($importer, $contact);
2357 // refetch the contact array
2358 $contact = self::contactByHandle($importer["uid"], $author);
2360 // If we are now friends, we are sending a share message.
2361 // Normally we needn't to do so, but the first message could have been vanished.
2362 if (in_array($contact["rel"], [Contact::FRIEND])) {
2363 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2365 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2366 $ret = self::sendShare($u[0], $contact);
2371 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2372 Contact::removeFollower($importer, $contact);
2377 if (!$following && $sharing && in_array($importer["page-flags"], [Contact::PAGE_SOAPBOX, Contact::PAGE_NORMAL])) {
2378 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2380 } elseif (!$following && !$sharing) {
2381 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2383 } elseif (!$following && $sharing) {
2384 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2385 } elseif ($following && $sharing) {
2386 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2387 } elseif ($following && !$sharing) {
2388 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2391 $ret = self::personByHandle($author);
2393 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2394 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2398 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2401 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2402 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2403 intval($importer["uid"]),
2404 DBA::escape($ret["network"]),
2405 DBA::escape($ret["addr"]),
2406 DateTimeFormat::utcNow(),
2407 DBA::escape($ret["url"]),
2408 DBA::escape(normalise_link($ret["url"])),
2409 DBA::escape($batch),
2410 DBA::escape($ret["name"]),
2411 DBA::escape($ret["nick"]),
2412 DBA::escape($ret["photo"]),
2413 DBA::escape($ret["pubkey"]),
2414 DBA::escape($ret["notify"]),
2415 DBA::escape($ret["poll"]),
2420 // find the contact record we just created
2422 $contact_record = self::contactByHandle($importer["uid"], $author);
2424 if (!$contact_record) {
2425 logger("unable to locate newly created contact record.");
2429 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2431 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2433 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2435 if (in_array($importer["page-flags"], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP])) {
2436 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2438 $hash = random_string().(string)time(); // Generate a confirm_key
2441 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2442 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2443 intval($importer["uid"]),
2444 intval($contact_record["id"]),
2447 DBA::escape(L10n::t("Sharing notification from Diaspora network")),
2449 DBA::escape(DateTimeFormat::utcNow())
2452 // automatic friend approval
2454 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2456 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2458 // technically they are sharing with us (Contact::SHARING),
2459 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2460 // we are going to change the relationship and make them a follower.
2462 if (($importer["page-flags"] == Contact::PAGE_FREELOVE) && $sharing && $following) {
2463 $new_relation = Contact::FRIEND;
2464 } elseif (($importer["page-flags"] == Contact::PAGE_FREELOVE) && $sharing) {
2465 $new_relation = Contact::SHARING;
2467 $new_relation = Contact::FOLLOWER;
2471 "UPDATE `contact` SET `rel` = %d,
2479 intval($new_relation),
2480 DBA::escape(DateTimeFormat::utcNow()),
2481 DBA::escape(DateTimeFormat::utcNow()),
2482 intval($contact_record["id"])
2485 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2487 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2488 $ret = self::sendShare($u[0], $contact_record);
2490 // Send the profile data, maybe it weren't transmitted before
2491 self::sendProfile($importer["uid"], [$contact_record]);
2499 * @brief Fetches a message with a given guid
2501 * @param string $guid message guid
2502 * @param string $orig_author handle of the original post
2503 * @param string $author handle of the sharer
2505 * @return array The fetched item
2507 public static function originalItem($guid, $orig_author)
2510 logger('Empty guid. Quitting.');
2514 // Do we already have this item?
2515 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2516 'author-name', 'author-link', 'author-avatar'];
2517 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2518 $item = Item::selectFirst($fields, $condition);
2520 if (DBA::isResult($item)) {
2521 logger("reshared message ".$guid." already exists on system.");
2523 // Maybe it is already a reshared item?
2524 // Then refetch the content, if it is a reshare from a reshare.
2525 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2526 if (self::isReshare($item["body"], true)) {
2528 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2529 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2531 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2533 // Add OEmbed and other information to the body
2534 $item["body"] = add_page_info_to_body($item["body"], false, true);
2542 if (!DBA::isResult($item)) {
2543 if (empty($orig_author)) {
2544 logger('Empty author for guid ' . $guid . '. Quitting.');
2548 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2549 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2550 $stored = self::storeByGuid($guid, $server);
2553 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2554 logger("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2555 $stored = self::storeByGuid($guid, $server);
2559 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2560 'author-name', 'author-link', 'author-avatar'];
2561 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2562 $item = Item::selectFirst($fields, $condition);
2564 if (DBA::isResult($item)) {
2565 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2566 if (self::isReshare($item["body"], false)) {
2567 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2568 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2579 * @brief Processes a reshare message
2581 * @param array $importer Array of the importer user
2582 * @param object $data The message object
2583 * @param string $xml The original XML of the message
2585 * @return int the message id
2587 private static function receiveReshare(array $importer, $data, $xml)
2589 $author = notags(unxmlify($data->author));
2590 $guid = notags(unxmlify($data->guid));
2591 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2592 $root_author = notags(unxmlify($data->root_author));
2593 $root_guid = notags(unxmlify($data->root_guid));
2594 /// @todo handle unprocessed property "provider_display_name"
2595 $public = notags(unxmlify($data->public));
2597 $contact = self::allowedContactByHandle($importer, $author, false);
2602 $message_id = self::messageExists($importer["uid"], $guid);
2607 $original_item = self::originalItem($root_guid, $root_author);
2608 if (!$original_item) {
2612 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2616 $datarray["uid"] = $importer["uid"];
2617 $datarray["contact-id"] = $contact["id"];
2618 $datarray["network"] = NETWORK_DIASPORA;
2620 $datarray["author-link"] = $contact["url"];
2621 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2623 $datarray["owner-link"] = $datarray["author-link"];
2624 $datarray["owner-id"] = $datarray["author-id"];
2626 $datarray["guid"] = $guid;
2627 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2629 $datarray["verb"] = ACTIVITY_POST;
2630 $datarray["gravity"] = GRAVITY_PARENT;
2632 $datarray["protocol"] = PROTOCOL_DIASPORA;
2633 $datarray["source"] = $xml;
2635 $prefix = share_header(
2636 $original_item["author-name"],
2637 $original_item["author-link"],
2638 $original_item["author-avatar"],
2639 $original_item["guid"],
2640 $original_item["created"],
2643 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2645 $datarray["tag"] = $original_item["tag"];
2646 $datarray["app"] = $original_item["app"];
2648 $datarray["plink"] = self::plink($author, $guid);
2649 $datarray["private"] = (($public == "false") ? 1 : 0);
2650 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2652 $datarray["object-type"] = $original_item["object-type"];
2654 self::fetchGuid($datarray);
2655 $message_id = Item::insert($datarray);
2657 self::sendParticipation($contact, $datarray);
2660 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2661 if ($datarray['uid'] == 0) {
2662 Item::distribute($message_id);
2671 * @brief Processes retractions
2673 * @param array $importer Array of the importer user
2674 * @param array $contact The contact of the item owner
2675 * @param object $data The message object
2677 * @return bool success
2679 private static function itemRetraction(array $importer, array $contact, $data)
2681 $author = notags(unxmlify($data->author));
2682 $target_guid = notags(unxmlify($data->target_guid));
2683 $target_type = notags(unxmlify($data->target_type));
2685 $person = self::personByHandle($author);
2686 if (!is_array($person)) {
2687 logger("unable to find author detail for ".$author);
2691 if (empty($contact["url"])) {
2692 $contact["url"] = $person["url"];
2695 // Fetch items that are about to be deleted
2696 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2698 // When we receive a public retraction, we delete every item that we find.
2699 if ($importer['uid'] == 0) {
2700 $condition = ['guid' => $target_guid, 'deleted' => false];
2702 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2705 $r = Item::select($fields, $condition);
2706 if (!DBA::isResult($r)) {
2707 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2711 while ($item = Item::fetch($r)) {
2712 if (strstr($item['file'], '[')) {
2713 logger("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", LOGGER_DEBUG);
2717 // Fetch the parent item
2718 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2720 // Only delete it if the parent author really fits
2721 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2722 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2726 Item::delete(['id' => $item['id']]);
2728 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2735 * @brief Receives retraction messages
2737 * @param array $importer Array of the importer user
2738 * @param string $sender The sender of the message
2739 * @param object $data The message object
2741 * @return bool Success
2743 private static function receiveRetraction(array $importer, $sender, $data)
2745 $target_type = notags(unxmlify($data->target_type));
2747 $contact = self::contactByHandle($importer["uid"], $sender);
2748 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2749 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2757 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2759 switch ($target_type) {
2764 case "StatusMessage":
2765 return self::itemRetraction($importer, $contact, $data);
2767 case "PollParticipation":
2769 // Currently unsupported
2773 logger("Unknown target type ".$target_type);
2780 * @brief Receives status messages
2782 * @param array $importer Array of the importer user
2783 * @param object $data The message object
2784 * @param string $xml The original XML of the message
2786 * @return int The message id of the newly created item
2788 private static function receiveStatusMessage(array $importer, $data, $xml)
2790 $author = notags(unxmlify($data->author));
2791 $guid = notags(unxmlify($data->guid));
2792 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2793 $public = notags(unxmlify($data->public));
2794 $text = unxmlify($data->text);
2795 $provider_display_name = notags(unxmlify($data->provider_display_name));
2797 $contact = self::allowedContactByHandle($importer, $author, false);
2802 $message_id = self::messageExists($importer["uid"], $guid);
2808 if ($data->location) {
2809 foreach ($data->location->children() as $fieldname => $data) {
2810 $address[$fieldname] = notags(unxmlify($data));
2814 $body = Markdown::toBBCode($text);
2818 // Attach embedded pictures to the body
2820 foreach ($data->photo as $photo) {
2821 $body = "[img]".unxmlify($photo->remote_photo_path).
2822 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2825 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2827 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2829 // Add OEmbed and other information to the body
2830 if (!self::isRedmatrix($contact["url"])) {
2831 $body = add_page_info_to_body($body, false, true);
2835 /// @todo enable support for polls
2836 //if ($data->poll) {
2837 // foreach ($data->poll AS $poll)
2842 /// @todo enable support for events
2844 $datarray["uid"] = $importer["uid"];
2845 $datarray["contact-id"] = $contact["id"];
2846 $datarray["network"] = NETWORK_DIASPORA;
2848 $datarray["author-link"] = $contact["url"];
2849 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2851 $datarray["owner-link"] = $datarray["author-link"];
2852 $datarray["owner-id"] = $datarray["author-id"];
2854 $datarray["guid"] = $guid;
2855 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2857 $datarray["verb"] = ACTIVITY_POST;
2858 $datarray["gravity"] = GRAVITY_PARENT;
2860 $datarray["protocol"] = PROTOCOL_DIASPORA;
2861 $datarray["source"] = $xml;
2863 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2865 if ($provider_display_name != "") {
2866 $datarray["app"] = $provider_display_name;
2869 $datarray["plink"] = self::plink($author, $guid);
2870 $datarray["private"] = (($public == "false") ? 1 : 0);
2871 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2873 if (isset($address["address"])) {
2874 $datarray["location"] = $address["address"];
2877 if (isset($address["lat"]) && isset($address["lng"])) {
2878 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2881 self::fetchGuid($datarray);
2882 $message_id = Item::insert($datarray);
2884 self::sendParticipation($contact, $datarray);
2887 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2888 if ($datarray['uid'] == 0) {
2889 Item::distribute($message_id);
2897 /* ************************************************************************************** *
2898 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2899 * ************************************************************************************** */
2902 * @brief returnes the handle of a contact
2904 * @param array $contact contact array
2906 * @return string the handle in the format user@domain.tld
2908 private static function myHandle(array $contact)
2910 if (!empty($contact["addr"])) {
2911 return $contact["addr"];
2914 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2915 // So - just in case - we build the the address here.
2916 if ($contact["nickname"] != "") {
2917 $nick = $contact["nickname"];
2919 $nick = $contact["nick"];
2922 return $nick . "@" . substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
2927 * @brief Creates the data for a private message in the new format
2929 * @param string $msg The message that is to be transmitted
2930 * @param array $user The record of the sender
2931 * @param array $contact Target of the communication
2932 * @param string $prvkey The private key of the sender
2933 * @param string $pubkey The public key of the receiver
2935 * @return string The encrypted data
2937 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
2939 logger("Message: ".$msg, LOGGER_DATA);
2941 // without a public key nothing will work
2943 logger("pubkey missing: contact id: ".$contact["id"]);
2947 $aes_key = openssl_random_pseudo_bytes(32);
2948 $b_aes_key = base64_encode($aes_key);
2949 $iv = openssl_random_pseudo_bytes(16);
2950 $b_iv = base64_encode($iv);
2952 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2954 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
2956 $encrypted_key_bundle = "";
2957 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
2959 $json_object = json_encode(
2960 ["aes_key" => base64_encode($encrypted_key_bundle),
2961 "encrypted_magic_envelope" => base64_encode($ciphertext)]
2964 return $json_object;
2968 * @brief Creates the envelope for the "fetch" endpoint and for the new format
2970 * @param string $msg The message that is to be transmitted
2971 * @param array $user The record of the sender
2973 * @return string The envelope
2975 public static function buildMagicEnvelope($msg, array $user)
2977 $b64url_data = base64url_encode($msg);
2978 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
2980 $key_id = base64url_encode(self::myHandle($user));
2981 $type = "application/xml";
2982 $encoding = "base64url";
2983 $alg = "RSA-SHA256";
2984 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2986 // Fallback if the private key wasn't transmitted in the expected field
2987 if ($user['uprvkey'] == "") {
2988 $user['uprvkey'] = $user['prvkey'];
2991 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
2992 $sig = base64url_encode($signature);
2994 $xmldata = ["me:env" => ["me:data" => $data,
2995 "@attributes" => ["type" => $type],
2996 "me:encoding" => $encoding,
2999 "@attributes2" => ["key_id" => $key_id]]];
3001 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3003 return XML::fromArray($xmldata, $xml, false, $namespaces);
3007 * @brief Create the envelope for a message
3009 * @param string $msg The message that is to be transmitted
3010 * @param array $user The record of the sender
3011 * @param array $contact Target of the communication
3012 * @param string $prvkey The private key of the sender
3013 * @param string $pubkey The public key of the receiver
3014 * @param bool $public Is the message public?
3016 * @return string The message that will be transmitted to other servers
3018 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3020 // The message is put into an envelope with the sender's signature
3021 $envelope = self::buildMagicEnvelope($msg, $user);
3023 // Private messages are put into a second envelope, encrypted with the receivers public key
3025 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3032 * @brief Creates a signature for a message
3034 * @param array $owner the array of the owner of the message
3035 * @param array $message The message that is to be signed
3037 * @return string The signature
3039 private static function signature($owner, $message)
3042 unset($sigmsg["author_signature"]);
3043 unset($sigmsg["parent_author_signature"]);
3045 $signed_text = implode(";", $sigmsg);
3047 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3051 * @brief Transmit a message to a target server
3053 * @param array $owner the array of the item owner
3054 * @param array $contact Target of the communication
3055 * @param string $envelope The message that is to be transmitted
3056 * @param bool $public_batch Is it a public post?
3057 * @param bool $queue_run Is the transmission called from the queue?
3058 * @param string $guid message guid
3060 * @return int Result of the transmission
3062 public static function transmit(array $owner, array $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
3066 $enabled = intval(Config::get("system", "diaspora_enabled"));
3071 $logid = random_string(4);
3073 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3075 // We always try to use the data from the fcontact table.
3076 // This is important for transmitting data to Friendica servers.
3077 if (!empty($contact['addr'])) {
3078 $fcontact = self::personByHandle($contact['addr']);
3079 if (!empty($fcontact)) {
3080 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3085 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3089 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3091 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3094 if (!intval(Config::get("system", "diaspora_test"))) {
3095 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3097 Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3098 $return_code = $a->get_curl_code();
3100 logger("test_mode");
3105 logger("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3107 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3108 if (!$no_queue && ($contact['contact-type'] != Contact::ACCOUNT_TYPE_RELAY)) {
3109 logger("queue message");
3110 // queue message for redelivery
3111 Queue::add($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3114 // The message could not be delivered. We mark the contact as "dead"
3115 Contact::markForArchival($contact);
3116 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3117 // We successfully delivered a message, the contact is alive
3118 Contact::unmarkForArchival($contact);
3121 return $return_code ? $return_code : -1;
3126 * @brief Build the post xml
3128 * @param string $type The message type
3129 * @param array $message The message data
3131 * @return string The post XML
3133 public static function buildPostXml($type, $message)
3135 $data = [$type => $message];
3137 return XML::fromArray($data, $xml);
3141 * @brief Builds and transmit messages
3143 * @param array $owner the array of the item owner
3144 * @param array $contact Target of the communication
3145 * @param string $type The message type
3146 * @param array $message The message data
3147 * @param bool $public_batch Is it a public post?
3148 * @param string $guid message guid
3149 * @param bool $spool Should the transmission be spooled or transmitted?
3151 * @return int Result of the transmission
3153 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3155 $msg = self::buildPostXml($type, $message);
3157 logger('message: '.$msg, LOGGER_DATA);
3158 logger('send guid '.$guid, LOGGER_DEBUG);
3160 // Fallback if the private key wasn't transmitted in the expected field
3161 if (empty($owner['uprvkey'])) {
3162 $owner['uprvkey'] = $owner['prvkey'];
3165 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3168 Queue::add($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3171 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3174 logger("guid: ".$guid." result ".$return_code, LOGGER_DEBUG);
3176 return $return_code;
3180 * @brief sends a participation (Used to get all further updates)
3182 * @param array $contact Target of the communication
3183 * @param array $item Item array
3185 * @return int The result of the transmission
3187 private static function sendParticipation(array $contact, array $item)
3189 // Don't send notifications for private postings
3190 if ($item['private']) {
3194 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3196 $result = Cache::get($cachekey);
3197 if (!is_null($result)) {
3201 // Fetch some user id to have a valid handle to transmit the participation.
3202 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3203 // If the item belongs to a user, we take this user id.
3204 if ($item['uid'] == 0) {
3205 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3206 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3207 $owner = User::getOwnerDataById($first_user['uid']);
3209 $owner = User::getOwnerDataById($item['uid']);
3212 $author = self::myHandle($owner);
3214 $message = ["author" => $author,
3215 "guid" => System::createGUID(32),
3216 "parent_type" => "Post",
3217 "parent_guid" => $item["guid"]];
3219 logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
3221 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3222 Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
3224 return self::buildAndTransmit($owner, $contact, "participation", $message);
3228 * @brief sends an account migration
3230 * @param array $owner the array of the item owner
3231 * @param array $contact Target of the communication
3232 * @param int $uid User ID
3234 * @return int The result of the transmission
3236 public static function sendAccountMigration(array $owner, array $contact, $uid)
3238 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3239 $profile = self::createProfileData($uid);
3241 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3242 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3244 $message = ["author" => $old_handle,
3245 "profile" => $profile,
3246 "signature" => $signature];
3248 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3250 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3254 * @brief Sends a "share" message
3256 * @param array $owner the array of the item owner
3257 * @param array $contact Target of the communication
3259 * @return int The result of the transmission
3261 public static function sendShare(array $owner, array $contact)
3264 * @todo support the different possible combinations of "following" and "sharing"
3265 * Currently, Diaspora only interprets the "sharing" field
3267 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3271 switch ($contact["rel"]) {
3272 case Contact::FRIEND:
3276 case Contact::SHARING:
3280 case Contact::FOLLOWER:
3286 $message = ["author" => self::myHandle($owner),
3287 "recipient" => $contact["addr"],
3288 "following" => "true",
3289 "sharing" => "true"];
3291 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3293 return self::buildAndTransmit($owner, $contact, "contact", $message);
3297 * @brief sends an "unshare"
3299 * @param array $owner the array of the item owner
3300 * @param array $contact Target of the communication
3302 * @return int The result of the transmission
3304 public static function sendUnshare(array $owner, array $contact)
3306 $message = ["author" => self::myHandle($owner),
3307 "recipient" => $contact["addr"],
3308 "following" => "false",
3309 "sharing" => "false"];
3311 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3313 return self::buildAndTransmit($owner, $contact, "contact", $message);
3317 * @brief Checks a message body if it is a reshare
3319 * @param string $body The message body that is to be check
3320 * @param bool $complete Should it be a complete check or a simple check?
3322 * @return array|bool Reshare details or "false" if no reshare
3324 public static function isReshare($body, $complete = true)
3326 $body = trim($body);
3328 // Skip if it isn't a pure repeated messages
3329 // Does it start with a share?
3330 if ((strpos($body, "[share") > 0) && $complete) {
3334 // Does it end with a share?
3335 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3339 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3340 // Skip if there is no shared message in there
3341 if ($body == $attributes) {
3345 // If we don't do the complete check we quit here
3348 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3349 if (!empty($matches[1])) {
3350 $guid = $matches[1];
3353 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3354 if (!empty($matches[1])) {
3355 $guid = $matches[1];
3358 if (($guid != "") && $complete) {
3359 $condition = ['guid' => $guid, 'network' => [NETWORK_DFRN, NETWORK_DIASPORA]];
3360 $item = Item::selectFirst(['contact-id'], $condition);
3361 if (DBA::isResult($item)) {
3363 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3364 $ret["root_guid"] = $guid;
3366 } elseif ($complete) {
3367 // We are resharing something that isn't a DFRN or Diaspora post.
3368 // So we have to return "false" on "$complete" to not trigger a reshare.
3371 } elseif (($guid == "") && $complete) {
3375 $ret["root_guid"] = $guid;
3378 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3379 if (!empty($matches[1])) {
3380 $profile = $matches[1];
3383 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3384 if (!empty($matches[1])) {
3385 $profile = $matches[1];
3390 if ($profile != "") {
3391 if (Contact::getIdForURL($profile)) {
3392 $author = Contact::getDetailsByURL($profile);
3393 $ret["root_handle"] = $author['addr'];
3397 if (empty($ret) && !$complete) {
3405 * @brief Create an event array
3407 * @param integer $event_id The id of the event
3409 * @return array with event data
3411 private static function buildEvent($event_id)
3413 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3414 if (!DBA::isResult($r)) {
3422 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3423 if (!DBA::isResult($r)) {
3429 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3430 if (!DBA::isResult($r)) {
3436 $eventdata['author'] = self::myHandle($owner);
3438 if ($event['guid']) {
3439 $eventdata['guid'] = $event['guid'];
3442 $mask = DateTimeFormat::ATOM;
3444 /// @todo - establish "all day" events in Friendica
3445 $eventdata["all_day"] = "false";
3447 if (!$event['adjust']) {
3448 $eventdata['timezone'] = $user['timezone'];
3450 if ($eventdata['timezone'] == "") {
3451 $eventdata['timezone'] = 'UTC';
3455 if ($event['start']) {
3456 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3458 if ($event['finish'] && !$event['nofinish']) {
3459 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3461 if ($event['summary']) {
3462 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3464 if ($event['desc']) {
3465 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3467 if ($event['location']) {
3468 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3469 $coord = Map::getCoordinates($event['location']);
3472 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3473 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3474 $location["lat"] = $coord['lat'];
3475 $location["lng"] = $coord['lon'];
3477 $location["lat"] = 0;
3478 $location["lng"] = 0;
3480 $eventdata['location'] = $location;
3487 * @brief Create a post (status message or reshare)
3489 * @param array $item The item that will be exported
3490 * @param array $owner the array of the item owner
3493 * 'type' -> Message type ("status_message" or "reshare")
3494 * 'message' -> Array of XML elements of the status
3496 public static function buildStatus(array $item, array $owner)
3498 $cachekey = "diaspora:buildStatus:".$item['guid'];
3500 $result = Cache::get($cachekey);
3501 if (!is_null($result)) {
3505 $myaddr = self::myHandle($owner);
3507 $public = (($item["private"]) ? "false" : "true");
3509 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3511 // Detect a share element and do a reshare
3512 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3513 $message = ["author" => $myaddr,
3514 "guid" => $item["guid"],
3515 "created_at" => $created,
3516 "root_author" => $ret["root_handle"],
3517 "root_guid" => $ret["root_guid"],
3518 "provider_display_name" => $item["app"],
3519 "public" => $public];
3523 $title = $item["title"];
3524 $body = $item["body"];
3526 if ($item['author-link'] != $item['owner-link']) {
3527 require_once 'mod/share.php';
3528 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3529 "", $item['created'], $item['plink']) . $body . '[/share]';
3532 // convert to markdown
3533 $body = html_entity_decode(BBCode::toMarkdown($body));
3536 if (strlen($title)) {
3537 $body = "## ".html_entity_decode($title)."\n\n".$body;
3540 if ($item["attach"]) {
3541 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3543 $body .= "\n".L10n::t("Attachments:")."\n";
3544 foreach ($matches as $mtch) {
3545 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3552 if ($item["location"] != "")
3553 $location["address"] = $item["location"];
3555 if ($item["coord"] != "") {
3556 $coord = explode(" ", $item["coord"]);
3557 $location["lat"] = $coord[0];
3558 $location["lng"] = $coord[1];
3561 $message = ["author" => $myaddr,
3562 "guid" => $item["guid"],
3563 "created_at" => $created,
3564 "public" => $public,
3566 "provider_display_name" => $item["app"],
3567 "location" => $location];
3569 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3570 if (!isset($location["lat"]) || !isset($location["lng"])) {
3571 unset($message["location"]);
3574 if ($item['event-id'] > 0) {
3575 $event = self::buildEvent($item['event-id']);
3576 if (count($event)) {
3577 $message['event'] = $event;
3579 if (!empty($event['location']['address']) &&
3580 !empty($event['location']['lat']) &&
3581 !empty($event['location']['lng'])) {
3582 $message['location'] = $event['location'];
3585 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3586 // $message['text'] = '';
3590 $type = "status_message";
3593 $msg = ["type" => $type, "message" => $message];
3595 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3601 * @brief Sends a post
3603 * @param array $item The item that will be exported
3604 * @param array $owner the array of the item owner
3605 * @param array $contact Target of the communication
3606 * @param bool $public_batch Is it a public post?
3608 * @return int The result of the transmission
3610 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3612 $status = self::buildStatus($item, $owner);
3614 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3618 * @brief Creates a "like" object
3620 * @param array $item The item that will be exported
3621 * @param array $owner the array of the item owner
3623 * @return array The data for a "like"
3625 private static function constructLike(array $item, array $owner)
3627 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3628 if (!DBA::isResult($parent)) {
3632 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3634 if ($item['verb'] === ACTIVITY_LIKE) {
3636 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3637 $positive = "false";
3640 return(["author" => self::myHandle($owner),
3641 "guid" => $item["guid"],
3642 "parent_guid" => $parent["guid"],
3643 "parent_type" => $target_type,
3644 "positive" => $positive,
3645 "author_signature" => ""]);
3649 * @brief Creates an "EventParticipation" object
3651 * @param array $item The item that will be exported
3652 * @param array $owner the array of the item owner
3654 * @return array The data for an "EventParticipation"
3656 private static function constructAttend(array $item, array $owner)
3658 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3659 if (!DBA::isResult($parent)) {
3663 switch ($item['verb']) {
3664 case ACTIVITY_ATTEND:
3665 $attend_answer = 'accepted';
3667 case ACTIVITY_ATTENDNO:
3668 $attend_answer = 'declined';
3670 case ACTIVITY_ATTENDMAYBE:
3671 $attend_answer = 'tentative';
3674 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3678 return(["author" => self::myHandle($owner),
3679 "guid" => $item["guid"],
3680 "parent_guid" => $parent["guid"],
3681 "status" => $attend_answer,
3682 "author_signature" => ""]);
3686 * @brief Creates the object for a comment
3688 * @param array $item The item that will be exported
3689 * @param array $owner the array of the item owner
3691 * @return array The data for a comment
3693 private static function constructComment(array $item, array $owner)
3695 $cachekey = "diaspora:constructComment:".$item['guid'];
3697 $result = Cache::get($cachekey);
3698 if (!is_null($result)) {
3702 $parent = Item::selectFirst(['guid'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3703 if (!DBA::isResult($parent)) {
3707 $text = html_entity_decode(BBCode::toMarkdown($item["body"]));
3708 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3710 $comment = ["author" => self::myHandle($owner),
3711 "guid" => $item["guid"],
3712 "created_at" => $created,
3713 "parent_guid" => $parent["guid"],
3715 "author_signature" => ""];
3717 // Send the thread parent guid only if it is a threaded comment
3718 if ($item['thr-parent'] != $item['parent-uri']) {
3719 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3722 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3728 * @brief Send a like or a comment
3730 * @param array $item The item that will be exported
3731 * @param array $owner the array of the item owner
3732 * @param array $contact Target of the communication
3733 * @param bool $public_batch Is it a public post?
3735 * @return int The result of the transmission
3737 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3739 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3740 $message = self::constructAttend($item, $owner);
3741 $type = "event_participation";
3742 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3743 $message = self::constructLike($item, $owner);
3746 $message = self::constructComment($item, $owner);
3754 $message["author_signature"] = self::signature($owner, $message);
3756 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3760 * @brief Creates a message from a signature record entry
3762 * @param array $item The item that will be exported
3763 * @param array $signature The entry of the "sign" record
3765 * @return string The message
3767 private static function messageFromSignature(array $item, array $signature)
3769 // Split the signed text
3770 $signed_parts = explode(";", $signature['signed_text']);
3772 if ($item["deleted"]) {
3773 $message = ["author" => $signature['signer'],
3774 "target_guid" => $signed_parts[0],
3775 "target_type" => $signed_parts[1]];
3776 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3777 $message = ["author" => $signed_parts[4],
3778 "guid" => $signed_parts[1],
3779 "parent_guid" => $signed_parts[3],
3780 "parent_type" => $signed_parts[2],
3781 "positive" => $signed_parts[0],
3782 "author_signature" => $signature['signature'],
3783 "parent_author_signature" => ""];
3785 // Remove the comment guid
3786 $guid = array_shift($signed_parts);
3788 // Remove the parent guid
3789 $parent_guid = array_shift($signed_parts);
3791 // Remove the handle
3792 $handle = array_pop($signed_parts);
3794 // Glue the parts together
3795 $text = implode(";", $signed_parts);
3797 $message = ["author" => $handle,
3799 "parent_guid" => $parent_guid,
3800 "text" => implode(";", $signed_parts),
3801 "author_signature" => $signature['signature'],
3802 "parent_author_signature" => ""];
3808 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3810 * @param array $item The item that will be exported
3811 * @param array $owner the array of the item owner
3812 * @param array $contact Target of the communication
3813 * @param bool $public_batch Is it a public post?
3815 * @return int The result of the transmission
3817 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3819 if ($item["deleted"]) {
3820 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3821 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3827 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3829 // fetch the original signature
3832 "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3837 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3843 // Old way - is used by the internal Friendica functions
3844 /// @todo Change all signatur storing functions to the new format
3845 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
3846 $message = self::messageFromSignature($item, $signature);
3848 $msg = json_decode($signature['signed_text'], true);
3851 if (is_array($msg)) {
3852 foreach ($msg as $field => $data) {
3853 if (!$item["deleted"]) {
3854 if ($field == "diaspora_handle") {
3857 if ($field == "target_type") {
3858 $field = "parent_type";
3862 $message[$field] = $data;
3865 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3869 $message["parent_author_signature"] = self::signature($owner, $message);
3871 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3873 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3877 * @brief Sends a retraction (deletion) of a message, like or comment
3879 * @param array $item The item that will be exported
3880 * @param array $owner the array of the item owner
3881 * @param array $contact Target of the communication
3882 * @param bool $public_batch Is it a public post?
3883 * @param bool $relay Is the retraction transmitted from a relay?
3885 * @return int The result of the transmission
3887 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
3889 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3891 $msg_type = "retraction";
3893 if ($item['id'] == $item['parent']) {
3894 $target_type = "Post";
3895 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3896 $target_type = "Like";
3898 $target_type = "Comment";
3901 $message = ["author" => $itemaddr,
3902 "target_guid" => $item['guid'],
3903 "target_type" => $target_type];
3905 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3907 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3911 * @brief Sends a mail
3913 * @param array $item The item that will be exported
3914 * @param array $owner The owner
3915 * @param array $contact Target of the communication
3917 * @return int The result of the transmission
3919 public static function sendMail(array $item, array $owner, array $contact)
3921 $myaddr = self::myHandle($owner);
3924 "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3925 intval($item["convid"]),
3926 intval($item["uid"])
3929 if (!DBA::isResult($r)) {
3930 logger("conversation not found.");
3936 "author" => $cnv["creator"],
3937 "guid" => $cnv["guid"],
3938 "subject" => $cnv["subject"],
3939 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3940 "participants" => $cnv["recips"]
3943 $body = BBCode::toMarkdown($item["body"]);
3944 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3947 "author" => $myaddr,
3948 "guid" => $item["guid"],
3949 "conversation_guid" => $cnv["guid"],
3951 "created_at" => $created,
3954 if ($item["reply"]) {
3959 "author" => $cnv["creator"],
3960 "guid" => $cnv["guid"],
3961 "subject" => $cnv["subject"],
3962 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3963 "participants" => $cnv["recips"],
3966 $type = "conversation";
3969 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
3973 * @brief Split a name into first name and last name
3975 * @param string $name The name
3977 * @return array The array with "first" and "last"
3979 public static function splitName($name) {
3980 $name = trim($name);
3982 // Is the name longer than 64 characters? Then cut the rest of it.
3983 if (strlen($name) > 64) {
3984 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3985 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3987 $name = substr($name, 0, 64);
3991 // Take the first word as first name
3992 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3993 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3994 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3995 return ['first' => $first, 'last' => $last];
3998 // Take the last word as last name
3999 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4000 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4002 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4003 return ['first' => $first, 'last' => $last];
4006 // Take the first 32 characters if there is no space in the first 32 characters
4007 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4008 $first = substr($name, 0, 32);
4009 $last = substr($name, 32);
4010 return ['first' => $first, 'last' => $last];
4013 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4014 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4016 // Check if the last name is longer than 32 characters
4017 if (strlen($last) > 32) {
4018 if (strpos($last, ' ') <= 32) {
4019 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4021 $last = substr($last, 0, 32);
4025 return ['first' => $first, 'last' => $last];
4029 * @brief Create profile data
4031 * @param int $uid The user id
4033 * @return array The profile data
4035 private static function createProfileData($uid)
4038 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4040 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4041 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4042 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4051 $handle = $profile["addr"];
4053 $split_name = self::splitName($profile['name']);
4054 $first = $split_name['first'];
4055 $last = $split_name['last'];
4057 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4058 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4059 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4060 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4066 if ($searchable === 'true') {
4069 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4070 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4074 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4077 $about = $profile['about'];
4078 $about = strip_tags(BBCode::convert($about));
4080 $location = Profile::formatLocation($profile);
4082 if ($profile['pub_keywords']) {
4083 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4084 $kw = str_replace(' ', ' ', $kw);
4085 $arr = explode(' ', $profile['pub_keywords']);
4087 for ($x = 0; $x < 5; $x ++) {
4088 if (trim($arr[$x])) {
4089 $tags .= '#'. trim($arr[$x]) .' ';
4094 $tags = trim($tags);
4097 return ["author" => $handle,
4098 "first_name" => $first,
4099 "last_name" => $last,
4100 "image_url" => $large,
4101 "image_url_medium" => $medium,
4102 "image_url_small" => $small,
4104 "gender" => $profile['gender'],
4106 "location" => $location,
4107 "searchable" => $searchable,
4109 "tag_string" => $tags];
4113 * @brief Sends profile data
4115 * @param int $uid The user id
4116 * @param bool $recips optional, default false
4119 public static function sendProfile($uid, $recips = false)
4125 $owner = User::getOwnerDataById($uid);
4132 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4133 AND `uid` = %d AND `rel` != %d",
4134 DBA::escape(NETWORK_DIASPORA),
4136 intval(Contact::SHARING)
4144 $message = self::createProfileData($uid);
4146 foreach ($recips as $recip) {
4147 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4148 self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4153 * @brief Stores the signature for likes that are created on our system
4155 * @param array $contact The contact array of the "like"
4156 * @param int $post_id The post id of the "like"
4158 * @return bool Success
4160 public static function storeLikeSignature(array $contact, $post_id)
4162 // Is the contact the owner? Then fetch the private key
4163 if (!$contact['self'] || ($contact['uid'] == 0)) {
4164 logger("No owner post, so not storing signature", LOGGER_DEBUG);
4168 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4169 if (!DBA::isResult($r)) {
4173 $contact["uprvkey"] = $r[0]['prvkey'];
4175 $item = Item::selectFirst([], ['id' => $post_id]);
4176 if (!DBA::isResult($item)) {
4180 if (!in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4184 $message = self::constructLike($item, $contact);
4185 if ($message === false) {
4189 $message["author_signature"] = self::signature($contact, $message);
4192 * Now store the signature more flexible to dynamically support new fields.
4193 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4195 DBA::insert('sign', ['iid' => $post_id, 'signed_text' => json_encode($message)]);
4197 logger('Stored diaspora like signature');
4202 * @brief Stores the signature for comments that are created on our system
4204 * @param array $item The item array of the comment
4205 * @param array $contact The contact array of the item owner
4206 * @param string $uprvkey The private key of the sender
4207 * @param int $message_id The message id of the comment
4209 * @return bool Success
4211 public static function storeCommentSignature(array $item, array $contact, $uprvkey, $message_id)
4213 if ($uprvkey == "") {
4214 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4218 $contact["uprvkey"] = $uprvkey;
4220 $message = self::constructComment($item, $contact);
4221 if ($message === false) {
4225 $message["author_signature"] = self::signature($contact, $message);
4228 * Now store the signature more flexible to dynamically support new fields.
4229 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4231 DBA::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($message)]);
4233 logger('Stored diaspora comment signature');