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