First pass at BookReaderPreview.php -- provides access to preview images
[bookreader.git] / BookReaderIA / datanode / BookReaderMeta.inc.php
1 <?
2 /*
3
4 Builds metadata about a book on the Internet Archive in json(p) format so that the book
5 can be accessed by other software including the Internet Archive BookReader.
6
7 Michael Ang <http://github.com/mangtronix>
8
9 Copyright (c) 2008-2010 Internet Archive. Software license AGPL version 3.
10
11 This file is part of BookReader.
12
13     BookReader is free software: you can redistribute it and/or modify
14     it under the terms of the GNU Affero General Public License as published by
15     the Free Software Foundation, either version 3 of the License, or
16     (at your option) any later version.
17
18     BookReader is distributed in the hope that it will be useful,
19     but WITHOUT ANY WARRANTY; without even the implied warranty of
20     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21     GNU Affero General Public License for more details.
22
23     You should have received a copy of the GNU Affero General Public License
24     along with BookReader.  If not, see <http://www.gnu.org/licenses/>.
25 */
26
27 class BookReaderMeta {
28
29     // Builds metadata object (to be encoded as JSON)
30     function buildMetadata($id, $itemPath, $bookId, $server) {
31     
32         $response = array();
33         
34         if (! $subPrefix) {
35             $subPrefix = $id;
36         }
37         $subItemPath = $itemPath . '/' . $subPrefix;
38         
39         if ("" == $id) {
40             $this->BRFatal("No identifier specified!");
41         }
42         
43         if ("" == $itemPath) {
44             $this->BRFatal("No itemPath specified!");
45         }
46         
47         if ("" == $server) {
48             $this->BRFatal("No server specified!");
49         }
50         
51         if (!preg_match("|^/\d+/items/{$id}$|", $itemPath)) {
52             $this->BRFatal("Bad id!");
53         }
54         
55         // XXX check here that subitem is okay
56         
57         $filesDataFile = "$itemPath/${id}_files.xml";
58         
59         if (file_exists($filesDataFile)) {
60             $filesData = simplexml_load_file("$itemPath/${id}_files.xml");
61         } else {
62             $this->BRfatal("File metadata not found!");
63         }
64         
65         $imageStackInfo = $this->findImageStack($subPrefix, $filesData);
66         if ($imageStackInfo['imageFormat'] == 'unknown') {
67             $this->BRfatal('Couldn\'t find image stack');
68         }
69         
70         $imageFormat = $imageStackInfo['imageFormat'];
71         $archiveFormat = $imageStackInfo['archiveFormat'];
72         $imageStackFile = $itemPath . "/" . $imageStackInfo['imageStackFile'];
73         
74         if ("unknown" == $imageFormat) {
75           $this->BRfatal("Unknown image format");
76         }
77         
78         if ("unknown" == $archiveFormat) {
79           $this->BRfatal("Unknown archive format");
80         }
81         
82         
83         $scanDataFile = "${subItemPath}_scandata.xml";
84         $scanDataZip  = "$itemPath/scandata.zip";
85         if (file_exists($scanDataFile)) {
86             $scanData = simplexml_load_file($scanDataFile);
87         } else if (file_exists($scanDataZip)) {
88             $cmd  = 'unzip -p ' . escapeshellarg($scanDataZip) . ' scandata.xml';
89             exec($cmd, $output, $retval);
90             if ($retval != 0) {
91                 $this->BRFatal("Could not unzip ScanData!");
92             }
93             
94             $dump = join("\n", $output);
95             $scanData = simplexml_load_string($dump);
96         } else if (file_exists("$itemPath/scandata.xml")) {
97             // For e.g. Scribe v.0 books!
98             $scanData = simplexml_load_file("$itemPath/scandata.xml");
99         } else {
100             $this->BRFatal("ScanData file not found!");
101         }
102         
103         $metaDataFile = "$itemPath/{$id}_meta.xml";
104         if (!file_exists($metaDataFile)) {
105             $this->BRFatal("MetaData file not found!");
106         }
107         
108         
109         $metaData = simplexml_load_file($metaDataFile);
110         
111         /* Find pages by type */
112         $titleLeaf = '';
113         $coverLeafs = array();
114         foreach ($scanData->pageData->page as $page) {
115             if (("Title Page" == $page->pageType) || ("Title" == $page->pageType)) {
116                 if ('' == $titleLeaf) {
117                     // not already set
118                     $titleLeaf = "{$page['leafNum']}";
119                 }
120             }
121             
122             if (('Cover' == $page->pageType) || ('Cover Page' == $page->pageType)) {
123                 array_push($coverLeafs, $page['leafNum']);
124             }
125         }
126         
127         // These arrays map accessible page index numbers to width, height, scanned leaf numbers
128         // and page number strings (NB: these may not be unique)
129         $pageWidths = array();
130         $pageHeights = array();
131         $leafNums = array();
132         $i=0;
133         $totalHeight = 0;
134         foreach ($scanData->pageData->page as $page) {
135             if ($this->shouldAddPage($page)) {
136                 $pageWidths[$i] = intval($page->cropBox->w);
137                 $pageHeights[$i] = intval($page->cropBox->h);
138                 $totalHeight += intval($page->cropBox->h/4) + 10;
139                 $leafNums[$i] = intval($page['leafNum']);
140                 $pageNums[$i] = $page->pageNumber . '';
141                 $i++;
142             }
143         }
144                 
145         # Load some values from meta.xml
146         $pageProgression = 'lr'; // default
147         if ('' != $metaData->{'page-progression'}) {
148           $pageProgression = $metaData->{"page-progression"};
149         }
150         
151         // General metadata
152         $response['title'] = $metaData->title . ''; // XXX renamed
153         $response['numPages'] = count($pageNums); // XXX renamed    
154         if ('' != $titleLeaf) {
155             $response['titleLeaf'] = $titleLeaf; // XXX change to titleIndex - do leaf mapping here
156             $titleIndex = $this->indexForLeaf($titleLeaf, $leafNums);
157             if ($titleIndex !== NULL) {
158                 $response['titleIndex'] = intval($titleIndex);
159             }
160         }
161         $response['url'] = "http://www.archive.org/details/$id";
162         $response['pageProgression'] = $pageProgression . '';
163         $response['pageWidths'] = $pageWidths;
164         $response['pageHeights'] = $pageHeights;
165         $response['pageNums'] = $pageNums;
166         
167         // Internet Archive specific
168         $response['itemId'] = $id; // XXX renamed
169         $response['bookId'] = $subPrefix;  // XXX renamed
170         $response['zip'] = $imageStackFile;
171         $response['server'] = $server;
172         $response['imageFormat'] = $imageFormat;
173         $response['archiveFormat'] = $archiveFormat;
174         $response['leafNums'] = $leafNums;
175         
176         // URL to title image
177         if ('' != $titleLeaf) {
178             $response['titleImage'] = $this->imageURL($titleLeaf, $response);
179         }
180         
181         if (count($coverLeafs) > 0) {
182             $coverIndices = array();
183             $coverImages = array();
184             foreach ($coverLeafs as $key => $leafNum) {
185                 array_push($coverIndices, $this->indexForLeaf($leafNum, $leafNums));
186                 array_push($coverImages, $this->imageUrl($leafNum, $response));
187             }
188             
189             $response['coverIndices'] = $coverIndices;
190             $response['coverImages'] = $coverImages;
191         }
192         
193         // Determine "preview" image, which may be the cover, title, or first page
194         if (array_key_exists('titleImage', $response)) {
195             // Use title image if was assert
196             $previewImage = $response['titleImage'];
197         } else if (array_key_exists('coverImages', $response)) {
198             // Try for the cover page
199             $previewImage = $response['coverImages'][0];
200         } else {
201             // Neither title nor cover asserted, use first page
202             $previewImage = $this->imageURL(0, $response);
203         }
204         $response['previewImage'] = $previewImage;
205         
206         return $response;
207     }
208     
209     function emitResponse($metadata) {
210         $callback = $_REQUEST['callback'];
211         
212         $contentType = 'application/json'; // default
213         if ($callback) {
214             if (! $this->isValidCallback($callback) ) {
215                 $this->BRfatal("Invalid callback");
216             }
217             $contentType = 'text/javascript'; // JSONP is not JSON
218         }
219         
220         header('Content-type: ' . $contentType . ';charset=UTF-8');
221         header('Access-Control-Allow-Origin: *'); // allow cross-origin requests
222         
223         if ($callback) {
224             print $callback . '( ';
225         }
226         print json_encode($metadata);
227         if ($callback) {
228             print ' );';
229         }
230     }
231     
232     function BRFatal($string) {
233         // $$$ TODO log error
234         echo "alert('$string');\n";
235         die(-1);
236     }
237     
238     // Returns true if a page should be added based on it's information in
239     // the metadata
240     function shouldAddPage($page) {
241         // Return false only if the page is marked addToAccessFormats false.
242         // If there is no assertion we assume it should be added.
243         if (isset($page->addToAccessFormats)) {
244             if ("false" == strtolower(trim($page->addToAccessFormats))) {
245                 return false;
246             }
247         }
248         
249         return true;
250     }
251     
252     // Returns { 'imageFormat' => , 'archiveFormat' => '} given a sub-item prefix and loaded xml data
253     function findImageStack($subPrefix, $filesData) {
254     
255         // $$$ The order of the image formats determines which will be returned first
256         $imageFormats = array('JP2' => 'jp2', 'TIFF' => 'tif', 'JPEG' => 'jpg');
257         $archiveFormats = array('ZIP' => 'zip', 'Tar' => 'tar');
258         $imageGroup = implode('|', array_keys($imageFormats));
259         $archiveGroup = implode('|', array_keys($archiveFormats));
260         // $$$ Currently only return processed images
261         $imageStackRegex = "/Single Page (Processed) (${imageGroup}) (${archiveGroup})/";
262             
263         foreach ($filesData->file as $file) {        
264             if (strpos($file['name'], $subPrefix) === 0) { // subprefix matches beginning
265                 if (preg_match($imageStackRegex, $file->format, $matches)) {
266                 
267                     // Make sure we have a regular image stack
268                     $imageFormat = $imageFormats[$matches[2]];
269                     if (strpos($file['name'], $subPrefix . '_' . $imageFormat) === 0) {            
270                         return array('imageFormat' => $imageFormat,
271                                      'archiveFormat' => $archiveFormats[$matches[3]],
272                                      'imageStackFile' => $file['name']);
273                     }
274                 }
275             }
276         }
277         
278         return array('imageFormat' => 'unknown', 'archiveFormat' => 'unknown', 'imageStackFile' => 'unknown');    
279     }
280     
281     function isValidCallback($identifier) {
282         $pattern = '/^[a-zA-Z_$][a-zA-Z0-9_$]*$/';
283         return preg_match($pattern, $identifier) == 1;
284     }
285     
286     function indexForLeaf($leafNum, $leafNums) {
287         $key = array_search($leafNum, $leafNums);
288         if ($key === FALSE) {
289             return NULL;
290         } else {
291             return $key;
292         }
293     }
294     
295     function imageURL($leafNum, $metadata, $scale, $rotate) {
296         // "Under the hood", non-public, dynamically changing (achtung!) image URLs currently look like:
297         // http://{server}/BookReader/BookReaderImages.php?zip={zipPath}&file={filePath}&scale={scale}&rotate={rotate}
298         // e.g. http://ia311213.us.archive.org/BookReader/BookReaderImages.php?zip=/0/items/coloritsapplicat00andriala/coloritsapplicat00andriala_jp2.zip&file=coloritsapplicat00andriala_jp2/coloritsapplicat00andriala_0009.jp2&scale=8&rotate=0
299         
300     
301         $filePath = $this->imageFilePath($leafNum, $metadata['bookId'], $metadata['imageFormat']);
302         $url = 'http://' . $metadata['server'] . '/BookReader/BookReaderImages.php?zip=' . $metadata['zip'] . '&file=' . $filePath;
303         
304         if (defined($scale)) {
305             $url .= '&scale=' . $scale;
306         }
307         if (defined($rotate)) {
308             $url .= '&rotate=' . $rotate;
309         }
310         
311         return $url;
312     }
313     
314     function imageFilePath($leafNum, $bookId, $format) {
315         return sprintf("%s_%s/%s_%04d.%s", $bookId, $format, $bookId, intval($leafNum), $format);
316     }
317     
318     function processRequest($requestEnv) {
319         $id = $requestEnv['itemId']; // XXX renamed
320         $itemPath = $requestEnv['itemPath'];
321         $bookId = $requestEnv['bookId']; // XXX renamed
322         $server = $requestEnv['server'];
323         
324         // Check if we're on a dev vhost and point to JSIA in the user's public_html on the datanode
325         // $$$ TODO consolidate this logic
326         if (strpos($_SERVER["REQUEST_URI"], "/~mang") === 0) { // Serving out of home dir
327             $server .= ':80/~mang';
328         } else if (strpos($_SERVER["REQUEST_URI"], "/~testflip") === 0) { // Serving out of home dir
329             $server .= ':80/~testflip';
330         }
331         
332         $this->emitResponse( $this->buildMetadata($id, $itemPath, $bookId, $server) );
333     }
334 }
335
336 ?>