feature(api): add more API functions such as upload

This commit is contained in:
David Bailey 2024-11-18 22:48:13 +01:00
parent c9808f90f8
commit 2e012b4fd5

View file

@ -1,13 +1,84 @@
<?php
if(preg_match('/^\/api\/posts(.*)$/', $REQUEST_PATH, $match)) {
header('Content-Type: application/json');
$post = $adapter->get_post($match[1]);
use Spatie\YamlFrontMatter\YamlFrontMatter;
preg_match('/^\/api\/([^\/]*)(.*)/', $REQUEST_PATH, $match);
$API_FUNCTION = $match[1];
switch($API_FUNCTION) {
case 'posts':
$post = $adapter->get_post($match[2]);
if(!isset($post)) {
echo json_encode([
'found' => false,
'status' => 404
]);
} else {
echo $post->to_json($REQUEST_QUERY);
}
break;
case 'upload':
if(!access_can_upload()) {
http_response_code(401);
echo json_encode([
'status' => '401 Unauthorized'
]);
die();
}
if( !isset($_POST['path']) or
!isset($_FILES['file'])) {
echo json_encode([
'status' => 'Missing paramters (must POST path and file!)'
]);
die();
}
$file_path = sanitize_post_path($_POST['path']);
$physical_file_path = $SITE_CONFIG['upload']['file_path'] . $file_path;
$file_dir = dirname($physical_file_path);
if(!is_dir($file_dir)) {
mkdir(dirname($physical_file_path), recursive: true);
}
move_uploaded_file($_FILES['file']['tmp_name'], $physical_file_path);
$file_ext = pathinfo($file_path, PATHINFO_EXTENSION);
if($file_ext == 'md') {
$is_directory = false;
$original_file_path = $file_path;
if(basename($file_path) == 'README.md') {
$is_directory = true;
$file_path = dirname($file_path);
}
$post_matter = YamlFrontMatter::parse(file_get_contents($physical_file_path));
$post_data = $post_matter->matter();
$post_data['path'] = $file_path;
$post_data['markdown'] = $post_matter->body();
if($is_directory) {
$post_data['base'] ??= $original_file_path;
$post_data['type'] ??= 'directory';
}
$sql_adapter->set_postdata($post_data);
}
break;
}
?>