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\Content\Text\NPF;
14 use Friendica\Core\Hook;
15 use Friendica\Core\Logger;
16 use Friendica\Core\Renderer;
17 use Friendica\Core\System;
19 use Friendica\Model\Item;
20 use Friendica\Model\Photo;
21 use Friendica\Model\Post;
22 use Friendica\Model\Tag;
23 use Friendica\Util\DateTimeFormat;
24 use Friendica\Util\Network;
25 use GuzzleHttp\Client;
26 use GuzzleHttp\Exception\RequestException;
27 use GuzzleHttp\HandlerStack;
28 use GuzzleHttp\Subscriber\Oauth\Oauth1;
30 function tumblr_install()
32 Hook::register('hook_fork', 'addon/tumblr/tumblr.php', 'tumblr_hook_fork');
33 Hook::register('post_local', 'addon/tumblr/tumblr.php', 'tumblr_post_local');
34 Hook::register('notifier_normal', 'addon/tumblr/tumblr.php', 'tumblr_send');
35 Hook::register('jot_networks', 'addon/tumblr/tumblr.php', 'tumblr_jot_nets');
36 Hook::register('connector_settings', 'addon/tumblr/tumblr.php', 'tumblr_settings');
37 Hook::register('connector_settings_post', 'addon/tumblr/tumblr.php', 'tumblr_settings_post');
41 * This is a statement rather than an actual function definition. The simple
42 * existence of this method is checked to figure out if the addon offers a
45 function tumblr_module()
49 function tumblr_content()
51 if (!DI::userSession()->getLocalUserId()) {
52 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
56 if (isset(DI::args()->getArgv()[1])) {
57 switch (DI::args()->getArgv()[1]) {
59 $o = tumblr_connect();
63 $o = tumblr_callback();
67 $o = print_r(DI::args()->getArgv(), true);
71 $o = tumblr_connect();
77 function tumblr_addon_admin(string &$o)
79 $t = Renderer::getMarkupTemplate('admin.tpl', 'addon/tumblr/');
81 $o = Renderer::replaceMacros($t, [
82 '$submit' => DI::l10n()->t('Save Settings'),
83 // name, label, value, help, [extra values]
84 '$consumer_key' => ['consumer_key', DI::l10n()->t('Consumer Key'), DI::config()->get('tumblr', 'consumer_key'), ''],
85 '$consumer_secret' => ['consumer_secret', DI::l10n()->t('Consumer Secret'), DI::config()->get('tumblr', 'consumer_secret'), ''],
89 function tumblr_addon_admin_post()
91 DI::config()->set('tumblr', 'consumer_key', trim($_POST['consumer_key'] ?? ''));
92 DI::config()->set('tumblr', 'consumer_secret', trim($_POST['consumer_secret'] ?? ''));
95 function tumblr_connect()
97 // Start a session. This is necessary to hold on to a few keys the callback script will also need
100 // Define the needed keys
101 $consumer_key = DI::config()->get('tumblr', 'consumer_key');
102 $consumer_secret = DI::config()->get('tumblr', 'consumer_secret');
104 // The callback URL is the script that gets called after the user authenticates with tumblr
105 // In this example, it would be the included callback.php
106 $callback_url = DI::baseUrl() . '/tumblr/callback';
108 // Let's begin. First we need a Request Token. The request token is required to send the user
109 // to Tumblr's login page.
111 // Create a new instance of the TumblrOAuth library. For this step, all we need to give the library is our
112 // Consumer Key and Consumer Secret
113 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret);
115 // Ask Tumblr for a Request Token. Specify the Callback URL here too (although this should be optional)
116 $request_token = $tum_oauth->getRequestToken($callback_url);
118 // Store the request token and Request Token Secret as out callback.php script will need this
119 DI::session()->set('request_token', $request_token['oauth_token']);
120 DI::session()->set('request_token_secret', $request_token['oauth_token_secret']);
122 // Check the HTTP Code. It should be a 200 (OK), if it's anything else then something didn't work.
123 switch ($tum_oauth->http_code) {
125 // Ask Tumblr to give us a special address to their login page
126 $url = $tum_oauth->getAuthorizeURL($request_token['oauth_token']);
128 // Redirect the user to the login URL given to us by Tumblr
129 System::externalRedirect($url);
132 * That's it for our side. The user is sent to a Tumblr Login page and
133 * asked to authroize our app. After that, Tumblr sends the user back to
134 * our Callback URL (callback.php) along with some information we need to get
140 // Give an error message
141 $o = 'Could not connect to Tumblr. Refresh the page or try again later.';
147 function tumblr_callback()
149 // Start a session, load the library
152 // Define the needed keys
153 $consumer_key = DI::config()->get('tumblr', 'consumer_key');
154 $consumer_secret = DI::config()->get('tumblr', 'consumer_secret');
156 // Once the user approves your app at Tumblr, they are sent back to this script.
157 // This script is passed two parameters in the URL, oauth_token (our Request Token)
158 // and oauth_verifier (Key that we need to get Access Token).
159 // We'll also need out Request Token Secret, which we stored in a session.
161 // Create instance of TumblrOAuth.
162 // It'll need our Consumer Key and Secret as well as our Request Token and Secret
163 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret);
165 // Ok, let's get an Access Token. We'll need to pass along our oauth_verifier which was given to us in the URL.
166 $access_token = $tum_oauth->getAccessToken($_REQUEST['oauth_verifier'], DI::session()->get('request_token'), DI::session()->get('request_token_secret'));
168 // We're done with the Request Token and Secret so let's remove those.
169 DI::session()->remove('request_token');
170 DI::session()->remove('request_token_secret');
172 // Make sure nothing went wrong.
173 if (200 == $tum_oauth->http_code) {
176 return 'Unable to authenticate';
179 // What's next? Now that we have an Access Token and Secret, we can make an API call.
180 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'oauth_token', $access_token['oauth_token']);
181 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'oauth_token_secret', $access_token['oauth_token_secret']);
183 DI::baseUrl()->redirect('settings/connectors/tumblr');
186 function tumblr_jot_nets(array &$jotnets_fields)
188 if (!DI::userSession()->getLocalUserId()) {
192 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post')) {
193 $jotnets_fields[] = [
194 'type' => 'checkbox',
197 DI::l10n()->t('Post to Tumblr'),
198 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post_by_default')
204 function tumblr_settings(array &$data)
206 if (!DI::userSession()->getLocalUserId()) {
210 $enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post', false);
211 $def_enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post_by_default', false);
213 $blogs = tumblr_get_blogs(DI::userSession()->getLocalUserId());
214 if (!empty($blogs)) {
215 $page = tumblr_get_page(DI::userSession()->getLocalUserId(), $blogs);
217 $page_select = ['tumblr_page', DI::l10n()->t('Post to page:'), $page, '', $blogs];
220 $t = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/tumblr/');
221 $html = Renderer::replaceMacros($t, [
223 'connect' => DI::l10n()->t('(Re-)Authenticate your tumblr page'),
224 'noconnect' => DI::l10n()->t('You are not authenticated to tumblr'),
227 '$authenticate_url' => DI::baseUrl() . '/tumblr/connect',
229 '$enable' => ['tumblr', DI::l10n()->t('Enable Tumblr Post Addon'), $enabled],
230 '$bydefault' => ['tumblr_bydefault', DI::l10n()->t('Post to Tumblr by default'), $def_enabled],
231 '$page_select' => $page_select ?? '',
235 'connector' => 'tumblr',
236 'title' => DI::l10n()->t('Tumblr Export'),
237 'image' => 'images/tumblr.png',
238 'enabled' => $enabled,
243 function tumblr_settings_post(array &$b)
245 if (!empty($_POST['tumblr-submit'])) {
246 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'post', intval($_POST['tumblr']));
247 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'page', $_POST['tumblr_page']);
248 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'post_by_default', intval($_POST['tumblr_bydefault']));
252 function tumblr_hook_fork(array &$b)
254 if ($b['name'] != 'notifier_normal') {
261 $post['deleted'] || $post['private'] || ($post['created'] !== $post['edited']) ||
262 !strstr($post['postopts'] ?? '', 'tumblr') || ($post['parent'] != $post['id'])
264 $b['execute'] = false;
269 function tumblr_post_local(array &$b)
271 // This can probably be changed to allow editing by pointing to a different API endpoint
277 if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
281 if ($b['private'] || $b['parent']) {
285 $tmbl_post = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post'));
287 $tmbl_enable = (($tmbl_post && !empty($_REQUEST['tumblr_enable'])) ? intval($_REQUEST['tumblr_enable']) : 0);
289 if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post_by_default'))) {
297 if (strlen($b['postopts'])) {
298 $b['postopts'] .= ',';
301 $b['postopts'] .= 'tumblr';
304 function tumblr_send(array &$b)
306 if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) {
310 if (!strstr($b['postopts'], 'tumblr')) {
314 if ($b['gravity'] != Item::GRAVITY_PARENT) {
318 if (tumblr_send_npf($b)) {
322 $connection = tumblr_connection($b['uid']);
323 if (empty($connection)) {
327 $b['body'] = BBCode::removeAttachment($b['body']);
329 $title = trim($b['title']);
331 $media = Post\Media::getByURIId($b['uri-id'], [Post\Media::HTML, Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE]);
333 $photo = array_search(Post\Media::IMAGE, array_column($media, 'type'));
334 $link = array_search(Post\Media::HTML, array_column($media, 'type'));
335 $audio = array_search(Post\Media::AUDIO, array_column($media, 'type'));
336 $video = array_search(Post\Media::VIDEO, array_column($media, 'type'));
339 'state' => 'published',
340 'tags' => implode(',', array_column(Tag::getByURIId($b['uri-id']), 'name')),
345 $body = BBCode::removeShareInformation($b['body']);
346 $body = Post\Media::removeFromEndOfBody($body);
348 if ($photo !== false) {
349 $params['type'] = 'photo';
350 $params['caption'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS);
351 $params['data'] = [];
352 foreach ($media as $photo) {
353 if ($photo['type'] == Post\Media::IMAGE) {
354 if (Network::isLocalLink($photo['url']) && ($data = Photo::getResourceData($photo['url']))) {
355 $photo = Photo::selectFirst([], ["`resource-id` = ? AND `scale` > ?", $data['guid'], 0]);
356 if (!empty($photo)) {
357 $params['data'][] = Photo::getImageDataForPhoto($photo);
362 } elseif ($link !== false) {
363 $params['type'] = 'link';
364 $params['title'] = $media[$link]['name'];
365 $params['url'] = $media[$link]['url'];
366 $params['description'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS);
368 if (!empty($media[$link]['preview'])) {
369 $params['thumbnail'] = $media[$link]['preview'];
371 if (!empty($media[$link]['description'])) {
372 $params['excerpt'] = $media[$link]['description'];
374 if (!empty($media[$link]['author-name'])) {
375 $params['author'] = $media[$link]['author-name'];
377 } elseif ($audio !== false) {
378 $params['type'] = 'audio';
379 $params['external_url'] = $media[$audio]['url'];
380 $params['caption'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS);
381 } elseif ($video !== false) {
382 $params['type'] = 'video';
383 $params['embed'] = $media[$video]['url'];
384 $params['caption'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS);
386 $params['type'] = 'text';
387 $params['title'] = $title;
388 $params['body'] = BBCode::convertForUriId($b['uri-id'], $b['body'], BBCode::CONNECTORS);
391 if (isset($params['caption']) && (trim($title) != '')) {
392 $params['caption'] = '<h1>' . $title . '</h1>' .
393 '<p>' . $params['caption'] . '</p>';
396 $page = tumblr_get_page($b['uid']);
398 $result = tumblr_post($connection, 'blog/' . $page . '/post', $params);
400 if ($result['success']) {
401 Logger::info('success', ['blog' => $page, 'params' => $params]);
404 Logger::notice('error', ['blog' => $page, 'params' => $params, 'result' => $result['data']]);
409 function tumblr_send_npf(array $post): bool
411 $page = tumblr_get_page($post['uid']);
413 $connection = tumblr_connection($post['uid']);
415 Logger::notice('Missing page, post will not be send to Tumblr.', ['uid' => $post['uid'], 'page' => $page, 'id' => $post['id']]);
416 // "true" is returned, since the legacy function will fail as well.
420 $post['body'] = Post\Media::addAttachmentsToBody($post['uri-id'], $post['body']);
421 if (!empty($post['title'])) {
422 $post['body'] = '[h1]' . $post['title'] . "[/h1]\n" . $post['body'];
426 'content' => NPF::fromBBCode($post['body'], $post['uri-id']),
427 'state' => 'published',
428 'date' => DateTimeFormat::utc($post['created'], DateTimeFormat::ATOM),
429 'tags' => implode(',', array_column(Tag::getByURIId($post['uri-id']), 'name')),
430 'is_private' => false,
431 'interactability_reblog' => 'everyone'
434 $result = tumblr_post($connection, 'blog/' . $page . '/posts', $params);
436 if ($result['success']) {
437 Logger::info('success', ['blog' => $page, 'params' => $params]);
440 Logger::notice('error', ['blog' => $page, 'params' => $params, 'result' => $result['data']]);
445 function tumblr_connection(int $uid): GuzzleHttp\Client|null
447 $oauth_token = DI::pConfig()->get($uid, 'tumblr', 'oauth_token');
448 $oauth_token_secret = DI::pConfig()->get($uid, 'tumblr', 'oauth_token_secret');
450 $consumer_key = DI::config()->get('tumblr', 'consumer_key');
451 $consumer_secret = DI::config()->get('tumblr', 'consumer_secret');
453 if (!$consumer_key || !$consumer_secret || !$oauth_token || !$oauth_token_secret) {
454 Logger::notice('Missing data, connection is not established', ['uid' => $uid]);
457 return tumblr_client($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
460 function tumblr_client(string $consumer_key, string $consumer_secret, string $oauth_token, string $oauth_token_secret): GuzzleHttp\Client
462 $stack = HandlerStack::create();
464 $middleware = new Oauth1([
465 'consumer_key' => $consumer_key,
466 'consumer_secret' => $consumer_secret,
467 'token' => $oauth_token,
468 'token_secret' => $oauth_token_secret
470 $stack->push($middleware);
473 'base_uri' => 'https://api.tumblr.com/v2/',
478 function tumblr_get_page(int $uid, array $blogs = [])
480 $page = DI::pConfig()->get($uid, 'tumblr', 'page');
482 if (!empty($page) && (strpos($page, '/') === false)) {
487 $blogs = tumblr_get_blogs($uid);
490 if (!empty($blogs)) {
491 $page = array_key_first($blogs);
492 DI::pConfig()->set($uid, 'tumblr', 'page', $page);
499 function tumblr_get_blogs(int $uid)
501 $connection = tumblr_connection($uid);
502 if (empty($connection)) {
506 $userinfo = tumblr_get($connection, 'user/info');
507 if (empty($userinfo['success'])) {
512 foreach ($userinfo['data']->response->user->blogs as $blog) {
513 $blogs[$blog->uuid] = $blog->name;
518 function tumblr_get($connection, string $url)
521 $res = $connection->get($url, ['auth' => 'oauth']);
524 $data = json_decode($res->getBody()->getContents());
525 } catch (RequestException $exception) {
528 Logger::notice('Request failed', ['code' => $exception->getCode(), 'message' => $exception->getMessage()]);
530 return ['success' => $success, 'data' => $data];
533 function tumblr_post($connection, string $url, array $parameter)
536 $res = $connection->post($url, ['auth' => 'oauth', 'json' => $parameter]);
539 $data = json_decode($res->getBody()->getContents());
540 } catch (RequestException $exception) {
542 $data = json_decode($exception->getResponse()->getBody()->getContents());
543 Logger::notice('Post failed', ['code' => $exception->getCode(), 'message' => $exception->getMessage()]);
545 return ['success' => $success, 'data' => $data];