2023-03-08 15:31:49 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Lewisdale\Webmentions;
|
|
|
|
|
|
|
|
use Symfony\Component\DomCrawler\Crawler;
|
|
|
|
use Symfony\Component\HttpClient\HttpClient;
|
|
|
|
use Symfony\Contracts\HttpClient\HttpClientInterface;
|
|
|
|
|
|
|
|
class Webmention {
|
|
|
|
private readonly HttpClientInterface $client;
|
|
|
|
|
|
|
|
function __construct()
|
|
|
|
{
|
|
|
|
$this->client = HttpClient::create();
|
|
|
|
}
|
|
|
|
|
|
|
|
public function sendForPage(string $source) : void {
|
2023-03-08 21:39:11 +00:00
|
|
|
$urls = $this->getUrls($source);
|
2023-03-08 15:31:49 +00:00
|
|
|
|
2023-03-08 21:39:11 +00:00
|
|
|
foreach($urls as $target) {
|
|
|
|
$this->sendWebmention($source, $target);
|
|
|
|
}
|
2023-03-08 15:31:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private function getUrls(string $url) : array {
|
|
|
|
$page = file_get_contents($url);
|
|
|
|
$doc = new Crawler($page);
|
|
|
|
|
2023-03-08 21:27:47 +00:00
|
|
|
$urls = [];
|
2023-03-08 15:31:49 +00:00
|
|
|
foreach ($doc->filter('.h-entry a') as $anchor) {
|
|
|
|
$target_url = $anchor->attributes->getNamedItem('href')->textContent;
|
|
|
|
|
|
|
|
if ($target_url !== null && strlen($target_url)) {
|
|
|
|
$urls[] = $target_url;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return $urls;
|
|
|
|
}
|
|
|
|
|
|
|
|
private function sendWebmention(string $source, string $target) {
|
|
|
|
$endpoint = $this->getWebmentionEndpoint($target);
|
2023-03-08 21:39:11 +00:00
|
|
|
|
|
|
|
if ($endpoint) {
|
|
|
|
echo "Sending for " . $endpoint . "<br />";
|
|
|
|
$this->client->request('POST', $endpoint,
|
|
|
|
[
|
|
|
|
"body" => [
|
|
|
|
"source" => $source,
|
|
|
|
"target" => $target
|
|
|
|
]
|
|
|
|
]);
|
|
|
|
}
|
2023-03-08 15:31:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private function getWebmentionEndpoint(string $url) : string | null {
|
|
|
|
$response = $this->client->request('GET', $url);
|
|
|
|
return EndpointParser::parse($response);
|
|
|
|
}
|
|
|
|
}
|