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\PConfig;
19 use Friendica\Core\Renderer;
20 use Friendica\Database\DBA;
22 use Friendica\Util\Strings;
24 function tumblr_install()
26 Hook::register('hook_fork', 'addon/tumblr/tumblr.php', 'tumblr_hook_fork');
27 Hook::register('post_local', 'addon/tumblr/tumblr.php', 'tumblr_post_local');
28 Hook::register('notifier_normal', 'addon/tumblr/tumblr.php', 'tumblr_send');
29 Hook::register('jot_networks', 'addon/tumblr/tumblr.php', 'tumblr_jot_nets');
30 Hook::register('connector_settings', 'addon/tumblr/tumblr.php', 'tumblr_settings');
31 Hook::register('connector_settings_post', 'addon/tumblr/tumblr.php', 'tumblr_settings_post');
34 function tumblr_uninstall()
36 Hook::unregister('hook_fork', 'addon/tumblr/tumblr.php', 'tumblr_hook_fork');
37 Hook::unregister('post_local', 'addon/tumblr/tumblr.php', 'tumblr_post_local');
38 Hook::unregister('notifier_normal', 'addon/tumblr/tumblr.php', 'tumblr_send');
39 Hook::unregister('jot_networks', 'addon/tumblr/tumblr.php', 'tumblr_jot_nets');
40 Hook::unregister('connector_settings', 'addon/tumblr/tumblr.php', 'tumblr_settings');
41 Hook::unregister('connector_settings_post', 'addon/tumblr/tumblr.php', 'tumblr_settings_post');
44 function tumblr_module()
48 function tumblr_content(App $a)
51 notice(L10n::t('Permission denied.') . EOL);
55 if (isset($a->argv[1])) {
56 switch ($a->argv[1]) {
58 $o = tumblr_connect($a);
62 $o = tumblr_callback($a);
66 $o = print_r($a->argv, true);
70 $o = tumblr_connect($a);
76 function tumblr_addon_admin(App $a, &$o)
78 $t = Renderer::getMarkupTemplate( "admin.tpl", "addon/tumblr/" );
80 $o = Renderer::replaceMacros($t, [
81 '$submit' => L10n::t('Save Settings'),
82 // name, label, value, help, [extra values]
83 '$consumer_key' => ['consumer_key', L10n::t('Consumer Key'), Config::get('tumblr', 'consumer_key' ), ''],
84 '$consumer_secret' => ['consumer_secret', L10n::t('Consumer Secret'), Config::get('tumblr', 'consumer_secret' ), ''],
88 function tumblr_addon_admin_post(App $a)
90 $consumer_key = (!empty($_POST['consumer_key']) ? Strings::escapeTags(trim($_POST['consumer_key'])) : '');
91 $consumer_secret = (!empty($_POST['consumer_secret']) ? Strings::escapeTags(trim($_POST['consumer_secret'])): '');
93 Config::set('tumblr', 'consumer_key',$consumer_key);
94 Config::set('tumblr', 'consumer_secret',$consumer_secret);
96 info(L10n::t('Settings updated.'). EOL);
99 function tumblr_connect(App $a)
101 // Start a session. This is necessary to hold on to a few keys the callback script will also need
104 // Include the TumblrOAuth library
105 //require_once('addon/tumblr/tumblroauth/tumblroauth.php');
107 // Define the needed keys
108 $consumer_key = Config::get('tumblr', 'consumer_key');
109 $consumer_secret = Config::get('tumblr', 'consumer_secret');
111 // The callback URL is the script that gets called after the user authenticates with tumblr
112 // In this example, it would be the included callback.php
113 $callback_url = DI::baseUrl()->get()."/tumblr/callback";
115 // Let's begin. First we need a Request Token. The request token is required to send the user
116 // to Tumblr's login page.
118 // Create a new instance of the TumblrOAuth library. For this step, all we need to give the library is our
119 // Consumer Key and Consumer Secret
120 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret);
122 // Ask Tumblr for a Request Token. Specify the Callback URL here too (although this should be optional)
123 $request_token = $tum_oauth->getRequestToken($callback_url);
125 // Store the request token and Request Token Secret as out callback.php script will need this
126 $_SESSION['request_token'] = $token = $request_token['oauth_token'];
127 $_SESSION['request_token_secret'] = $request_token['oauth_token_secret'];
129 // Check the HTTP Code. It should be a 200 (OK), if it's anything else then something didn't work.
130 switch ($tum_oauth->http_code) {
132 // Ask Tumblr to give us a special address to their login page
133 $url = $tum_oauth->getAuthorizeURL($token);
135 // Redirect the user to the login URL given to us by Tumblr
136 header('Location: ' . $url);
139 * That's it for our side. The user is sent to a Tumblr Login page and
140 * asked to authroize our app. After that, Tumblr sends the user back to
141 * our Callback URL (callback.php) along with some information we need to get
147 // Give an error message
148 $o = 'Could not connect to Tumblr. Refresh the page or try again later.';
154 function tumblr_callback(App $a)
156 // Start a session, load the library
158 //require_once('addon/tumblr/tumblroauth/tumblroauth.php');
160 // Define the needed keys
161 $consumer_key = Config::get('tumblr', 'consumer_key');
162 $consumer_secret = Config::get('tumblr', 'consumer_secret');
164 // Once the user approves your app at Tumblr, they are sent back to this script.
165 // This script is passed two parameters in the URL, oauth_token (our Request Token)
166 // and oauth_verifier (Key that we need to get Access Token).
167 // We'll also need out Request Token Secret, which we stored in a session.
169 // Create instance of TumblrOAuth.
170 // It'll need our Consumer Key and Secret as well as our Request Token and Secret
171 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $_SESSION['request_token'], $_SESSION['request_token_secret']);
173 // Ok, let's get an Access Token. We'll need to pass along our oauth_verifier which was given to us in the URL.
174 $access_token = $tum_oauth->getAccessToken($_REQUEST['oauth_verifier']);
176 // We're done with the Request Token and Secret so let's remove those.
177 unset($_SESSION['request_token']);
178 unset($_SESSION['request_token_secret']);
180 // Make sure nothing went wrong.
181 if (200 == $tum_oauth->http_code) {
184 return 'Unable to authenticate';
187 // What's next? Now that we have an Access Token and Secret, we can make an API call.
188 DI::pConfig()->set(local_user(), "tumblr", "oauth_token", $access_token['oauth_token']);
189 DI::pConfig()->set(local_user(), "tumblr", "oauth_token_secret", $access_token['oauth_token_secret']);
191 $o = L10n::t("You are now authenticated to tumblr.");
192 $o .= '<br /><a href="' . DI::baseUrl()->get() . '/settings/connectors">' . L10n::t("return to the connector page") . '</a>';
197 function tumblr_jot_nets(App $a, array &$jotnets_fields)
199 if (! local_user()) {
203 if (DI::pConfig()->get(local_user(),'tumblr','post')) {
204 $jotnets_fields[] = [
205 'type' => 'checkbox',
208 L10n::t('Post to Tumblr'),
209 DI::pConfig()->get(local_user(),'tumblr','post_by_default')
215 function tumblr_settings(App $a, &$s)
217 if (! local_user()) {
221 /* Add our stylesheet to the page so we can make our settings look nice */
223 DI::page()['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . DI::baseUrl()->get() . '/addon/tumblr/tumblr.css' . '" media="all" />' . "\r\n";
225 /* Get the current state of our config variables */
227 $enabled = DI::pConfig()->get(local_user(), 'tumblr', 'post');
228 $checked = (($enabled) ? ' checked="checked" ' : '');
229 $css = (($enabled) ? '' : '-disabled');
231 $def_enabled = DI::pConfig()->get(local_user(), 'tumblr', 'post_by_default');
233 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
235 /* Add some HTML to the existing form */
237 $s .= '<span id="settings_tumblr_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_tumblr_expanded\'); openClose(\'settings_tumblr_inflated\');">';
238 $s .= '<img class="connector'.$css.'" src="images/tumblr.png" /><h3 class="connector">'. L10n::t('Tumblr Export').'</h3>';
240 $s .= '<div id="settings_tumblr_expanded" class="settings-block" style="display: none;">';
241 $s .= '<span class="fakelink" onclick="openClose(\'settings_tumblr_expanded\'); openClose(\'settings_tumblr_inflated\');">';
242 $s .= '<img class="connector'.$css.'" src="images/tumblr.png" /><h3 class="connector">'. L10n::t('Tumblr Export').'</h3>';
245 $s .= '<div id="tumblr-username-wrapper">';
246 $s .= '<a href="'.DI::baseUrl()->get().'/tumblr/connect">'.L10n::t("(Re-)Authenticate your tumblr page").'</a>';
247 $s .= '</div><div class="clear"></div>';
249 $s .= '<div id="tumblr-enable-wrapper">';
250 $s .= '<label id="tumblr-enable-label" for="tumblr-checkbox">' . L10n::t('Enable Tumblr Post Addon') . '</label>';
251 $s .= '<input type="hidden" name="tumblr" value="0"/>';
252 $s .= '<input id="tumblr-checkbox" type="checkbox" name="tumblr" value="1" ' . $checked . '/>';
253 $s .= '</div><div class="clear"></div>';
255 $s .= '<div id="tumblr-bydefault-wrapper">';
256 $s .= '<label id="tumblr-bydefault-label" for="tumblr-bydefault">' . L10n::t('Post to Tumblr by default') . '</label>';
257 $s .= '<input type="hidden" name="tumblr_bydefault" value="0"/>';
258 $s .= '<input id="tumblr-bydefault" type="checkbox" name="tumblr_bydefault" value="1" ' . $def_checked . '/>';
259 $s .= '</div><div class="clear"></div>';
261 $oauth_token = DI::pConfig()->get(local_user(), "tumblr", "oauth_token");
262 $oauth_token_secret = DI::pConfig()->get(local_user(), "tumblr", "oauth_token_secret");
264 $s .= '<div id="tumblr-page-wrapper">';
266 if (($oauth_token != "") && ($oauth_token_secret != "")) {
267 $page = DI::pConfig()->get(local_user(), 'tumblr', 'page');
268 $consumer_key = Config::get('tumblr', 'consumer_key');
269 $consumer_secret = Config::get('tumblr', 'consumer_secret');
271 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
273 $userinfo = $tum_oauth->get('user/info');
277 $s .= '<label id="tumblr-page-label" for="tumblr-page">' . L10n::t('Post to page:') . '</label>';
278 $s .= '<select name="tumblr_page" id="tumblr-page">';
279 foreach($userinfo->response->user->blogs as $blog) {
280 $blogurl = substr(str_replace(["http://", "https://"], ["", ""], $blog->url), 0, -1);
282 if ($page == $blogurl) {
283 $s .= "<option value='".$blogurl."' selected>".$blogurl."</option>";
285 $s .= "<option value='".$blogurl."'>".$blogurl."</option>";
291 $s .= L10n::t("You are not authenticated to tumblr");
294 $s .= '</div><div class="clear"></div>';
296 /* provide a submit button */
297 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="tumblr-submit" name="tumblr-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div></div>';
300 function tumblr_settings_post(App $a, array &$b)
302 if (!empty($_POST['tumblr-submit'])) {
303 DI::pConfig()->set(local_user(), 'tumblr', 'post', intval($_POST['tumblr']));
304 DI::pConfig()->set(local_user(), 'tumblr', 'page', $_POST['tumblr_page']);
305 DI::pConfig()->set(local_user(), 'tumblr', 'post_by_default', intval($_POST['tumblr_bydefault']));
309 function tumblr_hook_fork(&$a, &$b)
311 if ($b['name'] != 'notifier_normal') {
317 if ($post['deleted'] || $post['private'] || ($post['created'] !== $post['edited']) ||
318 !strstr($post['postopts'], 'tumblr') || ($post['parent'] != $post['id'])) {
319 $b['execute'] = false;
324 function tumblr_post_local(App $a, array &$b)
326 // This can probably be changed to allow editing by pointing to a different API endpoint
332 if (!local_user() || (local_user() != $b['uid'])) {
336 if ($b['private'] || $b['parent']) {
340 $tmbl_post = intval(DI::pConfig()->get(local_user(), 'tumblr', 'post'));
342 $tmbl_enable = (($tmbl_post && !empty($_REQUEST['tumblr_enable'])) ? intval($_REQUEST['tumblr_enable']) : 0);
344 if ($b['api_source'] && intval(DI::pConfig()->get(local_user(), 'tumblr', 'post_by_default'))) {
352 if (strlen($b['postopts'])) {
353 $b['postopts'] .= ',';
356 $b['postopts'] .= 'tumblr';
362 function tumblr_send(App $a, array &$b) {
364 if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) {
368 if (! strstr($b['postopts'],'tumblr')) {
372 if ($b['parent'] != $b['id']) {
376 // Dont't post if the post doesn't belong to us.
377 // This is a check for forum postings
378 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
379 if ($b['contact-id'] != $self['id']) {
383 $oauth_token = DI::pConfig()->get($b['uid'], "tumblr", "oauth_token");
384 $oauth_token_secret = DI::pConfig()->get($b['uid'], "tumblr", "oauth_token_secret");
385 $page = DI::pConfig()->get($b['uid'], "tumblr", "page");
386 $tmbl_blog = 'blog/' . $page . '/post';
388 if ($oauth_token && $oauth_token_secret && $tmbl_blog) {
391 preg_match_all('/\#\[(.*?)\](.*?)\[/', $b['tag'], $matches, PREG_SET_ORDER);
393 if (!empty($matches)) {
394 foreach($matches as $mtch) {
395 $tag_arr[] = $mtch[2];
399 if (count($tag_arr)) {
400 $tags = implode(',', $tag_arr);
403 $title = trim($b['title']);
405 $siteinfo = BBCode::getAttachedData($b["body"]);
408 'state' => 'published',
414 if (!isset($siteinfo["type"])) {
415 $siteinfo["type"] = "";
418 if (($title == "") && isset($siteinfo["title"])) {
419 $title = $siteinfo["title"];
422 if (isset($siteinfo["text"])) {
423 $body = $siteinfo["text"];
425 $body = BBCode::removeShareInformation($b["body"]);
428 switch ($siteinfo["type"]) {
430 $params['type'] = "photo";
431 $params['caption'] = BBCode::convert($body, false, 4);
433 if (isset($siteinfo["url"])) {
434 $params['link'] = $siteinfo["url"];
437 $params['source'] = $siteinfo["image"];
441 $params['type'] = "link";
442 $params['title'] = $title;
443 $params['url'] = $siteinfo["url"];
444 $params['description'] = BBCode::convert($body, false, 4);
448 $params['type'] = "audio";
449 $params['external_url'] = $siteinfo["url"];
450 $params['caption'] = BBCode::convert($body, false, 4);
454 $params['type'] = "video";
455 $params['embed'] = $siteinfo["url"];
456 $params['caption'] = BBCode::convert($body, false, 4);
460 $params['type'] = "text";
461 $params['title'] = $title;
462 $params['body'] = BBCode::convert($b['body'], false, 4);
466 if (isset($params['caption']) && (trim($title) != "")) {
467 $params['caption'] = '<h1>'.$title."</h1>".
468 "<p>".$params['caption']."</p>";
471 if (empty($params['caption']) && !empty($siteinfo["description"])) {
472 $params['caption'] = BBCode::convert("[quote]" . $siteinfo["description"] . "[/quote]", false, 4);
475 $consumer_key = Config::get('tumblr','consumer_key');
476 $consumer_secret = Config::get('tumblr','consumer_secret');
478 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
480 // Make an API call with the TumblrOAuth instance.
481 $x = $tum_oauth->post($tmbl_blog,$params);
482 $ret_code = $tum_oauth->http_code;
485 if ($ret_code == 201) {
486 Logger::log('tumblr_send: success');
487 } elseif ($ret_code == 403) {
488 Logger::log('tumblr_send: authentication failure');
490 Logger::log('tumblr_send: general error: ' . print_r($x,true));