More changes to support first page and last page buttons [mang].
[bookreader.git] / GnuBookIA / flipbook_search_gb.php
1 <?php
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 // FIXME: TODO: Change path above to production installation location of perl
22 // when we deploy, Brad Neuberg, bkn3@columbia.edu
23 //
24 // From:
25 //   search.cgi v0.4
26 //   by Ralf Muehlen
27 //
28 // slight alterations by Brad Neuberg, bkn3@columbia.edu
29 //
30 // ported from perl to php by tracey, Oct 2005
31
32 //fixxx require_once '/petabox/setup.inc';
33 //I think this fixxx refers to the need to set DOCUMENT_ROOT below -- mang
34
35 if (strpos($_SERVER["REQUEST_URI"], "/~mang") === 0) { // Serving out of home dir
36     $_SERVER['DOCUMENT_ROOT']='/home/mang/petabox/www/sf';
37     require_once '/home/mang/petabox/setup.inc';
38 } else {
39     $_SERVER['DOCUMENT_ROOT']='/petabox/www/sf';
40     require_once '/petabox/setup.inc';
41 }
42
43 ini_set("memory_limit","200M"); // XML can be big, esp. brittanica (100MB)
44
45 /////// SETUP /////////////////////////////////////////////////////////////
46
47 $debug_level = 0; // 0=least, 3=most debugging info
48
49 $num_pre  = 3; // context words before search term
50 $num_post = 9; // context words after  search term
51
52 // defaults for testing (when no args given)
53 $url ='http://ia300202.us.archive.org/0/items/englishbookbindings00davenuoft/englishbookbindings00davenuoft_djvuxml.xml';
54
55 $term = "history";
56 $format = "XML";
57 $callback = false;
58
59 /////// SETUP /////////////////////////////////////////////////////////////
60
61
62 // fixxx prolly should escapesystemcall() these...
63 if (isset($_GET['url']))
64   $url =        $_GET['url'];
65 if (isset($_GET['term']))
66   $term =       $_GET['term'];
67 if (isset($_GET['format']))
68   $format =     $_GET['format'];
69 if (isset($_GET['callback']))
70   $callback =     $_GET['callback'];
71
72 //$url='http://homeserver.hq.archive.org/metafetch/thespy00cooparch_djvu.xml';
73 //$url='http://homeserver.hq.archive.org/metafetch/oldchristmas00irviarch_djvu.xml';
74 //$url = 'http://homeserver.hq.archive.org/metafetch/intlepisode00jamearch_djvu.xml';
75   
76
77 if ($format == "XML")
78 {
79   // This is kinda weird (confession!) but allows existing calls to "fatal()"
80   // to throw an exception instead of dumping HTML to stdout/browser!
81   $GLOBALS['fatal-exceptions']=1;
82 }
83 try
84 {
85
86
87 // pageFiles was added to keep track of on what page each search match was
88 // found, Brad Neuberg, bkn3@columbia.edu
89 // pageHeights and pageWidths was added to track the size of each page so that
90 // we can send it over to the client; this is necessary for scaling the images
91 // for search, Brad Neuberg, bkn3@columbia.edu
92 $pages =       array();
93 $pageFiles =   array();
94 $pageHeights = array();
95 $pageWidths =  array();
96
97
98 $time0 = microtime(true);
99 $timestamp = date('Y-m-d H:i:s');
100 $pid = posix_getpid();
101 debug_msg("Invoked at ".$time0."=$timestamp under UID ".posix_getuid(),2);
102  
103
104
105 //////////////////////////////////////
106
107 debug_msg("query: ".$_SERVER['QUERY_STRING'],3);
108
109
110 $term = preg_replace('/[^A-Za-z0-9 ]/', ' ', $term); // legal characters
111 $terms = explode(' ',$term);
112 debug_msg("url,term,format: $url,".var_export($terms,true).",$format",3);
113
114
115 if ($format == "HTML")
116 {
117   echo "<html><head><title>Search</title></head> <body> Searching <p>";
118   $tag_pre  = '<b style="color:black;background-color:#A0FFFF">';
119   $tag_post = '</b>';
120 }
121 else if ($format == "XML")
122 {
123   if (false === $callback) {
124       header('Content-type: text/xml');
125   } else {
126       header('application/x-javascript');
127   }
128   $tag_pre  = '</CONTEXT>';
129   $tag_post = '<CONTEXT>';
130 }
131 else
132 {
133   fatal("Unknown format request. ");
134 }
135  
136
137 // This looks like where we load the djvu.xml
138 if (!($document = file_get_contents($url)))
139   fatal("could not load $url");
140
141
142
143 $time1 = microtime(true) - $time0;
144
145
146 //// Pass 1 - build up page* arrays with xml fragments corresponding to matches
147 $pagenumber=0;
148 foreach (explode('</OBJECT>', $document) as $page)
149 {
150   $pagenumber++;
151   if (matches_terms($page, $terms)  &&
152       // 2nd clause here is to ensure that we aren't matching in the end
153       // of the overall XML document -- thus we ensure that OBJECT tag starts
154       // in the chunk we just were handed.  (traceyj)
155       strstr($page, '<OBJECT '))
156   {
157     // extract the page value so that we know what page we are on,
158     // Brad Neuberg, bkn3@columbia.edu
159     if (!preg_match('|<PARAM name="PAGE" value="([^"]*)"\s*\/>|', $page, $match))
160       fatal("page value not set on page number $pagenumber in $page!");
161     $pageFile = $match[1];
162     
163     // extract the page width and height, Brad Neuberg, bkn3@columbia.edu
164     if (!preg_match('/width="([^"]*)"/', $page, $match))
165       fatal("page width not set!");
166     $pageWidth = $match[1];
167
168     if (!preg_match('/height="([^"]*)"/', $page, $match))
169       fatal("page height not set!");
170     $pageHeight = $match[1];
171     
172     $page_new='';
173     foreach (explode('</WORD>',$page) as $token)
174     {
175       if (matches_terms($token, $terms))
176       {
177         list($junk, $keep) = explode('<WORD ',$token);
178         $token = " $tag_pre<WORD $keep</WORD>$tag_post "; 
179       }
180       else
181       {
182         $token = preg_replace('/<[^<]*>/','', $token);     //mark-up
183         $token = preg_replace('/[\&\#\d+;]/', ' ', $token);//non-ascii chars
184         $token = preg_replace('/\s+/', ' ', $token);       //white space
185       }
186
187       $page_new .= $token;
188     }
189
190     
191     
192     $page_new =
193       preg_replace('|.*((\W\w*){'.$num_pre.'}'.$tag_pre.')|',"$1",$page_new);
194     $page_new =
195       preg_replace('/('.$tag_post.'(\w*\W){'.$num_post.'}).*/',"$1",$page_new);
196     
197     
198     // added to keep track of the page we are on
199     // Brad Neuberg, bkn3@columbia.edu
200     $pageFiles  [$pagenumber] = $pageFile;
201     $pages      [$pagenumber] = $page_new;
202     // added to keep track of page widths and heights
203     $pageWidths [$pagenumber] = $pageWidth;
204     $pageHeights[$pagenumber] = $pageHeight;
205   }
206 }
207
208
209 $time2 =  microtime(true) - $time1;
210
211 //// Pass 2 - generate output from previously built arrays
212
213
214 if ($format == "HTML")
215 {
216   echo "Found ".count($pages)." pages containing $tag_pre";
217   print_r($terms);
218   echo "$tag_post.<br>\n";
219   foreach ($pages as $index => $page)
220   {
221     echo "<h4>Page $page:</h4>\n";
222     print_r($page);
223     echo "<p><br><p>\n";
224   }
225   $time3 = microtime(true) - $time2;
226   echo $tag_pre . "Fetched document in $time1 ms.$tag_post<p>\n";
227   echo $tag_pre . "Processed document in $time2 ms.$tag_post<p>\n";
228   echo $tag_pre . "Printed document in $time3 ms.$tag_post<p>\n";
229   echo "</body></html>\n";
230 }
231 else if ($format == "XML")
232 {
233   $xml = "";
234   $xml .= '<?xml version="1.0" encoding="utf-8"?>'."\n";
235   // Added to prevent Internet Explorer from adding default XML stylesheet,
236   // which messes up processing, Brad Neuberg, bkn3@columbia.edu
237   $xml .= '<?xml-stylesheet type="text/css" href="blank.css"?>'."\n";//fixxx
238   $xml .= '<SEARCH>';
239
240   foreach ($pages as $index => $page)
241   {
242     $xml .= "<PAGE file=\"{$pageFiles[$index]}\" width=\"{$pageWidths[$index]}\" height=\"{$pageHeights[$index]}\">\n";
243     $xml .= "<CONTEXT>\n";
244     $xml .= $page;
245     $xml .= "</CONTEXT>\n";
246     $xml .= "</PAGE>\n";
247   }
248   $xml .= "</SEARCH>\n";
249   
250   // The XML contains the page numbers from the DJVU XML.  We must remap them to flipbook indices
251   // since the flipbook indices are monotonically increasing generated from the pages with
252   // addToAccessFormats true (maybe)
253   $fsm = FlipSearchMap::buildSearchMap($url);
254   if (false === $callback) {
255       echo $fsm->remapSearch($xml);
256   } else {
257       $patterns[0] = '/\n/';
258       $patterns[1] = "/\'/"; 
259       $replac[0]   = '';
260       $replac[1]   = '&#39;';
261       
262       // We don't have FlipSearchMap remap since we have our own mapping between
263       // scandata.xml leaf numbers and GB indices that happens in GBSearchCallback
264       echo "$callback('". preg_replace($patterns, $replac, $xml)."');";
265   }
266   //echo $xml;
267 }
268
269 //////
270 debug_msg("Done and exiting!",2);
271 exit;
272 //////
273 }
274 catch (Exception $e)
275 {
276   // an internal method call invoked "fatal()"...
277   XML::resultMessage('error','internal_error', $e->getMessage());
278 }
279
280
281
282
283 function matches_terms(&$text, // search space
284                        &$terms)// array of search terms
285 {
286   foreach ($terms as $term)
287   {
288     if (preg_match("/$term/i", $text))
289       return true;
290   }
291   return false;
292 }
293
294
295 function debug_msg($msg, $level)
296 {
297   global $debug_level;
298   global $pid;
299   global $format;
300   if ($level <= $debug_level)
301   {
302     if ($format == "XML")
303       echo "<!-- FILL  ($pid):$level: $msg -->\n";
304     else
305       echo "FILL  ($pid):$level: $msg<br/>\n";
306   }
307 }
308
309
310 ?>