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