e17702d07bf1a607251334e6d627cda86e2544ba
[bookreader.git] / GnuBookIA / datanode / GnuBookJSIA.php
1 <?
2 /*
3 Copyright(c)2008 Internet Archive. Software license AGPL version 3.
4
5 This file is part of GnuBook.
6
7     GnuBook 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.
11
12     GnuBook 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.
16
17     You should have received a copy of the GNU Affero General Public License
18     along with GnuBook.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 $id = $_REQUEST['id'];
22 $itemPath = $_REQUEST['itemPath'];
23 $subPrefix = $_REQUEST['subPrefix'];
24 $server = $_REQUEST['server'];
25
26 // Check if we're on a dev vhost and point to JSIA in the user's public_html on the datanode
27 // $$$ TODO consolidate this logic
28 if (strpos($_SERVER["REQUEST_URI"], "/~mang") === 0) { // Serving out of home dir
29     $server .= ':80/~mang';
30 } else if (strpos($_SERVER["REQUEST_URI"], "/~testflip") === 0) { // Serving out of home dir
31     $server .= ':80/~testflip';
32 }
33
34 if ($subPrefix) {
35     $subItemPath = $itemPath . '/' . $subPrefix;
36 } else {
37     $subItemPath = $itemPath . '/' . $id;
38 }
39
40 if ("" == $id) {
41     GBFatal("No identifier specified!");
42 }
43
44 if ("" == $itemPath) {
45     GBFatal("No itemPath specified!");
46 }
47
48 if ("" == $server) {
49     GBFatal("No server specified!");
50 }
51
52 if (!preg_match("|^/[0-3]/items/{$id}$|", $itemPath)) {
53     GBFatal("Bad id!");
54 }
55
56 // XXX check here that subitem is okay
57
58 $imageFormat = 'unknown';
59 $zipFile = "${subItemPath}_jp2.zip";
60
61 if (file_exists($zipFile)) {
62     $imageFormat = 'jp2';
63 } else {
64   $zipFile = "${subItemPath}_tif.zip";
65   if (file_exists($zipFile)) {
66     $imageFormat = 'tif';
67   }
68 }
69
70 if ("unknown" == $imageFormat) {
71   GBfatal("Unknown image format");
72 }
73
74 $scanDataFile = "${subItemPath}_scandata.xml";
75 $scanDataZip  = "$itemPath/scandata.zip";
76 if (file_exists($scanDataFile)) {
77     $scanData = simplexml_load_file($scanDataFile);
78 } else if (file_exists($scanDataZip)) {
79     $cmd  = 'unzip -p ' . escapeshellarg($scanDataZip) . ' scandata.xml';
80     exec($cmd, $output, $retval);
81     if ($retval != 0) GBFatal("Could not unzip ScanData!");
82     
83     $dump = join("\n", $output);
84     $scanData = simplexml_load_string($dump);
85 } else if (file_exists("$itemPath/scandata.xml")) {
86     // For e.g. Scribe v.0 books!
87     $scanData = simplexml_load_file("$itemPath/scandata.xml");
88 } else {
89     GBFatal("ScanData file not found!");
90 }
91
92 $metaDataFile = "$itemPath/{$id}_meta.xml";
93 if (!file_exists($metaDataFile)) {
94     GBFatal("MetaData file not found!");
95 }
96
97
98 $metaData = simplexml_load_file($metaDataFile);
99
100 //$firstLeaf = $scanData->pageData->page[0]['leafNum'];
101 ?>
102
103 gb = new GnuBook();
104
105 <?
106 /* Output title leaf if marked */
107 $titleLeaf = '';
108 foreach ($scanData->pageData->page as $page) {
109     if (("Title Page" == $page->pageType) || ("Title" == $page->pageType)) {
110         $titleLeaf = "{$page['leafNum']}";
111         break;
112     }
113 }
114     
115 if ('' != $titleLeaf) {
116     printf("gb.titleLeaf = %d;\n", $titleLeaf);
117 }
118 ?>
119
120 gb.getPageWidth = function(index) {
121     //return parseInt(this.pageW[index]/this.reduce);
122     return this.pageW[index];
123 }
124
125 gb.getPageHeight = function(index) {
126     //return parseInt(this.pageH[index]/this.reduce);
127     return this.pageH[index];
128 }
129
130 gb.getPageURI = function(index) {
131     var leafStr = '0000';            
132     var imgStr = this.leafMap[index].toString();
133     var re = new RegExp("0{"+imgStr.length+"}$");
134     
135     var insideZipPrefix = this.subPrefix.match('[^/]+$');
136     var file = insideZipPrefix + '_' + this.imageFormat + '/' + insideZipPrefix + '_' + leafStr.replace(re, imgStr) + '.' + this.imageFormat;
137     
138     // $$$ add more image stack formats here
139     if (1==this.mode) {
140         var url = 'http://'+this.server+'/GnuBook/GnuBookImages.php?zip='+this.zip+'&file='+file+'&scale='+this.reduce;
141     } else {
142         var ratio = this.getPageHeight(index) / this.twoPageH;
143         var scale;
144         // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
145         if (ratio <= 2) {
146             scale = 1;
147         } else if (ratio <= 4) {
148             scale = 2;
149         } else {
150             scale = 4;
151         }        
152     
153         var url = 'http://'+this.server+'/GnuBook/GnuBookImages.php?zip='+this.zip+'&file='+file+'&scale='+scale;
154         
155     }
156     return url;
157 }
158
159 gb.getPageSide = function(index) {
160     //assume the book starts with a cover (right-hand leaf)
161     //we should really get handside from scandata.xml
162     
163     <? // Use special function if we should infer the page sides based off the title page index
164     if (preg_match('/goog$/', $id) && ('' != $titleLeaf)) {
165     ?>
166     // assume page side based on title page
167     var titleIndex = gb.leafNumToIndex(gb.titleLeaf);
168     // assume title page is RHS
169     var delta = titleIndex - index;
170     if (0 == (delta & 0x1)) {
171         // even delta
172         return 'R';
173     } else {
174         return 'L';
175     }
176     <?
177     }
178     ?>
179     
180     // $$$ we should get this from scandata instead of assuming the accessible
181     //     leafs are contiguous
182     if ('rl' != this.pageProgression) {
183         // If pageProgression is not set RTL we assume it is LTR
184         if (0 == (index & 0x1)) {
185             // Even-numbered page
186             return 'R';
187         } else {
188             // Odd-numbered page
189             return 'L';
190         }
191     } else {
192         // RTL
193         if (0 == (index & 0x1)) {
194             return 'L';
195         } else {
196             return 'R';
197         }
198     }
199 }
200
201 gb.getPageNum = function(index) {
202     var pageNum = this.pageNums[index];
203     if (pageNum) {
204         return pageNum;
205     } else {
206         return 'n' + index;
207     }
208 }
209
210 gb.leafNumToIndex = function(leafNum) {
211     var index = jQuery.inArray(leafNum, this.leafMap);
212     if (-1 == index) {
213         return null;
214     } else {
215         return index;
216     }
217 }
218
219 // This function returns the left and right indices for the user-visible
220 // spread that contains the given index.  The return values may be
221 // null if there is no facing page or the index is invalid.
222 gb.getSpreadIndices = function(pindex) {
223     // $$$ we could make a separate function for the RTL case and
224     //      only bind it if necessary instead of always checking
225     // $$$ we currently assume there are no gaps
226     
227     var spreadIndices = [null, null]; 
228     if ('rl' == this.pageProgression) {
229         // Right to Left
230         if (this.getPageSide(pindex) == 'R') {
231             spreadIndices[1] = pindex;
232             spreadIndices[0] = pindex + 1;
233         } else {
234             // Given index was LHS
235             spreadIndices[0] = pindex;
236             spreadIndices[1] = pindex - 1;
237         }
238     } else {
239         // Left to right
240         if (this.getPageSide(pindex) == 'L') {
241             spreadIndices[0] = pindex;
242             spreadIndices[1] = pindex + 1;
243         } else {
244             // Given index was RHS
245             spreadIndices[1] = pindex;
246             spreadIndices[0] = pindex - 1;
247         }
248     }
249     
250     //console.log("   index %d mapped to spread %d,%d", pindex, spreadIndices[0], spreadIndices[1]);
251     
252     return spreadIndices;
253 }
254
255 // Remove the page number assertions for all but the highest index page with
256 // a given assertion.  Ensures there is only a single page "{pagenum}"
257 // e.g. the last page asserted as page 5 retains that assertion.
258 gb.uniquifyPageNums = function() {
259     var seen = {};
260     
261     for (var i = gb.pageNums.length - 1; i--; i >= 0) {
262         var pageNum = gb.pageNums[i];
263         if ( !seen[pageNum] ) {
264             seen[pageNum] = true;
265         } else {
266             gb.pageNums[i] = null;
267         }
268     }
269
270 }
271
272 gb.cleanupMetadata = function() {
273     gb.uniquifyPageNums();
274 }
275
276 gb.pageW =              [
277             <?
278             $i=0;
279             foreach ($scanData->pageData->page as $page) {
280                 if (shouldAddPage($page)) {
281                     if(0 != $i) echo ",";   //stupid IE
282                     echo "{$page->cropBox->w}";
283                     $i++;
284                 }
285             }
286             ?>
287             ];
288
289 gb.pageH =              [
290             <?
291             $totalHeight = 0;
292             $i=0;            
293             foreach ($scanData->pageData->page as $page) {
294                 if (shouldAddPage($page)) {
295                     if(0 != $i) echo ",";   //stupid IE                
296                     echo "{$page->cropBox->h}";
297                     $totalHeight += intval($page->cropBox->h/4) + 10;
298                     $i++;
299                 }
300             }
301             ?>
302             ];
303 gb.leafMap = [
304             <?
305             $i=0;
306             foreach ($scanData->pageData->page as $page) {
307                 if (shouldAddPage($page)) {
308                     if(0 != $i) echo ",";   //stupid IE
309                     echo "{$page['leafNum']}";
310                     $i++;
311                 }
312             }
313             ?>    
314             ];
315
316 gb.pageNums = [
317             <?
318             $i=0;
319             foreach ($scanData->pageData->page as $page) {
320                 if (shouldAddPage($page)) {
321                     if(0 != $i) echo ",";   //stupid IE                
322                     if (array_key_exists('pageNumber', $page) && ('' != $page->pageNumber)) {
323                         echo "'{$page->pageNumber}'";
324                     } else {
325                         echo "null";
326                     }
327                     $i++;
328                 }
329             }
330             ?>    
331             ];
332             
333       
334 gb.numLeafs = gb.pageW.length;
335
336 gb.bookId   = '<?echo $id;?>';
337 gb.zip      = '<?echo $zipFile;?>';
338 gb.subPrefix = '<?echo $subPrefix;?>';
339 gb.server   = '<?echo $server;?>';
340 gb.bookTitle= '<?echo preg_replace("/\'/", "\\'", $metaData->title);?>';
341 gb.bookPath = '<?echo $subItemPath;?>';
342 gb.bookUrl  = '<?echo "http://www.archive.org/details/$id";?>';
343 gb.imageFormat = '<?echo $imageFormat;?>';
344
345 <?
346
347 # Load some values from meta.xml
348 if ('' != $metaData->{'page-progression'}) {
349   echo "gb.pageProgression = '" . $metaData->{"page-progression"} . "';";
350 } else {
351   // Assume page progression is Left To Right
352   echo "gb.pageProgression = 'lr';";
353 }
354
355 # Special cases
356 if ('bandersnatchhsye00scarrich' == $id) {
357     echo "gb.mode     = 2;\n";
358     echo "gb.auto     = true;\n";
359 }
360
361 ?>
362
363 // Check for config object
364 // $$$ change this to use the newer params object
365 if (typeof(gbConfig) != 'undefined') {
366     if (typeof(gbConfig["ui"]) != 'undefined') {
367         gb.ui = gbConfig["ui"];
368     }
369
370     if (gbConfig['mode'] == 1) {
371         gb.mode = 1;
372         if (typeof(gbConfig['reduce'] != 'undefined')) {
373             gb.reduce = gbConfig['reduce'];
374         }
375     } else if (gbConfig['mode'] == 2) {
376         gb.mode = 2;
377       
378 <?
379         //$$$mang hack to override request for 2up for books with attribution page
380         //   as first page until we can display that page in 2up
381         $needle = 'goog';
382         if (strrpos($id, $needle) === strlen($id)-strlen($needle)) {
383             print "// override for books with attribution page\n";
384             print "gb.mode = 1;\n";
385         }
386 ?>
387     }
388 } // gbConfig
389
390 gb.cleanupMetadata();
391 gb.init();
392
393 <?
394
395
396 function GBFatal($string) {
397     echo "alert('$string')\n";
398     die(-1);
399 }
400
401 // Returns true if a page should be added based on it's information in
402 // the metadata
403 function shouldAddPage($page) {
404     // Return false only if the page is marked addToAccessFormats false.
405     // If there is no assertion we assume it should be added.
406     if (isset($page->addToAccessFormats)) {
407         if ("false" == strtolower(trim($page->addToAccessFormats))) {
408             return false;
409         }
410     }
411     
412     return true;
413 }
414
415 ?>