4 * Name: GNU Social Connector
5 * Description: Bidirectional (posting, relaying and reading) connector for GNU Social.
7 * Author: Tobias Diekershoff <https://f.diekershoff.de/profile/tobias>
8 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
10 * Copyright (c) 2011-2013 Tobias Diekershoff, Michael Vogel
11 * All rights reserved.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions are met:
15 * * Redistributions of source code must retain the above copyright notice,
16 * this list of conditions and the following disclaimer.
17 * * Redistributions in binary form must reproduce the above
18 * * copyright notice, this list of conditions and the following disclaimer in
19 * the documentation and/or other materials provided with the distribution.
20 * * Neither the name of the <organization> nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
26 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT,
28 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
32 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
33 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 define('STATUSNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
38 require_once __DIR__ . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'statusnetoauth.php';
40 use CodebirdSN\CodebirdSN;
42 use Friendica\Content\Text\Plaintext;
43 use Friendica\Core\Hook;
44 use Friendica\Core\Logger;
45 use Friendica\Core\Renderer;
46 use Friendica\Core\System;
47 use Friendica\Database\DBA;
49 use Friendica\Model\Item;
50 use Friendica\Model\Post;
51 use Friendica\Model\User;
53 function statusnet_install()
55 // we need some hooks, for the configuration and for sending tweets
56 Hook::register('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
57 Hook::register('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
58 Hook::register('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
59 Hook::register('hook_fork', 'addon/statusnet/statusnet.php', 'statusnet_hook_fork');
60 Hook::register('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
61 Hook::register('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
62 Logger::notice('installed GNU Social');
65 function statusnet_jot_nets(array &$jotnets_fields)
67 if (!DI::userSession()->getLocalUserId()) {
71 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'post')) {
76 DI::l10n()->t('Post to GNU Social'),
77 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'post_by_default')
83 function statusnet_settings_post($post)
85 if (!DI::userSession()->getLocalUserId()) {
88 // don't check GNU Social settings if GNU Social submit button is not clicked
89 if (empty($_POST['statusnet-submit']) && empty($_POST['statusnet-disconnect'])) {
93 if (!empty($_POST['statusnet-disconnect'])) {
95 * if the GNU Social-disconnect button is clicked, clear the GNU Social configuration
97 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'statusnet', 'consumerkey');
98 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'statusnet', 'consumersecret');
99 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'statusnet', 'post');
100 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'statusnet', 'post_by_default');
101 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'statusnet', 'oauthtoken');
102 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'statusnet', 'oauthsecret');
103 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'statusnet', 'baseapi');
105 if (isset($_POST['statusnet-preconf-apiurl'])) {
107 * If the user used one of the preconfigured GNU Social server credentials
108 * use them. All the data are available in the global config.
109 * Check the API Url never the less and blame the admin if it's not working ^^
111 $globalsn = DI::config()->get('statusnet', 'sites');
112 foreach ($globalsn as $asn) {
113 if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl']) {
114 $apibase = $asn['apiurl'];
115 $c = DI::httpClient()->fetch($apibase . 'statusnet/version.xml');
116 if (strlen($c) > 0) {
117 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'consumerkey', $asn['consumerkey']);
118 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'consumersecret', $asn['consumersecret']);
119 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'baseapi', $asn['apiurl']);
120 //DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'application_name', $asn['applicationname'] );
122 DI::sysmsg()->addNotice(DI::l10n()->t('Please contact your site administrator.<br />The provided API URL is not valid.') . '<br />' . $asn['apiurl']);
127 if (isset($_POST['statusnet-consumersecret'])) {
128 // check if we can reach the API of the GNU Social server
129 // we'll check the API Version for that, if we don't get one we'll try to fix the path but will
130 // resign quickly after this one try to fix the path ;-)
131 $apibase = $_POST['statusnet-baseapi'];
132 $c = DI::httpClient()->fetch($apibase . 'statusnet/version.xml');
133 if (strlen($c) > 0) {
134 // ok the API path is correct, let's save the settings
135 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
136 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
137 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'baseapi', $apibase);
138 //DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'application_name', $_POST['statusnet-applicationname'] );
140 // the API path is not correct, maybe missing trailing / ?
141 $apibase = $apibase . '/';
142 $c = DI::httpClient()->fetch($apibase . 'statusnet/version.xml');
143 if (strlen($c) > 0) {
144 // ok the API path is now correct, let's save the settings
145 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
146 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
147 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'baseapi', $apibase);
149 // still not the correct API base, let's do noting
150 DI::sysmsg()->addNotice(DI::l10n()->t('We could not contact the GNU Social API with the Path you entered.'));
154 if (isset($_POST['statusnet-pin'])) {
155 // if the user supplied us with a PIN from GNU Social, let the magic of OAuth happen
156 $api = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'baseapi');
157 $ckey = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'consumerkey');
158 $csecret = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'consumersecret');
159 // the token and secret for which the PIN was generated were hidden in the settings
160 // form as token and token2, we need a new connection to GNU Social using these token
161 // and secret to request a Access Token with the PIN
162 $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
163 $token = $connection->getAccessToken($_POST['statusnet-pin']);
164 // ok, now that we have the Access Token, save them in the user config
165 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'oauthtoken', $token['oauth_token']);
166 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'oauthsecret', $token['oauth_token_secret']);
167 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'post', 1);
168 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'post_taglinks', 1);
169 // reload the Addon Settings page, if we don't do it see Bug #42
171 // if no PIN is supplied in the POST variables, the user has changed the setting
172 // to post a dent for every new __public__ posting to the wall
173 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'post', intval($_POST['statusnet-enable']));
174 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'statusnet', 'post_by_default', intval($_POST['statusnet-default']));
181 function statusnet_settings(array &$data)
183 if (!DI::userSession()->getLocalUserId()) {
187 DI::page()->registerStylesheet(__DIR__ . '/statusnet.css', 'all');
190 * 1) Check that we have a base api url and a consumer key & secret
191 * 2) If no OAuthtoken & stuff is present, generate button to get some
192 * allow the user to cancel the connection process at this step
193 * 3) Checkbox for "Send public notices (respect size limitation)
195 $baseapi = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'baseapi');
196 $ckey = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'consumerkey');
197 $csecret = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'consumersecret');
198 $otoken = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'oauthtoken');
199 $osecret = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'oauthsecret');
200 $enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'post', false);
201 $def_enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'post_by_default', false);
203 // Radio button list to select existing application credentials
204 $sites = array_map(function ($site) {
205 return ['statusnet-preconf-apiurl', $site['sitename'], $site['apiurl']];
206 }, DI::config()->get('statusnet', 'sites', []));
208 $submit = ['statusnet-submit' => DI::l10n()->t('Save Settings')];
210 if ($ckey && $csecret) {
211 if ($otoken && $osecret) {
213 * we have an OAuth key / secret pair for the user
214 * so let's give a chance to disable the postings to GNU Social
216 $connection = new StatusNetOAuth($baseapi, $ckey, $csecret, $otoken, $osecret);
217 $account = $connection->get('account/verify_credentials');
219 if (!empty($account)) {
220 $connected_account = DI::l10n()->t('Currently connected to: <a href="%s" target="_statusnet">%s</a>', $account->statusnet_profile_url, $account->screen_name);
223 $user = User::getById(DI::userSession()->getLocalUserId());
224 if ($user['hidewall']) {
225 $privacy_warning = DI::l10n()->t('<strong>Note</strong>: Due your privacy settings (<em>Hide your profile details from unknown viewers?</em>) the link potentially included in public postings relayed to GNU Social will lead the visitor to a blank page informing the visitor that the access to your profile has been restricted.');
228 $submit['statusnet-disconnect'] = DI::l10n()->t('Clear OAuth configuration');
231 * the user has not yet connected the account to GNU Social
232 * get a temporary OAuth key/secret pair and display a button with
233 * which the user can request a PIN to connect the account to a
234 * account at GNU Social
236 $connection = new StatusNetOAuth($baseapi, $ckey, $csecret);
237 $request_token = $connection->getRequestToken('oob');
238 $authorize_url = $connection->getAuthorizeURL($request_token['oauth_token'], false);
240 $submit['statusnet-disconnect'] = DI::l10n()->t('Cancel GNU Social Connection');
244 $t = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/statusnet/');
245 $html = Renderer::replaceMacros($t, [
247 'global_title' => DI::l10n()->t('Globally Available GNU Social OAuthKeys'),
248 'global_info' => DI::l10n()->t(DI::l10n()->t('There are preconfigured OAuth key pairs for some GNU Social servers available. If you are using one of them, please use these credentials. If not feel free to connect to any other GNU Social instance (see below).')),
249 'credentials_title' => DI::l10n()->t('Provide your own OAuth Credentials'),
250 'credentials_info' => DI::l10n()->t('No consumer key pair for GNU Social found. Register your Friendica Account as a desktop application on your GNU Social account, copy the consumer key pair here and enter the API base root.<br />Before you register your own OAuth key pair ask the administrator if there is already a key pair for this Friendica installation at your favorite GNU Social installation.'),
251 'oauth_info' => DI::l10n()->t('To connect to your GNU Social account click the button below to get a security code from GNU Social which you have to copy into the input box below and submit the form. Only your <strong>public</strong> posts will be posted to GNU Social.'),
252 'oauth_alt' => DI::l10n()->t('Log in with GNU Social'),
253 'oauth_cancel' => DI::l10n()->t('Cancel Connection Process'),
254 'oauth_api' => DI::l10n()->t('Current GNU Social API is: %s', $baseapi),
255 'connected_account' => $connected_account ?? '',
256 'privacy_warning' => $privacy_warning ?? '',
260 '$csecret' => $csecret,
261 '$otoken' => $otoken,
262 '$osecret' => $osecret,
265 '$authorize_url' => $authorize_url ?? '',
266 '$request_token' => $request_token ?? null,
267 '$account' => $account ?? null,
269 '$authenticate_url' => DI::baseUrl() . '/statusnet/connect',
271 '$consumerkey' => ['statusnet-consumerkey', DI::l10n()->t('OAuth Consumer Key'), '', '', false, ' size="35'],
272 '$consumersecret' => ['statusnet-consumersecret', DI::l10n()->t('OAuth Consumer Secret'), '', '', false, ' size="35'],
274 '$baseapi' => ['statusnet-baseapi', DI::l10n()->t('Base API Path (remember the trailing /)'), '', '', false, ' size="35'],
275 '$pin' => ['statusnet-pin', DI::l10n()->t('Copy the security code from GNU Social here')],
277 '$enable' => ['statusnet-enabled', DI::l10n()->t('Allow posting to GNU Social'), $enabled, DI::l10n()->t('If enabled all your <strong>public</strong> postings can be posted to the associated GNU Social account. You can choose to do so by default (here) or for every posting separately in the posting options when writing the entry.')],
278 '$default' => ['statusnet-default', DI::l10n()->t('Post to GNU Social by default'), $def_enabled],
282 'connector' => 'statusnet',
283 'title' => DI::l10n()->t('GNU Social Import/Export/Mirror'),
284 'image' => 'images/gnusocial.png',
285 'enabled' => $enabled,
291 function statusnet_hook_fork(array &$b)
293 if ($b['name'] != 'notifier_normal') {
299 if ($post['deleted'] || ($post['created'] !== $post['edited']) || strpos($post['postopts'] ?? '', 'statusnet') === false || ($post['parent'] != $post['id']) || $post['private']) {
300 $b['execute'] = false;
305 function statusnet_post_local(array &$b)
311 if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
315 $statusnet_post = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'post');
316 $statusnet_enable = (($statusnet_post && !empty($_REQUEST['statusnet_enable'])) ? intval($_REQUEST['statusnet_enable']) : 0);
318 // if API is used, default to the chosen settings
319 if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'statusnet', 'post_by_default'))) {
320 $statusnet_enable = 1;
323 if (!$statusnet_enable) {
327 if (strlen($b['postopts'])) {
328 $b['postopts'] .= ',';
331 $b['postopts'] .= 'statusnet';
334 function statusnet_post_hook(array &$b)
339 if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) {
343 $b['body'] = Post\Media::addAttachmentsToBody($b['uri-id'], DI::contentItem()->addSharedPost($b));
345 $api = DI::pConfig()->get($b['uid'], 'statusnet', 'baseapi');
346 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
348 if ($b['private'] || !strstr($b['postopts'], 'statusnet')) {
352 // Dont't post if the post doesn't belong to us.
353 // This is a check for forum postings
354 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
355 if ($b['contact-id'] != $self['id']) {
359 Logger::notice('GNU Socialpost invoked');
361 DI::pConfig()->load($b['uid'], 'statusnet');
363 $api = DI::pConfig()->get($b['uid'], 'statusnet', 'baseapi');
364 $ckey = DI::pConfig()->get($b['uid'], 'statusnet', 'consumerkey');
365 $csecret = DI::pConfig()->get($b['uid'], 'statusnet', 'consumersecret');
366 $otoken = DI::pConfig()->get($b['uid'], 'statusnet', 'oauthtoken');
367 $osecret = DI::pConfig()->get($b['uid'], 'statusnet', 'oauthsecret');
369 if ($ckey && $csecret && $otoken && $osecret) {
370 $dent = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
371 $max_char = $dent->get_maxlength(); // max. length for a dent
373 DI::pConfig()->set($b['uid'], 'statusnet', 'max_char', $max_char);
376 $msgarr = Plaintext::getPost($b, $max_char, true, 7);
377 $msg = $msgarr['text'];
379 if (($msg == '') && isset($msgarr['title']))
380 $msg = Plaintext::shorten($msgarr['title'], $max_char - 50, $b['uid']);
384 if (isset($msgarr['url']) && ($msgarr['type'] != 'photo')) {
385 $msg .= " \n" . $msgarr['url'];
386 } elseif (isset($msgarr['image']) && ($msgarr['type'] != 'video')) {
387 $image = $msgarr['image'];
391 $img_str = DI::httpClient()->fetch($image);
392 $tempfile = tempnam(System::getTempPath(), 'cache');
393 file_put_contents($tempfile, $img_str);
394 $postdata = ['status' => $msg, 'media[]' => $tempfile];
396 $postdata = ['status' => $msg];
399 // and now send it :-)
401 // New code that is able to post pictures
402 require_once __DIR__ . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'codebirdsn.php';
403 $cb = CodebirdSN::getInstance();
404 $cb->setAPIEndpoint($api);
405 $cb->setConsumerKey($ckey, $csecret);
406 $cb->setToken($otoken, $osecret);
407 $result = $cb->statuses_update($postdata);
408 //$result = $dent->post('statuses/update', $postdata);
409 Logger::info('statusnet_post send, result: ' . print_r($result, true) .
410 "\nmessage: " . $msg . "\nOriginal post: " . print_r($b, true) . "\nPost Data: " . print_r($postdata, true));
412 if (!empty($result->source)) {
413 DI::pConfig()->set($b['uid'], 'statusnet', 'application_name', strip_tags($result->source));
416 if (!empty($result->error)) {
417 Logger::notice('Send to GNU Social failed: "' . $result->error . '"');
418 } elseif ($iscomment) {
419 Logger::notice('statusnet_post: Update extid ' . $result->id . ' for post id ' . $b['id']);
420 Item::update(['extid' => $hostname . '::' . $result->id, 'body' => $result->text], ['id' => $b['id']]);
423 if ($tempfile != '') {
429 function statusnet_addon_admin_post()
433 foreach ($_POST['sitename'] as $id => $sitename) {
434 $sitename = trim($sitename);
435 $apiurl = trim($_POST['apiurl'][$id]);
436 if (!(substr($apiurl, -1) == '/')) {
437 $apiurl = $apiurl . '/';
439 $secret = trim($_POST['secret'][$id]);
440 $key = trim($_POST['key'][$id]);
441 //$applicationname = (!empty($_POST['applicationname']) ? Strings::escapeTags(trim($_POST['applicationname'][$id])):'');
442 if ($sitename != '' &&
446 empty($_POST['delete'][$id])) {
449 'sitename' => $sitename,
451 'consumersecret' => $secret,
452 'consumerkey' => $key,
453 //'applicationname' => $applicationname
458 $sites = DI::config()->set('statusnet', 'sites', $sites);
461 function statusnet_addon_admin(string &$o)
463 $sites = DI::config()->get('statusnet', 'sites');
465 if (is_array($sites)) {
466 foreach ($sites as $id => $s) {
468 'sitename' => ["sitename[$id]", "Site name", $s['sitename'], ""],
469 'apiurl' => ["apiurl[$id]", "Api url", $s['apiurl'], DI::l10n()->t("Base API Path \x28remember the trailing /\x29")],
470 'secret' => ["secret[$id]", "Secret", $s['consumersecret'], ""],
471 'key' => ["key[$id]", "Key", $s['consumerkey'], ""],
472 //'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
473 'delete' => ["delete[$id]", "Delete", False, "Check to delete this preset"],
477 /* empty form to add new site */
478 $id = count($sitesform);
480 'sitename' => ["sitename[$id]", DI::l10n()->t("Site name"), "", ""],
481 'apiurl' => ["apiurl[$id]", "Api url", "", DI::l10n()->t("Base API Path \x28remember the trailing /\x29")],
482 'secret' => ["secret[$id]", DI::l10n()->t("Consumer Secret"), "", ""],
483 'key' => ["key[$id]", DI::l10n()->t("Consumer Key"), "", ""],
484 //'applicationname' => Array("applicationname[$id]", DI::l10n()->t("Application name"), "", ""),
487 $t = Renderer::getMarkupTemplate('admin.tpl', 'addon/statusnet/');
488 $o = Renderer::replaceMacros($t, [
489 '$submit' => DI::l10n()->t('Save Settings'),
490 '$sites' => $sitesform,