]> git.mxchange.org Git - friendica-addons.git/blob - tumblr/tumblr.php
Merge pull request 'HU and IT translation updates' (#1371) from tobias/friendica...
[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 require_once __DIR__ . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'tumblroauth.php';
11
12 use Friendica\Content\Text\BBCode;
13 use Friendica\Content\Text\NPF;
14 use Friendica\Core\Hook;
15 use Friendica\Core\Logger;
16 use Friendica\Core\Renderer;
17 use Friendica\Core\System;
18 use Friendica\DI;
19 use Friendica\Model\Item;
20 use Friendica\Model\Photo;
21 use Friendica\Model\Post;
22 use Friendica\Model\Tag;
23 use Friendica\Util\DateTimeFormat;
24 use Friendica\Util\Network;
25 use GuzzleHttp\Client;
26 use GuzzleHttp\Exception\RequestException;
27 use GuzzleHttp\HandlerStack;
28 use GuzzleHttp\Subscriber\Oauth\Oauth1;
29
30 function tumblr_install()
31 {
32         Hook::register('hook_fork',               'addon/tumblr/tumblr.php', 'tumblr_hook_fork');
33         Hook::register('post_local',              'addon/tumblr/tumblr.php', 'tumblr_post_local');
34         Hook::register('notifier_normal',         'addon/tumblr/tumblr.php', 'tumblr_send');
35         Hook::register('jot_networks',            'addon/tumblr/tumblr.php', 'tumblr_jot_nets');
36         Hook::register('connector_settings',      'addon/tumblr/tumblr.php', 'tumblr_settings');
37         Hook::register('connector_settings_post', 'addon/tumblr/tumblr.php', 'tumblr_settings_post');
38 }
39
40 /**
41  * This is a statement rather than an actual function definition. The simple
42  * existence of this method is checked to figure out if the addon offers a
43  * module.
44  */
45 function tumblr_module()
46 {
47 }
48
49 function tumblr_content()
50 {
51         if (!DI::userSession()->getLocalUserId()) {
52                 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
53                 return '';
54         }
55
56         if (isset(DI::args()->getArgv()[1])) {
57                 switch (DI::args()->getArgv()[1]) {
58                         case 'connect':
59                                 $o = tumblr_connect();
60                                 break;
61
62                         case 'callback':
63                                 $o = tumblr_callback();
64                                 break;
65
66                         default:
67                                 $o = print_r(DI::args()->getArgv(), true);
68                                 break;
69                 }
70         } else {
71                 $o = tumblr_connect();
72         }
73
74         return $o;
75 }
76
77 function tumblr_addon_admin(string &$o)
78 {
79         $t = Renderer::getMarkupTemplate('admin.tpl', 'addon/tumblr/');
80
81         $o = Renderer::replaceMacros($t, [
82                 '$submit' => DI::l10n()->t('Save Settings'),
83                 // name, label, value, help, [extra values]
84                 '$consumer_key' => ['consumer_key', DI::l10n()->t('Consumer Key'), DI::config()->get('tumblr', 'consumer_key'), ''],
85                 '$consumer_secret' => ['consumer_secret', DI::l10n()->t('Consumer Secret'), DI::config()->get('tumblr', 'consumer_secret'), ''],
86         ]);
87 }
88
89 function tumblr_addon_admin_post()
90 {
91         DI::config()->set('tumblr', 'consumer_key', trim($_POST['consumer_key'] ?? ''));
92         DI::config()->set('tumblr', 'consumer_secret', trim($_POST['consumer_secret'] ?? ''));
93 }
94
95 function tumblr_connect()
96 {
97         // Start a session.  This is necessary to hold on to  a few keys the callback script will also need
98         session_start();
99
100         // Define the needed keys
101         $consumer_key = DI::config()->get('tumblr', 'consumer_key');
102         $consumer_secret = DI::config()->get('tumblr', 'consumer_secret');
103
104         // The callback URL is the script that gets called after the user authenticates with tumblr
105         // In this example, it would be the included callback.php
106         $callback_url = DI::baseUrl() . '/tumblr/callback';
107
108         // Let's begin.  First we need a Request Token.  The request token is required to send the user
109         // to Tumblr's login page.
110
111         // Create a new instance of the TumblrOAuth library.  For this step, all we need to give the library is our
112         // Consumer Key and Consumer Secret
113         $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret);
114
115         // Ask Tumblr for a Request Token.  Specify the Callback URL here too (although this should be optional)
116         $request_token = $tum_oauth->getRequestToken($callback_url);
117
118         // Store the request token and Request Token Secret as out callback.php script will need this
119         DI::session()->set('request_token', $request_token['oauth_token']);
120         DI::session()->set('request_token_secret', $request_token['oauth_token_secret']);
121
122         // Check the HTTP Code.  It should be a 200 (OK), if it's anything else then something didn't work.
123         switch ($tum_oauth->http_code) {
124                 case 200:
125                         // Ask Tumblr to give us a special address to their login page
126                         $url = $tum_oauth->getAuthorizeURL($request_token['oauth_token']);
127
128                         // Redirect the user to the login URL given to us by Tumblr
129                         System::externalRedirect($url);
130
131                         /*
132                          * That's it for our side.  The user is sent to a Tumblr Login page and
133                          * asked to authroize our app.  After that, Tumblr sends the user back to
134                          * our Callback URL (callback.php) along with some information we need to get
135                          * an access token.
136                          */
137                         break;
138
139                 default:
140                         // Give an error message
141                         $o = 'Could not connect to Tumblr. Refresh the page or try again later.';
142         }
143
144         return $o;
145 }
146
147 function tumblr_callback()
148 {
149         // Start a session, load the library
150         session_start();
151
152         // Define the needed keys
153         $consumer_key    = DI::config()->get('tumblr', 'consumer_key');
154         $consumer_secret = DI::config()->get('tumblr', 'consumer_secret');
155
156         // Once the user approves your app at Tumblr, they are sent back to this script.
157         // This script is passed two parameters in the URL, oauth_token (our Request Token)
158         // and oauth_verifier (Key that we need to get Access Token).
159         // We'll also need out Request Token Secret, which we stored in a session.
160
161         // Create instance of TumblrOAuth.
162         // It'll need our Consumer Key and Secret as well as our Request Token and Secret
163         $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret);
164
165         // Ok, let's get an Access Token. We'll need to pass along our oauth_verifier which was given to us in the URL.
166         $access_token = $tum_oauth->getAccessToken($_REQUEST['oauth_verifier'], DI::session()->get('request_token'), DI::session()->get('request_token_secret'));
167
168         // We're done with the Request Token and Secret so let's remove those.
169         DI::session()->remove('request_token');
170         DI::session()->remove('request_token_secret');
171
172         // Make sure nothing went wrong.
173         if (200 == $tum_oauth->http_code) {
174                 // good to go
175         } else {
176                 return 'Unable to authenticate';
177         }
178
179         // What's next?  Now that we have an Access Token and Secret, we can make an API call.
180         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'oauth_token', $access_token['oauth_token']);
181         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'oauth_token_secret', $access_token['oauth_token_secret']);
182
183         DI::baseUrl()->redirect('settings/connectors/tumblr');
184 }
185
186 function tumblr_jot_nets(array &$jotnets_fields)
187 {
188         if (!DI::userSession()->getLocalUserId()) {
189                 return;
190         }
191
192         if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post')) {
193                 $jotnets_fields[] = [
194                         'type' => 'checkbox',
195                         'field' => [
196                                 'tumblr_enable',
197                                 DI::l10n()->t('Post to Tumblr'),
198                                 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post_by_default')
199                         ]
200                 ];
201         }
202 }
203
204 function tumblr_settings(array &$data)
205 {
206         if (!DI::userSession()->getLocalUserId()) {
207                 return;
208         }
209
210         $enabled     = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post', false);
211         $def_enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post_by_default', false);
212
213         $blogs = tumblr_get_blogs(DI::userSession()->getLocalUserId());
214         if (!empty($blogs)) {
215                 $page = tumblr_get_page(DI::userSession()->getLocalUserId(), $blogs);
216         
217                 $page_select = ['tumblr_page', DI::l10n()->t('Post to page:'), $page, '', $blogs];
218         }
219
220         $t    = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/tumblr/');
221         $html = Renderer::replaceMacros($t, [
222                 '$l10n' => [
223                         'connect'   => DI::l10n()->t('(Re-)Authenticate your tumblr page'),
224                         'noconnect' => DI::l10n()->t('You are not authenticated to tumblr'),
225                 ],
226
227                 '$authenticate_url' => DI::baseUrl() . '/tumblr/connect',
228
229                 '$enable'      => ['tumblr', DI::l10n()->t('Enable Tumblr Post Addon'), $enabled],
230                 '$bydefault'   => ['tumblr_bydefault', DI::l10n()->t('Post to Tumblr by default'), $def_enabled],
231                 '$page_select' => $page_select ?? '',
232         ]);
233
234         $data = [
235                 'connector' => 'tumblr',
236                 'title'     => DI::l10n()->t('Tumblr Export'),
237                 'image'     => 'images/tumblr.png',
238                 'enabled'   => $enabled,
239                 'html'      => $html,
240         ];
241 }
242
243 function tumblr_settings_post(array &$b)
244 {
245         if (!empty($_POST['tumblr-submit'])) {
246                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'post',            intval($_POST['tumblr']));
247                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'page',            $_POST['tumblr_page']);
248                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'tumblr', 'post_by_default', intval($_POST['tumblr_bydefault']));
249         }
250 }
251
252 function tumblr_hook_fork(array &$b)
253 {
254         if ($b['name'] != 'notifier_normal') {
255                 return;
256         }
257
258         $post = $b['data'];
259
260         if (
261                 $post['deleted'] || $post['private'] || ($post['created'] !== $post['edited']) ||
262                 !strstr($post['postopts'] ?? '', 'tumblr') || ($post['parent'] != $post['id'])
263         ) {
264                 $b['execute'] = false;
265                 return;
266         }
267 }
268
269 function tumblr_post_local(array &$b)
270 {
271         // This can probably be changed to allow editing by pointing to a different API endpoint
272
273         if ($b['edit']) {
274                 return;
275         }
276
277         if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
278                 return;
279         }
280
281         if ($b['private'] || $b['parent']) {
282                 return;
283         }
284
285         $tmbl_post   = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post'));
286
287         $tmbl_enable = (($tmbl_post && !empty($_REQUEST['tumblr_enable'])) ? intval($_REQUEST['tumblr_enable']) : 0);
288
289         if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'tumblr', 'post_by_default'))) {
290                 $tmbl_enable = 1;
291         }
292
293         if (!$tmbl_enable) {
294                 return;
295         }
296
297         if (strlen($b['postopts'])) {
298                 $b['postopts'] .= ',';
299         }
300
301         $b['postopts'] .= 'tumblr';
302 }
303
304 function tumblr_send(array &$b)
305 {
306         if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) {
307                 return;
308         }
309
310         if (!strstr($b['postopts'], 'tumblr')) {
311                 return;
312         }
313
314         if ($b['gravity'] != Item::GRAVITY_PARENT) {
315                 return;
316         }
317
318         if (tumblr_send_npf($b)) {
319                 return;
320         }
321
322         $connection = tumblr_connection($b['uid']);
323         if (empty($connection)) {
324                 return;
325         }
326
327         $b['body'] = BBCode::removeAttachment($b['body']);
328
329         $title = trim($b['title']);
330
331         $media = Post\Media::getByURIId($b['uri-id'], [Post\Media::HTML, Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE]);
332
333         $photo = array_search(Post\Media::IMAGE, array_column($media, 'type'));
334         $link  = array_search(Post\Media::HTML, array_column($media, 'type'));
335         $audio = array_search(Post\Media::AUDIO, array_column($media, 'type'));
336         $video = array_search(Post\Media::VIDEO, array_column($media, 'type'));
337
338         $params = [
339                 'state'  => 'published',
340                 'tags'   => implode(',', array_column(Tag::getByURIId($b['uri-id']), 'name')),
341                 'tweet'  => 'off',
342                 'format' => 'html',
343         ];
344
345         $body = BBCode::removeShareInformation($b['body']);
346         $body = Post\Media::removeFromEndOfBody($body);
347
348         if ($photo !== false) {
349                 $params['type'] = 'photo';
350                 $params['caption'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS);
351                 $params['data'] = [];
352                 foreach ($media as $photo) {
353                         if ($photo['type'] == Post\Media::IMAGE) {
354                                 if (Network::isLocalLink($photo['url']) && ($data = Photo::getResourceData($photo['url']))) {
355                                         $photo = Photo::selectFirst([], ["`resource-id` = ? AND `scale` > ?", $data['guid'], 0]);
356                                         if (!empty($photo)) {
357                                                 $params['data'][] = Photo::getImageDataForPhoto($photo);
358                                         }
359                                 }
360                         }
361                 }
362         } elseif ($link !== false) {
363                 $params['type']        = 'link';
364                 $params['title']       = $media[$link]['name'];
365                 $params['url']         = $media[$link]['url'];
366                 $params['description'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS);
367
368                 if (!empty($media[$link]['preview'])) {
369                         $params['thumbnail'] = $media[$link]['preview'];
370                 }
371                 if (!empty($media[$link]['description'])) {
372                         $params['excerpt'] = $media[$link]['description'];
373                 }
374                 if (!empty($media[$link]['author-name'])) {
375                         $params['author'] = $media[$link]['author-name'];
376                 }
377         } elseif ($audio !== false) {
378                 $params['type']         = 'audio';
379                 $params['external_url'] = $media[$audio]['url'];
380                 $params['caption']      = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS);
381         } elseif ($video !== false) {
382                 $params['type']    = 'video';
383                 $params['embed']   = $media[$video]['url'];
384                 $params['caption'] = BBCode::convertForUriId($b['uri-id'], $body, BBCode::CONNECTORS);
385         } else {
386                 $params['type']  = 'text';
387                 $params['title'] = $title;
388                 $params['body']  = BBCode::convertForUriId($b['uri-id'], $b['body'], BBCode::CONNECTORS);
389         }
390
391         if (isset($params['caption']) && (trim($title) != '')) {
392                 $params['caption'] = '<h1>' . $title . '</h1>' .
393                         '<p>' . $params['caption'] . '</p>';
394         }
395
396         $page = tumblr_get_page($b['uid']);
397
398         $result = tumblr_post($connection, 'blog/' . $page . '/post', $params);
399
400         if ($result['success']) {
401                 Logger::info('success', ['blog' => $page, 'params' => $params]);
402                 return true;
403         } else {
404                 Logger::notice('error', ['blog' => $page, 'params' => $params, 'result' => $result['data']]);
405                 return false;
406         }
407 }
408
409 function tumblr_send_npf(array $post): bool
410 {
411         $page = tumblr_get_page($post['uid']);
412
413         $connection = tumblr_connection($post['uid']);
414         if (empty($page)) {
415                 Logger::notice('Missing page, post will not be send to Tumblr.', ['uid' => $post['uid'], 'page' => $page, 'id' => $post['id']]);
416                 // "true" is returned, since the legacy function will fail as well.
417                 return true;
418         }
419         
420         $post['body'] = Post\Media::addAttachmentsToBody($post['uri-id'], $post['body']);
421         if (!empty($post['title'])) {
422                 $post['body'] = '[h1]' . $post['title'] . "[/h1]\n" . $post['body'];
423         }
424
425         $params = [
426                 'content'                => NPF::fromBBCode($post['body'], $post['uri-id']),
427                 'state'                  => 'published',
428                 'date'                   => DateTimeFormat::utc($post['created'], DateTimeFormat::ATOM),
429                 'tags'                   => implode(',', array_column(Tag::getByURIId($post['uri-id']), 'name')),
430                 'is_private'             => false,
431                 'interactability_reblog' => 'everyone'
432         ];
433
434         $result = tumblr_post($connection, 'blog/' . $page . '/posts', $params);
435
436         if ($result['success']) {
437                 Logger::info('success', ['blog' => $page, 'params' => $params]);
438                 return true;
439         } else {
440                 Logger::notice('error', ['blog' => $page, 'params' => $params, 'result' => $result['data']]);
441                 return false;
442         }
443 }
444
445 function tumblr_connection(int $uid): ?GuzzleHttp\Client
446 {
447         $oauth_token        = DI::pConfig()->get($uid, 'tumblr', 'oauth_token');
448         $oauth_token_secret = DI::pConfig()->get($uid, 'tumblr', 'oauth_token_secret');
449
450         $consumer_key    = DI::config()->get('tumblr', 'consumer_key');
451         $consumer_secret = DI::config()->get('tumblr', 'consumer_secret');
452
453         if (!$consumer_key || !$consumer_secret || !$oauth_token || !$oauth_token_secret) {
454                 Logger::notice('Missing data, connection is not established', ['uid' => $uid]);
455                 return null;
456         }
457         return tumblr_client($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
458 }
459
460 function tumblr_client(string $consumer_key, string $consumer_secret, string $oauth_token, string $oauth_token_secret): GuzzleHttp\Client
461 {
462         $stack = HandlerStack::create();
463
464         $middleware = new Oauth1([
465                 'consumer_key'    => $consumer_key,
466                 'consumer_secret' => $consumer_secret,
467                 'token'           => $oauth_token,
468                 'token_secret'    => $oauth_token_secret
469         ]);
470         $stack->push($middleware);
471         
472         return new Client([
473                 'base_uri' => 'https://api.tumblr.com/v2/',
474                 'handler' => $stack
475         ]);
476 }
477
478 function tumblr_get_page(int $uid, array $blogs = [])
479 {
480         $page = DI::pConfig()->get($uid, 'tumblr', 'page');
481
482         if (!empty($page) && (strpos($page, '/') === false)) {
483                 return $page;
484         }
485
486         if (empty($blogs)) {
487                 $blogs = tumblr_get_blogs($uid);
488         }
489
490         if (!empty($blogs)) {
491                 $page = array_key_first($blogs);
492                 DI::pConfig()->set($uid, 'tumblr', 'page', $page);
493                 return $page;
494         }
495
496         return '';
497 }
498
499 function tumblr_get_blogs(int $uid)
500 {
501         $connection = tumblr_connection($uid);
502         if (empty($connection)) {
503                 return [];
504         }
505
506         $userinfo = tumblr_get($connection, 'user/info');
507         if (empty($userinfo['success'])) {
508                 return [];
509         }
510
511         $blogs = [];
512         foreach ($userinfo['data']->response->user->blogs as $blog) {
513                 $blogs[$blog->uuid] = $blog->name;
514         }
515         return $blogs;
516 }
517
518 function tumblr_get($connection, string $url)
519 {
520         try {
521                 $res = $connection->get($url, ['auth' => 'oauth']);
522
523                 $success = true;
524                 $data    = json_decode($res->getBody()->getContents());
525         } catch (RequestException $exception) {
526                 $success = false;
527                 $data    = [];
528                 Logger::notice('Request failed', ['code' => $exception->getCode(), 'message' => $exception->getMessage()]);
529         }
530         return ['success' => $success, 'data' => $data];
531 }
532
533 function tumblr_post($connection, string $url, array $parameter)
534 {
535         try {
536                 $res = $connection->post($url, ['auth' => 'oauth', 'json' => $parameter]);
537
538                 $success = true;
539                 $data    = json_decode($res->getBody()->getContents());
540         } catch (RequestException $exception) {
541                 $success = false;
542                 $data    = json_decode($exception->getResponse()->getBody()->getContents());
543                 Logger::notice('Post failed', ['code' => $exception->getCode(), 'message' => $exception->getMessage()]);
544         }
545         return ['success' => $success, 'data' => $data];
546 }