Index: millennium_enrich.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/millennium/contrib/millennium_enrich/Attic/millennium_enrich.module,v
retrieving revision 1.1.2.2
diff -u -r1.1.2.2 millennium_enrich.module
--- millennium_enrich.module	4 Dec 2009 03:07:03 -0000	1.1.2.2
+++ millennium_enrich.module	5 Dec 2009 00:09:13 -0000
@@ -9,8 +9,12 @@
     ),
     'openlibrary' => array(
       'name' => 'Open Library',
-      'description' => t('Obtains links to fulltext and cover image from the Open Library, and adds links to WorldCat, Google and LibraryThing pages.'),
+      'description' => t('Obtains links to fulltext from the Open Library, and adds links to WorldCat, Google and LibraryThing pages.'),
       ),
+    'coverimages' => array(
+      'name' => 'Find coverimage URLs',
+      'description' => t("Scans several sources for cover images based on the item's ISBN/ISSN."),
+    ),
   );
   return $sources;
 }
@@ -193,9 +197,6 @@
   if ($data["fulltext_link"]) {
     $biblio["fulltext_sources"][] = array("Open Library", $data["fulltext_link"]);
   }
-  if ($data["coverimage"]) {
-    $biblio["coverimage_sources"][] = array("Open Library", $data["coverimage"]);
-  }
 }
 
 
@@ -305,16 +306,6 @@
   $olnumber_begin = stripos($bookkey,"/b/") + 3;
   $olnumber = substr($bookkey, $olnumber_begin);
 
-  //test if Open Library returns a 1 pixel x 1 pixel image (i.e. no cover is available for the title)
-  $path = drupal_get_path('module', 'millennium_enrich');
-  $coverimagesize = getimagesize("http://covers.openlibrary.org/b/olid/$olnumber-M.jpg");
-  if($coverimagesize[0] == 1) {
-    $coverimage =  '';
-  }
-  else {
-    $coverimage = "http://covers.openlibrary.org/b/olid/" . $olnumber . "-M.jpg";
-  }
-
   //link to fulltext if available
   $link = $bookdataresult->{'ocaid'};
   if($link) {
@@ -327,7 +318,6 @@
   $googlebooks = 'http://books.google.com/books?vid=ISBN' . $isbn;
 
   $item_data = array(
-    'coverimage' => $coverimage,
     'openlibrary_link' => $bookpage,
     'authors' => $authors,
     'publishers' => $publishers,
@@ -344,3 +334,150 @@
 
   return $item_data;
 }
+
+
+function millennium_enrich_coverimages(&$biblio, $marc) {
+  #static $tot_ok, $tot_nok;
+  #timer_start("coverimages");
+  
+  $id = $biblio["isbn"];
+  if (!$id) {
+    $id = $biblio["issn"];
+  }
+  if (!$id) {
+    #$tot_nok++;
+    #timer_stop("coverimages");
+    return;
+  }
+  // Clear multiple ISBNs
+  $id = preg_replace("/;.*/", "", $id);
+  //clean id of dashes and spaces
+  $id = str_replace("-", "", $id);
+  $id = str_replace(" ", "", $id);
+
+  $sources = array(
+    'openlibrary' => "http://covers.openlibrary.org/b/isbn/%ISBN%-M.jpg",
+    'itesm' => "http://biblioteca.itesm.mx/millennium/imagenesamazon/%ISBN%.jpg",
+    'amazon' => "http://images.amazon.com/images/P/%ISBN%.01._FMjpg_SCLZZZZZZZ_.jpg",
+    #'librarything' => "http://covers.librarything.com/devkey/[YOUR LIBRARYTHING DEVKEY]/large/isbn/%ISBN%",
+    'syndetics' => "http://www.syndetics.com/hw7.pl?isbn=%ISBN%+A/LC.jpg",
+    #'worldcat' => "http://www.worldcat.org/wcpa/servlet/DCARead?standardNo=%ISBN%&standardNoType => 1",
+  );
+  
+  // Determine the source that has the largest image 
+  $candidate_sort = array();
+  $urls = array();
+  $tmpfilename = "";
+  #drupal_set_message("candidate coverimages for $id:");
+  foreach ($sources as $sourceid => $url) {
+    $url = str_replace("%ISBN%", $id, $url);
+    #drupal_set_message($url);
+    #if (fopen($url, "rb")) {
+      list($width, $height) = millennium_enrich_coverimages_getcoverimgsize($url, $tmpfilename);
+      if ($width > 1) {
+        $candidate_sort[$width] = $sourceid;
+        $urls[$sourceid] = $url;
+        break;
+      }
+    #}
+  }
+  #$time = timer_stop("coverimages");
+  #drupal_set_message("Total time spent in coverimages: " . sprintf("%.3f", $time["time"]/1000) . " OK: $tot_ok  NOT: $tot_nok");
+  // Clean up getcoverimgsize()
+  if ($tmpfilename) {
+    unlink($tmpfilename);
+  }
+  
+  if (sizeof($candidate_sort) == 0) {
+    $tot_nok++;
+    return;
+  }
+  $tot_ok++;
+  ksort($candidate_sort);
+  $coverimages = array();
+  foreach ($candidate_sort as $sourceid) {
+    $coverimages[] = array($sourceid, $urls[$sourceid]);
+  }
+  #$best_source_url = $sources[end($candidate_images)];
+  
+  #$tmpdir = file_directory_temp();
+  #drupal_set_message("coverimages for $id:");
+  #dpm($coverimages);
+  $biblio["coverimage_sources"] = $coverimages;
+  #dpm($coverimages);
+}
+  
+/**
+ * Blatently stolen from http://www.php.net/manual/en/function.getimagesize.php#88793
+ *
+ * "As noted below, getimagesize will download the entire image before it checks for
+ * the requested information. This is extremely slow on large images that are accessed
+ * remotely. Since the width/height is in the first few bytes of the file, there is
+ * no need to download the entire file. I wrote a function to get the size of a JPEG
+ * by streaming bytes until the proper data is found to report the width and height"
+ */
+function millennium_enrich_coverimages_getcoverimgsize($img_loc, &$filename) {
+  static $random_filename;
+  if (empty($random_filename)) {
+    $random_filename = rand(1, 999999);
+  }
+  if ($handle = @fopen($img_loc, "rb")) {
+    $new_block = NULL;
+    if (!feof($handle)) {
+      $new_block = fread($handle, 32);
+      $i = 0;
+      if ($new_block[$i]=="\xFF" && $new_block[$i+1]=="\xD8" && $new_block[$i+2]=="\xFF" && $new_block[$i+3]=="\xE0") {
+        $i += 4;
+        if ($new_block[$i+2]=="\x4A" && $new_block[$i+3]=="\x46" && $new_block[$i+4]=="\x49" && $new_block[$i+5]=="\x46" && $new_block[$i+6]=="\x00") {
+          // Read block size and skip ahead to begin cycling through blocks in search of SOF marker
+          $block_size = unpack("H*", $new_block[$i] . $new_block[$i+1]);
+          $block_size = hexdec($block_size[1]);
+          while (!feof($handle)) {
+            $i += $block_size;
+            $new_block .= fread($handle, $block_size);
+            if ($new_block[$i]=="\xFF") {
+              $isjpeg = TRUE;
+              // New block detected, check for SOF marker
+              $sof_marker = array("\xC0", "\xC1", "\xC2", "\xC3", "\xC5", "\xC6", "\xC7", "\xC8", "\xC9", "\xCA", "\xCB", "\xCD", "\xCE", "\xCF");
+              if (in_array($new_block[$i+1], $sof_marker)) {
+                // SOF marker detected. Width and height information is contained in bytes 4-7 after this byte.
+                $size_data = $new_block[$i+2] . $new_block[$i+3] . $new_block[$i+4] . $new_block[$i+5] . $new_block[$i+6] . $new_block[$i+7] . $new_block[$i+8];
+                $unpacked = unpack("H*", $size_data);
+                $unpacked = $unpacked[1];
+                $height = hexdec($unpacked[6] . $unpacked[7] . $unpacked[8] . $unpacked[9]);
+                $width = hexdec($unpacked[10] . $unpacked[11] . $unpacked[12] . $unpacked[13]);
+                return array($width, $height);
+              } else {
+                // Skip block marker and read block size
+                $i += 2;
+                $block_size = unpack("H*", $new_block[$i] . $new_block[$i+1]);
+                $block_size = hexdec($block_size[1]);
+              }
+            } else {
+              $isjpeg = FALSE;
+            }
+          }
+        }
+      }
+    }
+    if (!$isjpeg) {
+      if ($image = millennium_enrich_coverimages_getcoverimgsize_image_create_file($img_loc)) {
+        $filename = file_directory_temp() . "/coverimage_tmp_{$random_filename}.jpg";
+        imagejpeg($image, $filename, 0);
+        $size = getimagesize($filename);
+        if ($size) { return $size; } else { return FALSE; }
+      } else {
+        return FALSE;
+      }
+    }
+  }
+  return FALSE;
+} // End function coverimage()
+
+function millennium_enrich_coverimages_getcoverimgsize_image_create_file($f) {
+  if ($img = @imagecreatefromstring(@file_get_contents($f))) {
+    return $img;
+  } else {
+    return FALSE;
+  }
+}
\ No newline at end of file

