bluesky-handles/index.php
2024-02-28 03:02:14 +00:00

113 lines
2.7 KiB
PHP

<?php
$config = include 'config/local.config.php';
if (empty($config['config']['hostname'])) {
notFound();
}
$connection = connectDatabase($config);
if (empty($connection)) {
notFound();
}
if (!in_array($_REQUEST['pagename'], ['.well-known/atproto-did', ''])) {
notFound();
}
$server = '.' . trim($config['config']['hostname'], '.');
if (!strpos($_SERVER['SERVER_NAME'], $server)) {
notFound();
}
$nick = str_replace($server, '', $_SERVER['SERVER_NAME']);
$user = selectFirst($connection, "SELECT `uid` FROM `user` WHERE `nickname` = ?", [$nick]);
if (empty($user['uid'])) {
notFound();
}
if ($_REQUEST['pagename'] == '') {
header('Location: http://' . $config['config']['hostname'] . '/profile/' . $nick);
die();
}
$enabled = selectFirst($connection, "SELECT `v` FROM `pconfig` WHERE `uid` = ? AND `cat` = ? AND `k` = ?", [$user['uid'], 'bluesky', 'friendica_handle']);
if (empty($enabled['v'])) {
notFound();
}
$did = selectFirst($connection, "SELECT `v` FROM `pconfig` WHERE `uid` = ? AND `cat` = ? AND `k` = ?", [$user['uid'], 'bluesky', 'did']);
if (empty($did['v'])) {
notFound();
}
header('Content-Type: text/plain');
echo $did['v'];
function notFound()
{
header('HTTP/1.0 404 Not Found');
echo '<h1>404 - Page Not Found</h1>';
echo 'The requested resource could not be found but may be available in the future.';
die();
}
function connectDatabase(array $config): PDO
{
if (!empty($config['database']['socket'])) {
$connect = 'mysql:unix_socket=' . $config['database']['socket'];
} else {
$connect = 'mysql:host=' . $config['database']['hostname'];
if (!empty($config['database']['port'])) {
$connect .= ';port=' . $config['database']['port'];
}
}
if (!empty($config['database']['charset'])) {
$connect .= ';charset=' . $config['database']['charset'];
}
$connect .= ';dbname=' . $config['database']['database'];
try {
$connection = @new PDO($connect, $config['database']['username'], $config['database']['password'], [PDO::ATTR_PERSISTENT => false]);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
} catch (PDOException $e) {
$connection = null;
}
return $connection;
}
function selectFirst(PDO $connection, $query, $parameters = []): ?array
{
if (!$stmt = $connection->prepare($query)) {
return null;
}
foreach (array_keys($parameters) as $param) {
$data_type = PDO::PARAM_STR;
if (is_int($parameters[$param])) {
$data_type = PDO::PARAM_INT;
} elseif ($parameters[$param] !== null) {
$parameters[$param] = (string)$parameters[$param];
}
$stmt->bindParam($param + 1, $parameters[$param], $data_type);
}
if (!$stmt->execute()) {
return null;
}
$columns = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
if (!is_array($columns)) {
return null;
}
return $columns;
}
?>