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