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