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