Source for file ISBN.php
Documentation is available at ISBN.php
* Handle, Convert and Validate ISBN Numbers
* LICENSE: LGPL (In cases LGPL is not appropriate, it is licensed under GPL)
* Package to handle, convert and validate ISBN numbers. It includes:
* - ISBN specifics: EAN/PrefixArrayAccess (integer)
* - ISBN specifics: Group/Registration Group [2001: Group identifier] (integer)
* - ISBN specifics: GroupTitle/Registration Group Title (string)
* - ISBN specifics: Publisher/Registrant [2001: Publisher identifier] (string)
* - ISBN specifics: Title/Publication [2001: Title identifier] (string)
* - ISBN specifics: Checkdigit (string)
* - ISBN specifics: 'ISBNBody' (string)
* - ISBN specifics: 'ISBNSubbody' (string)
* - ISBN Version handling
* - Syntactical Validation plus Validation based on real ISBN Data
* - ISBN-10 (ISO 2108) checksum calculation
* - Validation (ISBN-10 and ISBN-13-978)
* - Conversion to ISBN-13-978
* - ISBN-13-978 (2005 Handbook, ISO pending; ISBN-13)
* - ISBN-13 checksum calculation (EAN)
* Based on standards published by international ISBN Agency
* http://www.isbn-international.org/
* @author Tom Klingenberg <tkli-php@lastflood.net>
* @copyright 2006-2007 Tom Klingenberg
* @license LGPL http://www.gnu.org/licenses/lgpl.txt
* @version v 0.1.6 CVS: <cvs_id>
* @link http://isbn.lastflood.com online docs
* @todo License for .js file or remove it
* ISBN Versions supported
define('ISBN_VERSION_NONE', false);
* VERSION_UNKNOWN is by the caller only, this shall never
* be a value returned by a public function or getter
define('ISBN_VERSION_UNKNOWN', 0);
define('ISBN_VERSION_ISBN_10', 10);
define('ISBN_VERSION_ISBN_13', 13978);
define('ISBN_VERSION_ISBN_13_978', ISBN_VERSION_ISBN_13);
define('ISBN_VERSION_ISBN_13_979', 13979); /* reserved */
* Default ISBN Version for class input / usage
define('ISBN_DEFAULT_INPUTVERSION', ISBN_VERSION_UNKNOWN);
* Default ISBN Seperator string
define('ISBN_DEFAULT_COSMETIC_SEPERATOR', '-');
* ISBN_DEFAULT_PRINT_LANG_SPECIFIC_PREFIX
* When printed, the ISBN is always preceded by the letters "ISBN".
* Note: In countries where the Latin alphabet is not used, an abbreviation
* in the characters of the local script may be used in addition to the
* This can be defined as a default value wihtin this constant.
define('ISBN_DEFAULT_PRINT_LANG_SPECIFIC_PREFIX', '');
require_once 'PEAR/Exception.php';
* @author Tom Klingenberg <tkli-php@lastflood.net>
* @copyright 2006-2007 Tom Klingenberg
* @license LGPL http://www.gnu.org/licenses/lgpl.txt
* @link http://isbn.lastflood.com/
* @since Class available since Release 0.1.3
* Class to Handle, Convert and Validate ISBN Numbers
* @author Tom Klingenberg <tkli-php@lastflood.net>
* @copyright 2006-2007 Tom Klingenberg
* @license LGPL http://www.gnu.org/licenses/lgpl.txt
* @link http://isbn.lastflood.com/
* @since Class available since Release 0.0.0
* @var string ISBN Registration Group
private $isbn_group = '';
* @var string ISBN Publisher
private $isbn_publisher = '';
private $isbn_title = '';
* @var mixed ISBN number version
private $ver = ISBN_VERSION_NONE;
* @var array ISBN Groups Data acting as cache
* @see _getISBN10Groups()
private static $varISBN10Groups = array();
* @param array $isbn String of ISBN Value to use
* @param mixed $ver Optional Version Constant
* @throws ISBN_Exception in case it fails
function __construct($isbn = '', $ver = ISBN_DEFAULT_INPUTVERSION)
/* validate & handle optional isbn parameter */
/* validate version parameter */
if (self::_isbnVersionIs($ver) == false) {
'ISBN Version parameter is not an ISBN Version'
/* ISBN has been passed, check the version now:
* if it is unknown, try to dertine it, if this fails
$verguess = self::_isbnVersionGuess($isbn);
if (self::_isbnVersionIsValid($verguess)) {
/* throw new ISBN_Exception(
*'ISBN Version couldn\'t determined.');
/* handle a complete invalid ISBN of which a version could
/* the isbn is invalid and not set, sothat this
* ISBN object will be set to a blank value. */
// {{{ _extractCheckdigit()
* extract Checkdigit of an ISBN-Number
* @param string $isbnn normalized ISBN string
* @return string|falseISBN-Body or false if failed
private static function _extractCheckdigit($isbnn)
$checkdigit = substr($isbnn, - 1);
return (string) $checkdigit;
// {{{ _extractEANPrefix()
* extracts EAN-Prefix of a normalized isbn string
* @param string $isbnn normalized isbn string
* @return string|falsePrefix or false if failed
private static function _extractEANPrefix($isbnn)
$prefix = substr($isbnn, 0, 3);
* extract Registration Group of an ISBN-Body
* @param string $isbnbody ISBN-Body
* @return integer|false Registration Group or false if failed
private static function _extractGroup($isbnbody)
$r = self::_isbnBodyParts($isbnbody, $group, $subbody);
// {{{ _extractISBNBody()
* extract ISBN-Body of an ISBN-Number
* @param string $isbnn normalized ISBN string
* @return string|falseISBN-Body or false if failed
private static function _extractISBNBody($isbnn)
$isbnn = (string) $isbnn;
$body = substr($isbnn, 0, - 1);
$body = substr($isbnn, 3, - 1);
* Get the 2 Parts of the ISBN-Body (ISBN-10/ISBN-13-978)
* @param string $isbnbody ISBN-Body
* @param string &$registrationgroup Registration Group
* @param string &$isbnsubbody ISBN-Subbody
* @return boolean False if failed, True on success
private static function _isbnBodyParts($isbnbody,
/* validate input (should not be needed, @access private) */
/* extract registraion group
* boundaries see p.13 2005 handbook
$boundaries[] = array( 0, 59999, 1);
$boundaries[] = array(60000, 60099, 3); // Iran 2006-12-05
$boundaries[] = array(60100, 69999, 0);
$boundaries[] = array(70000, 79999, 1);
$boundaries[] = array(80000, 94999, 2);
$boundaries[] = array(95000, 98999, 3);
$boundaries[] = array(99000, 99899, 4);
$boundaries[] = array(99900, 99999, 5);
$segment = substr($isbnbody, 0, 5);
$segmentvalue = intval($segment);
/* test segment value against boundaries */
foreach ($boundaries as $boundary) {
if ($segmentvalue >= $boundary[0] && $segmentvalue <= $boundary[1]) {
/* $r is 0 when the boundary is not defined */
$registrationgroup = substr($isbnbody, 0, $r);
$isbnsubbody = substr($isbnbody, $r);
// {{{ _isbnSubbodyParts()
* Get the 2 Parts of the ISBN-Subbody (ISBN-10/ISBN-13)
* @param string $isbnsubbody ISBN-Subbody
* @param integer $groupid Registrationgroup
* @param string &$registrant Registrant
* @param string &$publication Publication
* @return boolean False if failed, true on success
private static function _isbnSubbodyParts($isbnsubbody,
/* validate input (should not be needed, @access private) */
$r = settype($isbnsubbody, 'string');
if ($groupid < 0 || $groupid > 99999) {
/* extract registrant based on group and registrant range
* parse this specific group format:
* 'English speaking area',
* '00-09;10-19;200-699;7000-8499;85000-89999;' .
* '900000-949999;9500000-9999999'
$group = self::_getISBN10Group($groupid);
$len = self::_getRegistrantLength($isbnsubbody, $group[1]);
$registrant = substr($isbnsubbody, 0, $len);
$publication = substr($isbnsubbody, $len);
// {{{ _getRegistrantLength()
* Return Length of Registrant part within an ISBNSubbody in a specific
* grouprange in this specific format:
* '00-09;10-19;200-699;7000-8499;85000-89999;900000-949999;9500000-9999999'
* Info: This function is compatible with Groupranges formatted in the
* .js file and might become obsolete if new formats are more fitting.
* @param string $isbnsubbody ISBN-Subbody
* @param string $grouprange Grouprange in the Format '#a1-#z1;#a2-z2[...]'
* @return boolean|int False if failed or Length (in chars) of Registrant
private static function _getRegistrantLength($isbnsubbody, $grouprange)
$r = settype($grouprange, 'string');
if (strlen($grouprange) < 3) {
$ranges = explode(';', $grouprange);
foreach ($ranges as $range) {
if (count($fromto) !== 2) {
* from and to need to be in the same class,
* having the same length.
* registrant can not be bigger or same then the
* whole subbody, at least there is one digit for
if ($l != strlen($fromto[1])) {
/* check that from/to values are in order */
if (strcmp($fromto[0], $fromto[1]) >= 0) {
/* compare and fire if matched */
$comparec = substr($isbnsubbody, 0, $l);
if (strcmp($fromto[0], $comparec) < 1 &&
strcmp($fromto[1], $comparec) > - 1) {
* Get ISBN-10 Registration Group Data by its numeric ID
* @param integer $id Registration Group Identifier
* @return mixed array: group array
* boolean: False if failed
private static function _getISBN10Group($id)
$groups = self::_getISBN10Groups();
if (isset ($groups[$id]) === false) {
// {{{ _getISBN10Groups()
* Get all ISBN-10 Registration Groups
* @return array groups array
* Info: This function connects outer world data into this class logic
* which can be generated with the supplied tools.
* A user should not alter the array data. This data should be altered
* together with the international ISBN Agency only.
private static function _getISBN10Groups()
/* check if data has been already loaded */
if (sizeof(self::$varISBN10Groups) > 0 ) {
return self::$varISBN10Groups;
$t = file_get_contents('data/groups.csv', true, null);
'Unable to read ISBN Groups Data file.'
/* parse external data */
if (isset ($groups[$index])) {
'ISBN Groups Data is invalid, Group ' .
$index . 'is a duplicate.'
/* edit+ mature: sanitize external
$groups[$index] = array($tlp[1],$tlp[2]);
'ISBN Groups Data is malformed on line #' . $line .
'ISBN Groups Data does not contain any valid data.'
self::$varISBN10Groups = $groups;
* Get the Version of am ISBN Number
* @param string $isbn ISBN Number ofwhich the version to get
* @return mixed false for no, or fully identifyable ISBN
private static function _getVersion($isbn)
$ver = self::_isbnVersionGuess($isbn);
$r = self::_isbnVersionIsValid($ver);
// {{{ _checkdigitISBN10()
* Calculate checkdigit of an ISBN-10 string (ISBN-Body)
* as documented on pp.4-5 2001 handbook.
* @param string $isbnbody ISBN-Body
* @return string|falseCheckdigit [0-9,X] or false if failed
private static function _checkdigitISBN10($isbnbody)
/* The check digit is the last digit of an ISBN. It is calculated
* on a modulus 11 with weights 10-2, using X in lieu of 10 where
* ten would occur as a check digit.
* This means that each of the first nine digits of the ISBN �
* excluding the check digit itself � is multiplied by a number
* ranging from 10 to 2 and that the resulting sum of the products,
* plus the check digit, must be divisible by 11 without a
* remainder. (pp.4-5 2001 Handbook)
for ($i = 0; $i < 10; $i++ ) {
$checkdigit = 11 - $remainder;
return (string) $checkdigit;
// {{{ _checkdigitISBN13()
* Calculate checkdigit of an ISBN-13 string (Prefix + ISBN-Body)
* as documented on pp.10-11 2005 handbook.
* @param string $isbnbody ISBN-Body
* @param string $prefix EAN-Prefix (Default 978 for ISBN13-978)
* @return string|falseCheckdigit [0-9] or false if failed
private static function _checkdigitISBN13($isbnbody, $prefix = '978')
$prefixandisbnbody = $prefix . $isbnbody;
/* Step 1: Determine the sum of the weighted products for the first 12
* digits of the ISBN (see p.10 2005 handbook)
for ($i = 0; $i < 13; $i++ ) {
/* Step 2: Divide the sum of the weighted products of the first 12
* digits of the ISBN calculated in step 1 by 10, determining the
* remainder. (see p.11 2005 handbook)
/* Step 3: Subtract the remainder calculated in step 2 from 10. The
* resulting difference is the value of the check digit with one
* exception. If the remainder from step 2 is 0, the check
$checkdigit = 10 - $remainder;
/* return string value */
$checkdigit = (string) $checkdigit;
* @param string $isbn Number to validate
* @param string $ver Version to validate against
* @return integer|false Returns the Version to signal validity or false if
* ISBN number is not valid
private static function _isIsbnValid($isbn, $ver = ISBN_DEFAULT_INPUTVERSION)
$r = self::_isbnVersionIs($ver);
$ver = self::_isbnVersionGuess($isbn);
if (self::_isbnVersionIsValid($ver) === false) {
/* since a version is available now, normalise the ISBN input */
$isbnn = self::_normaliseISBN($isbn);
/* normalzied ISBN and Version available, it's ok now
* to perform indepth checks per version */
/* check syntax against checkdigit */
$isbnbody = self::_extractISBNBody($isbnn);
$check = self::_extractCheckdigit($isbnn);
$checkdigit = self::_checkdigitISBN10($isbnbody);
if ($checkdigit === false) {
if ($checkdigit !== $check) {
/* check registrationgroup validity */
$registrationgroup = false;
$r = self::_isbnBodyParts($isbnbody, $registrationgroup, $subbody);
/* check for undefined registrationgroup */
if (strlen($registrationgroup) == 0) {
/* check registrant validity */
$groupid = intval($registrationgroup);
$r = self::_isbnSubbodyParts($subbody, $groupid,
$registrant, $publication);
/* validate EAN Prefix */
$ean = self::_extractEANPrefix($isbnn);
/* check syntax against checkdigit */
$isbnbody = self::_extractISBNBody($isbnn);
$check = self::_extractCheckdigit($isbnn);
$checkdigit = self::_checkdigitISBN13($isbnbody);
if ($checkdigit === false) {
if ($check !== $checkdigit) {
$isbnbody = self::_extractISBNBody($isbnn);
if ($isbnbody === false) {
$registrationgroup = false;
$r = self::_isbnBodyParts($isbnbody, $registrationgroup, $subbody);
/* check for undefined registrationgroup */
if (strlen($registrationgroup) == 0) {
$r = self::_isbnSubbodyParts($subbody, $registrationgroup,
$registrant, $publication);
/* not yet standarized */
// {{{ _isbnVersionGuess()
* Guesses the version of an ISBN
* @param string $isbn ISBN Number of which the Version to guess
* @return integer|falseVersion Value or false (ISBN_VERSION_NONE) if failed
private static function _isbnVersionGuess($isbn)
$isbn = self::_normaliseISBN($isbn);
* Validate an ISBN Version value
* @param mixed $ver version to be checked being a valid ISBN Version
* @return bool true if value is valid, false if not
private static function _isbnVersionIs($ver)
// {{{ _isbnVersionIsValid()
* Validate an ISBN value being a valid (identifyable -10 / -13) value
* @param mixed $ver value to be checked being a valid ISBN Version
* @return bool true if value is valid, false if not
private static function _isbnVersionIsValid($ver)
$r = self::_isbnVersionIs($ver);
* downformat "any" ISBN Number to the very basics
* an isbn number is a 10 or 13 digit. with the
* 10 digit string, the last digit can be 0-9 and
* X as well, all other are 0-9 only
* additionally this fucntion can be used to validate
* the isbn against correct length and chars
* @param string $isbn ISBN String to normalise
* @return string|falsenormalised ISBN Number or false if the function was
* not able to normalise the input
private static function _normaliseISBN($isbn)
/* normalize (trim & case)*/
/* remove lang specific prefix (if any) */
$isbn = self::_normaliseISBNremoveLangSpecific($isbn);
/* remove ISBN-10: or ISBN-13: prefix (if any) */
$prefix = substr($isbn, 0, 8);
if ($prefix == 'ISBN-10:' || $prefix == 'ISBN-13:') {
/* remove lang specific prefix again (if any) */
$isbn = self::_normaliseISBNremoveLangSpecific($isbn);
/* remove "ISBN" prefix (if any)*/
if (substr($isbn, 0, 4) == 'ISBN') {
/* remove cosmetic chars and different type of spaces */
$isbn = str_replace(array('-', ' ', '\t', '\n'), '', $isbn);
/* take the length to check and differ between versions
* sothat a syntaxcheck can be made */
if ($l != 10 && $l != 13) {
// {{{ _normaliseISBNremoveLangSpecific()
* helper function for _normaliseISBN to
* remove lang sepcific ISBN prefix
* @param string $isbn ISBN String to check (partially normalised)
* @return string input value passed through helper
private static function _normaliseISBNremoveLangSpecific($isbn)
if (substr($isbn, 0, $l) == $lang) {
* converts an ISBN number from one version to another
* can convert ISBN-10 to ISBN-13 and ISBN-13 to ISBN-10
* @param string $isbnin ISBN to convert, must be a valid ISBN Number
* @param integer $verfrom version value of the input ISBN
* @param integer $verto version value to convert to
* @return string|falseconverted ISBN Number or false if conversion failed
public static function convert($isbnin, $verfrom = ISBN_VERSION_ISBN_10,
$verto = ISBN_VERSION_ISBN_13)
if (!self::_isbnVersionIsValid($verfrom)) {
if (!self::_isbnVersionIsValid($verto)) {
$r = self::validate($isbnin, $verfrom);
$isbnn = self::_normaliseISBN($isbnin);
/* input is ok now, let's convert */
$isbnbody = self::_extractISBNBody($isbnn);
if ($isbnbody === false) {
$isbnout = '978' . $isbnbody . self::_checkdigitISBN13($isbnbody);
$isbnbody = self::_extractISBNBody($isbnn);
if ($isbnbody === false) {
$isbnout = $isbnbody . self::_checkdigitISBN10($isbnbody);
/* version is the same so there is no need to convert */
* Get the Checkdigit Part of ISBN Number
* @return string|falseCheckdigit or false if failed
$check = self::_checkdigitISBN10($this->_getISBNBody());
$check = self::_checkdigitISBN13($this->_getISBNBody());
* Get the EAN Prefix of ISBN Number (ISBN-13)
* @return string|falseEAN Prefix or false if failed
* Get the Registrationgroup Part of the ISBN Number
* @return string|falseGroup Identifier or false if failed
return $this->isbn_group;
* Setter for the Registrationgroup Part of the ISBN Number
* @param string $group Registrationsgroup to set
* @throws ISBN_Exception in case it fails
private function _setGroup($group)
$testbody = substr($group . '000000000', 0, 9);
$testgroup = self::_extractGroup($testbody);
if ($testgroup === false ) {
if ($testgroup != $group) {
$this->isbn_group = $group;
* @return string ISBN Number (unformatted); empty string if this is
$r = self::_isbnVersionIsValid($ver);
$isbn .= $this->_getISBNBody();
// {{{ getISBNDisplayable()
* Get whole ISBN Number in a displayable fashion (see Handbook p. 15)
* @param string $format Formatstring 1-4 Chars:
* each character is a control char:
* #1 i or not: use international pre-prefix
* #2 i or not: "ISBN" in front or v: incl. version
* #3 : or not: insert a ":"
* #4 - or not: use - after EAN (ISBN 13 only)
* #4 or =: use - between each ISBN part
* ' --' 978-0-385-33941-4
* classic displayable ISBN
* ' v:-' ISBN-13: 978-0385339414
* ISBN-Format used by amazon
* 'iv:=' ISBN-13: 978-0-385-33941-4
* full blown: more is more!
* @return string ISBN Number (formatted); empty string if this is
$format = 'iv:='; //edit $this->ISBNFormatstring;
$format = substr($format . ' ', 0, 4);
$r = self::_isbnVersionIsValid($ver);
if (strlen($isbn)) $isbn .= ' ';
if ($format[1] == 'i' || $format[1] == 'v') {
if ($format[3] == '-' || $format[3] == '=') {
$isbn .= $this->getGroup() . $seperator;
$isbn .= $this->getTitle() . $seperator;
* @param string $isbn ISBN Number
* this is a valid ISBN Number or it is an Empty string
* which will reset the class
* @throws ISBN_Exception in case it fails
$this->isbn_publisher = '';
$isbnn = self::_normaliseISBN($isbn);
$ver = self::_getVersion($isbnn);
'ISBN Version of passed ISBN (' . $ver . ') '.
'does not match existing (' . $this->ver . ').'
$body = self::_extractISBNBody($isbnn);
$this->_setISBNBody($body);
'Invalid ISBN (invalid body "' . $body . '")', $e
* @return string ISBN Body (not an offical term)
private function _getISBNBody()
$body .= $this->_getISBNSubbody();
* @param string $body ISBNBody
* @throws ISBN_Exception in case it fails
private function _setISBNBody($body)
/* validate body by extracting and validating parts */
$r = self::_isbnBodyParts($body, $group, $subbody);
$this->_setGroup($group);
throw new Exception('Invalid Body: Group is invalid', $e);
$this->_setISBNSubbody($subbody);
'Invalid Body: Subbody is invalid (' . $e->getMessage() . ')', $e
private function _getISBNSubbody()
* Setter for the ISBN Subbody
* @param string $subbody ISBN Subbody
* @throws ISBN_Exception in case it fails
private function _setISBNSubbody($subbody)
/* validate by setting apart */
$groupid = intval($this->isbn_group);
$r = self::_isbnSubbodyParts($subbody, $groupid, $registrant, $publication);
/* edit+ setter/getter for Registrant/Publisher and Title/Publication */
$this->isbn_publisher = $registrant;
$this->isbn_title = $publication;
* Get the Publication Part of the ISBN Number
* @return string|falsePublisher or false if failed
return $this->isbn_publisher;
* Get the Title Part of the ISBN Number
* @return string|falseTitle or false if failed
return $this->isbn_title;
* Returns this ISBN validity
* @param string $isbn ISBN to validate
* @param integer $ver ISBN-Version to validate against
* @return integer|false Version value of a valid ISBN or false
public static function validate($isbn, $ver = ISBN_DEFAULT_INPUTVERSION)
$r = self::_isbnVersionIs($ver);
$ver = self::_isbnVersionGuess($isbn);
if (self::_isbnVersionIsValid($ver) === false) {
$r = self::_isIsbnValid($isbn, $ver);
* Returns version of this objects ISBN
* @return integer|false Version value or ISBN_VERSION_NONE
* Guesses ISBN version of passed string
* Note: This is not Validation. To get the validated
* version of an ISBN Number use self::validate();
* @param string $isbn ISBN Number to guess Version of
* @return integer|false Version Value or false if failed
$r = self::_isbnVersionGuess($isbn);
|