77a9a99fc3a87cc4ea44533a4fe1ea8cbf01f2a0
[friendica-addons.git/.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\App;
13 use Friendica\Content\Text\BBCode;
14 use Friendica\Core\Hook;
15 use Friendica\Core\Logger;
16 use Friendica\Core\Renderer;
17 use Friendica\Database\DBA;
18 use Friendica\DI;
19 use Friendica\Model\Tag;
20 use Friendica\Util\Strings;
21
22 function tumblr_install()
23 {
24         Hook::register('hook_fork',               'addon/tumblr/tumblr.php', 'tumblr_hook_fork');
25         Hook::register('post_local',              'addon/tumblr/tumblr.php', 'tumblr_post_local');
26         Hook::register('notifier_normal',         'addon/tumblr/tumblr.php', 'tumblr_send');
27         Hook::register('jot_networks',            'addon/tumblr/tumblr.php', 'tumblr_jot_nets');
28         Hook::register('connector_settings',      'addon/tumblr/tumblr.php', 'tumblr_settings');
29         Hook::register('connector_settings_post', 'addon/tumblr/tumblr.php', 'tumblr_settings_post');
30 }
31
32 function tumblr_uninstall()
33 {
34         Hook::unregister('hook_fork',               'addon/tumblr/tumblr.php', 'tumblr_hook_fork');
35         Hook::unregister('post_local',              'addon/tumblr/tumblr.php', 'tumblr_post_local');
36         Hook::unregister('notifier_normal',         'addon/tumblr/tumblr.php', 'tumblr_send');
37         Hook::unregister('jot_networks',            'addon/tumblr/tumblr.php', 'tumblr_jot_nets');
38         Hook::unregister('connector_settings',      'addon/tumblr/tumblr.php', 'tumblr_settings');
39         Hook::unregister('connector_settings_post', 'addon/tumblr/tumblr.php', 'tumblr_settings_post');
40 }
41
42 function tumblr_module()
43 {
44 }
45
46 function tumblr_content(App $a)
47 {
48         if (! local_user()) {
49                 notice(DI::l10n()->t('Permission denied.') . EOL);
50                 return '';
51         }
52
53         if (isset($a->argv[1])) {
54                 switch ($a->argv[1]) {
55                         case "connect":
56                                 $o = tumblr_connect($a);
57                                 break;
58
59                         case "callback":
60                                 $o = tumblr_callback($a);
61                                 break;
62
63                         default:
64                                 $o = print_r($a->argv, true);
65                                 break;
66                 }
67         } else {
68                 $o = tumblr_connect($a);
69         }
70
71         return $o;
72 }
73
74 function tumblr_addon_admin(App $a, &$o)
75 {
76         $t = Renderer::getMarkupTemplate( "admin.tpl", "addon/tumblr/" );
77
78         $o = Renderer::replaceMacros($t, [
79                 '$submit' => DI::l10n()->t('Save Settings'),
80                 // name, label, value, help, [extra values]
81                 '$consumer_key' => ['consumer_key', DI::l10n()->t('Consumer Key'),  DI::config()->get('tumblr', 'consumer_key' ), ''],
82                 '$consumer_secret' => ['consumer_secret', DI::l10n()->t('Consumer Secret'),  DI::config()->get('tumblr', 'consumer_secret' ), ''],
83         ]);
84 }
85
86 function tumblr_addon_admin_post(App $a)
87 {
88         $consumer_key    =       (!empty($_POST['consumer_key'])      ? Strings::escapeTags(trim($_POST['consumer_key']))   : '');
89         $consumer_secret =       (!empty($_POST['consumer_secret'])   ? Strings::escapeTags(trim($_POST['consumer_secret'])): '');
90
91         DI::config()->set('tumblr', 'consumer_key',$consumer_key);
92         DI::config()->set('tumblr', 'consumer_secret',$consumer_secret);
93
94         info(DI::l10n()->t('Settings updated.'). EOL);
95 }
96
97 function tumblr_connect(App $a)
98 {
99         // Start a session.  This is necessary to hold on to  a few keys the callback script will also need
100         session_start();
101
102         // Include the TumblrOAuth library
103         //require_once('addon/tumblr/tumblroauth/tumblroauth.php');
104
105         // Define the needed keys
106         $consumer_key = DI::config()->get('tumblr', 'consumer_key');
107         $consumer_secret = DI::config()->get('tumblr', 'consumer_secret');
108
109         // The callback URL is the script that gets called after the user authenticates with tumblr
110         // In this example, it would be the included callback.php
111         $callback_url = DI::baseUrl()->get()."/tumblr/callback";
112
113         // Let's begin.  First we need a Request Token.  The request token is required to send the user
114         // to Tumblr's login page.
115
116         // Create a new instance of the TumblrOAuth library.  For this step, all we need to give the library is our
117         // Consumer Key and Consumer Secret
118         $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret);
119
120         // Ask Tumblr for a Request Token.  Specify the Callback URL here too (although this should be optional)
121         $request_token = $tum_oauth->getRequestToken($callback_url);
122
123         // Store the request token and Request Token Secret as out callback.php script will need this
124         $_SESSION['request_token'] = $token = $request_token['oauth_token'];
125         $_SESSION['request_token_secret'] = $request_token['oauth_token_secret'];
126
127         // Check the HTTP Code.  It should be a 200 (OK), if it's anything else then something didn't work.
128         switch ($tum_oauth->http_code) {
129                 case 200:
130                         // Ask Tumblr to give us a special address to their login page
131                         $url = $tum_oauth->getAuthorizeURL($token);
132
133                         // Redirect the user to the login URL given to us by Tumblr
134                         header('Location: ' . $url);
135
136                         /*
137                          * That's it for our side.  The user is sent to a Tumblr Login page and
138                          * asked to authroize our app.  After that, Tumblr sends the user back to
139                          * our Callback URL (callback.php) along with some information we need to get
140                          * an access token.
141                          */
142                         break;
143
144                 default:
145                         // Give an error message
146                         $o = 'Could not connect to Tumblr. Refresh the page or try again later.';
147         }
148
149         return $o;
150 }
151
152 function tumblr_callback(App $a)
153 {
154         // Start a session, load the library
155         session_start();
156         //require_once('addon/tumblr/tumblroauth/tumblroauth.php');
157
158         // Define the needed keys
159         $consumer_key = DI::config()->get('tumblr', 'consumer_key');
160         $consumer_secret = DI::config()->get('tumblr', 'consumer_secret');
161
162         // Once the user approves your app at Tumblr, they are sent back to this script.
163         // This script is passed two parameters in the URL, oauth_token (our Request Token)
164         // and oauth_verifier (Key that we need to get Access Token).
165         // We'll also need out Request Token Secret, which we stored in a session.
166
167         // Create instance of TumblrOAuth.
168         // It'll need our Consumer Key and Secret as well as our Request Token and Secret
169         $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $_SESSION['request_token'], $_SESSION['request_token_secret']);
170
171         // Ok, let's get an Access Token. We'll need to pass along our oauth_verifier which was given to us in the URL.
172         $access_token = $tum_oauth->getAccessToken($_REQUEST['oauth_verifier']);
173
174         // We're done with the Request Token and Secret so let's remove those.
175         unset($_SESSION['request_token']);
176         unset($_SESSION['request_token_secret']);
177
178         // Make sure nothing went wrong.
179         if (200 == $tum_oauth->http_code) {
180                 // good to go
181         } else {
182                 return 'Unable to authenticate';
183         }
184
185         // What's next?  Now that we have an Access Token and Secret, we can make an API call.
186         DI::pConfig()->set(local_user(), "tumblr", "oauth_token", $access_token['oauth_token']);
187         DI::pConfig()->set(local_user(), "tumblr", "oauth_token_secret", $access_token['oauth_token_secret']);
188
189         $o = DI::l10n()->t("You are now authenticated to tumblr.");
190         $o .= '<br /><a href="' . DI::baseUrl()->get() . '/settings/connectors">' . DI::l10n()->t("return to the connector page") . '</a>';
191
192         return $o;
193 }
194
195 function tumblr_jot_nets(App $a, array &$jotnets_fields)
196 {
197         if (! local_user()) {
198                 return;
199         }
200
201         if (DI::pConfig()->get(local_user(),'tumblr','post')) {
202                 $jotnets_fields[] = [
203                         'type' => 'checkbox',
204                         'field' => [
205                                 'tumblr_enable',
206                                 DI::l10n()->t('Post to Tumblr'),
207                                 DI::pConfig()->get(local_user(),'tumblr','post_by_default')
208                         ]
209                 ];
210         }
211 }
212
213 function tumblr_settings(App $a, &$s)
214 {
215         if (! local_user()) {
216                 return;
217         }
218
219         /* Add our stylesheet to the page so we can make our settings look nice */
220
221         DI::page()['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . DI::baseUrl()->get() . '/addon/tumblr/tumblr.css' . '" media="all" />' . "\r\n";
222
223         /* Get the current state of our config variables */
224
225         $enabled = DI::pConfig()->get(local_user(), 'tumblr', 'post');
226         $checked = (($enabled) ? ' checked="checked" ' : '');
227         $css = (($enabled) ? '' : '-disabled');
228
229         $def_enabled = DI::pConfig()->get(local_user(), 'tumblr', 'post_by_default');
230
231         $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
232
233         /* Add some HTML to the existing form */
234
235         $s .= '<span id="settings_tumblr_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_tumblr_expanded\'); openClose(\'settings_tumblr_inflated\');">';
236         $s .= '<img class="connector'.$css.'" src="images/tumblr.png" /><h3 class="connector">'. DI::l10n()->t('Tumblr Export').'</h3>';
237         $s .= '</span>';
238         $s .= '<div id="settings_tumblr_expanded" class="settings-block" style="display: none;">';
239         $s .= '<span class="fakelink" onclick="openClose(\'settings_tumblr_expanded\'); openClose(\'settings_tumblr_inflated\');">';
240         $s .= '<img class="connector'.$css.'" src="images/tumblr.png" /><h3 class="connector">'. DI::l10n()->t('Tumblr Export').'</h3>';
241         $s .= '</span>';
242
243         $s .= '<div id="tumblr-username-wrapper">';
244         $s .= '<a href="'.DI::baseUrl()->get().'/tumblr/connect">'.DI::l10n()->t("(Re-)Authenticate your tumblr page").'</a>';
245         $s .= '</div><div class="clear"></div>';
246
247         $s .= '<div id="tumblr-enable-wrapper">';
248         $s .= '<label id="tumblr-enable-label" for="tumblr-checkbox">' . DI::l10n()->t('Enable Tumblr Post Addon') . '</label>';
249         $s .= '<input type="hidden" name="tumblr" value="0"/>';
250         $s .= '<input id="tumblr-checkbox" type="checkbox" name="tumblr" value="1" ' . $checked . '/>';
251         $s .= '</div><div class="clear"></div>';
252
253         $s .= '<div id="tumblr-bydefault-wrapper">';
254         $s .= '<label id="tumblr-bydefault-label" for="tumblr-bydefault">' . DI::l10n()->t('Post to Tumblr by default') . '</label>';
255         $s .= '<input type="hidden" name="tumblr_bydefault" value="0"/>';
256         $s .= '<input id="tumblr-bydefault" type="checkbox" name="tumblr_bydefault" value="1" ' . $def_checked . '/>';
257         $s .= '</div><div class="clear"></div>';
258
259         $oauth_token = DI::pConfig()->get(local_user(), "tumblr", "oauth_token");
260         $oauth_token_secret = DI::pConfig()->get(local_user(), "tumblr", "oauth_token_secret");
261
262         $s .= '<div id="tumblr-page-wrapper">';
263
264         if (($oauth_token != "") && ($oauth_token_secret != "")) {
265                 $page = DI::pConfig()->get(local_user(), 'tumblr', 'page');
266                 $consumer_key = DI::config()->get('tumblr', 'consumer_key');
267                 $consumer_secret = DI::config()->get('tumblr', 'consumer_secret');
268
269                 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
270
271                 $userinfo = $tum_oauth->get('user/info');
272
273                 $blogs = [];
274
275                 $s .= '<label id="tumblr-page-label" for="tumblr-page">' . DI::l10n()->t('Post to page:') . '</label>';
276                 $s .= '<select name="tumblr_page" id="tumblr-page">';
277                 foreach($userinfo->response->user->blogs as $blog) {
278                         $blogurl = substr(str_replace(["http://", "https://"], ["", ""], $blog->url), 0, -1);
279
280                         if ($page == $blogurl) {
281                                 $s .= "<option value='".$blogurl."' selected>".$blogurl."</option>";
282                         } else {
283                                 $s .= "<option value='".$blogurl."'>".$blogurl."</option>";
284                         }
285                 }
286
287                 $s .= "</select>";
288         } else {
289                 $s .= DI::l10n()->t("You are not authenticated to tumblr");
290         }
291
292         $s .= '</div><div class="clear"></div>';
293
294         /* provide a submit button */
295         $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="tumblr-submit" name="tumblr-submit" class="settings-submit" value="' . DI::l10n()->t('Save Settings') . '" /></div></div>';
296 }
297
298 function tumblr_settings_post(App $a, array &$b)
299 {
300         if (!empty($_POST['tumblr-submit'])) {
301                 DI::pConfig()->set(local_user(), 'tumblr', 'post',            intval($_POST['tumblr']));
302                 DI::pConfig()->set(local_user(), 'tumblr', 'page',            $_POST['tumblr_page']);
303                 DI::pConfig()->set(local_user(), 'tumblr', 'post_by_default', intval($_POST['tumblr_bydefault']));
304         }
305 }
306
307 function tumblr_hook_fork(&$a, &$b)
308 {
309         if ($b['name'] != 'notifier_normal') {
310                 return;
311         }
312
313         $post = $b['data'];
314
315         if ($post['deleted'] || $post['private'] || ($post['created'] !== $post['edited']) ||
316                 !strstr($post['postopts'], 'tumblr') || ($post['parent'] != $post['id'])) {
317                 $b['execute'] = false;
318                 return;
319         }
320 }
321
322 function tumblr_post_local(App $a, array &$b)
323 {
324         // This can probably be changed to allow editing by pointing to a different API endpoint
325
326         if ($b['edit']) {
327                 return;
328         }
329
330         if (!local_user() || (local_user() != $b['uid'])) {
331                 return;
332         }
333
334         if ($b['private'] || $b['parent']) {
335                 return;
336         }
337
338         $tmbl_post   = intval(DI::pConfig()->get(local_user(), 'tumblr', 'post'));
339
340         $tmbl_enable = (($tmbl_post && !empty($_REQUEST['tumblr_enable'])) ? intval($_REQUEST['tumblr_enable']) : 0);
341
342         if ($b['api_source'] && intval(DI::pConfig()->get(local_user(), 'tumblr', 'post_by_default'))) {
343                 $tmbl_enable = 1;
344         }
345
346         if (!$tmbl_enable) {
347                 return;
348         }
349
350         if (strlen($b['postopts'])) {
351                 $b['postopts'] .= ',';
352         }
353
354         $b['postopts'] .= 'tumblr';
355 }
356
357
358
359
360 function tumblr_send(App $a, array &$b) {
361
362         if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) {
363                 return;
364         }
365
366         if (! strstr($b['postopts'],'tumblr')) {
367                 return;
368         }
369
370         if ($b['parent'] != $b['id']) {
371                 return;
372         }
373
374         // Dont't post if the post doesn't belong to us.
375         // This is a check for forum postings
376         $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
377         if ($b['contact-id'] != $self['id']) {
378                 return;
379         }
380
381         $oauth_token = DI::pConfig()->get($b['uid'], "tumblr", "oauth_token");
382         $oauth_token_secret = DI::pConfig()->get($b['uid'], "tumblr", "oauth_token_secret");
383         $page = DI::pConfig()->get($b['uid'], "tumblr", "page");
384         $tmbl_blog = 'blog/' . $page . '/post';
385
386         if ($oauth_token && $oauth_token_secret && $tmbl_blog) {
387                 $tags = Tag::getByURIId($b['uri-id']);
388
389                 $tag_arr = [];
390
391                 foreach($tags as $tag) {
392                         $tag_arr[] = $tag['name'];
393                 }
394
395                 if (count($tag_arr)) {
396                         $tags = implode(',', $tag_arr);
397                 }
398
399                 $title = trim($b['title']);
400
401                 $siteinfo = BBCode::getAttachedData($b["body"]);
402
403                 $params = [
404                         'state'  => 'published',
405                         'tags'   => $tags,
406                         'tweet'  => 'off',
407                         'format' => 'html',
408                 ];
409
410                 if (!isset($siteinfo["type"])) {
411                         $siteinfo["type"] = "";
412                 }
413
414                 if (($title == "") && isset($siteinfo["title"])) {
415                         $title = $siteinfo["title"];
416                 }
417
418                 if (isset($siteinfo["text"])) {
419                         $body = $siteinfo["text"];
420                 } else {
421                         $body = BBCode::removeShareInformation($b["body"]);
422                 }
423
424                 switch ($siteinfo["type"]) {
425                         case "photo":
426                                 $params['type']    = "photo";
427                                 $params['caption'] = BBCode::convert($body, false, 4);
428
429                                 if (isset($siteinfo["url"])) {
430                                         $params['link'] = $siteinfo["url"];
431                                 }
432
433                                 $params['source'] = $siteinfo["image"];
434                                 break;
435
436                         case "link":
437                                 $params['type']        = "link";
438                                 $params['title']       = $title;
439                                 $params['url']         = $siteinfo["url"];
440                                 $params['description'] = BBCode::convert($body, false, 4);
441                                 break;
442
443                         case "audio":
444                                 $params['type']         = "audio";
445                                 $params['external_url'] = $siteinfo["url"];
446                                 $params['caption']      = BBCode::convert($body, false, 4);
447                                 break;
448
449                         case "video":
450                                 $params['type']    = "video";
451                                 $params['embed']   = $siteinfo["url"];
452                                 $params['caption'] = BBCode::convert($body, false, 4);
453                                 break;
454
455                         default:
456                                 $params['type']  = "text";
457                                 $params['title'] = $title;
458                                 $params['body']  = BBCode::convert($b['body'], false, 4);
459                                 break;
460                 }
461
462                 if (isset($params['caption']) && (trim($title) != "")) {
463                         $params['caption'] = '<h1>'.$title."</h1>".
464                                                 "<p>".$params['caption']."</p>";
465                 }
466
467                 if (empty($params['caption']) && !empty($siteinfo["description"])) {
468                         $params['caption'] = BBCode::convert("[quote]" . $siteinfo["description"] . "[/quote]", false, 4);
469                 }
470
471                 $consumer_key = DI::config()->get('tumblr','consumer_key');
472                 $consumer_secret = DI::config()->get('tumblr','consumer_secret');
473
474                 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
475
476                 // Make an API call with the TumblrOAuth instance.
477                 $x = $tum_oauth->post($tmbl_blog,$params);
478                 $ret_code = $tum_oauth->http_code;
479
480                 //print_r($params);
481                 if ($ret_code == 201) {
482                         Logger::log('tumblr_send: success');
483                 } elseif ($ret_code == 403) {
484                         Logger::log('tumblr_send: authentication failure');
485                 } else {
486                         Logger::log('tumblr_send: general error: ' . print_r($x,true));
487                 }
488         }
489 }
490