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 header('Content-Type: application/javascript');
23 $id = $_REQUEST['id'];
24 $itemPath = $_REQUEST['itemPath'];
25 $subPrefix = $_REQUEST['subPrefix'];
26 $server = $_REQUEST['server'];
28 // $$$mang this code has been refactored into BookReaderMeta.inc.php for use e.g. by
29 // BookReaderPreview.php and BookReaderImages.php. The code below should be
30 // taken out and replaced by calls into BookReaderMeta
32 // Check if we're on a dev vhost and point to JSIA in the user's public_html on the datanode
34 // $$$ TODO consolidate this logic
35 if (strpos($_SERVER["REQUEST_URI"], "/~mang") === 0) { // Serving out of home dir
36 $server .= ':80/~mang';
37 } else if (strpos($_SERVER["REQUEST_URI"], "/~rkumar") === 0) { // Serving out of home dir
38 $server .= ':80/~rkumar';
39 } else if (strpos($_SERVER["REQUEST_URI"], "/~testflip") === 0) { // Serving out of home dir
40 $server .= ':80/~testflip';
46 $subItemPath = $itemPath . '/' . $subPrefix;
49 BRFatal("No identifier specified!");
52 if ("" == $itemPath) {
53 BRFatal("No itemPath specified!");
57 BRFatal("No server specified!");
60 if (!preg_match("|^/\d+/items/{$id}$|", $itemPath)) {
64 // XXX check here that subitem is okay
66 $filesDataFile = "$itemPath/${id}_files.xml";
68 if (file_exists($filesDataFile)) {
69 $filesData = simplexml_load_file("$itemPath/${id}_files.xml");
71 BRfatal("File metadata not found!");
74 $imageStackInfo = findImageStack($subPrefix, $filesData);
75 if ($imageStackInfo['imageFormat'] == 'unknown') {
76 BRfatal('Couldn\'t find image stack');
79 $imageFormat = $imageStackInfo['imageFormat'];
80 $archiveFormat = $imageStackInfo['archiveFormat'];
81 $imageStackFile = $itemPath . "/" . $imageStackInfo['imageStackFile'];
83 if ("unknown" == $imageFormat) {
84 BRfatal("Unknown image format");
87 if ("unknown" == $archiveFormat) {
88 BRfatal("Unknown archive format");
92 $scanDataFile = "${subItemPath}_scandata.xml";
93 $scanDataZip = "$itemPath/scandata.zip";
94 if (file_exists($scanDataFile)) {
95 $scanData = simplexml_load_file($scanDataFile);
96 } else if (file_exists($scanDataZip)) {
97 $cmd = 'unzip -p ' . escapeshellarg($scanDataZip) . ' scandata.xml';
98 exec($cmd, $output, $retval);
99 if ($retval != 0) BRFatal("Could not unzip ScanData!");
101 $dump = join("\n", $output);
102 $scanData = simplexml_load_string($dump);
103 } else if (file_exists("$itemPath/scandata.xml")) {
104 // For e.g. Scribe v.0 books!
105 $scanData = simplexml_load_file("$itemPath/scandata.xml");
107 BRFatal("ScanData file not found!");
110 $metaDataFile = "$itemPath/{$id}_meta.xml";
111 if (!file_exists($metaDataFile)) {
112 BRFatal("MetaData file not found!");
116 $metaData = simplexml_load_file($metaDataFile);
118 //$firstLeaf = $scanData->pageData->page[0]['leafNum'];
121 br = new BookReader();
124 /* Output title leaf if marked */
126 foreach ($scanData->pageData->page as $page) {
127 if (("Title Page" == $page->pageType) || ("Title" == $page->pageType)) {
128 $titleLeaf = "{$page['leafNum']}";
133 if ('' != $titleLeaf) {
134 printf("br.titleLeaf = %d;\n", $titleLeaf);
138 br.getPageWidth = function(index) {
139 return this.pageW[index];
142 br.getPageHeight = function(index) {
143 return this.pageH[index];
146 // Returns true if page image is available rotated
147 br.canRotatePage = function(index) {
148 return 'jp2' == this.imageFormat; // Assume single format for now
151 // reduce defaults to 1 (no reduction)
152 // rotate defaults to 0 (no rotation)
153 br.getPageURI = function(index, reduce, rotate) {
157 if ('undefined' == typeof(reduce)) {
162 if ('undefined' == typeof(rotate)) {
168 var file = this._getPageFile(index);
170 // $$$ add more image stack formats here
171 return 'http://'+this.server+'/BookReader/BookReaderImages.php?zip='+this.zip+'&file='+file+'&scale='+_reduce+'&rotate='+_rotate;
174 br._getPageFile = function(index) {
175 var leafStr = '0000';
176 var imgStr = this.leafMap[index].toString();
177 var re = new RegExp("0{"+imgStr.length+"}$");
179 var insideZipPrefix = this.subPrefix.match('[^/]+$');
180 var file = insideZipPrefix + '_' + this.imageFormat + '/' + insideZipPrefix + '_' + leafStr.replace(re, imgStr) + '.' + this.imageFormat;
185 br.getPageSide = function(index) {
186 //assume the book starts with a cover (right-hand leaf)
187 //we should really get handside from scandata.xml
189 <? // Use special function if we should infer the page sides based off the title page index
190 if (preg_match('/goog$/', $id) && ('' != $titleLeaf)) {
192 // assume page side based on title pagex
193 var titleIndex = br.leafNumToIndex(br.titleLeaf);
194 // assume title page is RHS
195 var delta = titleIndex - index;
196 if (0 == (delta & 0x1)) {
206 // $$$ we should get this from scandata instead of assuming the accessible
207 // leafs are contiguous
208 if ('rl' != this.pageProgression) {
209 // If pageProgression is not set RTL we assume it is LTR
210 if (0 == (index & 0x1)) {
211 // Even-numbered page
219 if (0 == (index & 0x1)) {
227 br.getPageNum = function(index) {
228 var pageNum = this.pageNums[index];
236 // Single images in the Internet Archive scandata.xml metadata are (somewhat incorrectly)
237 // given a "leaf" number. Some of these images from the scanning process should not
238 // be displayed in the BookReader (for example colour calibration cards). Since some
239 // of the scanned images will not be displayed in the BookReader (those marked with
240 // addToAccessFormats false in the scandata.xml) leaf numbers and BookReader page
241 // indexes are generally not the same. This function returns the BookReader page
242 // index given a scanned leaf number.
244 // This function is used, for example, to map between search results (that use the
245 // leaf numbers) and the displayed pages in the BookReader.
246 br.leafNumToIndex = function(leafNum) {
247 for (var index = 0; index < this.leafMap.length; index++) {
248 if (this.leafMap[index] == leafNum) {
256 // This function returns the left and right indices for the user-visible
257 // spread that contains the given index. The return values may be
258 // null if there is no facing page or the index is invalid.
259 br.getSpreadIndices = function(pindex) {
260 // $$$ we could make a separate function for the RTL case and
261 // only bind it if necessary instead of always checking
262 // $$$ we currently assume there are no gaps
264 var spreadIndices = [null, null];
265 if ('rl' == this.pageProgression) {
267 if (this.getPageSide(pindex) == 'R') {
268 spreadIndices[1] = pindex;
269 spreadIndices[0] = pindex + 1;
271 // Given index was LHS
272 spreadIndices[0] = pindex;
273 spreadIndices[1] = pindex - 1;
277 if (this.getPageSide(pindex) == 'L') {
278 spreadIndices[0] = pindex;
279 spreadIndices[1] = pindex + 1;
281 // Given index was RHS
282 spreadIndices[1] = pindex;
283 spreadIndices[0] = pindex - 1;
287 //console.log(" index %d mapped to spread %d,%d", pindex, spreadIndices[0], spreadIndices[1]);
289 return spreadIndices;
292 // Remove the page number assertions for all but the highest index page with
293 // a given assertion. Ensures there is only a single page "{pagenum}"
294 // e.g. the last page asserted as page 5 retains that assertion.
295 br.uniquifyPageNums = function() {
298 for (var i = br.pageNums.length - 1; i--; i >= 0) {
299 var pageNum = br.pageNums[i];
300 if ( !seen[pageNum] ) {
301 seen[pageNum] = true;
303 br.pageNums[i] = null;
309 br.cleanupMetadata = function() {
310 br.uniquifyPageNums();
315 // Returns a URL for an embedded version of the current book
316 br.getEmbedURL = function() {
317 // We could generate a URL hash fragment here but for now we just leave at defaults
318 var url = 'http://' + window.location.host + '/stream/'+this.bookId;
319 if (this.subPrefix != this.bookId) { // Only include if needed
320 url += '/' + this.subPrefix;
328 // Returns the embed code HTML fragment suitable for copy and paste
329 br.getEmbedCode = function() {
330 return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
333 // getOpenLibraryRecord
334 br.getOpenLibraryRecord = function(callback) {
335 // Try looking up by ocaid first, then by source_record
337 var jsonURL = 'http://openlibrary.org/query.json?type=/type/edition&*=&ocaid=' + br.bookId;
340 success: function(data) {
341 if (data && data.length > 0) {
342 callback(br, data[0]);
345 jsonURL = 'http://openlibrary.org/query.json?type=/type/edition&*=&source_records=ia:' + br.bookId;
348 success: function(data) {
349 if (data && data.length > 0) {
350 callback(br, data[0]);
364 foreach ($scanData->pageData->page as $page) {
365 if (shouldAddPage($page)) {
366 if(0 != $i) echo ","; //stupid IE
367 echo "{$page->cropBox->w}";
378 foreach ($scanData->pageData->page as $page) {
379 if (shouldAddPage($page)) {
380 if(0 != $i) echo ","; //stupid IE
381 echo "{$page->cropBox->h}";
382 $totalHeight += intval($page->cropBox->h/4) + 10;
391 foreach ($scanData->pageData->page as $page) {
392 if (shouldAddPage($page)) {
393 if(0 != $i) echo ","; //stupid IE
394 echo "{$page['leafNum']}";
404 foreach ($scanData->pageData->page as $page) {
405 if (shouldAddPage($page)) {
406 if(0 != $i) echo ","; //stupid IE
407 if (array_key_exists('pageNumber', $page) && ('' != $page->pageNumber)) {
408 echo "'{$page->pageNumber}'";
419 br.numLeafs = br.pageW.length;
421 br.bookId = '<?echo $id;?>';
422 br.zip = '<?echo $imageStackFile;?>';
423 br.subPrefix = '<?echo $subPrefix;?>';
424 br.server = '<?echo $server;?>';
425 br.bookTitle= '<?echo preg_replace("/\'/", "\\'", $metaData->title);?>';
426 br.bookPath = '<?echo $subItemPath;?>';
427 br.bookUrl = '<?echo "http://www.archive.org/details/$id";?>';
428 br.imageFormat = '<?echo $imageFormat;?>';
429 br.archiveFormat = '<?echo $archiveFormat;?>';
433 # Load some values from meta.xml
434 if ('' != $metaData->{'page-progression'}) {
435 echo "br.pageProgression = '" . $metaData->{"page-progression"} . "';\n";
437 // Assume page progression is Left To Right
438 echo "br.pageProgression = 'lr';\n";
442 foreach ($metaData->xpath('//collection') as $collection) {
443 if('browserlending' == $collection) {
449 echo "br.olAuth = true;\n";
451 echo "br.olAuth = false;\n";
455 if ('bandersnatchhsye00scarrich' == $id) {
456 echo "br.mode = 2;\n";
457 echo "br.auto = true;\n";
462 // Check for config object
463 // $$$ change this to use the newer params object
464 if (typeof(brConfig) != 'undefined') {
465 if (typeof(brConfig["ui"]) != 'undefined') {
466 br.ui = brConfig["ui"];
469 if (brConfig['mode'] == 1) {
471 if (typeof(brConfig['reduce'] != 'undefined')) {
472 br.reduce = brConfig['reduce'];
474 } else if (brConfig['mode'] == 2) {
478 //$$$mang hack to override request for 2up for books with attribution page
479 // as first page until we can display that page in 2up
481 if (strrpos($id, $needle) === strlen($id)-strlen($needle)) {
482 print "// override for books with attribution page\n";
483 print "br.mode = 1;\n";
491 this.authUrl = 'http://openlibrary.org/ia_auth/' + br.bookId;
492 this.olConnect = false;
496 OLAuth.prototype.init = function() {
497 var htmlStr = '<p style="text-align:center;"><b>Authenticating in-browser loan with openlibrary.org!</b></p>';
498 htmlStr += '<p>Please wait...</p>';
500 this.showPopup("#ddd", "#000", htmlStr);
501 $.ajax({url:this.authUrl, dataType:'jsonp', jsonpCallback:'olAuth.initCallback'});
504 OLAuth.prototype.showPopup = function(bgColor, textColor, msg) {
505 this.popup = document.createElement("div");
507 position: 'absolute',
509 left: ($('#BookReader').attr('clientWidth')-400)/2 + 'px',
512 border: "3px double #999999",
514 backgroundColor: bgColor,
516 }).appendTo('#BookReader');
518 this.popup.innerHTML = msg;
522 OLAuth.prototype.initCallback = function(obj) {
523 if (false == obj.success) {
525 backgroundColor: "#f00",
529 this.popup.innerHTML = obj.msg;
533 //user is authenticated
534 this.setCookie(obj.token);
535 this.olConnect = true;
540 OLAuth.prototype.callback = function(obj) {
541 if (false == obj.success) {
542 this.showPopup("#f00", "#fff", obj.msg);
543 clearInterval(this.poller);
544 this.ttsPoller = null;
546 this.olConnect = true;
547 this.setCookie(obj.token);
551 OLAuth.prototype.setCookie = function(value) {
552 var date = new Date();
553 date.setTime(date.getTime()+(24*60*60*1000)); //one day expiry
554 var expiry = date.toGMTString();
555 var cookie = 'loan-'+br.bookId+'='+value;
556 cookie += '; expires='+expiry;
557 cookie += '; path=/; domain=.archive.org;';
558 document.cookie = cookie;
561 OLAuth.prototype.startPolling = function () {
563 this.poller=setInterval(function(){
564 if (!self.olConnect) {
565 self.showPopup("#f00", "#fff", 'Cound not connect to Open Library for authentication. Please check to see if you are still connected to the Internet, and then reload this web page.');
566 clearInterval(self.poller);
567 self.ttsPoller = null;
569 self.olConnect = false;
570 //be sure to add random param to authUrl to avoid stale cache
571 $.ajax({url:self.authUrl+'?rand='+Math.random(), dataType:'jsonp', jsonpCallback:'olAuth.callback'});
576 br.cleanupMetadata();
578 var olAuth = new OLAuth();
586 function BRFatal($string) {
587 // $$$ TODO log error
588 echo "alert('$string')\n";
592 // Returns true if a page should be added based on it's information in
594 function shouldAddPage($page) {
595 // Return false only if the page is marked addToAccessFormats false.
596 // If there is no assertion we assume it should be added.
597 if (isset($page->addToAccessFormats)) {
598 if ("false" == strtolower(trim($page->addToAccessFormats))) {
606 // Returns { 'imageFormat' => , 'archiveFormat' => '} given a sub-item prefix and loaded xml data
607 function findImageStack($subPrefix, $filesData) {
609 // $$$ The order of the image formats determines which will be returned first
610 $imageFormats = array('JP2' => 'jp2', 'TIFF' => 'tif', 'JPEG' => 'jpg');
611 $archiveFormats = array('ZIP' => 'zip', 'Tar' => 'tar');
612 $imageGroup = implode('|', array_keys($imageFormats));
613 $archiveGroup = implode('|', array_keys($archiveFormats));
614 // $$$ Currently only return processed images
615 $imageStackRegex = "/Single Page (Processed) (${imageGroup}) (${archiveGroup})/";
617 foreach ($filesData->file as $file) {
618 if (strpos($file['name'], $subPrefix) === 0) { // subprefix matches beginning
619 if (preg_match($imageStackRegex, $file->format, $matches)) {
621 // Make sure we have a regular image stack
622 $imageFormat = $imageFormats[$matches[2]];
623 if (strpos($file['name'], $subPrefix . '_' . $imageFormat) === 0) {
624 return array('imageFormat' => $imageFormat,
625 'archiveFormat' => $archiveFormats[$matches[3]],
626 'imageStackFile' => $file['name']);
632 return array('imageFormat' => 'unknown', 'archiveFormat' => 'unknown', 'imageStackFile' => 'unknown');