3 Copyright(c)2008 Internet Archive. Software license AGPL version 3.
5 This file is part of BookReader.
7 BookReader is free software: you can redistribute it and/or modify
8 it under the terms of the GNU Affero General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 BookReader is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU Affero General Public License for more details.
17 You should have received a copy of the GNU Affero General Public License
18 along with BookReader. If not, see <http://www.gnu.org/licenses/>.
21 $id = $_REQUEST['id'];
22 $itemPath = $_REQUEST['itemPath'];
23 $subPrefix = $_REQUEST['subPrefix'];
24 $server = $_REQUEST['server'];
26 // $$$mang this code has been refactored into BookReaderMeta.inc.php for use e.g. by
27 // BookReaderPreview.php and BookReaderImages.php. The code below should be
28 // taken out and replaced by calls into BookReaderMeta
30 // Check if we're on a dev vhost and point to JSIA in the user's public_html on the datanode
32 // $$$ TODO consolidate this logic
33 if (strpos($_SERVER["REQUEST_URI"], "/~mang") === 0) { // Serving out of home dir
34 $server .= ':80/~mang';
35 } else if (strpos($_SERVER["REQUEST_URI"], "/~rkumar") === 0) { // Serving out of home dir
36 $server .= ':80/~rkumar';
37 } else if (strpos($_SERVER["REQUEST_URI"], "/~testflip") === 0) { // Serving out of home dir
38 $server .= ':80/~testflip';
44 $subItemPath = $itemPath . '/' . $subPrefix;
47 BRFatal("No identifier specified!");
50 if ("" == $itemPath) {
51 BRFatal("No itemPath specified!");
55 BRFatal("No server specified!");
58 if (!preg_match("|^/\d+/items/{$id}$|", $itemPath)) {
62 // XXX check here that subitem is okay
64 $filesDataFile = "$itemPath/${id}_files.xml";
66 if (file_exists($filesDataFile)) {
67 $filesData = simplexml_load_file("$itemPath/${id}_files.xml");
69 BRfatal("File metadata not found!");
72 $imageStackInfo = findImageStack($subPrefix, $filesData);
73 if ($imageStackInfo['imageFormat'] == 'unknown') {
74 BRfatal('Couldn\'t find image stack');
77 $imageFormat = $imageStackInfo['imageFormat'];
78 $archiveFormat = $imageStackInfo['archiveFormat'];
79 $imageStackFile = $itemPath . "/" . $imageStackInfo['imageStackFile'];
81 if ("unknown" == $imageFormat) {
82 BRfatal("Unknown image format");
85 if ("unknown" == $archiveFormat) {
86 BRfatal("Unknown archive format");
90 $scanDataFile = "${subItemPath}_scandata.xml";
91 $scanDataZip = "$itemPath/scandata.zip";
92 if (file_exists($scanDataFile)) {
93 $scanData = simplexml_load_file($scanDataFile);
94 } else if (file_exists($scanDataZip)) {
95 $cmd = 'unzip -p ' . escapeshellarg($scanDataZip) . ' scandata.xml';
96 exec($cmd, $output, $retval);
97 if ($retval != 0) BRFatal("Could not unzip ScanData!");
99 $dump = join("\n", $output);
100 $scanData = simplexml_load_string($dump);
101 } else if (file_exists("$itemPath/scandata.xml")) {
102 // For e.g. Scribe v.0 books!
103 $scanData = simplexml_load_file("$itemPath/scandata.xml");
105 BRFatal("ScanData file not found!");
108 $metaDataFile = "$itemPath/{$id}_meta.xml";
109 if (!file_exists($metaDataFile)) {
110 BRFatal("MetaData file not found!");
114 $metaData = simplexml_load_file($metaDataFile);
116 //$firstLeaf = $scanData->pageData->page[0]['leafNum'];
119 br = new BookReader();
122 /* Output title leaf if marked */
124 foreach ($scanData->pageData->page as $page) {
125 if (("Title Page" == $page->pageType) || ("Title" == $page->pageType)) {
126 $titleLeaf = "{$page['leafNum']}";
131 if ('' != $titleLeaf) {
132 printf("br.titleLeaf = %d;\n", $titleLeaf);
136 br.getPageWidth = function(index) {
137 return this.pageW[index];
140 br.getPageHeight = function(index) {
141 return this.pageH[index];
144 // Returns true if page image is available rotated
145 br.canRotatePage = function(index) {
146 return 'jp2' == this.imageFormat; // Assume single format for now
149 // reduce defaults to 1 (no reduction)
150 // rotate defaults to 0 (no rotation)
151 br.getPageURI = function(index, reduce, rotate) {
155 if ('undefined' == typeof(reduce)) {
160 if ('undefined' == typeof(rotate)) {
166 var file = this._getPageFile(index);
168 // $$$ add more image stack formats here
169 return 'http://'+this.server+'/BookReader/BookReaderImages.php?zip='+this.zip+'&file='+file+'&scale='+_reduce+'&rotate='+_rotate;
172 br._getPageFile = function(index) {
173 var leafStr = '0000';
174 var imgStr = this.leafMap[index].toString();
175 var re = new RegExp("0{"+imgStr.length+"}$");
177 var insideZipPrefix = this.subPrefix.match('[^/]+$');
178 var file = insideZipPrefix + '_' + this.imageFormat + '/' + insideZipPrefix + '_' + leafStr.replace(re, imgStr) + '.' + this.imageFormat;
183 br.getPageSide = function(index) {
184 //assume the book starts with a cover (right-hand leaf)
185 //we should really get handside from scandata.xml
187 <? // Use special function if we should infer the page sides based off the title page index
188 if (preg_match('/goog$/', $id) && ('' != $titleLeaf)) {
190 // assume page side based on title pagex
191 var titleIndex = br.leafNumToIndex(br.titleLeaf);
192 // assume title page is RHS
193 var delta = titleIndex - index;
194 if (0 == (delta & 0x1)) {
204 // $$$ we should get this from scandata instead of assuming the accessible
205 // leafs are contiguous
206 if ('rl' != this.pageProgression) {
207 // If pageProgression is not set RTL we assume it is LTR
208 if (0 == (index & 0x1)) {
209 // Even-numbered page
217 if (0 == (index & 0x1)) {
225 br.getPageNum = function(index) {
226 var pageNum = this.pageNums[index];
234 // Single images in the Internet Archive scandata.xml metadata are (somewhat incorrectly)
235 // given a "leaf" number. Some of these images from the scanning process should not
236 // be displayed in the BookReader (for example colour calibration cards). Since some
237 // of the scanned images will not be displayed in the BookReader (those marked with
238 // addToAccessFormats false in the scandata.xml) leaf numbers and BookReader page
239 // indexes are generally not the same. This function returns the BookReader page
240 // index given a scanned leaf number.
242 // This function is used, for example, to map between search results (that use the
243 // leaf numbers) and the displayed pages in the BookReader.
244 br.leafNumToIndex = function(leafNum) {
245 for (var index = 0; index < this.leafMap.length; index++) {
246 if (this.leafMap[index] == leafNum) {
254 // This function returns the left and right indices for the user-visible
255 // spread that contains the given index. The return values may be
256 // null if there is no facing page or the index is invalid.
257 br.getSpreadIndices = function(pindex) {
258 // $$$ we could make a separate function for the RTL case and
259 // only bind it if necessary instead of always checking
260 // $$$ we currently assume there are no gaps
262 var spreadIndices = [null, null];
263 if ('rl' == this.pageProgression) {
265 if (this.getPageSide(pindex) == 'R') {
266 spreadIndices[1] = pindex;
267 spreadIndices[0] = pindex + 1;
269 // Given index was LHS
270 spreadIndices[0] = pindex;
271 spreadIndices[1] = pindex - 1;
275 if (this.getPageSide(pindex) == 'L') {
276 spreadIndices[0] = pindex;
277 spreadIndices[1] = pindex + 1;
279 // Given index was RHS
280 spreadIndices[1] = pindex;
281 spreadIndices[0] = pindex - 1;
285 //console.log(" index %d mapped to spread %d,%d", pindex, spreadIndices[0], spreadIndices[1]);
287 return spreadIndices;
290 // Remove the page number assertions for all but the highest index page with
291 // a given assertion. Ensures there is only a single page "{pagenum}"
292 // e.g. the last page asserted as page 5 retains that assertion.
293 br.uniquifyPageNums = function() {
296 for (var i = br.pageNums.length - 1; i--; i >= 0) {
297 var pageNum = br.pageNums[i];
298 if ( !seen[pageNum] ) {
299 seen[pageNum] = true;
301 br.pageNums[i] = null;
307 br.cleanupMetadata = function() {
308 br.uniquifyPageNums();
313 // Returns a URL for an embedded version of the current book
314 br.getEmbedURL = function() {
315 // We could generate a URL hash fragment here but for now we just leave at defaults
316 var url = 'http://' + window.location.host + '/stream/'+this.bookId;
317 if (this.subPrefix != this.bookId) { // Only include if needed
318 url += '/' + this.subPrefix;
326 // Returns the embed code HTML fragment suitable for copy and paste
327 br.getEmbedCode = function() {
328 return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
331 // getOpenLibraryJSON
332 br.getOpenLibraryJSON = function(callback) {
333 // Try looking up by ocaid first, then by source_record
335 var jsonURL = 'http://openlibrary.org/query.json?type=/type/edition&*=&ocaid=' + br.bookId;
338 success: function(data) {
339 if (data && data.length > 0) {
343 console.log('XXXmang couldnt find via ocaid');
344 jsonURL = 'http://openlibrary.org/query.json?type=/type/edition&*=&source_records=ia:' + br.bookId;
347 success: function(data) {
348 if (data && data.length > 0) {
363 foreach ($scanData->pageData->page as $page) {
364 if (shouldAddPage($page)) {
365 if(0 != $i) echo ","; //stupid IE
366 echo "{$page->cropBox->w}";
377 foreach ($scanData->pageData->page as $page) {
378 if (shouldAddPage($page)) {
379 if(0 != $i) echo ","; //stupid IE
380 echo "{$page->cropBox->h}";
381 $totalHeight += intval($page->cropBox->h/4) + 10;
390 foreach ($scanData->pageData->page as $page) {
391 if (shouldAddPage($page)) {
392 if(0 != $i) echo ","; //stupid IE
393 echo "{$page['leafNum']}";
403 foreach ($scanData->pageData->page as $page) {
404 if (shouldAddPage($page)) {
405 if(0 != $i) echo ","; //stupid IE
406 if (array_key_exists('pageNumber', $page) && ('' != $page->pageNumber)) {
407 echo "'{$page->pageNumber}'";
418 br.numLeafs = br.pageW.length;
420 br.bookId = '<?echo $id;?>';
421 br.zip = '<?echo $imageStackFile;?>';
422 br.subPrefix = '<?echo $subPrefix;?>';
423 br.server = '<?echo $server;?>';
424 br.bookTitle= '<?echo preg_replace("/\'/", "\\'", $metaData->title);?>';
425 br.bookPath = '<?echo $subItemPath;?>';
426 br.bookUrl = '<?echo "http://www.archive.org/details/$id";?>';
427 br.imageFormat = '<?echo $imageFormat;?>';
428 br.archiveFormat = '<?echo $archiveFormat;?>';
432 # Load some values from meta.xml
433 if ('' != $metaData->{'page-progression'}) {
434 echo "br.pageProgression = '" . $metaData->{"page-progression"} . "';";
436 // Assume page progression is Left To Right
437 echo "br.pageProgression = 'lr';";
441 if ('bandersnatchhsye00scarrich' == $id) {
442 echo "br.mode = 2;\n";
443 echo "br.auto = true;\n";
448 // Check for config object
449 // $$$ change this to use the newer params object
450 if (typeof(brConfig) != 'undefined') {
451 if (typeof(brConfig["ui"]) != 'undefined') {
452 br.ui = brConfig["ui"];
455 if (brConfig['mode'] == 1) {
457 if (typeof(brConfig['reduce'] != 'undefined')) {
458 br.reduce = brConfig['reduce'];
460 } else if (brConfig['mode'] == 2) {
464 //$$$mang hack to override request for 2up for books with attribution page
465 // as first page until we can display that page in 2up
467 if (strrpos($id, $needle) === strlen($id)-strlen($needle)) {
468 print "// override for books with attribution page\n";
469 print "br.mode = 1;\n";
475 br.cleanupMetadata();
481 function BRFatal($string) {
482 // $$$ TODO log error
483 echo "alert('$string')\n";
487 // Returns true if a page should be added based on it's information in
489 function shouldAddPage($page) {
490 // Return false only if the page is marked addToAccessFormats false.
491 // If there is no assertion we assume it should be added.
492 if (isset($page->addToAccessFormats)) {
493 if ("false" == strtolower(trim($page->addToAccessFormats))) {
501 // Returns { 'imageFormat' => , 'archiveFormat' => '} given a sub-item prefix and loaded xml data
502 function findImageStack($subPrefix, $filesData) {
504 // $$$ The order of the image formats determines which will be returned first
505 $imageFormats = array('JP2' => 'jp2', 'TIFF' => 'tif', 'JPEG' => 'jpg');
506 $archiveFormats = array('ZIP' => 'zip', 'Tar' => 'tar');
507 $imageGroup = implode('|', array_keys($imageFormats));
508 $archiveGroup = implode('|', array_keys($archiveFormats));
509 // $$$ Currently only return processed images
510 $imageStackRegex = "/Single Page (Processed) (${imageGroup}) (${archiveGroup})/";
512 foreach ($filesData->file as $file) {
513 if (strpos($file['name'], $subPrefix) === 0) { // subprefix matches beginning
514 if (preg_match($imageStackRegex, $file->format, $matches)) {
516 // Make sure we have a regular image stack
517 $imageFormat = $imageFormats[$matches[2]];
518 if (strpos($file['name'], $subPrefix . '_' . $imageFormat) === 0) {
519 return array('imageFormat' => $imageFormat,
520 'archiveFormat' => $archiveFormats[$matches[3]],
521 'imageStackFile' => $file['name']);
527 return array('imageFormat' => 'unknown', 'archiveFormat' => 'unknown', 'imageStackFile' => 'unknown');