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