3 * Name: Tumblr Post Connector
4 * Description: Post to Tumblr
6 * Author: Mike Macgirvin <http://macgirvin.com/profile/mike>
7 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
10 require_once __DIR__ . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'tumblroauth.php';
13 use Friendica\Content\Text\BBCode;
14 use Friendica\Core\Hook;
15 use Friendica\Core\Logger;
16 use Friendica\Core\Renderer;
17 use Friendica\Database\DBA;
19 use Friendica\Model\Tag;
20 use Friendica\Util\Strings;
22 function tumblr_install()
24 Hook::register('hook_fork', 'addon/tumblr/tumblr.php', 'tumblr_hook_fork');
25 Hook::register('post_local', 'addon/tumblr/tumblr.php', 'tumblr_post_local');
26 Hook::register('notifier_normal', 'addon/tumblr/tumblr.php', 'tumblr_send');
27 Hook::register('jot_networks', 'addon/tumblr/tumblr.php', 'tumblr_jot_nets');
28 Hook::register('connector_settings', 'addon/tumblr/tumblr.php', 'tumblr_settings');
29 Hook::register('connector_settings_post', 'addon/tumblr/tumblr.php', 'tumblr_settings_post');
32 function tumblr_uninstall()
34 Hook::unregister('hook_fork', 'addon/tumblr/tumblr.php', 'tumblr_hook_fork');
35 Hook::unregister('post_local', 'addon/tumblr/tumblr.php', 'tumblr_post_local');
36 Hook::unregister('notifier_normal', 'addon/tumblr/tumblr.php', 'tumblr_send');
37 Hook::unregister('jot_networks', 'addon/tumblr/tumblr.php', 'tumblr_jot_nets');
38 Hook::unregister('connector_settings', 'addon/tumblr/tumblr.php', 'tumblr_settings');
39 Hook::unregister('connector_settings_post', 'addon/tumblr/tumblr.php', 'tumblr_settings_post');
42 function tumblr_module()
46 function tumblr_content(App $a)
49 notice(DI::l10n()->t('Permission denied.') . EOL);
53 if (isset($a->argv[1])) {
54 switch ($a->argv[1]) {
56 $o = tumblr_connect($a);
60 $o = tumblr_callback($a);
64 $o = print_r($a->argv, true);
68 $o = tumblr_connect($a);
74 function tumblr_addon_admin(App $a, &$o)
76 $t = Renderer::getMarkupTemplate( "admin.tpl", "addon/tumblr/" );
78 $o = Renderer::replaceMacros($t, [
79 '$submit' => DI::l10n()->t('Save Settings'),
80 // name, label, value, help, [extra values]
81 '$consumer_key' => ['consumer_key', DI::l10n()->t('Consumer Key'), DI::config()->get('tumblr', 'consumer_key' ), ''],
82 '$consumer_secret' => ['consumer_secret', DI::l10n()->t('Consumer Secret'), DI::config()->get('tumblr', 'consumer_secret' ), ''],
86 function tumblr_addon_admin_post(App $a)
88 $consumer_key = (!empty($_POST['consumer_key']) ? Strings::escapeTags(trim($_POST['consumer_key'])) : '');
89 $consumer_secret = (!empty($_POST['consumer_secret']) ? Strings::escapeTags(trim($_POST['consumer_secret'])): '');
91 DI::config()->set('tumblr', 'consumer_key',$consumer_key);
92 DI::config()->set('tumblr', 'consumer_secret',$consumer_secret);
95 function tumblr_connect(App $a)
97 // Start a session. This is necessary to hold on to a few keys the callback script will also need
100 // Include the TumblrOAuth library
101 //require_once('addon/tumblr/tumblroauth/tumblroauth.php');
103 // Define the needed keys
104 $consumer_key = DI::config()->get('tumblr', 'consumer_key');
105 $consumer_secret = DI::config()->get('tumblr', 'consumer_secret');
107 // The callback URL is the script that gets called after the user authenticates with tumblr
108 // In this example, it would be the included callback.php
109 $callback_url = DI::baseUrl()->get()."/tumblr/callback";
111 // Let's begin. First we need a Request Token. The request token is required to send the user
112 // to Tumblr's login page.
114 // Create a new instance of the TumblrOAuth library. For this step, all we need to give the library is our
115 // Consumer Key and Consumer Secret
116 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret);
118 // Ask Tumblr for a Request Token. Specify the Callback URL here too (although this should be optional)
119 $request_token = $tum_oauth->getRequestToken($callback_url);
121 // Store the request token and Request Token Secret as out callback.php script will need this
122 $_SESSION['request_token'] = $token = $request_token['oauth_token'];
123 $_SESSION['request_token_secret'] = $request_token['oauth_token_secret'];
125 // Check the HTTP Code. It should be a 200 (OK), if it's anything else then something didn't work.
126 switch ($tum_oauth->http_code) {
128 // Ask Tumblr to give us a special address to their login page
129 $url = $tum_oauth->getAuthorizeURL($token);
131 // Redirect the user to the login URL given to us by Tumblr
132 header('Location: ' . $url);
135 * That's it for our side. The user is sent to a Tumblr Login page and
136 * asked to authroize our app. After that, Tumblr sends the user back to
137 * our Callback URL (callback.php) along with some information we need to get
143 // Give an error message
144 $o = 'Could not connect to Tumblr. Refresh the page or try again later.';
150 function tumblr_callback(App $a)
152 // Start a session, load the library
154 //require_once('addon/tumblr/tumblroauth/tumblroauth.php');
156 // Define the needed keys
157 $consumer_key = DI::config()->get('tumblr', 'consumer_key');
158 $consumer_secret = DI::config()->get('tumblr', 'consumer_secret');
160 // Once the user approves your app at Tumblr, they are sent back to this script.
161 // This script is passed two parameters in the URL, oauth_token (our Request Token)
162 // and oauth_verifier (Key that we need to get Access Token).
163 // We'll also need out Request Token Secret, which we stored in a session.
165 // Create instance of TumblrOAuth.
166 // It'll need our Consumer Key and Secret as well as our Request Token and Secret
167 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $_SESSION['request_token'], $_SESSION['request_token_secret']);
169 // Ok, let's get an Access Token. We'll need to pass along our oauth_verifier which was given to us in the URL.
170 $access_token = $tum_oauth->getAccessToken($_REQUEST['oauth_verifier']);
172 // We're done with the Request Token and Secret so let's remove those.
173 unset($_SESSION['request_token']);
174 unset($_SESSION['request_token_secret']);
176 // Make sure nothing went wrong.
177 if (200 == $tum_oauth->http_code) {
180 return 'Unable to authenticate';
183 // What's next? Now that we have an Access Token and Secret, we can make an API call.
184 DI::pConfig()->set(local_user(), "tumblr", "oauth_token", $access_token['oauth_token']);
185 DI::pConfig()->set(local_user(), "tumblr", "oauth_token_secret", $access_token['oauth_token_secret']);
187 $o = DI::l10n()->t("You are now authenticated to tumblr.");
188 $o .= '<br /><a href="' . DI::baseUrl()->get() . '/settings/connectors">' . DI::l10n()->t("return to the connector page") . '</a>';
193 function tumblr_jot_nets(App $a, array &$jotnets_fields)
195 if (! local_user()) {
199 if (DI::pConfig()->get(local_user(),'tumblr','post')) {
200 $jotnets_fields[] = [
201 'type' => 'checkbox',
204 DI::l10n()->t('Post to Tumblr'),
205 DI::pConfig()->get(local_user(),'tumblr','post_by_default')
211 function tumblr_settings(App $a, &$s)
213 if (! local_user()) {
217 /* Add our stylesheet to the page so we can make our settings look nice */
219 DI::page()['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . DI::baseUrl()->get() . '/addon/tumblr/tumblr.css' . '" media="all" />' . "\r\n";
221 /* Get the current state of our config variables */
223 $enabled = DI::pConfig()->get(local_user(), 'tumblr', 'post');
224 $checked = (($enabled) ? ' checked="checked" ' : '');
225 $css = (($enabled) ? '' : '-disabled');
227 $def_enabled = DI::pConfig()->get(local_user(), 'tumblr', 'post_by_default');
229 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
231 /* Add some HTML to the existing form */
233 $s .= '<span id="settings_tumblr_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_tumblr_expanded\'); openClose(\'settings_tumblr_inflated\');">';
234 $s .= '<img class="connector'.$css.'" src="images/tumblr.png" /><h3 class="connector">'. DI::l10n()->t('Tumblr Export').'</h3>';
236 $s .= '<div id="settings_tumblr_expanded" class="settings-block" style="display: none;">';
237 $s .= '<span class="fakelink" onclick="openClose(\'settings_tumblr_expanded\'); openClose(\'settings_tumblr_inflated\');">';
238 $s .= '<img class="connector'.$css.'" src="images/tumblr.png" /><h3 class="connector">'. DI::l10n()->t('Tumblr Export').'</h3>';
241 $s .= '<div id="tumblr-username-wrapper">';
242 $s .= '<a href="'.DI::baseUrl()->get().'/tumblr/connect">'.DI::l10n()->t("(Re-)Authenticate your tumblr page").'</a>';
243 $s .= '</div><div class="clear"></div>';
245 $s .= '<div id="tumblr-enable-wrapper">';
246 $s .= '<label id="tumblr-enable-label" for="tumblr-checkbox">' . DI::l10n()->t('Enable Tumblr Post Addon') . '</label>';
247 $s .= '<input type="hidden" name="tumblr" value="0"/>';
248 $s .= '<input id="tumblr-checkbox" type="checkbox" name="tumblr" value="1" ' . $checked . '/>';
249 $s .= '</div><div class="clear"></div>';
251 $s .= '<div id="tumblr-bydefault-wrapper">';
252 $s .= '<label id="tumblr-bydefault-label" for="tumblr-bydefault">' . DI::l10n()->t('Post to Tumblr by default') . '</label>';
253 $s .= '<input type="hidden" name="tumblr_bydefault" value="0"/>';
254 $s .= '<input id="tumblr-bydefault" type="checkbox" name="tumblr_bydefault" value="1" ' . $def_checked . '/>';
255 $s .= '</div><div class="clear"></div>';
257 $oauth_token = DI::pConfig()->get(local_user(), "tumblr", "oauth_token");
258 $oauth_token_secret = DI::pConfig()->get(local_user(), "tumblr", "oauth_token_secret");
260 $s .= '<div id="tumblr-page-wrapper">';
262 if (($oauth_token != "") && ($oauth_token_secret != "")) {
263 $page = DI::pConfig()->get(local_user(), 'tumblr', 'page');
264 $consumer_key = DI::config()->get('tumblr', 'consumer_key');
265 $consumer_secret = DI::config()->get('tumblr', 'consumer_secret');
267 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
269 $userinfo = $tum_oauth->get('user/info');
273 $s .= '<label id="tumblr-page-label" for="tumblr-page">' . DI::l10n()->t('Post to page:') . '</label>';
274 $s .= '<select name="tumblr_page" id="tumblr-page">';
275 foreach($userinfo->response->user->blogs as $blog) {
276 $blogurl = substr(str_replace(["http://", "https://"], ["", ""], $blog->url), 0, -1);
278 if ($page == $blogurl) {
279 $s .= "<option value='".$blogurl."' selected>".$blogurl."</option>";
281 $s .= "<option value='".$blogurl."'>".$blogurl."</option>";
287 $s .= DI::l10n()->t("You are not authenticated to tumblr");
290 $s .= '</div><div class="clear"></div>';
292 /* provide a submit button */
293 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="tumblr-submit" name="tumblr-submit" class="settings-submit" value="' . DI::l10n()->t('Save Settings') . '" /></div></div>';
296 function tumblr_settings_post(App $a, array &$b)
298 if (!empty($_POST['tumblr-submit'])) {
299 DI::pConfig()->set(local_user(), 'tumblr', 'post', intval($_POST['tumblr']));
300 DI::pConfig()->set(local_user(), 'tumblr', 'page', $_POST['tumblr_page']);
301 DI::pConfig()->set(local_user(), 'tumblr', 'post_by_default', intval($_POST['tumblr_bydefault']));
305 function tumblr_hook_fork(&$a, &$b)
307 if ($b['name'] != 'notifier_normal') {
313 if ($post['deleted'] || $post['private'] || ($post['created'] !== $post['edited']) ||
314 !strstr($post['postopts'], 'tumblr') || ($post['parent'] != $post['id'])) {
315 $b['execute'] = false;
320 function tumblr_post_local(App $a, array &$b)
322 // This can probably be changed to allow editing by pointing to a different API endpoint
328 if (!local_user() || (local_user() != $b['uid'])) {
332 if ($b['private'] || $b['parent']) {
336 $tmbl_post = intval(DI::pConfig()->get(local_user(), 'tumblr', 'post'));
338 $tmbl_enable = (($tmbl_post && !empty($_REQUEST['tumblr_enable'])) ? intval($_REQUEST['tumblr_enable']) : 0);
340 if ($b['api_source'] && intval(DI::pConfig()->get(local_user(), 'tumblr', 'post_by_default'))) {
348 if (strlen($b['postopts'])) {
349 $b['postopts'] .= ',';
352 $b['postopts'] .= 'tumblr';
358 function tumblr_send(App $a, array &$b) {
360 if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) {
364 if (! strstr($b['postopts'],'tumblr')) {
368 if ($b['parent'] != $b['id']) {
372 // Dont't post if the post doesn't belong to us.
373 // This is a check for forum postings
374 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
375 if ($b['contact-id'] != $self['id']) {
379 $oauth_token = DI::pConfig()->get($b['uid'], "tumblr", "oauth_token");
380 $oauth_token_secret = DI::pConfig()->get($b['uid'], "tumblr", "oauth_token_secret");
381 $page = DI::pConfig()->get($b['uid'], "tumblr", "page");
382 $tmbl_blog = 'blog/' . $page . '/post';
384 if ($oauth_token && $oauth_token_secret && $tmbl_blog) {
385 $tags = Tag::getByURIId($b['uri-id']);
389 foreach($tags as $tag) {
390 $tag_arr[] = $tag['name'];
393 if (count($tag_arr)) {
394 $tags = implode(',', $tag_arr);
397 $title = trim($b['title']);
399 $siteinfo = BBCode::getAttachedData($b["body"]);
402 'state' => 'published',
408 if (!isset($siteinfo["type"])) {
409 $siteinfo["type"] = "";
412 if (($title == "") && isset($siteinfo["title"])) {
413 $title = $siteinfo["title"];
416 if (isset($siteinfo["text"])) {
417 $body = $siteinfo["text"];
419 $body = BBCode::removeShareInformation($b["body"]);
422 switch ($siteinfo["type"]) {
424 $params['type'] = "photo";
425 $params['caption'] = BBCode::convert($body, false, BBCode::CONNECTORS);
427 if (isset($siteinfo["url"])) {
428 $params['link'] = $siteinfo["url"];
431 $params['source'] = $siteinfo["image"];
435 $params['type'] = "link";
436 $params['title'] = $title;
437 $params['url'] = $siteinfo["url"];
438 $params['description'] = BBCode::convert($body, false, BBCode::CONNECTORS);
442 $params['type'] = "audio";
443 $params['external_url'] = $siteinfo["url"];
444 $params['caption'] = BBCode::convert($body, false, BBCode::CONNECTORS);
448 $params['type'] = "video";
449 $params['embed'] = $siteinfo["url"];
450 $params['caption'] = BBCode::convert($body, false, BBCode::CONNECTORS);
454 $params['type'] = "text";
455 $params['title'] = $title;
456 $params['body'] = BBCode::convert($b['body'], false, BBCode::CONNECTORS);
460 if (isset($params['caption']) && (trim($title) != "")) {
461 $params['caption'] = '<h1>'.$title."</h1>".
462 "<p>".$params['caption']."</p>";
465 if (empty($params['caption']) && !empty($siteinfo["description"])) {
466 $params['caption'] = BBCode::convert("[quote]" . $siteinfo["description"] . "[/quote]", false, BBCode::CONNECTORS);
469 $consumer_key = DI::config()->get('tumblr','consumer_key');
470 $consumer_secret = DI::config()->get('tumblr','consumer_secret');
472 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
474 // Make an API call with the TumblrOAuth instance.
475 $x = $tum_oauth->post($tmbl_blog,$params);
476 $ret_code = $tum_oauth->http_code;
479 if ($ret_code == 201) {
480 Logger::log('tumblr_send: success');
481 } elseif ($ret_code == 403) {
482 Logger::log('tumblr_send: authentication failure');
484 Logger::log('tumblr_send: general error: ' . print_r($x,true));