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