X-Git-Url: https://git.mxchange.org/?a=blobdiff_plain;f=tumblr%2Ftumblr.php;h=812b5b30c6aa639905e29b8f55be42e0feaec537;hb=fa013574453974fa4e40bf3160a83b09ffc749ef;hp=e664ed7b899d1039745547cd7c4c90069ed1fade;hpb=ef71f4681e0876a1a9ac429b961741c656214549;p=friendica-addons.git diff --git a/tumblr/tumblr.php b/tumblr/tumblr.php index e664ed7b..812b5b30 100644 --- a/tumblr/tumblr.php +++ b/tumblr/tumblr.php @@ -7,292 +7,461 @@ * Author: Michael Vogel */ -require_once __DIR__ . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'tumblroauth.php'; - -use Friendica\App; +use Friendica\Content\PageInfo; use Friendica\Content\Text\BBCode; +use Friendica\Content\Text\HTML; +use Friendica\Content\Text\NPF; +use Friendica\Core\Cache\Enum\Duration; +use Friendica\Core\Config\Util\ConfigFileManager; use Friendica\Core\Hook; use Friendica\Core\Logger; +use Friendica\Core\Protocol; use Friendica\Core\Renderer; +use Friendica\Core\System; +use Friendica\Core\Worker; use Friendica\Database\DBA; use Friendica\DI; +use Friendica\Model\Contact; +use Friendica\Model\Item; +use Friendica\Model\Photo; use Friendica\Model\Post; use Friendica\Model\Tag; +use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses; +use Friendica\Network\HTTPClient\Client\HttpClientAccept; +use Friendica\Network\HTTPClient\Client\HttpClientOptions; +use Friendica\Protocol\Activity; +use Friendica\Util\DateTimeFormat; +use Friendica\Util\Network; +use Friendica\Util\Strings; +use GuzzleHttp\Client; +use GuzzleHttp\Exception\RequestException; +use GuzzleHttp\HandlerStack; +use GuzzleHttp\Subscriber\Oauth\Oauth1; + +define('TUMBLR_DEFAULT_POLL_INTERVAL', 10); // given in minutes +define('TUMBLR_DEFAULT_MAXIMUM_TAGS', 10); function tumblr_install() { - Hook::register('hook_fork', 'addon/tumblr/tumblr.php', 'tumblr_hook_fork'); - Hook::register('post_local', 'addon/tumblr/tumblr.php', 'tumblr_post_local'); - Hook::register('notifier_normal', 'addon/tumblr/tumblr.php', 'tumblr_send'); - Hook::register('jot_networks', 'addon/tumblr/tumblr.php', 'tumblr_jot_nets'); - Hook::register('connector_settings', 'addon/tumblr/tumblr.php', 'tumblr_settings'); - Hook::register('connector_settings_post', 'addon/tumblr/tumblr.php', 'tumblr_settings_post'); + Hook::register('load_config', __FILE__, 'tumblr_load_config'); + Hook::register('hook_fork', __FILE__, 'tumblr_hook_fork'); + Hook::register('post_local', __FILE__, 'tumblr_post_local'); + Hook::register('notifier_normal', __FILE__, 'tumblr_send'); + Hook::register('jot_networks', __FILE__, 'tumblr_jot_nets'); + Hook::register('connector_settings', __FILE__, 'tumblr_settings'); + Hook::register('connector_settings_post', __FILE__, 'tumblr_settings_post'); + Hook::register('cron', __FILE__, 'tumblr_cron'); + Hook::register('support_follow', __FILE__, 'tumblr_support_follow'); + Hook::register('support_probe', __FILE__, 'tumblr_support_probe'); + Hook::register('follow', __FILE__, 'tumblr_follow'); + Hook::register('unfollow', __FILE__, 'tumblr_unfollow'); + Hook::register('block', __FILE__, 'tumblr_block'); + Hook::register('unblock', __FILE__, 'tumblr_unblock'); + Hook::register('check_item_notification', __FILE__, 'tumblr_check_item_notification'); + Hook::register('probe_detect', __FILE__, 'tumblr_probe_detect'); + Hook::register('item_by_link', __FILE__, 'tumblr_item_by_link'); + Logger::info('installed tumblr'); } -function tumblr_module() +function tumblr_load_config(ConfigFileManager $loader) { + DI::app()->getConfigCache()->load($loader->loadAddonConfig('tumblr'), \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC); } -function tumblr_content(App $a) +function tumblr_check_item_notification(array &$notification_data) { - if (! local_user()) { - notice(DI::l10n()->t('Permission denied.') . EOL); - return ''; + if (!tumblr_enabled_for_user($notification_data['uid'])) { + return; } - if (isset(DI::args()->getArgv()[1])) { - switch (DI::args()->getArgv()[1]) { - case "connect": - $o = tumblr_connect($a); - break; - - case "callback": - $o = tumblr_callback($a); - break; - - default: - $o = print_r(DI::args()->getArgv(), true); - break; - } - } else { - $o = tumblr_connect($a); + $page = tumblr_get_page($notification_data['uid']); + if (empty($page)) { + return; } - return $o; + $own_user = Contact::selectFirst(['url', 'alias'], ['network' => Protocol::TUMBLR, 'uid' => [0, $notification_data['uid']], 'poll' => 'tumblr::' . $page]); + if ($own_user) { + $notification_data['profiles'][] = $own_user['url']; + $notification_data['profiles'][] = $own_user['alias']; + } } -function tumblr_addon_admin(App $a, &$o) +function tumblr_probe_detect(array &$hookData) { - $t = Renderer::getMarkupTemplate( "admin.tpl", "addon/tumblr/" ); + // Don't overwrite an existing result + if (isset($hookData['result'])) { + return; + } - $o = Renderer::replaceMacros($t, [ - '$submit' => DI::l10n()->t('Save Settings'), - // name, label, value, help, [extra values] - '$consumer_key' => ['consumer_key', DI::l10n()->t('Consumer Key'), DI::config()->get('tumblr', 'consumer_key' ), ''], - '$consumer_secret' => ['consumer_secret', DI::l10n()->t('Consumer Secret'), DI::config()->get('tumblr', 'consumer_secret' ), ''], - ]); -} + // Avoid a lookup for the wrong network + if (!in_array($hookData['network'], ['', Protocol::TUMBLR])) { + return; + } -function tumblr_addon_admin_post(App $a) -{ - $consumer_key = trim($_POST['consumer_key'] ?? ''); - $consumer_secret = trim($_POST['consumer_secret'] ?? ''); + $hookData['result'] = tumblr_get_contact_by_url($hookData['uri'], $hookData['uid']); - DI::config()->set('tumblr', 'consumer_key',$consumer_key); - DI::config()->set('tumblr', 'consumer_secret',$consumer_secret); + // Authoritative probe should set the result even if the probe was unsuccessful + if ($hookData['network'] == Protocol::TUMBLR && empty($hookData['result'])) { + $hookData['result'] = []; + } } -function tumblr_connect(App $a) +function tumblr_item_by_link(array &$hookData) { - // Start a session. This is necessary to hold on to a few keys the callback script will also need - session_start(); + // Don't overwrite an existing result + if (isset($hookData['item_id'])) { + return; + } - // Include the TumblrOAuth library - //require_once('addon/tumblr/tumblroauth/tumblroauth.php'); + if (!tumblr_enabled_for_user($hookData['uid'])) { + return; + } - // Define the needed keys - $consumer_key = DI::config()->get('tumblr', 'consumer_key'); - $consumer_secret = DI::config()->get('tumblr', 'consumer_secret'); + if (!preg_match('#^https?://www\.tumblr.com/blog/view/(.+)/(\d+).*#', $hookData['uri'], $matches) && !preg_match('#^https?://www\.tumblr.com/(.+)/(\d+).*#', $hookData['uri'], $matches)) { + return; + } - // The callback URL is the script that gets called after the user authenticates with tumblr - // In this example, it would be the included callback.php - $callback_url = DI::baseUrl()->get()."/tumblr/callback"; + Logger::debug('Found tumblr post', ['url' => $hookData['uri'], 'blog' => $matches[1], 'id' => $matches[2]]); - // Let's begin. First we need a Request Token. The request token is required to send the user - // to Tumblr's login page. + $parameters = ['id' => $matches[2], 'reblog_info' => false, 'notes_info' => false, 'npf' => false]; + $result = tumblr_get($hookData['uid'], 'blog/' . $matches[1] . '/posts', $parameters); + if ($result->meta->status > 399) { + Logger::notice('Error fetching status', ['meta' => $result->meta, 'response' => $result->response, 'errors' => $result->errors, 'blog' => $matches[1], 'id' => $matches[2]]); + return []; + } - // Create a new instance of the TumblrOAuth library. For this step, all we need to give the library is our - // Consumer Key and Consumer Secret - $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret); + Logger::debug('Got post', ['blog' => $matches[1], 'id' => $matches[2], 'result' => $result->response->posts]); + if (!empty($result->response->posts)) { + $hookData['item_id'] = tumblr_process_post($result->response->posts[0], $hookData['uid'], Item::PR_FETCHED); + } +} - // Ask Tumblr for a Request Token. Specify the Callback URL here too (although this should be optional) - $request_token = $tum_oauth->getRequestToken($callback_url); +function tumblr_support_follow(array &$data) +{ + if ($data['protocol'] == Protocol::TUMBLR) { + $data['result'] = true; + } +} - // Store the request token and Request Token Secret as out callback.php script will need this - $_SESSION['request_token'] = $token = $request_token['oauth_token']; - $_SESSION['request_token_secret'] = $request_token['oauth_token_secret']; +function tumblr_support_probe(array &$data) +{ + if ($data['protocol'] == Protocol::TUMBLR) { + $data['result'] = true; + } +} - // Check the HTTP Code. It should be a 200 (OK), if it's anything else then something didn't work. - switch ($tum_oauth->http_code) { - case 200: - // Ask Tumblr to give us a special address to their login page - $url = $tum_oauth->getAuthorizeURL($token); +function tumblr_follow(array &$hook_data) +{ + $uid = DI::userSession()->getLocalUserId(); - // Redirect the user to the login URL given to us by Tumblr - header('Location: ' . $url); + if (!tumblr_enabled_for_user($uid)) { + return; + } - /* - * That's it for our side. The user is sent to a Tumblr Login page and - * asked to authroize our app. After that, Tumblr sends the user back to - * our Callback URL (callback.php) along with some information we need to get - * an access token. - */ - break; + Logger::debug('Check if contact is Tumblr', ['url' => $hook_data['url']]); - default: - // Give an error message - $o = 'Could not connect to Tumblr. Refresh the page or try again later.'; + $fields = tumblr_get_contact_by_url($hook_data['url'], $uid); + if (empty($fields)) { + Logger::debug('Contact is not a Tumblr contact', ['url' => $hook_data['url']]); + return; } - return $o; + $result = tumblr_post($uid, 'user/follow', ['url' => $fields['url']]); + if ($result->meta->status <= 399) { + $hook_data['contact'] = $fields; + Logger::debug('Successfully start following', ['url' => $fields['url']]); + } else { + Logger::notice('Following failed', ['meta' => $result->meta, 'response' => $result->response, 'errors' => $result->errors, 'url' => $fields['url']]); + } } -function tumblr_callback(App $a) +function tumblr_unfollow(array &$hook_data) { - // Start a session, load the library - session_start(); - //require_once('addon/tumblr/tumblroauth/tumblroauth.php'); + if (!tumblr_enabled_for_user($hook_data['uid'])) { + return; + } - // Define the needed keys - $consumer_key = DI::config()->get('tumblr', 'consumer_key'); - $consumer_secret = DI::config()->get('tumblr', 'consumer_secret'); + if (!tumblr_get_contact_uuid($hook_data['contact'])) { + return; + } + $result = tumblr_post($hook_data['uid'], 'user/unfollow', ['url' => $hook_data['contact']['url']]); + $hook_data['result'] = ($result->meta->status <= 399); +} + +function tumblr_block(array &$hook_data) +{ + if (!tumblr_enabled_for_user($hook_data['uid'])) { + return; + } - // Once the user approves your app at Tumblr, they are sent back to this script. - // This script is passed two parameters in the URL, oauth_token (our Request Token) - // and oauth_verifier (Key that we need to get Access Token). - // We'll also need out Request Token Secret, which we stored in a session. + $uuid = tumblr_get_contact_uuid($hook_data['contact']); + if (!$uuid) { + return; + } - // Create instance of TumblrOAuth. - // It'll need our Consumer Key and Secret as well as our Request Token and Secret - $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $_SESSION['request_token'], $_SESSION['request_token_secret']); + $result = tumblr_post($hook_data['uid'], 'blog/' . tumblr_get_page($hook_data['uid']) . '/blocks', ['blocked_tumblelog' => $uuid]); + $hook_data['result'] = ($result->meta->status <= 399); - // Ok, let's get an Access Token. We'll need to pass along our oauth_verifier which was given to us in the URL. - $access_token = $tum_oauth->getAccessToken($_REQUEST['oauth_verifier']); + if ($hook_data['result']) { + $cdata = Contact::getPublicAndUserContactID($hook_data['contact']['id'], $hook_data['uid']); + if (!empty($cdata['user'])) { + Contact::remove($cdata['user']); + } + } +} - // We're done with the Request Token and Secret so let's remove those. - unset($_SESSION['request_token']); - unset($_SESSION['request_token_secret']); +function tumblr_unblock(array &$hook_data) +{ + if (!tumblr_enabled_for_user($hook_data['uid'])) { + return; + } - // Make sure nothing went wrong. - if (200 == $tum_oauth->http_code) { - // good to go - } else { - return 'Unable to authenticate'; + $uuid = tumblr_get_contact_uuid($hook_data['contact']); + if (!$uuid) { + return; } - // What's next? Now that we have an Access Token and Secret, we can make an API call. - DI::pConfig()->set(local_user(), "tumblr", "oauth_token", $access_token['oauth_token']); - DI::pConfig()->set(local_user(), "tumblr", "oauth_token_secret", $access_token['oauth_token_secret']); + $result = tumblr_delete($hook_data['uid'], 'blog/' . tumblr_get_page($hook_data['uid']) . '/blocks', ['blocked_tumblelog' => $uuid]); + $hook_data['result'] = ($result->meta->status <= 399); +} - $o = DI::l10n()->t("You are now authenticated to tumblr."); - $o .= '
' . DI::l10n()->t("return to the connector page") . ''; +function tumblr_get_contact_uuid(array $contact): string +{ + if (($contact['network'] != Protocol::TUMBLR) || (substr($contact['poll'], 0, 8) != 'tumblr::')) { + return ''; + } + return substr($contact['poll'], 8); +} - return $o; +/** + * This is a statement rather than an actual function definition. The simple + * existence of this method is checked to figure out if the addon offers a + * module. + */ +function tumblr_module() +{ } -function tumblr_jot_nets(App $a, array &$jotnets_fields) +function tumblr_content() { - if (! local_user()) { + if (!DI::userSession()->getLocalUserId()) { + DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.')); return; } - if (DI::pConfig()->get(local_user(),'tumblr','post')) { - $jotnets_fields[] = [ - 'type' => 'checkbox', - 'field' => [ - 'tumblr_enable', - DI::l10n()->t('Post to Tumblr'), - DI::pConfig()->get(local_user(),'tumblr','post_by_default') - ] - ]; + switch (DI::args()->getArgv()[1] ?? '') { + case 'connect': + tumblr_connect(); + break; + + case 'redirect': + tumblr_redirect(); + break; } + DI::baseUrl()->redirect('settings/connectors/tumblr'); } -function tumblr_settings(App $a, &$s) +function tumblr_redirect() { - if (! local_user()) { + if (($_REQUEST['state'] ?? '') != DI::session()->get('oauth_state')) { return; } - /* Add our stylesheet to the page so we can make our settings look nice */ + tumblr_get_token(DI::userSession()->getLocalUserId(), $_REQUEST['code'] ?? ''); +} - DI::page()['htmlhead'] .= '' . "\r\n"; +function tumblr_connect() +{ + // Define the needed keys + $consumer_key = DI::config()->get('tumblr', 'consumer_key'); + $consumer_secret = DI::config()->get('tumblr', 'consumer_secret'); - /* Get the current state of our config variables */ + if (empty($consumer_key) || empty($consumer_secret)) { + return; + } - $enabled = DI::pConfig()->get(local_user(), 'tumblr', 'post'); - $checked = (($enabled) ? ' checked="checked" ' : ''); - $css = (($enabled) ? '' : '-disabled'); + $state = base64_encode(random_bytes(20)); + DI::session()->set('oauth_state', $state); - $def_enabled = DI::pConfig()->get(local_user(), 'tumblr', 'post_by_default'); + $parameters = [ + 'client_id' => $consumer_key, + 'response_type' => 'code', + 'scope' => 'basic write offline_access', + 'state' => $state + ]; - $def_checked = (($def_enabled) ? ' checked="checked" ' : ''); + System::externalRedirect('https://www.tumblr.com/oauth2/authorize?' . http_build_query($parameters)); +} - /* Add some HTML to the existing form */ +function tumblr_addon_admin(string &$o) +{ + $t = Renderer::getMarkupTemplate('admin.tpl', 'addon/tumblr/'); - $s .= ''; - $s .= '

'. DI::l10n()->t('Tumblr Export').'

'; - $s .= '
'; - $s .= ''; + if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post')) { + $jotnets_fields[] = [ + 'type' => 'checkbox', + 'field' => [ + 'tumblr_enable', + DI::l10n()->t('Post to Tumblr'), + DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post_by_default') + ] + ]; + } } -function tumblr_settings_post(App $a, array &$b) +function tumblr_settings_post(array &$b) { if (!empty($_POST['tumblr-submit'])) { - DI::pConfig()->set(local_user(), 'tumblr', 'post', intval($_POST['tumblr'])); - DI::pConfig()->set(local_user(), 'tumblr', 'page', $_POST['tumblr_page']); - DI::pConfig()->set(local_user(), 'tumblr', 'post_by_default', intval($_POST['tumblr_bydefault'])); + DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'post', intval($_POST['tumblr'])); + DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'page', $_POST['tumblr_page']); + DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'post_by_default', intval($_POST['tumblr_bydefault'])); + DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'import', intval($_POST['tumblr_import'])); + + $max_tags = DI::config()->get('tumblr', 'max_tags') ?? TUMBLR_DEFAULT_MAXIMUM_TAGS; + $tags = []; + foreach (explode(',', $_POST['tags']) as $tag) { + if (count($tags) < $max_tags) { + $tags[] = trim($tag, ' #'); + } + } + + DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'tags', $tags); + } +} + +function tumblr_cron() +{ + $last = DI::keyValue()->get('tumblr_last_poll'); + + $poll_interval = intval(DI::config()->get('tumblr', 'poll_interval')); + if (!$poll_interval) { + $poll_interval = TUMBLR_DEFAULT_POLL_INTERVAL; + } + + if ($last) { + $next = $last + ($poll_interval * 60); + if ($next > time()) { + Logger::notice('poll interval not reached'); + return; + } + } + Logger::notice('cron_start'); + + $abandon_days = intval(DI::config()->get('system', 'account_abandon_days')); + if ($abandon_days < 1) { + $abandon_days = 0; + } + + $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400); + + $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'tumblr', 'k' => 'import', 'v' => true]); + foreach ($pconfigs as $pconfig) { + if ($abandon_days != 0) { + if (!DBA::exists('user', ["`uid` = ? AND `login_date` >= ?", $pconfig['uid'], $abandon_limit])) { + Logger::notice('abandoned account: timeline from user will not be imported', ['user' => $pconfig['uid']]); + continue; + } + } + + Logger::notice('importing timeline - start', ['user' => $pconfig['uid']]); + tumblr_fetch_dashboard($pconfig['uid']); + tumblr_fetch_tags($pconfig['uid']); + Logger::notice('importing timeline - done', ['user' => $pconfig['uid']]); + } + + $last_clean = DI::keyValue()->get('tumblr_last_clean'); + if (empty($last_clean) || ($last_clean + 86400 < time())) { + Logger::notice('Start contact cleanup'); + $contacts = DBA::select('account-user-view', ['id', 'pid'], ["`network` = ? AND `uid` != ? AND `rel` = ?", Protocol::TUMBLR, 0, Contact::NOTHING]); + while ($contact = DBA::fetch($contacts)) { + Worker::add(Worker::PRIORITY_LOW, 'MergeContact', $contact['pid'], $contact['id'], 0); + } + DBA::close($contacts); + DI::keyValue()->set('tumblr_last_clean', time()); + Logger::notice('Contact cleanup done'); } + + Logger::notice('cron_end'); + + DI::keyValue()->set('tumblr_last_poll', time()); } -function tumblr_hook_fork(&$a, &$b) +function tumblr_hook_fork(array &$b) { if ($b['name'] != 'notifier_normal') { return; @@ -300,22 +469,34 @@ function tumblr_hook_fork(&$a, &$b) $post = $b['data']; - if ($post['deleted'] || $post['private'] || ($post['created'] !== $post['edited']) || - !strstr($post['postopts'], 'tumblr') || ($post['parent'] != $post['id'])) { + // Editing is not supported by the addon + if (($post['created'] !== $post['edited']) && !$post['deleted']) { + DI::logger()->info('Editing is not supported by the addon'); + $b['execute'] = false; + return; + } + + if (DI::pConfig()->get($post['uid'], 'tumblr', 'import')) { + // Don't post if it isn't a reply to a tumblr post + if (($post['parent'] != $post['id']) && !Post::exists(['id' => $post['parent'], 'network' => Protocol::TUMBLR])) { + Logger::notice('No tumblr parent found', ['item' => $post['id']]); + $b['execute'] = false; + return; + } + } elseif (!strstr($post['postopts'] ?? '', 'tumblr') || ($post['parent'] != $post['id']) || $post['private']) { + DI::logger()->info('Activities are never exported when we don\'t import the tumblr timeline', ['uid' => $post['uid']]); $b['execute'] = false; return; } } -function tumblr_post_local(App $a, array &$b) +function tumblr_post_local(array &$b) { - // This can probably be changed to allow editing by pointing to a different API endpoint - if ($b['edit']) { return; } - if (!local_user() || (local_user() != $b['uid'])) { + if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) { return; } @@ -323,11 +504,11 @@ function tumblr_post_local(App $a, array &$b) return; } - $tmbl_post = intval(DI::pConfig()->get(local_user(), 'tumblr', 'post')); - + $tmbl_post = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post')); $tmbl_enable = (($tmbl_post && !empty($_REQUEST['tumblr_enable'])) ? intval($_REQUEST['tumblr_enable']) : 0); - if ($b['api_source'] && intval(DI::pConfig()->get(local_user(), 'tumblr', 'post_by_default'))) { + // if API is used, default to the chosen settings + if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post_by_default'))) { $tmbl_enable = 1; } @@ -342,139 +523,959 @@ function tumblr_post_local(App $a, array &$b) $b['postopts'] .= 'tumblr'; } +function tumblr_send(array &$b) +{ + if (($b['created'] !== $b['edited']) && !$b['deleted']) { + return; + } + + if ($b['gravity'] != Item::GRAVITY_PARENT) { + Logger::debug('Got comment', ['item' => $b]); + $parent = tumblr_get_post_from_uri($b['thr-parent']); + if (empty($parent)) { + Logger::notice('No tumblr post', ['thr-parent' => $b['thr-parent']]); + return; + } + Logger::debug('Parent found', ['parent' => $parent]); -function tumblr_send(App $a, array &$b) { + $page = tumblr_get_page($b['uid']); - if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) { + if ($b['gravity'] == Item::GRAVITY_COMMENT) { + Logger::notice('Commenting is not supported (yet)'); + } else { + if (($b['verb'] == Activity::LIKE) && !$b['deleted']) { + $params = ['id' => $parent['id'], 'reblog_key' => $parent['reblog_key']]; + $result = tumblr_post($b['uid'], 'user/like', $params); + } elseif (($b['verb'] == Activity::LIKE) && $b['deleted']) { + $params = ['id' => $parent['id'], 'reblog_key' => $parent['reblog_key']]; + $result = tumblr_post($b['uid'], 'user/unlike', $params); + } elseif (($b['verb'] == Activity::ANNOUNCE) && !$b['deleted']) { + $params = ['id' => $parent['id'], 'reblog_key' => $parent['reblog_key']]; + $result = tumblr_post($b['uid'], 'blog/' . $page . '/post/reblog', $params); + } elseif (($b['verb'] == Activity::ANNOUNCE) && $b['deleted']) { + $announce = tumblr_get_post_from_uri($b['extid']); + if (empty($announce)) { + return; + } + $params = ['id' => $announce['id']]; + $result = tumblr_post($b['uid'], 'blog/' . $page . '/post/delete', $params); + } else { + // Unsupported activity + return; + } + + if ($result->meta->status < 400) { + Logger::info('Successfully performed activity', ['verb' => $b['verb'], 'deleted' => $b['deleted'], 'meta' => $result->meta, 'response' => $result->response]); + if (!$b['deleted'] && !empty($result->response->id_string)) { + Item::update(['extid' => 'tumblr::' . $result->response->id_string], ['id' => $b['id']]); + } + } else { + Logger::notice('Error while performing activity', ['verb' => $b['verb'], 'deleted' => $b['deleted'], 'meta' => $result->meta, 'response' => $result->response, 'errors' => $result->errors, 'params' => $params]); + } + } + return; + } elseif ($b['private'] || !strstr($b['postopts'], 'tumblr')) { return; } - if (! strstr($b['postopts'],'tumblr')) { - return; + if (!tumblr_send_npf($b)) { + tumblr_send_legacy($b); } +} - if ($b['parent'] != $b['id']) { - return; +function tumblr_send_legacy(array $b) +{ + $b['body'] = BBCode::removeAttachment($b['body']); + + $title = trim($b['title']); + + $media = Post\Media::getByURIId($b['uri-id'], [Post\Media::HTML, Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE]); + + $photo = array_search(Post\Media::IMAGE, array_column($media, 'type')); + $link = array_search(Post\Media::HTML, array_column($media, 'type')); + $audio = array_search(Post\Media::AUDIO, array_column($media, 'type')); + $video = array_search(Post\Media::VIDEO, array_column($media, 'type')); + + $params = [ + 'state' => 'published', + 'tags' => implode(',', array_column(Tag::getByURIId($b['uri-id']), 'name')), + 'tweet' => 'off', + 'format' => 'html', + ]; + + $body = BBCode::removeShareInformation($b['body']); + $body = Post\Media::removeFromEndOfBody($body); + + if ($photo !== false) { + $params['type'] = 'photo'; + $params['caption'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS); + $params['data'] = []; + foreach ($media as $photo) { + if ($photo['type'] == Post\Media::IMAGE) { + if (Network::isLocalLink($photo['url']) && ($data = Photo::getResourceData($photo['url']))) { + $photo = Photo::selectFirst([], ["`resource-id` = ? AND `scale` > ?", $data['guid'], 0]); + if (!empty($photo)) { + $params['data'][] = Photo::getImageDataForPhoto($photo); + } + } + } + } + } elseif ($link !== false) { + $params['type'] = 'link'; + $params['title'] = $media[$link]['name']; + $params['url'] = $media[$link]['url']; + $params['description'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS); + + if (!empty($media[$link]['preview'])) { + $params['thumbnail'] = $media[$link]['preview']; + } + if (!empty($media[$link]['description'])) { + $params['excerpt'] = $media[$link]['description']; + } + if (!empty($media[$link]['author-name'])) { + $params['author'] = $media[$link]['author-name']; + } + } elseif ($audio !== false) { + $params['type'] = 'audio'; + $params['external_url'] = $media[$audio]['url']; + $params['caption'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS); + } elseif ($video !== false) { + $params['type'] = 'video'; + $params['embed'] = $media[$video]['url']; + $params['caption'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS); + } else { + $params['type'] = 'text'; + $params['title'] = $title; + $params['body'] = BBCode::convertForUriId($b['uri-id'], $b['body'], BBCode::CONNECTORS); + } + + if (isset($params['caption']) && (trim($title) != '')) { + $params['caption'] = '

' . $title . '

' . + '

' . $params['caption'] . '

'; + } + + $page = tumblr_get_page($b['uid']); + + $result = tumblr_post($b['uid'], 'blog/' . $page . '/post', $params); + + if ($result->meta->status < 400) { + Logger::info('Success (legacy)', ['blog' => $page, 'meta' => $result->meta, 'response' => $result->response]); + } else { + Logger::notice('Error posting blog (legacy)', ['blog' => $page, 'meta' => $result->meta, 'response' => $result->response, 'errors' => $result->errors, 'params' => $params]); + } +} + +function tumblr_send_npf(array $post): bool +{ + $page = tumblr_get_page($post['uid']); + + if (empty($page)) { + Logger::notice('Missing page, post will not be send to Tumblr.', ['uid' => $post['uid'], 'page' => $page, 'id' => $post['id']]); + // "true" is returned, since the legacy function will fail as well. + return true; + } + + $post['body'] = Post\Media::addAttachmentsToBody($post['uri-id'], $post['body']); + if (!empty($post['title'])) { + $post['body'] = '[h1]' . $post['title'] . "[/h1]\n" . $post['body']; + } + + $params = [ + 'content' => NPF::fromBBCode($post['body'], $post['uri-id']), + 'state' => 'published', + 'date' => DateTimeFormat::utc($post['created'], DateTimeFormat::ATOM), + 'tags' => implode(',', array_column(Tag::getByURIId($post['uri-id']), 'name')), + 'is_private' => false, + 'interactability_reblog' => 'everyone' + ]; + + $result = tumblr_post($post['uid'], 'blog/' . $page . '/posts', $params); + + if ($result->meta->status < 400) { + Logger::info('Success (NPF)', ['blog' => $page, 'meta' => $result->meta, 'response' => $result->response]); + return true; + } else { + Logger::notice('Error posting blog (NPF)', ['blog' => $page, 'meta' => $result->meta, 'response' => $result->response, 'errors' => $result->errors, 'params' => $params]); + return false; + } +} + +function tumblr_get_post_from_uri(string $uri): array +{ + $parts = explode(':', $uri); + if (($parts[0] != 'tumblr') || empty($parts[2])) { + return []; } - // Dont't post if the post doesn't belong to us. - // This is a check for forum postings - $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]); - if ($b['contact-id'] != $self['id']) { + $post['id'] = $parts[2]; + $post['reblog_key'] = $parts[3] ?? ''; + + $post['reblog_key'] = str_replace('@t', '', $post['reblog_key']); // Temp + return $post; +} + +/** + * Fetch posts for user defined hashtags for the given user + * + * @param integer $uid + * @return void + */ +function tumblr_fetch_tags(int $uid) +{ + if (!DI::config()->get('tumblr', 'max_tags') ?? TUMBLR_DEFAULT_MAXIMUM_TAGS) { return; } - $b['body'] = Post\Media::addAttachmentsToBody($b['uri-id'], $b['body']); + foreach (DI::pConfig()->get($uid, 'tumblr', 'tags') ?? [] as $tag) { + $data = tumblr_get($uid, 'tagged', ['tag' => $tag]); + foreach (array_reverse($data->response) as $post) { + $id = tumblr_process_post($post, $uid, Item::PR_TAG); + if (!empty($id)) { + Logger::debug('Tag post imported', ['tag' => $tag, 'id' => $id]); + $post = Post::selectFirst(['uri-id'], ['id' => $id]); + $stored = Post\Category::storeFileByURIId($post['uri-id'], $uid, Post\Category::SUBCRIPTION, $tag); + Logger::debug('Stored tag subscription for user', ['uri-id' => $post['uri-id'], 'uid' => $uid, 'tag' => $tag, 'stored' => $stored]); + } + } + } +} + +/** + * Fetch the dashboard (timeline) for the given user + * + * @param integer $uid + * @return void + */ +function tumblr_fetch_dashboard(int $uid) +{ + $parameters = ['reblog_info' => false, 'notes_info' => false, 'npf' => false]; - $oauth_token = DI::pConfig()->get($b['uid'], "tumblr", "oauth_token"); - $oauth_token_secret = DI::pConfig()->get($b['uid'], "tumblr", "oauth_token_secret"); - $page = DI::pConfig()->get($b['uid'], "tumblr", "page"); - $tmbl_blog = 'blog/' . $page . '/post'; + $last = DI::pConfig()->get($uid, 'tumblr', 'last_id'); + if (!empty($last)) { + $parameters['since_id'] = $last; + } - if ($oauth_token && $oauth_token_secret && $tmbl_blog) { - $tags = Tag::getByURIId($b['uri-id']); + $dashboard = tumblr_get($uid, 'user/dashboard', $parameters); + if ($dashboard->meta->status > 399) { + Logger::notice('Error fetching dashboard', ['meta' => $dashboard->meta, 'response' => $dashboard->response, 'errors' => $dashboard->errors]); + return []; + } - $tag_arr = []; + if (empty($dashboard->response->posts)) { + return; + } - foreach($tags as $tag) { - $tag_arr[] = $tag['name']; + foreach (array_reverse($dashboard->response->posts) as $post) { + if ($post->id > $last) { + $last = $post->id; } - if (count($tag_arr)) { - $tags = implode(',', $tag_arr); + Logger::debug('Importing post', ['uid' => $uid, 'created' => date(DateTimeFormat::MYSQL, $post->timestamp), 'id' => $post->id_string]); + + tumblr_process_post($post, $uid, Item::PR_NONE); + + DI::pConfig()->set($uid, 'tumblr', 'last_id', $last); + } +} + +function tumblr_process_post(stdClass $post, int $uid, int $post_reason): int +{ + $uri = 'tumblr::' . $post->id_string . ':' . $post->reblog_key; + + if (Post::exists(['uri' => $uri, 'uid' => $uid]) || ($post->blog->uuid == tumblr_get_page($uid))) { + return 0; + } + + $item = tumblr_get_header($post, $uri, $uid); + + $item = tumblr_get_content($item, $post); + + $item['post-reason'] = $post_reason; + + if (!empty($post->followed)) { + $item['post-reason'] = Item::PR_FOLLOWER; + } + + $id = item::insert($item); + + if ($id) { + $stored = Post::selectFirst(['uri-id'], ['id' => $id]); + + if (!empty($post->tags)) { + foreach ($post->tags as $tag) { + Tag::store($stored['uri-id'], Tag::HASHTAG, $tag); + } } + } + return $id; +} - $title = trim($b['title']); +/** + * Sets the initial data for the item array + * + * @param stdClass $post + * @param string $uri + * @param integer $uid + * @return array + */ +function tumblr_get_header(stdClass $post, string $uri, int $uid): array +{ + $contact = tumblr_get_contact($post->blog, $uid); + $item = [ + 'network' => Protocol::TUMBLR, + 'uid' => $uid, + 'wall' => false, + 'uri' => $uri, + 'private' => Item::UNLISTED, + 'verb' => Activity::POST, + 'contact-id' => $contact['id'], + 'author-name' => $contact['name'], + 'author-link' => $contact['url'], + 'author-avatar' => $contact['avatar'], + 'plink' => $post->post_url, + 'created' => date(DateTimeFormat::MYSQL, $post->timestamp) + ]; + + $item['owner-name'] = $item['author-name']; + $item['owner-link'] = $item['author-link']; + $item['owner-avatar'] = $item['author-avatar']; + + return $item; +} - $siteinfo = BBCode::getAttachedData($b["body"]); +/** + * Set the body according the given content type + * + * @param array $item + * @param stdClass $post + * @return array + */ +function tumblr_get_content(array $item, stdClass $post): array +{ + switch ($post->type) { + case 'text': + $item['title'] = $post->title; + $item['body'] = HTML::toBBCode(tumblr_add_npf_data($post->body, $post->post_url)); + break; - $params = [ - 'state' => 'published', - 'tags' => $tags, - 'tweet' => 'off', - 'format' => 'html', - ]; + case 'quote': + if (empty($post->text)) { + $body = HTML::toBBCode($post->text) . "\n"; + } else { + $body = ''; + } + if (!empty($post->source_title) && !empty($post->source_url)) { + $body .= '[url=' . $post->source_url . ']' . $post->source_title . "[/url]:\n"; + } elseif (!empty($post->source_title)) { + $body .= $post->source_title . ":\n"; + } + $body .= '[quote]' . HTML::toBBCode($post->source) . '[/quote]'; + $item['body'] = $body; + break; + + case 'link': + $item['body'] = HTML::toBBCode($post->description) . "\n" . PageInfo::getFooterFromUrl($post->url); + break; + + case 'answer': + if (!empty($post->asking_name) && !empty($post->asking_url)) { + $body = '[url=' . $post->asking_url . ']' . $post->asking_name . "[/url]:\n"; + } elseif (!empty($post->asking_name)) { + $body = $post->asking_name . ":\n"; + } else { + $body = ''; + } + $body .= '[quote]' . HTML::toBBCode($post->question) . "[/quote]\n" . HTML::toBBCode($post->answer); + $item['body'] = $body; + break; + + case 'video': + $item['body'] = HTML::toBBCode($post->caption); + if (!empty($post->video_url)) { + $item['body'] .= "\n[video]" . $post->video_url . "[/video]\n"; + } elseif (!empty($post->thumbnail_url)) { + $item['body'] .= "\n[url=" . $post->permalink_url . "][img]" . $post->thumbnail_url . "[/img][/url]\n"; + } elseif (!empty($post->permalink_url)) { + $item['body'] .= "\n[url]" . $post->permalink_url . "[/url]\n"; + } elseif (!empty($post->source_url) && !empty($post->source_title)) { + $item['body'] .= "\n[url=" . $post->source_url . "]" . $post->source_title . "[/url]\n"; + } elseif (!empty($post->source_url)) { + $item['body'] .= "\n[url]" . $post->source_url . "[/url]\n"; + } + break; + + case 'audio': + $item['body'] = HTML::toBBCode($post->caption); + if (!empty($post->source_url) && !empty($post->source_title)) { + $item['body'] .= "\n[url=" . $post->source_url . "]" . $post->source_title . "[/url]\n"; + } elseif (!empty($post->source_url)) { + $item['body'] .= "\n[url]" . $post->source_url . "[/url]\n"; + } + break; + + case 'photo': + $item['body'] = HTML::toBBCode($post->caption); + foreach ($post->photos as $photo) { + if (!empty($photo->original_size)) { + $item['body'] .= "\n[img]" . $photo->original_size->url . "[/img]"; + } elseif (!empty($photo->alt_sizes)) { + $item['body'] .= "\n[img]" . $photo->alt_sizes[0]->url . "[/img]"; + } + } + break; + + case 'chat': + $item['title'] = $post->title; + $item['body'] = "\n[ul]"; + foreach ($post->dialogue as $line) { + $item['body'] .= "\n[li]" . $line->label . " " . $line->phrase . "[/li]"; + } + $item['body'] .= "[/ul]\n"; + break; + } + return $item; +} + +function tumblr_add_npf_data(string $html, string $plink): string +{ + $doc = new DOMDocument(); + + $doc->formatOutput = true; + @$doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); + $xpath = new DomXPath($doc); + $list = $xpath->query('//p[@class="npf_link"]'); + foreach ($list as $node) { + $data = tumblr_get_npf_data($node); + if (empty($data)) { + continue; + } - if (!isset($siteinfo["type"])) { - $siteinfo["type"] = ""; + tumblr_replace_with_npf($doc, $node, tumblr_get_type_replacement($data, $plink)); + } + + $list = $xpath->query('//div[@data-npf]'); + foreach ($list as $node) { + $data = tumblr_get_npf_data($node); + if (empty($data)) { + continue; } - if (($title == "") && isset($siteinfo["title"])) { - $title = $siteinfo["title"]; + tumblr_replace_with_npf($doc, $node, tumblr_get_type_replacement($data, $plink)); + } + + $list = $xpath->query('//figure[@data-provider="youtube"]'); + foreach ($list as $node) { + $attributes = tumblr_get_attributes($node); + if (empty($attributes['data-url'])) { + continue; } + tumblr_replace_with_npf($doc, $node, '[youtube]' . $attributes['data-url'] . '[/youtube]'); + } - if (isset($siteinfo["text"])) { - $body = $siteinfo["text"]; - } else { - $body = BBCode::removeShareInformation($b["body"]); + $list = $xpath->query('//figure[@data-npf]'); + foreach ($list as $node) { + $data = tumblr_get_npf_data($node); + if (empty($data)) { + continue; } + tumblr_replace_with_npf($doc, $node, tumblr_get_type_replacement($data, $plink)); + } - switch ($siteinfo["type"]) { - case "photo": - $params['type'] = "photo"; - $params['caption'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS);; + return $doc->saveHTML(); +} - if (isset($siteinfo["url"])) { - $params['link'] = $siteinfo["url"]; - } +function tumblr_replace_with_npf(DOMDocument $doc, DOMNode $node, string $replacement) +{ + if (empty($replacement)) { + return; + } + $replace = $doc->createTextNode($replacement); + $node->parentNode->insertBefore($replace, $node); + $node->parentNode->removeChild($node); +} - $params['source'] = $siteinfo["image"]; - break; +function tumblr_get_npf_data(DOMNode $node): array +{ + $attributes = tumblr_get_attributes($node); + if (empty($attributes['data-npf'])) { + return []; + } - case "link": - $params['type'] = "link"; - $params['title'] = $title; - $params['url'] = $siteinfo["url"]; - $params['description'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS); - break; + return json_decode($attributes['data-npf'], true); +} - case "audio": - $params['type'] = "audio"; - $params['external_url'] = $siteinfo["url"]; - $params['caption'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS); - break; +function tumblr_get_attributes($node): array +{ + if (empty($node->attributes)) { + return []; + } - case "video": - $params['type'] = "video"; - $params['embed'] = $siteinfo["url"]; - $params['caption'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS); - break; + $attributes = []; + foreach ($node->attributes as $key => $attribute) { + $attributes[$key] = trim($attribute->value); + } + return $attributes; +} + +function tumblr_get_type_replacement(array $data, string $plink): string +{ + switch ($data['type']) { + case 'poll': + $body = '[p][url=' . $plink . ']' . $data['question'] . '[/url][/p][ul]'; + foreach ($data['answers'] as $answer) { + $body .= '[li]' . $answer['answer_text'] . '[/li]'; + } + $body .= '[/ul]'; + break; - default: - $params['type'] = "text"; - $params['title'] = $title; - $params['body'] = BBCode::convertForUriId($b['uri-id'], $b['body'], BBCode::CONNECTORS); + case 'link': + $body = PageInfo::getFooterFromUrl(str_replace('https://href.li/?', '', $data['url'])); + break; + + case 'video': + if (!empty($data['url']) && ($data['provider'] == 'tumblr')) { + $body = '[video]' . $data['url'] . '[/video]'; break; + } + + default: + Logger::notice('Unknown type', ['type' => $data['type'], 'data' => $data, 'plink' => $plink]); + $body = ''; + } + + return $body; +} + +/** + * Get a contact array for the given blog + * + * @param stdClass $blog + * @param integer $uid + * @return array + */ +function tumblr_get_contact(stdClass $blog, int $uid): array +{ + $condition = ['network' => Protocol::TUMBLR, 'uid' => 0, 'poll' => 'tumblr::' . $blog->uuid]; + $contact = Contact::selectFirst(['id', 'updated'], $condition); + + $update = empty($contact) || $contact['updated'] < DateTimeFormat::utc('now -24 hours'); + + $public_fields = $fields = tumblr_get_contact_fields($blog, $uid, $update); + + $avatar = $fields['avatar'] ?? ''; + unset($fields['avatar']); + unset($public_fields['avatar']); + + $public_fields['uid'] = 0; + $public_fields['rel'] = Contact::NOTHING; + + if (empty($contact)) { + $cid = Contact::insert($public_fields); + } else { + $cid = $contact['id']; + Contact::update($public_fields, ['id' => $cid], true); + } + + if ($uid != 0) { + $condition = ['network' => Protocol::TUMBLR, 'uid' => $uid, 'poll' => 'tumblr::' . $blog->uuid]; + + $contact = Contact::selectFirst(['id', 'rel', 'uid'], $condition); + if (!isset($fields['rel']) && isset($contact['rel'])) { + $fields['rel'] = $contact['rel']; + } elseif (!isset($fields['rel'])) { + $fields['rel'] = Contact::NOTHING; } + } - if (isset($params['caption']) && (trim($title) != "")) { - $params['caption'] = '

'.$title."

". - "

".$params['caption']."

"; + if (($uid != 0) && ($fields['rel'] != Contact::NOTHING)) { + if (empty($contact)) { + $cid = Contact::insert($fields); + } else { + $cid = $contact['id']; + Contact::update($fields, ['id' => $cid], true); } + Logger::debug('Get user contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]); + } else { + Logger::debug('Get public contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]); + } - if (empty($params['caption']) && !empty($siteinfo["description"])) { - $params['caption'] = BBCode::convertForUriId($b['uri-id'], "[quote]" . $siteinfo["description"] . "[/quote]", BBCode::CONNECTORS); + if (!empty($avatar)) { + Contact::updateAvatar($cid, $avatar); + } + + return Contact::getById($cid); +} + +function tumblr_get_contact_fields(stdClass $blog, int $uid, bool $update): array +{ + $baseurl = 'https://tumblr.com'; + $url = $baseurl . '/' . $blog->name; + + $fields = [ + 'uid' => $uid, + 'network' => Protocol::TUMBLR, + 'poll' => 'tumblr::' . $blog->uuid, + 'baseurl' => $baseurl, + 'priority' => 1, + 'writable' => true, + 'blocked' => false, + 'readonly' => false, + 'pending' => false, + 'url' => $url, + 'nurl' => Strings::normaliseLink($url), + 'alias' => $blog->url, + 'name' => $blog->title ?: $blog->name, + 'nick' => $blog->name, + 'addr' => $blog->name . '@tumblr.com', + 'about' => HTML::toBBCode($blog->description), + 'updated' => date(DateTimeFormat::MYSQL, $blog->updated) + ]; + + if (!$update) { + Logger::debug('Got contact fields', ['uid' => $uid, 'url' => $fields['url']]); + return $fields; + } + + $info = tumblr_get($uid, 'blog/' . $blog->uuid . '/info'); + if ($info->meta->status > 399) { + Logger::notice('Error fetching blog info', ['meta' => $info->meta, 'response' => $info->response, 'errors' => $info->errors]); + return $fields; + } + + $avatar = $info->response->blog->avatar; + if (!empty($avatar)) { + $fields['avatar'] = $avatar[0]->url; + } + + if ($info->response->blog->followed && $info->response->blog->subscribed) { + $fields['rel'] = Contact::FRIEND; + } elseif ($info->response->blog->followed && !$info->response->blog->subscribed) { + $fields['rel'] = Contact::SHARING; + } elseif (!$info->response->blog->followed && $info->response->blog->subscribed) { + $fields['rel'] = Contact::FOLLOWER; + } else { + $fields['rel'] = Contact::NOTHING; + } + + $fields['header'] = $info->response->blog->theme->header_image_focused; + + Logger::debug('Got updated contact fields', ['uid' => $uid, 'url' => $fields['url']]); + return $fields; +} + +/** + * Get the default page for posting. Detects the value if not provided or has got a bad value. + * + * @param integer $uid + * @param array $blogs + * @return string + */ +function tumblr_get_page(int $uid, array $blogs = []): string +{ + $page = DI::pConfig()->get($uid, 'tumblr', 'page'); + + if (!empty($page) && (strpos($page, '/') === false)) { + return $page; + } + + if (empty($blogs)) { + $blogs = tumblr_get_blogs($uid); + } + + if (!empty($blogs)) { + $page = array_key_first($blogs); + DI::pConfig()->set($uid, 'tumblr', 'page', $page); + return $page; + } + + return ''; +} + +/** + * Get an array of blogs for the given user + * + * @param integer $uid + * @return array + */ +function tumblr_get_blogs(int $uid): array +{ + $userinfo = tumblr_get($uid, 'user/info'); + if ($userinfo->meta->status > 399) { + Logger::notice('Error fetching blogs', ['meta' => $userinfo->meta, 'response' => $userinfo->response, 'errors' => $userinfo->errors]); + return []; + } + + $blogs = []; + foreach ($userinfo->response->user->blogs as $blog) { + $blogs[$blog->uuid] = $blog->name; + } + return $blogs; +} + +function tumblr_enabled_for_user(int $uid) +{ + return !empty($uid) && !empty(DI::pConfig()->get($uid, 'tumblr', 'access_token')) && + !empty(DI::pConfig()->get($uid, 'tumblr', 'refresh_token')) && + !empty(DI::config()->get('tumblr', 'consumer_key')) && + !empty(DI::config()->get('tumblr', 'consumer_secret')); +} + +/** + * Get a contact array from a Tumblr url + * + * @param string $url + * @param int $uid + * @return array|null + * @throws \Friendica\Network\HTTPException\InternalServerErrorException + */ +function tumblr_get_contact_by_url(string $url, int $uid): ?array +{ + if (!preg_match('#^https?://tumblr.com/(.+)#', $url, $matches) && !preg_match('#^https?://www\.tumblr.com/(.+)#', $url, $matches) && !preg_match('#^https?://(.+)\.tumblr.com#', $url, $matches)) { + try { + $curlResult = DI::httpClient()->get($url); + } catch (\Exception $e) { + return null; + } + $html = $curlResult->getBody(); + if (empty($html)) { + return null; } + $doc = new DOMDocument(); + @$doc->loadHTML($html); + $xpath = new DomXPath($doc); + $body = $xpath->query('body'); + $attributes = tumblr_get_attributes($body->item(0)); + $blog = $attributes['data-urlencoded-name'] ?? ''; + } else { + $blogs = explode('/', $matches[1]); + $blog = $blogs[0] ?? ''; + } + + if (empty($blog)) { + return null; + } + + Logger::debug('Update Tumblr blog data', ['url' => $url, 'blog' => $blog, 'uid' => $uid]); + + $info = tumblr_get($uid, 'blog/' . $blog . '/info'); + if ($info->meta->status > 399) { + Logger::notice('Error fetching blog info', ['meta' => $info->meta, 'response' => $info->response, 'errors' => $info->errors, 'blog' => $blog, 'uid' => $uid]); + return null; + } else { + Logger::debug('Got data', ['blog' => $blog, 'meta' => $info->meta]); + } - $consumer_key = DI::config()->get('tumblr','consumer_key'); - $consumer_secret = DI::config()->get('tumblr','consumer_secret'); + $baseurl = 'https://tumblr.com'; + $url = $baseurl . '/' . $info->response->blog->name; + + return [ + 'url' => $url, + 'nurl' => Strings::normaliseLink($url), + 'addr' => $info->response->blog->name . '@tumblr.com', + 'alias' => $info->response->blog->url, + 'batch' => '', + 'notify' => '', + 'poll' => 'tumblr::' . $info->response->blog->uuid, + 'poco' => '', + 'name' => $info->response->blog->title ?: $info->response->blog->name, + 'nick' => $info->response->blog->name, + 'network' => Protocol::TUMBLR, + 'baseurl' => $baseurl, + 'pubkey' => '', + 'priority' => 0, + 'guid' => $info->response->blog->uuid, + 'about' => HTML::toBBCode($info->response->blog->description), + 'photo' => $info->response->blog->avatar[0]->url, + 'header' => $info->response->blog->theme->header_image_focused, + ]; +} - $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret); +/** + * Perform an OAuth2 GET request + * + * @param integer $uid + * @param string $url + * @param array $parameters + * @return stdClass + */ +function tumblr_get(int $uid, string $url, array $parameters = []): stdClass +{ + $url = 'https://api.tumblr.com/v2/' . $url; - // Make an API call with the TumblrOAuth instance. - $x = $tum_oauth->post($tmbl_blog,$params); - $ret_code = $tum_oauth->http_code; + if ($uid == 0) { + $consumer_key = DI::config()->get('tumblr', 'consumer_key'); + $parameters['api_key'] = $consumer_key; + } - //print_r($params); - if ($ret_code == 201) { - Logger::notice('tumblr_send: success'); - } elseif ($ret_code == 403) { - Logger::notice('tumblr_send: authentication failure'); + if (!empty($parameters)) { + $url .= '?' . http_build_query($parameters); + } + + if ($uid > 0) { + $curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . tumblr_get_token($uid)]]]); + } else { + $curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON); + } + return tumblr_format_result($curlResult); +} + +/** + * Perform an OAuth2 POST request + * + * @param integer $uid + * @param string $url + * @param array $parameters + * @return stdClass + */ +function tumblr_post(int $uid, string $url, array $parameters): stdClass +{ + $url = 'https://api.tumblr.com/v2/' . $url; + + $curlResult = DI::httpClient()->post($url, $parameters, ['Authorization' => ['Bearer ' . tumblr_get_token($uid)]]); + return tumblr_format_result($curlResult); +} + +/** + * Perform an OAuth2 DELETE request + * + * @param integer $uid + * @param string $url + * @param array $parameters + * @return stdClass + */ +function tumblr_delete(int $uid, string $url, array $parameters): stdClass +{ + $url = 'https://api.tumblr.com/v2/' . $url; + + $opts = [ + HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . tumblr_get_token($uid)]], + HttpClientOptions::FORM_PARAMS => $parameters + ]; + + $curlResult = DI::httpClient()->request('delete', $url, $opts); + return tumblr_format_result($curlResult); +} + +/** + * Format the get/post result value + * + * @param ICanHandleHttpResponses $curlResult + * @return stdClass + */ +function tumblr_format_result(ICanHandleHttpResponses $curlResult): stdClass +{ + $result = json_decode($curlResult->getBody()); + if (empty($result) || empty($result->meta)) { + $result = new stdClass; + $result->meta = new stdClass; + $result->meta->status = 500; + $result->meta->msg = ''; + $result->response = []; + $result->errors = []; + } + return $result; +} + +/** + * Fetch the OAuth token, update it if needed + * + * @param integer $uid + * @param string $code + * @return string + */ +function tumblr_get_token(int $uid, string $code = ''): string +{ + $access_token = DI::pConfig()->get($uid, 'tumblr', 'access_token'); + $expires_at = DI::pConfig()->get($uid, 'tumblr', 'expires_at'); + $refresh_token = DI::pConfig()->get($uid, 'tumblr', 'refresh_token'); + + if (empty($code) && !empty($access_token) && ($expires_at > (time()))) { + Logger::debug('Got token', ['uid' => $uid, 'expires_at' => date('c', $expires_at)]); + return $access_token; + } + + $consumer_key = DI::config()->get('tumblr', 'consumer_key'); + $consumer_secret = DI::config()->get('tumblr', 'consumer_secret'); + + $parameters = ['client_id' => $consumer_key, 'client_secret' => $consumer_secret]; + + if (empty($refresh_token) && empty($code)) { + $result = tumblr_exchange_token($uid); + if (empty($result->refresh_token)) { + Logger::info('Invalid result while exchanging token', ['uid' => $uid]); + return ''; + } + $expires_at = time() + $result->expires_in; + Logger::debug('Updated token from OAuth1 to OAuth2', ['uid' => $uid, 'expires_at' => date('c', $expires_at)]); + } else { + if (!empty($code)) { + $parameters['code'] = $code; + $parameters['grant_type'] = 'authorization_code'; } else { - Logger::notice('tumblr_send: general error', ['error' => $x]); + $parameters['refresh_token'] = $refresh_token; + $parameters['grant_type'] = 'refresh_token'; } + + $curlResult = DI::httpClient()->post('https://api.tumblr.com/v2/oauth2/token', $parameters); + if (!$curlResult->isSuccess()) { + Logger::info('Error fetching token', ['uid' => $uid, 'code' => $code, 'result' => $curlResult->getBody(), 'parameters' => $parameters]); + return ''; + } + + $result = json_decode($curlResult->getBody()); + if (empty($result)) { + Logger::info('Invalid result when updating token', ['uid' => $uid]); + return ''; + } + + $expires_at = time() + $result->expires_in; + Logger::debug('Renewed token', ['uid' => $uid, 'expires_at' => date('c', $expires_at)]); } + + DI::pConfig()->set($uid, 'tumblr', 'access_token', $result->access_token); + DI::pConfig()->set($uid, 'tumblr', 'expires_at', $expires_at); + DI::pConfig()->set($uid, 'tumblr', 'refresh_token', $result->refresh_token); + + return $result->access_token; } +/** + * Create an OAuth2 token out of an OAuth1 token + * + * @param int $uid + * @return stdClass + */ +function tumblr_exchange_token(int $uid): stdClass +{ + $oauth_token = DI::pConfig()->get($uid, 'tumblr', 'oauth_token'); + $oauth_token_secret = DI::pConfig()->get($uid, 'tumblr', 'oauth_token_secret'); + + $consumer_key = DI::config()->get('tumblr', 'consumer_key'); + $consumer_secret = DI::config()->get('tumblr', 'consumer_secret'); + + $stack = HandlerStack::create(); + + $middleware = new Oauth1([ + 'consumer_key' => $consumer_key, + 'consumer_secret' => $consumer_secret, + 'token' => $oauth_token, + 'token_secret' => $oauth_token_secret + ]); + + $stack->push($middleware); + + try { + $client = new Client([ + 'base_uri' => 'https://api.tumblr.com/v2/', + 'handler' => $stack + ]); + + $response = $client->post('oauth2/exchange', ['auth' => 'oauth']); + return json_decode($response->getBody()->getContents()); + } catch (RequestException $exception) { + Logger::notice('Exchange failed', ['code' => $exception->getCode(), 'message' => $exception->getMessage()]); + return new stdClass; + } +}