179c7cb10c8e62b5f66088b5813ca02f079a3c7b
[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     // Fields from _meta.xml to add to response (if present)
30     var $metaFields = array(
31         'title' => 'title',
32         'author' => 'author',
33         'publisher' => 'publisher',
34         'date' => 'date',
35         'language' => 'language',
36         'contributor' => 'contributor',
37         'collection' => 'collection',
38         'page-progression' => 'pageProgression',
39     );
40     
41     var $metaDefaults = array(
42         'pageProgression' => 'lr',
43     );
44     
45     // Stash spot for callback data... where are closures when we need them?
46     static $cbData = NULL;
47
48     // Builds metadata object (to be encoded as JSON)
49     function buildMetadata($id, $itemPath, $subPrefix, $server) {
50     
51         $response = array();
52         
53         if ("" == $id) {
54             $this->BRFatal("No identifier specified!");
55         }
56         
57         if ("" == $itemPath) {
58             $this->BRFatal("No itemPath specified!");
59         }
60         
61         if ("" == $server) {
62             $this->BRFatal("No server specified!");
63         }
64         
65         if (!preg_match("|^/\d+/items/{$id}$|", $itemPath)) {
66             $this->BRFatal("Bad id!");
67         }
68         
69         $filesDataFile = "$itemPath/${id}_files.xml";
70         
71         if (file_exists($filesDataFile)) {
72             $filesData = simplexml_load_file("$itemPath/${id}_files.xml");
73         } else {
74             $this->BRfatal("File metadata not found!");
75         }
76         
77         $imageStackInfo = $this->findImageStack($subPrefix, $filesData);
78         if ($imageStackInfo['imageFormat'] == 'unknown') {
79             $this->BRfatal('Couldn\'t find image stack');
80         }
81         // Update subPrefix -> may have been autodetected
82         $subPrefix = $imageStackInfo['subPrefix'];
83         $subItemPath = $itemPath . '/' . $subPrefix;
84
85         
86         $imageFormat = $imageStackInfo['imageFormat'];
87         $archiveFormat = $imageStackInfo['archiveFormat'];
88         $imageStackFile = $itemPath . "/" . $imageStackInfo['imageStackFile'];
89         
90         if ("unknown" == $imageFormat) {
91           $this->BRfatal("Unknown image format");
92         }
93         
94         if ("unknown" == $archiveFormat) {
95           $this->BRfatal("Unknown archive format");
96         }
97         
98         
99         $scanDataFile = "${subItemPath}_scandata.xml";
100         $scanDataZip  = "$itemPath/scandata.zip";
101         if (file_exists($scanDataFile)) {
102             $this->checkPrivs($scanDataFile);
103             $scanData = simplexml_load_file($scanDataFile);
104         } else if (file_exists($scanDataZip)) {
105             $this->checkPrivs($scanDataZip);
106             $cmd  = 'unzip -p ' . escapeshellarg($scanDataZip) . ' scandata.xml';
107             exec($cmd, $output, $retval);
108             if ($retval != 0) {
109                 $this->BRFatal("Could not unzip ScanData!");
110             }
111             
112             $dump = join("\n", $output);
113             $scanData = simplexml_load_string($dump);
114         } else if (file_exists("$itemPath/scandata.xml")) {
115             // For e.g. Scribe v.0 books!
116             $scanData = simplexml_load_file("$itemPath/scandata.xml");
117         } else {
118             $this->BRFatal("ScanData file not found!");
119         }
120         
121         $metaDataFile = "$itemPath/{$id}_meta.xml";
122         if (!file_exists($metaDataFile)) {
123             $this->BRFatal("MetaData file not found!");
124         }
125         
126         
127         $metaData = simplexml_load_file($metaDataFile);
128         
129         /* Find pages by type */
130         $titleLeaf = '';
131         $coverLeafs = array();
132         foreach ($scanData->pageData->page as $page) {
133             if (("Title Page" == $page->pageType) || ("Title" == $page->pageType)) {
134                 if ('' == $titleLeaf) {
135                     // not already set
136                     $titleLeaf = "{$page['leafNum']}";
137                 }
138             }
139             
140             if (('Cover' == $page->pageType) || ('Cover Page' == $page->pageType)) {
141                 array_push($coverLeafs, $page['leafNum']);
142             }
143         }
144         
145         // These arrays map accessible page index numbers to width, height, scanned leaf numbers
146         // and page number strings (NB: these may not be unique)
147         $pageWidths = array();
148         $pageHeights = array();
149         $leafNums = array();
150         $i=0;
151         $totalHeight = 0;
152         foreach ($scanData->pageData->page as $page) {
153             if ($this->shouldAddPage($page)) {
154                 $pageWidths[$i] = intval($page->cropBox->w);
155                 $pageHeights[$i] = intval($page->cropBox->h);
156                 $totalHeight += intval($page->cropBox->h/4) + 10;
157                 $leafNums[$i] = intval($page['leafNum']);
158                 $pageNums[$i] = $page->pageNumber . '';
159                 $i++;
160             }
161         }
162                 
163         # Load some values from meta.xml
164         foreach ($this->metaFields as $srcName => $destName) {
165             if ($metaData->{$srcName}) {
166                 $response[$destName] = $metaData->{$srcName} . '';
167             } else {
168                 if (array_key_exists($destName, $this->metaDefaults)) {
169                     $response[$destName] = $this->metaDefaults[$destName];
170                 }
171             }
172         }
173         
174         // General metadata
175         $response['numPages'] = count($pageNums); // $$$ renamed    
176         if ('' != $titleLeaf) {
177             $response['titleLeaf'] = $titleLeaf; // $$$ change to titleIndex - do leaf mapping here
178             $titleIndex = $this->indexForLeaf($titleLeaf, $leafNums);
179             if ($titleIndex !== NULL) {
180                 $response['titleIndex'] = intval($titleIndex);
181             }
182         }
183         $response['url'] = "http://www.archive.org/details/$id";
184         $response['pageWidths'] = $pageWidths;
185         $response['pageHeights'] = $pageHeights;
186         $response['pageNums'] = $pageNums;
187         
188         // Internet Archive specific
189         $response['itemId'] = $id; // $$$ renamed
190         $response['subPrefix'] = $subPrefix;  // $$$ renamed
191         $response['itemPath'] = $itemPath;
192         $response['zip'] = $imageStackFile;
193         $response['server'] = $server;
194         $response['imageFormat'] = $imageFormat;
195         $response['archiveFormat'] = $archiveFormat;
196         $response['leafNums'] = $leafNums;
197         $response['previewImage'] = $this->previewURL('preview', $response);
198         
199         // URL to title image
200         if ('' != $titleLeaf) {
201             $response['titleImage'] = $this->previewURL('title', $response);
202         }
203         
204         if (count($coverLeafs) > 0) {
205             $coverIndices = array();
206             $coverImages = array();
207             foreach ($coverLeafs as $key => $leafNum) {
208                 array_push($coverIndices, $this->indexForLeaf($leafNum, $leafNums));
209                 // $$$ TODO use preview API once it supports multiple covers
210                 array_push($coverImages, $this->imageUrl($leafNum, $response));
211             }
212             
213             $response['coverIndices'] = $coverIndices;
214             $response['coverImages'] = $coverImages;
215         }
216                 
217         return $response;
218     }
219     
220     function emitResponse($metadata) {
221         $callback = $_REQUEST['callback'];
222         
223         $contentType = 'application/json'; // default
224         if ($callback) {
225             if (! $this->isValidCallback($callback) ) {
226                 $this->BRfatal("Invalid callback");
227             }
228             $contentType = 'text/javascript'; // JSONP is not JSON
229         }
230         
231         header('Content-type: ' . $contentType . ';charset=UTF-8');
232         header('Access-Control-Allow-Origin: *'); // allow cross-origin requests
233         
234         if ($callback) {
235             print $callback . '( ';
236         }
237         print json_encode($metadata);
238         if ($callback) {
239             print ' );';
240         }
241     }
242     
243     function BRFatal($string) {
244         // $$$ TODO log error
245         throw new Exception("Metadata error: $string");
246         //echo "alert('$string');\n";
247         //die(-1);
248     }
249     
250     // Returns true if a page should be added based on it's information in
251     // the metadata
252     function shouldAddPage($page) {
253         // Return false only if the page is marked addToAccessFormats false.
254         // If there is no assertion we assume it should be added.
255         if (isset($page->addToAccessFormats)) {
256             if ("false" == strtolower(trim($page->addToAccessFormats))) {
257                 return false;
258             }
259         }
260         
261         return true;
262     }
263     
264     // Returns { 'imageFormat' => , 'archiveFormat' => '} given a sub-item prefix and loaded xml data
265     function findImageStack($subPrefix, $filesData) {
266     
267         static $cbPrefix = NULL;
268     
269         // The order of the image formats determines which will be returned first
270         $imageFormats = array('JP2' => 'jp2', 'TIFF' => 'tif', 'JPEG' => 'jpg');
271         $imageFormatOrder = array_values($imageFormats);
272         $archiveFormats = array('ZIP' => 'zip', 'Tar' => 'tar');
273         $imageGroup = implode('|', array_keys($imageFormats));
274         $archiveGroup = implode('|', array_keys($archiveFormats));
275         // $$$ Currently only return processed images
276         $imageStackRegex = "/Single Page (Processed) (${imageGroup}) (${archiveGroup})/";
277
278         // Strategy:
279         //   - Find potential image stacks, regardless of subPrefix
280         //   - If not given subPrefix sort based on potential subPrefix and assign based on asciibetical first
281         //   - Filter results by subPrefix
282         //   - Sort based on image format
283         //   - Take best match
284
285         $imageStacks = array();
286         foreach ($filesData->file as $file) {
287             if ( preg_match($imageStackRegex, $file->format, $matches) === 1 ) {
288                 $imageFormat = $imageFormats[$matches[2]];
289                 $archiveFormat = $archiveFormats[$matches[3]];
290                 $imageStackFile = $file['name'] . '';
291                 
292                 if ( preg_match("#(.*)_${imageFormat}\.${archiveFormat}#", $imageStackFile, $matches) === 0) {
293                     // stack filename not regular
294                     continue;
295                 } else {
296                     array_push($imageStacks, array(
297                                                 'imageFormat' => $imageFormat,
298                                                 'archiveFormat' => $archiveFormat,
299                                                 'imageStackFile' => $imageStackFile,
300                                                 'subPrefix' => $matches[1])
301                     );
302                 }
303
304             }
305         }
306
307         /*
308         print("<pre>");
309         print("found subPrefix $subPrefix\n");
310         print_r($imageStacks);
311         */
312         
313         function subPrefixSort($imageStackA, $imageStackB) {
314             if ($imageStackA['subPrefix'] == $imageStackB['subPrefix']) {
315                 return 0;
316             }
317             return ($imageStackA['subPrefix'] < $imageStackB['subPrefix']) ? -1 : 1;
318         }
319         if (! $subPrefix) {
320             usort($imageStacks, 'subPrefixSort');
321             $subPrefix = $imageStacks[0]['subPrefix'];
322         }
323         
324         self::$cbData = $subPrefix;
325         function subPrefixFilter($imageStack) {
326             return $imageStack['subPrefix'] == BookReaderMeta::$cbData;
327         }
328         $imageStacks = array_filter($imageStacks, 'subPrefixFilter');
329                 
330         function formatSort($imageStackA, $imageStackB) {
331             $formatA = $imageStackA['imageFormat'];
332             $formatB = $imageStackB['imageFormat'];
333             if ($formatA == $formatB) {
334                 return 0;
335             }
336             
337             $indexA = array_search($formatA, $imageFormatOrder);
338             $indexB = array_search($formatB, $imageFormatOrder);
339             // We already matched base on format, so both indices should be set
340             if ($indexA == $indexB) {
341                 return 0;
342             }
343             return ($indexA < $indexB) ? 1 : -1;
344         }
345         usort($imageStacks, 'formatSort'); // necessary to remap keys
346         
347         if ( count($imageStacks) > 0 ) {
348             return $imageStacks[0];
349         } else {
350             return array('imageFormat' => 'unknown', 'archiveFormat' => 'unknown', 'imageStackFile' => 'unknown');
351         }
352     }
353     
354     function isValidCallback($identifier) {
355         $pattern = '/^[a-zA-Z_$][a-zA-Z0-9_$]*$/';
356         return preg_match($pattern, $identifier) == 1;
357     }
358     
359     function indexForLeaf($leafNum, $leafNums) {
360         $key = array_search($leafNum, $leafNums);
361         if ($key === FALSE) {
362             return NULL;
363         } else {
364             return $key;
365         }
366     }
367     
368     function leafForIndex($index, $leafNums) {
369         return $leafNums[$index]; // $$$ todo change to instance variables
370     }
371     
372     function imageURL($leafNum, $metadata, $scale = null, $rotate = null) {
373         // "Under the hood", non-public, dynamically changing (achtung!) image URLs currently look like:
374         // http://{server}/BookReader/BookReaderImages.php?zip={zipPath}&file={filePath}&scale={scale}&rotate={rotate}
375         // 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
376         
377     
378         $filePath = $this->imageFilePath($leafNum, $metadata['subPrefix'], $metadata['imageFormat']);
379         $url = 'http://' . $metadata['server'] . '/BookReader/BookReaderImages.php?zip=' . $metadata['zip'] . '&file=' . $filePath;
380         
381         if ($scale !== null) {
382             $url .= '&scale=' . $scale;
383         }
384         if ($rotate !== null) {
385             $url .= '&rotate=' . $rotate;
386         }
387         
388         return $url;
389     }
390     
391     // $$$ move inside BookReaderPreview
392     function previewURL($page, $metadata) {
393         $query = array(
394             'id' => $metadata['itemId'],
395             'subPrefix' => $metadata['subPrefix'],
396             'itemPath' => $metadata['itemPath'],
397             'server' => $metadata['server'],
398             'page' => $page,
399         );
400         
401         return 'http://' . $metadata['server'] . '/BookReader/BookReaderPreview.php?' . http_build_query($query, '', '&');
402     }
403     
404     function imageFilePath($leafNum, $subPrefix, $format) {
405         $pathParts = pathinfo($subPrefix);
406         $almostIdentifier = $pathParts['filename'];
407         return sprintf("%s_%s/%s_%04d.%s", $almostIdentifier, $format, $almostIdentifier, intval($leafNum), $format);
408     }
409     
410     // Parse date from _meta.xml to integer
411     function parseYear($dateFromMetaXML) {
412         // grab the first run of digits
413         if (preg_match('|(\d+)|', $dateFromMetaXML, $matches)) {
414             return (int)$matches[1];
415         }
416         return null;
417     }
418     
419     function processRequest($requestEnv) {
420         $id = $requestEnv['itemId']; // $$$ renamed
421         $itemPath = $requestEnv['itemPath'];
422         $subPrefix = $requestEnv['subPrefix']; // $$$ renamed
423         $server = $requestEnv['server'];
424         
425         // Check if we're on a dev vhost and point to JSIA in the user's public_html on the datanode
426         // $$$ TODO consolidate this logic
427         if (strpos($_SERVER["REQUEST_URI"], "/~mang") === 0) { // Serving out of home dir
428             $server .= ':80/~mang';
429         } else if (strpos($_SERVER["REQUEST_URI"], "/~testflip") === 0) { // Serving out of home dir
430             $server .= ':80/~testflip';
431         }
432         
433         $this->emitResponse( $this->buildMetadata($id, $itemPath, $subPrefix, $server) );
434     }
435     
436     function checkPrivs($filename) {
437         if (!is_readable($filename)) {
438             header('HTTP/1.1 403 Forbidden');
439             exit(0);
440         }
441     }
442
443 }
444
445 ?>