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 use Friendica\Content\PageInfo;
11 use Friendica\Content\Text\BBCode;
12 use Friendica\Content\Text\HTML;
13 use Friendica\Content\Text\NPF;
14 use Friendica\Core\Cache\Enum\Duration;
15 use Friendica\Core\Config\Util\ConfigFileManager;
16 use Friendica\Core\Hook;
17 use Friendica\Core\Logger;
18 use Friendica\Core\Protocol;
19 use Friendica\Core\Renderer;
20 use Friendica\Core\System;
21 use Friendica\Core\Worker;
22 use Friendica\Database\DBA;
24 use Friendica\Model\Contact;
25 use Friendica\Model\Item;
26 use Friendica\Model\Photo;
27 use Friendica\Model\Post;
28 use Friendica\Model\Tag;
29 use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
30 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
31 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
32 use Friendica\Protocol\Activity;
33 use Friendica\Util\DateTimeFormat;
34 use Friendica\Util\Network;
35 use Friendica\Util\Strings;
36 use GuzzleHttp\Client;
37 use GuzzleHttp\Exception\RequestException;
38 use GuzzleHttp\HandlerStack;
39 use GuzzleHttp\Subscriber\Oauth\Oauth1;
41 define('TUMBLR_DEFAULT_POLL_INTERVAL', 10); // given in minutes
42 define('TUMBLR_DEFAULT_MAXIMUM_TAGS', 10);
44 function tumblr_install()
46 Hook::register('load_config', __FILE__, 'tumblr_load_config');
47 Hook::register('hook_fork', __FILE__, 'tumblr_hook_fork');
48 Hook::register('post_local', __FILE__, 'tumblr_post_local');
49 Hook::register('notifier_normal', __FILE__, 'tumblr_send');
50 Hook::register('jot_networks', __FILE__, 'tumblr_jot_nets');
51 Hook::register('connector_settings', __FILE__, 'tumblr_settings');
52 Hook::register('connector_settings_post', __FILE__, 'tumblr_settings_post');
53 Hook::register('cron', __FILE__, 'tumblr_cron');
54 Hook::register('support_follow', __FILE__, 'tumblr_support_follow');
55 Hook::register('support_probe', __FILE__, 'tumblr_support_probe');
56 Hook::register('follow', __FILE__, 'tumblr_follow');
57 Hook::register('unfollow', __FILE__, 'tumblr_unfollow');
58 Hook::register('block', __FILE__, 'tumblr_block');
59 Hook::register('unblock', __FILE__, 'tumblr_unblock');
60 Hook::register('check_item_notification', __FILE__, 'tumblr_check_item_notification');
61 Hook::register('probe_detect', __FILE__, 'tumblr_probe_detect');
62 Hook::register('item_by_link', __FILE__, 'tumblr_item_by_link');
63 Logger::info('installed tumblr');
66 function tumblr_load_config(ConfigFileManager $loader)
68 DI::app()->getConfigCache()->load($loader->loadAddonConfig('tumblr'), \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC);
71 function tumblr_check_item_notification(array &$notification_data)
73 if (!tumblr_enabled_for_user($notification_data['uid'])) {
77 $page = tumblr_get_page($notification_data['uid']);
82 $own_user = Contact::selectFirst(['url', 'alias'], ['network' => Protocol::TUMBLR, 'uid' => [0, $notification_data['uid']], 'poll' => 'tumblr::' . $page]);
84 $notification_data['profiles'][] = $own_user['url'];
85 $notification_data['profiles'][] = $own_user['alias'];
89 function tumblr_probe_detect(array &$hookData)
91 // Don't overwrite an existing result
92 if (isset($hookData['result'])) {
96 // Avoid a lookup for the wrong network
97 if (!in_array($hookData['network'], ['', Protocol::TUMBLR])) {
101 $hookData['result'] = tumblr_get_contact_by_url($hookData['uri']);
103 // Authoritative probe should set the result even if the probe was unsuccessful
104 if ($hookData['network'] == Protocol::TUMBLR && empty($hookData['result'])) {
105 $hookData['result'] = [];
109 function tumblr_item_by_link(array &$hookData)
111 // Don't overwrite an existing result
112 if (isset($hookData['item_id'])) {
116 if (!tumblr_enabled_for_user($hookData['uid'])) {
120 if (!preg_match('#^https?://www\.tumblr.com/blog/view/(.+)/(\d+).*#', $hookData['uri'], $matches) && !preg_match('#^https?://www\.tumblr.com/(.+)/(\d+).*#', $hookData['uri'], $matches)) {
124 Logger::debug('Found tumblr post', ['url' => $hookData['uri'], 'blog' => $matches[1], 'id' => $matches[2]]);
126 $parameters = ['id' => $matches[2], 'reblog_info' => false, 'notes_info' => false, 'npf' => false];
127 $result = tumblr_get($hookData['uid'], 'blog/' . $matches[1] . '/posts', $parameters);
128 if ($result->meta->status > 399) {
129 Logger::notice('Error fetching status', ['meta' => $result->meta, 'response' => $result->response, 'errors' => $result->errors, 'blog' => $matches[1], 'id' => $matches[2]]);
133 Logger::debug('Got post', ['blog' => $matches[1], 'id' => $matches[2], 'result' => $result->response->posts]);
134 if (!empty($result->response->posts)) {
135 $hookData['item_id'] = tumblr_process_post($result->response->posts[0], $hookData['uid'], Item::PR_FETCHED);
139 function tumblr_support_follow(array &$data)
141 if ($data['protocol'] == Protocol::TUMBLR) {
142 $data['result'] = true;
146 function tumblr_support_probe(array &$data)
148 if ($data['protocol'] == Protocol::TUMBLR) {
149 $data['result'] = true;
153 function tumblr_follow(array &$hook_data)
155 $uid = DI::userSession()->getLocalUserId();
157 if (!tumblr_enabled_for_user($uid)) {
161 Logger::debug('Check if contact is Tumblr', ['url' => $hook_data['url']]);
163 $fields = tumblr_get_contact_by_url($hook_data['url']);
164 if (empty($fields)) {
165 Logger::debug('Contact is not a Tumblr contact', ['url' => $hook_data['url']]);
169 $result = tumblr_post($uid, 'user/follow', ['url' => $fields['url']]);
170 if ($result->meta->status <= 399) {
171 $hook_data['contact'] = $fields;
172 Logger::debug('Successfully start following', ['url' => $fields['url']]);
174 Logger::notice('Following failed', ['meta' => $result->meta, 'response' => $result->response, 'errors' => $result->errors, 'url' => $fields['url']]);
178 function tumblr_unfollow(array &$hook_data)
180 if (!tumblr_enabled_for_user($hook_data['uid'])) {
184 if (!tumblr_get_contact_uuid($hook_data['contact'])) {
187 $result = tumblr_post($hook_data['uid'], 'user/unfollow', ['url' => $hook_data['contact']['url']]);
188 $hook_data['result'] = ($result->meta->status <= 399);
191 function tumblr_block(array &$hook_data)
193 if (!tumblr_enabled_for_user($hook_data['uid'])) {
197 $uuid = tumblr_get_contact_uuid($hook_data['contact']);
202 $result = tumblr_post($hook_data['uid'], 'blog/' . tumblr_get_page($hook_data['uid']) . '/blocks', ['blocked_tumblelog' => $uuid]);
203 $hook_data['result'] = ($result->meta->status <= 399);
205 if ($hook_data['result']) {
206 $cdata = Contact::getPublicAndUserContactID($hook_data['contact']['id'], $hook_data['uid']);
207 if (!empty($cdata['user'])) {
208 Contact::remove($cdata['user']);
213 function tumblr_unblock(array &$hook_data)
215 if (!tumblr_enabled_for_user($hook_data['uid'])) {
219 $uuid = tumblr_get_contact_uuid($hook_data['contact']);
224 $result = tumblr_delete($hook_data['uid'], 'blog/' . tumblr_get_page($hook_data['uid']) . '/blocks', ['blocked_tumblelog' => $uuid]);
225 $hook_data['result'] = ($result->meta->status <= 399);
228 function tumblr_get_contact_uuid(array $contact): string
230 if (($contact['network'] != Protocol::TUMBLR) || (substr($contact['poll'], 0, 8) != 'tumblr::')) {
233 return substr($contact['poll'], 8);
237 * This is a statement rather than an actual function definition. The simple
238 * existence of this method is checked to figure out if the addon offers a
241 function tumblr_module()
245 function tumblr_content()
247 if (!DI::userSession()->getLocalUserId()) {
248 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
252 switch (DI::args()->getArgv()[1] ?? '') {
261 DI::baseUrl()->redirect('settings/connectors/tumblr');
264 function tumblr_redirect()
266 if (($_REQUEST['state'] ?? '') != DI::session()->get('oauth_state')) {
270 tumblr_get_token(DI::userSession()->getLocalUserId(), $_REQUEST['code'] ?? '');
273 function tumblr_connect()
275 // Define the needed keys
276 $consumer_key = DI::config()->get('tumblr', 'consumer_key');
277 $consumer_secret = DI::config()->get('tumblr', 'consumer_secret');
279 if (empty($consumer_key) || empty($consumer_secret)) {
283 $state = base64_encode(random_bytes(20));
284 DI::session()->set('oauth_state', $state);
287 'client_id' => $consumer_key,
288 'response_type' => 'code',
289 'scope' => 'basic write offline_access',
293 System::externalRedirect('https://www.tumblr.com/oauth2/authorize?' . http_build_query($parameters));
296 function tumblr_addon_admin(string &$o)
298 $t = Renderer::getMarkupTemplate('admin.tpl', 'addon/tumblr/');
300 $o = Renderer::replaceMacros($t, [
301 '$submit' => DI::l10n()->t('Save Settings'),
302 '$consumer_key' => ['consumer_key', DI::l10n()->t('Consumer Key'), DI::config()->get('tumblr', 'consumer_key'), ''],
303 '$consumer_secret' => ['consumer_secret', DI::l10n()->t('Consumer Secret'), DI::config()->get('tumblr', 'consumer_secret'), ''],
304 '$max_tags' => ['max_tags', DI::l10n()->t('Maximum tags'), DI::config()->get('tumblr', 'max_tags') ?? TUMBLR_DEFAULT_MAXIMUM_TAGS, DI::l10n()->t('Maximum number of tags that a user can follow. Enter 0 to deactivate the feature.')],
308 function tumblr_addon_admin_post()
310 DI::config()->set('tumblr', 'consumer_key', trim($_POST['consumer_key'] ?? ''));
311 DI::config()->set('tumblr', 'consumer_secret', trim($_POST['consumer_secret'] ?? ''));
312 DI::config()->set('tumblr', 'max_tags', max(0, intval($_POST['max_tags'] ?? '')));
315 function tumblr_settings(array &$data)
317 if (!DI::userSession()->getLocalUserId()) {
321 $enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post') ?? false;
322 $def_enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post_by_default') ?? false;
323 $import = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'import') ?? false;
324 $tags = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'tags') ?? [];
326 $max_tags = DI::config()->get('tumblr', 'max_tags') ?? TUMBLR_DEFAULT_MAXIMUM_TAGS;
328 $tags_str = implode(', ', $tags);
329 $cachekey = 'tumblr-blogs-' . DI::userSession()->getLocalUserId();
330 $blogs = DI::cache()->get($cachekey);
332 $blogs = tumblr_get_blogs(DI::userSession()->getLocalUserId());
333 if (!empty($blogs)) {
334 DI::cache()->set($cachekey, $blogs, Duration::HALF_HOUR);
338 if (!empty($blogs)) {
339 $page = tumblr_get_page(DI::userSession()->getLocalUserId(), $blogs);
341 $page_select = ['tumblr_page', DI::l10n()->t('Post to page:'), $page, '', $blogs];
344 $t = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/tumblr/');
345 $html = Renderer::replaceMacros($t, [
347 'connect' => DI::l10n()->t('(Re-)Authenticate your tumblr page'),
348 'noconnect' => DI::l10n()->t('You are not authenticated to tumblr'),
351 '$authenticate_url' => DI::baseUrl() . '/tumblr/connect',
353 '$enable' => ['tumblr', DI::l10n()->t('Enable Tumblr Post Addon'), $enabled],
354 '$bydefault' => ['tumblr_bydefault', DI::l10n()->t('Post to Tumblr by default'), $def_enabled],
355 '$import' => ['tumblr_import', DI::l10n()->t('Import the remote timeline'), $import],
356 '$tags' => ['tags', DI::l10n()->t('Subscribed tags'), $tags_str, DI::l10n()->t('Comma separated list of up to %d tags that will be imported additionally to the timeline', $max_tags)],
357 '$page_select' => $page_select ?? '',
361 'connector' => 'tumblr',
362 'title' => DI::l10n()->t('Tumblr Import/Export'),
363 'image' => 'images/tumblr.png',
364 'enabled' => $enabled,
369 function tumblr_jot_nets(array &$jotnets_fields)
371 if (!DI::userSession()->getLocalUserId()) {
375 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post')) {
376 $jotnets_fields[] = [
377 'type' => 'checkbox',
380 DI::l10n()->t('Post to Tumblr'),
381 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post_by_default')
387 function tumblr_settings_post(array &$b)
389 if (!empty($_POST['tumblr-submit'])) {
390 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'post', intval($_POST['tumblr']));
391 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'page', $_POST['tumblr_page']);
392 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'post_by_default', intval($_POST['tumblr_bydefault']));
393 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'import', intval($_POST['tumblr_import']));
395 $max_tags = DI::config()->get('tumblr', 'max_tags') ?? TUMBLR_DEFAULT_MAXIMUM_TAGS;
397 foreach (explode(',', $_POST['tags']) as $tag) {
398 if (count($tags) < $max_tags) {
399 $tags[] = trim($tag, ' #');
403 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'tags', $tags);
407 function tumblr_cron()
409 $last = DI::keyValue()->get('tumblr_last_poll');
411 $poll_interval = intval(DI::config()->get('tumblr', 'poll_interval'));
412 if (!$poll_interval) {
413 $poll_interval = TUMBLR_DEFAULT_POLL_INTERVAL;
417 $next = $last + ($poll_interval * 60);
418 if ($next > time()) {
419 Logger::notice('poll interval not reached');
423 Logger::notice('cron_start');
425 $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
426 if ($abandon_days < 1) {
430 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
432 $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'tumblr', 'k' => 'import', 'v' => true]);
433 foreach ($pconfigs as $pconfig) {
434 if ($abandon_days != 0) {
435 if (!DBA::exists('user', ["`uid` = ? AND `login_date` >= ?", $pconfig['uid'], $abandon_limit])) {
436 Logger::notice('abandoned account: timeline from user will not be imported', ['user' => $pconfig['uid']]);
441 Logger::notice('importing timeline - start', ['user' => $pconfig['uid']]);
442 tumblr_fetch_dashboard($pconfig['uid']);
443 tumblr_fetch_tags($pconfig['uid']);
444 Logger::notice('importing timeline - done', ['user' => $pconfig['uid']]);
447 $last_clean = DI::keyValue()->get('tumblr_last_clean');
448 if (empty($last_clean) || ($last_clean + 86400 < time())) {
449 Logger::notice('Start contact cleanup');
450 $contacts = DBA::select('account-user-view', ['id', 'pid'], ["`network` = ? AND `uid` != ? AND `rel` = ?", Protocol::TUMBLR, 0, Contact::NOTHING]);
451 while ($contact = DBA::fetch($contacts)) {
452 Worker::add(Worker::PRIORITY_LOW, 'MergeContact', $contact['pid'], $contact['id'], 0);
454 DBA::close($contacts);
455 DI::keyValue()->set('tumblr_last_clean', time());
456 Logger::notice('Contact cleanup done');
459 Logger::notice('cron_end');
461 DI::keyValue()->set('tumblr_last_poll', time());
464 function tumblr_hook_fork(array &$b)
466 if ($b['name'] != 'notifier_normal') {
472 // Editing is not supported by the addon
473 if (($post['created'] !== $post['edited']) && !$post['deleted']) {
474 DI::logger()->info('Editing is not supported by the addon');
475 $b['execute'] = false;
479 if (DI::pConfig()->get($post['uid'], 'tumblr', 'import')) {
480 // Don't post if it isn't a reply to a tumblr post
481 if (($post['parent'] != $post['id']) && !Post::exists(['id' => $post['parent'], 'network' => Protocol::TUMBLR])) {
482 Logger::notice('No tumblr parent found', ['item' => $post['id']]);
483 $b['execute'] = false;
486 } elseif (!strstr($post['postopts'] ?? '', 'tumblr') || ($post['parent'] != $post['id']) || $post['private']) {
487 DI::logger()->info('Activities are never exported when we don\'t import the tumblr timeline', ['uid' => $post['uid']]);
488 $b['execute'] = false;
493 function tumblr_post_local(array &$b)
499 if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
503 if ($b['private'] || $b['parent']) {
507 $tmbl_post = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post'));
508 $tmbl_enable = (($tmbl_post && !empty($_REQUEST['tumblr_enable'])) ? intval($_REQUEST['tumblr_enable']) : 0);
510 // if API is used, default to the chosen settings
511 if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post_by_default'))) {
519 if (strlen($b['postopts'])) {
520 $b['postopts'] .= ',';
523 $b['postopts'] .= 'tumblr';
526 function tumblr_send(array &$b)
528 if (($b['created'] !== $b['edited']) && !$b['deleted']) {
532 if ($b['gravity'] != Item::GRAVITY_PARENT) {
533 Logger::debug('Got comment', ['item' => $b]);
535 $parent = tumblr_get_post_from_uri($b['thr-parent']);
536 if (empty($parent)) {
537 Logger::notice('No tumblr post', ['thr-parent' => $b['thr-parent']]);
541 Logger::debug('Parent found', ['parent' => $parent]);
543 $page = tumblr_get_page($b['uid']);
545 if ($b['gravity'] == Item::GRAVITY_COMMENT) {
546 Logger::notice('Commenting is not supported (yet)');
548 if (($b['verb'] == Activity::LIKE) && !$b['deleted']) {
549 $params = ['id' => $parent['id'], 'reblog_key' => $parent['reblog_key']];
550 $result = tumblr_post($b['uid'], 'user/like', $params);
551 } elseif (($b['verb'] == Activity::LIKE) && $b['deleted']) {
552 $params = ['id' => $parent['id'], 'reblog_key' => $parent['reblog_key']];
553 $result = tumblr_post($b['uid'], 'user/unlike', $params);
554 } elseif (($b['verb'] == Activity::ANNOUNCE) && !$b['deleted']) {
555 $params = ['id' => $parent['id'], 'reblog_key' => $parent['reblog_key']];
556 $result = tumblr_post($b['uid'], 'blog/' . $page . '/post/reblog', $params);
557 } elseif (($b['verb'] == Activity::ANNOUNCE) && $b['deleted']) {
558 $announce = tumblr_get_post_from_uri($b['extid']);
559 if (empty($announce)) {
562 $params = ['id' => $announce['id']];
563 $result = tumblr_post($b['uid'], 'blog/' . $page . '/post/delete', $params);
565 // Unsupported activity
569 if ($result->meta->status < 400) {
570 Logger::info('Successfully performed activity', ['verb' => $b['verb'], 'deleted' => $b['deleted'], 'meta' => $result->meta, 'response' => $result->response]);
571 if (!$b['deleted'] && !empty($result->response->id_string)) {
572 Item::update(['extid' => 'tumblr::' . $result->response->id_string], ['id' => $b['id']]);
575 Logger::notice('Error while performing activity', ['verb' => $b['verb'], 'deleted' => $b['deleted'], 'meta' => $result->meta, 'response' => $result->response, 'errors' => $result->errors, 'params' => $params]);
579 } elseif ($b['private'] || !strstr($b['postopts'], 'tumblr')) {
583 if (!tumblr_send_npf($b)) {
584 tumblr_send_legacy($b);
588 function tumblr_send_legacy(array $b)
590 $b['body'] = BBCode::removeAttachment($b['body']);
592 $title = trim($b['title']);
594 $media = Post\Media::getByURIId($b['uri-id'], [Post\Media::HTML, Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE]);
596 $photo = array_search(Post\Media::IMAGE, array_column($media, 'type'));
597 $link = array_search(Post\Media::HTML, array_column($media, 'type'));
598 $audio = array_search(Post\Media::AUDIO, array_column($media, 'type'));
599 $video = array_search(Post\Media::VIDEO, array_column($media, 'type'));
602 'state' => 'published',
603 'tags' => implode(',', array_column(Tag::getByURIId($b['uri-id']), 'name')),
608 $body = BBCode::removeShareInformation($b['body']);
609 $body = Post\Media::removeFromEndOfBody($body);
611 if ($photo !== false) {
612 $params['type'] = 'photo';
613 $params['caption'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS);
614 $params['data'] = [];
615 foreach ($media as $photo) {
616 if ($photo['type'] == Post\Media::IMAGE) {
617 if (Network::isLocalLink($photo['url']) && ($data = Photo::getResourceData($photo['url']))) {
618 $photo = Photo::selectFirst([], ["`resource-id` = ? AND `scale` > ?", $data['guid'], 0]);
619 if (!empty($photo)) {
620 $params['data'][] = Photo::getImageDataForPhoto($photo);
625 } elseif ($link !== false) {
626 $params['type'] = 'link';
627 $params['title'] = $media[$link]['name'];
628 $params['url'] = $media[$link]['url'];
629 $params['description'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS);
631 if (!empty($media[$link]['preview'])) {
632 $params['thumbnail'] = $media[$link]['preview'];
634 if (!empty($media[$link]['description'])) {
635 $params['excerpt'] = $media[$link]['description'];
637 if (!empty($media[$link]['author-name'])) {
638 $params['author'] = $media[$link]['author-name'];
640 } elseif ($audio !== false) {
641 $params['type'] = 'audio';
642 $params['external_url'] = $media[$audio]['url'];
643 $params['caption'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS);
644 } elseif ($video !== false) {
645 $params['type'] = 'video';
646 $params['embed'] = $media[$video]['url'];
647 $params['caption'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS);
649 $params['type'] = 'text';
650 $params['title'] = $title;
651 $params['body'] = BBCode::convertForUriId($b['uri-id'], $b['body'], BBCode::CONNECTORS);
654 if (isset($params['caption']) && (trim($title) != '')) {
655 $params['caption'] = '<h1>' . $title . '</h1>' .
656 '<p>' . $params['caption'] . '</p>';
659 $page = tumblr_get_page($b['uid']);
661 $result = tumblr_post($b['uid'], 'blog/' . $page . '/post', $params);
663 if ($result->meta->status < 400) {
664 Logger::info('Success (legacy)', ['blog' => $page, 'meta' => $result->meta, 'response' => $result->response]);
666 Logger::notice('Error posting blog (legacy)', ['blog' => $page, 'meta' => $result->meta, 'response' => $result->response, 'errors' => $result->errors, 'params' => $params]);
670 function tumblr_send_npf(array $post): bool
672 $page = tumblr_get_page($post['uid']);
675 Logger::notice('Missing page, post will not be send to Tumblr.', ['uid' => $post['uid'], 'page' => $page, 'id' => $post['id']]);
676 // "true" is returned, since the legacy function will fail as well.
680 $post['body'] = Post\Media::addAttachmentsToBody($post['uri-id'], $post['body']);
681 if (!empty($post['title'])) {
682 $post['body'] = '[h1]' . $post['title'] . "[/h1]\n" . $post['body'];
686 'content' => NPF::fromBBCode($post['body'], $post['uri-id']),
687 'state' => 'published',
688 'date' => DateTimeFormat::utc($post['created'], DateTimeFormat::ATOM),
689 'tags' => implode(',', array_column(Tag::getByURIId($post['uri-id']), 'name')),
690 'is_private' => false,
691 'interactability_reblog' => 'everyone'
694 $result = tumblr_post($post['uid'], 'blog/' . $page . '/posts', $params);
696 if ($result->meta->status < 400) {
697 Logger::info('Success (NPF)', ['blog' => $page, 'meta' => $result->meta, 'response' => $result->response]);
700 Logger::notice('Error posting blog (NPF)', ['blog' => $page, 'meta' => $result->meta, 'response' => $result->response, 'errors' => $result->errors, 'params' => $params]);
705 function tumblr_get_post_from_uri(string $uri): array
707 $parts = explode(':', $uri);
708 if (($parts[0] != 'tumblr') || empty($parts[2])) {
712 $post['id'] = $parts[2];
713 $post['reblog_key'] = $parts[3] ?? '';
715 $post['reblog_key'] = str_replace('@t', '', $post['reblog_key']); // Temp
720 * Fetch posts for user defined hashtags for the given user
722 * @param integer $uid
725 function tumblr_fetch_tags(int $uid)
727 if (!DI::config()->get('tumblr', 'max_tags') ?? TUMBLR_DEFAULT_MAXIMUM_TAGS) {
731 foreach (DI::pConfig()->get($uid, 'tumblr', 'tags') ?? [] as $tag) {
732 $data = tumblr_get($uid, 'tagged', ['tag' => $tag]);
733 foreach (array_reverse($data->response) as $post) {
734 $id = tumblr_process_post($post, $uid, Item::PR_TAG);
736 Logger::debug('Tag post imported', ['tag' => $tag, 'id' => $id]);
737 $post = Post::selectFirst(['uri-id'], ['id' => $id]);
738 $stored = Post\Category::storeFileByURIId($post['uri-id'], $uid, Post\Category::SUBCRIPTION, $tag);
739 Logger::debug('Stored tag subscription for user', ['uri-id' => $post['uri-id'], 'uid' => $uid, 'tag' => $tag, 'stored' => $stored]);
746 * Fetch the dashboard (timeline) for the given user
748 * @param integer $uid
751 function tumblr_fetch_dashboard(int $uid)
753 $parameters = ['reblog_info' => false, 'notes_info' => false, 'npf' => false];
755 $last = DI::pConfig()->get($uid, 'tumblr', 'last_id');
757 $parameters['since_id'] = $last;
760 $dashboard = tumblr_get($uid, 'user/dashboard', $parameters);
761 if ($dashboard->meta->status > 399) {
762 Logger::notice('Error fetching dashboard', ['meta' => $dashboard->meta, 'response' => $dashboard->response, 'errors' => $dashboard->errors]);
766 if (empty($dashboard->response->posts)) {
770 foreach (array_reverse($dashboard->response->posts) as $post) {
771 if ($post->id > $last) {
775 Logger::debug('Importing post', ['uid' => $uid, 'created' => date(DateTimeFormat::MYSQL, $post->timestamp), 'id' => $post->id_string]);
777 tumblr_process_post($post, $uid, Item::PR_NONE);
779 DI::pConfig()->set($uid, 'tumblr', 'last_id', $last);
783 function tumblr_process_post(stdClass $post, int $uid, int $post_reason): int
785 $uri = 'tumblr::' . $post->id_string . ':' . $post->reblog_key;
787 if (Post::exists(['uri' => $uri, 'uid' => $uid]) || ($post->blog->uuid == tumblr_get_page($uid))) {
791 $item = tumblr_get_header($post, $uri, $uid);
793 $item = tumblr_get_content($item, $post);
795 $item['post-reason'] = $post_reason;
797 if (!empty($post->followed)) {
798 $item['post-reason'] = Item::PR_FOLLOWER;
801 $id = item::insert($item);
804 $stored = Post::selectFirst(['uri-id'], ['id' => $id]);
806 if (!empty($post->tags)) {
807 foreach ($post->tags as $tag) {
808 Tag::store($stored['uri-id'], Tag::HASHTAG, $tag);
816 * Sets the initial data for the item array
818 * @param stdClass $post
820 * @param integer $uid
823 function tumblr_get_header(stdClass $post, string $uri, int $uid): array
825 $contact = tumblr_get_contact($post->blog, $uid);
827 'network' => Protocol::TUMBLR,
831 'private' => Item::UNLISTED,
832 'verb' => Activity::POST,
833 'contact-id' => $contact['id'],
834 'author-name' => $contact['name'],
835 'author-link' => $contact['url'],
836 'author-avatar' => $contact['avatar'],
837 'plink' => $post->post_url,
838 'created' => date(DateTimeFormat::MYSQL, $post->timestamp)
841 $item['owner-name'] = $item['author-name'];
842 $item['owner-link'] = $item['author-link'];
843 $item['owner-avatar'] = $item['author-avatar'];
849 * Set the body according the given content type
852 * @param stdClass $post
855 function tumblr_get_content(array $item, stdClass $post): array
857 switch ($post->type) {
859 $item['title'] = $post->title;
860 $item['body'] = HTML::toBBCode(tumblr_add_npf_data($post->body, $post->post_url));
864 if (empty($post->text)) {
865 $body = HTML::toBBCode($post->text) . "\n";
869 if (!empty($post->source_title) && !empty($post->source_url)) {
870 $body .= '[url=' . $post->source_url . ']' . $post->source_title . "[/url]:\n";
871 } elseif (!empty($post->source_title)) {
872 $body .= $post->source_title . ":\n";
874 $body .= '[quote]' . HTML::toBBCode($post->source) . '[/quote]';
875 $item['body'] = $body;
879 $item['body'] = HTML::toBBCode($post->description) . "\n" . PageInfo::getFooterFromUrl($post->url);
883 if (!empty($post->asking_name) && !empty($post->asking_url)) {
884 $body = '[url=' . $post->asking_url . ']' . $post->asking_name . "[/url]:\n";
885 } elseif (!empty($post->asking_name)) {
886 $body = $post->asking_name . ":\n";
890 $body .= '[quote]' . HTML::toBBCode($post->question) . "[/quote]\n" . HTML::toBBCode($post->answer);
891 $item['body'] = $body;
895 $item['body'] = HTML::toBBCode($post->caption);
896 if (!empty($post->video_url)) {
897 $item['body'] .= "\n[video]" . $post->video_url . "[/video]\n";
898 } elseif (!empty($post->thumbnail_url)) {
899 $item['body'] .= "\n[url=" . $post->permalink_url . "][img]" . $post->thumbnail_url . "[/img][/url]\n";
900 } elseif (!empty($post->permalink_url)) {
901 $item['body'] .= "\n[url]" . $post->permalink_url . "[/url]\n";
902 } elseif (!empty($post->source_url) && !empty($post->source_title)) {
903 $item['body'] .= "\n[url=" . $post->source_url . "]" . $post->source_title . "[/url]\n";
904 } elseif (!empty($post->source_url)) {
905 $item['body'] .= "\n[url]" . $post->source_url . "[/url]\n";
910 $item['body'] = HTML::toBBCode($post->caption);
911 if (!empty($post->source_url) && !empty($post->source_title)) {
912 $item['body'] .= "\n[url=" . $post->source_url . "]" . $post->source_title . "[/url]\n";
913 } elseif (!empty($post->source_url)) {
914 $item['body'] .= "\n[url]" . $post->source_url . "[/url]\n";
919 $item['body'] = HTML::toBBCode($post->caption);
920 foreach ($post->photos as $photo) {
921 if (!empty($photo->original_size)) {
922 $item['body'] .= "\n[img]" . $photo->original_size->url . "[/img]";
923 } elseif (!empty($photo->alt_sizes)) {
924 $item['body'] .= "\n[img]" . $photo->alt_sizes[0]->url . "[/img]";
930 $item['title'] = $post->title;
931 $item['body'] = "\n[ul]";
932 foreach ($post->dialogue as $line) {
933 $item['body'] .= "\n[li]" . $line->label . " " . $line->phrase . "[/li]";
935 $item['body'] .= "[/ul]\n";
941 function tumblr_add_npf_data(string $html, string $plink): string
943 $doc = new DOMDocument();
945 $doc->formatOutput = true;
946 @$doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
947 $xpath = new DomXPath($doc);
948 $list = $xpath->query('//p[@class="npf_link"]');
949 foreach ($list as $node) {
950 $data = tumblr_get_npf_data($node);
955 tumblr_replace_with_npf($doc, $node, tumblr_get_type_replacement($data, $plink));
958 $list = $xpath->query('//div[@data-npf]');
959 foreach ($list as $node) {
960 $data = tumblr_get_npf_data($node);
965 tumblr_replace_with_npf($doc, $node, tumblr_get_type_replacement($data, $plink));
968 $list = $xpath->query('//figure[@data-provider="youtube"]');
969 foreach ($list as $node) {
970 $attributes = tumblr_get_attributes($node);
971 if (empty($attributes['data-url'])) {
974 tumblr_replace_with_npf($doc, $node, '[youtube]' . $attributes['data-url'] . '[/youtube]');
977 $list = $xpath->query('//figure[@data-npf]');
978 foreach ($list as $node) {
979 $data = tumblr_get_npf_data($node);
983 tumblr_replace_with_npf($doc, $node, tumblr_get_type_replacement($data, $plink));
986 return $doc->saveHTML();
989 function tumblr_replace_with_npf(DOMDocument $doc, DOMNode $node, string $replacement)
991 if (empty($replacement)) {
994 $replace = $doc->createTextNode($replacement);
995 $node->parentNode->insertBefore($replace, $node);
996 $node->parentNode->removeChild($node);
999 function tumblr_get_npf_data(DOMNode $node): array
1001 $attributes = tumblr_get_attributes($node);
1002 if (empty($attributes['data-npf'])) {
1006 return json_decode($attributes['data-npf'], true);
1009 function tumblr_get_attributes($node): array
1011 if (empty($node->attributes)) {
1016 foreach ($node->attributes as $key => $attribute) {
1017 $attributes[$key] = trim($attribute->value);
1022 function tumblr_get_type_replacement(array $data, string $plink): string
1024 switch ($data['type']) {
1026 $body = '[p][url=' . $plink . ']' . $data['question'] . '[/url][/p][ul]';
1027 foreach ($data['answers'] as $answer) {
1028 $body .= '[li]' . $answer['answer_text'] . '[/li]';
1034 $body = PageInfo::getFooterFromUrl(str_replace('https://href.li/?', '', $data['url']));
1038 if (!empty($data['url']) && ($data['provider'] == 'tumblr')) {
1039 $body = '[video]' . $data['url'] . '[/video]';
1044 Logger::notice('Unknown type', ['type' => $data['type'], 'data' => $data, 'plink' => $plink]);
1052 * Get a contact array for the given blog
1054 * @param stdClass $blog
1055 * @param integer $uid
1058 function tumblr_get_contact(stdClass $blog, int $uid): array
1060 $condition = ['network' => Protocol::TUMBLR, 'uid' => 0, 'poll' => 'tumblr::' . $blog->uuid];
1061 $contact = Contact::selectFirst(['id', 'updated'], $condition);
1063 $update = empty($contact) || $contact['updated'] < DateTimeFormat::utc('now -24 hours');
1065 $public_fields = $fields = tumblr_get_contact_fields($blog, $uid, $update);
1067 $avatar = $fields['avatar'] ?? '';
1068 unset($fields['avatar']);
1069 unset($public_fields['avatar']);
1071 $public_fields['uid'] = 0;
1072 $public_fields['rel'] = Contact::NOTHING;
1074 if (empty($contact)) {
1075 $cid = Contact::insert($public_fields);
1077 $cid = $contact['id'];
1078 Contact::update($public_fields, ['id' => $cid], true);
1082 $condition = ['network' => Protocol::TUMBLR, 'uid' => $uid, 'poll' => 'tumblr::' . $blog->uuid];
1084 $contact = Contact::selectFirst(['id', 'rel', 'uid'], $condition);
1085 if (!isset($fields['rel']) && isset($contact['rel'])) {
1086 $fields['rel'] = $contact['rel'];
1087 } elseif (!isset($fields['rel'])) {
1088 $fields['rel'] = Contact::NOTHING;
1092 if (($uid != 0) && ($fields['rel'] != Contact::NOTHING)) {
1093 if (empty($contact)) {
1094 $cid = Contact::insert($fields);
1096 $cid = $contact['id'];
1097 Contact::update($fields, ['id' => $cid], true);
1099 Logger::debug('Get user contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1101 Logger::debug('Get public contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1104 if (!empty($avatar)) {
1105 Contact::updateAvatar($cid, $avatar);
1108 return Contact::getById($cid);
1111 function tumblr_get_contact_fields(stdClass $blog, int $uid, bool $update): array
1113 $baseurl = 'https://tumblr.com';
1114 $url = $baseurl . '/' . $blog->name;
1118 'network' => Protocol::TUMBLR,
1119 'poll' => 'tumblr::' . $blog->uuid,
1120 'baseurl' => $baseurl,
1124 'readonly' => false,
1127 'nurl' => Strings::normaliseLink($url),
1128 'alias' => $blog->url,
1129 'name' => $blog->title ?: $blog->name,
1130 'nick' => $blog->name,
1131 'addr' => $blog->name . '@tumblr.com',
1132 'about' => HTML::toBBCode($blog->description),
1133 'updated' => date(DateTimeFormat::MYSQL, $blog->updated)
1137 Logger::debug('Got contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1141 $info = tumblr_get($uid, 'blog/' . $blog->uuid . '/info');
1142 if ($info->meta->status > 399) {
1143 Logger::notice('Error fetching blog info', ['meta' => $info->meta, 'response' => $info->response, 'errors' => $info->errors]);
1147 $avatar = $info->response->blog->avatar;
1148 if (!empty($avatar)) {
1149 $fields['avatar'] = $avatar[0]->url;
1152 if ($info->response->blog->followed && $info->response->blog->subscribed) {
1153 $fields['rel'] = Contact::FRIEND;
1154 } elseif ($info->response->blog->followed && !$info->response->blog->subscribed) {
1155 $fields['rel'] = Contact::SHARING;
1156 } elseif (!$info->response->blog->followed && $info->response->blog->subscribed) {
1157 $fields['rel'] = Contact::FOLLOWER;
1159 $fields['rel'] = Contact::NOTHING;
1162 $fields['header'] = $info->response->blog->theme->header_image_focused;
1164 Logger::debug('Got updated contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1169 * Get the default page for posting. Detects the value if not provided or has got a bad value.
1171 * @param integer $uid
1172 * @param array $blogs
1175 function tumblr_get_page(int $uid, array $blogs = []): string
1177 $page = DI::pConfig()->get($uid, 'tumblr', 'page');
1179 if (!empty($page) && (strpos($page, '/') === false)) {
1183 if (empty($blogs)) {
1184 $blogs = tumblr_get_blogs($uid);
1187 if (!empty($blogs)) {
1188 $page = array_key_first($blogs);
1189 DI::pConfig()->set($uid, 'tumblr', 'page', $page);
1197 * Get an array of blogs for the given user
1199 * @param integer $uid
1202 function tumblr_get_blogs(int $uid): array
1204 $userinfo = tumblr_get($uid, 'user/info');
1205 if ($userinfo->meta->status > 299) {
1206 Logger::notice('Error fetching blogs', ['meta' => $userinfo->meta, 'response' => $userinfo->response, 'errors' => $userinfo->errors]);
1211 foreach ($userinfo->response->user->blogs as $blog) {
1212 $blogs[$blog->uuid] = $blog->name;
1217 function tumblr_enabled_for_user(int $uid)
1219 return !empty($uid) && !empty(DI::pConfig()->get($uid, 'tumblr', 'access_token')) &&
1220 !empty(DI::pConfig()->get($uid, 'tumblr', 'refresh_token')) &&
1221 !empty(DI::config()->get('tumblr', 'consumer_key')) &&
1222 !empty(DI::config()->get('tumblr', 'consumer_secret'));
1226 * Get a contact array from a Tumblr url
1228 * @param string $url
1229 * @return array|null
1230 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1232 function tumblr_get_contact_by_url(string $url): ?array
1234 $consumer_key = DI::config()->get('tumblr', 'consumer_key');
1235 if (empty($consumer_key)) {
1239 if (!preg_match('#^https?://tumblr.com/(.+)#', $url, $matches) && !preg_match('#^https?://www\.tumblr.com/(.+)#', $url, $matches) && !preg_match('#^https?://(.+)\.tumblr.com#', $url, $matches)) {
1241 $curlResult = DI::httpClient()->get($url);
1242 } catch (\Exception $e) {
1245 $html = $curlResult->getBody();
1249 $doc = new DOMDocument();
1250 @$doc->loadHTML($html);
1251 $xpath = new DomXPath($doc);
1252 $body = $xpath->query('body');
1253 $attributes = tumblr_get_attributes($body->item(0));
1254 $blog = $attributes['data-urlencoded-name'] ?? '';
1256 $blogs = explode('/', $matches[1]);
1257 $blog = $blogs[0] ?? '';
1264 Logger::debug('Update Tumblr blog data', ['url' => $url]);
1266 $curlResult = DI::httpClient()->get('https://api.tumblr.com/v2/blog/' . $blog . '/info?api_key=' . $consumer_key);
1267 $body = $curlResult->getBody();
1268 $data = json_decode($body);
1273 if (is_array($data->response->blog) || empty($data->response->blog)) {
1274 Logger::warning('Unexpected blog format', ['blog' => $blog, 'data' => $data]);
1278 $baseurl = 'https://tumblr.com';
1279 $url = $baseurl . '/' . $data->response->blog->name;
1283 'nurl' => Strings::normaliseLink($url),
1284 'addr' => $data->response->blog->name . '@tumblr.com',
1285 'alias' => $data->response->blog->url,
1288 'poll' => 'tumblr::' . $data->response->blog->uuid,
1290 'name' => $data->response->blog->title ?: $data->response->blog->name,
1291 'nick' => $data->response->blog->name,
1292 'network' => Protocol::TUMBLR,
1293 'baseurl' => $baseurl,
1296 'guid' => $data->response->blog->uuid,
1297 'about' => HTML::toBBCode($data->response->blog->description),
1298 'photo' => $data->response->blog->avatar[0]->url,
1299 'header' => $data->response->blog->theme->header_image_focused,
1304 * Perform an OAuth2 GET request
1306 * @param integer $uid
1307 * @param string $url
1308 * @param array $parameters
1311 function tumblr_get(int $uid, string $url, array $parameters = []): stdClass
1313 $url = 'https://api.tumblr.com/v2/' . $url;
1315 if (!empty($parameters)) {
1316 $url .= '?' . http_build_query($parameters);
1319 $curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . tumblr_get_token($uid)]]]);
1320 return tumblr_format_result($curlResult);
1324 * Perform an OAuth2 POST request
1326 * @param integer $uid
1327 * @param string $url
1328 * @param array $parameters
1331 function tumblr_post(int $uid, string $url, array $parameters): stdClass
1333 $url = 'https://api.tumblr.com/v2/' . $url;
1335 $curlResult = DI::httpClient()->post($url, $parameters, ['Authorization' => ['Bearer ' . tumblr_get_token($uid)]]);
1336 return tumblr_format_result($curlResult);
1340 * Perform an OAuth2 DELETE request
1342 * @param integer $uid
1343 * @param string $url
1344 * @param array $parameters
1347 function tumblr_delete(int $uid, string $url, array $parameters): stdClass
1349 $url = 'https://api.tumblr.com/v2/' . $url;
1352 HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . tumblr_get_token($uid)]],
1353 HttpClientOptions::FORM_PARAMS => $parameters
1356 $curlResult = DI::httpClient()->request('delete', $url, $opts);
1357 return tumblr_format_result($curlResult);
1361 * Format the get/post result value
1363 * @param ICanHandleHttpResponses $curlResult
1366 function tumblr_format_result(ICanHandleHttpResponses $curlResult): stdClass
1368 $result = json_decode($curlResult->getBody());
1369 if (empty($result) || empty($result->meta)) {
1370 $result = new stdClass;
1371 $result->meta = new stdClass;
1372 $result->meta->status = 500;
1373 $result->meta->msg = '';
1374 $result->response = [];
1375 $result->errors = [];
1381 * Fetch the OAuth token, update it if needed
1383 * @param integer $uid
1384 * @param string $code
1387 function tumblr_get_token(int $uid, string $code = ''): string
1389 $access_token = DI::pConfig()->get($uid, 'tumblr', 'access_token');
1390 $expires_at = DI::pConfig()->get($uid, 'tumblr', 'expires_at');
1391 $refresh_token = DI::pConfig()->get($uid, 'tumblr', 'refresh_token');
1393 if (empty($code) && !empty($access_token) && ($expires_at > (time()))) {
1394 Logger::debug('Got token', ['uid' => $uid, 'expires_at' => date('c', $expires_at)]);
1395 return $access_token;
1398 $consumer_key = DI::config()->get('tumblr', 'consumer_key');
1399 $consumer_secret = DI::config()->get('tumblr', 'consumer_secret');
1401 $parameters = ['client_id' => $consumer_key, 'client_secret' => $consumer_secret];
1403 if (empty($refresh_token) && empty($code)) {
1404 $result = tumblr_exchange_token($uid);
1405 if (empty($result->refresh_token)) {
1406 Logger::info('Invalid result while exchanging token', ['uid' => $uid]);
1409 $expires_at = time() + $result->expires_in;
1410 Logger::debug('Updated token from OAuth1 to OAuth2', ['uid' => $uid, 'expires_at' => date('c', $expires_at)]);
1412 if (!empty($code)) {
1413 $parameters['code'] = $code;
1414 $parameters['grant_type'] = 'authorization_code';
1416 $parameters['refresh_token'] = $refresh_token;
1417 $parameters['grant_type'] = 'refresh_token';
1420 $curlResult = DI::httpClient()->post('https://api.tumblr.com/v2/oauth2/token', $parameters);
1421 if (!$curlResult->isSuccess()) {
1422 Logger::info('Error fetching token', ['uid' => $uid, 'code' => $code, 'result' => $curlResult->getBody(), 'parameters' => $parameters]);
1426 $result = json_decode($curlResult->getBody());
1427 if (empty($result)) {
1428 Logger::info('Invalid result when updating token', ['uid' => $uid]);
1432 $expires_at = time() + $result->expires_in;
1433 Logger::debug('Renewed token', ['uid' => $uid, 'expires_at' => date('c', $expires_at)]);
1436 DI::pConfig()->set($uid, 'tumblr', 'access_token', $result->access_token);
1437 DI::pConfig()->set($uid, 'tumblr', 'expires_at', $expires_at);
1438 DI::pConfig()->set($uid, 'tumblr', 'refresh_token', $result->refresh_token);
1440 return $result->access_token;
1444 * Create an OAuth2 token out of an OAuth1 token
1449 function tumblr_exchange_token(int $uid): stdClass
1451 $oauth_token = DI::pConfig()->get($uid, 'tumblr', 'oauth_token');
1452 $oauth_token_secret = DI::pConfig()->get($uid, 'tumblr', 'oauth_token_secret');
1454 $consumer_key = DI::config()->get('tumblr', 'consumer_key');
1455 $consumer_secret = DI::config()->get('tumblr', 'consumer_secret');
1457 $stack = HandlerStack::create();
1459 $middleware = new Oauth1([
1460 'consumer_key' => $consumer_key,
1461 'consumer_secret' => $consumer_secret,
1462 'token' => $oauth_token,
1463 'token_secret' => $oauth_token_secret
1466 $stack->push($middleware);
1469 $client = new Client([
1470 'base_uri' => 'https://api.tumblr.com/v2/',
1474 $response = $client->post('oauth2/exchange', ['auth' => 'oauth']);
1475 return json_decode($response->getBody()->getContents());
1476 } catch (RequestException $exception) {
1477 Logger::notice('Exchange failed', ['code' => $exception->getCode(), 'message' => $exception->getMessage()]);
1478 return new stdClass;