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\Protocol;
20 use Friendica\Core\System;
21 use Friendica\Core\Worker;
22 use Friendica\Database\DBA;
23 use Friendica\Model\Contact;
24 use Friendica\Model\Conversation;
25 use Friendica\Model\GContact;
26 use Friendica\Model\Group;
27 use Friendica\Model\Item;
28 use Friendica\Model\Profile;
29 use Friendica\Model\Queue;
30 use Friendica\Model\User;
31 use Friendica\Network\Probe;
32 use Friendica\Util\Crypto;
33 use Friendica\Util\DateTimeFormat;
34 use Friendica\Util\Map;
35 use Friendica\Util\Network;
36 use Friendica\Util\XML;
39 require_once 'include/dba.php';
40 require_once 'include/items.php';
43 * @brief This class contain functions to create and send Diaspora XML files
49 * @brief Return a list of relay servers
51 * The list contains not only the official relays but also servers that we serve directly
53 * @param integer $item_id The id of the item that is sent
54 * @param array $contacts The previously fetched contacts
56 * @return array of relay servers
58 public static function relayList($item_id, array $contacts = [])
62 // Fetching relay servers
63 $serverdata = Config::get("system", "relay_server");
65 if (!empty($serverdata)) {
66 $servers = explode(",", $serverdata);
67 foreach ($servers as $server) {
68 $serverlist[$server] = trim($server);
72 if (Config::get("system", "relay_directly", false)) {
73 // We distribute our stuff based on the parent to ensure that the thread will be complete
74 $parent = Item::selectFirst(['parent'], ['id' => $item_id]);
75 if (!DBA::isResult($parent)) {
79 // Servers that want to get all content
80 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
81 while ($server = DBA::fetch($servers)) {
82 $serverlist[$server['url']] = $server['url'];
85 // All tags of the current post
86 $condition = ['otype' => TERM_OBJ_POST, 'type' => TERM_HASHTAG, 'oid' => $parent['parent']];
87 $tags = DBA::select('term', ['term'], $condition);
89 while ($tag = DBA::fetch($tags)) {
90 $taglist[] = $tag['term'];
93 // All servers who wants content with this tag
95 if (!empty($taglist)) {
96 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
97 while ($server = DBA::fetch($tagserver)) {
98 $tagserverlist[] = $server['gserver-id'];
102 // All adresses with the given id
103 if (!empty($tagserverlist)) {
104 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
105 while ($server = DBA::fetch($servers)) {
106 $serverlist[$server['url']] = $server['url'];
111 // Now we are collecting all relay contacts
112 foreach ($serverlist as $server_url) {
113 // We don't send messages to ourselves
114 if (link_compare($server_url, System::baseUrl())) {
117 $contact = self::getRelayContact($server_url);
118 if (is_bool($contact)) {
123 foreach ($contacts as $entry) {
124 if ($entry['batch'] == $contact['batch']) {
130 $contacts[] = $contact;
138 * @brief Return a contact for a given server address or creates a dummy entry
140 * @param string $server_url The url of the server
141 * @return array with the contact
143 private static function getRelayContact($server_url)
145 $fields = ['batch', 'id', 'name', 'network', 'archive', 'blocked'];
147 // Fetch the relay contact
148 $condition = ['uid' => 0, 'nurl' => normalise_link($server_url),
149 'contact-type' => Contact::ACCOUNT_TYPE_RELAY];
150 $contact = DBA::selectFirst('contact', $fields, $condition);
152 if (DBA::isResult($contact)) {
153 if ($contact['archive'] || $contact['blocked']) {
158 self::setRelayContact($server_url);
160 $contact = DBA::selectFirst('contact', $fields, $condition);
161 if (DBA::isResult($contact)) {
166 // It should never happen that we arrive here
171 * @brief Update or insert a relay contact
173 * @param string $server_url The url of the server
174 * @param array $network_fields Optional network specific fields
176 public static function setRelayContact($server_url, array $network_fields = [])
178 $fields = ['created' => DateTimeFormat::utcNow(),
179 'name' => 'relay', 'nick' => 'relay',
180 'url' => $server_url, 'network' => Protocol::DIASPORA,
181 'batch' => $server_url . '/receive/public',
182 'rel' => Contact::FOLLOWER, 'blocked' => false,
183 'pending' => false, 'writable' => true];
185 $fields = array_merge($fields, $network_fields);
187 $condition = ['uid' => 0, 'nurl' => normalise_link($server_url),
188 'contact-type' => Contact::ACCOUNT_TYPE_RELAY];
190 if (DBA::exists('contact', $condition)) {
191 unset($fields['created']);
194 DBA::update('contact', $fields, $condition, true);
198 * @brief Return a list of participating contacts for a thread
200 * This is used for the participation feature.
201 * One of the parameters is a contact array.
202 * This is done to avoid duplicates.
204 * @param integer $thread The id of the thread
205 * @param array $contacts The previously fetched contacts
207 * @return array of relay servers
209 public static function participantsForThread($thread, array $contacts)
211 $r = DBA::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`,
212 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
213 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
214 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
215 WHERE `participation`.`iid` = ?", $thread);
217 while ($contact = DBA::fetch($r)) {
218 if (!empty($contact['fnetwork'])) {
219 $contact['network'] = $contact['fnetwork'];
221 unset($contact['fnetwork']);
223 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
224 $contact['batch'] = $contact['fbatch'];
226 unset($contact['fbatch']);
229 foreach ($contacts as $entry) {
230 if ($entry['batch'] == $contact['batch']) {
236 $contacts[] = $contact;
245 * @brief repairs a signature that was double encoded
247 * The function is unused at the moment. It was copied from the old implementation.
249 * @param string $signature The signature
250 * @param string $handle The handle of the signature owner
251 * @param integer $level This value is only set inside this function to avoid endless loops
253 * @return string the repaired signature
255 private static function repairSignature($signature, $handle = "", $level = 1)
257 if ($signature == "") {
261 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
262 $signature = base64_decode($signature);
263 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
265 // Do a recursive call to be able to fix even multiple levels
267 $signature = self::repairSignature($signature, $handle, ++$level);
275 * @brief verify the envelope and return the verified data
277 * @param string $envelope The magic envelope
279 * @return string verified data
281 private static function verifyMagicEnvelope($envelope)
283 $basedom = XML::parseString($envelope);
285 if (!is_object($basedom)) {
286 logger("Envelope is no XML file");
290 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
292 if (sizeof($children) == 0) {
293 logger("XML has no children");
299 $data = base64url_decode($children->data);
300 $type = $children->data->attributes()->type[0];
302 $encoding = $children->encoding;
304 $alg = $children->alg;
306 $sig = base64url_decode($children->sig);
307 $key_id = $children->sig->attributes()->key_id[0];
309 $handle = base64url_decode($key_id);
312 $b64url_data = base64url_encode($data);
313 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
315 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
318 logger('No author could be decoded. Discarding. Message: ' . $envelope);
322 $key = self::key($handle);
324 logger("Couldn't get a key for handle " . $handle . ". Discarding.");
328 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
330 logger('Message from ' . $handle . ' did not verify. Discarding.');
338 * @brief encrypts data via AES
340 * @param string $key The AES key
341 * @param string $iv The IV (is used for CBC encoding)
342 * @param string $data The data that is to be encrypted
344 * @return string encrypted data
346 private static function aesEncrypt($key, $iv, $data)
348 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
352 * @brief decrypts data via AES
354 * @param string $key The AES key
355 * @param string $iv The IV (is used for CBC encoding)
356 * @param string $encrypted The encrypted data
358 * @return string decrypted data
360 private static function aesDecrypt($key, $iv, $encrypted)
362 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
366 * @brief: Decodes incoming Diaspora message in the new format
368 * @param array $importer Array of the importer user
369 * @param string $raw raw post message
370 * @param boolean $no_exit Don't do an http exit on error
373 * 'message' -> decoded Diaspora XML message
374 * 'author' -> author diaspora handle
375 * 'key' -> author public key (converted to pkcs#8)
377 public static function decodeRaw(array $importer, $raw, $no_exit = false)
379 $data = json_decode($raw);
381 // Is it a private post? Then decrypt the outer Salmon
382 if (is_object($data)) {
383 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
384 $ciphertext = base64_decode($data->encrypted_magic_envelope);
386 $outer_key_bundle = '';
387 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
388 $j_outer_key_bundle = json_decode($outer_key_bundle);
390 if (!is_object($j_outer_key_bundle)) {
391 logger('Outer Salmon did not verify. Discarding.');
395 System::httpExit(400);
399 $outer_iv = base64_decode($j_outer_key_bundle->iv);
400 $outer_key = base64_decode($j_outer_key_bundle->key);
402 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
407 $basedom = XML::parseString($xml);
409 if (!is_object($basedom)) {
410 logger('Received data does not seem to be an XML. Discarding. '.$xml);
414 System::httpExit(400);
418 $base = $basedom->children(NAMESPACE_SALMON_ME);
420 // Not sure if this cleaning is needed
421 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
423 // Build the signed data
424 $type = $base->data[0]->attributes()->type[0];
425 $encoding = $base->encoding;
427 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
429 // This is the signature
430 $signature = base64url_decode($base->sig);
432 // Get the senders' public key
433 $key_id = $base->sig[0]->attributes()->key_id[0];
434 $author_addr = base64_decode($key_id);
435 if ($author_addr == '') {
436 logger('No author could be decoded. Discarding. Message: ' . $xml);
440 System::httpExit(400);
444 $key = self::key($author_addr);
446 logger("Couldn't get a key for handle " . $author_addr . ". Discarding.");
450 System::httpExit(400);
454 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
456 logger('Message did not verify. Discarding.');
460 System::httpExit(400);
464 return ['message' => (string)base64url_decode($base->data),
465 'author' => unxmlify($author_addr),
466 'key' => (string)$key];
470 * @brief: Decodes incoming Diaspora message in the deprecated format
472 * @param array $importer Array of the importer user
473 * @param string $xml urldecoded Diaspora salmon
476 * 'message' -> decoded Diaspora XML message
477 * 'author' -> author diaspora handle
478 * 'key' -> author public key (converted to pkcs#8)
480 public static function decode(array $importer, $xml)
483 $basedom = XML::parseString($xml);
485 if (!is_object($basedom)) {
486 logger("XML is not parseable.");
489 $children = $basedom->children('https://joindiaspora.com/protocol');
491 $inner_aes_key = null;
494 if ($children->header) {
496 $author_link = str_replace('acct:', '', $children->header->author_id);
498 // This happens with posts from a relais
500 logger("This is no private post in the old format", LOGGER_DEBUG);
504 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
506 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
507 $ciphertext = base64_decode($encrypted_header->ciphertext);
509 $outer_key_bundle = '';
510 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
512 $j_outer_key_bundle = json_decode($outer_key_bundle);
514 $outer_iv = base64_decode($j_outer_key_bundle->iv);
515 $outer_key = base64_decode($j_outer_key_bundle->key);
517 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
519 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
520 $idom = XML::parseString($decrypted);
522 $inner_iv = base64_decode($idom->iv);
523 $inner_aes_key = base64_decode($idom->aes_key);
525 $author_link = str_replace('acct:', '', $idom->author_id);
528 $dom = $basedom->children(NAMESPACE_SALMON_ME);
530 // figure out where in the DOM tree our data is hiding
533 if ($dom->provenance->data) {
534 $base = $dom->provenance;
535 } elseif ($dom->env->data) {
537 } elseif ($dom->data) {
542 logger('unable to locate salmon data in xml');
543 System::httpExit(400);
547 // Stash the signature away for now. We have to find their key or it won't be good for anything.
548 $signature = base64url_decode($base->sig);
552 // strip whitespace so our data element will return to one big base64 blob
553 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
556 // stash away some other stuff for later
558 $type = $base->data[0]->attributes()->type[0];
559 $keyhash = $base->sig[0]->attributes()->keyhash[0];
560 $encoding = $base->encoding;
564 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
568 $data = base64url_decode($data);
572 $inner_decrypted = $data;
574 // Decode the encrypted blob
575 $inner_encrypted = base64_decode($data);
576 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
580 logger('Could not retrieve author URI.');
581 System::httpExit(400);
583 // Once we have the author URI, go to the web and try to find their public key
584 // (first this will look it up locally if it is in the fcontact cache)
585 // This will also convert diaspora public key from pkcs#1 to pkcs#8
587 logger('Fetching key for '.$author_link);
588 $key = self::key($author_link);
591 logger('Could not retrieve author key.');
592 System::httpExit(400);
595 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
598 logger('Message did not verify. Discarding.');
599 System::httpExit(400);
602 logger('Message verified.');
604 return ['message' => (string)$inner_decrypted,
605 'author' => unxmlify($author_link),
606 'key' => (string)$key];
611 * @brief Dispatches public messages and find the fitting receivers
613 * @param array $msg The post that will be dispatched
615 * @return int The message id of the generated message, "true" or "false" if there was an error
617 public static function dispatchPublic($msg)
619 $enabled = intval(Config::get("system", "diaspora_enabled"));
621 logger("diaspora is disabled");
625 if (!($fields = self::validPosting($msg))) {
626 logger("Invalid posting");
630 $importer = ["uid" => 0, "page-flags" => Contact::PAGE_FREELOVE];
631 $success = self::dispatch($importer, $msg, $fields);
637 * @brief Dispatches the different message types to the different functions
639 * @param array $importer Array of the importer user
640 * @param array $msg The post that will be dispatched
641 * @param object $fields SimpleXML object that contains the message
643 * @return int The message id of the generated message, "true" or "false" if there was an error
645 public static function dispatch(array $importer, $msg, $fields = null)
647 // The sender is the handle of the contact that sent the message.
648 // This will often be different with relayed messages (for example "like" and "comment")
649 $sender = $msg["author"];
651 // This is only needed for private postings since this is already done for public ones before
652 if (is_null($fields)) {
654 if (!($fields = self::validPosting($msg))) {
655 logger("Invalid posting");
662 $type = $fields->getName();
664 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
667 case "account_migration":
669 logger('Message with type ' . $type . ' is not private, quitting.');
672 return self::receiveAccountMigration($importer, $fields);
674 case "account_deletion":
675 return self::receiveAccountDeletion($fields);
678 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
682 logger('Message with type ' . $type . ' is not private, quitting.');
685 return self::receiveContactRequest($importer, $fields);
689 logger('Message with type ' . $type . ' is not private, quitting.');
692 return self::receiveConversation($importer, $msg, $fields);
695 return self::receiveLike($importer, $sender, $fields);
699 logger('Message with type ' . $type . ' is not private, quitting.');
702 return self::receiveMessage($importer, $fields);
704 case "participation":
706 logger('Message with type ' . $type . ' is not private, quitting.');
709 return self::receiveParticipation($importer, $fields);
711 case "photo": // Not implemented
712 return self::receivePhoto($importer, $fields);
714 case "poll_participation": // Not implemented
715 return self::receivePollParticipation($importer, $fields);
719 logger('Message with type ' . $type . ' is not private, quitting.');
722 return self::receiveProfile($importer, $fields);
725 return self::receiveReshare($importer, $fields, $msg["message"]);
728 return self::receiveRetraction($importer, $sender, $fields);
730 case "status_message":
731 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
734 logger("Unknown message type ".$type);
742 * @brief Checks if a posting is valid and fetches the data fields.
744 * This function does not only check the signature.
745 * It also does the conversion between the old and the new diaspora format.
747 * @param array $msg Array with the XML, the sender handle and the sender signature
749 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
751 private static function validPosting($msg)
753 $data = XML::parseString($msg["message"]);
755 if (!is_object($data)) {
756 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
760 // Is this the new or the old version?
761 if ($data->getName() == "XML") {
763 foreach ($data->post->children() as $child) {
771 $type = $element->getName();
774 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
776 // All retractions are handled identically from now on.
777 // In the new version there will only be "retraction".
778 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
779 $type = "retraction";
781 if ($type == "request") {
785 $fields = new SimpleXMLElement("<".$type."/>");
788 $author_signature = null;
789 $parent_author_signature = null;
791 foreach ($element->children() as $fieldname => $entry) {
793 // Translation for the old XML structure
794 if ($fieldname == "diaspora_handle") {
795 $fieldname = "author";
797 if ($fieldname == "participant_handles") {
798 $fieldname = "participants";
800 if (in_array($type, ["like", "participation"])) {
801 if ($fieldname == "target_type") {
802 $fieldname = "parent_type";
805 if ($fieldname == "sender_handle") {
806 $fieldname = "author";
808 if ($fieldname == "recipient_handle") {
809 $fieldname = "recipient";
811 if ($fieldname == "root_diaspora_id") {
812 $fieldname = "root_author";
814 if ($type == "status_message") {
815 if ($fieldname == "raw_message") {
819 if ($type == "retraction") {
820 if ($fieldname == "post_guid") {
821 $fieldname = "target_guid";
823 if ($fieldname == "type") {
824 $fieldname = "target_type";
829 if (($fieldname == "author_signature") && ($entry != "")) {
830 $author_signature = base64_decode($entry);
831 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
832 $parent_author_signature = base64_decode($entry);
833 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
834 if ($signed_data != "") {
838 $signed_data .= $entry;
840 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
841 || ($orig_type == "relayable_retraction")
843 XML::copy($entry, $fields, $fieldname);
847 // This is something that shouldn't happen at all.
848 if (in_array($type, ["status_message", "reshare", "profile"])) {
849 if ($msg["author"] != $fields->author) {
850 logger("Message handle is not the same as envelope sender. Quitting this message.");
855 // Only some message types have signatures. So we quit here for the other types.
856 if (!in_array($type, ["comment", "like"])) {
859 // No author_signature? This is a must, so we quit.
860 if (!isset($author_signature)) {
861 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
865 if (isset($parent_author_signature)) {
866 $key = self::key($msg["author"]);
868 logger("No key found for parent author ".$msg["author"], LOGGER_DEBUG);
872 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
873 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);
878 $key = self::key($fields->author);
880 logger("No key found for author ".$fields->author, LOGGER_DEBUG);
884 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
885 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
893 * @brief Fetches the public key for a given handle
895 * @param string $handle The handle
897 * @return string The public key
899 private static function key($handle)
901 $handle = strval($handle);
903 logger("Fetching diaspora key for: ".$handle);
905 $r = self::personByHandle($handle);
914 * @brief Fetches data for a given handle
916 * @param string $handle The handle
918 * @return array the queried data
920 public static function personByHandle($handle)
924 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
925 if (DBA::isResult($person)) {
926 logger("In cache " . print_r($person, true), LOGGER_DEBUG);
928 // update record occasionally so it doesn't get stale
929 $d = strtotime($person["updated"]." +00:00");
930 if ($d < strtotime("now - 14 days")) {
934 if ($person["guid"] == "") {
939 if (!DBA::isResult($person) || $update) {
940 logger("create or refresh", LOGGER_DEBUG);
941 $r = Probe::uri($handle, Protocol::DIASPORA);
943 // Note that Friendica contacts will return a "Diaspora person"
944 // if Diaspora connectivity is enabled on their server
945 if ($r && ($r["network"] === Protocol::DIASPORA)) {
946 self::updateFContact($r);
948 // Fetch the updated or added contact
949 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
950 if (!DBA::isResult($person)) {
960 * @brief Updates the fcontact table
962 * @param array $arr The fcontact data
964 private static function updateFContact($arr)
966 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
967 'request' => $arr["request"], 'nick' => $arr["nick"],
968 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
969 'batch' => $arr["batch"], 'notify' => $arr["notify"],
970 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
971 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
972 'updated' => DateTimeFormat::utcNow()];
974 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
976 DBA::update('fcontact', $fields, $condition, true);
980 * @brief get a handle (user@domain.tld) from a given contact id
982 * @param int $contact_id The id in the contact table
983 * @param int $pcontact_id The id in the contact table (Used for the public contact)
985 * @return string the handle
987 private static function handleFromContact($contact_id, $pcontact_id = 0)
991 logger("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, LOGGER_DEBUG);
993 if ($pcontact_id != 0) {
994 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
996 if (DBA::isResult($contact) && !empty($contact["addr"])) {
997 return strtolower($contact["addr"]);
1002 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1006 if (DBA::isResult($r)) {
1009 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
1011 if ($contact['addr'] != "") {
1012 $handle = $contact['addr'];
1014 $baseurl_start = strpos($contact['url'], '://') + 3;
1015 // allows installations in a subdirectory--not sure how Diaspora will handle
1016 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1017 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1018 $handle = $contact['nick'].'@'.$baseurl;
1022 return strtolower($handle);
1026 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
1029 * @param mixed $fcontact_guid Hexadecimal string guid
1031 * @return string the contact url or null
1033 public static function urlFromContactGuid($fcontact_guid)
1035 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
1038 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1039 DBA::escape(Protocol::DIASPORA),
1040 DBA::escape($fcontact_guid)
1043 if (DBA::isResult($r)) {
1044 return $r[0]['url'];
1051 * @brief Get a contact id for a given handle
1053 * @todo Move to Friendica\Model\Contact
1055 * @param int $uid The user id
1056 * @param string $handle The handle in the format user@domain.tld
1058 * @return int Contact id
1060 private static function contactByHandle($uid, $handle)
1062 $cid = Contact::getIdForURL($handle, $uid);
1064 $handle_parts = explode("@", $handle);
1065 $nurl_sql = "%%://" . $handle_parts[1] . "%%/profile/" . $handle_parts[0];
1066 $cid = Contact::getIdForURL($nurl_sql, $uid);
1070 logger("Haven't found a contact for user " . $uid . " and handle " . $handle, LOGGER_DEBUG);
1074 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1075 if (!DBA::isResult($contact)) {
1076 // This here shouldn't happen at all
1077 logger("Haven't found a contact for user " . $uid . " and handle " . $handle, LOGGER_DEBUG);
1085 * @brief Check if posting is allowed for this contact
1087 * @param array $importer Array of the importer user
1088 * @param array $contact The contact that is checked
1089 * @param bool $is_comment Is the check for a comment?
1091 * @return bool is the contact allowed to post?
1093 private static function postAllow(array $importer, array $contact, $is_comment = false)
1096 * Perhaps we were already sharing with this person. Now they're sharing with us.
1097 * That makes us friends.
1098 * Normally this should have handled by getting a request - but this could get lost
1100 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1101 // It is not removed by now. Possibly the code is needed?
1102 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(Contact::PAGE_FREELOVE))) {
1105 // array('rel' => Contact::FRIEND, 'writable' => true),
1106 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1109 // $contact["rel"] = Contact::FRIEND;
1110 // logger("defining user ".$contact["nick"]." as friend");
1113 // We don't seem to like that person
1114 if ($contact["blocked"]) {
1115 // Maybe blocked, don't accept.
1117 // We are following this person?
1118 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1119 // Yes, then it is fine.
1121 // Is it a post to a community?
1122 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [Contact::PAGE_COMMUNITY, Contact::PAGE_PRVGROUP])) {
1125 // Is the message a global user or a comment?
1126 } elseif (($importer["uid"] == 0) || $is_comment) {
1127 // Messages for the global users and comments are always accepted
1135 * @brief Fetches the contact id for a handle and checks if posting is allowed
1137 * @param array $importer Array of the importer user
1138 * @param string $handle The checked handle in the format user@domain.tld
1139 * @param bool $is_comment Is the check for a comment?
1141 * @return array The contact data
1143 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1145 $contact = self::contactByHandle($importer["uid"], $handle);
1147 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1148 // If a contact isn't found, we accept it anyway if it is a comment
1149 if ($is_comment && ($importer["uid"] != 0)) {
1150 return self::contactByHandle(0, $handle);
1151 } elseif ($is_comment) {
1158 if (!self::postAllow($importer, $contact, $is_comment)) {
1159 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1166 * @brief Does the message already exists on the system?
1168 * @param int $uid The user id
1169 * @param string $guid The guid of the message
1171 * @return int|bool message id if the message already was stored into the system - or false.
1173 private static function messageExists($uid, $guid)
1175 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1176 if (DBA::isResult($item)) {
1177 logger("message ".$guid." already exists for user ".$uid);
1185 * @brief Checks for links to posts in a message
1187 * @param array $item The item array
1190 private static function fetchGuid(array $item)
1192 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1193 preg_replace_callback(
1195 function ($match) use ($item) {
1196 self::fetchGuidSub($match, $item);
1201 preg_replace_callback(
1202 "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1203 function ($match) use ($item) {
1204 self::fetchGuidSub($match, $item);
1211 * @brief Checks for relative /people/* links in an item body to match local
1212 * contacts or prepends the remote host taken from the author link.
1214 * @param string $body The item body to replace links from
1215 * @param string $author_link The author link for missing local contact fallback
1217 * @return string the replaced string
1219 public static function replacePeopleGuid($body, $author_link)
1221 $return = preg_replace_callback(
1222 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1223 function ($match) use ($author_link) {
1225 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1226 // 1 => '0123456789abcdef'
1228 $handle = self::urlFromContactGuid($match[1]);
1231 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1233 // No local match, restoring absolute remote URL from author scheme and host
1234 $author_url = parse_url($author_link);
1235 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1247 * @brief sub function of "fetchGuid" which checks for links in messages
1249 * @param array $match array containing a link that has to be checked for a message link
1250 * @param array $item The item array
1253 private static function fetchGuidSub($match, $item)
1255 if (!self::storeByGuid($match[1], $item["author-link"])) {
1256 self::storeByGuid($match[1], $item["owner-link"]);
1261 * @brief Fetches an item with a given guid from a given server
1263 * @param string $guid the message guid
1264 * @param string $server The server address
1265 * @param int $uid The user id of the user
1267 * @return int the message id of the stored message or false
1269 private static function storeByGuid($guid, $server, $uid = 0)
1271 $serverparts = parse_url($server);
1273 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1277 $server = $serverparts["scheme"]."://".$serverparts["host"];
1279 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1281 $msg = self::message($guid, $server);
1287 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1289 // Now call the dispatcher
1290 return self::dispatchPublic($msg);
1294 * @brief Fetches a message from a server
1296 * @param string $guid message guid
1297 * @param string $server The url of the server
1298 * @param int $level Endless loop prevention
1301 * 'message' => The message XML
1302 * 'author' => The author handle
1303 * 'key' => The public key of the author
1305 private static function message($guid, $server, $level = 0)
1311 // This will work for new Diaspora servers and Friendica servers from 3.5
1312 $source_url = $server."/fetch/post/".urlencode($guid);
1314 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1316 $envelope = Network::fetchUrl($source_url);
1318 logger("Envelope was fetched.", LOGGER_DEBUG);
1319 $x = self::verifyMagicEnvelope($envelope);
1321 logger("Envelope could not be verified.", LOGGER_DEBUG);
1323 logger("Envelope was verified.", LOGGER_DEBUG);
1329 // This will work for older Diaspora and Friendica servers
1331 $source_url = $server."/p/".urlencode($guid).".xml";
1332 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1334 $x = Network::fetchUrl($source_url);
1340 $source_xml = XML::parseString($x);
1342 if (!is_object($source_xml)) {
1346 if ($source_xml->post->reshare) {
1347 // Reshare of a reshare - old Diaspora version
1348 logger("Message is a reshare", LOGGER_DEBUG);
1349 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1350 } elseif ($source_xml->getName() == "reshare") {
1351 // Reshare of a reshare - new Diaspora version
1352 logger("Message is a new reshare", LOGGER_DEBUG);
1353 return self::message($source_xml->root_guid, $server, ++$level);
1358 // Fetch the author - for the old and the new Diaspora version
1359 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1360 $author = (string)$source_xml->post->status_message->diaspora_handle;
1361 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1362 $author = (string)$source_xml->author;
1365 // If this isn't a "status_message" then quit
1367 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1371 $msg = ["message" => $x, "author" => $author];
1373 $msg["key"] = self::key($msg["author"]);
1379 * @brief Fetches the item record of a given guid
1381 * @param int $uid The user id
1382 * @param string $guid message guid
1383 * @param string $author The handle of the item
1384 * @param array $contact The contact of the item owner
1386 * @return array the item record
1388 private static function parentItem($uid, $guid, $author, array $contact)
1390 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1391 'author-name', 'author-link', 'author-avatar',
1392 'owner-name', 'owner-link', 'owner-avatar'];
1393 $condition = ['uid' => $uid, 'guid' => $guid];
1394 $item = Item::selectFirst($fields, $condition);
1396 if (!DBA::isResult($item)) {
1397 $person = self::personByHandle($author);
1398 $result = self::storeByGuid($guid, $person["url"], $uid);
1400 // We don't have an url for items that arrived at the public dispatcher
1401 if (!$result && !empty($contact["url"])) {
1402 $result = self::storeByGuid($guid, $contact["url"], $uid);
1406 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1408 $item = Item::selectFirst($fields, $condition);
1412 if (!DBA::isResult($item)) {
1413 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1416 logger("parent item found: parent: ".$guid." - user: ".$uid);
1422 * @brief returns contact details
1424 * @param array $def_contact The default contact if the person isn't found
1425 * @param array $person The record of the person
1426 * @param int $uid The user id
1429 * 'cid' => contact id
1430 * 'network' => network type
1432 private static function authorContactByUrl($def_contact, $person, $uid)
1434 $condition = ['nurl' => normalise_link($person["url"]), 'uid' => $uid];
1435 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1436 if (DBA::isResult($contact)) {
1437 $cid = $contact["id"];
1438 $network = $contact["network"];
1440 $cid = $def_contact["id"];
1441 $network = Protocol::DIASPORA;
1444 return ["cid" => $cid, "network" => $network];
1448 * @brief Is the profile a hubzilla profile?
1450 * @param string $url The profile link
1452 * @return bool is it a hubzilla server?
1454 public static function isRedmatrix($url)
1456 return(strstr($url, "/channel/"));
1460 * @brief Generate a post link with a given handle and message guid
1462 * @param string $addr The user handle
1463 * @param string $guid message guid
1464 * @param string $parent_guid optional parent guid
1466 * @return string the post link
1468 private static function plink($addr, $guid, $parent_guid = '')
1470 $contact = Contact::getDetailsByAddr($addr);
1474 if ($parent_guid != '') {
1475 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1477 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1481 if ($contact["network"] == Protocol::DFRN) {
1482 return str_replace("/profile/" . $contact["nick"] . "/", "/display/" . $guid, $contact["url"] . "/");
1485 if (self::isRedmatrix($contact["url"])) {
1486 return $contact["url"] . "/?f=&mid=" . $guid;
1489 if ($parent_guid != '') {
1490 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1492 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1497 * @brief Receives account migration
1499 * @param array $importer Array of the importer user
1500 * @param object $data The message object
1502 * @return bool Success
1504 private static function receiveAccountMigration(array $importer, $data)
1506 $old_handle = notags(unxmlify($data->author));
1507 $new_handle = notags(unxmlify($data->profile->author));
1508 $signature = notags(unxmlify($data->signature));
1510 $contact = self::contactByHandle($importer["uid"], $old_handle);
1512 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1516 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1519 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1520 $key = self::key($old_handle);
1521 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1522 logger('No valid signature for migration.');
1526 // Update the profile
1527 self::receiveProfile($importer, $data->profile);
1529 // change the technical stuff in contact and gcontact
1530 $data = Probe::uri($new_handle);
1531 if ($data['network'] == Protocol::PHANTOM) {
1532 logger('Account for '.$new_handle." couldn't be probed.");
1536 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1537 'name' => $data['name'], 'nick' => $data['nick'],
1538 'addr' => $data['addr'], 'batch' => $data['batch'],
1539 'notify' => $data['notify'], 'poll' => $data['poll'],
1540 'network' => $data['network']];
1542 DBA::update('contact', $fields, ['addr' => $old_handle]);
1544 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1545 'name' => $data['name'], 'nick' => $data['nick'],
1546 'addr' => $data['addr'], 'connect' => $data['addr'],
1547 'notify' => $data['notify'], 'photo' => $data['photo'],
1548 'server_url' => $data['baseurl'], 'network' => $data['network']];
1550 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1552 logger('Contacts are updated.');
1558 * @brief Processes an account deletion
1560 * @param object $data The message object
1562 * @return bool Success
1564 private static function receiveAccountDeletion($data)
1566 $author = notags(unxmlify($data->author));
1568 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1569 while ($contact = DBA::fetch($contacts)) {
1570 Contact::remove($contact["id"]);
1573 DBA::delete('gcontact', ['addr' => $author]);
1575 logger('Removed contacts for ' . $author);
1581 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1583 * @param string $author Author handle
1584 * @param string $guid Message guid
1585 * @param boolean $onlyfound Only return uri when found in the database
1587 * @return string The constructed uri or the one from our database
1589 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1591 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1592 if (DBA::isResult($item)) {
1593 return $item["uri"];
1594 } elseif (!$onlyfound) {
1595 $contact = Contact::getDetailsByAddr($author, 0);
1596 if (!empty($contact['network'])) {
1597 $prefix = 'urn:X-' . $contact['network'] . ':';
1599 // This fallback should happen most unlikely
1600 $prefix = 'urn:X-dspr:';
1603 $author_parts = explode('@', $author);
1605 return $prefix . $author_parts[1] . ':' . $author_parts[0] . ':'. $guid;
1612 * @brief Fetch the guid from our database with a given uri
1614 * @param string $uri Message uri
1615 * @param string $uid Author handle
1617 * @return string The post guid
1619 private static function getGuidFromUri($uri, $uid)
1621 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1622 if (DBA::isResult($item)) {
1623 return $item["guid"];
1630 * @brief Find the best importer for a comment, like, ...
1632 * @param string $guid The guid of the item
1634 * @return array|boolean the origin owner of that post - or false
1636 private static function importerForGuid($guid)
1638 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1639 if (DBA::isResult($item)) {
1640 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1641 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1642 if (DBA::isResult($contact)) {
1650 * @brief Processes an incoming comment
1652 * @param array $importer Array of the importer user
1653 * @param string $sender The sender of the message
1654 * @param object $data The message object
1655 * @param string $xml The original XML of the message
1657 * @return int The message id of the generated comment or "false" if there was an error
1659 private static function receiveComment(array $importer, $sender, $data, $xml)
1661 $author = notags(unxmlify($data->author));
1662 $guid = notags(unxmlify($data->guid));
1663 $parent_guid = notags(unxmlify($data->parent_guid));
1664 $text = unxmlify($data->text);
1666 if (isset($data->created_at)) {
1667 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1669 $created_at = DateTimeFormat::utcNow();
1672 if (isset($data->thread_parent_guid)) {
1673 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1674 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1679 $contact = self::allowedContactByHandle($importer, $sender, true);
1684 $message_id = self::messageExists($importer["uid"], $guid);
1689 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1690 if (!$parent_item) {
1694 $person = self::personByHandle($author);
1695 if (!is_array($person)) {
1696 logger("unable to find author details");
1700 // Fetch the contact id - if we know this contact
1701 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1705 $datarray["uid"] = $importer["uid"];
1706 $datarray["contact-id"] = $author_contact["cid"];
1707 $datarray["network"] = $author_contact["network"];
1709 $datarray["author-link"] = $person["url"];
1710 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1712 $datarray["owner-link"] = $contact["url"];
1713 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1715 $datarray["guid"] = $guid;
1716 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1718 $datarray["verb"] = ACTIVITY_POST;
1719 $datarray["gravity"] = GRAVITY_COMMENT;
1721 if ($thr_uri != "") {
1722 $datarray["parent-uri"] = $thr_uri;
1724 $datarray["parent-uri"] = $parent_item["uri"];
1727 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1729 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1730 $datarray["source"] = $xml;
1732 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1734 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1736 $body = Markdown::toBBCode($text);
1738 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1740 self::fetchGuid($datarray);
1742 // If we are the origin of the parent we store the original data.
1743 // We notify our followers during the item storage.
1744 if ($parent_item["origin"]) {
1745 $datarray['diaspora_signed_text'] = json_encode($data);
1748 $message_id = Item::insert($datarray);
1750 if ($message_id <= 0) {
1755 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1756 if ($datarray['uid'] == 0) {
1757 Item::distribute($message_id, json_encode($data));
1765 * @brief processes and stores private messages
1767 * @param array $importer Array of the importer user
1768 * @param array $contact The contact of the message
1769 * @param object $data The message object
1770 * @param array $msg Array of the processed message, author handle and key
1771 * @param object $mesg The private message
1772 * @param array $conversation The conversation record to which this message belongs
1774 * @return bool "true" if it was successful
1776 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1778 $author = notags(unxmlify($data->author));
1779 $guid = notags(unxmlify($data->guid));
1780 $subject = notags(unxmlify($data->subject));
1782 // "diaspora_handle" is the element name from the old version
1783 // "author" is the element name from the new version
1784 if ($mesg->author) {
1785 $msg_author = notags(unxmlify($mesg->author));
1786 } elseif ($mesg->diaspora_handle) {
1787 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1792 $msg_guid = notags(unxmlify($mesg->guid));
1793 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1794 $msg_text = unxmlify($mesg->text);
1795 $msg_created_at = DateTimeFormat::utc(notags(unxmlify($mesg->created_at)));
1797 if ($msg_conversation_guid != $guid) {
1798 logger("message conversation guid does not belong to the current conversation.");
1802 $body = Markdown::toBBCode($msg_text);
1803 $message_uri = $msg_author.":".$msg_guid;
1805 $person = self::personByHandle($msg_author);
1809 if (DBA::exists('mail', ['guid' => $msg_guid, 'uid' => $importer["uid"]])) {
1810 logger("duplicate message already delivered.", LOGGER_DEBUG);
1815 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1816 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1817 intval($importer["uid"]),
1818 DBA::escape($msg_guid),
1819 intval($conversation["id"]),
1820 DBA::escape($person["name"]),
1821 DBA::escape($person["photo"]),
1822 DBA::escape($person["url"]),
1823 intval($contact["id"]),
1824 DBA::escape($subject),
1828 DBA::escape($message_uri),
1829 DBA::escape($author.":".$guid),
1830 DBA::escape($msg_created_at)
1835 DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
1839 "type" => NOTIFY_MAIL,
1840 "notify_flags" => $importer["notify-flags"],
1841 "language" => $importer["language"],
1842 "to_name" => $importer["username"],
1843 "to_email" => $importer["email"],
1844 "uid" =>$importer["uid"],
1845 "item" => ["id" => $conversation["id"], "title" => $subject, "subject" => $subject, "body" => $body],
1846 "source_name" => $person["name"],
1847 "source_link" => $person["url"],
1848 "source_photo" => $person["photo"],
1849 "verb" => ACTIVITY_POST,
1856 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1858 * @param array $importer Array of the importer user
1859 * @param array $msg Array of the processed message, author handle and key
1860 * @param object $data The message object
1862 * @return bool Success
1864 private static function receiveConversation(array $importer, $msg, $data)
1866 $author = notags(unxmlify($data->author));
1867 $guid = notags(unxmlify($data->guid));
1868 $subject = notags(unxmlify($data->subject));
1869 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1870 $participants = notags(unxmlify($data->participants));
1872 $messages = $data->message;
1874 if (!count($messages)) {
1875 logger("empty conversation");
1879 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1884 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1885 if (!DBA::isResult($conversation)) {
1887 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1888 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1889 intval($importer["uid"]),
1891 DBA::escape($author),
1892 DBA::escape($created_at),
1893 DBA::escape(DateTimeFormat::utcNow()),
1894 DBA::escape($subject),
1895 DBA::escape($participants)
1898 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1901 if (!$conversation) {
1902 logger("unable to create conversation.");
1906 foreach ($messages as $mesg) {
1907 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1914 * @brief Processes "like" messages
1916 * @param array $importer Array of the importer user
1917 * @param string $sender The sender of the message
1918 * @param object $data The message object
1920 * @return int The message id of the generated like or "false" if there was an error
1922 private static function receiveLike(array $importer, $sender, $data)
1924 $author = notags(unxmlify($data->author));
1925 $guid = notags(unxmlify($data->guid));
1926 $parent_guid = notags(unxmlify($data->parent_guid));
1927 $parent_type = notags(unxmlify($data->parent_type));
1928 $positive = notags(unxmlify($data->positive));
1930 // likes on comments aren't supported by Diaspora - only on posts
1931 // But maybe this will be supported in the future, so we will accept it.
1932 if (!in_array($parent_type, ["Post", "Comment"])) {
1936 $contact = self::allowedContactByHandle($importer, $sender, true);
1941 $message_id = self::messageExists($importer["uid"], $guid);
1946 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1947 if (!$parent_item) {
1951 $person = self::personByHandle($author);
1952 if (!is_array($person)) {
1953 logger("unable to find author details");
1957 // Fetch the contact id - if we know this contact
1958 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1960 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1961 // We would accept this anyhow.
1962 if ($positive == "true") {
1963 $verb = ACTIVITY_LIKE;
1965 $verb = ACTIVITY_DISLIKE;
1970 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1972 $datarray["uid"] = $importer["uid"];
1973 $datarray["contact-id"] = $author_contact["cid"];
1974 $datarray["network"] = $author_contact["network"];
1976 $datarray["author-link"] = $person["url"];
1977 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1979 $datarray["owner-link"] = $contact["url"];
1980 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1982 $datarray["guid"] = $guid;
1983 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1985 $datarray["verb"] = $verb;
1986 $datarray["gravity"] = GRAVITY_ACTIVITY;
1987 $datarray["parent-uri"] = $parent_item["uri"];
1989 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1991 $datarray["body"] = $verb;
1993 // Diaspora doesn't provide a date for likes
1994 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
1996 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1997 if ($parent_item["id"] != $parent_item["parent"]) {
1998 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
1999 $origin = $toplevel["origin"];
2001 $origin = $parent_item["origin"];
2004 // If we are the origin of the parent we store the original data.
2005 // We notify our followers during the item storage.
2007 $datarray['diaspora_signed_text'] = json_encode($data);
2010 $message_id = Item::insert($datarray);
2012 if ($message_id <= 0) {
2017 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2018 if ($datarray['uid'] == 0) {
2019 Item::distribute($message_id, json_encode($data));
2027 * @brief Processes private messages
2029 * @param array $importer Array of the importer user
2030 * @param object $data The message object
2032 * @return bool Success?
2034 private static function receiveMessage(array $importer, $data)
2036 $author = notags(unxmlify($data->author));
2037 $guid = notags(unxmlify($data->guid));
2038 $conversation_guid = notags(unxmlify($data->conversation_guid));
2039 $text = unxmlify($data->text);
2040 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2042 $contact = self::allowedContactByHandle($importer, $author, true);
2047 $conversation = null;
2049 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2050 $conversation = DBA::selectFirst('conv', [], $condition);
2052 if (!DBA::isResult($conversation)) {
2053 logger("conversation not available.");
2057 $message_uri = $author.":".$guid;
2059 $person = self::personByHandle($author);
2061 logger("unable to find author details");
2065 $body = Markdown::toBBCode($text);
2067 $body = self::replacePeopleGuid($body, $person["url"]);
2071 if (DBA::exists('mail', ['guid' => $guid, 'uid' => $importer["uid"]])) {
2072 logger("duplicate message already delivered.", LOGGER_DEBUG);
2077 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2078 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2079 intval($importer["uid"]),
2081 intval($conversation["id"]),
2082 DBA::escape($person["name"]),
2083 DBA::escape($person["photo"]),
2084 DBA::escape($person["url"]),
2085 intval($contact["id"]),
2086 DBA::escape($conversation["subject"]),
2090 DBA::escape($message_uri),
2091 DBA::escape($author.":".$conversation["guid"]),
2092 DBA::escape($created_at)
2097 DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
2102 * @brief Processes participations - unsupported by now
2104 * @param array $importer Array of the importer user
2105 * @param object $data The message object
2107 * @return bool always true
2109 private static function receiveParticipation(array $importer, $data)
2111 $author = strtolower(notags(unxmlify($data->author)));
2112 $parent_guid = notags(unxmlify($data->parent_guid));
2114 $contact_id = Contact::getIdForURL($author);
2116 logger('Contact not found: '.$author);
2120 $person = self::personByHandle($author);
2121 if (!is_array($person)) {
2122 logger("Person not found: ".$author);
2126 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2127 if (!DBA::isResult($item)) {
2128 logger('Item not found, no origin or private: '.$parent_guid);
2132 $author_parts = explode('@', $author);
2133 if (isset($author_parts[1])) {
2134 $server = $author_parts[1];
2136 // Should never happen
2140 logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
2142 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2143 DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2146 // Send all existing comments and likes to the requesting server
2147 $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2148 while ($comment = Item::fetch($comments)) {
2149 if ($comment['id'] == $comment['parent']) {
2152 if ($comment['verb'] == ACTIVITY_POST) {
2153 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2155 $cmd = $comment['self'] ? 'like' : 'comment-import';
2157 logger("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, LOGGER_DEBUG);
2158 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2160 DBA::close($comments);
2166 * @brief Processes photos - unneeded
2168 * @param array $importer Array of the importer user
2169 * @param object $data The message object
2171 * @return bool always true
2173 private static function receivePhoto(array $importer, $data)
2175 // There doesn't seem to be a reason for this function,
2176 // since the photo data is transmitted in the status message as well
2181 * @brief Processes poll participations - unssupported
2183 * @param array $importer Array of the importer user
2184 * @param object $data The message object
2186 * @return bool always true
2188 private static function receivePollParticipation(array $importer, $data)
2190 // We don't support polls by now
2195 * @brief Processes incoming profile updates
2197 * @param array $importer Array of the importer user
2198 * @param object $data The message object
2200 * @return bool Success
2202 private static function receiveProfile(array $importer, $data)
2204 $author = strtolower(notags(unxmlify($data->author)));
2206 $contact = self::contactByHandle($importer["uid"], $author);
2211 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2212 $image_url = unxmlify($data->image_url);
2213 $birthday = unxmlify($data->birthday);
2214 $gender = unxmlify($data->gender);
2215 $about = Markdown::toBBCode(unxmlify($data->bio));
2216 $location = Markdown::toBBCode(unxmlify($data->location));
2217 $searchable = (unxmlify($data->searchable) == "true");
2218 $nsfw = (unxmlify($data->nsfw) == "true");
2219 $tags = unxmlify($data->tag_string);
2221 $tags = explode("#", $tags);
2224 foreach ($tags as $tag) {
2225 $tag = trim(strtolower($tag));
2231 $keywords = implode(", ", $keywords);
2233 $handle_parts = explode("@", $author);
2234 $nick = $handle_parts[0];
2237 $name = $handle_parts[0];
2240 if (preg_match("|^https?://|", $image_url) === 0) {
2241 $image_url = "http://".$handle_parts[1].$image_url;
2244 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2246 // Generic birthday. We don't know the timezone. The year is irrelevant.
2248 $birthday = str_replace("1000", "1901", $birthday);
2250 if ($birthday != "") {
2251 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2254 // this is to prevent multiple birthday notifications in a single year
2255 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2257 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2258 $birthday = $contact["bd"];
2261 $fields = ['name' => $name, 'location' => $location,
2262 'name-date' => DateTimeFormat::utcNow(),
2263 'about' => $about, 'gender' => $gender,
2264 'addr' => $author, 'nick' => $nick,
2265 'keywords' => $keywords];
2267 if (!empty($birthday)) {
2268 $fields['bd'] = $birthday;
2271 DBA::update('contact', $fields, ['id' => $contact['id']]);
2273 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2274 "photo" => $image_url, "name" => $name, "location" => $location,
2275 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2276 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2277 "hide" => !$searchable, "nsfw" => $nsfw];
2279 $gcid = GContact::update($gcontact);
2281 GContact::link($gcid, $importer["uid"], $contact["id"]);
2283 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2289 * @brief Processes incoming friend requests
2291 * @param array $importer Array of the importer user
2292 * @param array $contact The contact that send the request
2295 private static function receiveRequestMakeFriend(array $importer, array $contact)
2299 if ($contact["rel"] == Contact::SHARING) {
2302 ['rel' => Contact::FRIEND, 'writable' => true],
2303 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2309 * @brief Processes incoming sharing notification
2311 * @param array $importer Array of the importer user
2312 * @param object $data The message object
2314 * @return bool Success
2316 private static function receiveContactRequest(array $importer, $data)
2318 $author = unxmlify($data->author);
2319 $recipient = unxmlify($data->recipient);
2321 if (!$author || !$recipient) {
2325 // the current protocol version doesn't know these fields
2326 // That means that we will assume their existance
2327 if (isset($data->following)) {
2328 $following = (unxmlify($data->following) == "true");
2333 if (isset($data->sharing)) {
2334 $sharing = (unxmlify($data->sharing) == "true");
2339 $contact = self::contactByHandle($importer["uid"], $author);
2341 // perhaps we were already sharing with this person. Now they're sharing with us.
2342 // That makes us friends.
2345 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2346 self::receiveRequestMakeFriend($importer, $contact);
2348 // refetch the contact array
2349 $contact = self::contactByHandle($importer["uid"], $author);
2351 // If we are now friends, we are sending a share message.
2352 // Normally we needn't to do so, but the first message could have been vanished.
2353 if (in_array($contact["rel"], [Contact::FRIEND])) {
2354 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2355 if (DBA::isResult($user)) {
2356 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2357 $ret = self::sendShare($user, $contact);
2362 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2363 Contact::removeFollower($importer, $contact);
2368 if (!$following && $sharing && in_array($importer["page-flags"], [Contact::PAGE_SOAPBOX, Contact::PAGE_NORMAL])) {
2369 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2371 } elseif (!$following && !$sharing) {
2372 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2374 } elseif (!$following && $sharing) {
2375 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2376 } elseif ($following && $sharing) {
2377 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2378 } elseif ($following && !$sharing) {
2379 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2382 $ret = self::personByHandle($author);
2384 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2385 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2389 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2392 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2393 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2394 intval($importer["uid"]),
2395 DBA::escape($ret["network"]),
2396 DBA::escape($ret["addr"]),
2397 DateTimeFormat::utcNow(),
2398 DBA::escape($ret["url"]),
2399 DBA::escape(normalise_link($ret["url"])),
2400 DBA::escape($batch),
2401 DBA::escape($ret["name"]),
2402 DBA::escape($ret["nick"]),
2403 DBA::escape($ret["photo"]),
2404 DBA::escape($ret["pubkey"]),
2405 DBA::escape($ret["notify"]),
2406 DBA::escape($ret["poll"]),
2411 // find the contact record we just created
2413 $contact_record = self::contactByHandle($importer["uid"], $author);
2415 if (!$contact_record) {
2416 logger("unable to locate newly created contact record.");
2420 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2422 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2424 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2426 if (in_array($importer["page-flags"], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP])) {
2427 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2429 $hash = random_string().(string)time(); // Generate a confirm_key
2432 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2433 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2434 intval($importer["uid"]),
2435 intval($contact_record["id"]),
2438 DBA::escape(L10n::t("Sharing notification from Diaspora network")),
2440 DBA::escape(DateTimeFormat::utcNow())
2443 // automatic friend approval
2445 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2447 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2450 * technically they are sharing with us (Contact::SHARING),
2451 * but if our page-type is Profile::PAGE_COMMUNITY or Profile::PAGE_SOAPBOX
2452 * we are going to change the relationship and make them a follower.
2454 if (($importer["page-flags"] == Contact::PAGE_FREELOVE) && $sharing && $following) {
2455 $new_relation = Contact::FRIEND;
2456 } elseif (($importer["page-flags"] == Contact::PAGE_FREELOVE) && $sharing) {
2457 $new_relation = Contact::SHARING;
2459 $new_relation = Contact::FOLLOWER;
2463 "UPDATE `contact` SET `rel` = %d,
2471 intval($new_relation),
2472 DBA::escape(DateTimeFormat::utcNow()),
2473 DBA::escape(DateTimeFormat::utcNow()),
2474 intval($contact_record["id"])
2477 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2478 if (DBA::isResult($user)) {
2479 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2480 $ret = self::sendShare($user, $contact_record);
2482 // Send the profile data, maybe it weren't transmitted before
2483 self::sendProfile($importer["uid"], [$contact_record]);
2491 * @brief Fetches a message with a given guid
2493 * @param string $guid message guid
2494 * @param string $orig_author handle of the original post
2495 * @param string $author handle of the sharer
2497 * @return array The fetched item
2499 public static function originalItem($guid, $orig_author)
2502 logger('Empty guid. Quitting.');
2506 // Do we already have this item?
2507 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2508 'author-name', 'author-link', 'author-avatar'];
2509 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2510 $item = Item::selectFirst($fields, $condition);
2512 if (DBA::isResult($item)) {
2513 logger("reshared message ".$guid." already exists on system.");
2515 // Maybe it is already a reshared item?
2516 // Then refetch the content, if it is a reshare from a reshare.
2517 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2518 if (self::isReshare($item["body"], true)) {
2520 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2521 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2523 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2525 // Add OEmbed and other information to the body
2526 $item["body"] = add_page_info_to_body($item["body"], false, true);
2534 if (!DBA::isResult($item)) {
2535 if (empty($orig_author)) {
2536 logger('Empty author for guid ' . $guid . '. Quitting.');
2540 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2541 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2542 $stored = self::storeByGuid($guid, $server);
2545 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2546 logger("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2547 $stored = self::storeByGuid($guid, $server);
2551 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2552 'author-name', 'author-link', 'author-avatar'];
2553 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2554 $item = Item::selectFirst($fields, $condition);
2556 if (DBA::isResult($item)) {
2557 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2558 if (self::isReshare($item["body"], false)) {
2559 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2560 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2571 * @brief Processes a reshare message
2573 * @param array $importer Array of the importer user
2574 * @param object $data The message object
2575 * @param string $xml The original XML of the message
2577 * @return int the message id
2579 private static function receiveReshare(array $importer, $data, $xml)
2581 $author = notags(unxmlify($data->author));
2582 $guid = notags(unxmlify($data->guid));
2583 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2584 $root_author = notags(unxmlify($data->root_author));
2585 $root_guid = notags(unxmlify($data->root_guid));
2586 /// @todo handle unprocessed property "provider_display_name"
2587 $public = notags(unxmlify($data->public));
2589 $contact = self::allowedContactByHandle($importer, $author, false);
2594 $message_id = self::messageExists($importer["uid"], $guid);
2599 $original_item = self::originalItem($root_guid, $root_author);
2600 if (!$original_item) {
2604 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2608 $datarray["uid"] = $importer["uid"];
2609 $datarray["contact-id"] = $contact["id"];
2610 $datarray["network"] = Protocol::DIASPORA;
2612 $datarray["author-link"] = $contact["url"];
2613 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2615 $datarray["owner-link"] = $datarray["author-link"];
2616 $datarray["owner-id"] = $datarray["author-id"];
2618 $datarray["guid"] = $guid;
2619 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2621 $datarray["verb"] = ACTIVITY_POST;
2622 $datarray["gravity"] = GRAVITY_PARENT;
2624 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2625 $datarray["source"] = $xml;
2627 $prefix = share_header(
2628 $original_item["author-name"],
2629 $original_item["author-link"],
2630 $original_item["author-avatar"],
2631 $original_item["guid"],
2632 $original_item["created"],
2635 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2637 $datarray["tag"] = $original_item["tag"];
2638 $datarray["app"] = $original_item["app"];
2640 $datarray["plink"] = self::plink($author, $guid);
2641 $datarray["private"] = (($public == "false") ? 1 : 0);
2642 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2644 $datarray["object-type"] = $original_item["object-type"];
2646 self::fetchGuid($datarray);
2647 $message_id = Item::insert($datarray);
2649 self::sendParticipation($contact, $datarray);
2652 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2653 if ($datarray['uid'] == 0) {
2654 Item::distribute($message_id);
2663 * @brief Processes retractions
2665 * @param array $importer Array of the importer user
2666 * @param array $contact The contact of the item owner
2667 * @param object $data The message object
2669 * @return bool success
2671 private static function itemRetraction(array $importer, array $contact, $data)
2673 $author = notags(unxmlify($data->author));
2674 $target_guid = notags(unxmlify($data->target_guid));
2675 $target_type = notags(unxmlify($data->target_type));
2677 $person = self::personByHandle($author);
2678 if (!is_array($person)) {
2679 logger("unable to find author detail for ".$author);
2683 if (empty($contact["url"])) {
2684 $contact["url"] = $person["url"];
2687 // Fetch items that are about to be deleted
2688 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2690 // When we receive a public retraction, we delete every item that we find.
2691 if ($importer['uid'] == 0) {
2692 $condition = ['guid' => $target_guid, 'deleted' => false];
2694 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2697 $r = Item::select($fields, $condition);
2698 if (!DBA::isResult($r)) {
2699 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2703 while ($item = Item::fetch($r)) {
2704 if (strstr($item['file'], '[')) {
2705 logger("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", LOGGER_DEBUG);
2709 // Fetch the parent item
2710 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2712 // Only delete it if the parent author really fits
2713 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2714 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2718 Item::delete(['id' => $item['id']]);
2720 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2727 * @brief Receives retraction messages
2729 * @param array $importer Array of the importer user
2730 * @param string $sender The sender of the message
2731 * @param object $data The message object
2733 * @return bool Success
2735 private static function receiveRetraction(array $importer, $sender, $data)
2737 $target_type = notags(unxmlify($data->target_type));
2739 $contact = self::contactByHandle($importer["uid"], $sender);
2740 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2741 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2749 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2751 switch ($target_type) {
2756 case "StatusMessage":
2757 return self::itemRetraction($importer, $contact, $data);
2759 case "PollParticipation":
2761 // Currently unsupported
2765 logger("Unknown target type ".$target_type);
2772 * @brief Receives status messages
2774 * @param array $importer Array of the importer user
2775 * @param object $data The message object
2776 * @param string $xml The original XML of the message
2778 * @return int The message id of the newly created item
2780 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2782 $author = notags(unxmlify($data->author));
2783 $guid = notags(unxmlify($data->guid));
2784 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2785 $public = notags(unxmlify($data->public));
2786 $text = unxmlify($data->text);
2787 $provider_display_name = notags(unxmlify($data->provider_display_name));
2789 $contact = self::allowedContactByHandle($importer, $author, false);
2794 $message_id = self::messageExists($importer["uid"], $guid);
2800 if ($data->location) {
2801 foreach ($data->location->children() as $fieldname => $data) {
2802 $address[$fieldname] = notags(unxmlify($data));
2806 $body = Markdown::toBBCode($text);
2810 // Attach embedded pictures to the body
2812 foreach ($data->photo as $photo) {
2813 $body = "[img]".unxmlify($photo->remote_photo_path).
2814 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2817 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2819 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2821 // Add OEmbed and other information to the body
2822 if (!self::isRedmatrix($contact["url"])) {
2823 $body = add_page_info_to_body($body, false, true);
2827 /// @todo enable support for polls
2828 //if ($data->poll) {
2829 // foreach ($data->poll AS $poll)
2834 /// @todo enable support for events
2836 $datarray["uid"] = $importer["uid"];
2837 $datarray["contact-id"] = $contact["id"];
2838 $datarray["network"] = Protocol::DIASPORA;
2840 $datarray["author-link"] = $contact["url"];
2841 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2843 $datarray["owner-link"] = $datarray["author-link"];
2844 $datarray["owner-id"] = $datarray["author-id"];
2846 $datarray["guid"] = $guid;
2847 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2849 $datarray["verb"] = ACTIVITY_POST;
2850 $datarray["gravity"] = GRAVITY_PARENT;
2852 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2853 $datarray["source"] = $xml;
2855 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2857 if ($provider_display_name != "") {
2858 $datarray["app"] = $provider_display_name;
2861 $datarray["plink"] = self::plink($author, $guid);
2862 $datarray["private"] = (($public == "false") ? 1 : 0);
2863 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2865 if (isset($address["address"])) {
2866 $datarray["location"] = $address["address"];
2869 if (isset($address["lat"]) && isset($address["lng"])) {
2870 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2873 self::fetchGuid($datarray);
2874 $message_id = Item::insert($datarray);
2876 self::sendParticipation($contact, $datarray);
2879 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2880 if ($datarray['uid'] == 0) {
2881 Item::distribute($message_id);
2889 /* ************************************************************************************** *
2890 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2891 * ************************************************************************************** */
2894 * @brief returnes the handle of a contact
2896 * @param array $contact contact array
2898 * @return string the handle in the format user@domain.tld
2900 private static function myHandle(array $contact)
2902 if (!empty($contact["addr"])) {
2903 return $contact["addr"];
2906 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2907 // So - just in case - we build the the address here.
2908 if ($contact["nickname"] != "") {
2909 $nick = $contact["nickname"];
2911 $nick = $contact["nick"];
2914 return $nick . "@" . substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
2919 * @brief Creates the data for a private message in the new format
2921 * @param string $msg The message that is to be transmitted
2922 * @param array $user The record of the sender
2923 * @param array $contact Target of the communication
2924 * @param string $prvkey The private key of the sender
2925 * @param string $pubkey The public key of the receiver
2927 * @return string The encrypted data
2929 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
2931 logger("Message: ".$msg, LOGGER_DATA);
2933 // without a public key nothing will work
2935 logger("pubkey missing: contact id: ".$contact["id"]);
2939 $aes_key = openssl_random_pseudo_bytes(32);
2940 $b_aes_key = base64_encode($aes_key);
2941 $iv = openssl_random_pseudo_bytes(16);
2942 $b_iv = base64_encode($iv);
2944 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2946 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
2948 $encrypted_key_bundle = "";
2949 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
2951 $json_object = json_encode(
2952 ["aes_key" => base64_encode($encrypted_key_bundle),
2953 "encrypted_magic_envelope" => base64_encode($ciphertext)]
2956 return $json_object;
2960 * @brief Creates the envelope for the "fetch" endpoint and for the new format
2962 * @param string $msg The message that is to be transmitted
2963 * @param array $user The record of the sender
2965 * @return string The envelope
2967 public static function buildMagicEnvelope($msg, array $user)
2969 $b64url_data = base64url_encode($msg);
2970 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
2972 $key_id = base64url_encode(self::myHandle($user));
2973 $type = "application/xml";
2974 $encoding = "base64url";
2975 $alg = "RSA-SHA256";
2976 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2978 // Fallback if the private key wasn't transmitted in the expected field
2979 if ($user['uprvkey'] == "") {
2980 $user['uprvkey'] = $user['prvkey'];
2983 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
2984 $sig = base64url_encode($signature);
2986 $xmldata = ["me:env" => ["me:data" => $data,
2987 "@attributes" => ["type" => $type],
2988 "me:encoding" => $encoding,
2991 "@attributes2" => ["key_id" => $key_id]]];
2993 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
2995 return XML::fromArray($xmldata, $xml, false, $namespaces);
2999 * @brief Create the envelope for a message
3001 * @param string $msg The message that is to be transmitted
3002 * @param array $user The record of the sender
3003 * @param array $contact Target of the communication
3004 * @param string $prvkey The private key of the sender
3005 * @param string $pubkey The public key of the receiver
3006 * @param bool $public Is the message public?
3008 * @return string The message that will be transmitted to other servers
3010 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3012 // The message is put into an envelope with the sender's signature
3013 $envelope = self::buildMagicEnvelope($msg, $user);
3015 // Private messages are put into a second envelope, encrypted with the receivers public key
3017 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3024 * @brief Creates a signature for a message
3026 * @param array $owner the array of the owner of the message
3027 * @param array $message The message that is to be signed
3029 * @return string The signature
3031 private static function signature($owner, $message)
3034 unset($sigmsg["author_signature"]);
3035 unset($sigmsg["parent_author_signature"]);
3037 $signed_text = implode(";", $sigmsg);
3039 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3043 * @brief Transmit a message to a target server
3045 * @param array $owner the array of the item owner
3046 * @param array $contact Target of the communication
3047 * @param string $envelope The message that is to be transmitted
3048 * @param bool $public_batch Is it a public post?
3049 * @param bool $queue_run Is the transmission called from the queue?
3050 * @param string $guid message guid
3052 * @return int Result of the transmission
3054 public static function transmit(array $owner, array $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
3058 $enabled = intval(Config::get("system", "diaspora_enabled"));
3063 $logid = random_string(4);
3065 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3067 // We always try to use the data from the fcontact table.
3068 // This is important for transmitting data to Friendica servers.
3069 if (!empty($contact['addr'])) {
3070 $fcontact = self::personByHandle($contact['addr']);
3071 if (!empty($fcontact)) {
3072 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3077 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3081 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3083 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3086 if (!intval(Config::get("system", "diaspora_test"))) {
3087 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3089 Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3090 $return_code = $a->get_curl_code();
3092 logger("test_mode");
3097 logger("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3099 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3100 if (!$no_queue && !empty($contact['contact-type']) && ($contact['contact-type'] != Contact::ACCOUNT_TYPE_RELAY)) {
3101 logger("queue message");
3102 // queue message for redelivery
3103 Queue::add($contact["id"], Protocol::DIASPORA, $envelope, $public_batch, $guid);
3106 // The message could not be delivered. We mark the contact as "dead"
3107 Contact::markForArchival($contact);
3108 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3109 // We successfully delivered a message, the contact is alive
3110 Contact::unmarkForArchival($contact);
3113 return $return_code ? $return_code : -1;
3118 * @brief Build the post xml
3120 * @param string $type The message type
3121 * @param array $message The message data
3123 * @return string The post XML
3125 public static function buildPostXml($type, $message)
3127 $data = [$type => $message];
3129 return XML::fromArray($data, $xml);
3133 * @brief Builds and transmit messages
3135 * @param array $owner the array of the item owner
3136 * @param array $contact Target of the communication
3137 * @param string $type The message type
3138 * @param array $message The message data
3139 * @param bool $public_batch Is it a public post?
3140 * @param string $guid message guid
3141 * @param bool $spool Should the transmission be spooled or transmitted?
3143 * @return int Result of the transmission
3145 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3147 $msg = self::buildPostXml($type, $message);
3149 logger('message: '.$msg, LOGGER_DATA);
3150 logger('send guid '.$guid, LOGGER_DEBUG);
3152 // Fallback if the private key wasn't transmitted in the expected field
3153 if (empty($owner['uprvkey'])) {
3154 $owner['uprvkey'] = $owner['prvkey'];
3157 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3160 Queue::add($contact['id'], Protocol::DIASPORA, $envelope, $public_batch, $guid);
3163 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3166 logger("guid: ".$guid." result ".$return_code, LOGGER_DEBUG);
3168 return $return_code;
3172 * @brief sends a participation (Used to get all further updates)
3174 * @param array $contact Target of the communication
3175 * @param array $item Item array
3177 * @return int The result of the transmission
3179 private static function sendParticipation(array $contact, array $item)
3181 // Don't send notifications for private postings
3182 if ($item['private']) {
3186 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3188 $result = Cache::get($cachekey);
3189 if (!is_null($result)) {
3193 // Fetch some user id to have a valid handle to transmit the participation.
3194 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3195 // If the item belongs to a user, we take this user id.
3196 if ($item['uid'] == 0) {
3197 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3198 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3199 $owner = User::getOwnerDataById($first_user['uid']);
3201 $owner = User::getOwnerDataById($item['uid']);
3204 $author = self::myHandle($owner);
3206 $message = ["author" => $author,
3207 "guid" => System::createGUID(32),
3208 "parent_type" => "Post",
3209 "parent_guid" => $item["guid"]];
3211 logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
3213 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3214 Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
3216 return self::buildAndTransmit($owner, $contact, "participation", $message);
3220 * @brief sends an account migration
3222 * @param array $owner the array of the item owner
3223 * @param array $contact Target of the communication
3224 * @param int $uid User ID
3226 * @return int The result of the transmission
3228 public static function sendAccountMigration(array $owner, array $contact, $uid)
3230 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3231 $profile = self::createProfileData($uid);
3233 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3234 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3236 $message = ["author" => $old_handle,
3237 "profile" => $profile,
3238 "signature" => $signature];
3240 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3242 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3246 * @brief Sends a "share" message
3248 * @param array $owner the array of the item owner
3249 * @param array $contact Target of the communication
3251 * @return int The result of the transmission
3253 public static function sendShare(array $owner, array $contact)
3256 * @todo support the different possible combinations of "following" and "sharing"
3257 * Currently, Diaspora only interprets the "sharing" field
3259 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3263 switch ($contact["rel"]) {
3264 case Contact::FRIEND:
3268 case Contact::SHARING:
3272 case Contact::FOLLOWER:
3278 $message = ["author" => self::myHandle($owner),
3279 "recipient" => $contact["addr"],
3280 "following" => "true",
3281 "sharing" => "true"];
3283 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3285 return self::buildAndTransmit($owner, $contact, "contact", $message);
3289 * @brief sends an "unshare"
3291 * @param array $owner the array of the item owner
3292 * @param array $contact Target of the communication
3294 * @return int The result of the transmission
3296 public static function sendUnshare(array $owner, array $contact)
3298 $message = ["author" => self::myHandle($owner),
3299 "recipient" => $contact["addr"],
3300 "following" => "false",
3301 "sharing" => "false"];
3303 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3305 return self::buildAndTransmit($owner, $contact, "contact", $message);
3309 * @brief Checks a message body if it is a reshare
3311 * @param string $body The message body that is to be check
3312 * @param bool $complete Should it be a complete check or a simple check?
3314 * @return array|bool Reshare details or "false" if no reshare
3316 public static function isReshare($body, $complete = true)
3318 $body = trim($body);
3320 // Skip if it isn't a pure repeated messages
3321 // Does it start with a share?
3322 if ((strpos($body, "[share") > 0) && $complete) {
3326 // Does it end with a share?
3327 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3331 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3332 // Skip if there is no shared message in there
3333 if ($body == $attributes) {
3337 // If we don't do the complete check we quit here
3340 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3341 if (!empty($matches[1])) {
3342 $guid = $matches[1];
3345 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3346 if (!empty($matches[1])) {
3347 $guid = $matches[1];
3350 if (($guid != "") && $complete) {
3351 $condition = ['guid' => $guid, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3352 $item = Item::selectFirst(['contact-id'], $condition);
3353 if (DBA::isResult($item)) {
3355 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3356 $ret["root_guid"] = $guid;
3358 } elseif ($complete) {
3359 // We are resharing something that isn't a DFRN or Diaspora post.
3360 // So we have to return "false" on "$complete" to not trigger a reshare.
3363 } elseif (($guid == "") && $complete) {
3367 $ret["root_guid"] = $guid;
3370 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3371 if (!empty($matches[1])) {
3372 $profile = $matches[1];
3375 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3376 if (!empty($matches[1])) {
3377 $profile = $matches[1];
3382 if ($profile != "") {
3383 if (Contact::getIdForURL($profile)) {
3384 $author = Contact::getDetailsByURL($profile);
3385 $ret["root_handle"] = $author['addr'];
3389 if (empty($ret) && !$complete) {
3397 * @brief Create an event array
3399 * @param integer $event_id The id of the event
3401 * @return array with event data
3403 private static function buildEvent($event_id)
3405 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3406 if (!DBA::isResult($r)) {
3414 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3415 if (!DBA::isResult($r)) {
3421 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3422 if (!DBA::isResult($r)) {
3428 $eventdata['author'] = self::myHandle($owner);
3430 if ($event['guid']) {
3431 $eventdata['guid'] = $event['guid'];
3434 $mask = DateTimeFormat::ATOM;
3436 /// @todo - establish "all day" events in Friendica
3437 $eventdata["all_day"] = "false";
3439 if (!$event['adjust']) {
3440 $eventdata['timezone'] = $user['timezone'];
3442 if ($eventdata['timezone'] == "") {
3443 $eventdata['timezone'] = 'UTC';
3447 if ($event['start']) {
3448 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3450 if ($event['finish'] && !$event['nofinish']) {
3451 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3453 if ($event['summary']) {
3454 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3456 if ($event['desc']) {
3457 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3459 if ($event['location']) {
3460 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3461 $coord = Map::getCoordinates($event['location']);
3464 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3465 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3466 $location["lat"] = $coord['lat'];
3467 $location["lng"] = $coord['lon'];
3469 $location["lat"] = 0;
3470 $location["lng"] = 0;
3472 $eventdata['location'] = $location;
3479 * @brief Create a post (status message or reshare)
3481 * @param array $item The item that will be exported
3482 * @param array $owner the array of the item owner
3485 * 'type' -> Message type ("status_message" or "reshare")
3486 * 'message' -> Array of XML elements of the status
3488 public static function buildStatus(array $item, array $owner)
3490 $cachekey = "diaspora:buildStatus:".$item['guid'];
3492 $result = Cache::get($cachekey);
3493 if (!is_null($result)) {
3497 $myaddr = self::myHandle($owner);
3499 $public = ($item["private"] ? "false" : "true");
3501 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3503 // Detect a share element and do a reshare
3504 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3505 $message = ["author" => $myaddr,
3506 "guid" => $item["guid"],
3507 "created_at" => $created,
3508 "root_author" => $ret["root_handle"],
3509 "root_guid" => $ret["root_guid"],
3510 "provider_display_name" => $item["app"],
3511 "public" => $public];
3515 $title = $item["title"];
3516 $body = $item["body"];
3518 if ($item['author-link'] != $item['owner-link']) {
3519 require_once 'mod/share.php';
3520 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3521 "", $item['created'], $item['plink']) . $body . '[/share]';
3524 // convert to markdown
3525 $body = html_entity_decode(BBCode::toMarkdown($body));
3528 if (strlen($title)) {
3529 $body = "## ".html_entity_decode($title)."\n\n".$body;
3532 if ($item["attach"]) {
3533 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3535 $body .= "\n".L10n::t("Attachments:")."\n";
3536 foreach ($matches as $mtch) {
3537 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3544 if ($item["location"] != "")
3545 $location["address"] = $item["location"];
3547 if ($item["coord"] != "") {
3548 $coord = explode(" ", $item["coord"]);
3549 $location["lat"] = $coord[0];
3550 $location["lng"] = $coord[1];
3553 $message = ["author" => $myaddr,
3554 "guid" => $item["guid"],
3555 "created_at" => $created,
3556 "public" => $public,
3558 "provider_display_name" => $item["app"],
3559 "location" => $location];
3561 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3562 if (!isset($location["lat"]) || !isset($location["lng"])) {
3563 unset($message["location"]);
3566 if ($item['event-id'] > 0) {
3567 $event = self::buildEvent($item['event-id']);
3568 if (count($event)) {
3569 $message['event'] = $event;
3571 if (!empty($event['location']['address']) &&
3572 !empty($event['location']['lat']) &&
3573 !empty($event['location']['lng'])) {
3574 $message['location'] = $event['location'];
3577 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3578 // $message['text'] = '';
3582 $type = "status_message";
3585 $msg = ["type" => $type, "message" => $message];
3587 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3593 * @brief Sends a post
3595 * @param array $item The item that will be exported
3596 * @param array $owner the array of the item owner
3597 * @param array $contact Target of the communication
3598 * @param bool $public_batch Is it a public post?
3600 * @return int The result of the transmission
3602 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3604 $status = self::buildStatus($item, $owner);
3606 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3610 * @brief Creates a "like" object
3612 * @param array $item The item that will be exported
3613 * @param array $owner the array of the item owner
3615 * @return array The data for a "like"
3617 private static function constructLike(array $item, array $owner)
3619 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3620 if (!DBA::isResult($parent)) {
3624 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3626 if ($item['verb'] === ACTIVITY_LIKE) {
3628 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3629 $positive = "false";
3632 return(["author" => self::myHandle($owner),
3633 "guid" => $item["guid"],
3634 "parent_guid" => $parent["guid"],
3635 "parent_type" => $target_type,
3636 "positive" => $positive,
3637 "author_signature" => ""]);
3641 * @brief Creates an "EventParticipation" object
3643 * @param array $item The item that will be exported
3644 * @param array $owner the array of the item owner
3646 * @return array The data for an "EventParticipation"
3648 private static function constructAttend(array $item, array $owner)
3650 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3651 if (!DBA::isResult($parent)) {
3655 switch ($item['verb']) {
3656 case ACTIVITY_ATTEND:
3657 $attend_answer = 'accepted';
3659 case ACTIVITY_ATTENDNO:
3660 $attend_answer = 'declined';
3662 case ACTIVITY_ATTENDMAYBE:
3663 $attend_answer = 'tentative';
3666 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3670 return(["author" => self::myHandle($owner),
3671 "guid" => $item["guid"],
3672 "parent_guid" => $parent["guid"],
3673 "status" => $attend_answer,
3674 "author_signature" => ""]);
3678 * @brief Creates the object for a comment
3680 * @param array $item The item that will be exported
3681 * @param array $owner the array of the item owner
3683 * @return array The data for a comment
3685 private static function constructComment(array $item, array $owner)
3687 $cachekey = "diaspora:constructComment:".$item['guid'];
3689 $result = Cache::get($cachekey);
3690 if (!is_null($result)) {
3694 $parent = Item::selectFirst(['guid'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3695 if (!DBA::isResult($parent)) {
3699 $text = html_entity_decode(BBCode::toMarkdown($item["body"]));
3700 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3702 $comment = ["author" => self::myHandle($owner),
3703 "guid" => $item["guid"],
3704 "created_at" => $created,
3705 "parent_guid" => $parent["guid"],
3707 "author_signature" => ""];
3709 // Send the thread parent guid only if it is a threaded comment
3710 if ($item['thr-parent'] != $item['parent-uri']) {
3711 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3714 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3720 * @brief Send a like or a comment
3722 * @param array $item The item that will be exported
3723 * @param array $owner the array of the item owner
3724 * @param array $contact Target of the communication
3725 * @param bool $public_batch Is it a public post?
3727 * @return int The result of the transmission
3729 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3731 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3732 $message = self::constructAttend($item, $owner);
3733 $type = "event_participation";
3734 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3735 $message = self::constructLike($item, $owner);
3738 $message = self::constructComment($item, $owner);
3746 $message["author_signature"] = self::signature($owner, $message);
3748 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3752 * @brief Creates a message from a signature record entry
3754 * @param array $item The item that will be exported
3755 * @param array $signature The entry of the "sign" record
3757 * @return string The message
3759 private static function messageFromSignature(array $item, array $signature)
3761 // Split the signed text
3762 $signed_parts = explode(";", $signature['signed_text']);
3764 if ($item["deleted"]) {
3765 $message = ["author" => $signature['signer'],
3766 "target_guid" => $signed_parts[0],
3767 "target_type" => $signed_parts[1]];
3768 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3769 $message = ["author" => $signed_parts[4],
3770 "guid" => $signed_parts[1],
3771 "parent_guid" => $signed_parts[3],
3772 "parent_type" => $signed_parts[2],
3773 "positive" => $signed_parts[0],
3774 "author_signature" => $signature['signature'],
3775 "parent_author_signature" => ""];
3777 // Remove the comment guid
3778 $guid = array_shift($signed_parts);
3780 // Remove the parent guid
3781 $parent_guid = array_shift($signed_parts);
3783 // Remove the handle
3784 $handle = array_pop($signed_parts);
3786 // Glue the parts together
3787 $text = implode(";", $signed_parts);
3789 $message = ["author" => $handle,
3791 "parent_guid" => $parent_guid,
3792 "text" => implode(";", $signed_parts),
3793 "author_signature" => $signature['signature'],
3794 "parent_author_signature" => ""];
3800 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3802 * @param array $item The item that will be exported
3803 * @param array $owner the array of the item owner
3804 * @param array $contact Target of the communication
3805 * @param bool $public_batch Is it a public post?
3807 * @return int The result of the transmission
3809 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3811 if ($item["deleted"]) {
3812 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3813 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3819 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3821 // fetch the original signature
3822 $fields = ['signed_text', 'signature', 'signer'];
3823 $signature = DBA::selectFirst('sign', $fields, ['iid' => $item["id"]]);
3824 if (!DBA::isResult($signature)) {
3825 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3829 // Old way - is used by the internal Friendica functions
3830 /// @todo Change all signatur storing functions to the new format
3831 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
3832 $message = self::messageFromSignature($item, $signature);
3834 $msg = json_decode($signature['signed_text'], true);
3837 if (is_array($msg)) {
3838 foreach ($msg as $field => $data) {
3839 if (!$item["deleted"]) {
3840 if ($field == "diaspora_handle") {
3843 if ($field == "target_type") {
3844 $field = "parent_type";
3848 $message[$field] = $data;
3851 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3855 $message["parent_author_signature"] = self::signature($owner, $message);
3857 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3859 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3863 * @brief Sends a retraction (deletion) of a message, like or comment
3865 * @param array $item The item that will be exported
3866 * @param array $owner the array of the item owner
3867 * @param array $contact Target of the communication
3868 * @param bool $public_batch Is it a public post?
3869 * @param bool $relay Is the retraction transmitted from a relay?
3871 * @return int The result of the transmission
3873 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
3875 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3877 $msg_type = "retraction";
3879 if ($item['id'] == $item['parent']) {
3880 $target_type = "Post";
3881 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3882 $target_type = "Like";
3884 $target_type = "Comment";
3887 $message = ["author" => $itemaddr,
3888 "target_guid" => $item['guid'],
3889 "target_type" => $target_type];
3891 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3893 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3897 * @brief Sends a mail
3899 * @param array $item The item that will be exported
3900 * @param array $owner The owner
3901 * @param array $contact Target of the communication
3903 * @return int The result of the transmission
3905 public static function sendMail(array $item, array $owner, array $contact)
3907 $myaddr = self::myHandle($owner);
3909 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
3910 if (!DBA::isResult($cnv)) {
3911 logger("conversation not found.");
3916 "author" => $cnv["creator"],
3917 "guid" => $cnv["guid"],
3918 "subject" => $cnv["subject"],
3919 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3920 "participants" => $cnv["recips"]
3923 $body = BBCode::toMarkdown($item["body"]);
3924 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3927 "author" => $myaddr,
3928 "guid" => $item["guid"],
3929 "conversation_guid" => $cnv["guid"],
3931 "created_at" => $created,
3934 if ($item["reply"]) {
3939 "author" => $cnv["creator"],
3940 "guid" => $cnv["guid"],
3941 "subject" => $cnv["subject"],
3942 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3943 "participants" => $cnv["recips"],
3946 $type = "conversation";
3949 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
3953 * @brief Split a name into first name and last name
3955 * @param string $name The name
3957 * @return array The array with "first" and "last"
3959 public static function splitName($name) {
3960 $name = trim($name);
3962 // Is the name longer than 64 characters? Then cut the rest of it.
3963 if (strlen($name) > 64) {
3964 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3965 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3967 $name = substr($name, 0, 64);
3971 // Take the first word as first name
3972 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3973 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3974 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3975 return ['first' => $first, 'last' => $last];
3978 // Take the last word as last name
3979 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3980 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3982 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3983 return ['first' => $first, 'last' => $last];
3986 // Take the first 32 characters if there is no space in the first 32 characters
3987 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3988 $first = substr($name, 0, 32);
3989 $last = substr($name, 32);
3990 return ['first' => $first, 'last' => $last];
3993 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3994 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3996 // Check if the last name is longer than 32 characters
3997 if (strlen($last) > 32) {
3998 if (strpos($last, ' ') <= 32) {
3999 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4001 $last = substr($last, 0, 32);
4005 return ['first' => $first, 'last' => $last];
4009 * @brief Create profile data
4011 * @param int $uid The user id
4013 * @return array The profile data
4015 private static function createProfileData($uid)
4018 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4020 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4021 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4022 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4031 $handle = $profile["addr"];
4033 $split_name = self::splitName($profile['name']);
4034 $first = $split_name['first'];
4035 $last = $split_name['last'];
4037 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4038 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4039 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4040 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4046 if ($searchable === 'true') {
4049 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4050 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4054 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4057 $about = $profile['about'];
4058 $about = strip_tags(BBCode::convert($about));
4060 $location = Profile::formatLocation($profile);
4062 if ($profile['pub_keywords']) {
4063 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4064 $kw = str_replace(' ', ' ', $kw);
4065 $arr = explode(' ', $profile['pub_keywords']);
4067 for ($x = 0; $x < 5; $x ++) {
4068 if (!empty($arr[$x])) {
4069 $tags .= '#'. trim($arr[$x]) .' ';
4074 $tags = trim($tags);
4077 return ["author" => $handle,
4078 "first_name" => $first,
4079 "last_name" => $last,
4080 "image_url" => $large,
4081 "image_url_medium" => $medium,
4082 "image_url_small" => $small,
4084 "gender" => $profile['gender'],
4086 "location" => $location,
4087 "searchable" => $searchable,
4089 "tag_string" => $tags];
4093 * @brief Sends profile data
4095 * @param int $uid The user id
4096 * @param bool $recips optional, default false
4099 public static function sendProfile($uid, $recips = false)
4105 $owner = User::getOwnerDataById($uid);
4112 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4113 AND `uid` = %d AND `rel` != %d",
4114 DBA::escape(Protocol::DIASPORA),
4116 intval(Contact::SHARING)
4124 $message = self::createProfileData($uid);
4126 foreach ($recips as $recip) {
4127 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4128 self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4133 * @brief Stores the signature for likes that are created on our system
4135 * @param array $contact The contact array of the "like"
4136 * @param int $post_id The post id of the "like"
4138 * @return bool Success
4140 public static function storeLikeSignature(array $contact, $post_id)
4142 // Is the contact the owner? Then fetch the private key
4143 if (!$contact['self'] || ($contact['uid'] == 0)) {
4144 logger("No owner post, so not storing signature", LOGGER_DEBUG);
4148 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $contact["uid"]]);
4149 if (!DBA::isResult($user)) {
4153 $contact["uprvkey"] = $user['prvkey'];
4155 $item = Item::selectFirst([], ['id' => $post_id]);
4156 if (!DBA::isResult($item)) {
4160 if (!in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4164 $message = self::constructLike($item, $contact);
4165 if ($message === false) {
4169 $message["author_signature"] = self::signature($contact, $message);
4172 * Now store the signature more flexible to dynamically support new fields.
4173 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4175 DBA::insert('sign', ['iid' => $post_id, 'signed_text' => json_encode($message)]);
4177 logger('Stored diaspora like signature');
4182 * @brief Stores the signature for comments that are created on our system
4184 * @param array $item The item array of the comment
4185 * @param array $contact The contact array of the item owner
4186 * @param string $uprvkey The private key of the sender
4187 * @param int $message_id The message id of the comment
4189 * @return bool Success
4191 public static function storeCommentSignature(array $item, array $contact, $uprvkey, $message_id)
4193 if ($uprvkey == "") {
4194 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4198 $contact["uprvkey"] = $uprvkey;
4200 $message = self::constructComment($item, $contact);
4201 if ($message === false) {
4205 $message["author_signature"] = self::signature($contact, $message);
4208 * Now store the signature more flexible to dynamically support new fields.
4209 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4211 DBA::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($message)]);
4213 logger('Stored diaspora comment signature');