[
'method' => 'GET',
'header' => [
'User-Agent: MastofetchBot/1.0 (+https://mastofetch.vercel.app)',
],
'timeout' => 10 // in seconds
]
];
// The actual fetching process
$context = stream_context_create($opts);
$response = @file_get_contents($fullUrl, false, $context);
if ($response === false) {
return [];
}
$data = json_decode($response, true);
return is_array($data) ? $data : [];
}
// The decoding process
function decodeEntities($text)
{
return html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
// Decoding the profile picture of the Mastodon user
function getAuthorProfileImage($account)
{
return $account['avatar'];
}
// Decoding the time and date of the posts and encoding it as the estimated length of time between you seeing the post and the time it was posted
function getTimeElapsedString($datetime)
{
$now = new DateTime("now", new DateTimeZone("UTC"));
$ago = new DateTime($datetime, new DateTimeZone("UTC"));
$diff = $now->diff($ago);
$string = [
'y' => 'year',
'm' => 'month',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
];
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . ($diff->$k > 1 ? $v . 's' : $v);
} else {
unset($string[$k]);
}
}
return $string ? implode(', ', array_slice($string, 0, 1)) . ' ago' : 'just now';
}
// Exclusing the already fetched URL to avoid getting from the same instance again during that run of the script
function getRandomInstanceURL($exclude = null)
{
global $instances;
$filtered = array_values(array_filter($instances, fn($url) => $url !== $exclude));
if (empty($filtered)) return null;
return $filtered[array_rand($filtered)];
}
// Includes some safety protections like sanitization
if (isset($_GET['ajax']) && $_GET['ajax'] === '1') {
$exclude = filter_input(INPUT_GET, 'exclude', FILTER_SANITIZE_URL);
$url = getRandomInstanceURL($exclude);
$posts = fetchPostsFromMastodon($url, 10);
// The encoding of the lazyload next post items
foreach ($posts as $post) {
$authorProfileImage = getAuthorProfileImage($post['account']);
echo "
";
}
exit;
}
// 5 Posts from the 1st instance will initially appear then the rest will appear during the lazyload
$firstInstance = $instances[array_rand($instances)];
$initialPosts = fetchPostsFromMastodon($firstInstance, 5);
?>
Mastofetch - Catch the fediverse in your hands
Mastofetch is your anonymized feed retriever for the Mastodon network. This project feeds the public posts posted across the entire Mastodon network to your web browser.