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\Logger;
19 use Friendica\Core\PConfig;
20 use Friendica\Core\Protocol;
21 use Friendica\Core\System;
22 use Friendica\Core\Worker;
23 use Friendica\Database\DBA;
24 use Friendica\Model\Contact;
25 use Friendica\Model\Conversation;
26 use Friendica\Model\GContact;
27 use Friendica\Model\Group;
28 use Friendica\Model\Item;
29 use Friendica\Model\Profile;
30 use Friendica\Model\Queue;
31 use Friendica\Model\User;
32 use Friendica\Network\Probe;
33 use Friendica\Util\Crypto;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\Map;
36 use Friendica\Util\Network;
37 use Friendica\Util\XML;
40 require_once 'include/dba.php';
41 require_once 'include/items.php';
44 * @brief This class contain functions to create and send Diaspora XML files
50 * @brief Return a list of relay servers
52 * The list contains not only the official relays but also servers that we serve directly
54 * @param integer $item_id The id of the item that is sent
55 * @param array $contacts The previously fetched contacts
57 * @return array of relay servers
59 public static function relayList($item_id, array $contacts = [])
63 // Fetching relay servers
64 $serverdata = Config::get("system", "relay_server");
66 if (!empty($serverdata)) {
67 $servers = explode(",", $serverdata);
68 foreach ($servers as $server) {
69 $serverlist[$server] = trim($server);
73 if (Config::get("system", "relay_directly", false)) {
74 // We distribute our stuff based on the parent to ensure that the thread will be complete
75 $parent = Item::selectFirst(['parent'], ['id' => $item_id]);
76 if (!DBA::isResult($parent)) {
80 // Servers that want to get all content
81 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
82 while ($server = DBA::fetch($servers)) {
83 $serverlist[$server['url']] = $server['url'];
86 // All tags of the current post
87 $condition = ['otype' => TERM_OBJ_POST, 'type' => TERM_HASHTAG, 'oid' => $parent['parent']];
88 $tags = DBA::select('term', ['term'], $condition);
90 while ($tag = DBA::fetch($tags)) {
91 $taglist[] = $tag['term'];
94 // All servers who wants content with this tag
96 if (!empty($taglist)) {
97 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
98 while ($server = DBA::fetch($tagserver)) {
99 $tagserverlist[] = $server['gserver-id'];
103 // All adresses with the given id
104 if (!empty($tagserverlist)) {
105 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
106 while ($server = DBA::fetch($servers)) {
107 $serverlist[$server['url']] = $server['url'];
112 // Now we are collecting all relay contacts
113 foreach ($serverlist as $server_url) {
114 // We don't send messages to ourselves
115 if (link_compare($server_url, System::baseUrl())) {
118 $contact = self::getRelayContact($server_url);
119 if (is_bool($contact)) {
124 foreach ($contacts as $entry) {
125 if ($entry['batch'] == $contact['batch']) {
131 $contacts[] = $contact;
139 * @brief Return a contact for a given server address or creates a dummy entry
141 * @param string $server_url The url of the server
142 * @return array with the contact
144 private static function getRelayContact($server_url)
146 $fields = ['batch', 'id', 'name', 'network', 'archive', 'blocked'];
148 // Fetch the relay contact
149 $condition = ['uid' => 0, 'nurl' => normalise_link($server_url),
150 'contact-type' => Contact::ACCOUNT_TYPE_RELAY];
151 $contact = DBA::selectFirst('contact', $fields, $condition);
153 if (DBA::isResult($contact)) {
154 if ($contact['archive'] || $contact['blocked']) {
159 self::setRelayContact($server_url);
161 $contact = DBA::selectFirst('contact', $fields, $condition);
162 if (DBA::isResult($contact)) {
167 // It should never happen that we arrive here
172 * @brief Update or insert a relay contact
174 * @param string $server_url The url of the server
175 * @param array $network_fields Optional network specific fields
177 public static function setRelayContact($server_url, array $network_fields = [])
179 $fields = ['created' => DateTimeFormat::utcNow(),
180 'name' => 'relay', 'nick' => 'relay',
181 'url' => $server_url, 'network' => Protocol::DIASPORA,
182 'batch' => $server_url . '/receive/public',
183 'rel' => Contact::FOLLOWER, 'blocked' => false,
184 'pending' => false, 'writable' => true];
186 $fields = array_merge($fields, $network_fields);
188 $condition = ['uid' => 0, 'nurl' => normalise_link($server_url),
189 'contact-type' => Contact::ACCOUNT_TYPE_RELAY];
191 if (DBA::exists('contact', $condition)) {
192 unset($fields['created']);
195 DBA::update('contact', $fields, $condition, true);
199 * @brief Return a list of participating contacts for a thread
201 * This is used for the participation feature.
202 * One of the parameters is a contact array.
203 * This is done to avoid duplicates.
205 * @param integer $thread The id of the thread
206 * @param array $contacts The previously fetched contacts
208 * @return array of relay servers
210 public static function participantsForThread($thread, array $contacts)
212 $r = DBA::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`,
213 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
214 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
215 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
216 WHERE `participation`.`iid` = ?", $thread);
218 while ($contact = DBA::fetch($r)) {
219 if (!empty($contact['fnetwork'])) {
220 $contact['network'] = $contact['fnetwork'];
222 unset($contact['fnetwork']);
224 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
225 $contact['batch'] = $contact['fbatch'];
227 unset($contact['fbatch']);
230 foreach ($contacts as $entry) {
231 if ($entry['batch'] == $contact['batch']) {
237 $contacts[] = $contact;
246 * @brief repairs a signature that was double encoded
248 * The function is unused at the moment. It was copied from the old implementation.
250 * @param string $signature The signature
251 * @param string $handle The handle of the signature owner
252 * @param integer $level This value is only set inside this function to avoid endless loops
254 * @return string the repaired signature
256 private static function repairSignature($signature, $handle = "", $level = 1)
258 if ($signature == "") {
262 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
263 $signature = base64_decode($signature);
264 Logger::log("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, Logger::DEBUG);
266 // Do a recursive call to be able to fix even multiple levels
268 $signature = self::repairSignature($signature, $handle, ++$level);
276 * @brief verify the envelope and return the verified data
278 * @param string $envelope The magic envelope
280 * @return string verified data
282 private static function verifyMagicEnvelope($envelope)
284 $basedom = XML::parseString($envelope);
286 if (!is_object($basedom)) {
287 Logger::log("Envelope is no XML file");
291 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
293 if (sizeof($children) == 0) {
294 Logger::log("XML has no children");
300 $data = base64url_decode($children->data);
301 $type = $children->data->attributes()->type[0];
303 $encoding = $children->encoding;
305 $alg = $children->alg;
307 $sig = base64url_decode($children->sig);
308 $key_id = $children->sig->attributes()->key_id[0];
310 $handle = base64url_decode($key_id);
313 $b64url_data = base64url_encode($data);
314 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
316 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
319 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
323 $key = self::key($handle);
325 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
329 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
331 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
339 * @brief encrypts data via AES
341 * @param string $key The AES key
342 * @param string $iv The IV (is used for CBC encoding)
343 * @param string $data The data that is to be encrypted
345 * @return string encrypted data
347 private static function aesEncrypt($key, $iv, $data)
349 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
353 * @brief decrypts data via AES
355 * @param string $key The AES key
356 * @param string $iv The IV (is used for CBC encoding)
357 * @param string $encrypted The encrypted data
359 * @return string decrypted data
361 private static function aesDecrypt($key, $iv, $encrypted)
363 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
367 * @brief: Decodes incoming Diaspora message in the new format
369 * @param array $importer Array of the importer user
370 * @param string $raw raw post message
371 * @param boolean $no_exit Don't do an http exit on error
374 * 'message' -> decoded Diaspora XML message
375 * 'author' -> author diaspora handle
376 * 'key' -> author public key (converted to pkcs#8)
378 public static function decodeRaw(array $importer, $raw, $no_exit = false)
380 $data = json_decode($raw);
382 // Is it a private post? Then decrypt the outer Salmon
383 if (is_object($data)) {
384 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
385 $ciphertext = base64_decode($data->encrypted_magic_envelope);
387 $outer_key_bundle = '';
388 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
389 $j_outer_key_bundle = json_decode($outer_key_bundle);
391 if (!is_object($j_outer_key_bundle)) {
392 Logger::log('Outer Salmon did not verify. Discarding.');
396 System::httpExit(400);
400 $outer_iv = base64_decode($j_outer_key_bundle->iv);
401 $outer_key = base64_decode($j_outer_key_bundle->key);
403 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
408 $basedom = XML::parseString($xml);
410 if (!is_object($basedom)) {
411 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
415 System::httpExit(400);
419 $base = $basedom->children(NAMESPACE_SALMON_ME);
421 // Not sure if this cleaning is needed
422 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
424 // Build the signed data
425 $type = $base->data[0]->attributes()->type[0];
426 $encoding = $base->encoding;
428 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
430 // This is the signature
431 $signature = base64url_decode($base->sig);
433 // Get the senders' public key
434 $key_id = $base->sig[0]->attributes()->key_id[0];
435 $author_addr = base64_decode($key_id);
436 if ($author_addr == '') {
437 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
441 System::httpExit(400);
445 $key = self::key($author_addr);
447 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
451 System::httpExit(400);
455 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
457 Logger::log('Message did not verify. Discarding.');
461 System::httpExit(400);
465 return ['message' => (string)base64url_decode($base->data),
466 'author' => XML::unescape($author_addr),
467 'key' => (string)$key];
471 * @brief: Decodes incoming Diaspora message in the deprecated format
473 * @param array $importer Array of the importer user
474 * @param string $xml urldecoded Diaspora salmon
477 * 'message' -> decoded Diaspora XML message
478 * 'author' -> author diaspora handle
479 * 'key' -> author public key (converted to pkcs#8)
481 public static function decode(array $importer, $xml)
484 $basedom = XML::parseString($xml);
486 if (!is_object($basedom)) {
487 Logger::log("XML is not parseable.");
490 $children = $basedom->children('https://joindiaspora.com/protocol');
492 $inner_aes_key = null;
495 if ($children->header) {
497 $author_link = str_replace('acct:', '', $children->header->author_id);
499 // This happens with posts from a relais
501 Logger::log("This is no private post in the old format", Logger::DEBUG);
505 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
507 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
508 $ciphertext = base64_decode($encrypted_header->ciphertext);
510 $outer_key_bundle = '';
511 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
513 $j_outer_key_bundle = json_decode($outer_key_bundle);
515 $outer_iv = base64_decode($j_outer_key_bundle->iv);
516 $outer_key = base64_decode($j_outer_key_bundle->key);
518 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
520 Logger::log('decrypted: '.$decrypted, Logger::DEBUG);
521 $idom = XML::parseString($decrypted);
523 $inner_iv = base64_decode($idom->iv);
524 $inner_aes_key = base64_decode($idom->aes_key);
526 $author_link = str_replace('acct:', '', $idom->author_id);
529 $dom = $basedom->children(NAMESPACE_SALMON_ME);
531 // figure out where in the DOM tree our data is hiding
534 if ($dom->provenance->data) {
535 $base = $dom->provenance;
536 } elseif ($dom->env->data) {
538 } elseif ($dom->data) {
543 Logger::log('unable to locate salmon data in xml');
544 System::httpExit(400);
548 // Stash the signature away for now. We have to find their key or it won't be good for anything.
549 $signature = base64url_decode($base->sig);
553 // strip whitespace so our data element will return to one big base64 blob
554 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
557 // stash away some other stuff for later
559 $type = $base->data[0]->attributes()->type[0];
560 $keyhash = $base->sig[0]->attributes()->keyhash[0];
561 $encoding = $base->encoding;
565 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
569 $data = base64url_decode($data);
573 $inner_decrypted = $data;
575 // Decode the encrypted blob
576 $inner_encrypted = base64_decode($data);
577 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
581 Logger::log('Could not retrieve author URI.');
582 System::httpExit(400);
584 // Once we have the author URI, go to the web and try to find their public key
585 // (first this will look it up locally if it is in the fcontact cache)
586 // This will also convert diaspora public key from pkcs#1 to pkcs#8
588 Logger::log('Fetching key for '.$author_link);
589 $key = self::key($author_link);
592 Logger::log('Could not retrieve author key.');
593 System::httpExit(400);
596 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
599 Logger::log('Message did not verify. Discarding.');
600 System::httpExit(400);
603 Logger::log('Message verified.');
605 return ['message' => (string)$inner_decrypted,
606 'author' => XML::unescape($author_link),
607 'key' => (string)$key];
612 * @brief Dispatches public messages and find the fitting receivers
614 * @param array $msg The post that will be dispatched
616 * @return int The message id of the generated message, "true" or "false" if there was an error
618 public static function dispatchPublic($msg)
620 $enabled = intval(Config::get("system", "diaspora_enabled"));
622 Logger::log("diaspora is disabled");
626 if (!($fields = self::validPosting($msg))) {
627 Logger::log("Invalid posting");
631 $importer = ["uid" => 0, "page-flags" => Contact::PAGE_FREELOVE];
632 $success = self::dispatch($importer, $msg, $fields);
638 * @brief Dispatches the different message types to the different functions
640 * @param array $importer Array of the importer user
641 * @param array $msg The post that will be dispatched
642 * @param object $fields SimpleXML object that contains the message
644 * @return int The message id of the generated message, "true" or "false" if there was an error
646 public static function dispatch(array $importer, $msg, $fields = null)
648 // The sender is the handle of the contact that sent the message.
649 // This will often be different with relayed messages (for example "like" and "comment")
650 $sender = $msg["author"];
652 // This is only needed for private postings since this is already done for public ones before
653 if (is_null($fields)) {
655 if (!($fields = self::validPosting($msg))) {
656 Logger::log("Invalid posting");
663 $type = $fields->getName();
665 Logger::log("Received message type ".$type." from ".$sender." for user ".$importer["uid"], Logger::DEBUG);
668 case "account_migration":
670 Logger::log('Message with type ' . $type . ' is not private, quitting.');
673 return self::receiveAccountMigration($importer, $fields);
675 case "account_deletion":
676 return self::receiveAccountDeletion($fields);
679 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
683 Logger::log('Message with type ' . $type . ' is not private, quitting.');
686 return self::receiveContactRequest($importer, $fields);
690 Logger::log('Message with type ' . $type . ' is not private, quitting.');
693 return self::receiveConversation($importer, $msg, $fields);
696 return self::receiveLike($importer, $sender, $fields);
700 Logger::log('Message with type ' . $type . ' is not private, quitting.');
703 return self::receiveMessage($importer, $fields);
705 case "participation":
707 Logger::log('Message with type ' . $type . ' is not private, quitting.');
710 return self::receiveParticipation($importer, $fields);
712 case "photo": // Not implemented
713 return self::receivePhoto($importer, $fields);
715 case "poll_participation": // Not implemented
716 return self::receivePollParticipation($importer, $fields);
720 Logger::log('Message with type ' . $type . ' is not private, quitting.');
723 return self::receiveProfile($importer, $fields);
726 return self::receiveReshare($importer, $fields, $msg["message"]);
729 return self::receiveRetraction($importer, $sender, $fields);
731 case "status_message":
732 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
735 Logger::log("Unknown message type ".$type);
743 * @brief Checks if a posting is valid and fetches the data fields.
745 * This function does not only check the signature.
746 * It also does the conversion between the old and the new diaspora format.
748 * @param array $msg Array with the XML, the sender handle and the sender signature
750 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
752 private static function validPosting($msg)
754 $data = XML::parseString($msg["message"]);
756 if (!is_object($data)) {
757 Logger::log("No valid XML ".$msg["message"], Logger::DEBUG);
761 // Is this the new or the old version?
762 if ($data->getName() == "XML") {
764 foreach ($data->post->children() as $child) {
772 $type = $element->getName();
775 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
777 // All retractions are handled identically from now on.
778 // In the new version there will only be "retraction".
779 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
780 $type = "retraction";
782 if ($type == "request") {
786 $fields = new SimpleXMLElement("<".$type."/>");
789 $author_signature = null;
790 $parent_author_signature = null;
792 foreach ($element->children() as $fieldname => $entry) {
794 // Translation for the old XML structure
795 if ($fieldname == "diaspora_handle") {
796 $fieldname = "author";
798 if ($fieldname == "participant_handles") {
799 $fieldname = "participants";
801 if (in_array($type, ["like", "participation"])) {
802 if ($fieldname == "target_type") {
803 $fieldname = "parent_type";
806 if ($fieldname == "sender_handle") {
807 $fieldname = "author";
809 if ($fieldname == "recipient_handle") {
810 $fieldname = "recipient";
812 if ($fieldname == "root_diaspora_id") {
813 $fieldname = "root_author";
815 if ($type == "status_message") {
816 if ($fieldname == "raw_message") {
820 if ($type == "retraction") {
821 if ($fieldname == "post_guid") {
822 $fieldname = "target_guid";
824 if ($fieldname == "type") {
825 $fieldname = "target_type";
830 if (($fieldname == "author_signature") && ($entry != "")) {
831 $author_signature = base64_decode($entry);
832 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
833 $parent_author_signature = base64_decode($entry);
834 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
835 if ($signed_data != "") {
839 $signed_data .= $entry;
841 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
842 || ($orig_type == "relayable_retraction")
844 XML::copy($entry, $fields, $fieldname);
848 // This is something that shouldn't happen at all.
849 if (in_array($type, ["status_message", "reshare", "profile"])) {
850 if ($msg["author"] != $fields->author) {
851 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
856 // Only some message types have signatures. So we quit here for the other types.
857 if (!in_array($type, ["comment", "like"])) {
860 // No author_signature? This is a must, so we quit.
861 if (!isset($author_signature)) {
862 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
866 if (isset($parent_author_signature)) {
867 $key = self::key($msg["author"]);
869 Logger::log("No key found for parent author ".$msg["author"], Logger::DEBUG);
873 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
874 Logger::log("No valid parent author signature for parent author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$parent_author_signature, Logger::DEBUG);
879 $key = self::key($fields->author);
881 Logger::log("No key found for author ".$fields->author, Logger::DEBUG);
885 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
886 Logger::log("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, Logger::DEBUG);
894 * @brief Fetches the public key for a given handle
896 * @param string $handle The handle
898 * @return string The public key
900 private static function key($handle)
902 $handle = strval($handle);
904 Logger::log("Fetching diaspora key for: ".$handle);
906 $r = self::personByHandle($handle);
915 * @brief Fetches data for a given handle
917 * @param string $handle The handle
919 * @return array the queried data
921 public static function personByHandle($handle)
925 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
926 if (DBA::isResult($person)) {
927 Logger::log("In cache " . print_r($person, true), Logger::DEBUG);
929 // update record occasionally so it doesn't get stale
930 $d = strtotime($person["updated"]." +00:00");
931 if ($d < strtotime("now - 14 days")) {
935 if ($person["guid"] == "") {
940 if (!DBA::isResult($person) || $update) {
941 Logger::log("create or refresh", Logger::DEBUG);
942 $r = Probe::uri($handle, Protocol::DIASPORA);
944 // Note that Friendica contacts will return a "Diaspora person"
945 // if Diaspora connectivity is enabled on their server
946 if ($r && ($r["network"] === Protocol::DIASPORA)) {
947 self::updateFContact($r);
949 // Fetch the updated or added contact
950 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
951 if (!DBA::isResult($person)) {
962 * @brief Updates the fcontact table
964 * @param array $arr The fcontact data
966 private static function updateFContact($arr)
968 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
969 'request' => $arr["request"], 'nick' => $arr["nick"],
970 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
971 'batch' => $arr["batch"], 'notify' => $arr["notify"],
972 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
973 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
974 'updated' => DateTimeFormat::utcNow()];
976 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
978 DBA::update('fcontact', $fields, $condition, true);
982 * @brief get a handle (user@domain.tld) from a given contact id
984 * @param int $contact_id The id in the contact table
985 * @param int $pcontact_id The id in the contact table (Used for the public contact)
987 * @return string the handle
989 private static function handleFromContact($contact_id, $pcontact_id = 0)
993 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
995 if ($pcontact_id != 0) {
996 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
998 if (DBA::isResult($contact) && !empty($contact["addr"])) {
999 return strtolower($contact["addr"]);
1004 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1008 if (DBA::isResult($r)) {
1011 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1013 if ($contact['addr'] != "") {
1014 $handle = $contact['addr'];
1016 $baseurl_start = strpos($contact['url'], '://') + 3;
1017 // allows installations in a subdirectory--not sure how Diaspora will handle
1018 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1019 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1020 $handle = $contact['nick'].'@'.$baseurl;
1024 return strtolower($handle);
1028 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
1031 * @param mixed $fcontact_guid Hexadecimal string guid
1033 * @return string the contact url or null
1035 public static function urlFromContactGuid($fcontact_guid)
1037 Logger::log("fcontact guid is ".$fcontact_guid, Logger::DEBUG);
1040 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1041 DBA::escape(Protocol::DIASPORA),
1042 DBA::escape($fcontact_guid)
1045 if (DBA::isResult($r)) {
1046 return $r[0]['url'];
1053 * @brief Get a contact id for a given handle
1055 * @todo Move to Friendica\Model\Contact
1057 * @param int $uid The user id
1058 * @param string $handle The handle in the format user@domain.tld
1060 * @return int Contact id
1062 private static function contactByHandle($uid, $handle)
1064 $cid = Contact::getIdForURL($handle, $uid);
1066 $handle_parts = explode("@", $handle);
1067 $nurl_sql = "%%://" . $handle_parts[1] . "%%/profile/" . $handle_parts[0];
1068 $cid = Contact::getIdForURL($nurl_sql, $uid);
1072 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1076 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1077 if (!DBA::isResult($contact)) {
1078 // This here shouldn't happen at all
1079 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1087 * @brief Check if posting is allowed for this contact
1089 * @param array $importer Array of the importer user
1090 * @param array $contact The contact that is checked
1091 * @param bool $is_comment Is the check for a comment?
1093 * @return bool is the contact allowed to post?
1095 private static function postAllow(array $importer, array $contact, $is_comment = false)
1098 * Perhaps we were already sharing with this person. Now they're sharing with us.
1099 * That makes us friends.
1100 * Normally this should have handled by getting a request - but this could get lost
1102 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1103 // It is not removed by now. Possibly the code is needed?
1104 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(Contact::PAGE_FREELOVE))) {
1107 // array('rel' => Contact::FRIEND, 'writable' => true),
1108 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1111 // $contact["rel"] = Contact::FRIEND;
1112 // Logger::log("defining user ".$contact["nick"]." as friend");
1115 // We don't seem to like that person
1116 if ($contact["blocked"]) {
1117 // Maybe blocked, don't accept.
1119 // We are following this person?
1120 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1121 // Yes, then it is fine.
1123 // Is it a post to a community?
1124 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [Contact::PAGE_COMMUNITY, Contact::PAGE_PRVGROUP])) {
1127 // Is the message a global user or a comment?
1128 } elseif (($importer["uid"] == 0) || $is_comment) {
1129 // Messages for the global users and comments are always accepted
1137 * @brief Fetches the contact id for a handle and checks if posting is allowed
1139 * @param array $importer Array of the importer user
1140 * @param string $handle The checked handle in the format user@domain.tld
1141 * @param bool $is_comment Is the check for a comment?
1143 * @return array The contact data
1145 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1147 $contact = self::contactByHandle($importer["uid"], $handle);
1149 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1150 // If a contact isn't found, we accept it anyway if it is a comment
1151 if ($is_comment && ($importer["uid"] != 0)) {
1152 return self::contactByHandle(0, $handle);
1153 } elseif ($is_comment) {
1160 if (!self::postAllow($importer, $contact, $is_comment)) {
1161 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1168 * @brief Does the message already exists on the system?
1170 * @param int $uid The user id
1171 * @param string $guid The guid of the message
1173 * @return int|bool message id if the message already was stored into the system - or false.
1175 private static function messageExists($uid, $guid)
1177 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1178 if (DBA::isResult($item)) {
1179 Logger::log("message ".$guid." already exists for user ".$uid);
1187 * @brief Checks for links to posts in a message
1189 * @param array $item The item array
1192 private static function fetchGuid(array $item)
1194 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1195 preg_replace_callback(
1197 function ($match) use ($item) {
1198 self::fetchGuidSub($match, $item);
1203 preg_replace_callback(
1204 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1205 function ($match) use ($item) {
1206 self::fetchGuidSub($match, $item);
1213 * @brief Checks for relative /people/* links in an item body to match local
1214 * contacts or prepends the remote host taken from the author link.
1216 * @param string $body The item body to replace links from
1217 * @param string $author_link The author link for missing local contact fallback
1219 * @return string the replaced string
1221 public static function replacePeopleGuid($body, $author_link)
1223 $return = preg_replace_callback(
1224 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1225 function ($match) use ($author_link) {
1227 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1228 // 1 => '0123456789abcdef'
1230 $handle = self::urlFromContactGuid($match[1]);
1233 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1235 // No local match, restoring absolute remote URL from author scheme and host
1236 $author_url = parse_url($author_link);
1237 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1249 * @brief sub function of "fetchGuid" which checks for links in messages
1251 * @param array $match array containing a link that has to be checked for a message link
1252 * @param array $item The item array
1255 private static function fetchGuidSub($match, $item)
1257 if (!self::storeByGuid($match[1], $item["author-link"])) {
1258 self::storeByGuid($match[1], $item["owner-link"]);
1263 * @brief Fetches an item with a given guid from a given server
1265 * @param string $guid the message guid
1266 * @param string $server The server address
1267 * @param int $uid The user id of the user
1269 * @return int the message id of the stored message or false
1271 private static function storeByGuid($guid, $server, $uid = 0)
1273 $serverparts = parse_url($server);
1275 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1279 $server = $serverparts["scheme"]."://".$serverparts["host"];
1281 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1283 $msg = self::message($guid, $server);
1289 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1291 // Now call the dispatcher
1292 return self::dispatchPublic($msg);
1296 * @brief Fetches a message from a server
1298 * @param string $guid message guid
1299 * @param string $server The url of the server
1300 * @param int $level Endless loop prevention
1303 * 'message' => The message XML
1304 * 'author' => The author handle
1305 * 'key' => The public key of the author
1307 private static function message($guid, $server, $level = 0)
1313 // This will work for new Diaspora servers and Friendica servers from 3.5
1314 $source_url = $server."/fetch/post/".urlencode($guid);
1316 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1318 $envelope = Network::fetchUrl($source_url);
1320 Logger::log("Envelope was fetched.", Logger::DEBUG);
1321 $x = self::verifyMagicEnvelope($envelope);
1323 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1325 Logger::log("Envelope was verified.", Logger::DEBUG);
1331 // This will work for older Diaspora and Friendica servers
1333 $source_url = $server."/p/".urlencode($guid).".xml";
1334 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1336 $x = Network::fetchUrl($source_url);
1342 $source_xml = XML::parseString($x);
1344 if (!is_object($source_xml)) {
1348 if ($source_xml->post->reshare) {
1349 // Reshare of a reshare - old Diaspora version
1350 Logger::log("Message is a reshare", Logger::DEBUG);
1351 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1352 } elseif ($source_xml->getName() == "reshare") {
1353 // Reshare of a reshare - new Diaspora version
1354 Logger::log("Message is a new reshare", Logger::DEBUG);
1355 return self::message($source_xml->root_guid, $server, ++$level);
1360 // Fetch the author - for the old and the new Diaspora version
1361 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1362 $author = (string)$source_xml->post->status_message->diaspora_handle;
1363 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1364 $author = (string)$source_xml->author;
1367 // If this isn't a "status_message" then quit
1369 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1373 $msg = ["message" => $x, "author" => $author];
1375 $msg["key"] = self::key($msg["author"]);
1381 * @brief Fetches the item record of a given guid
1383 * @param int $uid The user id
1384 * @param string $guid message guid
1385 * @param string $author The handle of the item
1386 * @param array $contact The contact of the item owner
1388 * @return array the item record
1390 private static function parentItem($uid, $guid, $author, array $contact)
1392 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1393 'author-name', 'author-link', 'author-avatar',
1394 'owner-name', 'owner-link', 'owner-avatar'];
1395 $condition = ['uid' => $uid, 'guid' => $guid];
1396 $item = Item::selectFirst($fields, $condition);
1398 if (!DBA::isResult($item)) {
1399 $person = self::personByHandle($author);
1400 $result = self::storeByGuid($guid, $person["url"], $uid);
1402 // We don't have an url for items that arrived at the public dispatcher
1403 if (!$result && !empty($contact["url"])) {
1404 $result = self::storeByGuid($guid, $contact["url"], $uid);
1408 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1410 $item = Item::selectFirst($fields, $condition);
1414 if (!DBA::isResult($item)) {
1415 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1418 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1424 * @brief returns contact details
1426 * @param array $def_contact The default contact if the person isn't found
1427 * @param array $person The record of the person
1428 * @param int $uid The user id
1431 * 'cid' => contact id
1432 * 'network' => network type
1434 private static function authorContactByUrl($def_contact, $person, $uid)
1436 $condition = ['nurl' => normalise_link($person["url"]), 'uid' => $uid];
1437 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1438 if (DBA::isResult($contact)) {
1439 $cid = $contact["id"];
1440 $network = $contact["network"];
1442 $cid = $def_contact["id"];
1443 $network = Protocol::DIASPORA;
1446 return ["cid" => $cid, "network" => $network];
1450 * @brief Is the profile a hubzilla profile?
1452 * @param string $url The profile link
1454 * @return bool is it a hubzilla server?
1456 public static function isRedmatrix($url)
1458 return(strstr($url, "/channel/"));
1462 * @brief Generate a post link with a given handle and message guid
1464 * @param string $addr The user handle
1465 * @param string $guid message guid
1466 * @param string $parent_guid optional parent guid
1468 * @return string the post link
1470 private static function plink($addr, $guid, $parent_guid = '')
1472 $contact = Contact::getDetailsByAddr($addr);
1476 if ($parent_guid != '') {
1477 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1479 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1483 if ($contact["network"] == Protocol::DFRN) {
1484 return str_replace("/profile/" . $contact["nick"] . "/", "/display/" . $guid, $contact["url"] . "/");
1487 if (self::isRedmatrix($contact["url"])) {
1488 return $contact["url"] . "/?f=&mid=" . $guid;
1491 if ($parent_guid != '') {
1492 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1494 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1499 * @brief Receives account migration
1501 * @param array $importer Array of the importer user
1502 * @param object $data The message object
1504 * @return bool Success
1506 private static function receiveAccountMigration(array $importer, $data)
1508 $old_handle = notags(XML::unescape($data->author));
1509 $new_handle = notags(XML::unescape($data->profile->author));
1510 $signature = notags(XML::unescape($data->signature));
1512 $contact = self::contactByHandle($importer["uid"], $old_handle);
1514 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1518 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1521 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1522 $key = self::key($old_handle);
1523 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1524 Logger::log('No valid signature for migration.');
1528 // Update the profile
1529 self::receiveProfile($importer, $data->profile);
1531 // change the technical stuff in contact and gcontact
1532 $data = Probe::uri($new_handle);
1533 if ($data['network'] == Protocol::PHANTOM) {
1534 Logger::log('Account for '.$new_handle." couldn't be probed.");
1538 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1539 'name' => $data['name'], 'nick' => $data['nick'],
1540 'addr' => $data['addr'], 'batch' => $data['batch'],
1541 'notify' => $data['notify'], 'poll' => $data['poll'],
1542 'network' => $data['network']];
1544 DBA::update('contact', $fields, ['addr' => $old_handle]);
1546 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1547 'name' => $data['name'], 'nick' => $data['nick'],
1548 'addr' => $data['addr'], 'connect' => $data['addr'],
1549 'notify' => $data['notify'], 'photo' => $data['photo'],
1550 'server_url' => $data['baseurl'], 'network' => $data['network']];
1552 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1554 Logger::log('Contacts are updated.');
1560 * @brief Processes an account deletion
1562 * @param object $data The message object
1564 * @return bool Success
1566 private static function receiveAccountDeletion($data)
1568 $author = notags(XML::unescape($data->author));
1570 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1571 while ($contact = DBA::fetch($contacts)) {
1572 Contact::remove($contact["id"]);
1575 DBA::delete('gcontact', ['addr' => $author]);
1577 Logger::log('Removed contacts for ' . $author);
1583 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1585 * @param string $author Author handle
1586 * @param string $guid Message guid
1587 * @param boolean $onlyfound Only return uri when found in the database
1589 * @return string The constructed uri or the one from our database
1591 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1593 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1594 if (DBA::isResult($item)) {
1595 return $item["uri"];
1596 } elseif (!$onlyfound) {
1597 $person = self::personByHandle($author);
1599 $parts = parse_url($person['url']);
1600 unset($parts['path']);
1601 $host_url = Network::unparseURL($parts);
1603 return $host_url . '/objects/' . $guid;
1610 * @brief Fetch the guid from our database with a given uri
1612 * @param string $uri Message uri
1613 * @param string $uid Author handle
1615 * @return string The post guid
1617 private static function getGuidFromUri($uri, $uid)
1619 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1620 if (DBA::isResult($item)) {
1621 return $item["guid"];
1628 * @brief Find the best importer for a comment, like, ...
1630 * @param string $guid The guid of the item
1632 * @return array|boolean the origin owner of that post - or false
1634 private static function importerForGuid($guid)
1636 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1637 if (DBA::isResult($item)) {
1638 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1639 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1640 if (DBA::isResult($contact)) {
1648 * @brief Processes an incoming comment
1650 * @param array $importer Array of the importer user
1651 * @param string $sender The sender of the message
1652 * @param object $data The message object
1653 * @param string $xml The original XML of the message
1655 * @return int The message id of the generated comment or "false" if there was an error
1657 private static function receiveComment(array $importer, $sender, $data, $xml)
1659 $author = notags(XML::unescape($data->author));
1660 $guid = notags(XML::unescape($data->guid));
1661 $parent_guid = notags(XML::unescape($data->parent_guid));
1662 $text = XML::unescape($data->text);
1664 if (isset($data->created_at)) {
1665 $created_at = DateTimeFormat::utc(notags(XML::unescape($data->created_at)));
1667 $created_at = DateTimeFormat::utcNow();
1670 if (isset($data->thread_parent_guid)) {
1671 $thread_parent_guid = notags(XML::unescape($data->thread_parent_guid));
1672 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1677 $contact = self::allowedContactByHandle($importer, $sender, true);
1682 $message_id = self::messageExists($importer["uid"], $guid);
1687 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1688 if (!$parent_item) {
1692 $person = self::personByHandle($author);
1693 if (!is_array($person)) {
1694 Logger::log("unable to find author details");
1698 // Fetch the contact id - if we know this contact
1699 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1703 $datarray["uid"] = $importer["uid"];
1704 $datarray["contact-id"] = $author_contact["cid"];
1705 $datarray["network"] = $author_contact["network"];
1707 $datarray["author-link"] = $person["url"];
1708 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1710 $datarray["owner-link"] = $contact["url"];
1711 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1713 $datarray["guid"] = $guid;
1714 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1716 $datarray["verb"] = ACTIVITY_POST;
1717 $datarray["gravity"] = GRAVITY_COMMENT;
1719 if ($thr_uri != "") {
1720 $datarray["parent-uri"] = $thr_uri;
1722 $datarray["parent-uri"] = $parent_item["uri"];
1725 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1727 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1728 $datarray["source"] = $xml;
1730 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1732 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1734 $body = Markdown::toBBCode($text);
1736 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1738 self::fetchGuid($datarray);
1740 // If we are the origin of the parent we store the original data.
1741 // We notify our followers during the item storage.
1742 if ($parent_item["origin"]) {
1743 $datarray['diaspora_signed_text'] = json_encode($data);
1746 $message_id = Item::insert($datarray);
1748 if ($message_id <= 0) {
1753 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1754 if ($datarray['uid'] == 0) {
1755 Item::distribute($message_id, json_encode($data));
1763 * @brief processes and stores private messages
1765 * @param array $importer Array of the importer user
1766 * @param array $contact The contact of the message
1767 * @param object $data The message object
1768 * @param array $msg Array of the processed message, author handle and key
1769 * @param object $mesg The private message
1770 * @param array $conversation The conversation record to which this message belongs
1772 * @return bool "true" if it was successful
1774 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1776 $author = notags(XML::unescape($data->author));
1777 $guid = notags(XML::unescape($data->guid));
1778 $subject = notags(XML::unescape($data->subject));
1780 // "diaspora_handle" is the element name from the old version
1781 // "author" is the element name from the new version
1782 if ($mesg->author) {
1783 $msg_author = notags(XML::unescape($mesg->author));
1784 } elseif ($mesg->diaspora_handle) {
1785 $msg_author = notags(XML::unescape($mesg->diaspora_handle));
1790 $msg_guid = notags(XML::unescape($mesg->guid));
1791 $msg_conversation_guid = notags(XML::unescape($mesg->conversation_guid));
1792 $msg_text = XML::unescape($mesg->text);
1793 $msg_created_at = DateTimeFormat::utc(notags(XML::unescape($mesg->created_at)));
1795 if ($msg_conversation_guid != $guid) {
1796 Logger::log("message conversation guid does not belong to the current conversation.");
1800 $body = Markdown::toBBCode($msg_text);
1801 $message_uri = $msg_author.":".$msg_guid;
1803 $person = self::personByHandle($msg_author);
1807 if (DBA::exists('mail', ['guid' => $msg_guid, 'uid' => $importer["uid"]])) {
1808 Logger::log("duplicate message already delivered.", Logger::DEBUG);
1813 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1814 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1815 intval($importer["uid"]),
1816 DBA::escape($msg_guid),
1817 intval($conversation["id"]),
1818 DBA::escape($person["name"]),
1819 DBA::escape($person["photo"]),
1820 DBA::escape($person["url"]),
1821 intval($contact["id"]),
1822 DBA::escape($subject),
1826 DBA::escape($message_uri),
1827 DBA::escape($author.":".$guid),
1828 DBA::escape($msg_created_at)
1833 DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
1837 "type" => NOTIFY_MAIL,
1838 "notify_flags" => $importer["notify-flags"],
1839 "language" => $importer["language"],
1840 "to_name" => $importer["username"],
1841 "to_email" => $importer["email"],
1842 "uid" =>$importer["uid"],
1843 "item" => ["id" => $conversation["id"], "title" => $subject, "subject" => $subject, "body" => $body],
1844 "source_name" => $person["name"],
1845 "source_link" => $person["url"],
1846 "source_photo" => $person["photo"],
1847 "verb" => ACTIVITY_POST,
1854 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1856 * @param array $importer Array of the importer user
1857 * @param array $msg Array of the processed message, author handle and key
1858 * @param object $data The message object
1860 * @return bool Success
1862 private static function receiveConversation(array $importer, $msg, $data)
1864 $author = notags(XML::unescape($data->author));
1865 $guid = notags(XML::unescape($data->guid));
1866 $subject = notags(XML::unescape($data->subject));
1867 $created_at = DateTimeFormat::utc(notags(XML::unescape($data->created_at)));
1868 $participants = notags(XML::unescape($data->participants));
1870 $messages = $data->message;
1872 if (!count($messages)) {
1873 Logger::log("empty conversation");
1877 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1882 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1883 if (!DBA::isResult($conversation)) {
1885 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1886 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1887 intval($importer["uid"]),
1889 DBA::escape($author),
1890 DBA::escape($created_at),
1891 DBA::escape(DateTimeFormat::utcNow()),
1892 DBA::escape($subject),
1893 DBA::escape($participants)
1896 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1899 if (!$conversation) {
1900 Logger::log("unable to create conversation.");
1904 foreach ($messages as $mesg) {
1905 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1912 * @brief Processes "like" messages
1914 * @param array $importer Array of the importer user
1915 * @param string $sender The sender of the message
1916 * @param object $data The message object
1918 * @return int The message id of the generated like or "false" if there was an error
1920 private static function receiveLike(array $importer, $sender, $data)
1922 $author = notags(XML::unescape($data->author));
1923 $guid = notags(XML::unescape($data->guid));
1924 $parent_guid = notags(XML::unescape($data->parent_guid));
1925 $parent_type = notags(XML::unescape($data->parent_type));
1926 $positive = notags(XML::unescape($data->positive));
1928 // likes on comments aren't supported by Diaspora - only on posts
1929 // But maybe this will be supported in the future, so we will accept it.
1930 if (!in_array($parent_type, ["Post", "Comment"])) {
1934 $contact = self::allowedContactByHandle($importer, $sender, true);
1939 $message_id = self::messageExists($importer["uid"], $guid);
1944 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1945 if (!$parent_item) {
1949 $person = self::personByHandle($author);
1950 if (!is_array($person)) {
1951 Logger::log("unable to find author details");
1955 // Fetch the contact id - if we know this contact
1956 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1958 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1959 // We would accept this anyhow.
1960 if ($positive == "true") {
1961 $verb = ACTIVITY_LIKE;
1963 $verb = ACTIVITY_DISLIKE;
1968 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1970 $datarray["uid"] = $importer["uid"];
1971 $datarray["contact-id"] = $author_contact["cid"];
1972 $datarray["network"] = $author_contact["network"];
1974 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
1975 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1977 $datarray["guid"] = $guid;
1978 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1980 $datarray["verb"] = $verb;
1981 $datarray["gravity"] = GRAVITY_ACTIVITY;
1982 $datarray["parent-uri"] = $parent_item["uri"];
1984 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1986 $datarray["body"] = $verb;
1988 // Diaspora doesn't provide a date for likes
1989 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
1991 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1992 if ($parent_item["id"] != $parent_item["parent"]) {
1993 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
1994 $origin = $toplevel["origin"];
1996 $origin = $parent_item["origin"];
1999 // If we are the origin of the parent we store the original data.
2000 // We notify our followers during the item storage.
2002 $datarray['diaspora_signed_text'] = json_encode($data);
2005 $message_id = Item::insert($datarray);
2007 if ($message_id <= 0) {
2012 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2013 if ($datarray['uid'] == 0) {
2014 Item::distribute($message_id, json_encode($data));
2022 * @brief Processes private messages
2024 * @param array $importer Array of the importer user
2025 * @param object $data The message object
2027 * @return bool Success?
2029 private static function receiveMessage(array $importer, $data)
2031 $author = notags(XML::unescape($data->author));
2032 $guid = notags(XML::unescape($data->guid));
2033 $conversation_guid = notags(XML::unescape($data->conversation_guid));
2034 $text = XML::unescape($data->text);
2035 $created_at = DateTimeFormat::utc(notags(XML::unescape($data->created_at)));
2037 $contact = self::allowedContactByHandle($importer, $author, true);
2042 $conversation = null;
2044 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2045 $conversation = DBA::selectFirst('conv', [], $condition);
2047 if (!DBA::isResult($conversation)) {
2048 Logger::log("conversation not available.");
2052 $message_uri = $author.":".$guid;
2054 $person = self::personByHandle($author);
2056 Logger::log("unable to find author details");
2060 $body = Markdown::toBBCode($text);
2062 $body = self::replacePeopleGuid($body, $person["url"]);
2066 if (DBA::exists('mail', ['guid' => $guid, 'uid' => $importer["uid"]])) {
2067 Logger::log("duplicate message already delivered.", Logger::DEBUG);
2072 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2073 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2074 intval($importer["uid"]),
2076 intval($conversation["id"]),
2077 DBA::escape($person["name"]),
2078 DBA::escape($person["photo"]),
2079 DBA::escape($person["url"]),
2080 intval($contact["id"]),
2081 DBA::escape($conversation["subject"]),
2085 DBA::escape($message_uri),
2086 DBA::escape($author.":".$conversation["guid"]),
2087 DBA::escape($created_at)
2092 DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
2097 * @brief Processes participations - unsupported by now
2099 * @param array $importer Array of the importer user
2100 * @param object $data The message object
2102 * @return bool always true
2104 private static function receiveParticipation(array $importer, $data)
2106 $author = strtolower(notags(XML::unescape($data->author)));
2107 $parent_guid = notags(XML::unescape($data->parent_guid));
2109 $contact_id = Contact::getIdForURL($author);
2111 Logger::log('Contact not found: '.$author);
2115 $person = self::personByHandle($author);
2116 if (!is_array($person)) {
2117 Logger::log("Person not found: ".$author);
2121 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2122 if (!DBA::isResult($item)) {
2123 Logger::log('Item not found, no origin or private: '.$parent_guid);
2127 $author_parts = explode('@', $author);
2128 if (isset($author_parts[1])) {
2129 $server = $author_parts[1];
2131 // Should never happen
2135 Logger::log('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, Logger::DEBUG);
2137 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2138 DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2141 // Send all existing comments and likes to the requesting server
2142 $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2143 while ($comment = Item::fetch($comments)) {
2144 if ($comment['id'] == $comment['parent']) {
2147 if ($comment['verb'] == ACTIVITY_POST) {
2148 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2150 $cmd = $comment['self'] ? 'like' : 'comment-import';
2152 Logger::log("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, Logger::DEBUG);
2153 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2155 DBA::close($comments);
2161 * @brief Processes photos - unneeded
2163 * @param array $importer Array of the importer user
2164 * @param object $data The message object
2166 * @return bool always true
2168 private static function receivePhoto(array $importer, $data)
2170 // There doesn't seem to be a reason for this function,
2171 // since the photo data is transmitted in the status message as well
2176 * @brief Processes poll participations - unssupported
2178 * @param array $importer Array of the importer user
2179 * @param object $data The message object
2181 * @return bool always true
2183 private static function receivePollParticipation(array $importer, $data)
2185 // We don't support polls by now
2190 * @brief Processes incoming profile updates
2192 * @param array $importer Array of the importer user
2193 * @param object $data The message object
2195 * @return bool Success
2197 private static function receiveProfile(array $importer, $data)
2199 $author = strtolower(notags(XML::unescape($data->author)));
2201 $contact = self::contactByHandle($importer["uid"], $author);
2206 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2207 $image_url = XML::unescape($data->image_url);
2208 $birthday = XML::unescape($data->birthday);
2209 $gender = XML::unescape($data->gender);
2210 $about = Markdown::toBBCode(XML::unescape($data->bio));
2211 $location = Markdown::toBBCode(XML::unescape($data->location));
2212 $searchable = (XML::unescape($data->searchable) == "true");
2213 $nsfw = (XML::unescape($data->nsfw) == "true");
2214 $tags = XML::unescape($data->tag_string);
2216 $tags = explode("#", $tags);
2219 foreach ($tags as $tag) {
2220 $tag = trim(strtolower($tag));
2226 $keywords = implode(", ", $keywords);
2228 $handle_parts = explode("@", $author);
2229 $nick = $handle_parts[0];
2232 $name = $handle_parts[0];
2235 if (preg_match("|^https?://|", $image_url) === 0) {
2236 $image_url = "http://".$handle_parts[1].$image_url;
2239 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2241 // Generic birthday. We don't know the timezone. The year is irrelevant.
2243 $birthday = str_replace("1000", "1901", $birthday);
2245 if ($birthday != "") {
2246 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2249 // this is to prevent multiple birthday notifications in a single year
2250 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2252 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2253 $birthday = $contact["bd"];
2256 $fields = ['name' => $name, 'location' => $location,
2257 'name-date' => DateTimeFormat::utcNow(),
2258 'about' => $about, 'gender' => $gender,
2259 'addr' => $author, 'nick' => $nick,
2260 'keywords' => $keywords];
2262 if (!empty($birthday)) {
2263 $fields['bd'] = $birthday;
2266 DBA::update('contact', $fields, ['id' => $contact['id']]);
2268 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2269 "photo" => $image_url, "name" => $name, "location" => $location,
2270 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2271 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2272 "hide" => !$searchable, "nsfw" => $nsfw];
2274 $gcid = GContact::update($gcontact);
2276 GContact::link($gcid, $importer["uid"], $contact["id"]);
2278 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2284 * @brief Processes incoming friend requests
2286 * @param array $importer Array of the importer user
2287 * @param array $contact The contact that send the request
2290 private static function receiveRequestMakeFriend(array $importer, array $contact)
2294 if ($contact["rel"] == Contact::SHARING) {
2297 ['rel' => Contact::FRIEND, 'writable' => true],
2298 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2304 * @brief Processes incoming sharing notification
2306 * @param array $importer Array of the importer user
2307 * @param object $data The message object
2309 * @return bool Success
2311 private static function receiveContactRequest(array $importer, $data)
2313 $author = XML::unescape($data->author);
2314 $recipient = XML::unescape($data->recipient);
2316 if (!$author || !$recipient) {
2320 // the current protocol version doesn't know these fields
2321 // That means that we will assume their existance
2322 if (isset($data->following)) {
2323 $following = (XML::unescape($data->following) == "true");
2328 if (isset($data->sharing)) {
2329 $sharing = (XML::unescape($data->sharing) == "true");
2334 $contact = self::contactByHandle($importer["uid"], $author);
2336 // perhaps we were already sharing with this person. Now they're sharing with us.
2337 // That makes us friends.
2340 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2341 self::receiveRequestMakeFriend($importer, $contact);
2343 // refetch the contact array
2344 $contact = self::contactByHandle($importer["uid"], $author);
2346 // If we are now friends, we are sending a share message.
2347 // Normally we needn't to do so, but the first message could have been vanished.
2348 if (in_array($contact["rel"], [Contact::FRIEND])) {
2349 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2350 if (DBA::isResult($user)) {
2351 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2352 $ret = self::sendShare($user, $contact);
2357 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2358 Contact::removeFollower($importer, $contact);
2363 if (!$following && $sharing && in_array($importer["page-flags"], [Contact::PAGE_SOAPBOX, Contact::PAGE_NORMAL])) {
2364 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2366 } elseif (!$following && !$sharing) {
2367 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2369 } elseif (!$following && $sharing) {
2370 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2371 } elseif ($following && $sharing) {
2372 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2373 } elseif ($following && !$sharing) {
2374 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2377 $ret = self::personByHandle($author);
2379 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2380 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2384 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2387 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2388 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2389 intval($importer["uid"]),
2390 DBA::escape($ret["network"]),
2391 DBA::escape($ret["addr"]),
2392 DateTimeFormat::utcNow(),
2393 DBA::escape($ret["url"]),
2394 DBA::escape(normalise_link($ret["url"])),
2395 DBA::escape($batch),
2396 DBA::escape($ret["name"]),
2397 DBA::escape($ret["nick"]),
2398 DBA::escape($ret["photo"]),
2399 DBA::escape($ret["pubkey"]),
2400 DBA::escape($ret["notify"]),
2401 DBA::escape($ret["poll"]),
2406 // find the contact record we just created
2408 $contact_record = self::contactByHandle($importer["uid"], $author);
2410 if (!$contact_record) {
2411 Logger::log("unable to locate newly created contact record.");
2415 Logger::log("Author ".$author." was added as contact number ".$contact_record["id"].".", Logger::DEBUG);
2417 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2419 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2421 if (in_array($importer["page-flags"], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP])) {
2422 Logger::log("Sending intra message for author ".$author.".", Logger::DEBUG);
2424 $hash = random_string().(string)time(); // Generate a confirm_key
2427 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2428 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2429 intval($importer["uid"]),
2430 intval($contact_record["id"]),
2433 DBA::escape(L10n::t("Sharing notification from Diaspora network")),
2435 DBA::escape(DateTimeFormat::utcNow())
2438 // automatic friend approval
2440 Logger::log("Does an automatic friend approval for author ".$author.".", Logger::DEBUG);
2442 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2445 * technically they are sharing with us (Contact::SHARING),
2446 * but if our page-type is Profile::PAGE_COMMUNITY or Profile::PAGE_SOAPBOX
2447 * we are going to change the relationship and make them a follower.
2449 if (($importer["page-flags"] == Contact::PAGE_FREELOVE) && $sharing && $following) {
2450 $new_relation = Contact::FRIEND;
2451 } elseif (($importer["page-flags"] == Contact::PAGE_FREELOVE) && $sharing) {
2452 $new_relation = Contact::SHARING;
2454 $new_relation = Contact::FOLLOWER;
2458 "UPDATE `contact` SET `rel` = %d,
2466 intval($new_relation),
2467 DBA::escape(DateTimeFormat::utcNow()),
2468 DBA::escape(DateTimeFormat::utcNow()),
2469 intval($contact_record["id"])
2472 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2473 if (DBA::isResult($user)) {
2474 Logger::log("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2475 $ret = self::sendShare($user, $contact_record);
2477 // Send the profile data, maybe it weren't transmitted before
2478 self::sendProfile($importer["uid"], [$contact_record]);
2486 * @brief Fetches a message with a given guid
2488 * @param string $guid message guid
2489 * @param string $orig_author handle of the original post
2490 * @param string $author handle of the sharer
2492 * @return array The fetched item
2494 public static function originalItem($guid, $orig_author)
2497 Logger::log('Empty guid. Quitting.');
2501 // Do we already have this item?
2502 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2503 'author-name', 'author-link', 'author-avatar'];
2504 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2505 $item = Item::selectFirst($fields, $condition);
2507 if (DBA::isResult($item)) {
2508 Logger::log("reshared message ".$guid." already exists on system.");
2510 // Maybe it is already a reshared item?
2511 // Then refetch the content, if it is a reshare from a reshare.
2512 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2513 if (self::isReshare($item["body"], true)) {
2515 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2516 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2518 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2520 // Add OEmbed and other information to the body
2521 $item["body"] = add_page_info_to_body($item["body"], false, true);
2529 if (!DBA::isResult($item)) {
2530 if (empty($orig_author)) {
2531 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2535 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2536 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2537 $stored = self::storeByGuid($guid, $server);
2540 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2541 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2542 $stored = self::storeByGuid($guid, $server);
2546 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2547 'author-name', 'author-link', 'author-avatar'];
2548 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2549 $item = Item::selectFirst($fields, $condition);
2551 if (DBA::isResult($item)) {
2552 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2553 if (self::isReshare($item["body"], false)) {
2554 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2555 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2566 * @brief Processes a reshare message
2568 * @param array $importer Array of the importer user
2569 * @param object $data The message object
2570 * @param string $xml The original XML of the message
2572 * @return int the message id
2574 private static function receiveReshare(array $importer, $data, $xml)
2576 $author = notags(XML::unescape($data->author));
2577 $guid = notags(XML::unescape($data->guid));
2578 $created_at = DateTimeFormat::utc(notags(XML::unescape($data->created_at)));
2579 $root_author = notags(XML::unescape($data->root_author));
2580 $root_guid = notags(XML::unescape($data->root_guid));
2581 /// @todo handle unprocessed property "provider_display_name"
2582 $public = notags(XML::unescape($data->public));
2584 $contact = self::allowedContactByHandle($importer, $author, false);
2589 $message_id = self::messageExists($importer["uid"], $guid);
2594 $original_item = self::originalItem($root_guid, $root_author);
2595 if (!$original_item) {
2599 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2603 $datarray["uid"] = $importer["uid"];
2604 $datarray["contact-id"] = $contact["id"];
2605 $datarray["network"] = Protocol::DIASPORA;
2607 $datarray["author-link"] = $contact["url"];
2608 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2610 $datarray["owner-link"] = $datarray["author-link"];
2611 $datarray["owner-id"] = $datarray["author-id"];
2613 $datarray["guid"] = $guid;
2614 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2616 $datarray["verb"] = ACTIVITY_POST;
2617 $datarray["gravity"] = GRAVITY_PARENT;
2619 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2620 $datarray["source"] = $xml;
2622 $prefix = share_header(
2623 $original_item["author-name"],
2624 $original_item["author-link"],
2625 $original_item["author-avatar"],
2626 $original_item["guid"],
2627 $original_item["created"],
2630 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2632 $datarray["tag"] = $original_item["tag"];
2633 $datarray["app"] = $original_item["app"];
2635 $datarray["plink"] = self::plink($author, $guid);
2636 $datarray["private"] = (($public == "false") ? 1 : 0);
2637 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2639 $datarray["object-type"] = $original_item["object-type"];
2641 self::fetchGuid($datarray);
2642 $message_id = Item::insert($datarray);
2644 self::sendParticipation($contact, $datarray);
2647 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2648 if ($datarray['uid'] == 0) {
2649 Item::distribute($message_id);
2658 * @brief Processes retractions
2660 * @param array $importer Array of the importer user
2661 * @param array $contact The contact of the item owner
2662 * @param object $data The message object
2664 * @return bool success
2666 private static function itemRetraction(array $importer, array $contact, $data)
2668 $author = notags(XML::unescape($data->author));
2669 $target_guid = notags(XML::unescape($data->target_guid));
2670 $target_type = notags(XML::unescape($data->target_type));
2672 $person = self::personByHandle($author);
2673 if (!is_array($person)) {
2674 Logger::log("unable to find author detail for ".$author);
2678 if (empty($contact["url"])) {
2679 $contact["url"] = $person["url"];
2682 // Fetch items that are about to be deleted
2683 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2685 // When we receive a public retraction, we delete every item that we find.
2686 if ($importer['uid'] == 0) {
2687 $condition = ['guid' => $target_guid, 'deleted' => false];
2689 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2692 $r = Item::select($fields, $condition);
2693 if (!DBA::isResult($r)) {
2694 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2698 while ($item = Item::fetch($r)) {
2699 if (strstr($item['file'], '[')) {
2700 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2704 // Fetch the parent item
2705 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2707 // Only delete it if the parent author really fits
2708 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2709 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2713 Item::delete(['id' => $item['id']]);
2715 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], Logger::DEBUG);
2722 * @brief Receives retraction messages
2724 * @param array $importer Array of the importer user
2725 * @param string $sender The sender of the message
2726 * @param object $data The message object
2728 * @return bool Success
2730 private static function receiveRetraction(array $importer, $sender, $data)
2732 $target_type = notags(XML::unescape($data->target_type));
2734 $contact = self::contactByHandle($importer["uid"], $sender);
2735 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2736 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2744 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2746 switch ($target_type) {
2751 case "StatusMessage":
2752 return self::itemRetraction($importer, $contact, $data);
2754 case "PollParticipation":
2756 // Currently unsupported
2760 Logger::log("Unknown target type ".$target_type);
2767 * @brief Receives status messages
2769 * @param array $importer Array of the importer user
2770 * @param object $data The message object
2771 * @param string $xml The original XML of the message
2773 * @return int The message id of the newly created item
2775 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2777 $author = notags(XML::unescape($data->author));
2778 $guid = notags(XML::unescape($data->guid));
2779 $created_at = DateTimeFormat::utc(notags(XML::unescape($data->created_at)));
2780 $public = notags(XML::unescape($data->public));
2781 $text = XML::unescape($data->text);
2782 $provider_display_name = notags(XML::unescape($data->provider_display_name));
2784 $contact = self::allowedContactByHandle($importer, $author, false);
2789 $message_id = self::messageExists($importer["uid"], $guid);
2795 if ($data->location) {
2796 foreach ($data->location->children() as $fieldname => $data) {
2797 $address[$fieldname] = notags(XML::unescape($data));
2801 $body = Markdown::toBBCode($text);
2805 // Attach embedded pictures to the body
2807 foreach ($data->photo as $photo) {
2808 $body = "[img]".XML::unescape($photo->remote_photo_path).
2809 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2812 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2814 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2816 // Add OEmbed and other information to the body
2817 if (!self::isRedmatrix($contact["url"])) {
2818 $body = add_page_info_to_body($body, false, true);
2822 /// @todo enable support for polls
2823 //if ($data->poll) {
2824 // foreach ($data->poll AS $poll)
2829 /// @todo enable support for events
2831 $datarray["uid"] = $importer["uid"];
2832 $datarray["contact-id"] = $contact["id"];
2833 $datarray["network"] = Protocol::DIASPORA;
2835 $datarray["author-link"] = $contact["url"];
2836 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2838 $datarray["owner-link"] = $datarray["author-link"];
2839 $datarray["owner-id"] = $datarray["author-id"];
2841 $datarray["guid"] = $guid;
2842 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2844 $datarray["verb"] = ACTIVITY_POST;
2845 $datarray["gravity"] = GRAVITY_PARENT;
2847 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2848 $datarray["source"] = $xml;
2850 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2852 if ($provider_display_name != "") {
2853 $datarray["app"] = $provider_display_name;
2856 $datarray["plink"] = self::plink($author, $guid);
2857 $datarray["private"] = (($public == "false") ? 1 : 0);
2858 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2860 if (isset($address["address"])) {
2861 $datarray["location"] = $address["address"];
2864 if (isset($address["lat"]) && isset($address["lng"])) {
2865 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2868 self::fetchGuid($datarray);
2869 $message_id = Item::insert($datarray);
2871 self::sendParticipation($contact, $datarray);
2874 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2875 if ($datarray['uid'] == 0) {
2876 Item::distribute($message_id);
2884 /* ************************************************************************************** *
2885 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2886 * ************************************************************************************** */
2889 * @brief returnes the handle of a contact
2891 * @param array $contact contact array
2893 * @return string the handle in the format user@domain.tld
2895 private static function myHandle(array $contact)
2897 if (!empty($contact["addr"])) {
2898 return $contact["addr"];
2901 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2902 // So - just in case - we build the the address here.
2903 if ($contact["nickname"] != "") {
2904 $nick = $contact["nickname"];
2906 $nick = $contact["nick"];
2909 return $nick . "@" . substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
2914 * @brief Creates the data for a private message in the new format
2916 * @param string $msg The message that is to be transmitted
2917 * @param array $user The record of the sender
2918 * @param array $contact Target of the communication
2919 * @param string $prvkey The private key of the sender
2920 * @param string $pubkey The public key of the receiver
2922 * @return string The encrypted data
2924 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
2926 Logger::log("Message: ".$msg, Logger::DATA);
2928 // without a public key nothing will work
2930 Logger::log("pubkey missing: contact id: ".$contact["id"]);
2934 $aes_key = openssl_random_pseudo_bytes(32);
2935 $b_aes_key = base64_encode($aes_key);
2936 $iv = openssl_random_pseudo_bytes(16);
2937 $b_iv = base64_encode($iv);
2939 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2941 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
2943 $encrypted_key_bundle = "";
2944 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
2946 $json_object = json_encode(
2947 ["aes_key" => base64_encode($encrypted_key_bundle),
2948 "encrypted_magic_envelope" => base64_encode($ciphertext)]
2951 return $json_object;
2955 * @brief Creates the envelope for the "fetch" endpoint and for the new format
2957 * @param string $msg The message that is to be transmitted
2958 * @param array $user The record of the sender
2960 * @return string The envelope
2962 public static function buildMagicEnvelope($msg, array $user)
2964 $b64url_data = base64url_encode($msg);
2965 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
2967 $key_id = base64url_encode(self::myHandle($user));
2968 $type = "application/xml";
2969 $encoding = "base64url";
2970 $alg = "RSA-SHA256";
2971 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2973 // Fallback if the private key wasn't transmitted in the expected field
2974 if ($user['uprvkey'] == "") {
2975 $user['uprvkey'] = $user['prvkey'];
2978 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
2979 $sig = base64url_encode($signature);
2981 $xmldata = ["me:env" => ["me:data" => $data,
2982 "@attributes" => ["type" => $type],
2983 "me:encoding" => $encoding,
2986 "@attributes2" => ["key_id" => $key_id]]];
2988 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
2990 return XML::fromArray($xmldata, $xml, false, $namespaces);
2994 * @brief Create the envelope for a message
2996 * @param string $msg The message that is to be transmitted
2997 * @param array $user The record of the sender
2998 * @param array $contact Target of the communication
2999 * @param string $prvkey The private key of the sender
3000 * @param string $pubkey The public key of the receiver
3001 * @param bool $public Is the message public?
3003 * @return string The message that will be transmitted to other servers
3005 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3007 // The message is put into an envelope with the sender's signature
3008 $envelope = self::buildMagicEnvelope($msg, $user);
3010 // Private messages are put into a second envelope, encrypted with the receivers public key
3012 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3019 * @brief Creates a signature for a message
3021 * @param array $owner the array of the owner of the message
3022 * @param array $message The message that is to be signed
3024 * @return string The signature
3026 private static function signature($owner, $message)
3029 unset($sigmsg["author_signature"]);
3030 unset($sigmsg["parent_author_signature"]);
3032 $signed_text = implode(";", $sigmsg);
3034 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3038 * @brief Transmit a message to a target server
3040 * @param array $owner the array of the item owner
3041 * @param array $contact Target of the communication
3042 * @param string $envelope The message that is to be transmitted
3043 * @param bool $public_batch Is it a public post?
3044 * @param bool $queue_run Is the transmission called from the queue?
3045 * @param string $guid message guid
3047 * @return int Result of the transmission
3049 public static function transmit(array $owner, array $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
3053 $enabled = intval(Config::get("system", "diaspora_enabled"));
3058 $logid = random_string(4);
3060 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3062 // We always try to use the data from the fcontact table.
3063 // This is important for transmitting data to Friendica servers.
3064 if (!empty($contact['addr'])) {
3065 $fcontact = self::personByHandle($contact['addr']);
3066 if (!empty($fcontact)) {
3067 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3072 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3076 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3078 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3081 if (!intval(Config::get("system", "diaspora_test"))) {
3082 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3084 $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3085 $return_code = $postResult->getReturnCode();
3087 Logger::log("test_mode");
3092 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3094 if (!$return_code || (($return_code == 503) && (stristr($postResult->getHeader(), "retry-after")))) {
3095 if (!$no_queue && !empty($contact['contact-type']) && ($contact['contact-type'] != Contact::ACCOUNT_TYPE_RELAY)) {
3096 Logger::log("queue message");
3097 // queue message for redelivery
3098 Queue::add($contact["id"], Protocol::DIASPORA, $envelope, $public_batch, $guid);
3101 // The message could not be delivered. We mark the contact as "dead"
3102 Contact::markForArchival($contact);
3103 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3104 // We successfully delivered a message, the contact is alive
3105 Contact::unmarkForArchival($contact);
3108 return $return_code ? $return_code : -1;
3113 * @brief Build the post xml
3115 * @param string $type The message type
3116 * @param array $message The message data
3118 * @return string The post XML
3120 public static function buildPostXml($type, $message)
3122 $data = [$type => $message];
3124 return XML::fromArray($data, $xml);
3128 * @brief Builds and transmit messages
3130 * @param array $owner the array of the item owner
3131 * @param array $contact Target of the communication
3132 * @param string $type The message type
3133 * @param array $message The message data
3134 * @param bool $public_batch Is it a public post?
3135 * @param string $guid message guid
3136 * @param bool $spool Should the transmission be spooled or transmitted?
3138 * @return int Result of the transmission
3140 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3142 $msg = self::buildPostXml($type, $message);
3144 Logger::log('message: '.$msg, Logger::DATA);
3145 Logger::log('send guid '.$guid, Logger::DEBUG);
3147 // Fallback if the private key wasn't transmitted in the expected field
3148 if (empty($owner['uprvkey'])) {
3149 $owner['uprvkey'] = $owner['prvkey'];
3152 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3155 Queue::add($contact['id'], Protocol::DIASPORA, $envelope, $public_batch, $guid);
3158 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3161 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3163 return $return_code;
3167 * @brief sends a participation (Used to get all further updates)
3169 * @param array $contact Target of the communication
3170 * @param array $item Item array
3172 * @return int The result of the transmission
3174 private static function sendParticipation(array $contact, array $item)
3176 // Don't send notifications for private postings
3177 if ($item['private']) {
3181 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3183 $result = Cache::get($cachekey);
3184 if (!is_null($result)) {
3188 // Fetch some user id to have a valid handle to transmit the participation.
3189 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3190 // If the item belongs to a user, we take this user id.
3191 if ($item['uid'] == 0) {
3192 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3193 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3194 $owner = User::getOwnerDataById($first_user['uid']);
3196 $owner = User::getOwnerDataById($item['uid']);
3199 $author = self::myHandle($owner);
3201 $message = ["author" => $author,
3202 "guid" => System::createUUID(),
3203 "parent_type" => "Post",
3204 "parent_guid" => $item["guid"]];
3206 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3208 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3209 Cache::set($cachekey, $item["guid"], Cache::QUARTER_HOUR);
3211 return self::buildAndTransmit($owner, $contact, "participation", $message);
3215 * @brief sends an account migration
3217 * @param array $owner the array of the item owner
3218 * @param array $contact Target of the communication
3219 * @param int $uid User ID
3221 * @return int The result of the transmission
3223 public static function sendAccountMigration(array $owner, array $contact, $uid)
3225 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3226 $profile = self::createProfileData($uid);
3228 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3229 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3231 $message = ["author" => $old_handle,
3232 "profile" => $profile,
3233 "signature" => $signature];
3235 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3237 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3241 * @brief Sends a "share" message
3243 * @param array $owner the array of the item owner
3244 * @param array $contact Target of the communication
3246 * @return int The result of the transmission
3248 public static function sendShare(array $owner, array $contact)
3251 * @todo support the different possible combinations of "following" and "sharing"
3252 * Currently, Diaspora only interprets the "sharing" field
3254 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3258 switch ($contact["rel"]) {
3259 case Contact::FRIEND:
3263 case Contact::SHARING:
3267 case Contact::FOLLOWER:
3273 $message = ["author" => self::myHandle($owner),
3274 "recipient" => $contact["addr"],
3275 "following" => "true",
3276 "sharing" => "true"];
3278 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3280 return self::buildAndTransmit($owner, $contact, "contact", $message);
3284 * @brief sends an "unshare"
3286 * @param array $owner the array of the item owner
3287 * @param array $contact Target of the communication
3289 * @return int The result of the transmission
3291 public static function sendUnshare(array $owner, array $contact)
3293 $message = ["author" => self::myHandle($owner),
3294 "recipient" => $contact["addr"],
3295 "following" => "false",
3296 "sharing" => "false"];
3298 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3300 return self::buildAndTransmit($owner, $contact, "contact", $message);
3304 * @brief Checks a message body if it is a reshare
3306 * @param string $body The message body that is to be check
3307 * @param bool $complete Should it be a complete check or a simple check?
3309 * @return array|bool Reshare details or "false" if no reshare
3311 public static function isReshare($body, $complete = true)
3313 $body = trim($body);
3315 // Skip if it isn't a pure repeated messages
3316 // Does it start with a share?
3317 if ((strpos($body, "[share") > 0) && $complete) {
3321 // Does it end with a share?
3322 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3326 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3327 // Skip if there is no shared message in there
3328 if ($body == $attributes) {
3332 // If we don't do the complete check we quit here
3335 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3336 if (!empty($matches[1])) {
3337 $guid = $matches[1];
3340 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3341 if (!empty($matches[1])) {
3342 $guid = $matches[1];
3345 if (($guid != "") && $complete) {
3346 $condition = ['guid' => $guid, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3347 $item = Item::selectFirst(['contact-id'], $condition);
3348 if (DBA::isResult($item)) {
3350 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3351 $ret["root_guid"] = $guid;
3353 } elseif ($complete) {
3354 // We are resharing something that isn't a DFRN or Diaspora post.
3355 // So we have to return "false" on "$complete" to not trigger a reshare.
3358 } elseif (($guid == "") && $complete) {
3362 $ret["root_guid"] = $guid;
3365 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3366 if (!empty($matches[1])) {
3367 $profile = $matches[1];
3370 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3371 if (!empty($matches[1])) {
3372 $profile = $matches[1];
3377 if ($profile != "") {
3378 if (Contact::getIdForURL($profile)) {
3379 $author = Contact::getDetailsByURL($profile);
3380 $ret["root_handle"] = $author['addr'];
3384 if (empty($ret) && !$complete) {
3392 * @brief Create an event array
3394 * @param integer $event_id The id of the event
3396 * @return array with event data
3398 private static function buildEvent($event_id)
3400 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3401 if (!DBA::isResult($r)) {
3409 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3410 if (!DBA::isResult($r)) {
3416 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3417 if (!DBA::isResult($r)) {
3423 $eventdata['author'] = self::myHandle($owner);
3425 if ($event['guid']) {
3426 $eventdata['guid'] = $event['guid'];
3429 $mask = DateTimeFormat::ATOM;
3431 /// @todo - establish "all day" events in Friendica
3432 $eventdata["all_day"] = "false";
3434 $eventdata['timezone'] = 'UTC';
3435 if (!$event['adjust'] && $user['timezone']) {
3436 $eventdata['timezone'] = $user['timezone'];
3439 if ($event['start']) {
3440 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3442 if ($event['finish'] && !$event['nofinish']) {
3443 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3445 if ($event['summary']) {
3446 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3448 if ($event['desc']) {
3449 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3451 if ($event['location']) {
3452 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3453 $coord = Map::getCoordinates($event['location']);
3456 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3457 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3458 $location["lat"] = $coord['lat'];
3459 $location["lng"] = $coord['lon'];
3461 $location["lat"] = 0;
3462 $location["lng"] = 0;
3464 $eventdata['location'] = $location;
3471 * @brief Create a post (status message or reshare)
3473 * @param array $item The item that will be exported
3474 * @param array $owner the array of the item owner
3477 * 'type' -> Message type ("status_message" or "reshare")
3478 * 'message' -> Array of XML elements of the status
3480 public static function buildStatus(array $item, array $owner)
3482 $cachekey = "diaspora:buildStatus:".$item['guid'];
3484 $result = Cache::get($cachekey);
3485 if (!is_null($result)) {
3489 $myaddr = self::myHandle($owner);
3491 $public = ($item["private"] ? "false" : "true");
3493 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3495 // Detect a share element and do a reshare
3496 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3497 $message = ["author" => $myaddr,
3498 "guid" => $item["guid"],
3499 "created_at" => $created,
3500 "root_author" => $ret["root_handle"],
3501 "root_guid" => $ret["root_guid"],
3502 "provider_display_name" => $item["app"],
3503 "public" => $public];
3507 $title = $item["title"];
3508 $body = $item["body"];
3510 if ($item['author-link'] != $item['owner-link']) {
3511 require_once 'mod/share.php';
3512 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3513 "", $item['created'], $item['plink']) . $body . '[/share]';
3516 // convert to markdown
3517 $body = html_entity_decode(BBCode::toMarkdown($body));
3520 if (strlen($title)) {
3521 $body = "## ".html_entity_decode($title)."\n\n".$body;
3524 if ($item["attach"]) {
3525 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3527 $body .= "\n".L10n::t("Attachments:")."\n";
3528 foreach ($matches as $mtch) {
3529 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3536 if ($item["location"] != "")
3537 $location["address"] = $item["location"];
3539 if ($item["coord"] != "") {
3540 $coord = explode(" ", $item["coord"]);
3541 $location["lat"] = $coord[0];
3542 $location["lng"] = $coord[1];
3545 $message = ["author" => $myaddr,
3546 "guid" => $item["guid"],
3547 "created_at" => $created,
3548 "public" => $public,
3550 "provider_display_name" => $item["app"],
3551 "location" => $location];
3553 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3554 if (!isset($location["lat"]) || !isset($location["lng"])) {
3555 unset($message["location"]);
3558 if ($item['event-id'] > 0) {
3559 $event = self::buildEvent($item['event-id']);
3560 if (count($event)) {
3561 $message['event'] = $event;
3563 if (!empty($event['location']['address']) &&
3564 !empty($event['location']['lat']) &&
3565 !empty($event['location']['lng'])) {
3566 $message['location'] = $event['location'];
3569 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3570 // $message['text'] = '';
3574 $type = "status_message";
3577 $msg = ["type" => $type, "message" => $message];
3579 Cache::set($cachekey, $msg, Cache::QUARTER_HOUR);
3585 * @brief Sends a post
3587 * @param array $item The item that will be exported
3588 * @param array $owner the array of the item owner
3589 * @param array $contact Target of the communication
3590 * @param bool $public_batch Is it a public post?
3592 * @return int The result of the transmission
3594 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3596 $status = self::buildStatus($item, $owner);
3598 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3602 * @brief Creates a "like" object
3604 * @param array $item The item that will be exported
3605 * @param array $owner the array of the item owner
3607 * @return array The data for a "like"
3609 private static function constructLike(array $item, array $owner)
3611 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3612 if (!DBA::isResult($parent)) {
3616 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3618 if ($item['verb'] === ACTIVITY_LIKE) {
3620 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3621 $positive = "false";
3624 return(["author" => self::myHandle($owner),
3625 "guid" => $item["guid"],
3626 "parent_guid" => $parent["guid"],
3627 "parent_type" => $target_type,
3628 "positive" => $positive,
3629 "author_signature" => ""]);
3633 * @brief Creates an "EventParticipation" object
3635 * @param array $item The item that will be exported
3636 * @param array $owner the array of the item owner
3638 * @return array The data for an "EventParticipation"
3640 private static function constructAttend(array $item, array $owner)
3642 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3643 if (!DBA::isResult($parent)) {
3647 switch ($item['verb']) {
3648 case ACTIVITY_ATTEND:
3649 $attend_answer = 'accepted';
3651 case ACTIVITY_ATTENDNO:
3652 $attend_answer = 'declined';
3654 case ACTIVITY_ATTENDMAYBE:
3655 $attend_answer = 'tentative';
3658 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3662 return(["author" => self::myHandle($owner),
3663 "guid" => $item["guid"],
3664 "parent_guid" => $parent["guid"],
3665 "status" => $attend_answer,
3666 "author_signature" => ""]);
3670 * @brief Creates the object for a comment
3672 * @param array $item The item that will be exported
3673 * @param array $owner the array of the item owner
3675 * @return array The data for a comment
3677 private static function constructComment(array $item, array $owner)
3679 $cachekey = "diaspora:constructComment:".$item['guid'];
3681 $result = Cache::get($cachekey);
3682 if (!is_null($result)) {
3686 $parent = Item::selectFirst(['guid'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3687 if (!DBA::isResult($parent)) {
3691 $text = html_entity_decode(BBCode::toMarkdown($item["body"]));
3692 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3694 $comment = ["author" => self::myHandle($owner),
3695 "guid" => $item["guid"],
3696 "created_at" => $created,
3697 "parent_guid" => $parent["guid"],
3699 "author_signature" => ""];
3701 // Send the thread parent guid only if it is a threaded comment
3702 if ($item['thr-parent'] != $item['parent-uri']) {
3703 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3706 Cache::set($cachekey, $comment, Cache::QUARTER_HOUR);
3712 * @brief Send a like or a comment
3714 * @param array $item The item that will be exported
3715 * @param array $owner the array of the item owner
3716 * @param array $contact Target of the communication
3717 * @param bool $public_batch Is it a public post?
3719 * @return int The result of the transmission
3721 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3723 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3724 $message = self::constructAttend($item, $owner);
3725 $type = "event_participation";
3726 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3727 $message = self::constructLike($item, $owner);
3730 $message = self::constructComment($item, $owner);
3738 $message["author_signature"] = self::signature($owner, $message);
3740 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3744 * @brief Creates a message from a signature record entry
3746 * @param array $item The item that will be exported
3747 * @param array $signature The entry of the "sign" record
3749 * @return string The message
3751 private static function messageFromSignature(array $item)
3753 // Split the signed text
3754 $signed_parts = explode(";", $item['signed_text']);
3756 if ($item["deleted"]) {
3757 $message = ["author" => $item['signer'],
3758 "target_guid" => $signed_parts[0],
3759 "target_type" => $signed_parts[1]];
3760 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3761 $message = ["author" => $signed_parts[4],
3762 "guid" => $signed_parts[1],
3763 "parent_guid" => $signed_parts[3],
3764 "parent_type" => $signed_parts[2],
3765 "positive" => $signed_parts[0],
3766 "author_signature" => $item['signature'],
3767 "parent_author_signature" => ""];
3769 // Remove the comment guid
3770 $guid = array_shift($signed_parts);
3772 // Remove the parent guid
3773 $parent_guid = array_shift($signed_parts);
3775 // Remove the handle
3776 $handle = array_pop($signed_parts);
3778 // Glue the parts together
3779 $text = implode(";", $signed_parts);
3781 $message = ["author" => $handle,
3783 "parent_guid" => $parent_guid,
3784 "text" => implode(";", $signed_parts),
3785 "author_signature" => $item['signature'],
3786 "parent_author_signature" => ""];
3792 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3794 * @param array $item The item that will be exported
3795 * @param array $owner the array of the item owner
3796 * @param array $contact Target of the communication
3797 * @param bool $public_batch Is it a public post?
3799 * @return int The result of the transmission
3801 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3803 if ($item["deleted"]) {
3804 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3805 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3811 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3813 // Old way - is used by the internal Friendica functions
3814 /// @todo Change all signatur storing functions to the new format
3815 if ($item['signed_text'] && $item['signature'] && $item['signer']) {
3816 $message = self::messageFromSignature($item);
3818 $msg = json_decode($item['signed_text'], true);
3821 if (is_array($msg)) {
3822 foreach ($msg as $field => $data) {
3823 if (!$item["deleted"]) {
3824 if ($field == "diaspora_handle") {
3827 if ($field == "target_type") {
3828 $field = "parent_type";
3832 $message[$field] = $data;
3835 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
3839 $message["parent_author_signature"] = self::signature($owner, $message);
3841 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
3843 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3847 * @brief Sends a retraction (deletion) of a message, like or comment
3849 * @param array $item The item that will be exported
3850 * @param array $owner the array of the item owner
3851 * @param array $contact Target of the communication
3852 * @param bool $public_batch Is it a public post?
3853 * @param bool $relay Is the retraction transmitted from a relay?
3855 * @return int The result of the transmission
3857 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
3859 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3861 $msg_type = "retraction";
3863 if ($item['id'] == $item['parent']) {
3864 $target_type = "Post";
3865 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3866 $target_type = "Like";
3868 $target_type = "Comment";
3871 $message = ["author" => $itemaddr,
3872 "target_guid" => $item['guid'],
3873 "target_type" => $target_type];
3875 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
3877 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3881 * @brief Sends a mail
3883 * @param array $item The item that will be exported
3884 * @param array $owner The owner
3885 * @param array $contact Target of the communication
3887 * @return int The result of the transmission
3889 public static function sendMail(array $item, array $owner, array $contact)
3891 $myaddr = self::myHandle($owner);
3893 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
3894 if (!DBA::isResult($cnv)) {
3895 Logger::log("conversation not found.");
3900 "author" => $cnv["creator"],
3901 "guid" => $cnv["guid"],
3902 "subject" => $cnv["subject"],
3903 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3904 "participants" => $cnv["recips"]
3907 $body = BBCode::toMarkdown($item["body"]);
3908 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3911 "author" => $myaddr,
3912 "guid" => $item["guid"],
3913 "conversation_guid" => $cnv["guid"],
3915 "created_at" => $created,
3918 if ($item["reply"]) {
3923 "author" => $cnv["creator"],
3924 "guid" => $cnv["guid"],
3925 "subject" => $cnv["subject"],
3926 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3927 "participants" => $cnv["recips"],
3930 $type = "conversation";
3933 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
3937 * @brief Split a name into first name and last name
3939 * @param string $name The name
3941 * @return array The array with "first" and "last"
3943 public static function splitName($name) {
3944 $name = trim($name);
3946 // Is the name longer than 64 characters? Then cut the rest of it.
3947 if (strlen($name) > 64) {
3948 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3949 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3951 $name = substr($name, 0, 64);
3955 // Take the first word as first name
3956 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3957 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3958 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3959 return ['first' => $first, 'last' => $last];
3962 // Take the last word as last name
3963 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3964 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3966 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3967 return ['first' => $first, 'last' => $last];
3970 // Take the first 32 characters if there is no space in the first 32 characters
3971 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3972 $first = substr($name, 0, 32);
3973 $last = substr($name, 32);
3974 return ['first' => $first, 'last' => $last];
3977 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3978 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3980 // Check if the last name is longer than 32 characters
3981 if (strlen($last) > 32) {
3982 if (strpos($last, ' ') <= 32) {
3983 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
3985 $last = substr($last, 0, 32);
3989 return ['first' => $first, 'last' => $last];
3993 * @brief Create profile data
3995 * @param int $uid The user id
3997 * @return array The profile data
3999 private static function createProfileData($uid)
4002 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4004 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4005 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4006 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4015 $handle = $profile["addr"];
4017 $split_name = self::splitName($profile['name']);
4018 $first = $split_name['first'];
4019 $last = $split_name['last'];
4021 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4022 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4023 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4024 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4030 if ($searchable === 'true') {
4033 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4034 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4038 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4041 $about = $profile['about'];
4042 $about = strip_tags(BBCode::convert($about));
4044 $location = Profile::formatLocation($profile);
4046 if ($profile['pub_keywords']) {
4047 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4048 $kw = str_replace(' ', ' ', $kw);
4049 $arr = explode(' ', $profile['pub_keywords']);
4051 for ($x = 0; $x < 5; $x ++) {
4052 if (!empty($arr[$x])) {
4053 $tags .= '#'. trim($arr[$x]) .' ';
4058 $tags = trim($tags);
4061 return ["author" => $handle,
4062 "first_name" => $first,
4063 "last_name" => $last,
4064 "image_url" => $large,
4065 "image_url_medium" => $medium,
4066 "image_url_small" => $small,
4068 "gender" => $profile['gender'],
4070 "location" => $location,
4071 "searchable" => $searchable,
4073 "tag_string" => $tags];
4077 * @brief Sends profile data
4079 * @param int $uid The user id
4080 * @param bool $recips optional, default false
4083 public static function sendProfile($uid, $recips = false)
4089 $owner = User::getOwnerDataById($uid);
4096 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4097 AND `uid` = %d AND `rel` != %d",
4098 DBA::escape(Protocol::DIASPORA),
4100 intval(Contact::SHARING)
4108 $message = self::createProfileData($uid);
4110 foreach ($recips as $recip) {
4111 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4112 self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4117 * @brief Creates the signature for likes that are created on our system
4119 * @param integer $uid The user of that comment
4120 * @param array $item Item array
4122 * @return array Signed content
4124 public static function createLikeSignature($uid, array $item)
4126 $owner = User::getOwnerDataById($uid);
4127 if (empty($owner)) {
4128 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4132 if (!in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4136 $message = self::constructLike($item, $owner);
4137 if ($message === false) {
4141 $message["author_signature"] = self::signature($owner, $message);
4147 * @brief Creates the signature for Comments that are created on our system
4149 * @param integer $uid The user of that comment
4150 * @param array $item Item array
4152 * @return array Signed content
4154 public static function createCommentSignature($uid, array $item)
4156 $owner = User::getOwnerDataById($uid);
4157 if (empty($owner)) {
4158 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4162 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4163 $item['thr-parent'] = $item['parent-uri'];
4165 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4166 if (!DBA::isResult($parent)) {
4170 $item['parent-uri'] = $parent['parent-uri'];
4172 $message = self::constructComment($item, $owner);
4173 if ($message === false) {
4177 $message["author_signature"] = self::signature($owner, $message);