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