Here is a simple PHP class I use to call Discourse API:
PHP code
<?php
namespace Kozomap;
use InvalidArgumentException;
use LogicException;
use RuntimeException;
class ForumApi
{
public static function call($method, $urlPath, $vars = []) {
$ch = null;
try {
$vars['api_username'] = KOZOVOD_FORUM_API_USERNAME;
$vars['api_key'] = KOZOVOD_FORUM_API_KEY;
$url = KOZOVOD_FORUM_URL;
if (substr($url, -1) !== '/') {
$url = $url . '/';
}
if (substr($urlPath, 0, 1) == '/') {
$urlPath = substr($urlPath, 1);
}
$url = $url . $urlPath;
if (strpos($url, 'https://') !== false) {
$port = 443;
} else {
$port = 80;
}
$curlOpts = [
CURLOPT_URL => $url,
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_PORT => $port,
];
$method = strtoupper($method);
switch ($method) {
case 'GET':
$url = $url . '?' . http_build_query($vars);
break;
case 'POST':
$curlOpts[CURLOPT_POST] = true;
$curlOpts[CURLOPT_POSTFIELDS] = $vars;
break;
case 'PUT':
$curlOpts[CURLOPT_CUSTOMREQUEST] = 'PUT';
$curlOpts[CURLOPT_POSTFIELDS] = $vars;
break;
case 'DELETE':
$curlOpts[CURLOPT_CUSTOMREQUEST] = 'DELETE';
break;
default:
throw new LogicException('Unknown method to call Forum API.');
}
$ch = curl_init();
if ($ch === false) {
throw new RuntimeException('Cannot initialize curl_init for Forum API.');
}
$res = curl_setopt_array($ch, $curlOpts);
if ($res === false) {
throw new RuntimeException('Cannot set curl options for Forum API.');
}
$response = curl_exec($ch);
if ($response === false) {
$errNo = curl_errno($ch);
$err = curl_error($ch);
throw new RuntimeException("Failed calling Forum API, curl_exec returned FALSE. CURL error no. $errNo, message: $err");
}
$decoded = json_decode($response, $assoc = true);
if ($decoded === null) {
throw new RuntimeException('Cannot json_decode Forum API result.');
}
return $decoded;
} catch (\Exception $e) {
// Rethrow the exception; might add error logging later
throw $e;
} finally {
if (!empty($ch)) {
curl_close($ch);
}
}
}
public static function runDataExplorerQuery($id) {
if (!ctype_digit(''.$id)) {
throw new InvalidArgumentException('Data Explorer Query ID is not an integer number.');
}
$json = self::call('POST', "admin/plugins/explorer/queries/{$id}/run.json");
if (!array_key_exists('success', $json)) {
throw new RuntimeException('Data Explorer Query result does not contain "success" key.');
}
if (!$json['success']) {
if (array_key_exists('errors', $json) && is_array($json['errors'])) {
$err = $json['errors'][0];
} else {
$err = 'No error details provided by Forum API.';
}
throw new RuntimeException("Data Explorer Query did not run successfully. $err");
}
return $json;
}
}
For instance, to fetch data returned by query with ID=5 (after you build it in your query explorer), use this:
$data = ForumApi::runDataExplorerQuery(5);
Of course, it will be practical to run data fetching once a few minutes and cache it, and let maps use local (cached) version of the data, otherwise you’ll end up DDoSing your Disccourse instance.