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