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\Addon;
15 use Friendica\Core\Config;
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;
21 use Friendica\Util\Strings;
23 function tumblr_install()
25 Addon::registerHook('post_local', 'addon/tumblr/tumblr.php', 'tumblr_post_local');
26 Addon::registerHook('notifier_normal', 'addon/tumblr/tumblr.php', 'tumblr_send');
27 Addon::registerHook('jot_networks', 'addon/tumblr/tumblr.php', 'tumblr_jot_nets');
28 Addon::registerHook('connector_settings', 'addon/tumblr/tumblr.php', 'tumblr_settings');
29 Addon::registerHook('connector_settings_post', 'addon/tumblr/tumblr.php', 'tumblr_settings_post');
32 function tumblr_uninstall()
34 Addon::unregisterHook('post_local', 'addon/tumblr/tumblr.php', 'tumblr_post_local');
35 Addon::unregisterHook('notifier_normal', 'addon/tumblr/tumblr.php', 'tumblr_send');
36 Addon::unregisterHook('jot_networks', 'addon/tumblr/tumblr.php', 'tumblr_jot_nets');
37 Addon::unregisterHook('connector_settings', 'addon/tumblr/tumblr.php', 'tumblr_settings');
38 Addon::unregisterHook('connector_settings_post', 'addon/tumblr/tumblr.php', 'tumblr_settings_post');
41 function tumblr_module()
45 function tumblr_content(App $a)
48 notice(L10n::t('Permission denied.') . EOL);
52 if (isset($a->argv[1])) {
53 switch ($a->argv[1]) {
55 $o = tumblr_connect($a);
59 $o = tumblr_callback($a);
63 $o = print_r($a->argv, true);
67 $o = tumblr_connect($a);
73 function tumblr_addon_admin(App $a, &$o)
75 $t = Renderer::getMarkupTemplate( "admin.tpl", "addon/tumblr/" );
77 $o = Renderer::replaceMacros($t, [
78 '$submit' => L10n::t('Save Settings'),
79 // name, label, value, help, [extra values]
80 '$consumer_key' => ['consumer_key', L10n::t('Consumer Key'), Config::get('tumblr', 'consumer_key' ), ''],
81 '$consumer_secret' => ['consumer_secret', L10n::t('Consumer Secret'), Config::get('tumblr', 'consumer_secret' ), ''],
85 function tumblr_addon_admin_post(App $a)
87 $consumer_key = ((!empty($_POST['consumer_key'])) ? Strings::escapeTags(trim($_POST['consumer_key'])) : '');
88 $consumer_secret = ((!empty($_POST['consumer_secret'])) ? Strings::escapeTags(trim($_POST['consumer_secret'])): '');
90 Config::set('tumblr', 'consumer_key',$consumer_key);
91 Config::set('tumblr', 'consumer_secret',$consumer_secret);
93 info(L10n::t('Settings updated.'). EOL);
96 function tumblr_connect(App $a)
98 // Start a session. This is necessary to hold on to a few keys the callback script will also need
101 // Include the TumblrOAuth library
102 //require_once('addon/tumblr/tumblroauth/tumblroauth.php');
104 // Define the needed keys
105 $consumer_key = Config::get('tumblr', 'consumer_key');
106 $consumer_secret = Config::get('tumblr', 'consumer_secret');
108 // The callback URL is the script that gets called after the user authenticates with tumblr
109 // In this example, it would be the included callback.php
110 $callback_url = $a->getBaseURL()."/tumblr/callback";
112 // Let's begin. First we need a Request Token. The request token is required to send the user
113 // to Tumblr's login page.
115 // Create a new instance of the TumblrOAuth library. For this step, all we need to give the library is our
116 // Consumer Key and Consumer Secret
117 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret);
119 // Ask Tumblr for a Request Token. Specify the Callback URL here too (although this should be optional)
120 $request_token = $tum_oauth->getRequestToken($callback_url);
122 // Store the request token and Request Token Secret as out callback.php script will need this
123 $_SESSION['request_token'] = $token = $request_token['oauth_token'];
124 $_SESSION['request_token_secret'] = $request_token['oauth_token_secret'];
126 // Check the HTTP Code. It should be a 200 (OK), if it's anything else then something didn't work.
127 switch ($tum_oauth->http_code) {
129 // Ask Tumblr to give us a special address to their login page
130 $url = $tum_oauth->getAuthorizeURL($token);
132 // Redirect the user to the login URL given to us by Tumblr
133 header('Location: ' . $url);
136 * That's it for our side. The user is sent to a Tumblr Login page and
137 * asked to authroize our app. After that, Tumblr sends the user back to
138 * our Callback URL (callback.php) along with some information we need to get
144 // Give an error message
145 $o = 'Could not connect to Tumblr. Refresh the page or try again later.';
151 function tumblr_callback(App $a)
153 // Start a session, load the library
155 //require_once('addon/tumblr/tumblroauth/tumblroauth.php');
157 // Define the needed keys
158 $consumer_key = Config::get('tumblr', 'consumer_key');
159 $consumer_secret = Config::get('tumblr', 'consumer_secret');
161 // Once the user approves your app at Tumblr, they are sent back to this script.
162 // This script is passed two parameters in the URL, oauth_token (our Request Token)
163 // and oauth_verifier (Key that we need to get Access Token).
164 // We'll also need out Request Token Secret, which we stored in a session.
166 // Create instance of TumblrOAuth.
167 // It'll need our Consumer Key and Secret as well as our Request Token and Secret
168 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $_SESSION['request_token'], $_SESSION['request_token_secret']);
170 // Ok, let's get an Access Token. We'll need to pass along our oauth_verifier which was given to us in the URL.
171 $access_token = $tum_oauth->getAccessToken($_REQUEST['oauth_verifier']);
173 // We're done with the Request Token and Secret so let's remove those.
174 unset($_SESSION['request_token']);
175 unset($_SESSION['request_token_secret']);
177 // Make sure nothing went wrong.
178 if (200 == $tum_oauth->http_code) {
181 return 'Unable to authenticate';
184 // What's next? Now that we have an Access Token and Secret, we can make an API call.
185 PConfig::set(local_user(), "tumblr", "oauth_token", $access_token['oauth_token']);
186 PConfig::set(local_user(), "tumblr", "oauth_token_secret", $access_token['oauth_token_secret']);
188 $o = L10n::t("You are now authenticated to tumblr.");
189 $o .= '<br /><a href="'.$a->getBaseURL().'/settings/connectors">'.L10n::t("return to the connector page").'</a>';
194 function tumblr_jot_nets(App $a, &$b)
196 if (! local_user()) {
200 $tmbl_post = PConfig::get(local_user(), 'tumblr', 'post');
202 if (intval($tmbl_post) == 1) {
203 $tmbl_defpost = PConfig::get(local_user(), 'tumblr', 'post_by_default');
204 $selected = ((intval($tmbl_defpost) == 1) ? ' checked="checked" ' : '');
205 $b .= '<div class="profile-jot-net"><input type="checkbox" name="tumblr_enable"' . $selected . ' value="1" /> '
206 . L10n::t('Post to Tumblr') . '</div>';
210 function tumblr_settings(App $a, &$s)
212 if (! local_user()) {
216 /* Add our stylesheet to the page so we can make our settings look nice */
218 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->getBaseURL() . '/addon/tumblr/tumblr.css' . '" media="all" />' . "\r\n";
220 /* Get the current state of our config variables */
222 $enabled = PConfig::get(local_user(), 'tumblr', 'post');
223 $checked = (($enabled) ? ' checked="checked" ' : '');
224 $css = (($enabled) ? '' : '-disabled');
226 $def_enabled = PConfig::get(local_user(), 'tumblr', 'post_by_default');
228 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
230 /* Add some HTML to the existing form */
232 $s .= '<span id="settings_tumblr_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_tumblr_expanded\'); openClose(\'settings_tumblr_inflated\');">';
233 $s .= '<img class="connector'.$css.'" src="images/tumblr.png" /><h3 class="connector">'. L10n::t('Tumblr Export').'</h3>';
235 $s .= '<div id="settings_tumblr_expanded" class="settings-block" style="display: none;">';
236 $s .= '<span class="fakelink" onclick="openClose(\'settings_tumblr_expanded\'); openClose(\'settings_tumblr_inflated\');">';
237 $s .= '<img class="connector'.$css.'" src="images/tumblr.png" /><h3 class="connector">'. L10n::t('Tumblr Export').'</h3>';
240 $s .= '<div id="tumblr-username-wrapper">';
241 $s .= '<a href="'.$a->getBaseURL().'/tumblr/connect">'.L10n::t("(Re-)Authenticate your tumblr page").'</a>';
242 $s .= '</div><div class="clear"></div>';
244 $s .= '<div id="tumblr-enable-wrapper">';
245 $s .= '<label id="tumblr-enable-label" for="tumblr-checkbox">' . L10n::t('Enable Tumblr Post Addon') . '</label>';
246 $s .= '<input id="tumblr-checkbox" type="checkbox" name="tumblr" value="1" ' . $checked . '/>';
247 $s .= '</div><div class="clear"></div>';
249 $s .= '<div id="tumblr-bydefault-wrapper">';
250 $s .= '<label id="tumblr-bydefault-label" for="tumblr-bydefault">' . L10n::t('Post to Tumblr by default') . '</label>';
251 $s .= '<input id="tumblr-bydefault" type="checkbox" name="tumblr_bydefault" value="1" ' . $def_checked . '/>';
252 $s .= '</div><div class="clear"></div>';
254 $oauth_token = PConfig::get(local_user(), "tumblr", "oauth_token");
255 $oauth_token_secret = PConfig::get(local_user(), "tumblr", "oauth_token_secret");
257 $s .= '<div id="tumblr-page-wrapper">';
259 if (($oauth_token != "") && ($oauth_token_secret != "")) {
260 $page = PConfig::get(local_user(), 'tumblr', 'page');
261 $consumer_key = Config::get('tumblr', 'consumer_key');
262 $consumer_secret = Config::get('tumblr', 'consumer_secret');
264 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
266 $userinfo = $tum_oauth->get('user/info');
270 $s .= '<label id="tumblr-page-label" for="tumblr-page">' . L10n::t('Post to page:') . '</label>';
271 $s .= '<select name="tumblr_page" id="tumblr-page">';
272 foreach($userinfo->response->user->blogs as $blog) {
273 $blogurl = substr(str_replace(["http://", "https://"], ["", ""], $blog->url), 0, -1);
275 if ($page == $blogurl) {
276 $s .= "<option value='".$blogurl."' selected>".$blogurl."</option>";
278 $s .= "<option value='".$blogurl."'>".$blogurl."</option>";
284 $s .= L10n::t("You are not authenticated to tumblr");
287 $s .= '</div><div class="clear"></div>';
289 /* provide a submit button */
290 $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>';
293 function tumblr_settings_post(App $a, array &$b)
295 if (!empty($_POST['tumblr-submit'])) {
296 PConfig::set(local_user(), 'tumblr', 'post', intval($_POST['tumblr']));
297 PConfig::set(local_user(), 'tumblr', 'page', $_POST['tumblr_page']);
298 PConfig::set(local_user(), 'tumblr', 'post_by_default', intval($_POST['tumblr_bydefault']));
302 function tumblr_post_local(App $a, array &$b)
304 // This can probably be changed to allow editing by pointing to a different API endpoint
310 if (!local_user() || (local_user() != $b['uid'])) {
314 if ($b['private'] || $b['parent']) {
318 $tmbl_post = intval(PConfig::get(local_user(), 'tumblr', 'post'));
320 $tmbl_enable = (($tmbl_post && !empty($_REQUEST['tumblr_enable'])) ? intval($_REQUEST['tumblr_enable']) : 0);
322 if ($b['api_source'] && intval(PConfig::get(local_user(), 'tumblr', 'post_by_default'))) {
330 if (strlen($b['postopts'])) {
331 $b['postopts'] .= ',';
334 $b['postopts'] .= 'tumblr';
340 function tumblr_send(App $a, array &$b) {
342 if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) {
346 if (! strstr($b['postopts'],'tumblr')) {
350 if ($b['parent'] != $b['id']) {
354 // Dont't post if the post doesn't belong to us.
355 // This is a check for forum postings
356 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
357 if ($b['contact-id'] != $self['id']) {
361 $oauth_token = PConfig::get($b['uid'], "tumblr", "oauth_token");
362 $oauth_token_secret = PConfig::get($b['uid'], "tumblr", "oauth_token_secret");
363 $page = PConfig::get($b['uid'], "tumblr", "page");
364 $tmbl_blog = 'blog/' . $page . '/post';
366 if ($oauth_token && $oauth_token_secret && $tmbl_blog) {
369 preg_match_all('/\#\[(.*?)\](.*?)\[/', $b['tag'], $matches, PREG_SET_ORDER);
371 if (!empty($matches)) {
372 foreach($matches as $mtch) {
373 $tag_arr[] = $mtch[2];
377 if (count($tag_arr)) {
378 $tags = implode(',', $tag_arr);
381 $title = trim($b['title']);
383 $siteinfo = BBCode::getAttachedData($b["body"]);
386 'state' => 'published',
392 if (!isset($siteinfo["type"])) {
393 $siteinfo["type"] = "";
396 if (($title == "") && isset($siteinfo["title"])) {
397 $title = $siteinfo["title"];
400 if (isset($siteinfo["text"])) {
401 $body = $siteinfo["text"];
403 $body = BBCode::removeShareInformation($b["body"]);
406 switch ($siteinfo["type"]) {
408 $params['type'] = "photo";
409 $params['caption'] = BBCode::convert($body, false, 4);
411 if (isset($siteinfo["url"])) {
412 $params['link'] = $siteinfo["url"];
415 $params['source'] = $siteinfo["image"];
419 $params['type'] = "link";
420 $params['title'] = $title;
421 $params['url'] = $siteinfo["url"];
422 $params['description'] = BBCode::convert($body, false, 4);
426 $params['type'] = "audio";
427 $params['external_url'] = $siteinfo["url"];
428 $params['caption'] = BBCode::convert($body, false, 4);
432 $params['type'] = "video";
433 $params['embed'] = $siteinfo["url"];
434 $params['caption'] = BBCode::convert($body, false, 4);
438 $params['type'] = "text";
439 $params['title'] = $title;
440 $params['body'] = BBCode::convert($b['body'], false, 4);
444 if (isset($params['caption']) && (trim($title) != "")) {
445 $params['caption'] = '<h1>'.$title."</h1>".
446 "<p>".$params['caption']."</p>";
449 if (empty($params['caption']) && !empty($siteinfo["description"])) {
450 $params['caption'] = BBCode::convert("[quote]" . $siteinfo["description"] . "[/quote]", false, 4);
453 $consumer_key = Config::get('tumblr','consumer_key');
454 $consumer_secret = Config::get('tumblr','consumer_secret');
456 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
458 // Make an API call with the TumblrOAuth instance.
459 $x = $tum_oauth->post($tmbl_blog,$params);
460 $ret_code = $tum_oauth->http_code;
463 if ($ret_code == 201) {
464 Logger::log('tumblr_send: success');
465 } elseif ($ret_code == 403) {
466 Logger::log('tumblr_send: authentication failure');
468 Logger::log('tumblr_send: general error: ' . print_r($x,true));