Crosspost of status and bookmarks is working

This commit is contained in:
Phyks 2015-01-18 23:35:33 +01:00
parent 5b48eb3cab
commit 3f0f556a80
4 changed files with 181 additions and 108 deletions

View File

@ -6,75 +6,153 @@
namespace IdnoPlugins\KnownDiaspora { namespace IdnoPlugins\KnownDiaspora {
/**
* Based on class from https://github.com/Faldrian/WP-diaspora-postwidget/blob/master/wp-diaspora-postwidget/diasphp.php -- Thanks, Faldrian!
*
* Ein fies zusammengehackter PHP-Diaspory-Client, der direkt von diesem abgeschaut ist:
* https://github.com/Javafant/diaspy/blob/master/client.py
*/
class DiasporaAPI { class DiasporaAPI {
function __construct($pod) {
$this->token_regex = '/content="(.*?)" name="csrf-token/';
static $_token_regex = '#content="(.*?)"\s+name="csrf-token#'; $this->pod = $pod;
$this->cookiejar = tempnam(sys_get_temp_dir(), 'cookies');
}
function __destruct() {
unlink($this->cookiejar);
}
private function _curl($url, $verb="get", $postfields=array(), $headers=array()) { function _fetch_token() {
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); $max_redirects = 10;
if ($verb == "post") {
curl_setopt($ch, CURLOPT_POST, 1); curl_setopt ($ch, CURLOPT_URL, $this->pod . "/stream");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); curl_setopt ($ch, CURLOPT_COOKIEFILE, $this->cookiejar);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $this->cookiejar);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
if (ini_get('open_basedir') === '' && ini_get('safe_mode' === 'Off')) {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, $max_redirects);
$output = curl_exec($ch);
} else {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
$mr = $max_redirects;
if ($mr > 0) {
$newurl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$rcurl = curl_copy_handle($ch);
curl_setopt($rcurl, CURLOPT_HEADER, true);
curl_setopt($rcurl, CURLOPT_NOBODY, true);
curl_setopt($rcurl, CURLOPT_FORBID_REUSE, false);
curl_setopt($rcurl, CURLOPT_RETURNTRANSFER, true);
do {
curl_setopt($rcurl, CURLOPT_URL, $newurl);
$header = curl_exec($rcurl);
if (curl_errno($rcurl)) {
$code = 0;
} else {
$code = curl_getinfo($rcurl, CURLINFO_HTTP_CODE);
if ($code == 301 || $code == 302) {
preg_match('/Location:(.*?)\n/', $header, $matches);
$newurl = trim(array_pop($matches));
} else {
$code = 0;
}
}
} while ($code && --$mr);
curl_close($rcurl);
if ($mr > 0) {
curl_setopt($ch, CURLOPT_URL, $newurl);
}
}
if($mr == 0 && $max_redirects > 0) {
$output = false;
} else {
$output = curl_exec($ch);
} }
if (!empty($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
} }
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_COOKIEFILE, $this->tmp_cookie_file);
curl_setopt($ch, CURLOPT_COOKIEJAR, $this->tmp_cookie_file);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$content = curl_exec($ch);
curl_close($ch); curl_close($ch);
return array('status_code' => $http_status, 'text' => $content); // Token holen und zurückgeben
preg_match($this->token_regex, $output, $matches);
return $matches[1];
} }
public function __construct($pod, $username, $password) { function login($username, $password) {
$this->tmp_cookie_file = tempnam(sys_get_temp_dir(), 'cookiejar'); $datatopost = array(
$this->pod = $pod;
$data = array(
'user[username]' => $username, 'user[username]' => $username,
'user[password]' => $password, 'user[password]' => $password,
'authenticity_token' => $this->_fetch_token() 'authenticity_token' => $this->_fetch_token()
); );
$response = $this->_curl($this->pod."/users/sign_in", "post", $data);
if ($response['status_code'] != 302) { $poststr = http_build_query($datatopost);
throw new \Exception("Invalid status code: ".$response['status_code']);
} // Adresse per cURL abrufen
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $this->pod . "/users/sign_in");
curl_setopt ($ch, CURLOPT_COOKIEFILE, $this->cookiejar);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $this->cookiejar);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $poststr);
curl_exec ($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if($info['http_code'] != 302) {
throw new \Exception('Login error '.print_r($info, true));
} }
public function __destruct() { // Das Objekt zurückgeben, damit man Aurufe verketten kann.
unlink($this->tmp_cookie_file); return $this;
} }
private function _fetch_token() { function post($text, $provider = "diasphp") {
$response = $this->_curl($this->pod."/stream"); // post-daten vorbereiten
$matches = array(); $datatopost = json_encode(array(
preg_match(self::$_token_regex, $response['text'], $matches); 'aspect_ids' => 'public',
return $matches[1]; 'status_message' => array('text' => $text,
} 'provider_display_name' => $provider)
public function post($text, $aspect_ids='public') {
$data = json_encode(array(
'status_message' => array('text' => $text),
'aspect_ids' => $aspect_ids
)); ));
// header vorbereiten
$headers = array( $headers = array(
'content-type' => 'application/json', 'Content-Type: application/json',
'accept' => 'application/json', 'accept: application/json',
'x-csrf-token' => $this->_fetch_token() 'x-csrf-token: '.$this->_fetch_token()
); );
$response = $this->_curl($this->pod."/status_messages", "post", $data, $headers);
var_dump($response); // Adresse per cURL abrufen
exit(); $ch = curl_init();
if ($response['status_code'] != 201) {
throw new \Exception("Invalid status code: ".$response['status_code']); curl_setopt ($ch, CURLOPT_URL, $this->pod . "/status_messages");
curl_setopt ($ch, CURLOPT_COOKIEFILE, $this->cookiejar);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $this->cookiejar);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $datatopost);
curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
curl_exec ($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if($info['http_code'] != 201) {
throw new \Exception('Post error '.print_r($info, true));
}
// Ende der möglichen Kette, gib mal "true" zurück.
return true;
} }
} }
} }
}

View File

@ -17,67 +17,53 @@
\Idno\Core\site()->template()->extendTemplate('account/menu/items', 'account/diaspora/menu'); \Idno\Core\site()->template()->extendTemplate('account/menu/items', 'account/diaspora/menu');
} }
/*function registerEventHooks() function registerEventHooks()
{ // TODO {
\Idno\Core\site()->syndication()->registerService('diaspora', function () { \Idno\Core\site()->syndication()->registerService('diaspora', function () {
return $this->hasDiaspora(); return $this->hasDiaspora();
}, array('note', 'article', 'image', 'media','rsvp', 'bookmark')); }, array('note', 'article', 'image', 'media','rsvp', 'bookmark'));
if ($this->hasDiaspora()) { if ($this->hasDiaspora()) {
if (is_array(\Idno\Core\site()->session()->currentUser()->diaspora) && !array_key_exists('access_token', \Idno\Core\site()->session()->currentUser()->facebook)) { \Idno\Core\site()->syndication()->registerServiceAccount('diaspora', \Idno\Core\site()->session()->currentUser()->diaspora['diaspora_username'], 'Diaspora ('.\Idno\Core\site()->session()->currentUser()->diaspora['diaspora_username'].')');
foreach(\Idno\Core\site()->session()->currentUser()->facebook as $username => $details) {
\Idno\Core\site()->syndication()->registerServiceAccount('facebook', $username, $details['name']);
}
}
} }
$notes_function = function (\Idno\Core\Event $event) { $notes_function = function (\Idno\Core\Event $event) {
$eventdata = $event->data(); $eventdata = $event->data();
$object = $eventdata['object']; $object = $eventdata['object'];
if ($this->hasFacebook()) { if ($this->hasDiaspora()) {
$object = $eventdata['object']; $object = $eventdata['object'];
if (!empty($eventdata['syndication_account'])) { $diasporaAPI = new DiasporaAPI(\Idno\Core\site()->session()->currentUser()->diaspora['diaspora_pod']);
$facebookAPI = $this->connect($eventdata['syndication_account']); $diasporaAPI->login(\Idno\Core\site()->session()->currentUser()->diaspora['diaspora_username'], \Idno\Core\site()->session()->currentUser()->diaspora['diaspora_password']);
} else { if (!empty($diasporaAPI)) {
$facebookAPI = $this->connect();
}
if (!empty($facebookAPI)) {
$message = preg_replace('/<[^\>]*>/', '', $object->getDescription()); //strip_tags($object->getDescription()); $message = preg_replace('/<[^\>]*>/', '', $object->getDescription()); //strip_tags($object->getDescription());
// Obey the IndieWeb reference setting // Obey the IndieWeb reference setting
if (!substr_count($message, \Idno\Core\site()->config()->host) && \Idno\Core\site()->config()->indieweb_reference) { if (!substr_count($message, \Idno\Core\site()->config()->host) && \Idno\Core\site()->config()->indieweb_reference) {
$message .= "\n\n(" . $object->getShortURL(true, false) . ")"; $message .= "\n\n(<a href=\"http://" . $object->getShortURL(true, false) . "\">" . $object->getShortURL(true, false) . "</a>)";
} }
if (!empty($message) && substr($message, 0, 1) != '@') { if (!empty($message) && substr($message, 0, 1) != '@') {
$params = array(
'message' => $message,
'actions' => json_encode([['name' => 'See Original', 'link' => $object->getURL()]]),
);
if (preg_match('/(?<!=)(?<!["\'])((ht|f)tps?:\/\/[^\s\r\n\t<>"\'\(\)]+)/i', $message, $matches)) {
$params['link'] = $matches[0]; // Set the first discovered link as the match
}
try { try {
$result = $facebookAPI->api('/'.$this->endpoint.'/feed', 'POST', $params); $result = $diasporaAPI->post($message, 'KnownDiaspora');
if (!empty($result['id'])) { if (!empty($result['id'])) {
$result['id'] = str_replace('_', '/posts/', $result['id']); $result['id'] = str_replace('_', '/posts/', $result['id']);
$object->setPosseLink('facebook', 'https://facebook.com/' . $result['id']);
$object->save(); $object->save();
} }
} catch (\Exception $e) { } catch (\Exception $e) {
error_log('There was a problem posting to Facebook: ' . $e->getMessage()); error_log('There was a problem posting to Diaspora: ' . $e->getMessage());
\Idno\Core\site()->session()->addMessage('There was a problem posting to Facebook: ' . $e->getMessage()); \Idno\Core\site()->session()->addMessage('There was a problem posting to Diaspora: ' . $e->getMessage());
} }
} }
} }
} }
}; };
// Push "notes" to Facebook // Push "notes" to Diaspora
\Idno\Core\site()->addEventHook('post/note/facebook', $notes_function); \Idno\Core\site()->addEventHook('post/note/diaspora', $notes_function);
\Idno\Core\site()->addEventHook('post/bookmark/facebook', $notes_function); \Idno\Core\site()->addEventHook('post/bookmark/diaspora', $notes_function);
// TODO
$article_function = function (\Idno\Core\Event $event) { $article_function = function (\Idno\Core\Event $event) {
$eventdata = $event->data(); $eventdata = $event->data();
$object = $eventdata['object']; $object = $eventdata['object'];
@ -104,11 +90,12 @@
}; };
// Push "articles" and "rsvps" to Facebook // Push "articles" and "rsvps" to Facebook
\Idno\Core\site()->addEventHook('post/rsvp/facebook', $article_function); \Idno\Core\site()->addEventHook('post/rsvp/diaspora', $article_function);
\Idno\Core\site()->addEventHook('post/article/facebook', $article_function); \Idno\Core\site()->addEventHook('post/article/diaspora', $article_function);
// TODO
// Push "media" to Facebook // Push "media" to Facebook
\Idno\Core\site()->addEventHook('post/media/facebook', function (\Idno\Core\Event $event) { \Idno\Core\site()->addEventHook('post/media/diaspora', function (\Idno\Core\Event $event) {
$eventdata = $event->data(); $eventdata = $event->data();
$object = $eventdata['object']; $object = $eventdata['object'];
if ($this->hasFacebook()) { if ($this->hasFacebook()) {
@ -133,8 +120,9 @@
} }
}); });
// TODO
// Push "images" to Facebook // Push "images" to Facebook
\Idno\Core\site()->addEventHook('post/image/facebook', function (\Idno\Core\Event $event) { \Idno\Core\site()->addEventHook('post/image/diaspora', function (\Idno\Core\Event $event) {
$eventdata = $event->data(); $eventdata = $event->data();
$object = $eventdata['object']; $object = $eventdata['object'];
if ($attachments = $object->getAttachments()) { if ($attachments = $object->getAttachments()) {
@ -172,7 +160,14 @@
} }
} }
}); });
}*/ }
/**
* Check if Diaspora plugin is enabled.
*/
function hasDiaspora() {
return !empty(\Idno\Core\site()->session()->currentUser()->diaspora['diaspora_username']) && !empty(\Idno\Core\site()->session()->currentUser()->diaspora['diaspora_pod']) && !empty(\Idno\Core\site()->session()->currentUser()->diaspora['diaspora_password']);
}
} }
} }

View File

@ -15,11 +15,7 @@
function getContent() function getContent()
{ {
if(isset($_GET['remove'])) { if(isset($_GET['remove'])) {
\Idno\Core\site()->config->config['diaspora'] = [ unset(\Idno\Core\site()->session()->currentUser()->diaspora);
'diaspora_username' => '',
'diaspora_password' => '',
'diaspora_pod' => ''
];
\Idno\Core\site()->config()->save(); \Idno\Core\site()->config()->save();
\Idno\Core\site()->session()->addMessage('Your Diaspora credentials were removed.'); \Idno\Core\site()->session()->addMessage('Your Diaspora credentials were removed.');
$this->forward(\Idno\Core\site()->config()->getDisplayURL() . 'account/diaspora/'); $this->forward(\Idno\Core\site()->config()->getDisplayURL() . 'account/diaspora/');
@ -35,14 +31,18 @@
$pod = $this->getInput('pod'); $pod = $this->getInput('pod');
$username = $this->getInput('user'); $username = $this->getInput('user');
$password = $this->getInput('pass'); $password = $this->getInput('pass');
\Idno\Core\site()->config->config['diaspora'] = [ $user = \Idno\Core\site()->session()->currentUser();
$user->diaspora = [
'diaspora_username' => $username, 'diaspora_username' => $username,
'diaspora_pod' => $pod 'diaspora_pod' => $pod
]; ];
if (empty(\Idno\Core\site()->config->config['diaspora']['diaspora_password']) || !empty($password) ) { if (empty($user->diaspora['diaspora_password']) || !empty($password) ) {
\Idno\Core\site()->config->config['diaspora']['diaspora_password'] = $password; $user->diaspora['diaspora_password'] = $password;
} }
\Idno\Core\site()->config()->save(); else {
$user->diaspora['diaspora_password'] = $user->diaspora['diaspora_password'];
}
$user->save();
\Idno\Core\site()->session()->addMessage('Your Diaspora credentials were saved.'); \Idno\Core\site()->session()->addMessage('Your Diaspora credentials were saved.');
$this->forward(\Idno\Core\site()->config()->getDisplayURL() . 'account/diaspora/'); $this->forward(\Idno\Core\site()->config()->getDisplayURL() . 'account/diaspora/');
} }

View File

@ -22,19 +22,19 @@
</div> </div>
<form class="form-horizontal" method="post" action="<?= \Idno\Core\site()->config()->getDisplayURL() ?>account/diaspora/"> <form class="form-horizontal" method="post" action="<?= \Idno\Core\site()->config()->getDisplayURL() ?>account/diaspora/">
<div class="row"> <div class="row">
<div class="span1"><p><strong><label class="control-label" for="pod">Pod</label></strong></p></div> <div class="span2"><p><strong><label class="control-label" for="pod">Pod</label></strong></p></div>
<div class="span3"><input type="text" name="pod" id="pod" value="<?=htmlspecialchars(\Idno\Core\site()->config()->diaspora['diaspora_pod'])?>"/></div> <div class="span4"><input type="text" name="pod" id="pod" value="<?=htmlspecialchars(\Idno\Core\site()->session()->currentUser()->diaspora['diaspora_pod'])?>"/></div>
<div class="span3"><p class="config-desc">Your Diaspora pod.</p></div> <div class="span4"><p class="config-desc">Your Diaspora pod.</p></div>
</div> </div>
<div class="row"> <div class="row">
<div class="span1"><p><strong><label class="control-label" for="user">Username</label></strong></p></div> <div class="span2"><p><strong><label class="control-label" for="user">Username</label></strong></p></div>
<div class="span3"><input type="text" name="user" id="user" value="<?=htmlspecialchars(\Idno\Core\site()->config()->diaspora['diaspora_username'])?>"/></div> <div class="span4"><input type="text" name="user" id="user" value="<?=htmlspecialchars(\Idno\Core\site()->session()->currentUser()->diaspora['diaspora_username'])?>"/></div>
<div class="span3"><p class="config-desc">Your Diaspora username.</p></div> <div class="span4"><p class="config-desc">Your Diaspora username.</p></div>
</div> </div>
<div class="row"> <div class="row">
<div class="span1"><p><strong><label class="control-label" for="pass">Password</label></strong></p></div> <div class="span2"><p><strong><label class="control-label" for="pass">Password</label></strong></p></div>
<div class="span3"><input type="password" name="pass" id="pass"/></div> <div class="span4"><input type="password" name="pass" id="pass"/></div>
<div class="span3"><p class="config-desc">Your Diaspora password.</p></div> <div class="span4"><p class="config-desc">Your Diaspora password.</p></div>
</div> </div>
<div class="control-group"> <div class="control-group">
<div class="controls-save"> <div class="controls-save">