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