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';
12 use Friendica\Content\Text\BBCode;
13 use Friendica\Core\Addon;
14 use Friendica\Core\Config;
15 use Friendica\Core\L10n;
16 use Friendica\Core\PConfig;
17 use Friendica\Database\DBA;
19 function tumblr_install() {
20 Addon::registerHook('post_local', 'addon/tumblr/tumblr.php', 'tumblr_post_local');
21 Addon::registerHook('notifier_normal', 'addon/tumblr/tumblr.php', 'tumblr_send');
22 Addon::registerHook('jot_networks', 'addon/tumblr/tumblr.php', 'tumblr_jot_nets');
23 Addon::registerHook('connector_settings', 'addon/tumblr/tumblr.php', 'tumblr_settings');
24 Addon::registerHook('connector_settings_post', 'addon/tumblr/tumblr.php', 'tumblr_settings_post');
27 function tumblr_uninstall() {
28 Addon::unregisterHook('post_local', 'addon/tumblr/tumblr.php', 'tumblr_post_local');
29 Addon::unregisterHook('notifier_normal', 'addon/tumblr/tumblr.php', 'tumblr_send');
30 Addon::unregisterHook('jot_networks', 'addon/tumblr/tumblr.php', 'tumblr_jot_nets');
31 Addon::unregisterHook('connector_settings', 'addon/tumblr/tumblr.php', 'tumblr_settings');
32 Addon::unregisterHook('connector_settings_post', 'addon/tumblr/tumblr.php', 'tumblr_settings_post');
35 function tumblr_module() {}
37 function tumblr_content(&$a) {
40 notice(L10n::t('Permission denied.') . EOL);
44 if (isset($a->argv[1]))
45 switch ($a->argv[1]) {
47 $o = tumblr_connect($a);
50 $o = tumblr_callback($a);
53 $o = print_r($a->argv, true);
57 $o = tumblr_connect($a);
62 function tumblr_addon_admin(&$a, &$o){
63 $t = get_markup_template( "admin.tpl", "addon/tumblr/" );
65 $o = replace_macros($t, [
66 '$submit' => L10n::t('Save Settings'),
67 // name, label, value, help, [extra values]
68 '$consumer_key' => ['consumer_key', L10n::t('Consumer Key'), Config::get('tumblr', 'consumer_key' ), ''],
69 '$consumer_secret' => ['consumer_secret', L10n::t('Consumer Secret'), Config::get('tumblr', 'consumer_secret' ), ''],
73 function tumblr_addon_admin_post(&$a){
74 $consumer_key = ((x($_POST,'consumer_key')) ? notags(trim($_POST['consumer_key'])) : '');
75 $consumer_secret = ((x($_POST,'consumer_secret')) ? notags(trim($_POST['consumer_secret'])): '');
76 Config::set('tumblr','consumer_key',$consumer_key);
77 Config::set('tumblr','consumer_secret',$consumer_secret);
78 info(L10n::t('Settings updated.'). EOL);
81 function tumblr_connect($a) {
82 // Start a session. This is necessary to hold on to a few keys the callback script will also need
85 // Include the TumblrOAuth library
86 //require_once('addon/tumblr/tumblroauth/tumblroauth.php');
88 // Define the needed keys
89 $consumer_key = Config::get('tumblr','consumer_key');
90 $consumer_secret = Config::get('tumblr','consumer_secret');
92 // The callback URL is the script that gets called after the user authenticates with tumblr
93 // In this example, it would be the included callback.php
94 $callback_url = $a->get_baseurl()."/tumblr/callback";
96 // Let's begin. First we need a Request Token. The request token is required to send the user
97 // to Tumblr's login page.
99 // Create a new instance of the TumblrOAuth library. For this step, all we need to give the library is our
100 // Consumer Key and Consumer Secret
101 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret);
103 // Ask Tumblr for a Request Token. Specify the Callback URL here too (although this should be optional)
104 $request_token = $tum_oauth->getRequestToken($callback_url);
106 // Store the request token and Request Token Secret as out callback.php script will need this
107 $_SESSION['request_token'] = $token = $request_token['oauth_token'];
108 $_SESSION['request_token_secret'] = $request_token['oauth_token_secret'];
110 // Check the HTTP Code. It should be a 200 (OK), if it's anything else then something didn't work.
111 switch ($tum_oauth->http_code) {
113 // Ask Tumblr to give us a special address to their login page
114 $url = $tum_oauth->getAuthorizeURL($token);
116 // Redirect the user to the login URL given to us by Tumblr
117 header('Location: ' . $url);
119 // That's it for our side. The user is sent to a Tumblr Login page and
120 // asked to authroize our app. After that, Tumblr sends the user back to
121 // our Callback URL (callback.php) along with some information we need to get
126 // Give an error message
127 $o = 'Could not connect to Tumblr. Refresh the page or try again later.';
132 function tumblr_callback($a) {
134 // Start a session, load the library
136 //require_once('addon/tumblr/tumblroauth/tumblroauth.php');
138 // Define the needed keys
139 $consumer_key = Config::get('tumblr','consumer_key');
140 $consumer_secret = Config::get('tumblr','consumer_secret');
142 // Once the user approves your app at Tumblr, they are sent back to this script.
143 // This script is passed two parameters in the URL, oauth_token (our Request Token)
144 // and oauth_verifier (Key that we need to get Access Token).
145 // We'll also need out Request Token Secret, which we stored in a session.
147 // Create instance of TumblrOAuth.
148 // It'll need our Consumer Key and Secret as well as our Request Token and Secret
149 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $_SESSION['request_token'], $_SESSION['request_token_secret']);
151 // Ok, let's get an Access Token. We'll need to pass along our oauth_verifier which was given to us in the URL.
152 $access_token = $tum_oauth->getAccessToken($_REQUEST['oauth_verifier']);
154 // We're done with the Request Token and Secret so let's remove those.
155 unset($_SESSION['request_token']);
156 unset($_SESSION['request_token_secret']);
158 // Make sure nothing went wrong.
159 if (200 == $tum_oauth->http_code) {
162 return('Unable to authenticate');
165 // What's next? Now that we have an Access Token and Secret, we can make an API call.
166 PConfig::set(local_user(), "tumblr", "oauth_token", $access_token['oauth_token']);
167 PConfig::set(local_user(), "tumblr", "oauth_token_secret", $access_token['oauth_token_secret']);
169 $o = L10n::t("You are now authenticated to tumblr.");
170 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.L10n::t("return to the connector page").'</a>';
174 function tumblr_jot_nets(&$a,&$b) {
178 $tmbl_post = PConfig::get(local_user(),'tumblr','post');
179 if(intval($tmbl_post) == 1) {
180 $tmbl_defpost = PConfig::get(local_user(),'tumblr','post_by_default');
181 $selected = ((intval($tmbl_defpost) == 1) ? ' checked="checked" ' : '');
182 $b .= '<div class="profile-jot-net"><input type="checkbox" name="tumblr_enable"' . $selected . ' value="1" /> '
183 . L10n::t('Post to Tumblr') . '</div>';
188 function tumblr_settings(&$a,&$s) {
193 /* Add our stylesheet to the page so we can make our settings look nice */
195 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/tumblr/tumblr.css' . '" media="all" />' . "\r\n";
197 /* Get the current state of our config variables */
199 $enabled = PConfig::get(local_user(),'tumblr','post');
200 $checked = (($enabled) ? ' checked="checked" ' : '');
201 $css = (($enabled) ? '' : '-disabled');
203 $def_enabled = PConfig::get(local_user(),'tumblr','post_by_default');
205 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
207 /* Add some HTML to the existing form */
209 $s .= '<span id="settings_tumblr_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_tumblr_expanded\'); openClose(\'settings_tumblr_inflated\');">';
210 $s .= '<img class="connector'.$css.'" src="images/tumblr.png" /><h3 class="connector">'. L10n::t('Tumblr Export').'</h3>';
212 $s .= '<div id="settings_tumblr_expanded" class="settings-block" style="display: none;">';
213 $s .= '<span class="fakelink" onclick="openClose(\'settings_tumblr_expanded\'); openClose(\'settings_tumblr_inflated\');">';
214 $s .= '<img class="connector'.$css.'" src="images/tumblr.png" /><h3 class="connector">'. L10n::t('Tumblr Export').'</h3>';
217 $s .= '<div id="tumblr-username-wrapper">';
218 $s .= '<a href="'.$a->get_baseurl().'/tumblr/connect">'.L10n::t("(Re-)Authenticate your tumblr page").'</a>';
219 $s .= '</div><div class="clear"></div>';
221 $s .= '<div id="tumblr-enable-wrapper">';
222 $s .= '<label id="tumblr-enable-label" for="tumblr-checkbox">' . L10n::t('Enable Tumblr Post Addon') . '</label>';
223 $s .= '<input id="tumblr-checkbox" type="checkbox" name="tumblr" value="1" ' . $checked . '/>';
224 $s .= '</div><div class="clear"></div>';
226 $s .= '<div id="tumblr-bydefault-wrapper">';
227 $s .= '<label id="tumblr-bydefault-label" for="tumblr-bydefault">' . L10n::t('Post to Tumblr by default') . '</label>';
228 $s .= '<input id="tumblr-bydefault" type="checkbox" name="tumblr_bydefault" value="1" ' . $def_checked . '/>';
229 $s .= '</div><div class="clear"></div>';
231 $oauth_token = PConfig::get(local_user(), "tumblr", "oauth_token");
232 $oauth_token_secret = PConfig::get(local_user(), "tumblr", "oauth_token_secret");
234 $s .= '<div id="tumblr-page-wrapper">';
235 if (($oauth_token != "") && ($oauth_token_secret != "")) {
237 $page = PConfig::get(local_user(),'tumblr','page');
238 $consumer_key = Config::get('tumblr','consumer_key');
239 $consumer_secret = Config::get('tumblr','consumer_secret');
241 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
243 $userinfo = $tum_oauth->get('user/info');
247 $s .= '<label id="tumblr-page-label" for="tumblr-page">' . L10n::t('Post to page:') . '</label>';
248 $s .= '<select name="tumblr_page" id="tumblr-page">';
249 foreach($userinfo->response->user->blogs as $blog) {
250 $blogurl = substr(str_replace(["http://", "https://"], ["", ""], $blog->url), 0, -1);
251 if ($page == $blogurl)
252 $s .= "<option value='".$blogurl."' selected>".$blogurl."</option>";
254 $s .= "<option value='".$blogurl."'>".$blogurl."</option>";
259 $s .= L10n::t("You are not authenticated to tumblr");
260 $s .= '</div><div class="clear"></div>';
262 /* provide a submit button */
264 $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>';
269 function tumblr_settings_post(&$a,&$b) {
271 if(x($_POST,'tumblr-submit')) {
273 PConfig::set(local_user(),'tumblr','post',intval($_POST['tumblr']));
274 PConfig::set(local_user(),'tumblr','page',$_POST['tumblr_page']);
275 PConfig::set(local_user(),'tumblr','post_by_default',intval($_POST['tumblr_bydefault']));
281 function tumblr_post_local(&$a, &$b) {
283 // This can probably be changed to allow editing by pointing to a different API endpoint
289 if (!local_user() || (local_user() != $b['uid'])) {
293 if ($b['private'] || $b['parent']) {
297 $tmbl_post = intval(PConfig::get(local_user(),'tumblr','post'));
299 $tmbl_enable = (($tmbl_post && x($_REQUEST,'tumblr_enable')) ? intval($_REQUEST['tumblr_enable']) : 0);
301 if ($b['api_source'] && intval(PConfig::get(local_user(),'tumblr','post_by_default'))) {
309 if (strlen($b['postopts'])) {
310 $b['postopts'] .= ',';
313 $b['postopts'] .= 'tumblr';
319 function tumblr_send(&$a,&$b) {
321 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) {
325 if(! strstr($b['postopts'],'tumblr')) {
329 if($b['parent'] != $b['id']) {
333 // Dont't post if the post doesn't belong to us.
334 // This is a check for forum postings
335 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
336 if ($b['contact-id'] != $self['id']) {
340 $oauth_token = PConfig::get($b['uid'], "tumblr", "oauth_token");
341 $oauth_token_secret = PConfig::get($b['uid'], "tumblr", "oauth_token_secret");
342 $page = PConfig::get($b['uid'], "tumblr", "page");
343 $tmbl_blog = 'blog/'.$page.'/post';
345 if($oauth_token && $oauth_token_secret && $tmbl_blog) {
348 $x = preg_match_all('/\#\[(.*?)\](.*?)\[/',$b['tag'],$matches,PREG_SET_ORDER);
351 foreach($matches as $mtch) {
352 $tag_arr[] = $mtch[2];
356 $tags = implode(',',$tag_arr);
358 $title = trim($b['title']);
360 $siteinfo = BBCode::getAttachedData($b["body"]);
363 'state' => 'published',
368 if (!isset($siteinfo["type"]))
369 $siteinfo["type"] = "";
371 if (($title == "") && isset($siteinfo["title"]))
372 $title = $siteinfo["title"];
374 if (isset($siteinfo["text"]))
375 $body = $siteinfo["text"];
377 $body = BBCode::removeShareInformation($b["body"]);
379 switch ($siteinfo["type"]) {
381 $params['type'] = "photo";
382 $params['caption'] = BBCode::convert($body, false, 4);
384 if (isset($siteinfo["url"]))
385 $params['link'] = $siteinfo["url"];
387 $params['source'] = $siteinfo["image"];
390 $params['type'] = "link";
391 $params['title'] = $title;
392 $params['url'] = $siteinfo["url"];
393 $params['description'] = BBCode::convert($body, false, 4);
396 $params['type'] = "audio";
397 $params['external_url'] = $siteinfo["url"];
398 $params['caption'] = BBCode::convert($body, false, 4);
401 $params['type'] = "video";
402 $params['embed'] = $siteinfo["url"];
403 $params['caption'] = BBCode::convert($body, false, 4);
406 $params['type'] = "text";
407 $params['title'] = $title;
408 $params['body'] = BBCode::convert($b['body'], false, 4);
412 if (isset($params['caption']) && (trim($title) != ""))
413 $params['caption'] = '<h1>'.$title."</h1>".
414 "<p>".$params['caption']."</p>";
416 if (empty($params['caption']))
417 $params['caption'] = BBCode::convert("[quote]" . $siteinfo["description"] . "[/quote]", false, 4);
419 $consumer_key = Config::get('tumblr','consumer_key');
420 $consumer_secret = Config::get('tumblr','consumer_secret');
422 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
424 // Make an API call with the TumblrOAuth instance.
425 $x = $tum_oauth->post($tmbl_blog,$params);
426 $ret_code = $tum_oauth->http_code;
429 logger('tumblr_send: success');
430 elseif($ret_code == 403)
431 logger('tumblr_send: authentication failure');
433 logger('tumblr_send: general error: ' . print_r($x,true));