PageRenderTime 42ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/php_demo/functions.php

https://gitlab.com/billyprice1/bdApi
PHP | 287 lines | 237 code | 47 blank | 3 comment | 23 complexity | 9ba1f1e97ec90c4af4682223d6df28c6 MD5 | raw file
  1. <?php
  2. session_start();
  3. function loadConfiguration()
  4. {
  5. $config = array();
  6. $path = dirname(__FILE__) . '/config.php';
  7. if (file_exists($path)) {
  8. require($path);
  9. if (empty($config['api_root'])) {
  10. $config = array();
  11. }
  12. }
  13. if (!empty($_SESSION['ignore_config'])) {
  14. $oldConfig = $config;
  15. $config = $_SESSION;
  16. if (!empty($oldConfig['api_root'])) {
  17. $config['placeholder'] = $oldConfig;
  18. }
  19. }
  20. return array_merge(array(
  21. 'api_root' => '',
  22. 'api_key' => '',
  23. 'api_secret' => '',
  24. 'api_scope' => '',
  25. 'placeholder' => array(
  26. 'api_root' => 'http://domain.com/xenforo/api',
  27. 'api_key' => 'abc123',
  28. 'api_secret' => 'xyz456',
  29. 'api_scope' => 'read',
  30. ),
  31. 'ignore_config' => false,
  32. ), $config);
  33. }
  34. function displaySetup()
  35. {
  36. require(dirname(__FILE__) . '/setup.php');
  37. exit;
  38. }
  39. function getBaseUrl()
  40. {
  41. // idea from http://stackoverflow.com/questions/6768793/get-the-full-url-in-php
  42. $ssl = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? true : false;
  43. $sp = strtolower($_SERVER['SERVER_PROTOCOL']);
  44. $protocol = substr($sp, 0, strpos($sp, '/')) . (($ssl) ? 's' : '');
  45. $port = $_SERVER['SERVER_PORT'];
  46. $port = ((!$ssl && $port == '80') || ($ssl && $port == '443')) ? '' : ':' . $port;
  47. // using HTTP_POST may have some security implication
  48. $host = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : null);
  49. $host = isset($host) ? $host : $_SERVER['SERVER_NAME'] . $port;
  50. $baseUrl = $protocol . '://' . $host . $_SERVER['REQUEST_URI'];
  51. $baseUrl = preg_replace('#\?.*$#', '', $baseUrl);
  52. $baseUrl = rtrim($baseUrl, '/');
  53. return $baseUrl;
  54. }
  55. function getCallbackUrl()
  56. {
  57. return sprintf(
  58. '%s?action=callback',
  59. getBaseUrl()
  60. );
  61. }
  62. function generateJsSdkUrl($apiRoot)
  63. {
  64. $url = sprintf(
  65. '%s/index.php?assets/sdk.js',
  66. $apiRoot
  67. );
  68. return $url;
  69. }
  70. function generateOneTimeToken($apiKey, $apiSecret, $userId = 0, $accessToken = '', $ttl = 86400)
  71. {
  72. $timestamp = time() + $ttl;
  73. $once = md5($userId . $timestamp . $accessToken . $apiSecret);
  74. return sprintf('%d,%d,%s,%s', $userId, $timestamp, $once, $apiKey);
  75. }
  76. function makeRequest($url, $apiRoot, $accessToken)
  77. {
  78. if (strpos($url, $apiRoot) === false) {
  79. $url = sprintf(
  80. '%s/index.php?%s&oauth_token=%s',
  81. $apiRoot,
  82. $url,
  83. rawurlencode($accessToken)
  84. );
  85. }
  86. $body = @file_get_contents($url);
  87. $json = @json_decode($body, true);
  88. return array($body, $json);
  89. }
  90. function makeSubscriptionRequest($config, $topic, $fwd, $accessToken = null)
  91. {
  92. $subscriptionUrl = sprintf(
  93. '%s/index.php?subscriptions',
  94. $config['api_root']
  95. );
  96. $callbackUrl = sprintf(
  97. '%s/subscriptions.php?fwd=%s',
  98. rtrim(preg_replace('#index.php$#', '', getBaseUrl()), '/'),
  99. rawurlencode($fwd)
  100. );
  101. $postFields = array(
  102. 'hub.callback' => $callbackUrl,
  103. 'hub.mode' => !empty($accessToken) ? 'subscribe' : 'unsubscribe',
  104. 'hub.topic' => $topic,
  105. 'oauth_token' => $accessToken,
  106. 'client_id' => $config['api_key'],
  107. );
  108. return array('response' => makeCurlPost($subscriptionUrl, $postFields, false));
  109. }
  110. function makeCurlPost($url, $postFields, $getJson = true)
  111. {
  112. $ch = curl_init();
  113. curl_setopt($ch, CURLOPT_URL, $url);
  114. curl_setopt($ch, CURLOPT_POST, true);
  115. curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
  116. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  117. $body = curl_exec($ch);
  118. curl_close($ch);
  119. if (!$getJson) {
  120. return $body;
  121. }
  122. $json = @json_decode($body, true);
  123. if (empty($json)) {
  124. die('Unexpected response from server: ' . $body);
  125. }
  126. return $json;
  127. }
  128. function renderMessageForPostRequest($url, array $postFields)
  129. {
  130. $message = 'It looks like you are testing a local installation. ';
  131. $message .= 'Since this test server cannot reach yours, please run this command in your terminal ';
  132. $message .= '(or equivalent) please:<br /><br />';
  133. $message .= '<div class="code">curl -XPOST "' . $url . '" \\</div>';
  134. $postFieldKeys = array_keys($postFields);
  135. $lastFieldKey = array_pop($postFieldKeys);
  136. foreach ($postFields as $postFieldKey => $postFieldValue) {
  137. $message .= sprintf(
  138. '<div class="code"> -F %s=%s%s</div>',
  139. $postFieldKey,
  140. $postFieldValue,
  141. $postFieldKey === $lastFieldKey ? '' : ' \\'
  142. );
  143. }
  144. return $message;
  145. }
  146. function renderMessageForJson($url, array $json)
  147. {
  148. global $accessToken;
  149. $html = str_replace(' ', '&nbsp;&nbsp;', var_export($json, true));
  150. if (!empty($accessToken)) {
  151. $offset = 0;
  152. while (true) {
  153. if (preg_match('#\'(?<link>http[^\']+)\'#', $html, $matches, PREG_OFFSET_CAPTURE, $offset)) {
  154. $offset = $matches[0][1] + strlen($matches[0][0]);
  155. $link = $matches['link'][0];
  156. $replacement = null;
  157. if (strpos($link, $accessToken) !== false) {
  158. // found a link
  159. $targetUrl = sprintf(
  160. '%s?action=request&url=%s&access_token=%s',
  161. getBaseUrl(),
  162. rawurlencode($link),
  163. rawurlencode($accessToken)
  164. );
  165. $replacement = sprintf('<a href="%s">%s</a>', $targetUrl, $link);
  166. } elseif (substr($link, 0, 4) === 'http') {
  167. $replacement = sprintf('<a href="%1$s" target="_blank">%1$s</a>', $link);
  168. }
  169. if (!empty($replacement)) {
  170. $html = substr_replace(
  171. $html,
  172. $replacement,
  173. $matches['link'][1],
  174. strlen($matches['link'][0])
  175. );
  176. $offset = $matches[0][1] + strlen($replacement);
  177. }
  178. } else {
  179. break;
  180. }
  181. }
  182. }
  183. return sprintf(
  184. '<div class="request">Sent Request: %s</div><div class="response">Received Response: %s</div>',
  185. $url,
  186. nl2br($html)
  187. );
  188. }
  189. function renderAccessTokenMessage($tokenUrl, array $json)
  190. {
  191. global $config, $accessToken;
  192. if (!empty($json['access_token'])) {
  193. $accessToken = $json['access_token'];
  194. $message = sprintf(
  195. 'Obtained access token successfully!<br />'
  196. . 'Scopes: %s<br />'
  197. . 'Expires At: %s<br />',
  198. $json['scope'],
  199. date('c', time() + $json['expires_in'])
  200. );
  201. if (!empty($json['refresh_token'])) {
  202. $message .= sprintf('Refresh Token: <a href="index.php?action=refresh&refresh_token=%1$s">%1$s</a><br />', $json['refresh_token']);
  203. } else {
  204. $message .= sprintf('Refresh Token: N/A<br />');
  205. }
  206. list($body, $json) = makeRequest('index', $config['api_root'], $accessToken);
  207. if (!empty($json['links'])) {
  208. $message .= '<hr />' . renderMessageForJson('index', $json);
  209. }
  210. } else {
  211. $message = renderMessageForJson($tokenUrl, $json);
  212. }
  213. return $message;
  214. }
  215. function isLocal($apiRoot) {
  216. $apiRootHost = parse_url($apiRoot, PHP_URL_HOST);
  217. $isLocal = in_array($apiRootHost, array(
  218. 'localhost',
  219. '127.0.0.1',
  220. 'local.dev',
  221. ));
  222. return $isLocal;
  223. }
  224. function bitlyShorten($token, $url)
  225. {
  226. $bitlyUrl = sprintf(
  227. '%s?access_token=%s&longUrl=%s&domain=j.mp&format=txt',
  228. 'https://api-ssl.bitly.com/v3/shorten',
  229. rawurlencode($token),
  230. rawurlencode($url)
  231. );
  232. $body = @file_get_contents($bitlyUrl);
  233. if (!empty($body)) {
  234. $url = $body;
  235. }
  236. return $url;
  237. }