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\Database\DBA;
21 function tumblr_install()
23 Addon::registerHook('post_local', 'addon/tumblr/tumblr.php', 'tumblr_post_local');
24 Addon::registerHook('notifier_normal', 'addon/tumblr/tumblr.php', 'tumblr_send');
25 Addon::registerHook('jot_networks', 'addon/tumblr/tumblr.php', 'tumblr_jot_nets');
26 Addon::registerHook('connector_settings', 'addon/tumblr/tumblr.php', 'tumblr_settings');
27 Addon::registerHook('connector_settings_post', 'addon/tumblr/tumblr.php', 'tumblr_settings_post');
30 function tumblr_uninstall()
32 Addon::unregisterHook('post_local', 'addon/tumblr/tumblr.php', 'tumblr_post_local');
33 Addon::unregisterHook('notifier_normal', 'addon/tumblr/tumblr.php', 'tumblr_send');
34 Addon::unregisterHook('jot_networks', 'addon/tumblr/tumblr.php', 'tumblr_jot_nets');
35 Addon::unregisterHook('connector_settings', 'addon/tumblr/tumblr.php', 'tumblr_settings');
36 Addon::unregisterHook('connector_settings_post', 'addon/tumblr/tumblr.php', 'tumblr_settings_post');
39 function tumblr_module()
43 function tumblr_content(App $a)
46 notice(L10n::t('Permission denied.') . EOL);
50 if (isset($a->argv[1])) {
51 switch ($a->argv[1]) {
53 $o = tumblr_connect($a);
57 $o = tumblr_callback($a);
61 $o = print_r($a->argv, true);
65 $o = tumblr_connect($a);
71 function tumblr_addon_admin(App $a, &$o)
73 $t = get_markup_template( "admin.tpl", "addon/tumblr/" );
75 $o = replace_macros($t, [
76 '$submit' => L10n::t('Save Settings'),
77 // name, label, value, help, [extra values]
78 '$consumer_key' => ['consumer_key', L10n::t('Consumer Key'), Config::get('tumblr', 'consumer_key' ), ''],
79 '$consumer_secret' => ['consumer_secret', L10n::t('Consumer Secret'), Config::get('tumblr', 'consumer_secret' ), ''],
83 function tumblr_addon_admin_post(App $a)
85 $consumer_key = ((!empty($_POST['consumer_key'])) ? notags(trim($_POST['consumer_key'])) : '');
86 $consumer_secret = ((!empty($_POST['consumer_secret'])) ? notags(trim($_POST['consumer_secret'])): '');
88 Config::set('tumblr', 'consumer_key',$consumer_key);
89 Config::set('tumblr', 'consumer_secret',$consumer_secret);
91 info(L10n::t('Settings updated.'). EOL);
94 function tumblr_connect(App $a)
96 // Start a session. This is necessary to hold on to a few keys the callback script will also need
99 // Include the TumblrOAuth library
100 //require_once('addon/tumblr/tumblroauth/tumblroauth.php');
102 // Define the needed keys
103 $consumer_key = Config::get('tumblr', 'consumer_key');
104 $consumer_secret = Config::get('tumblr', 'consumer_secret');
106 // The callback URL is the script that gets called after the user authenticates with tumblr
107 // In this example, it would be the included callback.php
108 $callback_url = $a->getBaseURL()."/tumblr/callback";
110 // Let's begin. First we need a Request Token. The request token is required to send the user
111 // to Tumblr's login page.
113 // Create a new instance of the TumblrOAuth library. For this step, all we need to give the library is our
114 // Consumer Key and Consumer Secret
115 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret);
117 // Ask Tumblr for a Request Token. Specify the Callback URL here too (although this should be optional)
118 $request_token = $tum_oauth->getRequestToken($callback_url);
120 // Store the request token and Request Token Secret as out callback.php script will need this
121 $_SESSION['request_token'] = $token = $request_token['oauth_token'];
122 $_SESSION['request_token_secret'] = $request_token['oauth_token_secret'];
124 // Check the HTTP Code. It should be a 200 (OK), if it's anything else then something didn't work.
125 switch ($tum_oauth->http_code) {
127 // Ask Tumblr to give us a special address to their login page
128 $url = $tum_oauth->getAuthorizeURL($token);
130 // Redirect the user to the login URL given to us by Tumblr
131 header('Location: ' . $url);
134 * That's it for our side. The user is sent to a Tumblr Login page and
135 * asked to authroize our app. After that, Tumblr sends the user back to
136 * our Callback URL (callback.php) along with some information we need to get
142 // Give an error message
143 $o = 'Could not connect to Tumblr. Refresh the page or try again later.';
149 function tumblr_callback(App $a)
151 // Start a session, load the library
153 //require_once('addon/tumblr/tumblroauth/tumblroauth.php');
155 // Define the needed keys
156 $consumer_key = Config::get('tumblr', 'consumer_key');
157 $consumer_secret = Config::get('tumblr', 'consumer_secret');
159 // Once the user approves your app at Tumblr, they are sent back to this script.
160 // This script is passed two parameters in the URL, oauth_token (our Request Token)
161 // and oauth_verifier (Key that we need to get Access Token).
162 // We'll also need out Request Token Secret, which we stored in a session.
164 // Create instance of TumblrOAuth.
165 // It'll need our Consumer Key and Secret as well as our Request Token and Secret
166 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $_SESSION['request_token'], $_SESSION['request_token_secret']);
168 // Ok, let's get an Access Token. We'll need to pass along our oauth_verifier which was given to us in the URL.
169 $access_token = $tum_oauth->getAccessToken($_REQUEST['oauth_verifier']);
171 // We're done with the Request Token and Secret so let's remove those.
172 unset($_SESSION['request_token']);
173 unset($_SESSION['request_token_secret']);
175 // Make sure nothing went wrong.
176 if (200 == $tum_oauth->http_code) {
179 return 'Unable to authenticate';
182 // What's next? Now that we have an Access Token and Secret, we can make an API call.
183 PConfig::set(local_user(), "tumblr", "oauth_token", $access_token['oauth_token']);
184 PConfig::set(local_user(), "tumblr", "oauth_token_secret", $access_token['oauth_token_secret']);
186 $o = L10n::t("You are now authenticated to tumblr.");
187 $o .= '<br /><a href="'.$a->getBaseURL().'/settings/connectors">'.L10n::t("return to the connector page").'</a>';
192 function tumblr_jot_nets(App $a, &$b)
194 if (! local_user()) {
198 $tmbl_post = PConfig::get(local_user(), 'tumblr', 'post');
200 if (intval($tmbl_post) == 1) {
201 $tmbl_defpost = PConfig::get(local_user(), 'tumblr', 'post_by_default');
202 $selected = ((intval($tmbl_defpost) == 1) ? ' checked="checked" ' : '');
203 $b .= '<div class="profile-jot-net"><input type="checkbox" name="tumblr_enable"' . $selected . ' value="1" /> '
204 . L10n::t('Post to Tumblr') . '</div>';
208 function tumblr_settings(App $a, &$s)
210 if (! local_user()) {
214 /* Add our stylesheet to the page so we can make our settings look nice */
216 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->getBaseURL() . '/addon/tumblr/tumblr.css' . '" media="all" />' . "\r\n";
218 /* Get the current state of our config variables */
220 $enabled = PConfig::get(local_user(), 'tumblr', 'post');
221 $checked = (($enabled) ? ' checked="checked" ' : '');
222 $css = (($enabled) ? '' : '-disabled');
224 $def_enabled = PConfig::get(local_user(), 'tumblr', 'post_by_default');
226 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
228 /* Add some HTML to the existing form */
230 $s .= '<span id="settings_tumblr_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_tumblr_expanded\'); openClose(\'settings_tumblr_inflated\');">';
231 $s .= '<img class="connector'.$css.'" src="images/tumblr.png" /><h3 class="connector">'. L10n::t('Tumblr Export').'</h3>';
233 $s .= '<div id="settings_tumblr_expanded" class="settings-block" style="display: none;">';
234 $s .= '<span class="fakelink" onclick="openClose(\'settings_tumblr_expanded\'); openClose(\'settings_tumblr_inflated\');">';
235 $s .= '<img class="connector'.$css.'" src="images/tumblr.png" /><h3 class="connector">'. L10n::t('Tumblr Export').'</h3>';
238 $s .= '<div id="tumblr-username-wrapper">';
239 $s .= '<a href="'.$a->getBaseURL().'/tumblr/connect">'.L10n::t("(Re-)Authenticate your tumblr page").'</a>';
240 $s .= '</div><div class="clear"></div>';
242 $s .= '<div id="tumblr-enable-wrapper">';
243 $s .= '<label id="tumblr-enable-label" for="tumblr-checkbox">' . L10n::t('Enable Tumblr Post Addon') . '</label>';
244 $s .= '<input id="tumblr-checkbox" type="checkbox" name="tumblr" value="1" ' . $checked . '/>';
245 $s .= '</div><div class="clear"></div>';
247 $s .= '<div id="tumblr-bydefault-wrapper">';
248 $s .= '<label id="tumblr-bydefault-label" for="tumblr-bydefault">' . L10n::t('Post to Tumblr by default') . '</label>';
249 $s .= '<input id="tumblr-bydefault" type="checkbox" name="tumblr_bydefault" value="1" ' . $def_checked . '/>';
250 $s .= '</div><div class="clear"></div>';
252 $oauth_token = PConfig::get(local_user(), "tumblr", "oauth_token");
253 $oauth_token_secret = PConfig::get(local_user(), "tumblr", "oauth_token_secret");
255 $s .= '<div id="tumblr-page-wrapper">';
257 if (($oauth_token != "") && ($oauth_token_secret != "")) {
258 $page = PConfig::get(local_user(), 'tumblr', 'page');
259 $consumer_key = Config::get('tumblr', 'consumer_key');
260 $consumer_secret = Config::get('tumblr', 'consumer_secret');
262 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
264 $userinfo = $tum_oauth->get('user/info');
268 $s .= '<label id="tumblr-page-label" for="tumblr-page">' . L10n::t('Post to page:') . '</label>';
269 $s .= '<select name="tumblr_page" id="tumblr-page">';
270 foreach($userinfo->response->user->blogs as $blog) {
271 $blogurl = substr(str_replace(["http://", "https://"], ["", ""], $blog->url), 0, -1);
273 if ($page == $blogurl) {
274 $s .= "<option value='".$blogurl."' selected>".$blogurl."</option>";
276 $s .= "<option value='".$blogurl."'>".$blogurl."</option>";
282 $s .= L10n::t("You are not authenticated to tumblr");
285 $s .= '</div><div class="clear"></div>';
287 /* provide a submit button */
288 $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>';
291 function tumblr_settings_post(App $a, array &$b)
293 if (!empty($_POST['tumblr-submit'])) {
294 PConfig::set(local_user(), 'tumblr', 'post', intval($_POST['tumblr']));
295 PConfig::set(local_user(), 'tumblr', 'page', $_POST['tumblr_page']);
296 PConfig::set(local_user(), 'tumblr', 'post_by_default', intval($_POST['tumblr_bydefault']));
300 function tumblr_post_local(App $a, array &$b)
302 // This can probably be changed to allow editing by pointing to a different API endpoint
308 if (!local_user() || (local_user() != $b['uid'])) {
312 if ($b['private'] || $b['parent']) {
316 $tmbl_post = intval(PConfig::get(local_user(), 'tumblr', 'post'));
318 $tmbl_enable = (($tmbl_post && !empty($_REQUEST['tumblr_enable'])) ? intval($_REQUEST['tumblr_enable']) : 0);
320 if ($b['api_source'] && intval(PConfig::get(local_user(), 'tumblr', 'post_by_default'))) {
328 if (strlen($b['postopts'])) {
329 $b['postopts'] .= ',';
332 $b['postopts'] .= 'tumblr';
338 function tumblr_send(App $a, array &$b) {
340 if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) {
344 if (! strstr($b['postopts'],'tumblr')) {
348 if ($b['parent'] != $b['id']) {
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 $oauth_token = PConfig::get($b['uid'], "tumblr", "oauth_token");
360 $oauth_token_secret = PConfig::get($b['uid'], "tumblr", "oauth_token_secret");
361 $page = PConfig::get($b['uid'], "tumblr", "page");
362 $tmbl_blog = 'blog/' . $page . '/post';
364 if ($oauth_token && $oauth_token_secret && $tmbl_blog) {
367 preg_match_all('/\#\[(.*?)\](.*?)\[/', $b['tag'], $matches, PREG_SET_ORDER);
369 if (!empty($matches)) {
370 foreach($matches as $mtch) {
371 $tag_arr[] = $mtch[2];
375 if (count($tag_arr)) {
376 $tags = implode(',', $tag_arr);
379 $title = trim($b['title']);
381 $siteinfo = BBCode::getAttachedData($b["body"]);
384 'state' => 'published',
390 if (!isset($siteinfo["type"])) {
391 $siteinfo["type"] = "";
394 if (($title == "") && isset($siteinfo["title"])) {
395 $title = $siteinfo["title"];
398 if (isset($siteinfo["text"])) {
399 $body = $siteinfo["text"];
401 $body = BBCode::removeShareInformation($b["body"]);
404 switch ($siteinfo["type"]) {
406 $params['type'] = "photo";
407 $params['caption'] = BBCode::convert($body, false, 4);
409 if (isset($siteinfo["url"])) {
410 $params['link'] = $siteinfo["url"];
413 $params['source'] = $siteinfo["image"];
417 $params['type'] = "link";
418 $params['title'] = $title;
419 $params['url'] = $siteinfo["url"];
420 $params['description'] = BBCode::convert($body, false, 4);
424 $params['type'] = "audio";
425 $params['external_url'] = $siteinfo["url"];
426 $params['caption'] = BBCode::convert($body, false, 4);
430 $params['type'] = "video";
431 $params['embed'] = $siteinfo["url"];
432 $params['caption'] = BBCode::convert($body, false, 4);
436 $params['type'] = "text";
437 $params['title'] = $title;
438 $params['body'] = BBCode::convert($b['body'], false, 4);
442 if (isset($params['caption']) && (trim($title) != "")) {
443 $params['caption'] = '<h1>'.$title."</h1>".
444 "<p>".$params['caption']."</p>";
447 if (empty($params['caption']) && !empty($siteinfo["description"])) {
448 $params['caption'] = BBCode::convert("[quote]" . $siteinfo["description"] . "[/quote]", false, 4);
451 $consumer_key = Config::get('tumblr','consumer_key');
452 $consumer_secret = Config::get('tumblr','consumer_secret');
454 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
456 // Make an API call with the TumblrOAuth instance.
457 $x = $tum_oauth->post($tmbl_blog,$params);
458 $ret_code = $tum_oauth->http_code;
461 if ($ret_code == 201) {
462 Logger::log('tumblr_send: success');
463 } elseif ($ret_code == 403) {
464 Logger::log('tumblr_send: authentication failure');
466 Logger::log('tumblr_send: general error: ' . print_r($x,true));