]> BookStack Code Mirror - api-scripts/blob - php-export-all-books/export-books.php
Added export-all-books example
[api-scripts] / php-export-all-books / export-books.php
1 #!/usr/bin/env php
2 <?php
3
4 // API Credentials
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') ?: '';
10
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] ?? './';
16
17 // Script logic
18 ////////////////
19
20 $books = getAllBooks();
21 $outDir = realpath($exportLocation);
22
23 $extensionByFormat = [
24     'pdf' => 'pdf',
25     'html' => 'html',
26     'plaintext' => 'txt',
27 ];
28
29 foreach ($books as $book) {
30     $id = $book['id'];
31     $extension = $extensionByFormat[$exportFormat] ?? $exportFormat;
32     $content = apiGet("api/books/{$id}/export/{$exportFormat}");
33     $outPath = $outDir  . "/{$book['slug']}.{$extension}";
34     file_put_contents($outPath, $content);
35 }
36
37 /**
38  * Get all books from the system API.
39  */
40 function getAllBooks() {
41     $count = 100;
42     $offset = 0;
43     $total = 0;
44     $allBooks = [];
45
46     do {
47         $endpoint = 'api/books?' . http_build_query(['count' => $count, 'offset' => $offset]);
48         $resp = apiGetJson($endpoint);
49
50         // Only set total on first request, due to API bug:
51         // https://github.com/BookStackApp/BookStack/issues/2043
52         if ($offset == 0) {
53             $total = $resp['total'] ?? 0;
54         }
55
56         $newBooks = $resp['data'] ?? [];
57         array_push($allBooks, ...$newBooks);
58         $offset += $count;
59     } while ($offset < $total);
60
61     return $allBooks;
62 }
63
64 /**
65  * Make a simple GET HTTP request to the API.
66  */
67 function apiGet(string $endpoint): string {
68     global $apiUrl, $clientId, $clientSecret;
69     $url = rtrim($apiUrl, '/') . '/' . ltrim($endpoint, '/');
70     $opts = ['http' => ['header' => "Authorization: Token {$clientId}:{$clientSecret}"]];
71     $context = stream_context_create($opts);
72     return file_get_contents($url, false, $context);
73 }
74
75 /**
76  * Make a simple GET HTTP request to the API &
77  * decode the JSON response to an array.
78  */
79 function apiGetJson(string $endpoint): array {
80     $data = apiGet($endpoint);
81     return json_decode($data, true);
82 }
83
84 /**
85  * DEBUG: Dump out the given variables and exit.
86  */
87 function dd(...$args) {
88     foreach ($args as $arg) {
89         var_dump($arg);
90     }
91     exit(1);
92 }