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\Hook;
15 use Friendica\Core\Logger;
16 use Friendica\Core\Renderer;
17 use Friendica\Database\DBA;
19 use Friendica\Model\Post;
20 use Friendica\Model\Tag;
22 function tumblr_install()
24 Hook::register('hook_fork', 'addon/tumblr/tumblr.php', 'tumblr_hook_fork');
25 Hook::register('post_local', 'addon/tumblr/tumblr.php', 'tumblr_post_local');
26 Hook::register('notifier_normal', 'addon/tumblr/tumblr.php', 'tumblr_send');
27 Hook::register('jot_networks', 'addon/tumblr/tumblr.php', 'tumblr_jot_nets');
28 Hook::register('connector_settings', 'addon/tumblr/tumblr.php', 'tumblr_settings');
29 Hook::register('connector_settings_post', 'addon/tumblr/tumblr.php', 'tumblr_settings_post');
32 function tumblr_module()
36 function tumblr_content(App $a)
39 notice(DI::l10n()->t('Permission denied.') . EOL);
43 if (isset(DI::args()->getArgv()[1])) {
44 switch (DI::args()->getArgv()[1]) {
46 $o = tumblr_connect($a);
50 $o = tumblr_callback($a);
54 $o = print_r(DI::args()->getArgv(), true);
58 $o = tumblr_connect($a);
64 function tumblr_addon_admin(App $a, &$o)
66 $t = Renderer::getMarkupTemplate( "admin.tpl", "addon/tumblr/" );
68 $o = Renderer::replaceMacros($t, [
69 '$submit' => DI::l10n()->t('Save Settings'),
70 // name, label, value, help, [extra values]
71 '$consumer_key' => ['consumer_key', DI::l10n()->t('Consumer Key'), DI::config()->get('tumblr', 'consumer_key' ), ''],
72 '$consumer_secret' => ['consumer_secret', DI::l10n()->t('Consumer Secret'), DI::config()->get('tumblr', 'consumer_secret' ), ''],
76 function tumblr_addon_admin_post(App $a)
78 $consumer_key = trim($_POST['consumer_key'] ?? '');
79 $consumer_secret = trim($_POST['consumer_secret'] ?? '');
81 DI::config()->set('tumblr', 'consumer_key',$consumer_key);
82 DI::config()->set('tumblr', 'consumer_secret',$consumer_secret);
85 function tumblr_connect(App $a)
87 // Start a session. This is necessary to hold on to a few keys the callback script will also need
90 // Include the TumblrOAuth library
91 //require_once('addon/tumblr/tumblroauth/tumblroauth.php');
93 // Define the needed keys
94 $consumer_key = DI::config()->get('tumblr', 'consumer_key');
95 $consumer_secret = DI::config()->get('tumblr', 'consumer_secret');
97 // The callback URL is the script that gets called after the user authenticates with tumblr
98 // In this example, it would be the included callback.php
99 $callback_url = DI::baseUrl()->get()."/tumblr/callback";
101 // Let's begin. First we need a Request Token. The request token is required to send the user
102 // to Tumblr's login page.
104 // Create a new instance of the TumblrOAuth library. For this step, all we need to give the library is our
105 // Consumer Key and Consumer Secret
106 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret);
108 // Ask Tumblr for a Request Token. Specify the Callback URL here too (although this should be optional)
109 $request_token = $tum_oauth->getRequestToken($callback_url);
111 // Store the request token and Request Token Secret as out callback.php script will need this
112 $_SESSION['request_token'] = $token = $request_token['oauth_token'];
113 $_SESSION['request_token_secret'] = $request_token['oauth_token_secret'];
115 // Check the HTTP Code. It should be a 200 (OK), if it's anything else then something didn't work.
116 switch ($tum_oauth->http_code) {
118 // Ask Tumblr to give us a special address to their login page
119 $url = $tum_oauth->getAuthorizeURL($token);
121 // Redirect the user to the login URL given to us by Tumblr
122 header('Location: ' . $url);
125 * That's it for our side. The user is sent to a Tumblr Login page and
126 * asked to authroize our app. After that, Tumblr sends the user back to
127 * our Callback URL (callback.php) along with some information we need to get
133 // Give an error message
134 $o = 'Could not connect to Tumblr. Refresh the page or try again later.';
140 function tumblr_callback(App $a)
142 // Start a session, load the library
144 //require_once('addon/tumblr/tumblroauth/tumblroauth.php');
146 // Define the needed keys
147 $consumer_key = DI::config()->get('tumblr', 'consumer_key');
148 $consumer_secret = DI::config()->get('tumblr', 'consumer_secret');
150 // Once the user approves your app at Tumblr, they are sent back to this script.
151 // This script is passed two parameters in the URL, oauth_token (our Request Token)
152 // and oauth_verifier (Key that we need to get Access Token).
153 // We'll also need out Request Token Secret, which we stored in a session.
155 // Create instance of TumblrOAuth.
156 // It'll need our Consumer Key and Secret as well as our Request Token and Secret
157 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $_SESSION['request_token'], $_SESSION['request_token_secret']);
159 // Ok, let's get an Access Token. We'll need to pass along our oauth_verifier which was given to us in the URL.
160 $access_token = $tum_oauth->getAccessToken($_REQUEST['oauth_verifier']);
162 // We're done with the Request Token and Secret so let's remove those.
163 unset($_SESSION['request_token']);
164 unset($_SESSION['request_token_secret']);
166 // Make sure nothing went wrong.
167 if (200 == $tum_oauth->http_code) {
170 return 'Unable to authenticate';
173 // What's next? Now that we have an Access Token and Secret, we can make an API call.
174 DI::pConfig()->set(local_user(), "tumblr", "oauth_token", $access_token['oauth_token']);
175 DI::pConfig()->set(local_user(), "tumblr", "oauth_token_secret", $access_token['oauth_token_secret']);
177 $o = DI::l10n()->t("You are now authenticated to tumblr.");
178 $o .= '<br /><a href="' . DI::baseUrl()->get() . '/settings/connectors">' . DI::l10n()->t("return to the connector page") . '</a>';
183 function tumblr_jot_nets(App $a, array &$jotnets_fields)
185 if (! local_user()) {
189 if (DI::pConfig()->get(local_user(),'tumblr','post')) {
190 $jotnets_fields[] = [
191 'type' => 'checkbox',
194 DI::l10n()->t('Post to Tumblr'),
195 DI::pConfig()->get(local_user(),'tumblr','post_by_default')
201 function tumblr_settings(App $a, array &$data)
207 $enabled = DI::pConfig()->get(local_user(), 'tumblr', 'post', false);
208 $def_enabled = DI::pConfig()->get(local_user(), 'tumblr', 'post_by_default', false);
210 $oauth_token = DI::pConfig()->get(local_user(), 'tumblr', 'oauth_token');
211 $oauth_token_secret = DI::pConfig()->get(local_user(), 'tumblr', 'oauth_token_secret');
213 if ($oauth_token && $oauth_token_secret) {
214 $page = DI::pConfig()->get(local_user(), 'tumblr', 'page');
215 $consumer_key = DI::config()->get('tumblr', 'consumer_key');
216 $consumer_secret = DI::config()->get('tumblr', 'consumer_secret');
218 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
219 $userinfo = $tum_oauth->get('user/info');
221 $blogs = array_map(function ($blog) {
222 return substr(str_replace(["http://", "https://"], ["", ""], $blog->url), 0, -1);
223 }, $userinfo->response->user->blogs);
225 $page_select = ['tumblr-page', DI::l10n()->t('Post to page:'), $page, '', $blogs];
228 $t = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/tumblr/');
229 $html = Renderer::replaceMacros($t, [
231 'connect' => DI::l10n()->t('(Re-)Authenticate your tumblr page'),
232 'noconnect' => DI::l10n()->t('You are not authenticated to tumblr'),
235 '$authenticate_url' => DI::baseUrl()->get() . '/tumblr/connect',
237 '$enable' => ['tumblr', DI::l10n()->t('Enable Tumblr Post Addon'), $enabled],
238 '$bydefault' => ['tumblr_bydefault', DI::l10n()->t('Post to Tumblr by default'), $def_enabled],
239 '$page_select' => $page_select ?? '',
243 'connector' => 'tumblr',
244 'title' => DI::l10n()->t('Tumblr Export'),
245 'image' => 'images/tumblr.png',
246 'enabled' => $enabled,
251 function tumblr_settings_post(App $a, array &$b)
253 if (!empty($_POST['tumblr-submit'])) {
254 DI::pConfig()->set(local_user(), 'tumblr', 'post', intval($_POST['tumblr']));
255 DI::pConfig()->set(local_user(), 'tumblr', 'page', $_POST['tumblr_page']);
256 DI::pConfig()->set(local_user(), 'tumblr', 'post_by_default', intval($_POST['tumblr_bydefault']));
260 function tumblr_hook_fork(&$a, &$b)
262 if ($b['name'] != 'notifier_normal') {
268 if ($post['deleted'] || $post['private'] || ($post['created'] !== $post['edited']) ||
269 !strstr($post['postopts'], 'tumblr') || ($post['parent'] != $post['id'])) {
270 $b['execute'] = false;
275 function tumblr_post_local(App $a, array &$b)
277 // This can probably be changed to allow editing by pointing to a different API endpoint
283 if (!local_user() || (local_user() != $b['uid'])) {
287 if ($b['private'] || $b['parent']) {
291 $tmbl_post = intval(DI::pConfig()->get(local_user(), 'tumblr', 'post'));
293 $tmbl_enable = (($tmbl_post && !empty($_REQUEST['tumblr_enable'])) ? intval($_REQUEST['tumblr_enable']) : 0);
295 if ($b['api_source'] && intval(DI::pConfig()->get(local_user(), 'tumblr', 'post_by_default'))) {
303 if (strlen($b['postopts'])) {
304 $b['postopts'] .= ',';
307 $b['postopts'] .= 'tumblr';
313 function tumblr_send(App $a, array &$b) {
315 if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) {
319 if (! strstr($b['postopts'],'tumblr')) {
323 if ($b['parent'] != $b['id']) {
327 // Dont't post if the post doesn't belong to us.
328 // This is a check for forum postings
329 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
330 if ($b['contact-id'] != $self['id']) {
334 $b['body'] = Post\Media::addAttachmentsToBody($b['uri-id'], $b['body']);
336 $oauth_token = DI::pConfig()->get($b['uid'], "tumblr", "oauth_token");
337 $oauth_token_secret = DI::pConfig()->get($b['uid'], "tumblr", "oauth_token_secret");
338 $page = DI::pConfig()->get($b['uid'], "tumblr", "page");
339 $tmbl_blog = 'blog/' . $page . '/post';
341 if ($oauth_token && $oauth_token_secret && $tmbl_blog) {
342 $tags = Tag::getByURIId($b['uri-id']);
346 foreach($tags as $tag) {
347 $tag_arr[] = $tag['name'];
350 if (count($tag_arr)) {
351 $tags = implode(',', $tag_arr);
354 $title = trim($b['title']);
356 $siteinfo = BBCode::getAttachedData($b["body"]);
359 'state' => 'published',
365 if (!isset($siteinfo["type"])) {
366 $siteinfo["type"] = "";
369 if (($title == "") && isset($siteinfo["title"])) {
370 $title = $siteinfo["title"];
373 if (isset($siteinfo["text"])) {
374 $body = $siteinfo["text"];
376 $body = BBCode::removeShareInformation($b["body"]);
379 switch ($siteinfo["type"]) {
381 $params['type'] = "photo";
382 $params['caption'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS);;
384 if (isset($siteinfo["url"])) {
385 $params['link'] = $siteinfo["url"];
388 $params['source'] = $siteinfo["image"];
392 $params['type'] = "link";
393 $params['title'] = $title;
394 $params['url'] = $siteinfo["url"];
395 $params['description'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS);
399 $params['type'] = "audio";
400 $params['external_url'] = $siteinfo["url"];
401 $params['caption'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS);
405 $params['type'] = "video";
406 $params['embed'] = $siteinfo["url"];
407 $params['caption'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS);
411 $params['type'] = "text";
412 $params['title'] = $title;
413 $params['body'] = BBCode::convertForUriId($b['uri-id'], $b['body'], BBCode::CONNECTORS);
417 if (isset($params['caption']) && (trim($title) != "")) {
418 $params['caption'] = '<h1>'.$title."</h1>".
419 "<p>".$params['caption']."</p>";
422 if (empty($params['caption']) && !empty($siteinfo["description"])) {
423 $params['caption'] = BBCode::convertForUriId($b['uri-id'], "[quote]" . $siteinfo["description"] . "[/quote]", BBCode::CONNECTORS);
426 $consumer_key = DI::config()->get('tumblr','consumer_key');
427 $consumer_secret = DI::config()->get('tumblr','consumer_secret');
429 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
431 // Make an API call with the TumblrOAuth instance.
432 $x = $tum_oauth->post($tmbl_blog,$params);
433 $ret_code = $tum_oauth->http_code;
436 if ($ret_code == 201) {
437 Logger::notice('tumblr_send: success');
438 } elseif ($ret_code == 403) {
439 Logger::notice('tumblr_send: authentication failure');
441 Logger::notice('tumblr_send: general error', ['error' => $x]);