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