Skip to content

Instantly share code, notes, and snippets.

@ssddanbrown
Forked from kritschy/foo.php
Last active May 14, 2020 21:15
Show Gist options
  • Save ssddanbrown/c74c84e89e5bf53395abba27d1bd7ef5 to your computer and use it in GitHub Desktop.
Save ssddanbrown/c74c84e89e5bf53395abba27d1bd7ef5 to your computer and use it in GitHub Desktop.
<?php
// Alter these to your instance, do not share publicly like this.
$base_api_url = 'http://bookstack.local/api/';
$token_id='ZNI62nNoghS3GyfzThlZFXqYNtHdHnM6';
$token_secret='zPffPZ1ATQcv4Nz75QYLEbMm6fPzmo7I';
// Id of the shelf we want to add our book to.
$shelfId = 12; // $_POST["category"]
// Info for the new book
$bookInfo = [
'name' => 'My new book', // $_POST['title']
'description' => 'My new book description', // $_POST['description']
];
// Create our new book
$book = request('/books', 'POST', $bookInfo);
// Get the shelf and create an array of the existing book ids
$shelf = request("/shelves/{$shelfId}", "GET");
$shelfBookIds = [];
foreach ($shelf->books as $existingBook) {
$shelfBookIds[] = $existingBook->id;
}
// Add our new book id to the array of book ids for the shelf
$shelfBookIds[] = $book->id;
// Update our shelf with the new books
$updatedShelf = request("/shelves/{$shelfId}", "PUT", [
"books" => $shelfBookIds,
]);
echo '<h1>Vielen Dank</h1>';
/**
* Make a request to BookStack and decode the response to JSON.
* Will die on any curl errors.
*/
function request(string $path, string $method = 'GET', array $data = []): stdClass {
global $base_api_url, $token_id, $token_secret;
$url = rtrim($base_api_url, '/') . '/' . ltrim($path, '/');
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, ["Authorization: Token {$token_id}:{$token_secret}"]);
if (count($data) > 0) {
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
}
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
die("Request to {$url} failed with error {$err}");
}
return json_decode($response);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment