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\Config;
15 use Friendica\Core\Hook;
16 use Friendica\Core\L10n;
17 use Friendica\Core\Logger;
18 use Friendica\Core\Renderer;
19 use Friendica\Database\DBA;
21 use Friendica\Util\Strings;
23 function tumblr_install()
25 Hook::register('hook_fork', 'addon/tumblr/tumblr.php', 'tumblr_hook_fork');
26 Hook::register('post_local', 'addon/tumblr/tumblr.php', 'tumblr_post_local');
27 Hook::register('notifier_normal', 'addon/tumblr/tumblr.php', 'tumblr_send');
28 Hook::register('jot_networks', 'addon/tumblr/tumblr.php', 'tumblr_jot_nets');
29 Hook::register('connector_settings', 'addon/tumblr/tumblr.php', 'tumblr_settings');
30 Hook::register('connector_settings_post', 'addon/tumblr/tumblr.php', 'tumblr_settings_post');
33 function tumblr_uninstall()
35 Hook::unregister('hook_fork', 'addon/tumblr/tumblr.php', 'tumblr_hook_fork');
36 Hook::unregister('post_local', 'addon/tumblr/tumblr.php', 'tumblr_post_local');
37 Hook::unregister('notifier_normal', 'addon/tumblr/tumblr.php', 'tumblr_send');
38 Hook::unregister('jot_networks', 'addon/tumblr/tumblr.php', 'tumblr_jot_nets');
39 Hook::unregister('connector_settings', 'addon/tumblr/tumblr.php', 'tumblr_settings');
40 Hook::unregister('connector_settings_post', 'addon/tumblr/tumblr.php', 'tumblr_settings_post');
43 function tumblr_module()
47 function tumblr_content(App $a)
50 notice(DI::l10n()->t('Permission denied.') . EOL);
54 if (isset($a->argv[1])) {
55 switch ($a->argv[1]) {
57 $o = tumblr_connect($a);
61 $o = tumblr_callback($a);
65 $o = print_r($a->argv, true);
69 $o = tumblr_connect($a);
75 function tumblr_addon_admin(App $a, &$o)
77 $t = Renderer::getMarkupTemplate( "admin.tpl", "addon/tumblr/" );
79 $o = Renderer::replaceMacros($t, [
80 '$submit' => DI::l10n()->t('Save Settings'),
81 // name, label, value, help, [extra values]
82 '$consumer_key' => ['consumer_key', DI::l10n()->t('Consumer Key'), Config::get('tumblr', 'consumer_key' ), ''],
83 '$consumer_secret' => ['consumer_secret', DI::l10n()->t('Consumer Secret'), Config::get('tumblr', 'consumer_secret' ), ''],
87 function tumblr_addon_admin_post(App $a)
89 $consumer_key = (!empty($_POST['consumer_key']) ? Strings::escapeTags(trim($_POST['consumer_key'])) : '');
90 $consumer_secret = (!empty($_POST['consumer_secret']) ? Strings::escapeTags(trim($_POST['consumer_secret'])): '');
92 Config::set('tumblr', 'consumer_key',$consumer_key);
93 Config::set('tumblr', 'consumer_secret',$consumer_secret);
95 info(DI::l10n()->t('Settings updated.'). EOL);
98 function tumblr_connect(App $a)
100 // Start a session. This is necessary to hold on to a few keys the callback script will also need
103 // Include the TumblrOAuth library
104 //require_once('addon/tumblr/tumblroauth/tumblroauth.php');
106 // Define the needed keys
107 $consumer_key = Config::get('tumblr', 'consumer_key');
108 $consumer_secret = Config::get('tumblr', 'consumer_secret');
110 // The callback URL is the script that gets called after the user authenticates with tumblr
111 // In this example, it would be the included callback.php
112 $callback_url = DI::baseUrl()->get()."/tumblr/callback";
114 // Let's begin. First we need a Request Token. The request token is required to send the user
115 // to Tumblr's login page.
117 // Create a new instance of the TumblrOAuth library. For this step, all we need to give the library is our
118 // Consumer Key and Consumer Secret
119 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret);
121 // Ask Tumblr for a Request Token. Specify the Callback URL here too (although this should be optional)
122 $request_token = $tum_oauth->getRequestToken($callback_url);
124 // Store the request token and Request Token Secret as out callback.php script will need this
125 $_SESSION['request_token'] = $token = $request_token['oauth_token'];
126 $_SESSION['request_token_secret'] = $request_token['oauth_token_secret'];
128 // Check the HTTP Code. It should be a 200 (OK), if it's anything else then something didn't work.
129 switch ($tum_oauth->http_code) {
131 // Ask Tumblr to give us a special address to their login page
132 $url = $tum_oauth->getAuthorizeURL($token);
134 // Redirect the user to the login URL given to us by Tumblr
135 header('Location: ' . $url);
138 * That's it for our side. The user is sent to a Tumblr Login page and
139 * asked to authroize our app. After that, Tumblr sends the user back to
140 * our Callback URL (callback.php) along with some information we need to get
146 // Give an error message
147 $o = 'Could not connect to Tumblr. Refresh the page or try again later.';
153 function tumblr_callback(App $a)
155 // Start a session, load the library
157 //require_once('addon/tumblr/tumblroauth/tumblroauth.php');
159 // Define the needed keys
160 $consumer_key = Config::get('tumblr', 'consumer_key');
161 $consumer_secret = Config::get('tumblr', 'consumer_secret');
163 // Once the user approves your app at Tumblr, they are sent back to this script.
164 // This script is passed two parameters in the URL, oauth_token (our Request Token)
165 // and oauth_verifier (Key that we need to get Access Token).
166 // We'll also need out Request Token Secret, which we stored in a session.
168 // Create instance of TumblrOAuth.
169 // It'll need our Consumer Key and Secret as well as our Request Token and Secret
170 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $_SESSION['request_token'], $_SESSION['request_token_secret']);
172 // Ok, let's get an Access Token. We'll need to pass along our oauth_verifier which was given to us in the URL.
173 $access_token = $tum_oauth->getAccessToken($_REQUEST['oauth_verifier']);
175 // We're done with the Request Token and Secret so let's remove those.
176 unset($_SESSION['request_token']);
177 unset($_SESSION['request_token_secret']);
179 // Make sure nothing went wrong.
180 if (200 == $tum_oauth->http_code) {
183 return 'Unable to authenticate';
186 // What's next? Now that we have an Access Token and Secret, we can make an API call.
187 DI::pConfig()->set(local_user(), "tumblr", "oauth_token", $access_token['oauth_token']);
188 DI::pConfig()->set(local_user(), "tumblr", "oauth_token_secret", $access_token['oauth_token_secret']);
190 $o = DI::l10n()->t("You are now authenticated to tumblr.");
191 $o .= '<br /><a href="' . DI::baseUrl()->get() . '/settings/connectors">' . DI::l10n()->t("return to the connector page") . '</a>';
196 function tumblr_jot_nets(App $a, array &$jotnets_fields)
198 if (! local_user()) {
202 if (DI::pConfig()->get(local_user(),'tumblr','post')) {
203 $jotnets_fields[] = [
204 'type' => 'checkbox',
207 DI::l10n()->t('Post to Tumblr'),
208 DI::pConfig()->get(local_user(),'tumblr','post_by_default')
214 function tumblr_settings(App $a, &$s)
216 if (! local_user()) {
220 /* Add our stylesheet to the page so we can make our settings look nice */
222 DI::page()['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . DI::baseUrl()->get() . '/addon/tumblr/tumblr.css' . '" media="all" />' . "\r\n";
224 /* Get the current state of our config variables */
226 $enabled = DI::pConfig()->get(local_user(), 'tumblr', 'post');
227 $checked = (($enabled) ? ' checked="checked" ' : '');
228 $css = (($enabled) ? '' : '-disabled');
230 $def_enabled = DI::pConfig()->get(local_user(), 'tumblr', 'post_by_default');
232 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
234 /* Add some HTML to the existing form */
236 $s .= '<span id="settings_tumblr_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_tumblr_expanded\'); openClose(\'settings_tumblr_inflated\');">';
237 $s .= '<img class="connector'.$css.'" src="images/tumblr.png" /><h3 class="connector">'. DI::l10n()->t('Tumblr Export').'</h3>';
239 $s .= '<div id="settings_tumblr_expanded" class="settings-block" style="display: none;">';
240 $s .= '<span class="fakelink" onclick="openClose(\'settings_tumblr_expanded\'); openClose(\'settings_tumblr_inflated\');">';
241 $s .= '<img class="connector'.$css.'" src="images/tumblr.png" /><h3 class="connector">'. DI::l10n()->t('Tumblr Export').'</h3>';
244 $s .= '<div id="tumblr-username-wrapper">';
245 $s .= '<a href="'.DI::baseUrl()->get().'/tumblr/connect">'.DI::l10n()->t("(Re-)Authenticate your tumblr page").'</a>';
246 $s .= '</div><div class="clear"></div>';
248 $s .= '<div id="tumblr-enable-wrapper">';
249 $s .= '<label id="tumblr-enable-label" for="tumblr-checkbox">' . DI::l10n()->t('Enable Tumblr Post Addon') . '</label>';
250 $s .= '<input type="hidden" name="tumblr" value="0"/>';
251 $s .= '<input id="tumblr-checkbox" type="checkbox" name="tumblr" value="1" ' . $checked . '/>';
252 $s .= '</div><div class="clear"></div>';
254 $s .= '<div id="tumblr-bydefault-wrapper">';
255 $s .= '<label id="tumblr-bydefault-label" for="tumblr-bydefault">' . DI::l10n()->t('Post to Tumblr by default') . '</label>';
256 $s .= '<input type="hidden" name="tumblr_bydefault" value="0"/>';
257 $s .= '<input id="tumblr-bydefault" type="checkbox" name="tumblr_bydefault" value="1" ' . $def_checked . '/>';
258 $s .= '</div><div class="clear"></div>';
260 $oauth_token = DI::pConfig()->get(local_user(), "tumblr", "oauth_token");
261 $oauth_token_secret = DI::pConfig()->get(local_user(), "tumblr", "oauth_token_secret");
263 $s .= '<div id="tumblr-page-wrapper">';
265 if (($oauth_token != "") && ($oauth_token_secret != "")) {
266 $page = DI::pConfig()->get(local_user(), 'tumblr', 'page');
267 $consumer_key = Config::get('tumblr', 'consumer_key');
268 $consumer_secret = Config::get('tumblr', 'consumer_secret');
270 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
272 $userinfo = $tum_oauth->get('user/info');
276 $s .= '<label id="tumblr-page-label" for="tumblr-page">' . DI::l10n()->t('Post to page:') . '</label>';
277 $s .= '<select name="tumblr_page" id="tumblr-page">';
278 foreach($userinfo->response->user->blogs as $blog) {
279 $blogurl = substr(str_replace(["http://", "https://"], ["", ""], $blog->url), 0, -1);
281 if ($page == $blogurl) {
282 $s .= "<option value='".$blogurl."' selected>".$blogurl."</option>";
284 $s .= "<option value='".$blogurl."'>".$blogurl."</option>";
290 $s .= DI::l10n()->t("You are not authenticated to tumblr");
293 $s .= '</div><div class="clear"></div>';
295 /* provide a submit button */
296 $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>';
299 function tumblr_settings_post(App $a, array &$b)
301 if (!empty($_POST['tumblr-submit'])) {
302 DI::pConfig()->set(local_user(), 'tumblr', 'post', intval($_POST['tumblr']));
303 DI::pConfig()->set(local_user(), 'tumblr', 'page', $_POST['tumblr_page']);
304 DI::pConfig()->set(local_user(), 'tumblr', 'post_by_default', intval($_POST['tumblr_bydefault']));
308 function tumblr_hook_fork(&$a, &$b)
310 if ($b['name'] != 'notifier_normal') {
316 if ($post['deleted'] || $post['private'] || ($post['created'] !== $post['edited']) ||
317 !strstr($post['postopts'], 'tumblr') || ($post['parent'] != $post['id'])) {
318 $b['execute'] = false;
323 function tumblr_post_local(App $a, array &$b)
325 // This can probably be changed to allow editing by pointing to a different API endpoint
331 if (!local_user() || (local_user() != $b['uid'])) {
335 if ($b['private'] || $b['parent']) {
339 $tmbl_post = intval(DI::pConfig()->get(local_user(), 'tumblr', 'post'));
341 $tmbl_enable = (($tmbl_post && !empty($_REQUEST['tumblr_enable'])) ? intval($_REQUEST['tumblr_enable']) : 0);
343 if ($b['api_source'] && intval(DI::pConfig()->get(local_user(), 'tumblr', 'post_by_default'))) {
351 if (strlen($b['postopts'])) {
352 $b['postopts'] .= ',';
355 $b['postopts'] .= 'tumblr';
361 function tumblr_send(App $a, array &$b) {
363 if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) {
367 if (! strstr($b['postopts'],'tumblr')) {
371 if ($b['parent'] != $b['id']) {
375 // Dont't post if the post doesn't belong to us.
376 // This is a check for forum postings
377 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
378 if ($b['contact-id'] != $self['id']) {
382 $oauth_token = DI::pConfig()->get($b['uid'], "tumblr", "oauth_token");
383 $oauth_token_secret = DI::pConfig()->get($b['uid'], "tumblr", "oauth_token_secret");
384 $page = DI::pConfig()->get($b['uid'], "tumblr", "page");
385 $tmbl_blog = 'blog/' . $page . '/post';
387 if ($oauth_token && $oauth_token_secret && $tmbl_blog) {
390 preg_match_all('/\#\[(.*?)\](.*?)\[/', $b['tag'], $matches, PREG_SET_ORDER);
392 if (!empty($matches)) {
393 foreach($matches as $mtch) {
394 $tag_arr[] = $mtch[2];
398 if (count($tag_arr)) {
399 $tags = implode(',', $tag_arr);
402 $title = trim($b['title']);
404 $siteinfo = BBCode::getAttachedData($b["body"]);
407 'state' => 'published',
413 if (!isset($siteinfo["type"])) {
414 $siteinfo["type"] = "";
417 if (($title == "") && isset($siteinfo["title"])) {
418 $title = $siteinfo["title"];
421 if (isset($siteinfo["text"])) {
422 $body = $siteinfo["text"];
424 $body = BBCode::removeShareInformation($b["body"]);
427 switch ($siteinfo["type"]) {
429 $params['type'] = "photo";
430 $params['caption'] = BBCode::convert($body, false, 4);
432 if (isset($siteinfo["url"])) {
433 $params['link'] = $siteinfo["url"];
436 $params['source'] = $siteinfo["image"];
440 $params['type'] = "link";
441 $params['title'] = $title;
442 $params['url'] = $siteinfo["url"];
443 $params['description'] = BBCode::convert($body, false, 4);
447 $params['type'] = "audio";
448 $params['external_url'] = $siteinfo["url"];
449 $params['caption'] = BBCode::convert($body, false, 4);
453 $params['type'] = "video";
454 $params['embed'] = $siteinfo["url"];
455 $params['caption'] = BBCode::convert($body, false, 4);
459 $params['type'] = "text";
460 $params['title'] = $title;
461 $params['body'] = BBCode::convert($b['body'], false, 4);
465 if (isset($params['caption']) && (trim($title) != "")) {
466 $params['caption'] = '<h1>'.$title."</h1>".
467 "<p>".$params['caption']."</p>";
470 if (empty($params['caption']) && !empty($siteinfo["description"])) {
471 $params['caption'] = BBCode::convert("[quote]" . $siteinfo["description"] . "[/quote]", false, 4);
474 $consumer_key = Config::get('tumblr','consumer_key');
475 $consumer_secret = Config::get('tumblr','consumer_secret');
477 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
479 // Make an API call with the TumblrOAuth instance.
480 $x = $tum_oauth->post($tmbl_blog,$params);
481 $ret_code = $tum_oauth->http_code;
484 if ($ret_code == 201) {
485 Logger::log('tumblr_send: success');
486 } elseif ($ret_code == 403) {
487 Logger::log('tumblr_send: authentication failure');
489 Logger::log('tumblr_send: general error: ' . print_r($x,true));