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\Database\DBM;
23 use Friendica\Model\Contact;
24 use Friendica\Model\GContact;
25 use Friendica\Model\Group;
26 use Friendica\Model\Item;
27 use Friendica\Model\Profile;
28 use Friendica\Model\Queue;
29 use Friendica\Model\User;
30 use Friendica\Network\Probe;
31 use Friendica\Util\Crypto;
32 use Friendica\Util\DateTimeFormat;
33 use Friendica\Util\Map;
34 use Friendica\Util\Network;
35 use Friendica\Util\XML;
38 require_once 'include/dba.php';
39 require_once 'include/items.php';
42 * @brief This class contain functions to create and send Diaspora XML files
48 * @brief Return a list of relay servers
50 * The list contains not only the official relays but also servers that we serve directly
52 * @param integer $item_id The id of the item that is sent
53 * @param array $contacts The previously fetched contacts
55 * @return array of relay servers
57 public static function relayList($item_id, array $contacts = [])
61 // Fetching relay servers
62 $serverdata = Config::get("system", "relay_server");
64 if (!empty($serverdata)) {
65 $servers = explode(",", $serverdata);
66 foreach ($servers as $server) {
67 $serverlist[$server] = trim($server);
71 if (Config::get("system", "relay_directly", false)) {
72 // We distribute our stuff based on the parent to ensure that the thread will be complete
73 $parent = Item::selectFirst(['parent'], ['id' => $item_id]);
74 if (!DBM::is_result($parent)) {
78 // Servers that want to get all content
79 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
80 while ($server = DBA::fetch($servers)) {
81 $serverlist[$server['url']] = $server['url'];
84 // All tags of the current post
85 $condition = ['otype' => TERM_OBJ_POST, 'type' => TERM_HASHTAG, 'oid' => $parent['parent']];
86 $tags = DBA::select('term', ['term'], $condition);
88 while ($tag = DBA::fetch($tags)) {
89 $taglist[] = $tag['term'];
92 // All servers who wants content with this tag
94 if (!empty($taglist)) {
95 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
96 while ($server = DBA::fetch($tagserver)) {
97 $tagserverlist[] = $server['gserver-id'];
101 // All adresses with the given id
102 if (!empty($tagserverlist)) {
103 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
104 while ($server = DBA::fetch($servers)) {
105 $serverlist[$server['url']] = $server['url'];
110 // Now we are collecting all relay contacts
111 foreach ($serverlist as $server_url) {
112 // We don't send messages to ourselves
113 if (link_compare($server_url, System::baseUrl())) {
116 $contact = self::getRelayContact($server_url);
117 if (is_bool($contact)) {
122 foreach ($contacts as $entry) {
123 if ($entry['batch'] == $contact['batch']) {
129 $contacts[] = $contact;
137 * @brief Return a contact for a given server address or creates a dummy entry
139 * @param string $server_url The url of the server
140 * @return array with the contact
142 private static function getRelayContact($server_url)
144 $fields = ['batch', 'id', 'name', 'network', 'archive', 'blocked'];
146 // Fetch the relay contact
147 $condition = ['uid' => 0, 'nurl' => normalise_link($server_url),
148 'contact-type' => ACCOUNT_TYPE_RELAY];
149 $contact = DBA::selectFirst('contact', $fields, $condition);
151 if (DBM::is_result($contact)) {
152 if ($contact['archive'] || $contact['blocked']) {
157 self::setRelayContact($server_url);
159 $contact = DBA::selectFirst('contact', $fields, $condition);
160 if (DBM::is_result($contact)) {
165 // It should never happen that we arrive here
170 * @brief Update or insert a relay contact
172 * @param string $server_url The url of the server
173 * @param array $network_fields Optional network specific fields
175 public static function setRelayContact($server_url, array $network_fields = [])
177 $fields = ['created' => DateTimeFormat::utcNow(),
178 'name' => 'relay', 'nick' => 'relay',
179 'url' => $server_url, 'network' => NETWORK_DIASPORA,
180 'batch' => $server_url . '/receive/public',
181 'rel' => CONTACT_IS_FOLLOWER, 'blocked' => false,
182 'pending' => false, 'writable' => true];
184 $fields = array_merge($fields, $network_fields);
186 $condition = ['uid' => 0, 'nurl' => normalise_link($server_url),
187 'contact-type' => ACCOUNT_TYPE_RELAY];
189 if (DBA::exists('contact', $condition)) {
190 unset($fields['created']);
193 DBA::update('contact', $fields, $condition, true);
197 * @brief Return a list of participating contacts for a thread
199 * This is used for the participation feature.
200 * One of the parameters is a contact array.
201 * This is done to avoid duplicates.
203 * @param integer $thread The id of the thread
204 * @param array $contacts The previously fetched contacts
206 * @return array of relay servers
208 public static function participantsForThread($thread, array $contacts)
210 $r = DBA::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`,
211 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
212 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
213 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
214 WHERE `participation`.`iid` = ?", $thread);
216 while ($contact = DBA::fetch($r)) {
217 if (!empty($contact['fnetwork'])) {
218 $contact['network'] = $contact['fnetwork'];
220 unset($contact['fnetwork']);
222 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
223 $contact['batch'] = $contact['fbatch'];
225 unset($contact['fbatch']);
228 foreach ($contacts as $entry) {
229 if ($entry['batch'] == $contact['batch']) {
235 $contacts[] = $contact;
244 * @brief repairs a signature that was double encoded
246 * The function is unused at the moment. It was copied from the old implementation.
248 * @param string $signature The signature
249 * @param string $handle The handle of the signature owner
250 * @param integer $level This value is only set inside this function to avoid endless loops
252 * @return string the repaired signature
254 private static function repairSignature($signature, $handle = "", $level = 1)
256 if ($signature == "") {
260 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
261 $signature = base64_decode($signature);
262 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
264 // Do a recursive call to be able to fix even multiple levels
266 $signature = self::repairSignature($signature, $handle, ++$level);
274 * @brief verify the envelope and return the verified data
276 * @param string $envelope The magic envelope
278 * @return string verified data
280 private static function verifyMagicEnvelope($envelope)
282 $basedom = XML::parseString($envelope);
284 if (!is_object($basedom)) {
285 logger("Envelope is no XML file");
289 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
291 if (sizeof($children) == 0) {
292 logger("XML has no children");
298 $data = base64url_decode($children->data);
299 $type = $children->data->attributes()->type[0];
301 $encoding = $children->encoding;
303 $alg = $children->alg;
305 $sig = base64url_decode($children->sig);
306 $key_id = $children->sig->attributes()->key_id[0];
308 $handle = base64url_decode($key_id);
311 $b64url_data = base64url_encode($data);
312 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
314 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
317 logger('No author could be decoded. Discarding. Message: ' . $envelope);
321 $key = self::key($handle);
323 logger("Couldn't get a key for handle " . $handle . ". Discarding.");
327 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
329 logger('Message from ' . $handle . ' did not verify. Discarding.');
337 * @brief encrypts data via AES
339 * @param string $key The AES key
340 * @param string $iv The IV (is used for CBC encoding)
341 * @param string $data The data that is to be encrypted
343 * @return string encrypted data
345 private static function aesEncrypt($key, $iv, $data)
347 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
351 * @brief decrypts data via AES
353 * @param string $key The AES key
354 * @param string $iv The IV (is used for CBC encoding)
355 * @param string $encrypted The encrypted data
357 * @return string decrypted data
359 private static function aesDecrypt($key, $iv, $encrypted)
361 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
365 * @brief: Decodes incoming Diaspora message in the new format
367 * @param array $importer Array of the importer user
368 * @param string $raw raw post message
371 * 'message' -> decoded Diaspora XML message
372 * 'author' -> author diaspora handle
373 * 'key' -> author public key (converted to pkcs#8)
375 public static function decodeRaw(array $importer, $raw)
377 $data = json_decode($raw);
379 // Is it a private post? Then decrypt the outer Salmon
380 if (is_object($data)) {
381 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
382 $ciphertext = base64_decode($data->encrypted_magic_envelope);
384 $outer_key_bundle = '';
385 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
386 $j_outer_key_bundle = json_decode($outer_key_bundle);
388 if (!is_object($j_outer_key_bundle)) {
389 logger('Outer Salmon did not verify. Discarding.');
390 System::httpExit(400);
393 $outer_iv = base64_decode($j_outer_key_bundle->iv);
394 $outer_key = base64_decode($j_outer_key_bundle->key);
396 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
401 $basedom = XML::parseString($xml);
403 if (!is_object($basedom)) {
404 logger('Received data does not seem to be an XML. Discarding. '.$xml);
405 System::httpExit(400);
408 $base = $basedom->children(NAMESPACE_SALMON_ME);
410 // Not sure if this cleaning is needed
411 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
413 // Build the signed data
414 $type = $base->data[0]->attributes()->type[0];
415 $encoding = $base->encoding;
417 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
419 // This is the signature
420 $signature = base64url_decode($base->sig);
422 // Get the senders' public key
423 $key_id = $base->sig[0]->attributes()->key_id[0];
424 $author_addr = base64_decode($key_id);
425 if ($author_addr == '') {
426 logger('No author could be decoded. Discarding. Message: ' . $xml);
427 System::httpExit(400);
430 $key = self::key($author_addr);
432 logger("Couldn't get a key for handle " . $author_addr . ". Discarding.");
433 System::httpExit(400);
436 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
438 logger('Message did not verify. Discarding.');
439 System::httpExit(400);
442 return ['message' => (string)base64url_decode($base->data),
443 'author' => unxmlify($author_addr),
444 'key' => (string)$key];
448 * @brief: Decodes incoming Diaspora message in the deprecated format
450 * @param array $importer Array of the importer user
451 * @param string $xml urldecoded Diaspora salmon
454 * 'message' -> decoded Diaspora XML message
455 * 'author' -> author diaspora handle
456 * 'key' -> author public key (converted to pkcs#8)
458 public static function decode(array $importer, $xml)
461 $basedom = XML::parseString($xml);
463 if (!is_object($basedom)) {
464 logger("XML is not parseable.");
467 $children = $basedom->children('https://joindiaspora.com/protocol');
469 $inner_aes_key = null;
472 if ($children->header) {
474 $author_link = str_replace('acct:', '', $children->header->author_id);
476 // This happens with posts from a relais
478 logger("This is no private post in the old format", LOGGER_DEBUG);
482 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
484 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
485 $ciphertext = base64_decode($encrypted_header->ciphertext);
487 $outer_key_bundle = '';
488 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
490 $j_outer_key_bundle = json_decode($outer_key_bundle);
492 $outer_iv = base64_decode($j_outer_key_bundle->iv);
493 $outer_key = base64_decode($j_outer_key_bundle->key);
495 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
497 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
498 $idom = XML::parseString($decrypted);
500 $inner_iv = base64_decode($idom->iv);
501 $inner_aes_key = base64_decode($idom->aes_key);
503 $author_link = str_replace('acct:', '', $idom->author_id);
506 $dom = $basedom->children(NAMESPACE_SALMON_ME);
508 // figure out where in the DOM tree our data is hiding
511 if ($dom->provenance->data) {
512 $base = $dom->provenance;
513 } elseif ($dom->env->data) {
515 } elseif ($dom->data) {
520 logger('unable to locate salmon data in xml');
521 System::httpExit(400);
525 // Stash the signature away for now. We have to find their key or it won't be good for anything.
526 $signature = base64url_decode($base->sig);
530 // strip whitespace so our data element will return to one big base64 blob
531 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
534 // stash away some other stuff for later
536 $type = $base->data[0]->attributes()->type[0];
537 $keyhash = $base->sig[0]->attributes()->keyhash[0];
538 $encoding = $base->encoding;
542 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
546 $data = base64url_decode($data);
550 $inner_decrypted = $data;
552 // Decode the encrypted blob
553 $inner_encrypted = base64_decode($data);
554 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
558 logger('Could not retrieve author URI.');
559 System::httpExit(400);
561 // Once we have the author URI, go to the web and try to find their public key
562 // (first this will look it up locally if it is in the fcontact cache)
563 // This will also convert diaspora public key from pkcs#1 to pkcs#8
565 logger('Fetching key for '.$author_link);
566 $key = self::key($author_link);
569 logger('Could not retrieve author key.');
570 System::httpExit(400);
573 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
576 logger('Message did not verify. Discarding.');
577 System::httpExit(400);
580 logger('Message verified.');
582 return ['message' => (string)$inner_decrypted,
583 'author' => unxmlify($author_link),
584 'key' => (string)$key];
589 * @brief Dispatches public messages and find the fitting receivers
591 * @param array $msg The post that will be dispatched
593 * @return int The message id of the generated message, "true" or "false" if there was an error
595 public static function dispatchPublic($msg)
597 $enabled = intval(Config::get("system", "diaspora_enabled"));
599 logger("diaspora is disabled");
603 if (!($fields = self::validPosting($msg))) {
604 logger("Invalid posting");
608 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
609 $success = self::dispatch($importer, $msg, $fields);
615 * @brief Dispatches the different message types to the different functions
617 * @param array $importer Array of the importer user
618 * @param array $msg The post that will be dispatched
619 * @param object $fields SimpleXML object that contains the message
621 * @return int The message id of the generated message, "true" or "false" if there was an error
623 public static function dispatch(array $importer, $msg, $fields = null)
625 // The sender is the handle of the contact that sent the message.
626 // This will often be different with relayed messages (for example "like" and "comment")
627 $sender = $msg["author"];
629 // This is only needed for private postings since this is already done for public ones before
630 if (is_null($fields)) {
632 if (!($fields = self::validPosting($msg))) {
633 logger("Invalid posting");
640 $type = $fields->getName();
642 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
645 case "account_migration":
647 logger('Message with type ' . $type . ' is not private, quitting.');
650 return self::receiveAccountMigration($importer, $fields);
652 case "account_deletion":
653 return self::receiveAccountDeletion($fields);
656 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
660 logger('Message with type ' . $type . ' is not private, quitting.');
663 return self::receiveContactRequest($importer, $fields);
667 logger('Message with type ' . $type . ' is not private, quitting.');
670 return self::receiveConversation($importer, $msg, $fields);
673 return self::receiveLike($importer, $sender, $fields);
677 logger('Message with type ' . $type . ' is not private, quitting.');
680 return self::receiveMessage($importer, $fields);
682 case "participation":
684 logger('Message with type ' . $type . ' is not private, quitting.');
687 return self::receiveParticipation($importer, $fields);
689 case "photo": // Not implemented
690 return self::receivePhoto($importer, $fields);
692 case "poll_participation": // Not implemented
693 return self::receivePollParticipation($importer, $fields);
697 logger('Message with type ' . $type . ' is not private, quitting.');
700 return self::receiveProfile($importer, $fields);
703 return self::receiveReshare($importer, $fields, $msg["message"]);
706 return self::receiveRetraction($importer, $sender, $fields);
708 case "status_message":
709 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
712 logger("Unknown message type ".$type);
720 * @brief Checks if a posting is valid and fetches the data fields.
722 * This function does not only check the signature.
723 * It also does the conversion between the old and the new diaspora format.
725 * @param array $msg Array with the XML, the sender handle and the sender signature
727 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
729 private static function validPosting($msg)
731 $data = XML::parseString($msg["message"]);
733 if (!is_object($data)) {
734 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
738 // Is this the new or the old version?
739 if ($data->getName() == "XML") {
741 foreach ($data->post->children() as $child) {
749 $type = $element->getName();
752 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
754 // All retractions are handled identically from now on.
755 // In the new version there will only be "retraction".
756 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
757 $type = "retraction";
759 if ($type == "request") {
763 $fields = new SimpleXMLElement("<".$type."/>");
766 $author_signature = null;
767 $parent_author_signature = null;
769 foreach ($element->children() as $fieldname => $entry) {
771 // Translation for the old XML structure
772 if ($fieldname == "diaspora_handle") {
773 $fieldname = "author";
775 if ($fieldname == "participant_handles") {
776 $fieldname = "participants";
778 if (in_array($type, ["like", "participation"])) {
779 if ($fieldname == "target_type") {
780 $fieldname = "parent_type";
783 if ($fieldname == "sender_handle") {
784 $fieldname = "author";
786 if ($fieldname == "recipient_handle") {
787 $fieldname = "recipient";
789 if ($fieldname == "root_diaspora_id") {
790 $fieldname = "root_author";
792 if ($type == "status_message") {
793 if ($fieldname == "raw_message") {
797 if ($type == "retraction") {
798 if ($fieldname == "post_guid") {
799 $fieldname = "target_guid";
801 if ($fieldname == "type") {
802 $fieldname = "target_type";
807 if (($fieldname == "author_signature") && ($entry != "")) {
808 $author_signature = base64_decode($entry);
809 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
810 $parent_author_signature = base64_decode($entry);
811 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
812 if ($signed_data != "") {
816 $signed_data .= $entry;
818 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
819 || ($orig_type == "relayable_retraction")
821 XML::copy($entry, $fields, $fieldname);
825 // This is something that shouldn't happen at all.
826 if (in_array($type, ["status_message", "reshare", "profile"])) {
827 if ($msg["author"] != $fields->author) {
828 logger("Message handle is not the same as envelope sender. Quitting this message.");
833 // Only some message types have signatures. So we quit here for the other types.
834 if (!in_array($type, ["comment", "like"])) {
837 // No author_signature? This is a must, so we quit.
838 if (!isset($author_signature)) {
839 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
843 if (isset($parent_author_signature)) {
844 $key = self::key($msg["author"]);
846 logger("No key found for parent author ".$msg["author"], LOGGER_DEBUG);
850 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
851 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);
856 $key = self::key($fields->author);
858 logger("No key found for author ".$fields->author, LOGGER_DEBUG);
862 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
863 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
871 * @brief Fetches the public key for a given handle
873 * @param string $handle The handle
875 * @return string The public key
877 private static function key($handle)
879 $handle = strval($handle);
881 logger("Fetching diaspora key for: ".$handle);
883 $r = self::personByHandle($handle);
892 * @brief Fetches data for a given handle
894 * @param string $handle The handle
896 * @return array the queried data
898 public static function personByHandle($handle)
902 $person = DBA::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
903 if (DBM::is_result($person)) {
904 logger("In cache " . print_r($person, true), LOGGER_DEBUG);
906 // update record occasionally so it doesn't get stale
907 $d = strtotime($person["updated"]." +00:00");
908 if ($d < strtotime("now - 14 days")) {
912 if ($person["guid"] == "") {
917 if (!DBM::is_result($person) || $update) {
918 logger("create or refresh", LOGGER_DEBUG);
919 $r = Probe::uri($handle, NETWORK_DIASPORA);
921 // Note that Friendica contacts will return a "Diaspora person"
922 // if Diaspora connectivity is enabled on their server
923 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
924 self::updateFContact($r);
926 // Fetch the updated or added contact
927 $person = DBA::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
928 if (!DBM::is_result($person)) {
938 * @brief Updates the fcontact table
940 * @param array $arr The fcontact data
942 private static function updateFContact($arr)
944 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
945 'request' => $arr["request"], 'nick' => $arr["nick"],
946 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
947 'batch' => $arr["batch"], 'notify' => $arr["notify"],
948 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
949 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
950 'updated' => DateTimeFormat::utcNow()];
952 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
954 DBA::update('fcontact', $fields, $condition, true);
958 * @brief get a handle (user@domain.tld) from a given contact id
960 * @param int $contact_id The id in the contact table
961 * @param int $pcontact_id The id in the contact table (Used for the public contact)
963 * @return string the handle
965 private static function handleFromContact($contact_id, $pcontact_id = 0)
969 logger("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, LOGGER_DEBUG);
971 if ($pcontact_id != 0) {
973 "SELECT `addr` FROM `contact` WHERE `id` = %d AND `addr` != ''",
977 if (DBM::is_result($r)) {
978 return strtolower($r[0]["addr"]);
983 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
987 if (DBM::is_result($r)) {
990 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
992 if ($contact['addr'] != "") {
993 $handle = $contact['addr'];
995 $baseurl_start = strpos($contact['url'], '://') + 3;
996 // allows installations in a subdirectory--not sure how Diaspora will handle
997 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
998 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
999 $handle = $contact['nick'].'@'.$baseurl;
1003 return strtolower($handle);
1007 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
1010 * @param mixed $fcontact_guid Hexadecimal string guid
1012 * @return string the contact url or null
1014 public static function urlFromContactGuid($fcontact_guid)
1016 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
1019 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1020 dbesc(NETWORK_DIASPORA),
1021 dbesc($fcontact_guid)
1024 if (DBM::is_result($r)) {
1025 return $r[0]['url'];
1032 * @brief Get a contact id for a given handle
1034 * @todo Move to Friendica\Model\Contact
1036 * @param int $uid The user id
1037 * @param string $handle The handle in the format user@domain.tld
1039 * @return int Contact id
1041 private static function contactByHandle($uid, $handle)
1043 // First do a direct search on the contact table
1045 "SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
1050 if (DBM::is_result($r)) {
1054 * We haven't found it?
1055 * We use another function for it that will possibly create a contact entry.
1057 $cid = Contact::getIdForURL($handle, $uid);
1060 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
1061 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
1063 if (DBM::is_result($r)) {
1069 $handle_parts = explode("@", $handle);
1070 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
1072 "SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
1073 dbesc(NETWORK_DFRN),
1077 if (DBM::is_result($r)) {
1081 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
1086 * @brief Check if posting is allowed for this contact
1088 * @param array $importer Array of the importer user
1089 * @param array $contact The contact that is checked
1090 * @param bool $is_comment Is the check for a comment?
1092 * @return bool is the contact allowed to post?
1094 private static function postAllow(array $importer, array $contact, $is_comment = false)
1097 * Perhaps we were already sharing with this person. Now they're sharing with us.
1098 * That makes us friends.
1099 * Normally this should have handled by getting a request - but this could get lost
1101 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1102 // It is not removed by now. Possibly the code is needed?
1103 //if (!$is_comment && $contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1106 // array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
1107 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1110 // $contact["rel"] = CONTACT_IS_FRIEND;
1111 // logger("defining user ".$contact["nick"]." as friend");
1114 // We don't seem to like that person
1115 if ($contact["blocked"]) {
1116 // Maybe blocked, don't accept.
1118 // We are following this person?
1119 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
1120 // Yes, then it is fine.
1122 // Is it a post to a community?
1123 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && in_array($importer["page-flags"], [PAGE_COMMUNITY, PAGE_PRVGROUP])) {
1126 // Is the message a global user or a comment?
1127 } elseif (($importer["uid"] == 0) || $is_comment) {
1128 // Messages for the global users and comments are always accepted
1136 * @brief Fetches the contact id for a handle and checks if posting is allowed
1138 * @param array $importer Array of the importer user
1139 * @param string $handle The checked handle in the format user@domain.tld
1140 * @param bool $is_comment Is the check for a comment?
1142 * @return array The contact data
1144 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1146 $contact = self::contactByHandle($importer["uid"], $handle);
1148 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1149 // If a contact isn't found, we accept it anyway if it is a comment
1157 if (!self::postAllow($importer, $contact, $is_comment)) {
1158 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1165 * @brief Does the message already exists on the system?
1167 * @param int $uid The user id
1168 * @param string $guid The guid of the message
1170 * @return int|bool message id if the message already was stored into the system - or false.
1172 private static function messageExists($uid, $guid)
1174 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1175 if (DBM::is_result($item)) {
1176 logger("message ".$guid." already exists for user ".$uid);
1184 * @brief Checks for links to posts in a message
1186 * @param array $item The item array
1189 private static function fetchGuid(array $item)
1191 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1192 preg_replace_callback(
1194 function ($match) use ($item) {
1195 self::fetchGuidSub($match, $item);
1200 preg_replace_callback(
1201 "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1202 function ($match) use ($item) {
1203 self::fetchGuidSub($match, $item);
1210 * @brief Checks for relative /people/* links in an item body to match local
1211 * contacts or prepends the remote host taken from the author link.
1213 * @param string $body The item body to replace links from
1214 * @param string $author_link The author link for missing local contact fallback
1216 * @return string the replaced string
1218 public static function replacePeopleGuid($body, $author_link)
1220 $return = preg_replace_callback(
1221 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1222 function ($match) use ($author_link) {
1224 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1225 // 1 => '0123456789abcdef'
1227 $handle = self::urlFromContactGuid($match[1]);
1230 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1232 // No local match, restoring absolute remote URL from author scheme and host
1233 $author_url = parse_url($author_link);
1234 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1246 * @brief sub function of "fetchGuid" which checks for links in messages
1248 * @param array $match array containing a link that has to be checked for a message link
1249 * @param array $item The item array
1252 private static function fetchGuidSub($match, $item)
1254 if (!self::storeByGuid($match[1], $item["author-link"])) {
1255 self::storeByGuid($match[1], $item["owner-link"]);
1260 * @brief Fetches an item with a given guid from a given server
1262 * @param string $guid the message guid
1263 * @param string $server The server address
1264 * @param int $uid The user id of the user
1266 * @return int the message id of the stored message or false
1268 private static function storeByGuid($guid, $server, $uid = 0)
1270 $serverparts = parse_url($server);
1271 $server = $serverparts["scheme"]."://".$serverparts["host"];
1273 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1275 $msg = self::message($guid, $server);
1281 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1283 // Now call the dispatcher
1284 return self::dispatchPublic($msg);
1288 * @brief Fetches a message from a server
1290 * @param string $guid message guid
1291 * @param string $server The url of the server
1292 * @param int $level Endless loop prevention
1295 * 'message' => The message XML
1296 * 'author' => The author handle
1297 * 'key' => The public key of the author
1299 private static function message($guid, $server, $level = 0)
1305 // This will work for new Diaspora servers and Friendica servers from 3.5
1306 $source_url = $server."/fetch/post/".urlencode($guid);
1308 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1310 $envelope = Network::fetchUrl($source_url);
1312 logger("Envelope was fetched.", LOGGER_DEBUG);
1313 $x = self::verifyMagicEnvelope($envelope);
1315 logger("Envelope could not be verified.", LOGGER_DEBUG);
1317 logger("Envelope was verified.", LOGGER_DEBUG);
1323 // This will work for older Diaspora and Friendica servers
1325 $source_url = $server."/p/".urlencode($guid).".xml";
1326 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1328 $x = Network::fetchUrl($source_url);
1334 $source_xml = XML::parseString($x);
1336 if (!is_object($source_xml)) {
1340 if ($source_xml->post->reshare) {
1341 // Reshare of a reshare - old Diaspora version
1342 logger("Message is a reshare", LOGGER_DEBUG);
1343 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1344 } elseif ($source_xml->getName() == "reshare") {
1345 // Reshare of a reshare - new Diaspora version
1346 logger("Message is a new reshare", LOGGER_DEBUG);
1347 return self::message($source_xml->root_guid, $server, ++$level);
1352 // Fetch the author - for the old and the new Diaspora version
1353 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1354 $author = (string)$source_xml->post->status_message->diaspora_handle;
1355 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1356 $author = (string)$source_xml->author;
1359 // If this isn't a "status_message" then quit
1361 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1365 $msg = ["message" => $x, "author" => $author];
1367 $msg["key"] = self::key($msg["author"]);
1373 * @brief Fetches the item record of a given guid
1375 * @param int $uid The user id
1376 * @param string $guid message guid
1377 * @param string $author The handle of the item
1378 * @param array $contact The contact of the item owner
1380 * @return array the item record
1382 private static function parentItem($uid, $guid, $author, array $contact)
1384 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1385 'author-name', 'author-link', 'author-avatar',
1386 'owner-name', 'owner-link', 'owner-avatar'];
1387 $condition = ['uid' => $uid, 'guid' => $guid];
1388 $item = Item::selectFirst($fields, $condition);
1390 if (!DBM::is_result($item)) {
1391 $result = self::storeByGuid($guid, $contact["url"], $uid);
1394 $person = self::personByHandle($author);
1395 $result = self::storeByGuid($guid, $person["url"], $uid);
1399 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1401 $item = Item::selectFirst($fields, $condition);
1405 if (!DBM::is_result($item)) {
1406 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1409 logger("parent item found: parent: ".$guid." - user: ".$uid);
1415 * @brief returns contact details
1417 * @param array $def_contact The default contact if the person isn't found
1418 * @param array $person The record of the person
1419 * @param int $uid The user id
1422 * 'cid' => contact id
1423 * 'network' => network type
1425 private static function authorContactByUrl($def_contact, $person, $uid)
1427 $condition = ['nurl' => normalise_link($person["url"]), 'uid' => $uid];
1428 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1429 if (DBM::is_result($contact)) {
1430 $cid = $contact["id"];
1431 $network = $contact["network"];
1433 $cid = $def_contact["id"];
1434 $network = NETWORK_DIASPORA;
1437 return ["cid" => $cid, "network" => $network];
1441 * @brief Is the profile a hubzilla profile?
1443 * @param string $url The profile link
1445 * @return bool is it a hubzilla server?
1447 public static function isRedmatrix($url)
1449 return(strstr($url, "/channel/"));
1453 * @brief Generate a post link with a given handle and message guid
1455 * @param string $addr The user handle
1456 * @param string $guid message guid
1457 * @param string $parent_guid optional parent guid
1459 * @return string the post link
1461 private static function plink($addr, $guid, $parent_guid = '')
1463 $contact = Contact::getDetailsByAddr($addr);
1467 if ($parent_guid != '') {
1468 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1470 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1474 if ($contact["network"] == NETWORK_DFRN) {
1475 return str_replace("/profile/" . $contact["nick"] . "/", "/display/" . $guid, $contact["url"] . "/");
1478 if (self::isRedmatrix($contact["url"])) {
1479 return $contact["url"] . "/?f=&mid=" . $guid;
1482 if ($parent_guid != '') {
1483 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1485 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1490 * @brief Receives account migration
1492 * @param array $importer Array of the importer user
1493 * @param object $data The message object
1495 * @return bool Success
1497 private static function receiveAccountMigration(array $importer, $data)
1499 $old_handle = notags(unxmlify($data->author));
1500 $new_handle = notags(unxmlify($data->profile->author));
1501 $signature = notags(unxmlify($data->signature));
1503 $contact = self::contactByHandle($importer["uid"], $old_handle);
1505 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1509 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1512 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1513 $key = self::key($old_handle);
1514 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1515 logger('No valid signature for migration.');
1519 // Update the profile
1520 self::receiveProfile($importer, $data->profile);
1522 // change the technical stuff in contact and gcontact
1523 $data = Probe::uri($new_handle);
1524 if ($data['network'] == NETWORK_PHANTOM) {
1525 logger('Account for '.$new_handle." couldn't be probed.");
1529 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1530 'name' => $data['name'], 'nick' => $data['nick'],
1531 'addr' => $data['addr'], 'batch' => $data['batch'],
1532 'notify' => $data['notify'], 'poll' => $data['poll'],
1533 'network' => $data['network']];
1535 DBA::update('contact', $fields, ['addr' => $old_handle]);
1537 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1538 'name' => $data['name'], 'nick' => $data['nick'],
1539 'addr' => $data['addr'], 'connect' => $data['addr'],
1540 'notify' => $data['notify'], 'photo' => $data['photo'],
1541 'server_url' => $data['baseurl'], 'network' => $data['network']];
1543 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1545 logger('Contacts are updated.');
1551 * @brief Processes an account deletion
1553 * @param object $data The message object
1555 * @return bool Success
1557 private static function receiveAccountDeletion($data)
1559 $author = notags(unxmlify($data->author));
1561 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1562 while ($contact = DBA::fetch($contacts)) {
1563 Contact::remove($contact["id"]);
1566 DBA::delete('gcontact', ['addr' => $author]);
1568 logger('Removed contacts for ' . $author);
1574 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1576 * @param string $author Author handle
1577 * @param string $guid Message guid
1578 * @param boolean $onlyfound Only return uri when found in the database
1580 * @return string The constructed uri or the one from our database
1582 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1584 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1585 if (DBM::is_result($item)) {
1586 return $item["uri"];
1587 } elseif (!$onlyfound) {
1588 $contact = Contact::getDetailsByAddr($author, 0);
1589 if (!empty($contact['network'])) {
1590 $prefix = 'urn:X-' . $contact['network'] . ':';
1592 // This fallback should happen most unlikely
1593 $prefix = 'urn:X-dspr:';
1596 $author_parts = explode('@', $author);
1598 return $prefix . $author_parts[1] . ':' . $author_parts[0] . ':'. $guid;
1605 * @brief Fetch the guid from our database with a given uri
1607 * @param string $uri Message uri
1608 * @param string $uid Author handle
1610 * @return string The post guid
1612 private static function getGuidFromUri($uri, $uid)
1614 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1615 if (DBM::is_result($item)) {
1616 return $item["guid"];
1623 * @brief Find the best importer for a comment, like, ...
1625 * @param string $guid The guid of the item
1627 * @return array|boolean the origin owner of that post - or false
1629 private static function importerForGuid($guid)
1631 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1632 if (DBM::is_result($item)) {
1633 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1634 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1635 if (DBM::is_result($contact)) {
1643 * @brief Processes an incoming comment
1645 * @param array $importer Array of the importer user
1646 * @param string $sender The sender of the message
1647 * @param object $data The message object
1648 * @param string $xml The original XML of the message
1650 * @return int The message id of the generated comment or "false" if there was an error
1652 private static function receiveComment(array $importer, $sender, $data, $xml)
1654 $author = notags(unxmlify($data->author));
1655 $guid = notags(unxmlify($data->guid));
1656 $parent_guid = notags(unxmlify($data->parent_guid));
1657 $text = unxmlify($data->text);
1659 if (isset($data->created_at)) {
1660 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1662 $created_at = DateTimeFormat::utcNow();
1665 if (isset($data->thread_parent_guid)) {
1666 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1667 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1672 $contact = self::allowedContactByHandle($importer, $sender, true);
1677 $message_id = self::messageExists($importer["uid"], $guid);
1682 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1683 if (!$parent_item) {
1687 $person = self::personByHandle($author);
1688 if (!is_array($person)) {
1689 logger("unable to find author details");
1693 // Fetch the contact id - if we know this contact
1694 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1698 $datarray["uid"] = $importer["uid"];
1699 $datarray["contact-id"] = $author_contact["cid"];
1700 $datarray["network"] = $author_contact["network"];
1702 $datarray["author-link"] = $person["url"];
1703 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1705 $datarray["owner-link"] = $contact["url"];
1706 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1708 $datarray["guid"] = $guid;
1709 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1711 $datarray["verb"] = ACTIVITY_POST;
1712 $datarray["gravity"] = GRAVITY_COMMENT;
1714 if ($thr_uri != "") {
1715 $datarray["parent-uri"] = $thr_uri;
1717 $datarray["parent-uri"] = $parent_item["uri"];
1720 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1722 $datarray["protocol"] = PROTOCOL_DIASPORA;
1723 $datarray["source"] = $xml;
1725 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1727 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1729 $body = Markdown::toBBCode($text);
1731 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1733 self::fetchGuid($datarray);
1735 // If we are the origin of the parent we store the original data.
1736 // We notify our followers during the item storage.
1737 if ($parent_item["origin"]) {
1738 $datarray['diaspora_signed_text'] = json_encode($data);
1741 $message_id = Item::insert($datarray);
1743 if ($message_id <= 0) {
1748 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1749 if ($datarray['uid'] == 0) {
1750 Item::distribute($message_id, json_encode($data));
1758 * @brief processes and stores private messages
1760 * @param array $importer Array of the importer user
1761 * @param array $contact The contact of the message
1762 * @param object $data The message object
1763 * @param array $msg Array of the processed message, author handle and key
1764 * @param object $mesg The private message
1765 * @param array $conversation The conversation record to which this message belongs
1767 * @return bool "true" if it was successful
1769 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1771 $author = notags(unxmlify($data->author));
1772 $guid = notags(unxmlify($data->guid));
1773 $subject = notags(unxmlify($data->subject));
1775 // "diaspora_handle" is the element name from the old version
1776 // "author" is the element name from the new version
1777 if ($mesg->author) {
1778 $msg_author = notags(unxmlify($mesg->author));
1779 } elseif ($mesg->diaspora_handle) {
1780 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1785 $msg_guid = notags(unxmlify($mesg->guid));
1786 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1787 $msg_text = unxmlify($mesg->text);
1788 $msg_created_at = DateTimeFormat::utc(notags(unxmlify($mesg->created_at)));
1790 if ($msg_conversation_guid != $guid) {
1791 logger("message conversation guid does not belong to the current conversation.");
1795 $body = Markdown::toBBCode($msg_text);
1796 $message_uri = $msg_author.":".$msg_guid;
1798 $person = self::personByHandle($msg_author);
1803 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1805 intval($importer["uid"])
1807 if (DBM::is_result($r)) {
1808 logger("duplicate message already delivered.", LOGGER_DEBUG);
1813 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1814 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1815 intval($importer["uid"]),
1817 intval($conversation["id"]),
1818 dbesc($person["name"]),
1819 dbesc($person["photo"]),
1820 dbesc($person["url"]),
1821 intval($contact["id"]),
1826 dbesc($message_uri),
1827 dbesc($author.":".$guid),
1828 dbesc($msg_created_at)
1833 DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
1837 "type" => NOTIFY_MAIL,
1838 "notify_flags" => $importer["notify-flags"],
1839 "language" => $importer["language"],
1840 "to_name" => $importer["username"],
1841 "to_email" => $importer["email"],
1842 "uid" =>$importer["uid"],
1843 "item" => ["subject" => $subject, "body" => $body],
1844 "source_name" => $person["name"],
1845 "source_link" => $person["url"],
1846 "source_photo" => $person["thumb"],
1847 "verb" => ACTIVITY_POST,
1854 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1856 * @param array $importer Array of the importer user
1857 * @param array $msg Array of the processed message, author handle and key
1858 * @param object $data The message object
1860 * @return bool Success
1862 private static function receiveConversation(array $importer, $msg, $data)
1864 $author = notags(unxmlify($data->author));
1865 $guid = notags(unxmlify($data->guid));
1866 $subject = notags(unxmlify($data->subject));
1867 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1868 $participants = notags(unxmlify($data->participants));
1870 $messages = $data->message;
1872 if (!count($messages)) {
1873 logger("empty conversation");
1877 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1882 $conversation = null;
1885 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1886 intval($importer["uid"]),
1890 $conversation = $c[0];
1893 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1894 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1895 intval($importer["uid"]),
1899 dbesc(DateTimeFormat::utcNow()),
1901 dbesc($participants)
1905 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1906 intval($importer["uid"]),
1912 $conversation = $c[0];
1915 if (!$conversation) {
1916 logger("unable to create conversation.");
1920 foreach ($messages as $mesg) {
1921 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1928 * @brief Processes "like" messages
1930 * @param array $importer Array of the importer user
1931 * @param string $sender The sender of the message
1932 * @param object $data The message object
1934 * @return int The message id of the generated like or "false" if there was an error
1936 private static function receiveLike(array $importer, $sender, $data)
1938 $author = notags(unxmlify($data->author));
1939 $guid = notags(unxmlify($data->guid));
1940 $parent_guid = notags(unxmlify($data->parent_guid));
1941 $parent_type = notags(unxmlify($data->parent_type));
1942 $positive = notags(unxmlify($data->positive));
1944 // likes on comments aren't supported by Diaspora - only on posts
1945 // But maybe this will be supported in the future, so we will accept it.
1946 if (!in_array($parent_type, ["Post", "Comment"])) {
1950 $contact = self::allowedContactByHandle($importer, $sender, true);
1955 $message_id = self::messageExists($importer["uid"], $guid);
1960 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1961 if (!$parent_item) {
1965 $person = self::personByHandle($author);
1966 if (!is_array($person)) {
1967 logger("unable to find author details");
1971 // Fetch the contact id - if we know this contact
1972 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1974 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1975 // We would accept this anyhow.
1976 if ($positive == "true") {
1977 $verb = ACTIVITY_LIKE;
1979 $verb = ACTIVITY_DISLIKE;
1984 $datarray["protocol"] = PROTOCOL_DIASPORA;
1986 $datarray["uid"] = $importer["uid"];
1987 $datarray["contact-id"] = $author_contact["cid"];
1988 $datarray["network"] = $author_contact["network"];
1990 $datarray["author-link"] = $person["url"];
1991 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1993 $datarray["owner-link"] = $contact["url"];
1994 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1996 $datarray["guid"] = $guid;
1997 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1999 $datarray["verb"] = $verb;
2000 $datarray["gravity"] = GRAVITY_ACTIVITY;
2001 $datarray["parent-uri"] = $parent_item["uri"];
2003 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2005 $datarray["body"] = $verb;
2007 // Diaspora doesn't provide a date for likes
2008 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2010 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2011 if ($parent_item["id"] != $parent_item["parent"]) {
2012 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
2013 $origin = $toplevel["origin"];
2015 $origin = $parent_item["origin"];
2018 // If we are the origin of the parent we store the original data.
2019 // We notify our followers during the item storage.
2021 $datarray['diaspora_signed_text'] = json_encode($data);
2024 $message_id = Item::insert($datarray);
2026 if ($message_id <= 0) {
2031 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2032 if ($datarray['uid'] == 0) {
2033 Item::distribute($message_id, json_encode($data));
2041 * @brief Processes private messages
2043 * @param array $importer Array of the importer user
2044 * @param object $data The message object
2046 * @return bool Success?
2048 private static function receiveMessage(array $importer, $data)
2050 $author = notags(unxmlify($data->author));
2051 $guid = notags(unxmlify($data->guid));
2052 $conversation_guid = notags(unxmlify($data->conversation_guid));
2053 $text = unxmlify($data->text);
2054 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2056 $contact = self::allowedContactByHandle($importer, $author, true);
2061 $conversation = null;
2064 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2065 intval($importer["uid"]),
2066 dbesc($conversation_guid)
2069 $conversation = $c[0];
2071 logger("conversation not available.");
2075 $message_uri = $author.":".$guid;
2077 $person = self::personByHandle($author);
2079 logger("unable to find author details");
2083 $body = Markdown::toBBCode($text);
2085 $body = self::replacePeopleGuid($body, $person["url"]);
2090 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2092 intval($importer["uid"])
2094 if (DBM::is_result($r)) {
2095 logger("duplicate message already delivered.", LOGGER_DEBUG);
2100 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2101 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2102 intval($importer["uid"]),
2104 intval($conversation["id"]),
2105 dbesc($person["name"]),
2106 dbesc($person["photo"]),
2107 dbesc($person["url"]),
2108 intval($contact["id"]),
2109 dbesc($conversation["subject"]),
2113 dbesc($message_uri),
2114 dbesc($author.":".$conversation["guid"]),
2120 DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
2125 * @brief Processes participations - unsupported by now
2127 * @param array $importer Array of the importer user
2128 * @param object $data The message object
2130 * @return bool always true
2132 private static function receiveParticipation(array $importer, $data)
2134 $author = strtolower(notags(unxmlify($data->author)));
2135 $parent_guid = notags(unxmlify($data->parent_guid));
2137 $contact_id = Contact::getIdForURL($author);
2139 logger('Contact not found: '.$author);
2143 $person = self::personByHandle($author);
2144 if (!is_array($person)) {
2145 logger("Person not found: ".$author);
2149 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2150 if (!DBM::is_result($item)) {
2151 logger('Item not found, no origin or private: '.$parent_guid);
2155 $author_parts = explode('@', $author);
2156 if (isset($author_parts[1])) {
2157 $server = $author_parts[1];
2159 // Should never happen
2163 logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
2165 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2166 DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2169 // Send all existing comments and likes to the requesting server
2170 $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2171 while ($comment = Item::fetch($comments)) {
2172 if ($comment['id'] == $comment['parent']) {
2175 if ($comment['verb'] == ACTIVITY_POST) {
2176 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2178 $cmd = $comment['self'] ? 'like' : 'comment-import';
2180 logger("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, LOGGER_DEBUG);
2181 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2183 DBA::close($comments);
2189 * @brief Processes photos - unneeded
2191 * @param array $importer Array of the importer user
2192 * @param object $data The message object
2194 * @return bool always true
2196 private static function receivePhoto(array $importer, $data)
2198 // There doesn't seem to be a reason for this function,
2199 // since the photo data is transmitted in the status message as well
2204 * @brief Processes poll participations - unssupported
2206 * @param array $importer Array of the importer user
2207 * @param object $data The message object
2209 * @return bool always true
2211 private static function receivePollParticipation(array $importer, $data)
2213 // We don't support polls by now
2218 * @brief Processes incoming profile updates
2220 * @param array $importer Array of the importer user
2221 * @param object $data The message object
2223 * @return bool Success
2225 private static function receiveProfile(array $importer, $data)
2227 $author = strtolower(notags(unxmlify($data->author)));
2229 $contact = self::contactByHandle($importer["uid"], $author);
2234 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2235 $image_url = unxmlify($data->image_url);
2236 $birthday = unxmlify($data->birthday);
2237 $gender = unxmlify($data->gender);
2238 $about = Markdown::toBBCode(unxmlify($data->bio));
2239 $location = Markdown::toBBCode(unxmlify($data->location));
2240 $searchable = (unxmlify($data->searchable) == "true");
2241 $nsfw = (unxmlify($data->nsfw) == "true");
2242 $tags = unxmlify($data->tag_string);
2244 $tags = explode("#", $tags);
2247 foreach ($tags as $tag) {
2248 $tag = trim(strtolower($tag));
2254 $keywords = implode(", ", $keywords);
2256 $handle_parts = explode("@", $author);
2257 $nick = $handle_parts[0];
2260 $name = $handle_parts[0];
2263 if (preg_match("|^https?://|", $image_url) === 0) {
2264 $image_url = "http://".$handle_parts[1].$image_url;
2267 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2269 // Generic birthday. We don't know the timezone. The year is irrelevant.
2271 $birthday = str_replace("1000", "1901", $birthday);
2273 if ($birthday != "") {
2274 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2277 // this is to prevent multiple birthday notifications in a single year
2278 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2280 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2281 $birthday = $contact["bd"];
2284 $fields = ['name' => $name, 'location' => $location,
2285 'name-date' => DateTimeFormat::utcNow(),
2286 'about' => $about, 'gender' => $gender,
2287 'addr' => $author, 'nick' => $nick,
2288 'keywords' => $keywords];
2290 if (!empty($birthday)) {
2291 $fields['bd'] = $birthday;
2294 DBA::update('contact', $fields, ['id' => $contact['id']]);
2296 $gcontact = ["url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2297 "photo" => $image_url, "name" => $name, "location" => $location,
2298 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2299 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2300 "hide" => !$searchable, "nsfw" => $nsfw];
2302 $gcid = GContact::update($gcontact);
2304 GContact::link($gcid, $importer["uid"], $contact["id"]);
2306 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2312 * @brief Processes incoming friend requests
2314 * @param array $importer Array of the importer user
2315 * @param array $contact The contact that send the request
2318 private static function receiveRequestMakeFriend(array $importer, array $contact)
2322 if ($contact["rel"] == CONTACT_IS_SHARING) {
2325 ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
2326 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2332 * @brief Processes incoming sharing notification
2334 * @param array $importer Array of the importer user
2335 * @param object $data The message object
2337 * @return bool Success
2339 private static function receiveContactRequest(array $importer, $data)
2341 $author = unxmlify($data->author);
2342 $recipient = unxmlify($data->recipient);
2344 if (!$author || !$recipient) {
2348 // the current protocol version doesn't know these fields
2349 // That means that we will assume their existance
2350 if (isset($data->following)) {
2351 $following = (unxmlify($data->following) == "true");
2356 if (isset($data->sharing)) {
2357 $sharing = (unxmlify($data->sharing) == "true");
2362 $contact = self::contactByHandle($importer["uid"], $author);
2364 // perhaps we were already sharing with this person. Now they're sharing with us.
2365 // That makes us friends.
2368 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2369 self::receiveRequestMakeFriend($importer, $contact);
2371 // refetch the contact array
2372 $contact = self::contactByHandle($importer["uid"], $author);
2374 // If we are now friends, we are sending a share message.
2375 // Normally we needn't to do so, but the first message could have been vanished.
2376 if (in_array($contact["rel"], [CONTACT_IS_FRIEND])) {
2377 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2379 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2380 $ret = self::sendShare($u[0], $contact);
2385 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2386 Contact::removeFollower($importer, $contact);
2391 if (!$following && $sharing && in_array($importer["page-flags"], [PAGE_SOAPBOX, PAGE_NORMAL])) {
2392 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2394 } elseif (!$following && !$sharing) {
2395 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2397 } elseif (!$following && $sharing) {
2398 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2399 } elseif ($following && $sharing) {
2400 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2401 } elseif ($following && !$sharing) {
2402 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2405 $ret = self::personByHandle($author);
2407 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2408 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2412 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2415 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2416 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2417 intval($importer["uid"]),
2418 dbesc($ret["network"]),
2419 dbesc($ret["addr"]),
2420 DateTimeFormat::utcNow(),
2422 dbesc(normalise_link($ret["url"])),
2424 dbesc($ret["name"]),
2425 dbesc($ret["nick"]),
2426 dbesc($ret["photo"]),
2427 dbesc($ret["pubkey"]),
2428 dbesc($ret["notify"]),
2429 dbesc($ret["poll"]),
2434 // find the contact record we just created
2436 $contact_record = self::contactByHandle($importer["uid"], $author);
2438 if (!$contact_record) {
2439 logger("unable to locate newly created contact record.");
2443 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2445 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2447 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2449 if (in_array($importer["page-flags"], [PAGE_NORMAL, PAGE_PRVGROUP])) {
2450 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2452 $hash = random_string().(string)time(); // Generate a confirm_key
2455 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2456 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2457 intval($importer["uid"]),
2458 intval($contact_record["id"]),
2461 dbesc(L10n::t("Sharing notification from Diaspora network")),
2463 dbesc(DateTimeFormat::utcNow())
2466 // automatic friend approval
2468 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2470 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2472 // technically they are sharing with us (CONTACT_IS_SHARING),
2473 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2474 // we are going to change the relationship and make them a follower.
2476 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following) {
2477 $new_relation = CONTACT_IS_FRIEND;
2478 } elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing) {
2479 $new_relation = CONTACT_IS_SHARING;
2481 $new_relation = CONTACT_IS_FOLLOWER;
2485 "UPDATE `contact` SET `rel` = %d,
2493 intval($new_relation),
2494 dbesc(DateTimeFormat::utcNow()),
2495 dbesc(DateTimeFormat::utcNow()),
2496 intval($contact_record["id"])
2499 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2501 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2502 $ret = self::sendShare($u[0], $contact_record);
2504 // Send the profile data, maybe it weren't transmitted before
2505 self::sendProfile($importer["uid"], [$contact_record]);
2513 * @brief Fetches a message with a given guid
2515 * @param string $guid message guid
2516 * @param string $orig_author handle of the original post
2517 * @param string $author handle of the sharer
2519 * @return array The fetched item
2521 public static function originalItem($guid, $orig_author)
2524 logger('Empty guid. Quitting.');
2528 // Do we already have this item?
2529 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2530 'author-name', 'author-link', 'author-avatar'];
2531 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2532 $item = Item::selectFirst($fields, $condition);
2534 if (DBM::is_result($item)) {
2535 logger("reshared message ".$guid." already exists on system.");
2537 // Maybe it is already a reshared item?
2538 // Then refetch the content, if it is a reshare from a reshare.
2539 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2540 if (self::isReshare($item["body"], true)) {
2542 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2543 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2545 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2547 // Add OEmbed and other information to the body
2548 $item["body"] = add_page_info_to_body($item["body"], false, true);
2556 if (!DBM::is_result($item)) {
2557 if (empty($orig_author)) {
2558 logger('Empty author for guid ' . $guid . '. Quitting.');
2562 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2563 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2564 $stored = self::storeByGuid($guid, $server);
2567 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2568 logger("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2569 $stored = self::storeByGuid($guid, $server);
2573 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2574 'author-name', 'author-link', 'author-avatar'];
2575 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2576 $item = Item::selectFirst($fields, $condition);
2578 if (DBM::is_result($item)) {
2579 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2580 if (self::isReshare($item["body"], false)) {
2581 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2582 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2593 * @brief Processes a reshare message
2595 * @param array $importer Array of the importer user
2596 * @param object $data The message object
2597 * @param string $xml The original XML of the message
2599 * @return int the message id
2601 private static function receiveReshare(array $importer, $data, $xml)
2603 $author = notags(unxmlify($data->author));
2604 $guid = notags(unxmlify($data->guid));
2605 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2606 $root_author = notags(unxmlify($data->root_author));
2607 $root_guid = notags(unxmlify($data->root_guid));
2608 /// @todo handle unprocessed property "provider_display_name"
2609 $public = notags(unxmlify($data->public));
2611 $contact = self::allowedContactByHandle($importer, $author, false);
2616 $message_id = self::messageExists($importer["uid"], $guid);
2621 $original_item = self::originalItem($root_guid, $root_author);
2622 if (!$original_item) {
2626 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2630 $datarray["uid"] = $importer["uid"];
2631 $datarray["contact-id"] = $contact["id"];
2632 $datarray["network"] = NETWORK_DIASPORA;
2634 $datarray["author-link"] = $contact["url"];
2635 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2637 $datarray["owner-link"] = $datarray["author-link"];
2638 $datarray["owner-id"] = $datarray["author-id"];
2640 $datarray["guid"] = $guid;
2641 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2643 $datarray["verb"] = ACTIVITY_POST;
2644 $datarray["gravity"] = GRAVITY_PARENT;
2646 $datarray["protocol"] = PROTOCOL_DIASPORA;
2647 $datarray["source"] = $xml;
2649 $prefix = share_header(
2650 $original_item["author-name"],
2651 $original_item["author-link"],
2652 $original_item["author-avatar"],
2653 $original_item["guid"],
2654 $original_item["created"],
2657 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2659 $datarray["tag"] = $original_item["tag"];
2660 $datarray["app"] = $original_item["app"];
2662 $datarray["plink"] = self::plink($author, $guid);
2663 $datarray["private"] = (($public == "false") ? 1 : 0);
2664 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2666 $datarray["object-type"] = $original_item["object-type"];
2668 self::fetchGuid($datarray);
2669 $message_id = Item::insert($datarray);
2671 self::sendParticipation($contact, $datarray);
2674 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2675 if ($datarray['uid'] == 0) {
2676 Item::distribute($message_id);
2685 * @brief Processes retractions
2687 * @param array $importer Array of the importer user
2688 * @param array $contact The contact of the item owner
2689 * @param object $data The message object
2691 * @return bool success
2693 private static function itemRetraction(array $importer, array $contact, $data)
2695 $author = notags(unxmlify($data->author));
2696 $target_guid = notags(unxmlify($data->target_guid));
2697 $target_type = notags(unxmlify($data->target_type));
2699 $person = self::personByHandle($author);
2700 if (!is_array($person)) {
2701 logger("unable to find author detail for ".$author);
2705 if (empty($contact["url"])) {
2706 $contact["url"] = $person["url"];
2709 // Fetch items that are about to be deleted
2710 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2712 // When we receive a public retraction, we delete every item that we find.
2713 if ($importer['uid'] == 0) {
2714 $condition = ['guid' => $target_guid, 'deleted' => false];
2716 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2719 $r = Item::select($fields, $condition);
2720 if (!DBM::is_result($r)) {
2721 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2725 while ($item = Item::fetch($r)) {
2726 if (strstr($item['file'], '[')) {
2727 logger("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", LOGGER_DEBUG);
2731 // Fetch the parent item
2732 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2734 // Only delete it if the parent author really fits
2735 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2736 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2740 Item::delete(['id' => $item['id']]);
2742 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2749 * @brief Receives retraction messages
2751 * @param array $importer Array of the importer user
2752 * @param string $sender The sender of the message
2753 * @param object $data The message object
2755 * @return bool Success
2757 private static function receiveRetraction(array $importer, $sender, $data)
2759 $target_type = notags(unxmlify($data->target_type));
2761 $contact = self::contactByHandle($importer["uid"], $sender);
2762 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2763 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2771 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2773 switch ($target_type) {
2778 case "StatusMessage":
2779 return self::itemRetraction($importer, $contact, $data);
2781 case "PollParticipation":
2783 // Currently unsupported
2787 logger("Unknown target type ".$target_type);
2794 * @brief Receives status messages
2796 * @param array $importer Array of the importer user
2797 * @param object $data The message object
2798 * @param string $xml The original XML of the message
2800 * @return int The message id of the newly created item
2802 private static function receiveStatusMessage(array $importer, $data, $xml)
2804 $author = notags(unxmlify($data->author));
2805 $guid = notags(unxmlify($data->guid));
2806 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2807 $public = notags(unxmlify($data->public));
2808 $text = unxmlify($data->text);
2809 $provider_display_name = notags(unxmlify($data->provider_display_name));
2811 $contact = self::allowedContactByHandle($importer, $author, false);
2816 $message_id = self::messageExists($importer["uid"], $guid);
2822 if ($data->location) {
2823 foreach ($data->location->children() as $fieldname => $data) {
2824 $address[$fieldname] = notags(unxmlify($data));
2828 $body = Markdown::toBBCode($text);
2832 // Attach embedded pictures to the body
2834 foreach ($data->photo as $photo) {
2835 $body = "[img]".unxmlify($photo->remote_photo_path).
2836 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2839 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2841 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2843 // Add OEmbed and other information to the body
2844 if (!self::isRedmatrix($contact["url"])) {
2845 $body = add_page_info_to_body($body, false, true);
2849 /// @todo enable support for polls
2850 //if ($data->poll) {
2851 // foreach ($data->poll AS $poll)
2856 /// @todo enable support for events
2858 $datarray["uid"] = $importer["uid"];
2859 $datarray["contact-id"] = $contact["id"];
2860 $datarray["network"] = NETWORK_DIASPORA;
2862 $datarray["author-link"] = $contact["url"];
2863 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2865 $datarray["owner-link"] = $datarray["author-link"];
2866 $datarray["owner-id"] = $datarray["author-id"];
2868 $datarray["guid"] = $guid;
2869 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2871 $datarray["verb"] = ACTIVITY_POST;
2872 $datarray["gravity"] = GRAVITY_PARENT;
2874 $datarray["protocol"] = PROTOCOL_DIASPORA;
2875 $datarray["source"] = $xml;
2877 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2879 if ($provider_display_name != "") {
2880 $datarray["app"] = $provider_display_name;
2883 $datarray["plink"] = self::plink($author, $guid);
2884 $datarray["private"] = (($public == "false") ? 1 : 0);
2885 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2887 if (isset($address["address"])) {
2888 $datarray["location"] = $address["address"];
2891 if (isset($address["lat"]) && isset($address["lng"])) {
2892 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2895 self::fetchGuid($datarray);
2896 $message_id = Item::insert($datarray);
2898 self::sendParticipation($contact, $datarray);
2901 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2902 if ($datarray['uid'] == 0) {
2903 Item::distribute($message_id);
2911 /* ************************************************************************************** *
2912 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2913 * ************************************************************************************** */
2916 * @brief returnes the handle of a contact
2918 * @param array $contact contact array
2920 * @return string the handle in the format user@domain.tld
2922 private static function myHandle(array $contact)
2924 if (!empty($contact["addr"])) {
2925 return $contact["addr"];
2928 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2929 // So - just in case - we build the the address here.
2930 if ($contact["nickname"] != "") {
2931 $nick = $contact["nickname"];
2933 $nick = $contact["nick"];
2936 return $nick . "@" . substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
2941 * @brief Creates the data for a private message in the new format
2943 * @param string $msg The message that is to be transmitted
2944 * @param array $user The record of the sender
2945 * @param array $contact Target of the communication
2946 * @param string $prvkey The private key of the sender
2947 * @param string $pubkey The public key of the receiver
2949 * @return string The encrypted data
2951 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
2953 logger("Message: ".$msg, LOGGER_DATA);
2955 // without a public key nothing will work
2957 logger("pubkey missing: contact id: ".$contact["id"]);
2961 $aes_key = openssl_random_pseudo_bytes(32);
2962 $b_aes_key = base64_encode($aes_key);
2963 $iv = openssl_random_pseudo_bytes(16);
2964 $b_iv = base64_encode($iv);
2966 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2968 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
2970 $encrypted_key_bundle = "";
2971 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
2973 $json_object = json_encode(
2974 ["aes_key" => base64_encode($encrypted_key_bundle),
2975 "encrypted_magic_envelope" => base64_encode($ciphertext)]
2978 return $json_object;
2982 * @brief Creates the envelope for the "fetch" endpoint and for the new format
2984 * @param string $msg The message that is to be transmitted
2985 * @param array $user The record of the sender
2987 * @return string The envelope
2989 public static function buildMagicEnvelope($msg, array $user)
2991 $b64url_data = base64url_encode($msg);
2992 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
2994 $key_id = base64url_encode(self::myHandle($user));
2995 $type = "application/xml";
2996 $encoding = "base64url";
2997 $alg = "RSA-SHA256";
2998 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
3000 // Fallback if the private key wasn't transmitted in the expected field
3001 if ($user['uprvkey'] == "") {
3002 $user['uprvkey'] = $user['prvkey'];
3005 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3006 $sig = base64url_encode($signature);
3008 $xmldata = ["me:env" => ["me:data" => $data,
3009 "@attributes" => ["type" => $type],
3010 "me:encoding" => $encoding,
3013 "@attributes2" => ["key_id" => $key_id]]];
3015 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3017 return XML::fromArray($xmldata, $xml, false, $namespaces);
3021 * @brief Create the envelope for a message
3023 * @param string $msg The message that is to be transmitted
3024 * @param array $user The record of the sender
3025 * @param array $contact Target of the communication
3026 * @param string $prvkey The private key of the sender
3027 * @param string $pubkey The public key of the receiver
3028 * @param bool $public Is the message public?
3030 * @return string The message that will be transmitted to other servers
3032 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3034 // The message is put into an envelope with the sender's signature
3035 $envelope = self::buildMagicEnvelope($msg, $user);
3037 // Private messages are put into a second envelope, encrypted with the receivers public key
3039 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3046 * @brief Creates a signature for a message
3048 * @param array $owner the array of the owner of the message
3049 * @param array $message The message that is to be signed
3051 * @return string The signature
3053 private static function signature($owner, $message)
3056 unset($sigmsg["author_signature"]);
3057 unset($sigmsg["parent_author_signature"]);
3059 $signed_text = implode(";", $sigmsg);
3061 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3065 * @brief Transmit a message to a target server
3067 * @param array $owner the array of the item owner
3068 * @param array $contact Target of the communication
3069 * @param string $envelope The message that is to be transmitted
3070 * @param bool $public_batch Is it a public post?
3071 * @param bool $queue_run Is the transmission called from the queue?
3072 * @param string $guid message guid
3074 * @return int Result of the transmission
3076 public static function transmit(array $owner, array $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
3080 $enabled = intval(Config::get("system", "diaspora_enabled"));
3085 $logid = random_string(4);
3087 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3089 // We always try to use the data from the fcontact table.
3090 // This is important for transmitting data to Friendica servers.
3091 if (!empty($contact['addr'])) {
3092 $fcontact = self::personByHandle($contact['addr']);
3093 if (!empty($fcontact)) {
3094 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3099 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3103 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3105 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3108 if (!intval(Config::get("system", "diaspora_test"))) {
3109 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3111 Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3112 $return_code = $a->get_curl_code();
3114 logger("test_mode");
3119 logger("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3121 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3122 if (!$no_queue && ($contact['contact-type'] != ACCOUNT_TYPE_RELAY)) {
3123 logger("queue message");
3124 // queue message for redelivery
3125 Queue::add($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3128 // The message could not be delivered. We mark the contact as "dead"
3129 Contact::markForArchival($contact);
3130 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3131 // We successfully delivered a message, the contact is alive
3132 Contact::unmarkForArchival($contact);
3135 return $return_code ? $return_code : -1;
3140 * @brief Build the post xml
3142 * @param string $type The message type
3143 * @param array $message The message data
3145 * @return string The post XML
3147 public static function buildPostXml($type, $message)
3149 $data = [$type => $message];
3151 return XML::fromArray($data, $xml);
3155 * @brief Builds and transmit messages
3157 * @param array $owner the array of the item owner
3158 * @param array $contact Target of the communication
3159 * @param string $type The message type
3160 * @param array $message The message data
3161 * @param bool $public_batch Is it a public post?
3162 * @param string $guid message guid
3163 * @param bool $spool Should the transmission be spooled or transmitted?
3165 * @return int Result of the transmission
3167 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3169 $msg = self::buildPostXml($type, $message);
3171 logger('message: '.$msg, LOGGER_DATA);
3172 logger('send guid '.$guid, LOGGER_DEBUG);
3174 // Fallback if the private key wasn't transmitted in the expected field
3175 if (empty($owner['uprvkey'])) {
3176 $owner['uprvkey'] = $owner['prvkey'];
3179 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3182 Queue::add($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3185 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3188 logger("guid: ".$guid." result ".$return_code, LOGGER_DEBUG);
3190 return $return_code;
3194 * @brief sends a participation (Used to get all further updates)
3196 * @param array $contact Target of the communication
3197 * @param array $item Item array
3199 * @return int The result of the transmission
3201 private static function sendParticipation(array $contact, array $item)
3203 // Don't send notifications for private postings
3204 if ($item['private']) {
3208 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3210 $result = Cache::get($cachekey);
3211 if (!is_null($result)) {
3215 // Fetch some user id to have a valid handle to transmit the participation.
3216 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3217 // If the item belongs to a user, we take this user id.
3218 if ($item['uid'] == 0) {
3219 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3220 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3221 $owner = User::getOwnerDataById($first_user['uid']);
3223 $owner = User::getOwnerDataById($item['uid']);
3226 $author = self::myHandle($owner);
3228 $message = ["author" => $author,
3229 "guid" => System::createGUID(32),
3230 "parent_type" => "Post",
3231 "parent_guid" => $item["guid"]];
3233 logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
3235 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3236 Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
3238 return self::buildAndTransmit($owner, $contact, "participation", $message);
3242 * @brief sends an account migration
3244 * @param array $owner the array of the item owner
3245 * @param array $contact Target of the communication
3246 * @param int $uid User ID
3248 * @return int The result of the transmission
3250 public static function sendAccountMigration(array $owner, array $contact, $uid)
3252 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3253 $profile = self::createProfileData($uid);
3255 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3256 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3258 $message = ["author" => $old_handle,
3259 "profile" => $profile,
3260 "signature" => $signature];
3262 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3264 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3268 * @brief Sends a "share" message
3270 * @param array $owner the array of the item owner
3271 * @param array $contact Target of the communication
3273 * @return int The result of the transmission
3275 public static function sendShare(array $owner, array $contact)
3278 * @todo support the different possible combinations of "following" and "sharing"
3279 * Currently, Diaspora only interprets the "sharing" field
3281 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3285 switch ($contact["rel"]) {
3286 case CONTACT_IS_FRIEND:
3289 case CONTACT_IS_SHARING:
3292 case CONTACT_IS_FOLLOWER:
3298 $message = ["author" => self::myHandle($owner),
3299 "recipient" => $contact["addr"],
3300 "following" => "true",
3301 "sharing" => "true"];
3303 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3305 return self::buildAndTransmit($owner, $contact, "contact", $message);
3309 * @brief sends an "unshare"
3311 * @param array $owner the array of the item owner
3312 * @param array $contact Target of the communication
3314 * @return int The result of the transmission
3316 public static function sendUnshare(array $owner, array $contact)
3318 $message = ["author" => self::myHandle($owner),
3319 "recipient" => $contact["addr"],
3320 "following" => "false",
3321 "sharing" => "false"];
3323 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3325 return self::buildAndTransmit($owner, $contact, "contact", $message);
3329 * @brief Checks a message body if it is a reshare
3331 * @param string $body The message body that is to be check
3332 * @param bool $complete Should it be a complete check or a simple check?
3334 * @return array|bool Reshare details or "false" if no reshare
3336 public static function isReshare($body, $complete = true)
3338 $body = trim($body);
3340 // Skip if it isn't a pure repeated messages
3341 // Does it start with a share?
3342 if ((strpos($body, "[share") > 0) && $complete) {
3346 // Does it end with a share?
3347 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3351 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3352 // Skip if there is no shared message in there
3353 if ($body == $attributes) {
3357 // If we don't do the complete check we quit here
3360 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3361 if (!empty($matches[1])) {
3362 $guid = $matches[1];
3365 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3366 if (!empty($matches[1])) {
3367 $guid = $matches[1];
3370 if (($guid != "") && $complete) {
3371 $condition = ['guid' => $guid, 'network' => [NETWORK_DFRN, NETWORK_DIASPORA]];
3372 $item = Item::selectFirst(['contact-id'], $condition);
3373 if (DBM::is_result($item)) {
3375 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3376 $ret["root_guid"] = $guid;
3378 } elseif ($complete) {
3379 // We are resharing something that isn't a DFRN or Diaspora post.
3380 // So we have to return "false" on "$complete" to not trigger a reshare.
3383 } elseif (($guid == "") && $complete) {
3387 $ret["root_guid"] = $guid;
3390 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3391 if (!empty($matches[1])) {
3392 $profile = $matches[1];
3395 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3396 if (!empty($matches[1])) {
3397 $profile = $matches[1];
3402 if ($profile != "") {
3403 if (Contact::getIdForURL($profile)) {
3404 $author = Contact::getDetailsByURL($profile);
3405 $ret["root_handle"] = $author['addr'];
3409 if (empty($ret) && !$complete) {
3417 * @brief Create an event array
3419 * @param integer $event_id The id of the event
3421 * @return array with event data
3423 private static function buildEvent($event_id)
3425 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3426 if (!DBM::is_result($r)) {
3434 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3435 if (!DBM::is_result($r)) {
3441 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3442 if (!DBM::is_result($r)) {
3448 $eventdata['author'] = self::myHandle($owner);
3450 if ($event['guid']) {
3451 $eventdata['guid'] = $event['guid'];
3454 $mask = DateTimeFormat::ATOM;
3456 /// @todo - establish "all day" events in Friendica
3457 $eventdata["all_day"] = "false";
3459 if (!$event['adjust']) {
3460 $eventdata['timezone'] = $user['timezone'];
3462 if ($eventdata['timezone'] == "") {
3463 $eventdata['timezone'] = 'UTC';
3467 if ($event['start']) {
3468 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3470 if ($event['finish'] && !$event['nofinish']) {
3471 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3473 if ($event['summary']) {
3474 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3476 if ($event['desc']) {
3477 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3479 if ($event['location']) {
3480 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3481 $coord = Map::getCoordinates($event['location']);
3484 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3485 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3486 $location["lat"] = $coord['lat'];
3487 $location["lng"] = $coord['lon'];
3489 $location["lat"] = 0;
3490 $location["lng"] = 0;
3492 $eventdata['location'] = $location;
3499 * @brief Create a post (status message or reshare)
3501 * @param array $item The item that will be exported
3502 * @param array $owner the array of the item owner
3505 * 'type' -> Message type ("status_message" or "reshare")
3506 * 'message' -> Array of XML elements of the status
3508 public static function buildStatus(array $item, array $owner)
3510 $cachekey = "diaspora:buildStatus:".$item['guid'];
3512 $result = Cache::get($cachekey);
3513 if (!is_null($result)) {
3517 $myaddr = self::myHandle($owner);
3519 $public = (($item["private"]) ? "false" : "true");
3521 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3523 // Detect a share element and do a reshare
3524 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3525 $message = ["author" => $myaddr,
3526 "guid" => $item["guid"],
3527 "created_at" => $created,
3528 "root_author" => $ret["root_handle"],
3529 "root_guid" => $ret["root_guid"],
3530 "provider_display_name" => $item["app"],
3531 "public" => $public];
3535 $title = $item["title"];
3536 $body = $item["body"];
3538 if ($item['author-link'] != $item['owner-link']) {
3539 require_once 'mod/share.php';
3540 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3541 "", $item['created'], $item['plink']) . $body . '[/share]';
3544 // convert to markdown
3545 $body = html_entity_decode(BBCode::toMarkdown($body));
3548 if (strlen($title)) {
3549 $body = "## ".html_entity_decode($title)."\n\n".$body;
3552 if ($item["attach"]) {
3553 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3555 $body .= "\n".L10n::t("Attachments:")."\n";
3556 foreach ($matches as $mtch) {
3557 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3564 if ($item["location"] != "")
3565 $location["address"] = $item["location"];
3567 if ($item["coord"] != "") {
3568 $coord = explode(" ", $item["coord"]);
3569 $location["lat"] = $coord[0];
3570 $location["lng"] = $coord[1];
3573 $message = ["author" => $myaddr,
3574 "guid" => $item["guid"],
3575 "created_at" => $created,
3576 "public" => $public,
3578 "provider_display_name" => $item["app"],
3579 "location" => $location];
3581 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3582 if (!isset($location["lat"]) || !isset($location["lng"])) {
3583 unset($message["location"]);
3586 if ($item['event-id'] > 0) {
3587 $event = self::buildEvent($item['event-id']);
3588 if (count($event)) {
3589 $message['event'] = $event;
3591 if (!empty($event['location']['address']) &&
3592 !empty($event['location']['lat']) &&
3593 !empty($event['location']['lng'])) {
3594 $message['location'] = $event['location'];
3597 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3598 // $message['text'] = '';
3602 $type = "status_message";
3605 $msg = ["type" => $type, "message" => $message];
3607 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3613 * @brief Sends a post
3615 * @param array $item The item that will be exported
3616 * @param array $owner the array of the item owner
3617 * @param array $contact Target of the communication
3618 * @param bool $public_batch Is it a public post?
3620 * @return int The result of the transmission
3622 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3624 $status = self::buildStatus($item, $owner);
3626 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3630 * @brief Creates a "like" object
3632 * @param array $item The item that will be exported
3633 * @param array $owner the array of the item owner
3635 * @return array The data for a "like"
3637 private static function constructLike(array $item, array $owner)
3639 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3640 if (!DBM::is_result($parent)) {
3644 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3646 if ($item['verb'] === ACTIVITY_LIKE) {
3648 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3649 $positive = "false";
3652 return(["author" => self::myHandle($owner),
3653 "guid" => $item["guid"],
3654 "parent_guid" => $parent["guid"],
3655 "parent_type" => $target_type,
3656 "positive" => $positive,
3657 "author_signature" => ""]);
3661 * @brief Creates an "EventParticipation" object
3663 * @param array $item The item that will be exported
3664 * @param array $owner the array of the item owner
3666 * @return array The data for an "EventParticipation"
3668 private static function constructAttend(array $item, array $owner)
3670 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3671 if (!DBM::is_result($parent)) {
3675 switch ($item['verb']) {
3676 case ACTIVITY_ATTEND:
3677 $attend_answer = 'accepted';
3679 case ACTIVITY_ATTENDNO:
3680 $attend_answer = 'declined';
3682 case ACTIVITY_ATTENDMAYBE:
3683 $attend_answer = 'tentative';
3686 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3690 return(["author" => self::myHandle($owner),
3691 "guid" => $item["guid"],
3692 "parent_guid" => $parent["guid"],
3693 "status" => $attend_answer,
3694 "author_signature" => ""]);
3698 * @brief Creates the object for a comment
3700 * @param array $item The item that will be exported
3701 * @param array $owner the array of the item owner
3703 * @return array The data for a comment
3705 private static function constructComment(array $item, array $owner)
3707 $cachekey = "diaspora:constructComment:".$item['guid'];
3709 $result = Cache::get($cachekey);
3710 if (!is_null($result)) {
3714 $parent = Item::selectFirst(['guid'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3715 if (!DBM::is_result($parent)) {
3719 $text = html_entity_decode(BBCode::toMarkdown($item["body"]));
3720 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3722 $comment = ["author" => self::myHandle($owner),
3723 "guid" => $item["guid"],
3724 "created_at" => $created,
3725 "parent_guid" => $parent["guid"],
3727 "author_signature" => ""];
3729 // Send the thread parent guid only if it is a threaded comment
3730 if ($item['thr-parent'] != $item['parent-uri']) {
3731 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3734 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3740 * @brief Send a like or a comment
3742 * @param array $item The item that will be exported
3743 * @param array $owner the array of the item owner
3744 * @param array $contact Target of the communication
3745 * @param bool $public_batch Is it a public post?
3747 * @return int The result of the transmission
3749 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3751 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3752 $message = self::constructAttend($item, $owner);
3753 $type = "event_participation";
3754 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3755 $message = self::constructLike($item, $owner);
3758 $message = self::constructComment($item, $owner);
3766 $message["author_signature"] = self::signature($owner, $message);
3768 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3772 * @brief Creates a message from a signature record entry
3774 * @param array $item The item that will be exported
3775 * @param array $signature The entry of the "sign" record
3777 * @return string The message
3779 private static function messageFromSignature(array $item, array $signature)
3781 // Split the signed text
3782 $signed_parts = explode(";", $signature['signed_text']);
3784 if ($item["deleted"]) {
3785 $message = ["author" => $signature['signer'],
3786 "target_guid" => $signed_parts[0],
3787 "target_type" => $signed_parts[1]];
3788 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3789 $message = ["author" => $signed_parts[4],
3790 "guid" => $signed_parts[1],
3791 "parent_guid" => $signed_parts[3],
3792 "parent_type" => $signed_parts[2],
3793 "positive" => $signed_parts[0],
3794 "author_signature" => $signature['signature'],
3795 "parent_author_signature" => ""];
3797 // Remove the comment guid
3798 $guid = array_shift($signed_parts);
3800 // Remove the parent guid
3801 $parent_guid = array_shift($signed_parts);
3803 // Remove the handle
3804 $handle = array_pop($signed_parts);
3806 // Glue the parts together
3807 $text = implode(";", $signed_parts);
3809 $message = ["author" => $handle,
3811 "parent_guid" => $parent_guid,
3812 "text" => implode(";", $signed_parts),
3813 "author_signature" => $signature['signature'],
3814 "parent_author_signature" => ""];
3820 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3822 * @param array $item The item that will be exported
3823 * @param array $owner the array of the item owner
3824 * @param array $contact Target of the communication
3825 * @param bool $public_batch Is it a public post?
3827 * @return int The result of the transmission
3829 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3831 if ($item["deleted"]) {
3832 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3833 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3839 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3841 // fetch the original signature
3844 "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3849 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3855 // Old way - is used by the internal Friendica functions
3856 /// @todo Change all signatur storing functions to the new format
3857 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
3858 $message = self::messageFromSignature($item, $signature);
3860 $msg = json_decode($signature['signed_text'], true);
3863 if (is_array($msg)) {
3864 foreach ($msg as $field => $data) {
3865 if (!$item["deleted"]) {
3866 if ($field == "diaspora_handle") {
3869 if ($field == "target_type") {
3870 $field = "parent_type";
3874 $message[$field] = $data;
3877 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3881 $message["parent_author_signature"] = self::signature($owner, $message);
3883 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3885 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3889 * @brief Sends a retraction (deletion) of a message, like or comment
3891 * @param array $item The item that will be exported
3892 * @param array $owner the array of the item owner
3893 * @param array $contact Target of the communication
3894 * @param bool $public_batch Is it a public post?
3895 * @param bool $relay Is the retraction transmitted from a relay?
3897 * @return int The result of the transmission
3899 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
3901 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3903 $msg_type = "retraction";
3905 if ($item['id'] == $item['parent']) {
3906 $target_type = "Post";
3907 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3908 $target_type = "Like";
3910 $target_type = "Comment";
3913 $message = ["author" => $itemaddr,
3914 "target_guid" => $item['guid'],
3915 "target_type" => $target_type];
3917 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3919 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3923 * @brief Sends a mail
3925 * @param array $item The item that will be exported
3926 * @param array $owner The owner
3927 * @param array $contact Target of the communication
3929 * @return int The result of the transmission
3931 public static function sendMail(array $item, array $owner, array $contact)
3933 $myaddr = self::myHandle($owner);
3936 "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3937 intval($item["convid"]),
3938 intval($item["uid"])
3941 if (!DBM::is_result($r)) {
3942 logger("conversation not found.");
3948 "author" => $cnv["creator"],
3949 "guid" => $cnv["guid"],
3950 "subject" => $cnv["subject"],
3951 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3952 "participants" => $cnv["recips"]
3955 $body = BBCode::toMarkdown($item["body"]);
3956 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3959 "author" => $myaddr,
3960 "guid" => $item["guid"],
3961 "conversation_guid" => $cnv["guid"],
3963 "created_at" => $created,
3966 if ($item["reply"]) {
3971 "author" => $cnv["creator"],
3972 "guid" => $cnv["guid"],
3973 "subject" => $cnv["subject"],
3974 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3975 "participants" => $cnv["recips"],
3978 $type = "conversation";
3981 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
3985 * @brief Split a name into first name and last name
3987 * @param string $name The name
3989 * @return array The array with "first" and "last"
3991 public static function splitName($name) {
3992 $name = trim($name);
3994 // Is the name longer than 64 characters? Then cut the rest of it.
3995 if (strlen($name) > 64) {
3996 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3997 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3999 $name = substr($name, 0, 64);
4003 // Take the first word as first name
4004 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4005 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4006 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4007 return ['first' => $first, 'last' => $last];
4010 // Take the last word as last name
4011 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4012 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4014 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4015 return ['first' => $first, 'last' => $last];
4018 // Take the first 32 characters if there is no space in the first 32 characters
4019 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4020 $first = substr($name, 0, 32);
4021 $last = substr($name, 32);
4022 return ['first' => $first, 'last' => $last];
4025 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4026 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4028 // Check if the last name is longer than 32 characters
4029 if (strlen($last) > 32) {
4030 if (strpos($last, ' ') <= 32) {
4031 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4033 $last = substr($last, 0, 32);
4037 return ['first' => $first, 'last' => $last];
4041 * @brief Create profile data
4043 * @param int $uid The user id
4045 * @return array The profile data
4047 private static function createProfileData($uid)
4050 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4052 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4053 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4054 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4063 $handle = $profile["addr"];
4065 $split_name = self::splitName($profile['name']);
4066 $first = $split_name['first'];
4067 $last = $split_name['last'];
4069 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4070 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4071 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4072 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4078 if ($searchable === 'true') {
4081 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4082 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4086 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4089 $about = $profile['about'];
4090 $about = strip_tags(BBCode::convert($about));
4092 $location = Profile::formatLocation($profile);
4094 if ($profile['pub_keywords']) {
4095 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4096 $kw = str_replace(' ', ' ', $kw);
4097 $arr = explode(' ', $profile['pub_keywords']);
4099 for ($x = 0; $x < 5; $x ++) {
4100 if (trim($arr[$x])) {
4101 $tags .= '#'. trim($arr[$x]) .' ';
4106 $tags = trim($tags);
4109 return ["author" => $handle,
4110 "first_name" => $first,
4111 "last_name" => $last,
4112 "image_url" => $large,
4113 "image_url_medium" => $medium,
4114 "image_url_small" => $small,
4116 "gender" => $profile['gender'],
4118 "location" => $location,
4119 "searchable" => $searchable,
4121 "tag_string" => $tags];
4125 * @brief Sends profile data
4127 * @param int $uid The user id
4128 * @param bool $recips optional, default false
4131 public static function sendProfile($uid, $recips = false)
4137 $owner = User::getOwnerDataById($uid);
4144 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4145 AND `uid` = %d AND `rel` != %d",
4146 dbesc(NETWORK_DIASPORA),
4148 intval(CONTACT_IS_SHARING)
4156 $message = self::createProfileData($uid);
4158 foreach ($recips as $recip) {
4159 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4160 self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4165 * @brief Stores the signature for likes that are created on our system
4167 * @param array $contact The contact array of the "like"
4168 * @param int $post_id The post id of the "like"
4170 * @return bool Success
4172 public static function storeLikeSignature(array $contact, $post_id)
4174 // Is the contact the owner? Then fetch the private key
4175 if (!$contact['self'] || ($contact['uid'] == 0)) {
4176 logger("No owner post, so not storing signature", LOGGER_DEBUG);
4180 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4181 if (!DBM::is_result($r)) {
4185 $contact["uprvkey"] = $r[0]['prvkey'];
4187 $item = Item::selectFirst([], ['id' => $post_id]);
4188 if (!DBM::is_result($item)) {
4192 if (!in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4196 $message = self::constructLike($item, $contact);
4197 if ($message === false) {
4201 $message["author_signature"] = self::signature($contact, $message);
4204 * Now store the signature more flexible to dynamically support new fields.
4205 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4207 DBA::insert('sign', ['iid' => $post_id, 'signed_text' => json_encode($message)]);
4209 logger('Stored diaspora like signature');
4214 * @brief Stores the signature for comments that are created on our system
4216 * @param array $item The item array of the comment
4217 * @param array $contact The contact array of the item owner
4218 * @param string $uprvkey The private key of the sender
4219 * @param int $message_id The message id of the comment
4221 * @return bool Success
4223 public static function storeCommentSignature(array $item, array $contact, $uprvkey, $message_id)
4225 if ($uprvkey == "") {
4226 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4230 $contact["uprvkey"] = $uprvkey;
4232 $message = self::constructComment($item, $contact);
4233 if ($message === false) {
4237 $message["author_signature"] = self::signature($contact, $message);
4240 * Now store the signature more flexible to dynamically support new fields.
4241 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4243 DBA::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($message)]);
4245 logger('Stored diaspora comment signature');