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