Skip to content

Instantly share code, notes, and snippets.

@tstarling
Created December 2, 2022 02:47
Show Gist options
  • Save tstarling/738ced431d8ddddfd01d7bdcd4c46ef4 to your computer and use it in GitHub Desktop.
Save tstarling/738ced431d8ddddfd01d7bdcd4c46ef4 to your computer and use it in GitHub Desktop.
<?php
const MASTO_HOST = 'https://wikis.world/';
require __DIR__ .'/../vendor/autoload.php';
function fatalError( $message ) {
print nl2br( htmlspecialchars( $message ) );
exit;
}
function appendQuery( &$url, $params ) {
$first = true;
foreach ( $params as $name => $value ) {
if ( $first ) {
$first = false;
$url .= '?';
} else {
$url .= '&';
}
$url .= rawurlencode( $name ) . '=' . rawurlencode( $value );
}
return $url;
}
function getApiUrl( $path, $params ) {
$url = MASTO_HOST . "api/$path";
appendQuery( $url, $params );
return $url;
}
function doRequest( $url ) {
$client = new \GuzzleHttp\Client( [ 'http_errors' => true ] );
$response = $client->request( 'GET', $url );
$data = json_decode( $response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR );
$error = $data['error'] ?? null;
if ( $error ) {
fatalError( "Error: $error" );
}
$links = $response->getHeaderLine( 'Link' );
$next = null;
foreach ( explode( ',', $links ) as $link ) {
if ( preg_match( '/^ *<([^>]*)>; *rel="next" *$/', $link, $m ) ) {
$next = $m[1];
}
}
return [ $data, $next ];
}
function main() {
print "<!DOCTYPE html>\n<html><body><ul>\n";
$required = array_fill_keys( [ 'user', 'q' ], true );
$missing = array_diff_key( $required, $_GET );
if ( $missing ) {
fatalError( "Missing parameters: " . implode( ', ', array_keys( $missing ) ) );
}
$user = $_GET['user'];
$search = $_GET['q'];
$acctId = doRequest( getApiUrl( 'v1/accounts/lookup', [ 'acct' => $user ] ) )[0]['id'];
$maxResults = $_GET['limit'] ?? 100;
$batchSize = 20;
$url = getApiUrl( "v1/accounts/$acctId/statuses", [ 'limit' => $batchSize ] );
$numResults = 0;
for ( $i = 0; $i < ceil( $maxResults / $batchSize ); $i++ ) {
[ $statuses, $next ] = doRequest( $url );
foreach ( $statuses as $status ) {
if ( preg_match( '{' . $search . '}', $status['content'] ) ) {
$encUrl = htmlspecialchars( "https://wikis.world/@$user/{$status['id']}" );
print "<li>{$status['content']}<a href=\"$encUrl\">...</a></li>\n";
$numResults++;
}
}
if ( $next === null ) {
break;
}
if ( !str_starts_with( $next, MASTO_HOST ) ) {
fatalError( "Cross-domain next link" );
}
$url = $next;
}
print "</ul>\n<p>$numResults results found</p>\n";
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment