public static function query(Isbn $isbn) { include_once 'mysql_conn.php'; $fields = array('author', 'title', 'price', 'year', 'isbn', 'description'); $query = 'select ' . implode(', ', $fields) . ' from books where isbn="' . $isbn->toString() . '"' . ' order by price;'; $result = mysql_query($query); $book = Book::fromMySql($result); if (!$book) { return null; } while ($b = Book::fromMySql($result)) { $isComplete = true; foreach ($fields as $field) { if ($book->get($field)) { continue; } if ($b->get($field)) { $book->set($field, $b->get($field)); continue; } $isComplete = false; } if ($isComplete) { break; } } return $book; }
function testUBKarlsruhe() { $isbn13 = new Isbn('978-3897215429'); $expected = new Book(array('author' => 'Günther, Karsten', 'title' => 'LaTeX', 'year' => '2008', 'isbn' => $isbn13->toString())); $prov = new UBKarlsruheProvider(); $prov->provideBookFor($isbn13); $result = $prov->getBook(); $this->assertEquals($expected, $result); }
function testGetBook() { $isbn = new Isbn('0596002068'); $expected = new Book(array('author' => 'Ray, Randy J. and Kulchenko, Pavel', 'title' => 'Programming Web services with Perl', 'isbn' => $isbn->toString(), 'year' => '2003')); $prov = new GoogleProvider(); $prov->provideBookFor($isbn); $result = $prov->getBook(); $this->assertEquals($expected, $result); }
function setUp() { include 'mysql_conn.php'; $isbn = new Isbn('0596002068'); $book = new Book(array('author' => 'Linke, Maikel', 'title' => 'uBook Test', 'isbn' => $isbn->toString(), 'price' => '0,00', 'year' => '2011', 'description' => 'This is only a test.')); $query = 'insert into books' . ' (id, author, title, isbn, price, year, description) values' . ' (1, "' . $book->get('author') . '", "' . $book->get('title') . '", "' . $book->get('isbn') . '", "' . $book->get('price') . '", "' . $book->get('year') . '", "' . $book->get('description') . '");'; mysql_query($query); $this->isbn = $isbn; $this->book = $book; }
function testIsbnDbDotCom() { if (!self::$authKey) { $this->markTestSkipped('Auth key for isbndb.com required.'); } $isbn = new Isbn('0596002068'); $expected = new Book(array('author' => 'Randy J. Ray and Pavel Kulchenko', 'title' => 'Programming Web services with Perl', 'isbn' => $isbn->toString())); $prov = new IsbnDbDotComProvider(self::$authKey); $prov->provideBookFor($isbn); $result = $prov->getBook(); $this->assertEquals($expected, $result); }
public function InsertAndSendMail() { $quotedAuthor = trim($_POST['mail']); $quotedTitle = trim($_POST['title']); $isbn = Isbn::stringFromPost(); $year = (int) trim($_POST['year']); $price = (double) str_replace(',', '.', $_POST['price']); $quotedDescription = $_POST['desc']; $key = KeyGenerator::genKey(); $query = 'insert into books' . ' (author, title, year, price, isbn, description, mail, auth_key' . ', created,expires)' . ' values (' . '"' . $quotedAuthor . '"' . ', "' . $quotedTitle . '"' . ', "' . $year . '"' . ', "' . $price . '"' . ', "' . $isbn . '"' . ', "' . $quotedDescription . '"' . ', "' . $this->getMail() . '"' . ', "' . $key . '"' . ', now()' . ', date_add(now(), interval 45 day)' . ')'; mysql_query($query); $book_id = mysql_insert_id(); $this->selectableCategories->setBookId($book_id); $this->selectableCategories->update(); $subject = ''; $message = 'Mit deiner E-Mailadresse wurde das unten stehende Buch angeboten. Hebe diese E-Mail auf, um das Angebot später ändern und löschen zu können.'; Mailer::send($book_id, $subject, $message); $searches = new Searches(); if ($searches->areActivated()) { $author = stripslashes($quotedAuthor); $title = stripslashes($quotedTitle); $description = stripslashes($quotedDescription); $searches->bookAdded($book_id, $author, $title, $description); } header('Location: book.php?id=' . $book_id . '&key=' . $key . '&new=1'); exit; }
/** * @brief get ISBN data for $isbn at ISBNdb * * @param string $isbn ISBN to search for * @param arrayref &$meta * @return int $status (0 on success, ERRORCODE otherwise) */ public static function get($isbn, &$meta) { if ($keyString = Config::getApp('isbndb-key', '')) { $keys = explode(',', $keyString); $key = $keys[rand(0, count($keys) - 1)]; $data = false; $isbn = preg_replace('/[^0-9X]/i', '', $isbn); if (Isbn::validate($isbn)) { $command = 'http://isbndb.com/api/v2/json/' . $key . '/book/' . $isbn; $data = json_decode(file_get_contents($command), true); if (isset($data['error'])) { Util::logWarn("ISBNDB: " . $data['error']); if (!(stripos($data['error'], 'Daily request limit exceeded') === false)) { return Isbn::REQUEST_LIMIT_EXCEEDED; } elseif (!(stripos($data['error'], 'Unable to locate') === false)) { return Isbn::NOT_FOUND; } else { return Isbn::ERROR; } } else { self::parse($data['data'][0], $meta); return Isbn::SUCCESS; } } } return false; }
function testContainsValidChars() { $this->assertTrue(Isbn::containsValidChars('1234567890')); $this->assertTrue(Isbn::containsValidChars('978-3-86680-192-9')); $this->assertTrue(Isbn::containsValidChars('978 3 86680 192 9')); $this->assertFalse(Isbn::containsValidChars('12345678')); $this->assertFalse(Isbn::containsValidChars('978 3 86680 192 99')); }
public static function getUrl(array $prices) { global $tag, $marketplaceSingleCart; if (!$marketplaceSingleCart && count($prices) == 1) { return "http://www.amazon.com/gp/offer-listing/" . Isbn::to10(current($prices)->bookId) . "/condition=all&tag={$tag}"; } else { return Amazon::getUrl($prices); } }
function getByISBN($isbn) { if (!Isbn::isValid($isbn)) { throw new \Exception('invalid isbn'); } $isbn = str_replace(' ', '', $isbn); $isbn = str_replace('-', '', $isbn); if ($this->use_cache) { $temp = TempStore::getInstance(); $key = 'IsbnDbClient/isbn/' . $isbn; $res = $temp->get($key); if ($res) { return unserialize($res); } } $url = 'http://isbndb.com/api/books.xml' . '?access_key=' . $this->api_key . '&index1=isbn' . '&value1=' . $isbn; $http = new HttpClient($url); $data = $http->getBody(); $xml = simplexml_load_string($data); $attrs = $xml->BookList; if ($attrs['total_results'] == 0) { return false; } $d = $xml->BookList->BookData; $attrs = $d->attributes(); if (!$attrs) { throw new \Exception('no attrs'); } $book = new BookResource(); $book->title = strval($d->Title); $book->authors = strval($d->AuthorsText); $book->publisher = strval($d->PublisherText); $book->isbn10 = strval($attrs['isbn']); $book->isbn13 = strval($attrs['isbn13']); if ($this->use_cache) { $temp->set($key, serialize($book), '24h'); } return $book; }
protected function makeNewItem($sectionId, $details, $packageId = null, $status = null) { // undefined index errors if we have high error level reporting on. we // really don't care about these here, it's fine if they're interpreted as // falsy $oldLevel = error_reporting(0); if ($details['requiredStatus'] < SectionHasItem::GO_TO_CLASS_FIRST) { return true; } if (Isbn::validate(Isbn::clean($details['isbn']))) { $details['isbn'] = Isbn::to13(Isbn::clean($details['isbn'])); } else { $details['isbn'] = null; } $item = $this->getItemQuery()->filterByProductId($details['productId'])->filterByPartNumber($details['partNumber'])->filterByIsbn($details['isbn'])->findOne(); if (!$item) { $item = $this->newItem()->setIsbn($details['isbn'])->setProductId($details['productId'])->setPartNumber($details['partNumber']); } $item->setTitle($details['title'])->setAuthor($details['author'])->setEdition($details['edition'])->setPublisher($details['publisher'])->setImageUrl($details['imageUrl'])->setBNew($details['newPrice'])->setBUsed($details['usedPrice'])->setIsPackage($details['isPackage'] || $details['components'])->setPackageId($packageId)->save(); if (isset($details['components'])) { foreach ($details['components'] as $component) { $this->makeNewItem($sectionId, $component, $item->getId(), $details['requiredStatus']); } } if ($packageId === null) { $sectionHasItem = $this->getSectionHasItemQuery()->filterByItem($item)->filterBySectionId($sectionId)->findOne(); if (!$sectionHasItem) { $sectionHasItem = $this->newSectionHasItem()->setItem($item)->setSectionId($sectionId); } $sectionHasItem->setRequiredStatus($details['requiredStatus'] ?: $status)->setTouched(1)->save(); } error_reporting($oldLevel); }
protected static function processItemText($item) { $details = array(); if (preg_match('/Author\\:\\ \\;([^<]*)\\</', $item, $matches)) { $details['author'] = ucname(trim($matches[1])); } if (preg_match('/Edition\\:\\ \\;([^<]*)\\</', $item, $matches)) { $details['edition'] = trim($matches[1]); } if (preg_match('/src\\="(http[^"]+([X0-9]{10,13}|noBookImage)[^"]+?)"[^>]*?alt\\="([^"]+?)"/', $item, $matches)) { if (strpos($matches[1], 'noBookImage')) { $details['imageUrl'] = false; $details['isbn'] = null; } else { $details['imageUrl'] = trim($matches[1]); $details['isbn'] = Isbn::to13(Isbn::clean($matches[2])); } $details['title'] = titleCase(trim(html_entity_decode($matches[3]))); } $details['newPrice'] = $details['usedPrice'] = null; if (!strpos($item, 'Buy Digital') && preg_match('/buynewradio[^>]+?\\>\\s*?\\$([\\d\\.]+)/', $item, $matches)) { $details['newPrice'] = $matches[1]; } if (preg_match('/buyusedradio[^>]+?\\>\\s*?\\$([\\d\\.]+)/', $item, $matches)) { $details['usedPrice'] = $matches[1]; } if (preg_match('/ISBN:\\s*(?:\\ \\;)?(\\d{10,13})/', $item, $matches)) { $details['isbn'] = Isbn::to13(Isbn::clean($matches[1])); } // lowercase c in catEntry ensures that the rental item id is not selected, because it is like rentalCatEntry. // the new item id seems to always be exactly one less than the used // note: we don't use this as a unique identifier because we don't want to deal with which // is used and which is new, and because availability changes if (preg_match_all('/catEntryId_\\d+[^>]+?value\\="(\\d*)"/', $item, $matches)) { //$details['productId'] = count($matches[1] == 1) ? $matches[1][0] : call_user_func_array('min', $matches[1]); } $details['partNumber'] = null; $details['publisher'] = null; $details['isPackage'] = false; $details['components'] = array(); return $details; }
protected function urlFor(Isbn $isbn) { $this->isbn = $isbn; $urlString = 'http://books.google.com/books/feeds/volumes' . '?q=isbn%3A' . $isbn->toString(); return new HttpUrl($urlString); }
/** * @return an array of item metadata: productId, partNumber, isbn, title, author, * edition, publisher, imageUrl, usedPrice, newPrice, required */ protected static function getItemMetadata($itemText) { $details = array(); $productId = $partNumber = $isbn = $title = $author = $edition = $publisher = ""; $usedPrice = $newPrice = $required = $isPackage = $isComponent = ""; if (preg_match("/productId\\=(.+?)&/", $itemText, $matches)) { $details['productId'] = trim($matches[1]); } if (preg_match("/partNumber\\=(.+?)&/", $itemText, $matches)) { $details['partNumber'] = rtrim($matches[1], "&"); } if (preg_match("/ISBN\\:\\<\\/span\\>.+?(\\d+).+?\\</s", $itemText, $matches)) { $isbn = trim($matches[1]); $isbn = Isbn::validate($isbn) ? $isbn : ""; if ($isbn[0] == '2') { $isbn = ""; } $details['isbn'] = $isbn; } if (preg_match("/\\d{5}'\\stitle\\=\"(.+?)\"\\>.+?\\<img/s", $itemText, $matches)) { $details['title'] = titleCase(trim(htmlspecialchars_decode($matches[1], ENT_QUOTES))); } if (preg_match("/\\<span\\>Author:.*?\\<\\/span\\>(.+?)\\<\\/li/s", $itemText, $matches)) { $author = ucname(trim($matches[1])); $details['author'] = is_numeric($author) ? "" : $author; } if (preg_match("/Edition:\\<\\/span\\>(.+?)\\<br/", $itemText, $matches)) { $details['edition'] = strtolower(trim($matches[1])); } if (preg_match("/Publisher:\\<\\/span\\>(.+?)\\<br/", $itemText, $matches)) { $details['publisher'] = titleCase(trim($matches[1])); } if (preg_match("/Used.+?(\\d{1,3}\\.\\d{2})/s", $itemText, $matches)) { $details['usedPrice'] = $matches[1]; } if (preg_match("/New.+?(\\d{1,3}\\.\\d{2})/s", $itemText, $matches)) { $details['newPrice'] = $matches[1]; } if (strpos($itemText, "The price of the textbook is not yet available")) { $details['newPrice'] = $details['usedPrice'] = 0; } if (!$details['title'] && !$details['author']) { return false; } $details['imageUrl'] = ""; // todo $options = array("REQUIRED\\sPACKAGE", "RECOMMENDED\\sPACKAGE", "REQUIRED", "RECOMMENDED", "PACKAGE\\sCOMPONENT", "GO\\sTO\\sCLASS FIRST", "BOOKSTORE\\sRECOMMENDED"); preg_match("/" . implode('|', $options) . "/", $itemText, $matches); $required = trim($matches[0]); $details['isPackage'] = $required == "REQUIRED PACKAGE" || $required == "RECOMMENDED PACKAGE"; $details['isComponent'] = $required == "PACKAGE COMPONENT"; if ($required == "REQUIRED PACKAGE" || $required == "REQUIRED") { $required = SectionHasItem::REQUIRED; } else { if ($required == "RECOMMENDED PACKAGE" || $required == "RECOMMENDED") { $required = SectionHasItem::RECOMMENDED; } else { if ($required == "GO TO CLASS FIRST") { $required = SectionHasItem::GO_TO_CLASS_FIRST; } else { if ($required == "BOOKSTORE RECOMMENDED") { $required = SectionHasItem::BOOKSTORE_RECOMMENDED; } else { $required = SectionHasItem::REQUIRED; } } } } $details['requiredStatus'] = $required; return $details; }
protected function urlFor(Isbn $isbn) { $urlString = 'http://isbndb.com/api/books.xml?' . 'access_key=' . $this->accessKey . '&index1=isbn&value1=' . $isbn->toString(); return new HttpUrl($urlString); }
/** * Makes an Amazon cart. Requires $tag global to be set. * * todo: fail gracefully if amazon cart api goes down (it did once). * * @return string the url of an Amazon cart containing the items referred to in $ids */ public static function getCartUrl(array $isbns, array $offerListingIds = array()) { global $tag; $items = array(); foreach ($isbns as $isbn) { $items[] = array('type' => 'ASIN', 'id' => Isbn::to10($isbn)); } foreach ($offerListingIds as $id) { $items[] = array('type' => 'OfferListingId', 'id' => $id); } $amazon = new AmazonAPI(); $data = array("AssociateTag" => $tag); $i = 1; $j = 1; $cartId = null; while ($j <= count($items)) { if ($cartId) { $data["CartId"] = $cartId; $data["HMAC"] = $hmac; } $data["Item.{$i}.{$items[$j - 1]['type']}"] = $items[$j - 1]['id']; $data["Item.{$i}.Quantity"] = "1"; if ($i % 6 == 0 || $j == count($items)) { $operation = $cartId ? "CartAdd" : "CartCreate"; $result = $amazon->request($operation, $data); $cartId = (string) $result->Cart->CartId; $hmac = (string) $result->Cart->HMAC; $i = 0; $data = array("AssociateTag" => $tag); } $i++; $j++; } return $result->Cart->PurchaseURL; }
protected function urlFor(Isbn $isbn) { $this->isbn = $isbn; $urlString = 'http://www.ubka.uni-karlsruhe.de/hylib-bin/suche.cgi' . '?opacdb=UBKA_OPAC&simple_search=isbn%3D' . $isbn->toString() . '&raw=1&einzeltreffer=kurz'; return new HttpUrl($urlString); }
/** * @brief check pdf for metadata * * @param string $path path to pdf * @param arrayref $meta reference to array of metadata */ public static function pdf($path, &$meta) { if (\OC_Util::runningOnWindows()) { /* not supported when running on Windows due to use of exec() */ return; } /* first, try to get metadata through ISBN */ $command = ['pdftotext -l 10 "', '" -']; $output = array(); exec($command[0] . $path . $command[1], $output); if (!($output && ($isbn = Isbn::scan($output)) && Isbn::get($isbn, $meta))) { /* No ISBN, try PDF metadata */ $output = array(); $command = ["pdfinfo '", "'|grep -we '^\\(Title\\|Author\\|Subject\\|Keywords\\|CreationDate\\|ModDate\\)'"]; exec($command[0] . $path . $command[1], $output); foreach ($output as $data) { list($key, $value) = explode(':', $data, 2); $value = trim($value); } if (isset($value) && !($value == '')) { switch ($key) { case 'Title': $meta['title'] = $value; break; case 'Author': $meta['author'] = $value; break; case 'Subject': case 'Keywords': $meta['subjects'] .= $value; break; case 'CreationDate': case 'ModDate': $meta['date'] = strtotime($value); break; } } } }
/** * @param mixed $isbn10 * * @return bool */ public static function validate($isbn10) { trigger_error('Isbn10::validate validator is deprecated since 1.2 and will be removed in 2.0. Use Isbn::validate($value, 10) instead.', E_USER_DEPRECATED); return Isbn::validate($isbn10, 10); }
protected function urlFor(Isbn $isbn) { $urlString = 'http://www.booklooker.de/interface/search.php' . '?pid=' . $this->pid . '&medium=book&isbn=' . $isbn->toString(); return new HttpUrl($urlString); }
public function testValidateAndConvertIsbn13Only() { $this->assertTrue(Isbn::validate($this->validIsbn13Only)); $this->assertFalse(Isbn::to10($this->validIsbn13Only)); }
public static function getSectionsHaveItems($sections) { $result_url = $base . 'Course/Results'; foreach ($sections as $section) { self::doRequest('CourseMaterials/AddSection?sectionId=' . urlencode($section['BId']), $sections[0]); } $doc = new DOMDocument(); @$doc->loadHTML(self::doRequest('Course/Results', $sections[0])); $finder = new DomXPath($doc); $ret = array(); foreach ($finder->query('//div[@class="course-info"]') as $course) { $tds = $finder->query('//td[@class="course-materials-description"]', $course); $items = array(); foreach ($tds as $td) { $item = array(); $item['Title'] = $finder->query('.//p[@class="title"]', $td)->item(0)->nodeValue; $info = explode('<br>', innerHTML($finder->query('.//p[@class="info"]', $td)->item(0))); foreach ($info as $subject) { list($key, $value) = array_map('trim', explode(':', strip_tags($subject))); if ($key == 'Edition') { //we need to get Edition and Publisher here.. $values = explode(',', $value); $item['edition'] = trim($values[0]); //$item['Year'] = preg_replace('([^0-9]*)', '', $values[1]); } else { if ($key == 'Author') { $item['author'] = $value; } else { if ($key == 'ISBN' && Isbn::validate(Isbn::clean($value))) { $item['isbn'] = $value; } } } } $required = strtolower($finder->query('.//a[@rel="/Help/RequirementHelp"]//strong', $td)->item(0)->nodeValue); $item['isComponent'] = $required == 'part of set'; if ($required == 'required') { $required = SectionHasItem::REQUIRED; } else { if ($required == 'recommended' || $required == 'optional') { $required = SectionHasItem::RECOMMENDED; } else { if ($required == 'neebo-suggested') { $required = SectionHasItem::BOOKSTORE_RECOMMENDED; } else { $required = SectionHasItem::REQUIRED; } } } $item['requiredStatus'] = $required; $prices = $finder->query('.//td[@class="course-product-price"]/label'); $priceList = array(); foreach ($prices as $price) { $priceList[] = preg_replace('([^0-9\\.]*)', '', $price->nodeValue); } $item['BNew'] = max($priceList); $items[] = $item; } list(, $sectionId) = explode('=', $finder->query('//h4/a', $course)->item(0)->getAttribute('href')); $ret[$sectionId] = self::processItems($items); } return $ret; }
public function create_isbn_with_default_type() { $this->assertEquals(new Isbn('978-3-16-148410-0', Isbn::EAN13), Isbn::with()->number('978-3-16-148410-0')->create()); }
/** * todo: this should be changed to use Amazon::getMultiAmazonData so only * one call is made if there are multiple isbns. however, that makes it * difficult to keep isbn10/isbn13 distinction. */ public function book($isbn) { global $app; $isbns = explode("-", $isbn); $ret = array(); foreach ($isbns as $isbn) { if (Isbn::validate($isbn) && ($data = Amazon::getAmazonData($isbn))) { // Occasionally Amazon returns data for the book we want, but // with a different ISBN. This preserves the original ISBN. if ($data['isbn'] != Isbn::to13($isbn)) { $itemId = $data['isbn']; } else { $itemId = $isbn; } $ret[] = array('itemId' => $itemId, 'slug' => $itemId, 'data' => $data); } else { $ret[] = array('itemId' => $isbn, 'slug' => $isbn, 'error' => true); } } echo json_encode($ret); $app->stop(); Results::fetchPrices($isbns); }