3 * @file include/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 * Currently this implementation here interprets the old and the new protocol and sends the old one.
8 * This will change in the future.
11 use \Friendica\Core\Config;
13 require_once 'include/items.php';
14 require_once 'include/bb2diaspora.php';
15 require_once 'include/Scrape.php';
16 require_once 'include/Contact.php';
17 require_once 'include/Photo.php';
18 require_once 'include/socgraph.php';
19 require_once 'include/group.php';
20 require_once 'include/xml.php';
21 require_once 'include/datetime.php';
22 require_once 'include/queue_fn.php';
23 require_once 'include/cache.php';
26 * @brief This class contain functions to create and send Diaspora XML files
32 * @brief Return a list of relay servers
34 * This is an experimental Diaspora feature.
36 * @return array of relay servers
38 public static function relay_list() {
40 $serverdata = get_config("system", "relay_server");
41 if ($serverdata == "")
46 $servers = explode(",", $serverdata);
48 foreach ($servers AS $server) {
49 $server = trim($server);
50 $addr = "relay@".str_replace("http://", "", normalise_link($server));
51 $batch = $server."/receive/public";
53 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
54 dbesc($batch), dbesc($addr), dbesc(normalise_link($server)));
57 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
58 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
63 dbesc(normalise_link($server)),
65 dbesc(NETWORK_DIASPORA),
66 intval(CONTACT_IS_FOLLOWER),
67 dbesc(datetime_convert()),
68 dbesc(datetime_convert()),
69 dbesc(datetime_convert())
72 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
74 $relay[] = $relais[0];
76 $relay[] = $relais[0];
83 * @brief repairs a signature that was double encoded
85 * The function is unused at the moment. It was copied from the old implementation.
87 * @param string $signature The signature
88 * @param string $handle The handle of the signature owner
89 * @param integer $level This value is only set inside this function to avoid endless loops
91 * @return string the repaired signature
93 private static function repair_signature($signature, $handle = "", $level = 1) {
98 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
99 $signature = base64_decode($signature);
100 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
102 // Do a recursive call to be able to fix even multiple levels
104 $signature = self::repair_signature($signature, $handle, ++$level);
111 * @brief verify the envelope and return the verified data
113 * @param string $envelope The magic envelope
115 * @return string verified data
117 private static function verify_magic_envelope($envelope) {
119 $basedom = parse_xml_string($envelope, false);
121 if (!is_object($basedom)) {
122 logger("Envelope is no XML file");
126 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
128 if (sizeof($children) == 0) {
129 logger("XML has no children");
135 $data = base64url_decode($children->data);
136 $type = $children->data->attributes()->type[0];
138 $encoding = $children->encoding;
140 $alg = $children->alg;
142 $sig = base64url_decode($children->sig);
143 $key_id = $children->sig->attributes()->key_id[0];
145 $handle = base64url_decode($key_id);
147 $b64url_data = base64url_encode($data);
148 $msg = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
150 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
152 $key = self::key($handle);
154 $verify = rsa_verify($signable_data, $sig, $key);
156 logger('Message did not verify. Discarding.');
164 * @brief encrypts data via AES
166 * @param string $key The AES key
167 * @param string $iv The IV (is used for CBC encoding)
168 * @param string $data The data that is to be encrypted
170 * @return string encrypted data
172 private static function aes_encrypt($key, $iv, $data) {
173 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
177 * @brief decrypts data via AES
179 * @param string $key The AES key
180 * @param string $iv The IV (is used for CBC encoding)
181 * @param string $encrypted The encrypted data
183 * @return string decrypted data
185 private static function aes_decrypt($key, $iv, $encrypted) {
186 return openssl_decrypt($encrypted,'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA,str_pad($iv, 16, "\0"));
190 * @brief: Decodes incoming Diaspora message in the new format
192 * @param array $importer Array of the importer user
193 * @param string $raw raw post message
196 * 'message' -> decoded Diaspora XML message
197 * 'author' -> author diaspora handle
198 * 'key' -> author public key (converted to pkcs#8)
200 public static function decode_raw($importer, $raw) {
201 $data = json_decode($raw);
203 // Is it a private post? Then decrypt the outer Salmon
204 if (is_object($data)) {
205 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
206 $ciphertext = base64_decode($data->encrypted_magic_envelope);
208 $outer_key_bundle = '';
209 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
210 $j_outer_key_bundle = json_decode($outer_key_bundle);
212 if (!is_object($j_outer_key_bundle)) {
213 logger('Outer Salmon did not verify. Discarding.');
214 http_status_exit(400);
217 $outer_iv = base64_decode($j_outer_key_bundle->iv);
218 $outer_key = base64_decode($j_outer_key_bundle->key);
220 $xml = diaspora::aes_decrypt($outer_key, $outer_iv, $ciphertext);
225 $basedom = parse_xml_string($xml);
227 if (!is_object($basedom)) {
228 logger('Received data does not seem to be an XML. Discarding.');
229 http_status_exit(400);
232 $base = $basedom->children(NAMESPACE_SALMON_ME);
234 // Not sure if this cleaning is needed
235 $data = str_replace(array(" ", "\t", "\r", "\n"), array("", "", "", ""), $base->data);
237 // Build the signed data
238 $type = $base->data[0]->attributes()->type[0];
239 $encoding = $base->encoding;
241 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
243 // This is the signature
244 $signature = base64url_decode($base->sig);
246 // Get the senders' public key
247 $key_id = $base->sig[0]->attributes()->key_id[0];
248 $author_addr = base64_decode($key_id);
249 $key = diaspora::key($author_addr);
251 $verify = rsa_verify($signed_data, $signature, $key);
253 logger('Message did not verify. Discarding.');
254 http_status_exit(400);
257 return array('message' => (string)base64url_decode($base->data),
258 'author' => unxmlify($author_addr),
259 'key' => (string)$key);
263 * @brief: Decodes incoming Diaspora message in the deprecated format
265 * @param array $importer Array of the importer user
266 * @param string $xml urldecoded Diaspora salmon
269 * 'message' -> decoded Diaspora XML message
270 * 'author' -> author diaspora handle
271 * 'key' -> author public key (converted to pkcs#8)
273 public static function decode($importer, $xml) {
276 $basedom = parse_xml_string($xml);
278 if (!is_object($basedom)) {
279 logger("XML is not parseable.");
282 $children = $basedom->children('https://joindiaspora.com/protocol');
284 if ($children->header) {
286 $author_link = str_replace('acct:','',$children->header->author_id);
289 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
291 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
292 $ciphertext = base64_decode($encrypted_header->ciphertext);
294 $outer_key_bundle = '';
295 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
297 $j_outer_key_bundle = json_decode($outer_key_bundle);
299 $outer_iv = base64_decode($j_outer_key_bundle->iv);
300 $outer_key = base64_decode($j_outer_key_bundle->key);
302 $decrypted = self::aes_decrypt($outer_key, $outer_iv, $ciphertext);
304 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
305 $idom = parse_xml_string($decrypted,false);
307 $inner_iv = base64_decode($idom->iv);
308 $inner_aes_key = base64_decode($idom->aes_key);
310 $author_link = str_replace('acct:','',$idom->author_id);
313 $dom = $basedom->children(NAMESPACE_SALMON_ME);
315 // figure out where in the DOM tree our data is hiding
317 if ($dom->provenance->data)
318 $base = $dom->provenance;
319 elseif ($dom->env->data)
325 logger('unable to locate salmon data in xml');
326 http_status_exit(400);
330 // Stash the signature away for now. We have to find their key or it won't be good for anything.
331 $signature = base64url_decode($base->sig);
335 // strip whitespace so our data element will return to one big base64 blob
336 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
339 // stash away some other stuff for later
341 $type = $base->data[0]->attributes()->type[0];
342 $keyhash = $base->sig[0]->attributes()->keyhash[0];
343 $encoding = $base->encoding;
347 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
351 $data = base64url_decode($data);
355 $inner_decrypted = $data;
358 // Decode the encrypted blob
360 $inner_encrypted = base64_decode($data);
361 $inner_decrypted = self::aes_decrypt($inner_aes_key, $inner_iv, $inner_encrypted);
365 logger('Could not retrieve author URI.');
366 http_status_exit(400);
368 // Once we have the author URI, go to the web and try to find their public key
369 // (first this will look it up locally if it is in the fcontact cache)
370 // This will also convert diaspora public key from pkcs#1 to pkcs#8
372 logger('Fetching key for '.$author_link);
373 $key = self::key($author_link);
376 logger('Could not retrieve author key.');
377 http_status_exit(400);
380 $verify = rsa_verify($signed_data,$signature,$key);
383 logger('Message did not verify. Discarding.');
384 http_status_exit(400);
387 logger('Message verified.');
389 return array('message' => (string)$inner_decrypted,
390 'author' => unxmlify($author_link),
391 'key' => (string)$key);
396 * @brief Dispatches public messages and find the fitting receivers
398 * @param array $msg The post that will be dispatched
400 * @return int The message id of the generated message, "true" or "false" if there was an error
402 public static function dispatch_public($msg) {
404 $enabled = intval(get_config("system", "diaspora_enabled"));
406 logger("diaspora is disabled");
410 if (!($postdata = self::valid_posting($msg))) {
411 logger("Invalid posting");
415 $fields = $postdata['fields'];
417 // Is it a an action (comment, like, ...) for our own post?
418 if (isset($fields->parent_guid) AND !$postdata["relayed"]) {
419 $guid = notags(unxmlify($fields->parent_guid));
420 $importer = self::importer_for_guid($guid);
421 if (is_array($importer)) {
422 logger("delivering to origin: ".$importer["name"]);
423 $message_id = self::dispatch($importer, $msg, $fields);
428 // Now distribute it to the followers
429 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
430 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
431 AND NOT `account_expired` AND NOT `account_removed`",
432 dbesc(NETWORK_DIASPORA),
433 dbesc($msg["author"])
436 if (dbm::is_result($r)) {
437 foreach ($r as $rr) {
438 logger("delivering to: ".$rr["username"]);
439 self::dispatch($rr, $msg, $fields);
441 } elseif (!Config::get('system', 'relay_subscribe', false)) {
442 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
444 // Use a dummy importer to import the data for the public copy
445 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
446 $message_id = self::dispatch($importer, $msg, $fields);
453 * @brief Dispatches the different message types to the different functions
455 * @param array $importer Array of the importer user
456 * @param array $msg The post that will be dispatched
457 * @param object $fields SimpleXML object that contains the message
459 * @return int The message id of the generated message, "true" or "false" if there was an error
461 public static function dispatch($importer, $msg, $fields = null) {
463 // The sender is the handle of the contact that sent the message.
464 // This will often be different with relayed messages (for example "like" and "comment")
465 $sender = $msg["author"];
467 // This is only needed for private postings since this is already done for public ones before
468 if (is_null($fields)) {
469 if (!($postdata = self::valid_posting($msg))) {
470 logger("Invalid posting");
473 $fields = $postdata['fields'];
476 $type = $fields->getName();
478 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
481 case "account_deletion":
482 return self::receive_account_deletion($importer, $fields);
485 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
488 return self::receive_contact_request($importer, $fields);
491 return self::receive_conversation($importer, $msg, $fields);
494 return self::receive_like($importer, $sender, $fields);
497 return self::receive_message($importer, $fields);
499 case "participation": // Not implemented
500 return self::receive_participation($importer, $fields);
502 case "photo": // Not implemented
503 return self::receive_photo($importer, $fields);
505 case "poll_participation": // Not implemented
506 return self::receive_poll_participation($importer, $fields);
509 return self::receive_profile($importer, $fields);
512 return self::receive_reshare($importer, $fields, $msg["message"]);
515 return self::receive_retraction($importer, $sender, $fields);
517 case "status_message":
518 return self::receive_status_message($importer, $fields, $msg["message"]);
521 logger("Unknown message type ".$type);
529 * @brief Checks if a posting is valid and fetches the data fields.
531 * This function does not only check the signature.
532 * It also does the conversion between the old and the new diaspora format.
534 * @param array $msg Array with the XML, the sender handle and the sender signature
536 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
538 private static function valid_posting($msg) {
540 $data = parse_xml_string($msg["message"], false);
542 if (!is_object($data)) {
543 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
547 $first_child = $data->getName();
549 // Is this the new or the old version?
550 if ($data->getName() == "XML") {
552 foreach ($data->post->children() as $child)
559 $type = $element->getName();
562 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
564 // All retractions are handled identically from now on.
565 // In the new version there will only be "retraction".
566 if (in_array($type, array("signed_retraction", "relayable_retraction")))
567 $type = "retraction";
569 if ($type == "request")
572 $fields = new SimpleXMLElement("<".$type."/>");
576 foreach ($element->children() AS $fieldname => $entry) {
578 // Translation for the old XML structure
579 if ($fieldname == "diaspora_handle") {
580 $fieldname = "author";
582 if ($fieldname == "participant_handles") {
583 $fieldname = "participants";
585 if (in_array($type, array("like", "participation"))) {
586 if ($fieldname == "target_type") {
587 $fieldname = "parent_type";
590 if ($fieldname == "sender_handle") {
591 $fieldname = "author";
593 if ($fieldname == "recipient_handle") {
594 $fieldname = "recipient";
596 if ($fieldname == "root_diaspora_id") {
597 $fieldname = "root_author";
599 if ($type == "status_message") {
600 if ($fieldname == "raw_message") {
604 if ($type == "retraction") {
605 if ($fieldname == "post_guid") {
606 $fieldname = "target_guid";
608 if ($fieldname == "type") {
609 $fieldname = "target_type";
614 if (($fieldname == "author_signature") AND ($entry != ""))
615 $author_signature = base64_decode($entry);
616 elseif (($fieldname == "parent_author_signature") AND ($entry != ""))
617 $parent_author_signature = base64_decode($entry);
618 elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
619 if ($signed_data != "") {
621 $signed_data_parent .= ";";
624 $signed_data .= $entry;
626 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
627 ($orig_type == "relayable_retraction"))
628 xml::copy($entry, $fields, $fieldname);
631 // This is something that shouldn't happen at all.
632 if (in_array($type, array("status_message", "reshare", "profile")))
633 if ($msg["author"] != $fields->author) {
634 logger("Message handle is not the same as envelope sender. Quitting this message.");
638 // Only some message types have signatures. So we quit here for the other types.
639 if (!in_array($type, array("comment", "message", "like"))) {
640 return array("fields" => $fields, "relayed" => false);
642 // No author_signature? This is a must, so we quit.
643 if (!isset($author_signature)) {
644 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
648 if (isset($parent_author_signature)) {
651 $key = self::key($msg["author"]);
653 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
654 logger("No valid parent author signature for parent author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$parent_author_signature, LOGGER_DEBUG);
661 $key = self::key($fields->author);
663 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
664 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
667 return array("fields" => $fields, "relayed" => $relayed);
672 * @brief Fetches the public key for a given handle
674 * @param string $handle The handle
676 * @return string The public key
678 private static function key($handle) {
679 $handle = strval($handle);
681 logger("Fetching diaspora key for: ".$handle);
683 $r = self::person_by_handle($handle);
691 * @brief Fetches data for a given handle
693 * @param string $handle The handle
695 * @return array the queried data
697 private static function person_by_handle($handle) {
699 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
700 dbesc(NETWORK_DIASPORA),
705 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
707 // update record occasionally so it doesn't get stale
708 $d = strtotime($person["updated"]." +00:00");
709 if ($d < strtotime("now - 14 days"))
712 if ($person["guid"] == "")
716 if (!$person OR $update) {
717 logger("create or refresh", LOGGER_DEBUG);
718 $r = probe_url($handle, PROBE_DIASPORA);
720 // Note that Friendica contacts will return a "Diaspora person"
721 // if Diaspora connectivity is enabled on their server
722 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
723 self::add_fcontact($r, $update);
731 * @brief Updates the fcontact table
733 * @param array $arr The fcontact data
734 * @param bool $update Update or insert?
736 * @return string The id of the fcontact entry
738 private static function add_fcontact($arr, $update = false) {
741 $r = q("UPDATE `fcontact` SET
755 WHERE `url` = '%s' AND `network` = '%s'",
757 dbesc($arr["photo"]),
758 dbesc($arr["request"]),
760 dbesc(strtolower($arr["addr"])),
762 dbesc($arr["batch"]),
763 dbesc($arr["notify"]),
765 dbesc($arr["confirm"]),
766 dbesc($arr["alias"]),
767 dbesc($arr["pubkey"]),
768 dbesc(datetime_convert()),
770 dbesc($arr["network"])
773 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
774 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
775 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
778 dbesc($arr["photo"]),
779 dbesc($arr["request"]),
783 dbesc($arr["batch"]),
784 dbesc($arr["notify"]),
786 dbesc($arr["confirm"]),
787 dbesc($arr["network"]),
788 dbesc($arr["alias"]),
789 dbesc($arr["pubkey"]),
790 dbesc(datetime_convert())
798 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
800 * @param int $contact_id The id in the contact table
801 * @param int $gcontact_id The id in the gcontact table
803 * @return string the handle
805 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
808 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
810 if ($gcontact_id != 0) {
811 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
812 intval($gcontact_id));
814 if (dbm::is_result($r)) {
815 return strtolower($r[0]["addr"]);
819 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
820 intval($contact_id));
822 if (dbm::is_result($r)) {
825 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
827 if ($contact['addr'] != "") {
828 $handle = $contact['addr'];
830 $baseurl_start = strpos($contact['url'],'://') + 3;
831 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
832 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
833 $handle = $contact['nick'].'@'.$baseurl;
837 return strtolower($handle);
841 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
844 * @param mixed $fcontact_guid Hexadecimal string guid
846 * @return string the contact url or null
848 public static function url_from_contact_guid($fcontact_guid) {
849 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
851 $r = q("SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
852 dbesc(NETWORK_DIASPORA),
853 dbesc($fcontact_guid)
856 if (dbm::is_result($r)) {
864 * @brief Get a contact id for a given handle
866 * @param int $uid The user id
867 * @param string $handle The handle in the format user@domain.tld
869 * @return The contact id
871 private static function contact_by_handle($uid, $handle) {
873 // First do a direct search on the contact table
874 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
879 if (dbm::is_result($r)) {
882 // We haven't found it?
883 // We use another function for it that will possibly create a contact entry
884 $cid = get_contact($handle, $uid);
887 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
889 if (dbm::is_result($r)) {
895 $handle_parts = explode("@", $handle);
896 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
897 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
902 if (dbm::is_result($r)) {
906 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
911 * @brief Check if posting is allowed for this contact
913 * @param array $importer Array of the importer user
914 * @param array $contact The contact that is checked
915 * @param bool $is_comment Is the check for a comment?
917 * @return bool is the contact allowed to post?
919 private static function post_allow($importer, $contact, $is_comment = false) {
921 // perhaps we were already sharing with this person. Now they're sharing with us.
922 // That makes us friends.
923 // Normally this should have handled by getting a request - but this could get lost
924 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
925 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
926 intval(CONTACT_IS_FRIEND),
927 intval($contact["id"]),
928 intval($importer["uid"])
930 $contact["rel"] = CONTACT_IS_FRIEND;
931 logger("defining user ".$contact["nick"]." as friend");
934 // We don't seem to like that person
935 if ($contact["blocked"] || $contact["readonly"] || $contact["archive"]) {
937 // We are following this person? Then it is okay
938 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
940 // Is it a post to a community? That's good
941 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
944 // Messages for the global users and comments are always accepted
945 if (($importer["uid"] == 0) || $is_comment) {
953 * @brief Fetches the contact id for a handle and checks if posting is allowed
955 * @param array $importer Array of the importer user
956 * @param string $handle The checked handle in the format user@domain.tld
957 * @param bool $is_comment Is the check for a comment?
959 * @return array The contact data
961 private static function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
962 $contact = self::contact_by_handle($importer["uid"], $handle);
964 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
965 // If a contact isn't found, we accept it anyway if it is a comment
973 if (!self::post_allow($importer, $contact, $is_comment)) {
974 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
981 * @brief Does the message already exists on the system?
983 * @param int $uid The user id
984 * @param string $guid The guid of the message
986 * @return int|bool message id if the message already was stored into the system - or false.
988 private static function message_exists($uid, $guid) {
989 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
994 if (dbm::is_result($r)) {
995 logger("message ".$guid." already exists for user ".$uid);
1003 * @brief Checks for links to posts in a message
1005 * @param array $item The item array
1007 private static function fetch_guid($item) {
1008 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1009 function ($match) use ($item){
1010 return(self::fetch_guid_sub($match, $item));
1015 * @brief Checks for relative /people/* links in an item body to match local
1016 * contacts or prepends the remote host taken from the author link.
1018 * @param string $body The item body to replace links from
1019 * @param string $author_link The author link for missing local contact fallback
1021 * @return the replaced string
1023 public function replace_people_guid($body, $author_link) {
1024 $return = preg_replace_callback("&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1025 function ($match) use ($author_link) {
1027 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1028 // 1 => '0123456789abcdef'
1030 $handle = self::url_from_contact_guid($match[1]);
1033 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1035 // No local match, restoring absolute remote URL from author scheme and host
1036 $author_url = parse_url($author_link);
1037 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1047 * @brief sub function of "fetch_guid" which checks for links in messages
1049 * @param array $match array containing a link that has to be checked for a message link
1050 * @param array $item The item array
1052 private static function fetch_guid_sub($match, $item) {
1053 if (!self::store_by_guid($match[1], $item["author-link"]))
1054 self::store_by_guid($match[1], $item["owner-link"]);
1058 * @brief Fetches an item with a given guid from a given server
1060 * @param string $guid the message guid
1061 * @param string $server The server address
1062 * @param int $uid The user id of the user
1064 * @return int the message id of the stored message or false
1066 private static function store_by_guid($guid, $server, $uid = 0) {
1067 $serverparts = parse_url($server);
1068 $server = $serverparts["scheme"]."://".$serverparts["host"];
1070 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1072 $msg = self::message($guid, $server);
1077 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1079 // Now call the dispatcher
1080 return self::dispatch_public($msg);
1084 * @brief Fetches a message from a server
1086 * @param string $guid message guid
1087 * @param string $server The url of the server
1088 * @param int $level Endless loop prevention
1091 * 'message' => The message XML
1092 * 'author' => The author handle
1093 * 'key' => The public key of the author
1095 private static function message($guid, $server, $level = 0) {
1100 // This will work for new Diaspora servers and Friendica servers from 3.5
1101 $source_url = $server."/fetch/post/".$guid;
1102 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1104 $envelope = fetch_url($source_url);
1106 logger("Envelope was fetched.", LOGGER_DEBUG);
1107 $x = self::verify_magic_envelope($envelope);
1109 logger("Envelope could not be verified.", LOGGER_DEBUG);
1111 logger("Envelope was verified.", LOGGER_DEBUG);
1115 // This will work for older Diaspora and Friendica servers
1117 $source_url = $server."/p/".$guid.".xml";
1118 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1120 $x = fetch_url($source_url);
1125 $source_xml = parse_xml_string($x, false);
1127 if (!is_object($source_xml))
1130 if ($source_xml->post->reshare) {
1131 // Reshare of a reshare - old Diaspora version
1132 logger("Message is a reshare", LOGGER_DEBUG);
1133 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1134 } elseif ($source_xml->getName() == "reshare") {
1135 // Reshare of a reshare - new Diaspora version
1136 logger("Message is a new reshare", LOGGER_DEBUG);
1137 return self::message($source_xml->root_guid, $server, ++$level);
1142 // Fetch the author - for the old and the new Diaspora version
1143 if ($source_xml->post->status_message->diaspora_handle)
1144 $author = (string)$source_xml->post->status_message->diaspora_handle;
1145 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
1146 $author = (string)$source_xml->author;
1148 // If this isn't a "status_message" then quit
1150 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1154 $msg = array("message" => $x, "author" => $author);
1156 $msg["key"] = self::key($msg["author"]);
1162 * @brief Fetches the item record of a given guid
1164 * @param int $uid The user id
1165 * @param string $guid message guid
1166 * @param string $author The handle of the item
1167 * @param array $contact The contact of the item owner
1169 * @return array the item record
1171 private static function parent_item($uid, $guid, $author, $contact) {
1172 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1173 `author-name`, `author-link`, `author-avatar`,
1174 `owner-name`, `owner-link`, `owner-avatar`
1175 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1176 intval($uid), dbesc($guid));
1179 $result = self::store_by_guid($guid, $contact["url"], $uid);
1182 $person = self::person_by_handle($author);
1183 $result = self::store_by_guid($guid, $person["url"], $uid);
1187 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1189 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1190 `author-name`, `author-link`, `author-avatar`,
1191 `owner-name`, `owner-link`, `owner-avatar`
1192 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1193 intval($uid), dbesc($guid));
1198 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1201 logger("parent item found: parent: ".$guid." - user: ".$uid);
1207 * @brief returns contact details
1209 * @param array $contact The default contact if the person isn't found
1210 * @param array $person The record of the person
1211 * @param int $uid The user id
1214 * 'cid' => contact id
1215 * 'network' => network type
1217 private static function author_contact_by_url($contact, $person, $uid) {
1219 $r = q("SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1220 dbesc(normalise_link($person["url"])), intval($uid));
1223 $network = $r[0]["network"];
1225 // We are receiving content from a user that possibly is about to be terminated
1226 // This means the user is vital, so we remove a possible termination date.
1227 unmark_for_death($r[0]);
1229 $cid = $contact["id"];
1230 $network = NETWORK_DIASPORA;
1233 return array("cid" => $cid, "network" => $network);
1237 * @brief Is the profile a hubzilla profile?
1239 * @param string $url The profile link
1241 * @return bool is it a hubzilla server?
1243 public static function is_redmatrix($url) {
1244 return(strstr($url, "/channel/"));
1248 * @brief Generate a post link with a given handle and message guid
1250 * @param string $addr The user handle
1251 * @param string $guid message guid
1253 * @return string the post link
1255 private static function plink($addr, $guid) {
1256 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1260 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1262 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1263 // So we try another way as well.
1264 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1266 $r[0]["network"] = $s[0]["network"];
1268 if ($r[0]["network"] == NETWORK_DFRN)
1269 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
1271 if (self::is_redmatrix($r[0]["url"]))
1272 return $r[0]["url"]."/?f=&mid=".$guid;
1274 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1278 * @brief Processes an account deletion
1280 * @param array $importer Array of the importer user
1281 * @param object $data The message object
1283 * @return bool Success
1285 private static function receive_account_deletion($importer, $data) {
1287 /// @todo Account deletion should remove the contact from the global contacts as well
1289 $author = notags(unxmlify($data->author));
1291 $contact = self::contact_by_handle($importer["uid"], $author);
1293 logger("cannot find contact for author: ".$author);
1297 // We now remove the contact
1298 contact_remove($contact["id"]);
1303 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1305 * @param string $author Author handle
1306 * @param string $guid Message guid
1307 * @param boolean $onlyfound Only return uri when found in the database
1309 * @return string The constructed uri or the one from our database
1311 private static function get_uri_from_guid($author, $guid, $onlyfound = false) {
1313 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1314 if (dbm::is_result($r)) {
1315 return $r[0]["uri"];
1316 } elseif (!$onlyfound) {
1317 return $author.":".$guid;
1324 * @brief Fetch the guid from our database with a given uri
1326 * @param string $author Author handle
1327 * @param string $uri Message uri
1329 * @return string The post guid
1331 private static function get_guid_from_uri($uri, $uid) {
1333 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1334 if (dbm::is_result($r)) {
1335 return $r[0]["guid"];
1342 * @brief Find the best importer for a comment, like, ...
1344 * @param string $guid The guid of the item
1346 * @return array|boolean the origin owner of that post - or false
1348 private static function importer_for_guid($guid) {
1349 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1351 if (dbm::is_result($item)) {
1352 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1353 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1354 if (dbm::is_result($contact)) {
1362 * @brief Processes an incoming comment
1364 * @param array $importer Array of the importer user
1365 * @param string $sender The sender of the message
1366 * @param object $data The message object
1367 * @param string $xml The original XML of the message
1369 * @return int The message id of the generated comment or "false" if there was an error
1371 private static function receive_comment($importer, $sender, $data, $xml) {
1372 $author = notags(unxmlify($data->author));
1373 $guid = notags(unxmlify($data->guid));
1374 $parent_guid = notags(unxmlify($data->parent_guid));
1375 $text = unxmlify($data->text);
1377 if (isset($data->created_at)) {
1378 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1380 $created_at = datetime_convert();
1383 if (isset($data->thread_parent_guid)) {
1384 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1385 $thr_uri = self::get_uri_from_guid("", $thread_parent_guid, true);
1390 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1395 $message_id = self::message_exists($importer["uid"], $guid);
1400 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1401 if (!$parent_item) {
1405 $person = self::person_by_handle($author);
1406 if (!is_array($person)) {
1407 logger("unable to find author details");
1411 // Fetch the contact id - if we know this contact
1412 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1414 $datarray = array();
1416 $datarray["uid"] = $importer["uid"];
1417 $datarray["contact-id"] = $author_contact["cid"];
1418 $datarray["network"] = $author_contact["network"];
1420 $datarray["author-name"] = $person["name"];
1421 $datarray["author-link"] = $person["url"];
1422 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1424 $datarray["owner-name"] = $contact["name"];
1425 $datarray["owner-link"] = $contact["url"];
1426 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1428 $datarray["guid"] = $guid;
1429 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1431 $datarray["type"] = "remote-comment";
1432 $datarray["verb"] = ACTIVITY_POST;
1433 $datarray["gravity"] = GRAVITY_COMMENT;
1435 if ($thr_uri != "") {
1436 $datarray["parent-uri"] = $thr_uri;
1438 $datarray["parent-uri"] = $parent_item["uri"];
1441 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1443 $datarray["protocol"] = PROTOCOL_DIASPORA;
1444 $datarray["source"] = $xml;
1446 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1448 $body = diaspora2bb($text);
1450 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1452 self::fetch_guid($datarray);
1454 $message_id = item_store($datarray);
1457 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1460 // If we are the origin of the parent we store the original data and notify our followers
1461 if ($message_id AND $parent_item["origin"]) {
1463 // Formerly we stored the signed text, the signature and the author in different fields.
1464 // We now store the raw data so that we are more flexible.
1465 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1466 intval($message_id),
1467 dbesc(json_encode($data))
1471 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1478 * @brief processes and stores private messages
1480 * @param array $importer Array of the importer user
1481 * @param array $contact The contact of the message
1482 * @param object $data The message object
1483 * @param array $msg Array of the processed message, author handle and key
1484 * @param object $mesg The private message
1485 * @param array $conversation The conversation record to which this message belongs
1487 * @return bool "true" if it was successful
1489 private static function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1490 $author = notags(unxmlify($data->author));
1491 $guid = notags(unxmlify($data->guid));
1492 $subject = notags(unxmlify($data->subject));
1494 // "diaspora_handle" is the element name from the old version
1495 // "author" is the element name from the new version
1496 if ($mesg->author) {
1497 $msg_author = notags(unxmlify($mesg->author));
1498 } elseif ($mesg->diaspora_handle) {
1499 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1504 $msg_guid = notags(unxmlify($mesg->guid));
1505 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1506 $msg_text = unxmlify($mesg->text);
1507 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1509 /// @todo these fields doesn't seem to be supported by the new protocol
1510 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1511 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1512 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1514 if ($msg_conversation_guid != $guid) {
1515 logger("message conversation guid does not belong to the current conversation.");
1519 $body = diaspora2bb($msg_text);
1520 $message_uri = $msg_author.":".$msg_guid;
1522 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1524 $author_signature = base64_decode($msg_author_signature);
1526 if (strcasecmp($msg_author,$msg["author"]) == 0) {
1530 $person = self::person_by_handle($msg_author);
1532 if (is_array($person) && x($person, "pubkey")) {
1533 $key = $person["pubkey"];
1535 logger("unable to find author details");
1540 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1541 logger("verification failed.");
1545 if ($msg_parent_author_signature) {
1546 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1548 $parent_author_signature = base64_decode($msg_parent_author_signature);
1552 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1553 logger("owner verification failed.");
1558 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1561 if (dbm::is_result($r)) {
1562 logger("duplicate message already delivered.", LOGGER_DEBUG);
1566 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1567 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1568 intval($importer["uid"]),
1570 intval($conversation["id"]),
1571 dbesc($person["name"]),
1572 dbesc($person["photo"]),
1573 dbesc($person["url"]),
1574 intval($contact["id"]),
1579 dbesc($message_uri),
1580 dbesc($author.":".$guid),
1581 dbesc($msg_created_at)
1584 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1585 dbesc(datetime_convert()),
1586 intval($conversation["id"])
1590 "type" => NOTIFY_MAIL,
1591 "notify_flags" => $importer["notify-flags"],
1592 "language" => $importer["language"],
1593 "to_name" => $importer["username"],
1594 "to_email" => $importer["email"],
1595 "uid" =>$importer["uid"],
1596 "item" => array("subject" => $subject, "body" => $body),
1597 "source_name" => $person["name"],
1598 "source_link" => $person["url"],
1599 "source_photo" => $person["thumb"],
1600 "verb" => ACTIVITY_POST,
1607 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1609 * @param array $importer Array of the importer user
1610 * @param array $msg Array of the processed message, author handle and key
1611 * @param object $data The message object
1613 * @return bool Success
1615 private static function receive_conversation($importer, $msg, $data) {
1616 $author = notags(unxmlify($data->author));
1617 $guid = notags(unxmlify($data->guid));
1618 $subject = notags(unxmlify($data->subject));
1619 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1620 $participants = notags(unxmlify($data->participants));
1622 $messages = $data->message;
1624 if (!count($messages)) {
1625 logger("empty conversation");
1629 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1633 $conversation = null;
1635 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1636 intval($importer["uid"]),
1640 $conversation = $c[0];
1642 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1643 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1644 intval($importer["uid"]),
1648 dbesc(datetime_convert()),
1650 dbesc($participants)
1653 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1654 intval($importer["uid"]),
1659 $conversation = $c[0];
1661 if (!$conversation) {
1662 logger("unable to create conversation.");
1666 foreach ($messages as $mesg)
1667 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1673 * @brief Creates the body for a "like" message
1675 * @param array $contact The contact that send us the "like"
1676 * @param array $parent_item The item array of the parent item
1677 * @param string $guid message guid
1679 * @return string the body
1681 private static function construct_like_body($contact, $parent_item, $guid) {
1682 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1684 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1685 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1686 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1688 return sprintf($bodyverb, $ulink, $alink, $plink);
1692 * @brief Creates a XML object for a "like"
1694 * @param array $importer Array of the importer user
1695 * @param array $parent_item The item array of the parent item
1697 * @return string The XML
1699 private static function construct_like_object($importer, $parent_item) {
1700 $objtype = ACTIVITY_OBJ_NOTE;
1701 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1702 $parent_body = $parent_item["body"];
1704 $xmldata = array("object" => array("type" => $objtype,
1706 "id" => $parent_item["uri"],
1709 "content" => $parent_body));
1711 return xml::from_array($xmldata, $xml, true);
1715 * @brief Processes "like" messages
1717 * @param array $importer Array of the importer user
1718 * @param string $sender The sender of the message
1719 * @param object $data The message object
1721 * @return int The message id of the generated like or "false" if there was an error
1723 private static function receive_like($importer, $sender, $data) {
1724 $author = notags(unxmlify($data->author));
1725 $guid = notags(unxmlify($data->guid));
1726 $parent_guid = notags(unxmlify($data->parent_guid));
1727 $parent_type = notags(unxmlify($data->parent_type));
1728 $positive = notags(unxmlify($data->positive));
1730 // likes on comments aren't supported by Diaspora - only on posts
1731 // But maybe this will be supported in the future, so we will accept it.
1732 if (!in_array($parent_type, array("Post", "Comment")))
1735 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1739 $message_id = self::message_exists($importer["uid"], $guid);
1743 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1747 $person = self::person_by_handle($author);
1748 if (!is_array($person)) {
1749 logger("unable to find author details");
1753 // Fetch the contact id - if we know this contact
1754 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1756 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1757 // We would accept this anyhow.
1758 if ($positive == "true")
1759 $verb = ACTIVITY_LIKE;
1761 $verb = ACTIVITY_DISLIKE;
1763 $datarray = array();
1765 $datarray["protocol"] = PROTOCOL_DIASPORA;
1767 $datarray["uid"] = $importer["uid"];
1768 $datarray["contact-id"] = $author_contact["cid"];
1769 $datarray["network"] = $author_contact["network"];
1771 $datarray["author-name"] = $person["name"];
1772 $datarray["author-link"] = $person["url"];
1773 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1775 $datarray["owner-name"] = $contact["name"];
1776 $datarray["owner-link"] = $contact["url"];
1777 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1779 $datarray["guid"] = $guid;
1780 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1782 $datarray["type"] = "activity";
1783 $datarray["verb"] = $verb;
1784 $datarray["gravity"] = GRAVITY_LIKE;
1785 $datarray["parent-uri"] = $parent_item["uri"];
1787 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1788 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1790 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1792 $message_id = item_store($datarray);
1795 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1797 // If we are the origin of the parent we store the original data and notify our followers
1798 if ($message_id AND $parent_item["origin"]) {
1800 // Formerly we stored the signed text, the signature and the author in different fields.
1801 // We now store the raw data so that we are more flexible.
1802 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1803 intval($message_id),
1804 dbesc(json_encode($data))
1808 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1815 * @brief Processes private messages
1817 * @param array $importer Array of the importer user
1818 * @param object $data The message object
1820 * @return bool Success?
1822 private static function receive_message($importer, $data) {
1823 $author = notags(unxmlify($data->author));
1824 $guid = notags(unxmlify($data->guid));
1825 $conversation_guid = notags(unxmlify($data->conversation_guid));
1826 $text = unxmlify($data->text);
1827 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1829 /// @todo "parent_guid" doesn't seem to be part of the new protocol
1830 $parent_guid = notags(unxmlify($data->parent_guid));
1832 $contact = self::allowed_contact_by_handle($importer, $author, true);
1837 $conversation = null;
1839 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1840 intval($importer["uid"]),
1841 dbesc($conversation_guid)
1844 $conversation = $c[0];
1846 logger("conversation not available.");
1850 $message_uri = $author.":".$guid;
1852 $person = self::person_by_handle($author);
1854 logger("unable to find author details");
1858 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1859 dbesc($message_uri),
1860 intval($importer["uid"])
1862 if (dbm::is_result($r)) {
1863 logger("duplicate message already delivered.", LOGGER_DEBUG);
1867 $body = diaspora2bb($text);
1869 $body = self::replace_people_guid($body, $person["url"]);
1871 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1872 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1873 intval($importer["uid"]),
1875 intval($conversation["id"]),
1876 dbesc($person["name"]),
1877 dbesc($person["photo"]),
1878 dbesc($person["url"]),
1879 intval($contact["id"]),
1880 dbesc($conversation["subject"]),
1884 dbesc($message_uri),
1885 dbesc($author.":".$parent_guid),
1889 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1890 dbesc(datetime_convert()),
1891 intval($conversation["id"])
1898 * @brief Processes participations - unsupported by now
1900 * @param array $importer Array of the importer user
1901 * @param object $data The message object
1903 * @return bool always true
1905 private static function receive_participation($importer, $data) {
1906 // I'm not sure if we can fully support this message type
1911 * @brief Processes photos - unneeded
1913 * @param array $importer Array of the importer user
1914 * @param object $data The message object
1916 * @return bool always true
1918 private static function receive_photo($importer, $data) {
1919 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1924 * @brief Processes poll participations - unssupported
1926 * @param array $importer Array of the importer user
1927 * @param object $data The message object
1929 * @return bool always true
1931 private static function receive_poll_participation($importer, $data) {
1932 // We don't support polls by now
1937 * @brief Processes incoming profile updates
1939 * @param array $importer Array of the importer user
1940 * @param object $data The message object
1942 * @return bool Success
1944 private static function receive_profile($importer, $data) {
1945 $author = strtolower(notags(unxmlify($data->author)));
1947 $contact = self::contact_by_handle($importer["uid"], $author);
1951 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1952 $image_url = unxmlify($data->image_url);
1953 $birthday = unxmlify($data->birthday);
1954 $gender = unxmlify($data->gender);
1955 $about = diaspora2bb(unxmlify($data->bio));
1956 $location = diaspora2bb(unxmlify($data->location));
1957 $searchable = (unxmlify($data->searchable) == "true");
1958 $nsfw = (unxmlify($data->nsfw) == "true");
1959 $tags = unxmlify($data->tag_string);
1961 $tags = explode("#", $tags);
1963 $keywords = array();
1964 foreach ($tags as $tag) {
1965 $tag = trim(strtolower($tag));
1970 $keywords = implode(", ", $keywords);
1972 $handle_parts = explode("@", $author);
1973 $nick = $handle_parts[0];
1976 $name = $handle_parts[0];
1978 if ( preg_match("|^https?://|", $image_url) === 0)
1979 $image_url = "http://".$handle_parts[1].$image_url;
1981 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1983 // Generic birthday. We don't know the timezone. The year is irrelevant.
1985 $birthday = str_replace("1000", "1901", $birthday);
1987 if ($birthday != "")
1988 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1990 // this is to prevent multiple birthday notifications in a single year
1991 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1993 if (substr($birthday,5) === substr($contact["bd"],5))
1994 $birthday = $contact["bd"];
1996 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1997 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2001 dbesc(datetime_convert()),
2007 intval($contact["id"]),
2008 intval($importer["uid"])
2011 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2012 "photo" => $image_url, "name" => $name, "location" => $location,
2013 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2014 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2015 "hide" => !$searchable, "nsfw" => $nsfw);
2017 $gcid = update_gcontact($gcontact);
2019 link_gcontact($gcid, $importer["uid"], $contact["id"]);
2021 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2027 * @brief Processes incoming friend requests
2029 * @param array $importer Array of the importer user
2030 * @param array $contact The contact that send the request
2032 private static function receive_request_make_friend($importer, $contact) {
2036 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
2037 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
2038 intval(CONTACT_IS_FRIEND),
2039 intval($contact["id"]),
2040 intval($importer["uid"])
2043 // send notification
2045 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2046 intval($importer["uid"])
2049 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
2051 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2052 intval($importer["uid"])
2055 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2057 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2060 $arr["protocol"] = PROTOCOL_DIASPORA;
2061 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2062 $arr["uid"] = $importer["uid"];
2063 $arr["contact-id"] = $self[0]["id"];
2065 $arr["type"] = 'wall';
2066 $arr["gravity"] = 0;
2068 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2069 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2070 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2071 $arr["verb"] = ACTIVITY_FRIEND;
2072 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2074 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2075 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2076 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2077 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
2079 $arr["object"] = self::construct_new_friend_object($contact);
2081 $arr["last-child"] = 1;
2083 $arr["allow_cid"] = $user[0]["allow_cid"];
2084 $arr["allow_gid"] = $user[0]["allow_gid"];
2085 $arr["deny_cid"] = $user[0]["deny_cid"];
2086 $arr["deny_gid"] = $user[0]["deny_gid"];
2088 $i = item_store($arr);
2090 proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
2096 * @brief Creates a XML object for a "new friend" message
2098 * @param array $contact Array of the contact
2100 * @return string The XML
2102 private static function construct_new_friend_object($contact) {
2103 $objtype = ACTIVITY_OBJ_PERSON;
2104 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2105 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2107 $xmldata = array("object" => array("type" => $objtype,
2108 "title" => $contact["name"],
2109 "id" => $contact["url"]."/".$contact["name"],
2112 return xml::from_array($xmldata, $xml, true);
2116 * @brief Processes incoming sharing notification
2118 * @param array $importer Array of the importer user
2119 * @param object $data The message object
2121 * @return bool Success
2123 private static function receive_contact_request($importer, $data) {
2124 $author = unxmlify($data->author);
2125 $recipient = unxmlify($data->recipient);
2127 if (!$author || !$recipient) {
2131 // the current protocol version doesn't know these fields
2132 // That means that we will assume their existance
2133 if (isset($data->following)) {
2134 $following = (unxmlify($data->following) == "true");
2139 if (isset($data->sharing)) {
2140 $sharing = (unxmlify($data->sharing) == "true");
2145 $contact = self::contact_by_handle($importer["uid"],$author);
2147 // perhaps we were already sharing with this person. Now they're sharing with us.
2148 // That makes us friends.
2150 if ($following AND $sharing) {
2151 logger("Author ".$author." (Contact ".$contact["id"].") wants to have a bidirectional conection.", LOGGER_DEBUG);
2152 self::receive_request_make_friend($importer, $contact);
2154 // refetch the contact array
2155 $contact = self::contact_by_handle($importer["uid"],$author);
2157 // If we are now friends, we are sending a share message.
2158 // Normally we needn't to do so, but the first message could have been vanished.
2159 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND, CONTACT_IS_FOLLOWER))) {
2160 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2162 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2163 $ret = self::send_share($u[0], $contact);
2167 } else { /// @todo Handle all possible variations of adding and retracting of permissions
2168 logger("Author ".$author." (Contact ".$contact["id"].") wants to change the relationship: Following: ".$following." - sharing: ".$sharing. "(By now unsupported)", LOGGER_DEBUG);
2173 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2174 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2176 } elseif (!$following AND !$sharing) {
2177 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2179 } elseif (!$following AND $sharing) {
2180 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2181 } elseif ($following AND $sharing) {
2182 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2183 } elseif ($following AND !$sharing) {
2184 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2187 $ret = self::person_by_handle($author);
2189 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2190 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2194 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2196 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2197 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2198 intval($importer["uid"]),
2199 dbesc($ret["network"]),
2200 dbesc($ret["addr"]),
2203 dbesc(normalise_link($ret["url"])),
2205 dbesc($ret["name"]),
2206 dbesc($ret["nick"]),
2207 dbesc($ret["photo"]),
2208 dbesc($ret["pubkey"]),
2209 dbesc($ret["notify"]),
2210 dbesc($ret["poll"]),
2215 // find the contact record we just created
2217 $contact_record = self::contact_by_handle($importer["uid"],$author);
2219 if (!$contact_record) {
2220 logger("unable to locate newly created contact record.");
2224 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2226 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2228 if (intval($def_gid))
2229 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2231 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2233 if ($importer["page-flags"] == PAGE_NORMAL) {
2235 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2237 $hash = random_string().(string)time(); // Generate a confirm_key
2239 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2240 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2241 intval($importer["uid"]),
2242 intval($contact_record["id"]),
2245 dbesc(t("Sharing notification from Diaspora network")),
2247 dbesc(datetime_convert())
2251 // automatic friend approval
2253 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2255 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2257 // technically they are sharing with us (CONTACT_IS_SHARING),
2258 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2259 // we are going to change the relationship and make them a follower.
2261 if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
2262 $new_relation = CONTACT_IS_FRIEND;
2263 elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
2264 $new_relation = CONTACT_IS_SHARING;
2266 $new_relation = CONTACT_IS_FOLLOWER;
2268 $r = q("UPDATE `contact` SET `rel` = %d,
2276 intval($new_relation),
2277 dbesc(datetime_convert()),
2278 dbesc(datetime_convert()),
2279 intval($contact_record["id"])
2282 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2284 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2285 $ret = self::send_share($u[0], $contact_record);
2287 // Send the profile data, maybe it weren't transmitted before
2288 self::send_profile($importer["uid"], array($contact_record));
2296 * @brief Fetches a message with a given guid
2298 * @param string $guid message guid
2299 * @param string $orig_author handle of the original post
2300 * @param string $author handle of the sharer
2302 * @return array The fetched item
2304 private static function original_item($guid, $orig_author, $author) {
2306 // Do we already have this item?
2307 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2308 `author-name`, `author-link`, `author-avatar`
2309 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2312 if (dbm::is_result($r)) {
2313 logger("reshared message ".$guid." already exists on system.");
2315 // Maybe it is already a reshared item?
2316 // Then refetch the content, if it is a reshare from a reshare.
2317 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2318 if (self::is_reshare($r[0]["body"], true)) {
2320 } elseif (self::is_reshare($r[0]["body"], false)) {
2321 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2323 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2325 // Add OEmbed and other information to the body
2326 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2334 if (!dbm::is_result($r)) {
2335 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2336 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2337 $item_id = self::store_by_guid($guid, $server);
2340 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2341 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2342 $item_id = self::store_by_guid($guid, $server);
2346 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2347 `author-name`, `author-link`, `author-avatar`
2348 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2351 if (dbm::is_result($r)) {
2352 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2353 if (self::is_reshare($r[0]["body"], false)) {
2354 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2355 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2367 * @brief Processes a reshare message
2369 * @param array $importer Array of the importer user
2370 * @param object $data The message object
2371 * @param string $xml The original XML of the message
2373 * @return int the message id
2375 private static function receive_reshare($importer, $data, $xml) {
2376 $author = notags(unxmlify($data->author));
2377 $guid = notags(unxmlify($data->guid));
2378 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2379 $root_author = notags(unxmlify($data->root_author));
2380 $root_guid = notags(unxmlify($data->root_guid));
2381 /// @todo handle unprocessed property "provider_display_name"
2382 $public = notags(unxmlify($data->public));
2384 $contact = self::allowed_contact_by_handle($importer, $author, false);
2389 $message_id = self::message_exists($importer["uid"], $guid);
2394 $original_item = self::original_item($root_guid, $root_author, $author);
2395 if (!$original_item) {
2399 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
2401 $datarray = array();
2403 $datarray["uid"] = $importer["uid"];
2404 $datarray["contact-id"] = $contact["id"];
2405 $datarray["network"] = NETWORK_DIASPORA;
2407 $datarray["author-name"] = $contact["name"];
2408 $datarray["author-link"] = $contact["url"];
2409 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2411 $datarray["owner-name"] = $datarray["author-name"];
2412 $datarray["owner-link"] = $datarray["author-link"];
2413 $datarray["owner-avatar"] = $datarray["author-avatar"];
2415 $datarray["guid"] = $guid;
2416 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2418 $datarray["verb"] = ACTIVITY_POST;
2419 $datarray["gravity"] = GRAVITY_PARENT;
2421 $datarray["protocol"] = PROTOCOL_DIASPORA;
2422 $datarray["source"] = $xml;
2424 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2425 $original_item["guid"], $original_item["created"], $orig_url);
2426 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2428 $datarray["tag"] = $original_item["tag"];
2429 $datarray["app"] = $original_item["app"];
2431 $datarray["plink"] = self::plink($author, $guid);
2432 $datarray["private"] = (($public == "false") ? 1 : 0);
2433 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2435 $datarray["object-type"] = $original_item["object-type"];
2437 self::fetch_guid($datarray);
2438 $message_id = item_store($datarray);
2441 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2448 * @brief Processes retractions
2450 * @param array $importer Array of the importer user
2451 * @param array $contact The contact of the item owner
2452 * @param object $data The message object
2454 * @return bool success
2456 private static function item_retraction($importer, $contact, $data) {
2457 $author = notags(unxmlify($data->author));
2458 $target_guid = notags(unxmlify($data->target_guid));
2459 $target_type = notags(unxmlify($data->target_type));
2461 $person = self::person_by_handle($author);
2462 if (!is_array($person)) {
2463 logger("unable to find author detail for ".$author);
2467 if (!isset($contact["url"])) {
2468 $contact["url"] = $person["url"];
2471 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2472 dbesc($target_guid),
2473 intval($importer["uid"])
2476 logger("Target guid ".$target_guid." was not found for user ".$importer["uid"]);
2480 // Check if the sender is the thread owner
2481 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2482 intval($r[0]["parent"]));
2484 // Only delete it if the parent author really fits
2485 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2486 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2490 // Currently we don't have a central deletion function that we could use in this case. The function "item_drop" doesn't work for that case
2491 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2492 dbesc(datetime_convert()),
2493 dbesc(datetime_convert()),
2496 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2498 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2500 // Now check if the retraction needs to be relayed by us
2501 if ($p[0]["origin"]) {
2503 proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $r[0]["id"]);
2510 * @brief Receives retraction messages
2512 * @param array $importer Array of the importer user
2513 * @param string $sender The sender of the message
2514 * @param object $data The message object
2516 * @return bool Success
2518 private static function receive_retraction($importer, $sender, $data) {
2519 $target_type = notags(unxmlify($data->target_type));
2521 $contact = self::contact_by_handle($importer["uid"], $sender);
2522 if (!$contact AND (in_array($target_type, array("Contact", "Person")))) {
2523 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2527 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2529 switch ($target_type) {
2532 case "Post": // "Post" will be supported in a future version
2534 case "StatusMessage":
2535 return self::item_retraction($importer, $contact, $data);
2539 /// @todo What should we do with an "unshare"?
2540 // Removing the contact isn't correct since we still can read the public items
2541 contact_remove($contact["id"]);
2545 logger("Unknown target type ".$target_type);
2552 * @brief Receives status messages
2554 * @param array $importer Array of the importer user
2555 * @param object $data The message object
2556 * @param string $xml The original XML of the message
2558 * @return int The message id of the newly created item
2560 private static function receive_status_message($importer, $data, $xml) {
2561 $author = notags(unxmlify($data->author));
2562 $guid = notags(unxmlify($data->guid));
2563 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2564 $public = notags(unxmlify($data->public));
2565 $text = unxmlify($data->text);
2566 $provider_display_name = notags(unxmlify($data->provider_display_name));
2568 $contact = self::allowed_contact_by_handle($importer, $author, false);
2573 $message_id = self::message_exists($importer["uid"], $guid);
2579 if ($data->location) {
2580 foreach ($data->location->children() AS $fieldname => $data) {
2581 $address[$fieldname] = notags(unxmlify($data));
2585 $body = diaspora2bb($text);
2587 $datarray = array();
2589 // Attach embedded pictures to the body
2591 foreach ($data->photo AS $photo) {
2592 $body = "[img]".unxmlify($photo->remote_photo_path).
2593 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2596 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2598 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2600 // Add OEmbed and other information to the body
2601 if (!self::is_redmatrix($contact["url"])) {
2602 $body = add_page_info_to_body($body, false, true);
2606 /// @todo enable support for polls
2607 //if ($data->poll) {
2608 // foreach ($data->poll AS $poll)
2613 /// @todo enable support for events
2615 $datarray["uid"] = $importer["uid"];
2616 $datarray["contact-id"] = $contact["id"];
2617 $datarray["network"] = NETWORK_DIASPORA;
2619 $datarray["author-name"] = $contact["name"];
2620 $datarray["author-link"] = $contact["url"];
2621 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2623 $datarray["owner-name"] = $datarray["author-name"];
2624 $datarray["owner-link"] = $datarray["author-link"];
2625 $datarray["owner-avatar"] = $datarray["author-avatar"];
2627 $datarray["guid"] = $guid;
2628 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2630 $datarray["verb"] = ACTIVITY_POST;
2631 $datarray["gravity"] = GRAVITY_PARENT;
2633 $datarray["protocol"] = PROTOCOL_DIASPORA;
2634 $datarray["source"] = $xml;
2636 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2638 if ($provider_display_name != "") {
2639 $datarray["app"] = $provider_display_name;
2642 $datarray["plink"] = self::plink($author, $guid);
2643 $datarray["private"] = (($public == "false") ? 1 : 0);
2644 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2646 if (isset($address["address"])) {
2647 $datarray["location"] = $address["address"];
2650 if (isset($address["lat"]) AND isset($address["lng"])) {
2651 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2654 self::fetch_guid($datarray);
2655 $message_id = item_store($datarray);
2658 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2664 /* ************************************************************************************** *
2665 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2666 * ************************************************************************************** */
2669 * @brief returnes the handle of a contact
2671 * @param array $me contact array
2673 * @return string the handle in the format user@domain.tld
2675 private static function my_handle($contact) {
2676 if ($contact["addr"] != "") {
2677 return $contact["addr"];
2680 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2681 // So - just in case - we build the the address here.
2682 if ($contact["nickname"] != "") {
2683 $nick = $contact["nickname"];
2685 $nick = $contact["nick"];
2688 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2692 * @brief Creates the envelope for the "fetch" endpoint
2694 * @param string $msg The message that is to be transmitted
2695 * @param array $user The record of the sender
2697 * @return string The envelope
2700 public static function build_magic_envelope($msg, $user) {
2702 $b64url_data = base64url_encode($msg);
2703 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2705 $key_id = base64url_encode(self::my_handle($user));
2706 $type = "application/xml";
2707 $encoding = "base64url";
2708 $alg = "RSA-SHA256";
2709 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2710 $signature = rsa_sign($signable_data, $user["prvkey"]);
2711 $sig = base64url_encode($signature);
2713 $xmldata = array("me:env" => array("me:data" => $data,
2714 "@attributes" => array("type" => $type),
2715 "me:encoding" => $encoding,
2718 "@attributes2" => array("key_id" => $key_id)));
2720 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2722 return xml::from_array($xmldata, $xml, false, $namespaces);
2726 * @brief Creates the envelope for a public message
2728 * @param string $msg The message that is to be transmitted
2729 * @param array $user The record of the sender
2730 * @param array $contact Target of the communication
2731 * @param string $prvkey The private key of the sender
2732 * @param string $pubkey The public key of the receiver
2734 * @return string The envelope
2736 private static function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2738 logger("Message: ".$msg, LOGGER_DATA);
2740 $handle = self::my_handle($user);
2742 $b64url_data = base64url_encode($msg);
2744 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2746 $type = "application/xml";
2747 $encoding = "base64url";
2748 $alg = "RSA-SHA256";
2750 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2752 $signature = rsa_sign($signable_data,$prvkey);
2753 $sig = base64url_encode($signature);
2755 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2756 "me:env" => array("me:encoding" => $encoding,
2759 "@attributes" => array("type" => $type),
2760 "me:sig" => $sig)));
2762 $namespaces = array("" => "https://joindiaspora.com/protocol",
2763 "me" => "http://salmon-protocol.org/ns/magic-env");
2765 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2767 logger("magic_env: ".$magic_env, LOGGER_DATA);
2772 * @brief Creates the envelope for a private message
2774 * @param string $msg The message that is to be transmitted
2775 * @param array $user The record of the sender
2776 * @param array $contact Target of the communication
2777 * @param string $prvkey The private key of the sender
2778 * @param string $pubkey The public key of the receiver
2780 * @return string The envelope
2782 private static function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2784 logger("Message: ".$msg, LOGGER_DATA);
2786 // without a public key nothing will work
2789 logger("pubkey missing: contact id: ".$contact["id"]);
2793 $inner_aes_key = openssl_random_pseudo_bytes(32);
2794 $b_inner_aes_key = base64_encode($inner_aes_key);
2795 $inner_iv = openssl_random_pseudo_bytes(16);
2796 $b_inner_iv = base64_encode($inner_iv);
2798 $outer_aes_key = openssl_random_pseudo_bytes(32);
2799 $b_outer_aes_key = base64_encode($outer_aes_key);
2800 $outer_iv = openssl_random_pseudo_bytes(16);
2801 $b_outer_iv = base64_encode($outer_iv);
2803 $handle = self::my_handle($user);
2805 $inner_encrypted = self::aes_encrypt($inner_aes_key, $inner_iv, $msg);
2807 $b64_data = base64_encode($inner_encrypted);
2810 $b64url_data = base64url_encode($b64_data);
2811 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2813 $type = "application/xml";
2814 $encoding = "base64url";
2815 $alg = "RSA-SHA256";
2817 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2819 $signature = rsa_sign($signable_data,$prvkey);
2820 $sig = base64url_encode($signature);
2822 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2823 "aes_key" => $b_inner_aes_key,
2824 "author_id" => $handle));
2826 $decrypted_header = xml::from_array($xmldata, $xml, true);
2828 $ciphertext = self::aes_encrypt($outer_aes_key, $outer_iv, $decrypted_header);
2830 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2832 $encrypted_outer_key_bundle = "";
2833 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2835 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2837 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2839 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2840 "ciphertext" => base64_encode($ciphertext)));
2841 $cipher_json = base64_encode($encrypted_header_json_object);
2843 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2844 "me:env" => array("me:encoding" => $encoding,
2847 "@attributes" => array("type" => $type),
2848 "me:sig" => $sig)));
2850 $namespaces = array("" => "https://joindiaspora.com/protocol",
2851 "me" => "http://salmon-protocol.org/ns/magic-env");
2853 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2855 logger("magic_env: ".$magic_env, LOGGER_DATA);
2860 * @brief Create the envelope for a message
2862 * @param string $msg The message that is to be transmitted
2863 * @param array $user The record of the sender
2864 * @param array $contact Target of the communication
2865 * @param string $prvkey The private key of the sender
2866 * @param string $pubkey The public key of the receiver
2867 * @param bool $public Is the message public?
2869 * @return string The message that will be transmitted to other servers
2871 private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2874 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2876 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2878 // The data that will be transmitted is double encoded via "urlencode", strange ...
2879 $slap = "xml=".urlencode(urlencode($magic_env));
2884 * @brief Creates a signature for a message
2886 * @param array $owner the array of the owner of the message
2887 * @param array $message The message that is to be signed
2889 * @return string The signature
2891 private static function signature($owner, $message) {
2893 unset($sigmsg["author_signature"]);
2894 unset($sigmsg["parent_author_signature"]);
2896 $signed_text = implode(";", $sigmsg);
2898 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2902 * @brief Transmit a message to a target server
2904 * @param array $owner the array of the item owner
2905 * @param array $contact Target of the communication
2906 * @param string $slap The message that is to be transmitted
2907 * @param bool $public_batch Is it a public post?
2908 * @param bool $queue_run Is the transmission called from the queue?
2909 * @param string $guid message guid
2911 * @return int Result of the transmission
2913 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2917 $enabled = intval(get_config("system", "diaspora_enabled"));
2921 $logid = random_string(4);
2922 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2924 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2928 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2930 if (!$queue_run && was_recently_delayed($contact["id"])) {
2933 if (!intval(get_config("system", "diaspora_test"))) {
2934 post_url($dest_url."/", $slap);
2935 $return_code = $a->get_curl_code();
2937 logger("test_mode");
2942 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2944 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2945 logger("queue message");
2947 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2948 intval($contact["id"]),
2949 dbesc(NETWORK_DIASPORA),
2951 intval($public_batch)
2954 logger("add_to_queue ignored - identical item already in queue");
2956 // queue message for redelivery
2957 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2959 // The message could not be delivered. We mark the contact as "dead"
2960 mark_for_death($contact);
2962 } elseif (($return_code >= 200) AND ($return_code <= 299)) {
2963 // We successfully delivered a message, the contact is alive
2964 unmark_for_death($contact);
2967 return(($return_code) ? $return_code : (-1));
2972 * @brief Build the post xml
2974 * @param string $type The message type
2975 * @param array $message The message data
2977 * @return string The post XML
2979 public static function build_post_xml($type, $message) {
2981 $data = array("XML" => array("post" => array($type => $message)));
2982 return xml::from_array($data, $xml);
2986 * @brief Builds and transmit messages
2988 * @param array $owner the array of the item owner
2989 * @param array $contact Target of the communication
2990 * @param string $type The message type
2991 * @param array $message The message data
2992 * @param bool $public_batch Is it a public post?
2993 * @param string $guid message guid
2994 * @param bool $spool Should the transmission be spooled or transmitted?
2996 * @return int Result of the transmission
2998 private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
3000 $msg = self::build_post_xml($type, $message);
3002 logger('message: '.$msg, LOGGER_DATA);
3003 logger('send guid '.$guid, LOGGER_DEBUG);
3005 // Fallback if the private key wasn't transmitted in the expected field
3006 if ($owner['uprvkey'] == "")
3007 $owner['uprvkey'] = $owner['prvkey'];
3009 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3012 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
3015 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
3017 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
3019 return $return_code;
3023 * @brief Sends a "share" message
3025 * @param array $owner the array of the item owner
3026 * @param array $contact Target of the communication
3028 * @return int The result of the transmission
3030 public static function send_share($owner,$contact) {
3032 $message = array("sender_handle" => self::my_handle($owner),
3033 "recipient_handle" => $contact["addr"]);
3035 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3037 return self::build_and_transmit($owner, $contact, "request", $message);
3041 * @brief sends an "unshare"
3043 * @param array $owner the array of the item owner
3044 * @param array $contact Target of the communication
3046 * @return int The result of the transmission
3048 public static function send_unshare($owner,$contact) {
3050 $message = array("post_guid" => $owner["guid"],
3051 "diaspora_handle" => self::my_handle($owner),
3052 "type" => "Person");
3054 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3056 return self::build_and_transmit($owner, $contact, "retraction", $message);
3060 * @brief Checks a message body if it is a reshare
3062 * @param string $body The message body that is to be check
3063 * @param bool $complete Should it be a complete check or a simple check?
3065 * @return array|bool Reshare details or "false" if no reshare
3067 public static function is_reshare($body, $complete = true) {
3068 $body = trim($body);
3070 // Skip if it isn't a pure repeated messages
3071 // Does it start with a share?
3072 if ((strpos($body, "[share") > 0) AND $complete)
3075 // Does it end with a share?
3076 if (strlen($body) > (strrpos($body, "[/share]") + 8))
3079 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3080 // Skip if there is no shared message in there
3081 if ($body == $attributes)
3084 // If we don't do the complete check we quit here
3089 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3090 if ($matches[1] != "")
3091 $guid = $matches[1];
3093 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3094 if ($matches[1] != "")
3095 $guid = $matches[1];
3098 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3099 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
3102 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
3103 $ret["root_guid"] = $guid;
3109 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3110 if ($matches[1] != "")
3111 $profile = $matches[1];
3113 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3114 if ($matches[1] != "")
3115 $profile = $matches[1];
3119 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3120 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
3124 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3125 if ($matches[1] != "")
3126 $link = $matches[1];
3128 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3129 if ($matches[1] != "")
3130 $link = $matches[1];
3132 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3133 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
3140 * @brief Create an event array
3142 * @param integer $event_id The id of the event
3144 * @return array with event data
3146 private static function build_event($event_id) {
3148 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3149 if (!dbm::is_result($r)) {
3155 $eventdata = array();
3157 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3158 if (!dbm::is_result($r)) {
3164 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3165 if (!dbm::is_result($r)) {
3171 $eventdata['author'] = self::my_handle($owner);
3173 if ($event['guid']) {
3174 $eventdata['guid'] = $event['guid'];
3177 $mask = 'Y-m-d\TH:i:s\Z';
3179 /// @todo - establish "all day" events in Friendica
3180 $eventdata["all_day"] = "false";
3182 if (!$event['adjust']) {
3183 $eventdata['timezone'] = $user['timezone'];
3185 if ($eventdata['timezone'] == "") {
3186 $eventdata['timezone'] = 'UTC';
3190 if ($event['start']) {
3191 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3193 if ($event['finish'] AND !$event['nofinish']) {
3194 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3196 if ($event['summary']) {
3197 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3199 if ($event['desc']) {
3200 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3202 if ($event['location']) {
3203 $location = array();
3204 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3205 $location["lat"] = 0;
3206 $location["lng"] = 0;
3207 $eventdata['location'] = $location;
3214 * @brief Create a post (status message or reshare)
3216 * @param array $item The item that will be exported
3217 * @param array $owner the array of the item owner
3220 * 'type' -> Message type ("status_message" or "reshare")
3221 * 'message' -> Array of XML elements of the status
3223 public static function build_status($item, $owner) {
3225 $cachekey = "diaspora:build_status:".$item['guid'];
3227 $result = Cache::get($cachekey);
3228 if (!is_null($result)) {
3232 $myaddr = self::my_handle($owner);
3234 $public = (($item["private"]) ? "false" : "true");
3236 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3238 // Detect a share element and do a reshare
3239 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
3240 $message = array("root_diaspora_id" => $ret["root_handle"],
3241 "root_guid" => $ret["root_guid"],
3242 "guid" => $item["guid"],
3243 "diaspora_handle" => $myaddr,
3244 "public" => $public,
3245 "created_at" => $created,
3246 "provider_display_name" => $item["app"]);
3250 $title = $item["title"];
3251 $body = $item["body"];
3253 // convert to markdown
3254 $body = html_entity_decode(bb2diaspora($body));
3258 $body = "## ".html_entity_decode($title)."\n\n".$body;
3260 if ($item["attach"]) {
3261 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3263 $body .= "\n".t("Attachments:")."\n";
3264 foreach ($matches as $mtch)
3265 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3269 $location = array();
3271 if ($item["location"] != "")
3272 $location["address"] = $item["location"];
3274 if ($item["coord"] != "") {
3275 $coord = explode(" ", $item["coord"]);
3276 $location["lat"] = $coord[0];
3277 $location["lng"] = $coord[1];
3280 $message = array("raw_message" => $body,
3281 "location" => $location,
3282 "guid" => $item["guid"],
3283 "diaspora_handle" => $myaddr,
3284 "public" => $public,
3285 "created_at" => $created,
3286 "provider_display_name" => $item["app"]);
3288 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3289 if (!isset($location["lat"]) OR !isset($location["lng"])) {
3290 unset($message["location"]);
3293 if ($item['event-id'] > 0) {
3294 $event = self::build_event($item['event-id']);
3295 if (count($event)) {
3296 $message['event'] = $event;
3298 /// @todo Once Diaspora supports it, we will remove the body
3299 // $message['raw_message'] = '';
3303 $type = "status_message";
3306 $msg = array("type" => $type, "message" => $message);
3308 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3314 * @brief Sends a post
3316 * @param array $item The item that will be exported
3317 * @param array $owner the array of the item owner
3318 * @param array $contact Target of the communication
3319 * @param bool $public_batch Is it a public post?
3321 * @return int The result of the transmission
3323 public static function send_status($item, $owner, $contact, $public_batch = false) {
3325 $status = self::build_status($item, $owner);
3327 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3331 * @brief Creates a "like" object
3333 * @param array $item The item that will be exported
3334 * @param array $owner the array of the item owner
3336 * @return array The data for a "like"
3338 private static function construct_like($item, $owner) {
3340 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3341 dbesc($item["thr-parent"]));
3342 if (!dbm::is_result($p))
3347 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3348 if ($item['verb'] === ACTIVITY_LIKE) {
3350 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3351 $positive = "false";
3354 return(array("positive" => $positive,
3355 "guid" => $item["guid"],
3356 "target_type" => $target_type,
3357 "parent_guid" => $parent["guid"],
3358 "author_signature" => "",
3359 "diaspora_handle" => self::my_handle($owner)));
3363 * @brief Creates an "EventParticipation" object
3365 * @param array $item The item that will be exported
3366 * @param array $owner the array of the item owner
3368 * @return array The data for an "EventParticipation"
3370 private static function construct_attend($item, $owner) {
3372 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3373 dbesc($item["thr-parent"]));
3374 if (!dbm::is_result($p))
3379 switch ($item['verb']) {
3380 case ACTIVITY_ATTEND:
3381 $attend_answer = 'accepted';
3383 case ACTIVITY_ATTENDNO:
3384 $attend_answer = 'declined';
3386 case ACTIVITY_ATTENDMAYBE:
3387 $attend_answer = 'tentative';
3390 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3394 return(array("author" => self::my_handle($owner),
3395 "guid" => $item["guid"],
3396 "parent_guid" => $parent["guid"],
3397 "status" => $attend_answer,
3398 "author_signature" => ""));
3402 * @brief Creates the object for a comment
3404 * @param array $item The item that will be exported
3405 * @param array $owner the array of the item owner
3407 * @return array The data for a comment
3409 private static function construct_comment($item, $owner) {
3411 $cachekey = "diaspora:construct_comment:".$item['guid'];
3413 $result = Cache::get($cachekey);
3414 if (!is_null($result)) {
3418 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3419 intval($item["parent"]),
3420 intval($item["parent"])
3423 if (!dbm::is_result($p))
3428 $text = html_entity_decode(bb2diaspora($item["body"]));
3429 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3431 $comment = array("guid" => $item["guid"],
3432 "parent_guid" => $parent["guid"],
3433 "author_signature" => "",
3435 /// @todo Currently disabled until Diaspora supports it: "created_at" => $created,
3436 "diaspora_handle" => self::my_handle($owner));
3438 // Send the thread parent guid only if it is a threaded comment
3439 if ($item['thr-parent'] != $item['parent-uri']) {
3440 $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3443 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3449 * @brief Send a like or a comment
3451 * @param array $item The item that will be exported
3452 * @param array $owner the array of the item owner
3453 * @param array $contact Target of the communication
3454 * @param bool $public_batch Is it a public post?
3456 * @return int The result of the transmission
3458 public static function send_followup($item,$owner,$contact,$public_batch = false) {
3460 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3461 $message = self::construct_attend($item, $owner);
3462 $type = "event_participation";
3463 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3464 $message = self::construct_like($item, $owner);
3467 $message = self::construct_comment($item, $owner);
3474 $message["author_signature"] = self::signature($owner, $message);
3476 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3480 * @brief Creates a message from a signature record entry
3482 * @param array $item The item that will be exported
3483 * @param array $signature The entry of the "sign" record
3485 * @return string The message
3487 private static function message_from_signature($item, $signature) {
3489 // Split the signed text
3490 $signed_parts = explode(";", $signature['signed_text']);
3492 if ($item["deleted"])
3493 $message = array("parent_author_signature" => "",
3494 "target_guid" => $signed_parts[0],
3495 "target_type" => $signed_parts[1],
3496 "sender_handle" => $signature['signer'],
3497 "target_author_signature" => $signature['signature']);
3498 elseif ($item['verb'] === ACTIVITY_LIKE)
3499 $message = array("positive" => $signed_parts[0],
3500 "guid" => $signed_parts[1],
3501 "target_type" => $signed_parts[2],
3502 "parent_guid" => $signed_parts[3],
3503 "parent_author_signature" => "",
3504 "author_signature" => $signature['signature'],
3505 "diaspora_handle" => $signed_parts[4]);
3507 // Remove the comment guid
3508 $guid = array_shift($signed_parts);
3510 // Remove the parent guid
3511 $parent_guid = array_shift($signed_parts);
3513 // Remove the handle
3514 $handle = array_pop($signed_parts);
3516 // Glue the parts together
3517 $text = implode(";", $signed_parts);
3519 $message = array("guid" => $guid,
3520 "parent_guid" => $parent_guid,
3521 "parent_author_signature" => "",
3522 "author_signature" => $signature['signature'],
3523 "text" => implode(";", $signed_parts),
3524 "diaspora_handle" => $handle);
3530 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3532 * @param array $item The item that will be exported
3533 * @param array $owner the array of the item owner
3534 * @param array $contact Target of the communication
3535 * @param bool $public_batch Is it a public post?
3537 * @return int The result of the transmission
3539 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3541 if ($item["deleted"])
3542 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3543 elseif ($item['verb'] === ACTIVITY_LIKE)
3548 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3550 // fetch the original signature
3552 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3553 intval($item["id"]));
3556 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3562 // Old way - is used by the internal Friendica functions
3563 /// @todo Change all signatur storing functions to the new format
3564 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
3565 $message = self::message_from_signature($item, $signature);
3567 $msg = json_decode($signature['signed_text'], true);
3570 if (is_array($msg)) {
3571 foreach ($msg AS $field => $data) {
3572 if (!$item["deleted"]) {
3573 if ($field == "author")
3574 $field = "diaspora_handle";
3575 if ($field == "parent_type")
3576 $field = "target_type";
3579 $message[$field] = $data;
3582 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3585 $message["parent_author_signature"] = self::signature($owner, $message);
3587 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3589 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3593 * @brief Sends a retraction (deletion) of a message, like or comment
3595 * @param array $item The item that will be exported
3596 * @param array $owner the array of the item owner
3597 * @param array $contact Target of the communication
3598 * @param bool $public_batch Is it a public post?
3599 * @param bool $relay Is the retraction transmitted from a relay?
3601 * @return int The result of the transmission
3603 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3605 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3607 // Check whether the retraction is for a top-level post or whether it's a relayable
3608 if ($item["uri"] !== $item["parent-uri"]) {
3609 $msg_type = "relayable_retraction";
3610 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
3612 $msg_type = "signed_retraction";
3613 $target_type = "StatusMessage";
3616 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
3617 $signature = "parent_author_signature";
3619 $signature = "target_author_signature";
3621 $signed_text = $item["guid"].";".$target_type;
3623 $message = array("target_guid" => $item['guid'],
3624 "target_type" => $target_type,
3625 "sender_handle" => $itemaddr,
3626 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
3628 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3630 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3634 * @brief Sends a mail
3636 * @param array $item The item that will be exported
3637 * @param array $owner The owner
3638 * @param array $contact Target of the communication
3640 * @return int The result of the transmission
3642 public static function send_mail($item, $owner, $contact) {
3644 $myaddr = self::my_handle($owner);
3646 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3647 intval($item["convid"]),
3648 intval($item["uid"])
3651 if (!dbm::is_result($r)) {
3652 logger("conversation not found.");
3658 "guid" => $cnv["guid"],
3659 "subject" => $cnv["subject"],
3660 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3661 "diaspora_handle" => $cnv["creator"],
3662 "participant_handles" => $cnv["recips"]
3665 $body = bb2diaspora($item["body"]);
3666 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3668 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3669 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3672 "guid" => $item["guid"],
3673 "parent_guid" => $cnv["guid"],
3674 "parent_author_signature" => $sig,
3675 "author_signature" => $sig,
3677 "created_at" => $created,
3678 "diaspora_handle" => $myaddr,
3679 "conversation_guid" => $cnv["guid"]
3682 if ($item["reply"]) {
3686 $message = array("guid" => $cnv["guid"],
3687 "subject" => $cnv["subject"],
3688 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3690 "diaspora_handle" => $cnv["creator"],
3691 "participant_handles" => $cnv["recips"]);
3693 $type = "conversation";
3696 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3700 * @brief Sends profile data
3702 * @param int $uid The user id
3704 public static function send_profile($uid, $recips = false) {
3710 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3711 AND `uid` = %d AND `rel` != %d",
3712 dbesc(NETWORK_DIASPORA),
3714 intval(CONTACT_IS_SHARING)
3719 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3721 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3722 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3723 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3732 $handle = $profile["addr"];
3733 $first = ((strpos($profile['name'],' ')
3734 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3735 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3736 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3737 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3738 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3739 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3741 if ($searchable === 'true') {
3742 $dob = '1000-00-00';
3744 if (($profile['dob']) && ($profile['dob'] > '0001-01-01'))
3745 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3747 $about = $profile['about'];
3748 $about = strip_tags(bbcode($about));
3750 $location = formatted_location($profile);
3752 if ($profile['pub_keywords']) {
3753 $kw = str_replace(',',' ',$profile['pub_keywords']);
3754 $kw = str_replace(' ',' ',$kw);
3755 $arr = explode(' ',$profile['pub_keywords']);
3757 for ($x = 0; $x < 5; $x ++) {
3759 $tags .= '#'. trim($arr[$x]) .' ';
3763 $tags = trim($tags);
3766 $message = array("diaspora_handle" => $handle,
3767 "first_name" => $first,
3768 "last_name" => $last,
3769 "image_url" => $large,
3770 "image_url_medium" => $medium,
3771 "image_url_small" => $small,
3773 "gender" => $profile['gender'],
3775 "location" => $location,
3776 "searchable" => $searchable,
3777 "tag_string" => $tags);
3779 foreach ($recips as $recip) {
3780 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3781 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3786 * @brief Stores the signature for likes that are created on our system
3788 * @param array $contact The contact array of the "like"
3789 * @param int $post_id The post id of the "like"
3791 * @return bool Success
3793 public static function store_like_signature($contact, $post_id) {
3795 // Is the contact the owner? Then fetch the private key
3796 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3797 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3801 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3802 if (!dbm::is_result($r)) {
3806 $contact["uprvkey"] = $r[0]['prvkey'];
3808 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3809 if (!dbm::is_result($r)) {
3813 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3817 $message = self::construct_like($r[0], $contact);
3818 $message["author_signature"] = self::signature($contact, $message);
3820 // We now store the signature more flexible to dynamically support new fields.
3821 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3822 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3823 intval($message_id),
3824 dbesc(json_encode($message))
3827 logger('Stored diaspora like signature');
3832 * @brief Stores the signature for comments that are created on our system
3834 * @param array $item The item array of the comment
3835 * @param array $contact The contact array of the item owner
3836 * @param string $uprvkey The private key of the sender
3837 * @param int $message_id The message id of the comment
3839 * @return bool Success
3841 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3843 if ($uprvkey == "") {
3844 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3848 $contact["uprvkey"] = $uprvkey;
3850 $message = self::construct_comment($item, $contact);
3851 $message["author_signature"] = self::signature($contact, $message);
3853 // We now store the signature more flexible to dynamically support new fields.
3854 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3855 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3856 intval($message_id),
3857 dbesc(json_encode($message))
3860 logger('Stored diaspora comment signature');