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