]> git.mxchange.org Git - friendica-addons.git/blob - tumblr/tumblr.php
Tumblr: Users can now follow tags
[friendica-addons.git] / tumblr / tumblr.php
1 <?php
2 /**
3  * Name: Tumblr Post Connector
4  * Description: Post to Tumblr
5  * Version: 2.0
6  * Author: Mike Macgirvin <http://macgirvin.com/profile/mike>
7  * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
8  */
9
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\Database\DBA;
22 use Friendica\DI;
23 use Friendica\Model\Contact;
24 use Friendica\Model\Item;
25 use Friendica\Model\ItemURI;
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;
40
41 define('TUMBLR_DEFAULT_POLL_INTERVAL', 10); // given in minutes
42 define('TUMBLR_DEFAULT_MAXIMUM_TAGS', 10);
43
44 function tumblr_install()
45 {
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');
64 }
65
66 function tumblr_load_config(ConfigFileManager $loader)
67 {
68         DI::app()->getConfigCache()->load($loader->loadAddonConfig('tumblr'), \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC);
69 }
70
71 function tumblr_check_item_notification(array &$notification_data)
72 {
73         if (!tumblr_enabled_for_user($notification_data['uid'])) { 
74                 return;
75         }
76
77         $page = tumblr_get_page($notification_data['uid']);
78         if (empty($page)) {
79                 return;
80         }
81
82         $own_user = Contact::selectFirst(['url', 'alias'], ['uid' => $notification_data['uid'], 'poll' => 'tumblr::'.$page]);
83         if ($own_user) {
84                 $notification_data['profiles'][] = $own_user['url'];
85                 $notification_data['profiles'][] = $own_user['alias'];
86         }
87 }
88
89 function tumblr_probe_detect(array &$hookData)
90 {
91         // Don't overwrite an existing result
92         if (isset($hookData['result'])) {
93                 return;
94         }
95
96         // Avoid a lookup for the wrong network
97         if (!in_array($hookData['network'], ['', Protocol::TUMBLR])) {
98                 return;
99         }
100
101         $hookData['result'] = tumblr_get_contact_by_url($hookData['uri']);
102 }
103
104 function tumblr_item_by_link(array &$hookData)
105 {
106         // Don't overwrite an existing result
107         if (isset($hookData['item_id'])) {
108                 return;
109         }
110
111         if (!tumblr_enabled_for_user($hookData['uid'])) {
112                 return;
113         }
114
115         if (!preg_match('#^https?://www\.tumblr.com/blog/view/(.+)/(\d+).*#', $hookData['uri'], $matches) && !preg_match('#^https?://www\.tumblr.com/(.+)/(\d+).*#', $hookData['uri'], $matches)) {
116                 return;
117         }
118         
119         Logger::debug('Found tumblr post', ['url' => $hookData['uri'], 'blog' => $matches[1], 'id' => $matches[2]]);
120
121         $parameters = ['id' => $matches[2], 'reblog_info' => false, 'notes_info' => false, 'npf' => false];
122         $result = tumblr_get($hookData['uid'], 'blog/' . $matches[1] . '/posts', $parameters);
123         if ($result->meta->status > 399) {
124                 Logger::notice('Error fetching status', ['meta' => $result->meta, 'response' => $result->response, 'errors' => $result->errors, 'blog' => $matches[1], 'id' => $matches[2]]);
125                 return [];
126         }
127
128         Logger::debug('Got post', ['blog' => $matches[1], 'id' => $matches[2], 'result' => $result->response->posts]);
129         if (!empty($result->response->posts)) {
130                 $hookData['item_id'] = tumblr_process_post($result->response->posts[0], $hookData['uid'], Item::PR_FETCHED);
131         }
132 }
133
134 function tumblr_support_follow(array &$data)
135 {
136         if ($data['protocol'] == Protocol::TUMBLR) {
137                 $data['result'] = true;
138         }
139 }
140
141 function tumblr_support_probe(array &$data)
142 {
143         if ($data['protocol'] == Protocol::TUMBLR) {
144                 $data['result'] = true;
145         }
146 }
147
148 function tumblr_follow(array &$hook_data)
149 {
150         $uid = DI::userSession()->getLocalUserId();
151
152         if (!tumblr_enabled_for_user($uid)) {
153                 return;
154         }
155
156         Logger::debug('Check if contact is Tumblr', ['url' => $hook_data['url']]);
157
158         $fields = tumblr_get_contact_by_url($hook_data['url']);
159         if (empty($fields)) {
160                 Logger::debug('Contact is not a Tumblr contact', ['url' => $hook_data['url']]);
161                 return;
162         }
163
164         $result = tumblr_post($uid, 'user/follow', ['url' => $fields['url']]);
165         if ($result->meta->status <= 399) {
166                 $hook_data['contact'] = $fields;
167                 Logger::debug('Successfully start following', ['url' => $fields['url']]);
168         } else {
169                 Logger::notice('Following failed', ['meta' => $result->meta, 'response' => $result->response, 'errors' => $result->errors, 'url' => $fields['url']]);
170         }
171 }
172
173 function tumblr_unfollow(array &$hook_data)
174 {
175         if (!tumblr_enabled_for_user($hook_data['uid'])) {
176                 return;
177         }
178
179         if (!tumblr_get_contact_uuid($hook_data['contact'])) {
180                 return;
181         }
182         $result = tumblr_post($hook_data['uid'], 'user/unfollow', ['url' => $hook_data['contact']['url']]);
183         $hook_data['result'] = ($result->meta->status <= 399);
184 }
185
186 function tumblr_block(array &$hook_data)
187 {
188         if (!tumblr_enabled_for_user($hook_data['uid'])) {
189                 return;
190         }
191
192         $uuid = tumblr_get_contact_uuid($hook_data['contact']);
193         if (!$uuid) {
194                 return;
195         }
196
197         $result = tumblr_post($hook_data['uid'], 'blog/' . tumblr_get_page($hook_data['uid']) . '/blocks', ['blocked_tumblelog' => $uuid]);
198         $hook_data['result'] = ($result->meta->status <= 399);
199
200         if ($hook_data['result']) {
201                 $cdata = Contact::getPublicAndUserContactID($hook_data['contact']['id'], $hook_data['uid']);
202                 if (!empty($cdata['user'])) {
203                         Contact::remove($cdata['user']);
204                 }
205         }
206 }
207
208 function tumblr_unblock(array &$hook_data)
209 {
210         if (!tumblr_enabled_for_user($hook_data['uid'])) {
211                 return;
212         }
213
214         $uuid = tumblr_get_contact_uuid($hook_data['contact']);
215         if (!$uuid) {
216                 return;
217         }
218
219         $result = tumblr_delete($hook_data['uid'], 'blog/' . tumblr_get_page($hook_data['uid']) . '/blocks', ['blocked_tumblelog' => $uuid]);
220         $hook_data['result'] = ($result->meta->status <= 399);
221 }
222
223 function tumblr_get_contact_uuid(array $contact): string
224 {
225         if (($contact['network'] != Protocol::TUMBLR) || (substr($contact['poll'], 0, 8) != 'tumblr::')) {
226                 return '';
227         }
228         return substr($contact['poll'], 8);
229 }
230
231 /**
232  * This is a statement rather than an actual function definition. The simple
233  * existence of this method is checked to figure out if the addon offers a
234  * module.
235  */
236 function tumblr_module()
237 {
238 }
239
240 function tumblr_content()
241 {
242         if (!DI::userSession()->getLocalUserId()) {
243                 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
244                 return;
245         }
246
247         switch (DI::args()->getArgv()[1] ?? '') {
248                 case 'connect':
249                         tumblr_connect();
250                         break;
251
252                 case 'redirect':
253                         tumblr_redirect();
254                         break;
255         }
256         DI::baseUrl()->redirect('settings/connectors/tumblr');
257 }
258
259 function tumblr_redirect()
260 {
261         if (($_REQUEST['state'] ?? '') != DI::session()->get('oauth_state')) {
262                 return;
263         }
264
265         tumblr_get_token(DI::userSession()->getLocalUserId(), $_REQUEST['code'] ?? '');
266 }
267
268 function tumblr_connect()
269 {
270         // Define the needed keys
271         $consumer_key    = DI::config()->get('tumblr', 'consumer_key');
272         $consumer_secret = DI::config()->get('tumblr', 'consumer_secret');
273
274         if (empty($consumer_key) || empty($consumer_secret)) {
275                 return;
276         }
277
278         $state = base64_encode(random_bytes(20));
279         DI::session()->set('oauth_state', $state);
280
281         $parameters = [
282                 'client_id'     => $consumer_key,
283                 'response_type' => 'code',
284                 'scope'         => 'basic write offline_access',
285                 'state'         => $state
286         ];
287
288         System::externalRedirect('https://www.tumblr.com/oauth2/authorize?' . http_build_query($parameters));
289 }
290
291 function tumblr_addon_admin(string &$o)
292 {
293         $t = Renderer::getMarkupTemplate('admin.tpl', 'addon/tumblr/');
294
295         $o = Renderer::replaceMacros($t, [
296                 '$submit' => DI::l10n()->t('Save Settings'),
297                 '$consumer_key'    => ['consumer_key', DI::l10n()->t('Consumer Key'), DI::config()->get('tumblr', 'consumer_key'), ''],
298                 '$consumer_secret' => ['consumer_secret', DI::l10n()->t('Consumer Secret'), DI::config()->get('tumblr', 'consumer_secret'), ''],
299                 '$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.')],
300         ]);
301 }
302
303 function tumblr_addon_admin_post()
304 {
305         DI::config()->set('tumblr', 'consumer_key', trim($_POST['consumer_key'] ?? ''));
306         DI::config()->set('tumblr', 'consumer_secret', trim($_POST['consumer_secret'] ?? ''));
307         DI::config()->set('tumblr', 'max_tags', max(0, intval($_POST['max_tags'] ?? '')));
308 }
309
310 function tumblr_settings(array &$data)
311 {
312         if (!DI::userSession()->getLocalUserId()) {
313                 return;
314         }
315
316         $enabled     = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post', false);
317         $def_enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post_by_default', false);
318         $import      = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'import', false);
319         $tags        = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'tags');
320
321         $max_tags = DI::config()->get('tumblr', 'max_tags', TUMBLR_DEFAULT_MAXIMUM_TAGS);
322
323         $tags_str = implode(', ', $tags ?? []);
324         $cachekey = 'tumblr-blogs-' . DI::userSession()->getLocalUserId();
325         $blogs = DI::cache()->get($cachekey);
326         if (empty($blogs)) {
327                 $blogs = tumblr_get_blogs(DI::userSession()->getLocalUserId());
328                 if (!empty($blogs)) {
329                         DI::cache()->set($cachekey, $blogs, Duration::HALF_HOUR);
330                 }
331         }
332
333         if (!empty($blogs)) {
334                 $page = tumblr_get_page(DI::userSession()->getLocalUserId(), $blogs);
335
336                 $page_select = ['tumblr_page', DI::l10n()->t('Post to page:'), $page, '', $blogs];
337         }
338
339         $t    = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/tumblr/');
340         $html = Renderer::replaceMacros($t, [
341                 '$l10n' => [
342                         'connect'   => DI::l10n()->t('(Re-)Authenticate your tumblr page'),
343                         'noconnect' => DI::l10n()->t('You are not authenticated to tumblr'),
344                 ],
345
346                 '$authenticate_url' => DI::baseUrl() . '/tumblr/connect',
347
348                 '$enable'      => ['tumblr', DI::l10n()->t('Enable Tumblr Post Addon'), $enabled],
349                 '$bydefault'   => ['tumblr_bydefault', DI::l10n()->t('Post to Tumblr by default'), $def_enabled],
350                 '$import'      => ['tumblr_import', DI::l10n()->t('Import the remote timeline'), $import],
351                 '$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)],
352                 '$page_select' => $page_select ?? '',
353         ]);
354
355         $data = [
356                 'connector' => 'tumblr',
357                 'title'     => DI::l10n()->t('Tumblr Import/Export'),
358                 'image'     => 'images/tumblr.png',
359                 'enabled'   => $enabled,
360                 'html'      => $html,
361         ];
362 }
363
364 function tumblr_jot_nets(array &$jotnets_fields)
365 {
366         if (!DI::userSession()->getLocalUserId()) {
367                 return;
368         }
369
370         if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post')) {
371                 $jotnets_fields[] = [
372                         'type' => 'checkbox',
373                         'field' => [
374                                 'tumblr_enable',
375                                 DI::l10n()->t('Post to Tumblr'),
376                                 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post_by_default')
377                         ]
378                 ];
379         }
380 }
381
382 function tumblr_settings_post(array &$b)
383 {
384         if (!empty($_POST['tumblr-submit'])) {
385                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'post',            intval($_POST['tumblr']));
386                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'page',            $_POST['tumblr_page']);
387                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'post_by_default', intval($_POST['tumblr_bydefault']));
388                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'import',          intval($_POST['tumblr_import']));
389
390                 $max_tags = DI::config()->get('tumblr', 'max_tags', TUMBLR_DEFAULT_MAXIMUM_TAGS);
391                 $tags     = [];
392                 foreach (explode(',', $_POST['tags']) as $tag) {
393                         if (count($tags) < $max_tags) {
394                                 $tags[] = trim($tag, ' #');
395                         }
396                 }
397
398                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'tags', $tags);
399         }
400 }
401
402 function tumblr_cron()
403 {
404         $last = DI::keyValue()->get('tumblr_last_poll');
405
406         $poll_interval = intval(DI::config()->get('tumblr', 'poll_interval'));
407         if (!$poll_interval) {
408                 $poll_interval = TUMBLR_DEFAULT_POLL_INTERVAL;
409         }
410
411         if ($last) {
412                 $next = $last + ($poll_interval * 60);
413                 if ($next > time()) {
414                         Logger::notice('poll interval not reached');
415                         return;
416                 }
417         }
418         Logger::notice('cron_start');
419
420         $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
421         if ($abandon_days < 1) {
422                 $abandon_days = 0;
423         }
424
425         $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
426
427         $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'tumblr', 'k' => 'import', 'v' => true]);
428         foreach ($pconfigs as $pconfig) {
429                 if ($abandon_days != 0) {
430                         if (!DBA::exists('user', ["`uid` = ? AND `login_date` >= ?", $pconfig['uid'], $abandon_limit])) {
431                                 Logger::notice('abandoned account: timeline from user will not be imported', ['user' => $pconfig['uid']]);
432                                 continue;
433                         }
434                 }
435
436                 Logger::notice('importing timeline - start', ['user' => $pconfig['uid']]);
437                 tumblr_fetch_dashboard($pconfig['uid']);
438                 tumblr_fetch_tags($pconfig['uid']);
439                 Logger::notice('importing timeline - done', ['user' => $pconfig['uid']]);
440         }
441
442         Logger::notice('cron_end');
443
444         DI::keyValue()->set('tumblr_last_poll', time());
445 }
446
447 function tumblr_hook_fork(array &$b)
448 {
449         if ($b['name'] != 'notifier_normal') {
450                 return;
451         }
452
453         $post = $b['data'];
454
455         // Editing is not supported by the addon
456         if (($post['created'] !== $post['edited']) && !$post['deleted']) {
457                 DI::logger()->info('Editing is not supported by the addon');
458                 $b['execute'] = false;
459                 return;
460         }
461
462         if (DI::pConfig()->get($post['uid'], 'tumblr', 'import')) {
463                 // Don't post if it isn't a reply to a tumblr post
464                 if (($post['parent'] != $post['id']) && !Post::exists(['id' => $post['parent'], 'network' => Protocol::TUMBLR])) {
465                         Logger::notice('No tumblr parent found', ['item' => $post['id']]);
466                         $b['execute'] = false;
467                         return;
468                 }
469         } elseif (!strstr($post['postopts'] ?? '', 'tumblr') || ($post['parent'] != $post['id']) || $post['private']) {
470                 DI::logger()->info('Activities are never exported when we don\'t import the tumblr timeline', ['uid' => $post['uid']]);
471                 $b['execute'] = false;
472                 return;
473         }
474 }
475
476 function tumblr_post_local(array &$b)
477 {
478         if ($b['edit']) {
479                 return;
480         }
481
482         if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
483                 return;
484         }
485
486         if ($b['private'] || $b['parent']) {
487                 return;
488         }
489
490         $tmbl_post   = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post'));
491         $tmbl_enable = (($tmbl_post && !empty($_REQUEST['tumblr_enable'])) ? intval($_REQUEST['tumblr_enable']) : 0);
492
493         // if API is used, default to the chosen settings
494         if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post_by_default'))) {
495                 $tmbl_enable = 1;
496         }
497
498         if (!$tmbl_enable) {
499                 return;
500         }
501
502         if (strlen($b['postopts'])) {
503                 $b['postopts'] .= ',';
504         }
505
506         $b['postopts'] .= 'tumblr';
507 }
508
509 function tumblr_send(array &$b)
510 {
511         if (($b['created'] !== $b['edited']) && !$b['deleted']) {
512                 return;
513         }
514
515         if ($b['gravity'] != Item::GRAVITY_PARENT) {
516                 Logger::debug('Got comment', ['item' => $b]);
517
518                 $parent = tumblr_get_post_from_uri($b['thr-parent']);
519                 if (empty($parent)) {
520                         Logger::notice('No tumblr post', ['thr-parent' => $b['thr-parent']]);
521                         return;
522                 }
523
524                 Logger::debug('Parent found', ['parent' => $parent]);
525
526                 $page = tumblr_get_page($b['uid']);
527
528                 if ($b['gravity'] == Item::GRAVITY_COMMENT) {
529                         Logger::notice('Commenting is not supported (yet)');
530                 } else {
531                         if (($b['verb'] == Activity::LIKE) && !$b['deleted']) {
532                                 $params = ['id' => $parent['id'], 'reblog_key' => $parent['reblog_key']];
533                                 $result = tumblr_post($b['uid'], 'user/like', $params);
534                         } elseif (($b['verb'] == Activity::LIKE) && $b['deleted']) {
535                                 $params = ['id' => $parent['id'], 'reblog_key' => $parent['reblog_key']];
536                                 $result = tumblr_post($b['uid'], 'user/unlike', $params);
537                         } elseif (($b['verb'] == Activity::ANNOUNCE) && !$b['deleted']) {
538                                 $params = ['id' => $parent['id'], 'reblog_key' => $parent['reblog_key']];
539                                 $result = tumblr_post($b['uid'], 'blog/' . $page . '/post/reblog', $params);
540                         } elseif (($b['verb'] == Activity::ANNOUNCE) && $b['deleted']) {
541                                 $announce = tumblr_get_post_from_uri($b['extid']);
542                                 if (empty($announce)) {
543                                         return;
544                                 }
545                                 $params = ['id' => $announce['id']];
546                                 $result = tumblr_post($b['uid'], 'blog/' . $page . '/post/delete', $params);
547                         } else {
548                                 // Unsupported activity
549                                 return;
550                         }
551
552                         if ($result->meta->status < 400) {
553                                 Logger::info('Successfully performed activity', ['verb' => $b['verb'], 'deleted' => $b['deleted'], 'meta' => $result->meta, 'response' => $result->response]);
554                                 if (!$b['deleted'] && !empty($result->response->id_string)) {
555                                         Item::update(['extid' => 'tumblr::' . $result->response->id_string], ['id' => $b['id']]);
556                                 }
557                         } else {
558                                 Logger::notice('Error while performing activity', ['verb' => $b['verb'], 'deleted' => $b['deleted'], 'meta' => $result->meta, 'response' => $result->response, 'errors' => $result->errors, 'params' => $params]);
559                         }
560                 }
561                 return;
562         } elseif ($b['private'] || !strstr($b['postopts'], 'tumblr')) {
563                 return;
564         }
565
566         if (!tumblr_send_npf($b)) {
567                 tumblr_send_legacy($b);
568         }
569 }
570
571 function tumblr_send_legacy(array $b)
572 {
573         $b['body'] = BBCode::removeAttachment($b['body']);
574
575         $title = trim($b['title']);
576
577         $media = Post\Media::getByURIId($b['uri-id'], [Post\Media::HTML, Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE]);
578
579         $photo = array_search(Post\Media::IMAGE, array_column($media, 'type'));
580         $link  = array_search(Post\Media::HTML, array_column($media, 'type'));
581         $audio = array_search(Post\Media::AUDIO, array_column($media, 'type'));
582         $video = array_search(Post\Media::VIDEO, array_column($media, 'type'));
583
584         $params = [
585                 'state'  => 'published',
586                 'tags'   => implode(',', array_column(Tag::getByURIId($b['uri-id']), 'name')),
587                 'tweet'  => 'off',
588                 'format' => 'html',
589         ];
590
591         $body = BBCode::removeShareInformation($b['body']);
592         $body = Post\Media::removeFromEndOfBody($body);
593
594         if ($photo !== false) {
595                 $params['type'] = 'photo';
596                 $params['caption'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS);
597                 $params['data'] = [];
598                 foreach ($media as $photo) {
599                         if ($photo['type'] == Post\Media::IMAGE) {
600                                 if (Network::isLocalLink($photo['url']) && ($data = Photo::getResourceData($photo['url']))) {
601                                         $photo = Photo::selectFirst([], ["`resource-id` = ? AND `scale` > ?", $data['guid'], 0]);
602                                         if (!empty($photo)) {
603                                                 $params['data'][] = Photo::getImageDataForPhoto($photo);
604                                         }
605                                 }
606                         }
607                 }
608         } elseif ($link !== false) {
609                 $params['type']        = 'link';
610                 $params['title']       = $media[$link]['name'];
611                 $params['url']         = $media[$link]['url'];
612                 $params['description'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS);
613
614                 if (!empty($media[$link]['preview'])) {
615                         $params['thumbnail'] = $media[$link]['preview'];
616                 }
617                 if (!empty($media[$link]['description'])) {
618                         $params['excerpt'] = $media[$link]['description'];
619                 }
620                 if (!empty($media[$link]['author-name'])) {
621                         $params['author'] = $media[$link]['author-name'];
622                 }
623         } elseif ($audio !== false) {
624                 $params['type']         = 'audio';
625                 $params['external_url'] = $media[$audio]['url'];
626                 $params['caption']      = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS);
627         } elseif ($video !== false) {
628                 $params['type']    = 'video';
629                 $params['embed']   = $media[$video]['url'];
630                 $params['caption'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS);
631         } else {
632                 $params['type']  = 'text';
633                 $params['title'] = $title;
634                 $params['body']  = BBCode::convertForUriId($b['uri-id'], $b['body'], BBCode::CONNECTORS);
635         }
636
637         if (isset($params['caption']) && (trim($title) != '')) {
638                 $params['caption'] = '<h1>' . $title . '</h1>' .
639                         '<p>' . $params['caption'] . '</p>';
640         }
641
642         $page = tumblr_get_page($b['uid']);
643
644         $result = tumblr_post($b['uid'], 'blog/' . $page . '/post', $params);
645
646         if ($result->meta->status < 400) {
647                 Logger::info('Success (legacy)', ['blog' => $page, 'meta' => $result->meta, 'response' => $result->response]);
648         } else {
649                 Logger::notice('Error posting blog (legacy)', ['blog' => $page, 'meta' => $result->meta, 'response' => $result->response, 'errors' => $result->errors, 'params' => $params]);
650         }
651 }
652
653 function tumblr_send_npf(array $post): bool
654 {
655         $page = tumblr_get_page($post['uid']);
656
657         if (empty($page)) {
658                 Logger::notice('Missing page, post will not be send to Tumblr.', ['uid' => $post['uid'], 'page' => $page, 'id' => $post['id']]);
659                 // "true" is returned, since the legacy function will fail as well.
660                 return true;
661         }
662
663         $post['body'] = Post\Media::addAttachmentsToBody($post['uri-id'], $post['body']);
664         if (!empty($post['title'])) {
665                 $post['body'] = '[h1]' . $post['title'] . "[/h1]\n" . $post['body'];
666         }
667
668         $params = [
669                 'content'                => NPF::fromBBCode($post['body'], $post['uri-id']),
670                 'state'                  => 'published',
671                 'date'                   => DateTimeFormat::utc($post['created'], DateTimeFormat::ATOM),
672                 'tags'                   => implode(',', array_column(Tag::getByURIId($post['uri-id']), 'name')),
673                 'is_private'             => false,
674                 'interactability_reblog' => 'everyone'
675         ];
676
677         $result = tumblr_post($post['uid'], 'blog/' . $page . '/posts', $params);
678
679         if ($result->meta->status < 400) {
680                 Logger::info('Success (NPF)', ['blog' => $page, 'meta' => $result->meta, 'response' => $result->response]);
681                 return true;
682         } else {
683                 Logger::notice('Error posting blog (NPF)', ['blog' => $page, 'meta' => $result->meta, 'response' => $result->response, 'errors' => $result->errors, 'params' => $params]);
684                 return false;
685         }
686 }
687
688 function tumblr_get_post_from_uri(string $uri): array
689 {
690         $parts = explode(':', $uri);
691         if (($parts[0] != 'tumblr') || empty($parts[2])) {
692                 return [];
693         }
694
695         $post['id']        = $parts[2];
696         $post['reblog_key'] = $parts[3] ?? '';
697
698         $post['reblog_key'] = str_replace('@t', '', $post['reblog_key']); // Temp
699         return $post;
700 }
701
702 /**
703  * Fetch posts for user defined hashtags for the given user
704  *
705  * @param integer $uid
706  * @return void
707  */
708 function tumblr_fetch_tags(int $uid)
709 {
710         if (!DI::config()->get('tumblr', 'max_tags', TUMBLR_DEFAULT_MAXIMUM_TAGS)) {
711                 return;
712         }
713
714         foreach (DI::pConfig()->get($uid, 'tumblr', 'tags', []) as $tag) {
715                 $data = tumblr_get($uid, 'tagged', ['tag' => $tag]);
716                 foreach (array_reverse($data->response) as $post) {
717                         $id = tumblr_process_post($post, $uid, Item::PR_TAG);
718                         if (!empty($id)) {
719                                 Logger::debug('Tag post imported', ['tag' => $tag, 'id' => $id]);
720                         }
721                 }
722         }
723 }
724
725 /**
726  * Fetch the dashboard (timeline) for the given user
727  *
728  * @param integer $uid
729  * @return void
730  */
731 function tumblr_fetch_dashboard(int $uid)
732 {
733         $parameters = ['reblog_info' => false, 'notes_info' => false, 'npf' => false];
734
735         $last = DI::pConfig()->get($uid, 'tumblr', 'last_id');
736         if (!empty($last)) {
737                 $parameters['since_id'] = $last;
738         }
739
740         $dashboard = tumblr_get($uid, 'user/dashboard', $parameters);
741         if ($dashboard->meta->status > 399) {
742                 Logger::notice('Error fetching dashboard', ['meta' => $dashboard->meta, 'response' => $dashboard->response, 'errors' => $dashboard->errors]);
743                 return [];
744         }
745
746         if (empty($dashboard->response->posts)) {
747                 return;
748         }
749
750         foreach (array_reverse($dashboard->response->posts) as $post) {
751                 if ($post->id > $last) {
752                         $last = $post->id;
753                 }
754
755                 Logger::debug('Importing post', ['uid' => $uid, 'created' => date(DateTimeFormat::MYSQL, $post->timestamp), 'id' => $post->id_string]);
756
757                 tumblr_process_post($post, $uid, Item::PR_NONE);
758
759                 DI::pConfig()->set($uid, 'tumblr', 'last_id', $last);
760         }
761 }
762
763 function tumblr_process_post(stdClass $post, int $uid, int $post_reason): int
764 {
765         $uri = 'tumblr::' . $post->id_string . ':' . $post->reblog_key;
766
767         if (Post::exists(['uri' => $uri, 'uid' => $uid]) || ($post->blog->uuid == tumblr_get_page($uid))) {
768                 return 0;
769         }
770
771         $item = tumblr_get_header($post, $uri, $uid);
772
773         $item = tumblr_get_content($item, $post);
774
775         $item['post-reason'] = $post_reason;
776
777         if (!empty($post->followed)) {
778                 $item['post-reason'] = Item::PR_FOLLOWER;
779         }
780
781         $id = item::insert($item);
782
783         if ($id) {
784                 $stored = Post::selectFirst(['uri-id'], ['id' => $id]);
785
786                 if (!empty($post->tags)) {
787                         foreach ($post->tags as $tag) {
788                                 Tag::store($stored['uri-id'], Tag::HASHTAG, $tag);
789                         }
790                 }
791         }
792         return $id;
793 }
794
795 /**
796  * Sets the initial data for the item array
797  *
798  * @param stdClass $post
799  * @param string $uri
800  * @param integer $uid
801  * @return array
802  */
803 function tumblr_get_header(stdClass $post, string $uri, int $uid): array
804 {
805         $contact = tumblr_get_contact($post->blog, $uid);
806         $item = [
807                 'network'       => Protocol::TUMBLR,
808                 'uid'           => $uid,
809                 'wall'          => false,
810                 'uri'           => $uri,
811                 'private'       => Item::UNLISTED,
812                 'verb'          => Activity::POST,
813                 'contact-id'    => $contact['id'],
814                 'author-name'   => $contact['name'],
815                 'author-link'   => $contact['url'],
816                 'author-avatar' => $contact['avatar'],
817                 'plink'         => $post->post_url,
818                 'created'       => date(DateTimeFormat::MYSQL, $post->timestamp)
819         ];
820
821         $item['owner-name']   = $item['author-name'];
822         $item['owner-link']   = $item['author-link'];
823         $item['owner-avatar'] = $item['author-avatar'];
824
825         return $item;
826 }
827
828 /**
829  * Set the body according the given content type
830  *
831  * @param array $item
832  * @param stdClass $post
833  * @return array
834  */
835 function tumblr_get_content(array $item, stdClass $post): array
836 {
837         switch ($post->type) {
838                 case 'text':
839                         $item['title'] = $post->title;
840                         $item['body'] = HTML::toBBCode(tumblr_add_npf_data($post->body, $post->post_url));
841                         break;
842
843                 case 'quote':
844                         if (empty($post->text)) {
845                                 $body = HTML::toBBCode($post->text) . "\n";
846                         } else {
847                                 $body = '';
848                         }
849                         if (!empty($post->source_title) && !empty($post->source_url)) {
850                                 $body .= '[url=' . $post->source_url . ']' . $post->source_title . "[/url]:\n";
851                         } elseif (!empty($post->source_title)) {
852                                 $body .= $post->source_title . ":\n";
853                         }
854                         $body .= '[quote]' . HTML::toBBCode($post->source) . '[/quote]';
855                         $item['body'] = $body;
856                         break;
857
858                 case 'link':
859                         $item['body'] = HTML::toBBCode($post->description) . "\n" . PageInfo::getFooterFromUrl($post->url);
860                         break;
861
862                 case 'answer':
863                         if (!empty($post->asking_name) && !empty($post->asking_url)) {
864                                 $body = '[url=' . $post->asking_url . ']' . $post->asking_name . "[/url]:\n";
865                         } elseif (!empty($post->asking_name)) {
866                                 $body = $post->asking_name . ":\n";
867                         } else {
868                                 $body = '';
869                         }
870                         $body .= '[quote]' . HTML::toBBCode($post->question) . "[/quote]\n" . HTML::toBBCode($post->answer);
871                         $item['body'] = $body;
872                         break;
873
874                 case 'video':
875                         $item['body'] = HTML::toBBCode($post->caption);
876                         if (!empty($post->video_url)) {
877                                 $item['body'] .= "\n[video]" . $post->video_url . "[/video]\n";
878                         } elseif (!empty($post->thumbnail_url)) {
879                                 $item['body'] .= "\n[url=" . $post->permalink_url . "][img]" . $post->thumbnail_url . "[/img][/url]\n";
880                         } elseif (!empty($post->permalink_url)) {
881                                 $item['body'] .= "\n[url]" . $post->permalink_url . "[/url]\n";
882                         } elseif (!empty($post->source_url) && !empty($post->source_title)) {
883                                 $item['body'] .= "\n[url=" . $post->source_url . "]" . $post->source_title . "[/url]\n";
884                         } elseif (!empty($post->source_url)) {
885                                 $item['body'] .= "\n[url]" . $post->source_url . "[/url]\n";
886                         }
887                         break;
888
889                 case 'audio':
890                         $item['body'] = HTML::toBBCode($post->caption);
891                         if (!empty($post->source_url) && !empty($post->source_title)) {
892                                 $item['body'] .= "\n[url=" . $post->source_url . "]" . $post->source_title . "[/url]\n";
893                         } elseif (!empty($post->source_url)) {
894                                 $item['body'] .= "\n[url]" . $post->source_url . "[/url]\n";
895                         }
896                         break;
897
898                 case 'photo':
899                         $item['body'] = HTML::toBBCode($post->caption);
900                         foreach ($post->photos as $photo) {
901                                 if (!empty($photo->original_size)) {
902                                         $item['body'] .= "\n[img]" . $photo->original_size->url . "[/img]";
903                                 } elseif (!empty($photo->alt_sizes)) {
904                                         $item['body'] .= "\n[img]" . $photo->alt_sizes[0]->url . "[/img]";
905                                 }
906                         }
907                         break;
908
909                 case 'chat':
910                         $item['title'] = $post->title;
911                         $item['body']  = "\n[ul]";
912                         foreach ($post->dialogue as $line) {
913                                 $item['body'] .= "\n[li]" . $line->label . " " . $line->phrase . "[/li]";
914                         }
915                         $item['body'] .= "[/ul]\n";
916                         break;
917         }
918         return $item;
919 }
920
921 function tumblr_add_npf_data(string $html, string $plink): string
922 {
923         $doc = new DOMDocument();
924
925         $doc->formatOutput = true;
926         @$doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
927         $xpath = new DomXPath($doc);
928         $list = $xpath->query('//p[@class="npf_link"]');
929         foreach ($list as $node) {
930                 $data = tumblr_get_npf_data($node);
931                 if (empty($data)) {
932                         continue;
933                 }
934
935                 tumblr_replace_with_npf($doc, $node, tumblr_get_type_replacement($data, $plink));
936         }
937
938         $list = $xpath->query('//div[@data-npf]');
939         foreach ($list as $node) {
940                 $data = tumblr_get_npf_data($node);
941                 if (empty($data)) {
942                         continue;
943                 }
944
945                 tumblr_replace_with_npf($doc, $node, tumblr_get_type_replacement($data, $plink));
946         }
947
948         $list = $xpath->query('//figure[@data-provider="youtube"]');
949         foreach ($list as $node) {
950                 $attributes = tumblr_get_attributes($node);
951                 if (empty($attributes['data-url'])) {
952                         continue;
953                 }
954                 tumblr_replace_with_npf($doc, $node, '[youtube]' . $attributes['data-url'] . '[/youtube]');
955         }
956
957         $list = $xpath->query('//figure[@data-npf]');
958         foreach ($list as $node) {
959                 $data = tumblr_get_npf_data($node);
960                 if (empty($data)) {
961                         continue;
962                 }
963                 tumblr_replace_with_npf($doc, $node, tumblr_get_type_replacement($data, $plink));
964         }
965
966         return $doc->saveHTML();
967 }
968
969 function tumblr_replace_with_npf(DOMDocument $doc, DOMNode $node, string $replacement)
970 {
971         if (empty($replacement)) {
972                 return;
973         }
974         $replace = $doc->createTextNode($replacement);
975         $node->parentNode->insertBefore($replace, $node);
976         $node->parentNode->removeChild($node);
977 }
978
979 function tumblr_get_npf_data(DOMNode $node): array
980 {
981         $attributes = tumblr_get_attributes($node);
982         if (empty($attributes['data-npf'])) {
983                 return [];
984         }
985
986         return json_decode($attributes['data-npf'], true);
987 }
988
989 function tumblr_get_attributes($node): array
990 {
991         if (empty($node->attributes)) {
992                 return [];
993         }
994
995         $attributes = [];
996         foreach ($node->attributes as $key => $attribute) {
997                 $attributes[$key] = trim($attribute->value);
998         }
999         return $attributes;
1000 }
1001
1002 function tumblr_get_type_replacement(array $data, string $plink): string
1003 {
1004         switch ($data['type']) {
1005                 case 'poll':
1006                         $body = '[p][url=' . $plink . ']' . $data['question'] . '[/url][/p][ul]';
1007                         foreach ($data['answers'] as $answer) {
1008                                 $body .= '[li]' . $answer['answer_text'] . '[/li]';
1009                         }
1010                         $body .= '[/ul]';
1011                         break;
1012
1013                 case 'link':
1014                         $body = PageInfo::getFooterFromUrl(str_replace('https://href.li/?', '', $data['url']));
1015                         break;
1016
1017                 case 'video':
1018                         if (!empty($data['url']) && ($data['provider'] == 'tumblr')) {
1019                                 $body = '[video]' . $data['url'] . '[/video]';
1020                                 break;
1021                         }
1022
1023                 default:
1024                         Logger::notice('Unknown type', ['type' => $data['type'], 'data' => $data, 'plink' => $plink]);
1025                         $body = '';
1026         }
1027
1028         return $body;
1029 }
1030
1031 /**
1032  * Get a contact array for the given blog
1033  *
1034  * @param stdClass $blog
1035  * @param integer $uid
1036  * @return array
1037  */
1038 function tumblr_get_contact(stdClass $blog, int $uid): array
1039 {
1040         $condition = ['network' => Protocol::TUMBLR, 'uid' => $uid, 'poll' => 'tumblr::' . $blog->uuid];
1041         $contact = Contact::selectFirst([], $condition);
1042         if (!empty($contact) && (strtotime($contact['updated']) >= $blog->updated)) {
1043                 return $contact;
1044         }
1045         if (empty($contact)) {
1046                 $cid = tumblr_insert_contact($blog, $uid);
1047         } else {
1048                 $cid = $contact['id'];
1049         }
1050
1051         $condition['uid'] = 0;
1052
1053         $contact = Contact::selectFirst([], $condition);
1054         if (empty($contact)) {
1055                 $pcid = tumblr_insert_contact($blog, 0);
1056         } else {
1057                 $pcid = $contact['id'];
1058         }
1059
1060         tumblr_update_contact($blog, $uid, $cid, $pcid);
1061
1062         return Contact::getById($cid);
1063 }
1064
1065 /**
1066  * Create a new contact
1067  *
1068  * @param stdClass $blog
1069  * @param integer $uid
1070  * @return void
1071  */
1072 function tumblr_insert_contact(stdClass $blog, int $uid)
1073 {
1074         $baseurl = 'https://tumblr.com';
1075         $url     = $baseurl . '/' . $blog->name;
1076
1077         $fields = [
1078                 'uid'      => $uid,
1079                 'network'  => Protocol::TUMBLR,
1080                 'poll'     => 'tumblr::' . $blog->uuid,
1081                 'baseurl'  => $baseurl,
1082                 'priority' => 1,
1083                 'writable' => true,
1084                 'blocked'  => false,
1085                 'readonly' => false,
1086                 'pending'  => false,
1087                 'url'      => $url,
1088                 'nurl'     => Strings::normaliseLink($url),
1089                 'alias'    => $blog->url,
1090                 'name'     => $blog->title ?: $blog->name,
1091                 'nick'     => $blog->name,
1092                 'addr'     => $blog->name . '@tumblr.com',
1093                 'about'    => HTML::toBBCode($blog->description),
1094                 'updated'  => date(DateTimeFormat::MYSQL, $blog->updated)
1095         ];
1096         return Contact::insert($fields);
1097 }
1098
1099 /**
1100  * Updates the given contact for the given user and proviced contact ids
1101  *
1102  * @param stdClass $blog
1103  * @param integer $uid
1104  * @param integer $cid
1105  * @param integer $pcid
1106  * @return void
1107  */
1108 function tumblr_update_contact(stdClass $blog, int $uid, int $cid, int $pcid)
1109 {
1110         $info = tumblr_get($uid, 'blog/' . $blog->uuid . '/info');
1111         if ($info->meta->status > 399) {
1112                 Logger::notice('Error fetching dashboard', ['meta' => $info->meta, 'response' => $info->response, 'errors' => $info->errors]);
1113                 return;
1114         }
1115
1116         $avatar = $info->response->blog->avatar;
1117         if (!empty($avatar)) {
1118                 Contact::updateAvatar($cid, $avatar[0]->url);
1119         }
1120
1121         $baseurl = 'https://tumblr.com';
1122         $url     = $baseurl . '/' . $info->response->blog->name;
1123
1124         if ($info->response->blog->followed && $info->response->blog->subscribed) {
1125                 $rel = Contact::FRIEND;
1126         } elseif ($info->response->blog->followed && !$info->response->blog->subscribed) {
1127                 $rel = Contact::SHARING;
1128         } elseif (!$info->response->blog->followed && $info->response->blog->subscribed) {
1129                 $rel = Contact::FOLLOWER;
1130         } else {
1131                 $rel = Contact::NOTHING;
1132         }
1133
1134         $uri_id = ItemURI::getIdByURI($url);
1135         $fields = [
1136                 'url'     => $url,
1137                 'nurl'    => Strings::normaliseLink($url),
1138                 'uri-id'  => $uri_id,
1139                 'alias'   => $info->response->blog->url,
1140                 'name'    => $info->response->blog->title ?: $info->response->blog->name,
1141                 'nick'    => $info->response->blog->name,
1142                 'addr'    => $info->response->blog->name . '@tumblr.com',
1143                 'about'   => HTML::toBBCode($info->response->blog->description),
1144                 'updated' => date(DateTimeFormat::MYSQL, $info->response->blog->updated),
1145                 'header'  => $info->response->blog->theme->header_image_focused,
1146                 'rel'     => $rel,
1147         ];
1148
1149         Contact::update($fields, ['id' => $cid]);
1150
1151         $fields['rel'] = Contact::NOTHING;
1152         Contact::update($fields, ['id' => $pcid]);
1153 }
1154
1155 /**
1156  * Get the default page for posting. Detects the value if not provided or has got a bad value.
1157  *
1158  * @param integer $uid
1159  * @param array $blogs
1160  * @return string
1161  */
1162 function tumblr_get_page(int $uid, array $blogs = []): string
1163 {
1164         $page = DI::pConfig()->get($uid, 'tumblr', 'page');
1165
1166         if (!empty($page) && (strpos($page, '/') === false)) {
1167                 return $page;
1168         }
1169
1170         if (empty($blogs)) {
1171                 $blogs = tumblr_get_blogs($uid);
1172         }
1173
1174         if (!empty($blogs)) {
1175                 $page = array_key_first($blogs);
1176                 DI::pConfig()->set($uid, 'tumblr', 'page', $page);
1177                 return $page;
1178         }
1179
1180         return '';
1181 }
1182
1183 /**
1184  * Get an array of blogs for the given user
1185  *
1186  * @param integer $uid
1187  * @return array
1188  */
1189 function tumblr_get_blogs(int $uid): array
1190 {
1191         $userinfo = tumblr_get($uid, 'user/info');
1192         if ($userinfo->meta->status > 299) {
1193                 Logger::notice('Error fetching blogs', ['meta' => $userinfo->meta, 'response' => $userinfo->response, 'errors' => $userinfo->errors]);
1194                 return [];
1195         }
1196
1197         $blogs = [];
1198         foreach ($userinfo->response->user->blogs as $blog) {
1199                 $blogs[$blog->uuid] = $blog->name;
1200         }
1201         return $blogs;
1202 }
1203
1204 function tumblr_enabled_for_user(int $uid) 
1205 {
1206         return !empty($uid) && !empty(DI::pConfig()->get($uid, 'tumblr', 'access_token')) &&
1207                 !empty(DI::pConfig()->get($uid, 'tumblr', 'refresh_token')) &&
1208                 !empty(DI::config()->get('tumblr', 'consumer_key')) &&
1209                 !empty(DI::config()->get('tumblr', 'consumer_secret'));
1210 }
1211
1212 /**
1213  * Get a contact array from a Tumblr url
1214  *
1215  * @param string $url
1216  * @return array
1217  */
1218 function tumblr_get_contact_by_url(string $url): array
1219 {
1220         $consumer_key = DI::config()->get('tumblr', 'consumer_key');
1221         if (empty($consumer_key)) {
1222                 return [];
1223         }
1224
1225         if (!preg_match('#^https?://tumblr.com/(.+)#', $url, $matches) && !preg_match('#^https?://www\.tumblr.com/(.+)#', $url, $matches) && !preg_match('#^https?://(.+)\.tumblr.com#', $url, $matches)) {
1226                 try {
1227                         $curlResult = DI::httpClient()->get($url);
1228                 } catch (\Exception $e) {
1229                         return [];
1230                 }
1231                 $html = $curlResult->getBody();
1232                 if (empty($html)) {
1233                         return [];
1234                 }
1235                 $doc = new DOMDocument();
1236                 @$doc->loadHTML($html);
1237                 $xpath = new DomXPath($doc);
1238                 $body = $xpath->query('body');
1239                 $attributes = tumblr_get_attributes($body->item(0));
1240                 $blog = $attributes['data-urlencoded-name'] ?? '';
1241         } else {
1242                 $blogs = explode('/', $matches[1]);
1243                 $blog = $blogs[0] ?? '';
1244         }
1245
1246         if (empty($blog)) {
1247                 return [];
1248         }
1249
1250         Logger::debug('Update Tumblr blog data', ['url' => $url]);
1251
1252         $curlResult = DI::httpClient()->get('https://api.tumblr.com/v2/blog/' . $blog . '/info?api_key=' . $consumer_key);
1253         $body = $curlResult->getBody();
1254         $data = json_decode($body);
1255         if (empty($data)) {
1256                 return [];
1257         }
1258
1259         $baseurl = 'https://tumblr.com';
1260         $url     = $baseurl . '/' . $data->response->blog->name;
1261
1262         return [
1263                 'url'      => $url,
1264                 'nurl'     => Strings::normaliseLink($url),
1265                 'addr'     => $data->response->blog->name . '@tumblr.com',
1266                 'alias'    => $data->response->blog->url,
1267                 'batch'    => '',
1268                 'notify'   => '',
1269                 'poll'     => 'tumblr::' . $data->response->blog->uuid,
1270                 'poco'     => '',
1271                 'name'     => $data->response->blog->title ?: $data->response->blog->name,
1272                 'nick'     => $data->response->blog->name,
1273                 'network'  => Protocol::TUMBLR,
1274                 'baseurl'  => $baseurl,
1275                 'pubkey'   => '',
1276                 'priority' => 0,
1277                 'guid'     => $data->response->blog->uuid,
1278                 'about'    => HTML::toBBCode($data->response->blog->description),
1279         'photo'    => $data->response->blog->avatar[0]->url,
1280         'header'   => $data->response->blog->theme->header_image_focused,
1281         ];
1282 }
1283
1284 /**
1285  * Perform an OAuth2 GET request
1286  *
1287  * @param integer $uid
1288  * @param string $url
1289  * @param array $parameters
1290  * @return stdClass
1291  */
1292 function tumblr_get(int $uid, string $url, array $parameters = []): stdClass
1293 {
1294         $url = 'https://api.tumblr.com/v2/' . $url;
1295
1296         if (!empty($parameters)) {
1297                 $url .= '?' . http_build_query($parameters);
1298         }
1299
1300         $curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . tumblr_get_token($uid)]]]);
1301         return tumblr_format_result($curlResult);
1302 }
1303
1304 /**
1305  * Perform an OAuth2 POST request
1306  *
1307  * @param integer $uid
1308  * @param string $url
1309  * @param array $parameters
1310  * @return stdClass
1311  */
1312 function tumblr_post(int $uid, string $url, array $parameters): stdClass
1313 {
1314         $url = 'https://api.tumblr.com/v2/' . $url;
1315
1316         $curlResult = DI::httpClient()->post($url, $parameters, ['Authorization' => ['Bearer ' . tumblr_get_token($uid)]]);
1317         return tumblr_format_result($curlResult);
1318 }
1319
1320 /**
1321  * Perform an OAuth2 DELETE request
1322  *
1323  * @param integer $uid
1324  * @param string $url
1325  * @param array $parameters
1326  * @return stdClass
1327  */
1328 function tumblr_delete(int $uid, string $url, array $parameters): stdClass
1329 {
1330         $url = 'https://api.tumblr.com/v2/' . $url;
1331
1332         $opts = [
1333                 HttpClientOptions::HEADERS     => ['Authorization' => ['Bearer ' . tumblr_get_token($uid)]],
1334                 HttpClientOptions::FORM_PARAMS => $parameters
1335         ];
1336
1337         $curlResult = DI::httpClient()->request('delete', $url, $opts);
1338         return tumblr_format_result($curlResult);
1339 }
1340
1341 /**
1342  * Format the get/post result value
1343  *
1344  * @param ICanHandleHttpResponses $curlResult
1345  * @return stdClass
1346  */
1347 function tumblr_format_result(ICanHandleHttpResponses $curlResult): stdClass
1348 {
1349         $result = json_decode($curlResult->getBody());
1350         if (empty($result) || empty($result->meta)) {
1351                 $result               = new stdClass;
1352                 $result->meta         = new stdClass;
1353                 $result->meta->status = 500;
1354                 $result->meta->msg    = '';
1355                 $result->response     = [];
1356                 $result->errors       = [];
1357         }
1358         return $result;
1359 }
1360
1361 /**
1362  * Fetch the OAuth token, update it if needed
1363  *
1364  * @param integer $uid
1365  * @param string $code
1366  * @return string
1367  */
1368 function tumblr_get_token(int $uid, string $code = ''): string
1369 {
1370         $access_token  = DI::pConfig()->get($uid, 'tumblr', 'access_token');
1371         $expires_at    = DI::pConfig()->get($uid, 'tumblr', 'expires_at');
1372         $refresh_token = DI::pConfig()->get($uid, 'tumblr', 'refresh_token');
1373
1374         if (empty($code) && !empty($access_token) && ($expires_at > (time()))) {
1375                 Logger::debug('Got token', ['uid' => $uid, 'expires_at' => date('c', $expires_at)]);
1376                 return $access_token;
1377         }
1378
1379         $consumer_key    = DI::config()->get('tumblr', 'consumer_key');
1380         $consumer_secret = DI::config()->get('tumblr', 'consumer_secret');
1381
1382         $parameters = ['client_id' => $consumer_key, 'client_secret' => $consumer_secret];
1383
1384         if (empty($refresh_token) && empty($code)) {
1385                 $result = tumblr_exchange_token($uid);
1386                 if (empty($result->refresh_token)) {
1387                         Logger::info('Invalid result while exchanging token', ['uid' => $uid]);
1388                         return '';
1389                 }
1390                 $expires_at = time() + $result->expires_in;
1391                 Logger::debug('Updated token from OAuth1 to OAuth2', ['uid' => $uid, 'expires_at' => date('c', $expires_at)]);
1392         } else {
1393                 if (!empty($code)) {
1394                         $parameters['code']       = $code;
1395                         $parameters['grant_type'] = 'authorization_code';
1396                 } else {
1397                         $parameters['refresh_token'] = $refresh_token;
1398                         $parameters['grant_type']    = 'refresh_token';
1399                 }
1400
1401                 $curlResult = DI::httpClient()->post('https://api.tumblr.com/v2/oauth2/token', $parameters);
1402                 if (!$curlResult->isSuccess()) {
1403                         Logger::info('Error fetching token', ['uid' => $uid, 'code' => $code, 'result' => $curlResult->getBody(), 'parameters' => $parameters]);
1404                         return '';
1405                 }
1406         
1407                 $result = json_decode($curlResult->getBody());
1408                 if (empty($result)) {
1409                         Logger::info('Invalid result when updating token', ['uid' => $uid]);
1410                         return '';
1411                 }
1412         
1413                 $expires_at = time() + $result->expires_in;
1414                 Logger::debug('Renewed token', ['uid' => $uid, 'expires_at' => date('c', $expires_at)]);
1415         }
1416
1417         DI::pConfig()->set($uid, 'tumblr', 'access_token', $result->access_token);
1418         DI::pConfig()->set($uid, 'tumblr', 'expires_at', $expires_at);
1419         DI::pConfig()->set($uid, 'tumblr', 'refresh_token', $result->refresh_token);
1420
1421         return $result->access_token;
1422 }
1423
1424 /**
1425  * Create an OAuth2 token out of an OAuth1 token
1426  *
1427  * @param int $uid
1428  * @return stdClass
1429  */
1430 function tumblr_exchange_token(int $uid): stdClass
1431 {
1432         $oauth_token        = DI::pConfig()->get($uid, 'tumblr', 'oauth_token');
1433         $oauth_token_secret = DI::pConfig()->get($uid, 'tumblr', 'oauth_token_secret');
1434
1435         $consumer_key    = DI::config()->get('tumblr', 'consumer_key');
1436         $consumer_secret = DI::config()->get('tumblr', 'consumer_secret');
1437
1438         $stack = HandlerStack::create();
1439
1440         $middleware = new Oauth1([
1441                 'consumer_key'    => $consumer_key,
1442                 'consumer_secret' => $consumer_secret,
1443                 'token'           => $oauth_token,
1444                 'token_secret'    => $oauth_token_secret
1445         ]);
1446
1447         $stack->push($middleware);
1448
1449         try {
1450                 $client = new Client([
1451                         'base_uri' => 'https://api.tumblr.com/v2/',
1452                         'handler' => $stack
1453                 ]);
1454
1455                 $response = $client->post('oauth2/exchange', ['auth' => 'oauth']);
1456                 return json_decode($response->getBody()->getContents());
1457         } catch (RequestException $exception) {
1458                 Logger::notice('Exchange failed', ['code' => $exception->getCode(), 'message' => $exception->getMessage()]);
1459                 return new stdClass;
1460         }
1461 }