PageRenderTime 39ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/tumblr/tumblr.php

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