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