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;
18 function tumblr_install() {
19 Addon::registerHook('post_local', 'addon/tumblr/tumblr.php', 'tumblr_post_local');
20 Addon::registerHook('notifier_normal', 'addon/tumblr/tumblr.php', 'tumblr_send');
21 Addon::registerHook('jot_networks', 'addon/tumblr/tumblr.php', 'tumblr_jot_nets');
22 Addon::registerHook('connector_settings', 'addon/tumblr/tumblr.php', 'tumblr_settings');
23 Addon::registerHook('connector_settings_post', 'addon/tumblr/tumblr.php', 'tumblr_settings_post');
26 function tumblr_uninstall() {
27 Addon::unregisterHook('post_local', 'addon/tumblr/tumblr.php', 'tumblr_post_local');
28 Addon::unregisterHook('notifier_normal', 'addon/tumblr/tumblr.php', 'tumblr_send');
29 Addon::unregisterHook('jot_networks', 'addon/tumblr/tumblr.php', 'tumblr_jot_nets');
30 Addon::unregisterHook('connector_settings', 'addon/tumblr/tumblr.php', 'tumblr_settings');
31 Addon::unregisterHook('connector_settings_post', 'addon/tumblr/tumblr.php', 'tumblr_settings_post');
34 function tumblr_module() {}
36 function tumblr_content(&$a) {
39 notice(L10n::t('Permission denied.') . EOL);
43 if (isset($a->argv[1]))
44 switch ($a->argv[1]) {
46 $o = tumblr_connect($a);
49 $o = tumblr_callback($a);
52 $o = print_r($a->argv, true);
56 $o = tumblr_connect($a);
61 function tumblr_addon_admin(&$a, &$o){
62 $t = get_markup_template( "admin.tpl", "addon/tumblr/" );
64 $o = replace_macros($t, [
65 '$submit' => L10n::t('Save Settings'),
66 // name, label, value, help, [extra values]
67 '$consumer_key' => ['consumer_key', L10n::t('Consumer Key'), Config::get('tumblr', 'consumer_key' ), ''],
68 '$consumer_secret' => ['consumer_secret', L10n::t('Consumer Secret'), Config::get('tumblr', 'consumer_secret' ), ''],
72 function tumblr_addon_admin_post(&$a){
73 $consumer_key = ((x($_POST,'consumer_key')) ? notags(trim($_POST['consumer_key'])) : '');
74 $consumer_secret = ((x($_POST,'consumer_secret')) ? notags(trim($_POST['consumer_secret'])): '');
75 Config::set('tumblr','consumer_key',$consumer_key);
76 Config::set('tumblr','consumer_secret',$consumer_secret);
77 info(L10n::t('Settings updated.'). EOL);
80 function tumblr_connect($a) {
81 // Start a session. This is necessary to hold on to a few keys the callback script will also need
84 // Include the TumblrOAuth library
85 //require_once('addon/tumblr/tumblroauth/tumblroauth.php');
87 // Define the needed keys
88 $consumer_key = Config::get('tumblr','consumer_key');
89 $consumer_secret = Config::get('tumblr','consumer_secret');
91 // The callback URL is the script that gets called after the user authenticates with tumblr
92 // In this example, it would be the included callback.php
93 $callback_url = $a->get_baseurl()."/tumblr/callback";
95 // Let's begin. First we need a Request Token. The request token is required to send the user
96 // to Tumblr's login page.
98 // Create a new instance of the TumblrOAuth library. For this step, all we need to give the library is our
99 // Consumer Key and Consumer Secret
100 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret);
102 // Ask Tumblr for a Request Token. Specify the Callback URL here too (although this should be optional)
103 $request_token = $tum_oauth->getRequestToken($callback_url);
105 // Store the request token and Request Token Secret as out callback.php script will need this
106 $_SESSION['request_token'] = $token = $request_token['oauth_token'];
107 $_SESSION['request_token_secret'] = $request_token['oauth_token_secret'];
109 // Check the HTTP Code. It should be a 200 (OK), if it's anything else then something didn't work.
110 switch ($tum_oauth->http_code) {
112 // Ask Tumblr to give us a special address to their login page
113 $url = $tum_oauth->getAuthorizeURL($token);
115 // Redirect the user to the login URL given to us by Tumblr
116 header('Location: ' . $url);
118 // That's it for our side. The user is sent to a Tumblr Login page and
119 // asked to authroize our app. After that, Tumblr sends the user back to
120 // our Callback URL (callback.php) along with some information we need to get
125 // Give an error message
126 $o = 'Could not connect to Tumblr. Refresh the page or try again later.';
131 function tumblr_callback($a) {
133 // Start a session, load the library
135 //require_once('addon/tumblr/tumblroauth/tumblroauth.php');
137 // Define the needed keys
138 $consumer_key = Config::get('tumblr','consumer_key');
139 $consumer_secret = Config::get('tumblr','consumer_secret');
141 // Once the user approves your app at Tumblr, they are sent back to this script.
142 // This script is passed two parameters in the URL, oauth_token (our Request Token)
143 // and oauth_verifier (Key that we need to get Access Token).
144 // We'll also need out Request Token Secret, which we stored in a session.
146 // Create instance of TumblrOAuth.
147 // It'll need our Consumer Key and Secret as well as our Request Token and Secret
148 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $_SESSION['request_token'], $_SESSION['request_token_secret']);
150 // Ok, let's get an Access Token. We'll need to pass along our oauth_verifier which was given to us in the URL.
151 $access_token = $tum_oauth->getAccessToken($_REQUEST['oauth_verifier']);
153 // We're done with the Request Token and Secret so let's remove those.
154 unset($_SESSION['request_token']);
155 unset($_SESSION['request_token_secret']);
157 // Make sure nothing went wrong.
158 if (200 == $tum_oauth->http_code) {
161 return('Unable to authenticate');
164 // What's next? Now that we have an Access Token and Secret, we can make an API call.
165 PConfig::set(local_user(), "tumblr", "oauth_token", $access_token['oauth_token']);
166 PConfig::set(local_user(), "tumblr", "oauth_token_secret", $access_token['oauth_token_secret']);
168 $o = L10n::t("You are now authenticated to tumblr.");
169 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.L10n::t("return to the connector page").'</a>';
173 function tumblr_jot_nets(&$a,&$b) {
177 $tmbl_post = PConfig::get(local_user(),'tumblr','post');
178 if(intval($tmbl_post) == 1) {
179 $tmbl_defpost = PConfig::get(local_user(),'tumblr','post_by_default');
180 $selected = ((intval($tmbl_defpost) == 1) ? ' checked="checked" ' : '');
181 $b .= '<div class="profile-jot-net"><input type="checkbox" name="tumblr_enable"' . $selected . ' value="1" /> '
182 . L10n::t('Post to Tumblr') . '</div>';
187 function tumblr_settings(&$a,&$s) {
192 /* Add our stylesheet to the page so we can make our settings look nice */
194 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/tumblr/tumblr.css' . '" media="all" />' . "\r\n";
196 /* Get the current state of our config variables */
198 $enabled = PConfig::get(local_user(),'tumblr','post');
199 $checked = (($enabled) ? ' checked="checked" ' : '');
200 $css = (($enabled) ? '' : '-disabled');
202 $def_enabled = PConfig::get(local_user(),'tumblr','post_by_default');
204 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
206 /* Add some HTML to the existing form */
208 $s .= '<span id="settings_tumblr_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_tumblr_expanded\'); openClose(\'settings_tumblr_inflated\');">';
209 $s .= '<img class="connector'.$css.'" src="images/tumblr.png" /><h3 class="connector">'. L10n::t('Tumblr Export').'</h3>';
211 $s .= '<div id="settings_tumblr_expanded" class="settings-block" style="display: none;">';
212 $s .= '<span class="fakelink" onclick="openClose(\'settings_tumblr_expanded\'); openClose(\'settings_tumblr_inflated\');">';
213 $s .= '<img class="connector'.$css.'" src="images/tumblr.png" /><h3 class="connector">'. L10n::t('Tumblr Export').'</h3>';
216 $s .= '<div id="tumblr-username-wrapper">';
217 $s .= '<a href="'.$a->get_baseurl().'/tumblr/connect">'.L10n::t("(Re-)Authenticate your tumblr page").'</a>';
218 $s .= '</div><div class="clear"></div>';
220 $s .= '<div id="tumblr-enable-wrapper">';
221 $s .= '<label id="tumblr-enable-label" for="tumblr-checkbox">' . L10n::t('Enable Tumblr Post Addon') . '</label>';
222 $s .= '<input id="tumblr-checkbox" type="checkbox" name="tumblr" value="1" ' . $checked . '/>';
223 $s .= '</div><div class="clear"></div>';
225 $s .= '<div id="tumblr-bydefault-wrapper">';
226 $s .= '<label id="tumblr-bydefault-label" for="tumblr-bydefault">' . L10n::t('Post to Tumblr by default') . '</label>';
227 $s .= '<input id="tumblr-bydefault" type="checkbox" name="tumblr_bydefault" value="1" ' . $def_checked . '/>';
228 $s .= '</div><div class="clear"></div>';
230 $oauth_token = PConfig::get(local_user(), "tumblr", "oauth_token");
231 $oauth_token_secret = PConfig::get(local_user(), "tumblr", "oauth_token_secret");
233 $s .= '<div id="tumblr-page-wrapper">';
234 if (($oauth_token != "") && ($oauth_token_secret != "")) {
236 $page = PConfig::get(local_user(),'tumblr','page');
237 $consumer_key = Config::get('tumblr','consumer_key');
238 $consumer_secret = Config::get('tumblr','consumer_secret');
240 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
242 $userinfo = $tum_oauth->get('user/info');
246 $s .= '<label id="tumblr-page-label" for="tumblr-page">' . L10n::t('Post to page:') . '</label>';
247 $s .= '<select name="tumblr_page" id="tumblr-page">';
248 foreach($userinfo->response->user->blogs as $blog) {
249 $blogurl = substr(str_replace(["http://", "https://"], ["", ""], $blog->url), 0, -1);
250 if ($page == $blogurl)
251 $s .= "<option value='".$blogurl."' selected>".$blogurl."</option>";
253 $s .= "<option value='".$blogurl."'>".$blogurl."</option>";
258 $s .= L10n::t("You are not authenticated to tumblr");
259 $s .= '</div><div class="clear"></div>';
261 /* provide a submit button */
263 $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>';
268 function tumblr_settings_post(&$a,&$b) {
270 if(x($_POST,'tumblr-submit')) {
272 PConfig::set(local_user(),'tumblr','post',intval($_POST['tumblr']));
273 PConfig::set(local_user(),'tumblr','page',$_POST['tumblr_page']);
274 PConfig::set(local_user(),'tumblr','post_by_default',intval($_POST['tumblr_bydefault']));
280 function tumblr_post_local(&$a, &$b) {
282 // This can probably be changed to allow editing by pointing to a different API endpoint
288 if (!local_user() || (local_user() != $b['uid'])) {
292 if ($b['private'] || $b['parent']) {
296 $tmbl_post = intval(PConfig::get(local_user(),'tumblr','post'));
298 $tmbl_enable = (($tmbl_post && x($_REQUEST,'tumblr_enable')) ? intval($_REQUEST['tumblr_enable']) : 0);
300 if ($b['api_source'] && intval(PConfig::get(local_user(),'tumblr','post_by_default'))) {
308 if (strlen($b['postopts'])) {
309 $b['postopts'] .= ',';
312 $b['postopts'] .= 'tumblr';
318 function tumblr_send(&$a,&$b) {
320 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) {
324 if(! strstr($b['postopts'],'tumblr')) {
328 if($b['parent'] != $b['id']) {
332 // Dont't post if the post doesn't belong to us.
333 // This is a check for forum postings
334 $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
335 if ($b['contact-id'] != $self['id']) {
339 $oauth_token = PConfig::get($b['uid'], "tumblr", "oauth_token");
340 $oauth_token_secret = PConfig::get($b['uid'], "tumblr", "oauth_token_secret");
341 $page = PConfig::get($b['uid'], "tumblr", "page");
342 $tmbl_blog = 'blog/'.$page.'/post';
344 if($oauth_token && $oauth_token_secret && $tmbl_blog) {
347 $x = preg_match_all('/\#\[(.*?)\](.*?)\[/',$b['tag'],$matches,PREG_SET_ORDER);
350 foreach($matches as $mtch) {
351 $tag_arr[] = $mtch[2];
355 $tags = implode(',',$tag_arr);
357 $title = trim($b['title']);
359 $siteinfo = BBCode::getAttachedData($b["body"]);
362 'state' => 'published',
367 if (!isset($siteinfo["type"]))
368 $siteinfo["type"] = "";
370 if (($title == "") && isset($siteinfo["title"]))
371 $title = $siteinfo["title"];
373 if (isset($siteinfo["text"]))
374 $body = $siteinfo["text"];
376 $body = BBCode::removeShareInformation($b["body"]);
378 switch ($siteinfo["type"]) {
380 $params['type'] = "photo";
381 $params['caption'] = BBCode::convert($body, false, 4);
383 if (isset($siteinfo["url"]))
384 $params['link'] = $siteinfo["url"];
386 $params['source'] = $siteinfo["image"];
389 $params['type'] = "link";
390 $params['title'] = $title;
391 $params['url'] = $siteinfo["url"];
392 $params['description'] = BBCode::convert($body, false, 4);
395 $params['type'] = "audio";
396 $params['external_url'] = $siteinfo["url"];
397 $params['caption'] = BBCode::convert($body, false, 4);
400 $params['type'] = "video";
401 $params['embed'] = $siteinfo["url"];
402 $params['caption'] = BBCode::convert($body, false, 4);
405 $params['type'] = "text";
406 $params['title'] = $title;
407 $params['body'] = BBCode::convert($b['body'], false, 4);
411 if (isset($params['caption']) && (trim($title) != ""))
412 $params['caption'] = '<h1>'.$title."</h1>".
413 "<p>".$params['caption']."</p>";
415 if (empty($params['caption']))
416 $params['caption'] = BBCode::convert("[quote]" . $siteinfo["description"] . "[/quote]", false, 4);
418 $consumer_key = Config::get('tumblr','consumer_key');
419 $consumer_secret = Config::get('tumblr','consumer_secret');
421 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
423 // Make an API call with the TumblrOAuth instance.
424 $x = $tum_oauth->post($tmbl_blog,$params);
425 $ret_code = $tum_oauth->http_code;
428 logger('tumblr_send: success');
429 elseif($ret_code == 403)
430 logger('tumblr_send: authentication failure');
432 logger('tumblr_send: general error: ' . print_r($x,true));