5 // You can either provide them as environment variables
6 // or hard-code them in the empty strings below.
7 $apiUrl = getenv('BS_URL') ?: ''; // http://bookstack.local/
8 $clientId = getenv('BS_TOKEN_ID') ?: '';
9 $clientSecret = getenv('BS_TOKEN_SECRET') ?: '';
11 // Export Format & Location
12 // Can be provided as a arguments when calling the script
13 // or be hard-coded as strings below.
14 $exportFormat = $argv[1] ?? 'pdf';
15 $exportLocation = $argv[2] ?? './';
20 // Get all list of all books in the system
21 $books = getAllBooks();
22 // Get a reference to our output location
23 $outDir = realpath($exportLocation);
25 // Mapping for export formats to the resulting export file extensions
26 $extensionByFormat = [
33 // Loop over each book, exporting each one-by-one and saving its
34 // contents into the output location, using the books slug as
36 foreach ($books as $book) {
38 $extension = $extensionByFormat[$exportFormat] ?? $exportFormat;
39 $content = apiGet("api/books/{$id}/export/{$exportFormat}");
40 $outPath = $outDir . "/{$book['slug']}.{$extension}";
41 file_put_contents($outPath, $content);
45 * Get all books from the system API.
47 function getAllBooks(): array {
54 $endpoint = 'api/books?' . http_build_query(['count' => $count, 'offset' => $offset]);
55 $resp = apiGetJson($endpoint);
57 $total = $resp['total'] ?? 0;
58 $newBooks = $resp['data'] ?? [];
59 array_push($allBooks, ...$newBooks);
61 } while ($offset < $total);
67 * Make a simple GET HTTP request to the API.
69 function apiGet(string $endpoint): string {
70 global $apiUrl, $clientId, $clientSecret;
71 $url = rtrim($apiUrl, '/') . '/' . ltrim($endpoint, '/');
72 $opts = ['http' => ['header' => "Authorization: Token {$clientId}:{$clientSecret}"]];
73 $context = stream_context_create($opts);
74 return file_get_contents($url, false, $context);
78 * Make a simple GET HTTP request to the API &
79 * decode the JSON response to an array.
81 function apiGetJson(string $endpoint): array {
82 $data = apiGet($endpoint);
83 return json_decode($data, true);
87 * DEBUG: Dump out the given variables and exit.
89 function dd(...$args) {
90 foreach ($args as $arg) {