]> git.mxchange.org Git - friendica-addons.git/blob - tumblr/tumblr.php
Function renamed
[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 use Friendica\Util\Strings;
22
23 function tumblr_install()
24 {
25         Addon::registerHook('post_local',              'addon/tumblr/tumblr.php', 'tumblr_post_local');
26         Addon::registerHook('notifier_normal',         'addon/tumblr/tumblr.php', 'tumblr_send');
27         Addon::registerHook('jot_networks',            'addon/tumblr/tumblr.php', 'tumblr_jot_nets');
28         Addon::registerHook('connector_settings',      'addon/tumblr/tumblr.php', 'tumblr_settings');
29         Addon::registerHook('connector_settings_post', 'addon/tumblr/tumblr.php', 'tumblr_settings_post');
30 }
31
32 function tumblr_uninstall()
33 {
34         Addon::unregisterHook('post_local',              'addon/tumblr/tumblr.php', 'tumblr_post_local');
35         Addon::unregisterHook('notifier_normal',         'addon/tumblr/tumblr.php', 'tumblr_send');
36         Addon::unregisterHook('jot_networks',            'addon/tumblr/tumblr.php', 'tumblr_jot_nets');
37         Addon::unregisterHook('connector_settings',      'addon/tumblr/tumblr.php', 'tumblr_settings');
38         Addon::unregisterHook('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(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' => L10n::t('Save Settings'),
79                 // name, label, value, help, [extra values]
80                 '$consumer_key' => ['consumer_key', L10n::t('Consumer Key'),  Config::get('tumblr', 'consumer_key' ), ''],
81                 '$consumer_secret' => ['consumer_secret', L10n::t('Consumer Secret'),  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         Config::set('tumblr', 'consumer_key',$consumer_key);
91         Config::set('tumblr', 'consumer_secret',$consumer_secret);
92
93         info(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 = Config::get('tumblr', 'consumer_key');
106         $consumer_secret = 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 = $a->getBaseURL()."/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 = Config::get('tumblr', 'consumer_key');
159         $consumer_secret = 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         PConfig::set(local_user(), "tumblr", "oauth_token", $access_token['oauth_token']);
186         PConfig::set(local_user(), "tumblr", "oauth_token_secret", $access_token['oauth_token_secret']);
187
188         $o = L10n::t("You are now authenticated to tumblr.");
189         $o .= '<br /><a href="'.$a->getBaseURL().'/settings/connectors">'.L10n::t("return to the connector page").'</a>';
190
191         return $o;
192 }
193
194 function tumblr_jot_nets(App $a, &$b)
195 {
196         if (! local_user()) {
197                 return;
198         }
199
200         $tmbl_post = PConfig::get(local_user(), 'tumblr', 'post');
201
202         if (intval($tmbl_post) == 1) {
203                 $tmbl_defpost = PConfig::get(local_user(), 'tumblr', 'post_by_default');
204                 $selected = ((intval($tmbl_defpost) == 1) ? ' checked="checked" ' : '');
205                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="tumblr_enable"' . $selected . ' value="1" /> '
206                         . L10n::t('Post to Tumblr') . '</div>';
207         }
208 }
209
210 function tumblr_settings(App $a, &$s)
211 {
212         if (! local_user()) {
213                 return;
214         }
215
216         /* Add our stylesheet to the page so we can make our settings look nice */
217
218         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->getBaseURL() . '/addon/tumblr/tumblr.css' . '" media="all" />' . "\r\n";
219
220         /* Get the current state of our config variables */
221
222         $enabled = PConfig::get(local_user(), 'tumblr', 'post');
223         $checked = (($enabled) ? ' checked="checked" ' : '');
224         $css = (($enabled) ? '' : '-disabled');
225
226         $def_enabled = PConfig::get(local_user(), 'tumblr', 'post_by_default');
227
228         $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
229
230         /* Add some HTML to the existing form */
231
232         $s .= '<span id="settings_tumblr_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_tumblr_expanded\'); openClose(\'settings_tumblr_inflated\');">';
233         $s .= '<img class="connector'.$css.'" src="images/tumblr.png" /><h3 class="connector">'. L10n::t('Tumblr Export').'</h3>';
234         $s .= '</span>';
235         $s .= '<div id="settings_tumblr_expanded" class="settings-block" style="display: none;">';
236         $s .= '<span class="fakelink" onclick="openClose(\'settings_tumblr_expanded\'); openClose(\'settings_tumblr_inflated\');">';
237         $s .= '<img class="connector'.$css.'" src="images/tumblr.png" /><h3 class="connector">'. L10n::t('Tumblr Export').'</h3>';
238         $s .= '</span>';
239
240         $s .= '<div id="tumblr-username-wrapper">';
241         $s .= '<a href="'.$a->getBaseURL().'/tumblr/connect">'.L10n::t("(Re-)Authenticate your tumblr page").'</a>';
242         $s .= '</div><div class="clear"></div>';
243
244         $s .= '<div id="tumblr-enable-wrapper">';
245         $s .= '<label id="tumblr-enable-label" for="tumblr-checkbox">' . L10n::t('Enable Tumblr Post Addon') . '</label>';
246         $s .= '<input id="tumblr-checkbox" type="checkbox" name="tumblr" value="1" ' . $checked . '/>';
247         $s .= '</div><div class="clear"></div>';
248
249         $s .= '<div id="tumblr-bydefault-wrapper">';
250         $s .= '<label id="tumblr-bydefault-label" for="tumblr-bydefault">' . L10n::t('Post to Tumblr by default') . '</label>';
251         $s .= '<input id="tumblr-bydefault" type="checkbox" name="tumblr_bydefault" value="1" ' . $def_checked . '/>';
252         $s .= '</div><div class="clear"></div>';
253
254         $oauth_token = PConfig::get(local_user(), "tumblr", "oauth_token");
255         $oauth_token_secret = PConfig::get(local_user(), "tumblr", "oauth_token_secret");
256
257         $s .= '<div id="tumblr-page-wrapper">';
258
259         if (($oauth_token != "") && ($oauth_token_secret != "")) {
260                 $page = PConfig::get(local_user(), 'tumblr', 'page');
261                 $consumer_key = Config::get('tumblr', 'consumer_key');
262                 $consumer_secret = Config::get('tumblr', 'consumer_secret');
263
264                 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
265
266                 $userinfo = $tum_oauth->get('user/info');
267
268                 $blogs = [];
269
270                 $s .= '<label id="tumblr-page-label" for="tumblr-page">' . L10n::t('Post to page:') . '</label>';
271                 $s .= '<select name="tumblr_page" id="tumblr-page">';
272                 foreach($userinfo->response->user->blogs as $blog) {
273                         $blogurl = substr(str_replace(["http://", "https://"], ["", ""], $blog->url), 0, -1);
274
275                         if ($page == $blogurl) {
276                                 $s .= "<option value='".$blogurl."' selected>".$blogurl."</option>";
277                         } else {
278                                 $s .= "<option value='".$blogurl."'>".$blogurl."</option>";
279                         }
280                 }
281
282                 $s .= "</select>";
283         } else {
284                 $s .= L10n::t("You are not authenticated to tumblr");
285         }
286
287         $s .= '</div><div class="clear"></div>';
288
289         /* provide a submit button */
290         $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>';
291 }
292
293 function tumblr_settings_post(App $a, array &$b)
294 {
295         if (!empty($_POST['tumblr-submit'])) {
296                 PConfig::set(local_user(), 'tumblr', 'post',            intval($_POST['tumblr']));
297                 PConfig::set(local_user(), 'tumblr', 'page',            $_POST['tumblr_page']);
298                 PConfig::set(local_user(), 'tumblr', 'post_by_default', intval($_POST['tumblr_bydefault']));
299         }
300 }
301
302 function tumblr_post_local(App $a, array &$b)
303 {
304         // This can probably be changed to allow editing by pointing to a different API endpoint
305
306         if ($b['edit']) {
307                 return;
308         }
309
310         if (!local_user() || (local_user() != $b['uid'])) {
311                 return;
312         }
313
314         if ($b['private'] || $b['parent']) {
315                 return;
316         }
317
318         $tmbl_post   = intval(PConfig::get(local_user(), 'tumblr', 'post'));
319
320         $tmbl_enable = (($tmbl_post && !empty($_REQUEST['tumblr_enable'])) ? intval($_REQUEST['tumblr_enable']) : 0);
321
322         if ($b['api_source'] && intval(PConfig::get(local_user(), 'tumblr', 'post_by_default'))) {
323                 $tmbl_enable = 1;
324         }
325
326         if (!$tmbl_enable) {
327                 return;
328         }
329
330         if (strlen($b['postopts'])) {
331                 $b['postopts'] .= ',';
332         }
333
334         $b['postopts'] .= 'tumblr';
335 }
336
337
338
339
340 function tumblr_send(App $a, array &$b) {
341
342         if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) {
343                 return;
344         }
345
346         if (! strstr($b['postopts'],'tumblr')) {
347                 return;
348         }
349
350         if ($b['parent'] != $b['id']) {
351                 return;
352         }
353
354         // Dont't post if the post doesn't belong to us.
355         // This is a check for forum postings
356         $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
357         if ($b['contact-id'] != $self['id']) {
358                 return;
359         }
360
361         $oauth_token = PConfig::get($b['uid'], "tumblr", "oauth_token");
362         $oauth_token_secret = PConfig::get($b['uid'], "tumblr", "oauth_token_secret");
363         $page = PConfig::get($b['uid'], "tumblr", "page");
364         $tmbl_blog = 'blog/' . $page . '/post';
365
366         if ($oauth_token && $oauth_token_secret && $tmbl_blog) {
367                 $tag_arr = [];
368                 $tags = '';
369                 preg_match_all('/\#\[(.*?)\](.*?)\[/', $b['tag'], $matches, PREG_SET_ORDER);
370
371                 if (!empty($matches)) {
372                         foreach($matches as $mtch) {
373                                 $tag_arr[] = $mtch[2];
374                         }
375                 }
376
377                 if (count($tag_arr)) {
378                         $tags = implode(',', $tag_arr);
379                 }
380
381                 $title = trim($b['title']);
382
383                 $siteinfo = BBCode::getAttachedData($b["body"]);
384
385                 $params = [
386                         'state'  => 'published',
387                         'tags'   => $tags,
388                         'tweet'  => 'off',
389                         'format' => 'html',
390                 ];
391
392                 if (!isset($siteinfo["type"])) {
393                         $siteinfo["type"] = "";
394                 }
395
396                 if (($title == "") && isset($siteinfo["title"])) {
397                         $title = $siteinfo["title"];
398                 }
399
400                 if (isset($siteinfo["text"])) {
401                         $body = $siteinfo["text"];
402                 } else {
403                         $body = BBCode::removeShareInformation($b["body"]);
404                 }
405
406                 switch ($siteinfo["type"]) {
407                         case "photo":
408                                 $params['type']    = "photo";
409                                 $params['caption'] = BBCode::convert($body, false, 4);
410
411                                 if (isset($siteinfo["url"])) {
412                                         $params['link'] = $siteinfo["url"];
413                                 }
414
415                                 $params['source'] = $siteinfo["image"];
416                                 break;
417
418                         case "link":
419                                 $params['type']        = "link";
420                                 $params['title']       = $title;
421                                 $params['url']         = $siteinfo["url"];
422                                 $params['description'] = BBCode::convert($body, false, 4);
423                                 break;
424
425                         case "audio":
426                                 $params['type']         = "audio";
427                                 $params['external_url'] = $siteinfo["url"];
428                                 $params['caption']      = BBCode::convert($body, false, 4);
429                                 break;
430
431                         case "video":
432                                 $params['type']    = "video";
433                                 $params['embed']   = $siteinfo["url"];
434                                 $params['caption'] = BBCode::convert($body, false, 4);
435                                 break;
436
437                         default:
438                                 $params['type']  = "text";
439                                 $params['title'] = $title;
440                                 $params['body']  = BBCode::convert($b['body'], false, 4);
441                                 break;
442                 }
443
444                 if (isset($params['caption']) && (trim($title) != "")) {
445                         $params['caption'] = '<h1>'.$title."</h1>".
446                                                 "<p>".$params['caption']."</p>";
447                 }
448
449                 if (empty($params['caption']) && !empty($siteinfo["description"])) {
450                         $params['caption'] = BBCode::convert("[quote]" . $siteinfo["description"] . "[/quote]", false, 4);
451                 }
452
453                 $consumer_key = Config::get('tumblr','consumer_key');
454                 $consumer_secret = Config::get('tumblr','consumer_secret');
455
456                 $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
457
458                 // Make an API call with the TumblrOAuth instance.
459                 $x = $tum_oauth->post($tmbl_blog,$params);
460                 $ret_code = $tum_oauth->http_code;
461
462                 //print_r($params);
463                 if ($ret_code == 201) {
464                         Logger::log('tumblr_send: success');
465                 } elseif ($ret_code == 403) {
466                         Logger::log('tumblr_send: authentication failure');
467                 } else {
468                         Logger::log('tumblr_send: general error: ' . print_r($x,true));
469                 }
470         }
471 }
472