Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Commit 0.1.0 alpha release

git-svn-id: https://svn.php.net/repository/pear/packages/File_MARC/trunk@223342 c90b9560-bf6c-de11-be94-00142212c4b1
  • Loading branch information...
commit 42d0c5710f2b681ab440cd436ff5bfa03e8d0300 1 parent 18897ce
Dan Scott authored
47 CHANGELOG
View
@@ -0,0 +1,47 @@
+0.0.9-alpha
+* Separate getFields() from getField(), getSubfields() from getSubfield()
+ to avoid forcing users to test is_array() after every call
+* Add addWarnings() / getWarnings() for records to avoid throwing an
+ exception for a non-fatal error
+* Fix examples, touch up phpdoc in preparation for call for votes
+
+0.0.8-alpha
+* Switch to PEAR_Exception for error handling
+
+0.0.7-alpha
+* Implement useful key() overrides for key=>value iteration through
+ fields and subfields
+* Adjust to new Structures_LinkedList_Double names
+
+0.0.6-alpha
+* Remove package globals, define class constants & static vars instead
+* Change addField/Subfield() to append..(), prepend...(), and insert...()
+
+0.0.5-alpha
+* Work towards a more consistent API (delete getAllSubfields)
+* Make PCRE expressions in getFields() and deleteFields() optional.
+* Make duplicate() actually return a deep copy of a record.
+* Stronger, better, faster (now with typehints)
+* Iterate with foreach() everywhere now
+
+0.0.4-alpha
+* Adjust to Structures_Linked_List package name change and minor API changes
+* Adhere to PEAR CS (thanks PHP_CodeSniffer!)
+* Correct sloppy use of references (thanks E_STRICT!)
+* Okay, this time real error handling using PEAR_ErrorStack
+* Prepare first package for PEPR
+
+0.0.3-alpha
+* Split MARC into separate File_MARC and Structure_Linked_List packages (with corresponding renaming of classes and constants)
+* Adopt PEAR naming conventions (s/MARC/File_MARC/)
+* Initial stab at PEAR_ErrorStack error handling
+
+0.0.2-alpha
+* Fix marc_004.phpt: explicitly compare object references with === operator
+* Document all constants.
+* Fix MARC_Field::deleteSubfield() function
+* Add this ChangeLog
+
+0.0.1-alpha
+* First publicly available release, based on MARC decoding algorithm from
+the emilda.org php-marc package with a completely new API and class hierarchy
504 LICENSE
View
@@ -0,0 +1,504 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+ When we speak of free software, we are referring to freedom of use,
+not price. Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
+
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+ GNU LESSER GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the library's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ <signature of Ty Coon>, 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
+
+
376 MARC.php
View
@@ -0,0 +1,376 @@
+<?php
+
+/* vim: set expandtab shiftwidth=4 tabstop=4 softtabstop=4 foldmethod=marker: */
+
+/**
+ * Parser for MARC records
+ *
+ * This package is based on the PHP MARC package, originally called "php-marc",
+ * that is part of the Emilda Project (http://www.emilda.org). Christoffer
+ * Landtman generously agreed to make the "php-marc" code available under the
+ * GNU LGPL so it could be used as the basis of this PEAR package.
+ *
+ * PHP version 5
+ *
+ * LICENSE: This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation; either version 2.1 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * @category File Formats
+ * @package File_MARC
+ * @author Christoffer Landtman <landtman@realnode.com>
+ * @author Dan Scott <dscott@laurentian.ca>
+ * @copyright 2003-2006 Oy Realnode Ab, Dan Scott
+ * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
+ * @version CVS: $Id$
+ * @link http://pear.php.net/package/File_MARC
+ * @example read.php Retrieve specific fields and subfields from a record
+ * @example subfields.php Create new subfields and add them in specific order
+ * @example marc_yaz.php Pretty print a MARC record retrieved through the PECL yaz extension
+ */
+
+require_once 'PEAR/Exception.php';
+require_once 'Structures/LinkedList/Double.php';
+require_once 'File/MARC/Record.php';
+require_once 'File/MARC/Field.php';
+require_once 'File/MARC/Control_Field.php';
+require_once 'File/MARC/Data_Field.php';
+require_once 'File/MARC/Subfield.php';
+require_once 'File/MARC/Exception.php';
+require_once 'File/MARC/List.php';
+
+// {{{ class File_MARC
+/**
+ * The main File_MARC class enables you to return File_MARC_Record
+ * objects from a stream or string.
+ *
+ * @category File Formats
+ * @package File_MARC
+ * @author Christoffer Landtman <landtman@realnode.com>
+ * @author Dan Scott <dscott@laurentian.ca>
+ * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
+ * @link http://pear.php.net/package/File_MARC
+ */
+class File_MARC {
+
+ // {{{ constants
+
+ /**
+ * MARC records retrieved from a file
+ */
+ const SOURCE_FILE = 1;
+
+ /**
+ * MARC records retrieved from a binary string
+ */
+ const SOURCE_STRING = 2;
+
+ /**
+ * Hexadecimal value for Subfield indicator
+ */
+ const SUBFIELD_INDICATOR = "\x1F";
+
+ /**
+ * Hexadecimal value for End of Field
+ */
+ const END_OF_FIELD = "\x1E";
+
+ /**
+ * Hexadecimal value for End of Record
+ */
+ const END_OF_RECORD = "\x1D";
+
+ /**
+ * Length of the Directory
+ */
+ const DIRECTORY_ENTRY_LEN = 12;
+
+ /**
+ * Length of the Leader
+ */
+ const LEADER_LEN = 24;
+
+ /**
+ * Maximum record length
+ */
+ const MAX_RECORD_LENGTH = 99999;
+ // }}}
+
+ // {{{ properties
+ /**
+ * Source containing raw records
+ *
+ * @var resource
+ */
+ protected $source;
+
+ /**
+ * Source type (SOURCE_FILE or SOURCE_STRING)
+ *
+ * @var int
+ */
+ protected $type;
+ // }}}
+
+ // {{{ Constructor: function __construct()
+ /**
+ * Read in MARC records
+ *
+ * This function reads in MARC record files or strings that
+ * contain one or more MARC records.
+ *
+ * <code>
+ * <?php
+ * // Retrieve MARC records from a file
+ * $journals = new File_MARC('journals.mrc', SOURCE_FILE);
+ *
+ * // Retrieve MARC records from a string (e.g. Z39 query results)
+ * $monographs = new File_MARC($raw_marc, SOURCE_STRING);
+ * ?>
+ * </code>
+ *
+ * @param string $in Name of the file, or a raw MARC string
+ * @param int $source Source of the input, either SOURCE_FILE
+ * or SOURCE_STRING
+ */
+ function __construct($source, $type = self::SOURCE_FILE)
+ {
+ switch ($type) {
+
+ case self::SOURCE_FILE:
+ if (!file_exists($source)) {
+ $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_FILE], array('filename' => $source));
+ throw new File_MARC_Exception($errorMessage, File_MARC_Exception::ERROR_INVALID_FILE);
+ }
+ $this->type = self::SOURCE_FILE;
+ $this->source = fopen($source, 'rb');
+ break;
+
+ case self::SOURCE_STRING:
+ $this->type = self::SOURCE_STRING;
+ $this->source = explode(File_MARC::END_OF_RECORD, $source);
+ break;
+
+ default:
+ throw new File_MARC_Exception(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_SOURCE], File_MARC_Exception::ERROR_INVALID_SOURCE);
+ }
+ }
+ // }}}
+
+ // {{{ nextRaw()
+ /**
+ * Return the next raw MARC record
+ *
+ * Returns the next raw MARC record, unless all records already have
+ * been read.
+ *
+ * @return string Either a raw record or false
+ */
+ function nextRaw()
+ {
+ if ($this->type == self::SOURCE_FILE) {
+ $record = stream_get_line($this->source, File_MARC::MAX_RECORD_LENGTH, File_MARC::END_OF_RECORD);
+
+ // Remove illegal stuff that sometimes occurs between records
+ $record = preg_replace('/^[\\x0a\\x0d\\x00]+/', "", $record);
+
+ } elseif ($this->type == self::SOURCE_STRING) {
+ $record = array_shift($this->source);
+ }
+
+ // Exit if we are at the end of the file
+ if (!$record) {
+ return false;
+ }
+
+ // Append the end of record we lost during stream_get_line() or explode()
+ $record .= File_MARC::END_OF_RECORD;
+
+ // Validate record structure
+ if (strlen($record) < 5) {
+ throw new File_MARC_Exception(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_MISSING_LENGTH], File_MARC_Exception::ERROR_MISSING_LENGTH);
+ }
+ $record_length = substr($record, 0, 5);
+ if (!preg_match("/^\d{5}$/", $record_length)) {
+ $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_NONNUMERIC_LENGTH], array("record_length" => $record_length));
+ throw new File_MARC_Exception($errorMessage, File_MARC_Exception::ERROR_NONNUMERIC_LENGTH);
+ }
+ if ($record_length != strlen($record)) {
+ $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INCORRECT_LENGTH], array("record_length" => $record_length, "actual" => strlen($record)));
+ throw new File_MARC_Exception($errorMessage, File_MARC_Exception::ERROR_INCORRECT_LENGTH);
+ }
+
+ return $record;
+ }
+ // }}}
+
+ // {{{ next()
+ /**
+ * Return next {@link File_MARC_Record} object
+ *
+ * Decodes the next raw MARC record and returns the {@link File_MARC_Record}
+ * object.
+ * <code>
+ * <?php
+ * // Retrieve a set of MARC records from a file
+ * $journals = new File_MARC('journals.mrc', SOURCE_FILE);
+ *
+ * // Iterate through the retrieved records
+ * while ($record = $journals->next()) {
+ * print $record;
+ * print "\n";
+ * }
+ *
+ * ?>
+ * </code>
+ *
+ * @return File_MARC_Record next record, or false if there are
+ * no more records
+ */
+ function next()
+ {
+ if ($raw = $this->nextRaw()) {
+ return $this->_decode($raw);
+ } else {
+ return false;
+ }
+ }
+ // }}}
+
+ // {{{ _decode()
+ /**
+ * Decode a given raw MARC record
+ *
+ * Port of Andy Lesters MARC::File::USMARC->decode() Perl function into PHP.
+ *
+ * @param string $text Raw MARC record
+ * @return File_MARC_Record Decoded File_MARC_Record object
+ */
+ private function _decode($text)
+ {
+ if (!preg_match("/^(\d{5})/", $text, $matches)) {
+ $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_NONNUMERIC_LENGTH], array("record_length" => substr($text, 0, 5)));
+ throw new File_MARC_Exception($errorMessage, File_MARC_Exception::ERROR_NONNUMERIC_LENGTH);
+ }
+
+ $marc = new File_MARC_Record();
+
+ // Store record length
+ $record_length = $matches[1];
+
+ if ($record_length != strlen($text)) {
+ $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INCORRECT_LENGTH], array("record_length" => substr($record_length), "actual" => strlen($text)));
+ throw new File_MARC_Exception($errorMessage, File_MARC_Exception::ERROR_INCORRECT_LENGTH);
+ }
+
+ if (substr($text, -1, 1) != File_MARC::END_OF_RECORD)
+ throw new File_MARC_Exception(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_TERMINATOR], File_MARC_Exception::ERROR_INVALID_TERMINATOR);
+
+ // Store leader
+ $marc->setLeader(substr($text, 0, File_MARC::LEADER_LEN));
+
+ // bytes 12 - 16 of leader give offset to the body of the record
+ $data_start = 0 + substr($text, 12, 5);
+
+ // immediately after the leader comes the directory (no separator)
+ $dir = substr($text, File_MARC::LEADER_LEN, $data_start - File_MARC::LEADER_LEN - 1); // -1 to allow for \x1e at end of directory
+
+ // character after the directory must be \x1e
+ if (substr($text, $data_start-1, 1) != File_MARC::END_OF_FIELD) {
+ throw new File_MARC_Exception(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_NO_DIRECTORY], File_MARC_Exception::ERROR_NO_DIRECTORY);
+ }
+
+ // All directory entries 12 bytes long, so length % 12 must be 0
+ if (strlen($dir) % File_MARC::DIRECTORY_ENTRY_LEN != 0) {
+ throw new File_MARC_Exception(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_DIRECTORY_LENGTH], File_MARC_Exception::ERROR_INVALID_DIRECTORY_LENGTH);
+ }
+
+ // go through all the fields
+ $nfields = strlen($dir) / File_MARC::DIRECTORY_ENTRY_LEN;
+ for ($n=0; $n<$nfields; $n++) {
+ // As pack returns to key 1, leave place 0 in list empty
+ list(, $tag) = unpack("A3", substr($dir, $n*File_MARC::DIRECTORY_ENTRY_LEN, File_MARC::DIRECTORY_ENTRY_LEN));
+ list(, $len) = unpack("A3/A4", substr($dir, $n*File_MARC::DIRECTORY_ENTRY_LEN, File_MARC::DIRECTORY_ENTRY_LEN));
+ list(, $offset) = unpack("A3/A4/A5", substr($dir, $n*File_MARC::DIRECTORY_ENTRY_LEN, File_MARC::DIRECTORY_ENTRY_LEN));
+
+ // Check directory validity
+ if (!preg_match("/^[0-9A-Za-z]{3}$/", $tag)) {
+ $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_DIRECTORY_TAG], array("tag" => $tag));
+ throw new File_MARC_Exception($errorMessage, File_MARC_Exception::ERROR_INVALID_DIRECTORY_TAG);
+ }
+ if (!preg_match("/^\d{4}$/", $len)) {
+ $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_DIRECTORY_TAG_LENGTH], array("tag" => $tag, "len" => $len));
+ throw new File_MARC_Exception($errorMessage, File_MARC_Exception::ERROR_INVALID_DIRECTORY_TAG_LENGTH);
+ }
+ if (!preg_match("/^\d{5}$/", $offset)) {
+ $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_DIRECTORY_OFFSET], array("tag" => $tag, "offset" => $offset));
+ throw new File_MARC_Exception($errorMessage, File_MARC_Exception::ERROR_INVALID_DIRECTORY_OFFSET);
+ }
+ if ($offset + $len > $record_length) {
+ $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_DIRECTORY], array("tag" => $tag));
+ throw new File_MARC_Exception($errorMessage, File_MARC_Exception::ERROR_INVALID_DIRECTORY);
+ }
+
+ $tag_data = substr($text, $data_start + $offset, $len);
+
+ if (substr($tag_data, -1, 1) == File_MARC::END_OF_FIELD) {
+ /* get rid of the end-of-tag character */
+ $tag_data = substr($tag_data, 0, -1);
+ $len--;
+ } else {
+ $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_FIELD_EOF], array("tag" => $tag));
+ throw new File_MARC_Exception($errorMessage, File_MARC_Exception::ERROR_FIELD_EOF);
+ }
+
+ if (preg_match("/^\d+$/", $tag) and ($tag < 10)) {
+ $marc->appendField(new File_MARC_Control_Field($tag, $tag_data));
+ } else {
+ $subfields = split(File_MARC::SUBFIELD_INDICATOR, $tag_data);
+ $indicators = array_shift($subfields);
+
+ if (strlen($indicators) > 2 || strlen($indicators) == 0) {
+ $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_INDICATORS], array("tag" => $tag, "indicators" => $indicators));
+ $marc->addWarning($errorMessage);
+ list($ind1,$ind2) = array(" ", " ");
+ } else {
+ $ind1 = substr($indicators, 0, 1);
+ $ind2 = substr($indicators, 1, 1);
+ }
+
+ // Split the subfield data into subfield name and data pairs
+ $subfield_data = array();
+ foreach ($subfields as $subfield) {
+ if (strlen($subfield) > 0) {
+ $subfield_data[] = new File_MARC_Subfield(substr($subfield, 0, 1), substr($subfield, 1));
+ } else {
+ $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_EMPTY_SUBFIELD], array("tag" => $tag));
+ throw new File_MARC_Exception($errorMessage, File_MARC_Exception::ERROR_EMPTY_SUBFIELD);
+ }
+ }
+
+ if (!isset($subfield_data)) {
+ $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_EMPTY_SUBFIELD], array("tag" => $tag));
+ throw new File_MARC_Exception($errorMessage, File_MARC_Exception::ERROR_EMPTY_SUBFIELD);
+ }
+
+ $marc->appendField(new File_MARC_Data_Field($tag, $subfield_data, $ind1, $ind2));
+ }
+ }
+
+ return $marc;
+ }
+ // }}}
+
+}
+// }}}
+
171 MARC/Control_Field.php
View
@@ -0,0 +1,171 @@
+<?php
+
+/* vim: set expandtab shiftwidth=4 tabstop=4 softtabstop=4 foldmethod=marker: */
+
+/**
+ * Parser for MARC records
+ *
+ * This package is based on the PHP MARC package, originally called "php-marc",
+ * that is part of the Emilda Project (http://www.emilda.org). Christoffer
+ * Landtman generously agreed to make the "php-marc" code available under the
+ * GNU LGPL so it could be used as the basis of this PEAR package.
+ *
+ * PHP version 5
+ *
+ * LICENSE: This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation; either version 2.1 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * @category File Formats
+ * @package File_MARC
+ * @author Christoffer Landtman <landtman@realnode.com>
+ * @author Dan Scott <dscott@laurentian.ca>
+ * @copyright 2003-2006 Oy Realnode Ab, Dan Scott
+ * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
+ * @version CVS: $Id$
+ */
+
+// {{{ class File_MARC_Control_Field extends File_MARC_Field
+/**
+ * The File_MARC_Control_Field class represents a single control field
+ * in a MARC record.
+ *
+ * A MARC control field consists of a tag name and control data.
+ *
+ * @category File Formats
+ * @package File_MARC
+ * @author Christoffer Landtman <landtman@realnode.com>
+ * @author Dan Scott <dscott@laurentian.ca>
+ * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
+ * @link http://pear.php.net/package/File_MARC
+ */
+class File_MARC_Control_Field extends File_MARC_Field {
+
+ // {{{ Properties
+ /**
+ * Value of field, if field is a Control field
+ * @var string
+ */
+ protected $data;
+ // }}}
+
+ // {{{ Constructor: function __construct()
+ /**
+ * Field init function
+ *
+ * Create a new {@link File_MARC_Control_Field} object from passed arguments
+ *
+ * @param string $tag tag
+ * @param string $data control field data
+ * @param string $ind1 placeholder for class strictness
+ * @param string $ind2 placeholder for class strictness
+ */
+ function __construct($tag, $data, $ind1 = null, $ind2 = null)
+ {
+ $this->data = $data;
+ parent::__construct($tag);
+
+ }
+ // }}}
+
+ // {{{ Destructor: function __destruct()
+ /**
+ * Destroys the control field
+ */
+ function __destruct()
+ {
+ $this->data = null;
+ parent::__destruct();
+ }
+ // }}}
+
+ // {{{ Explicit destructor: function delete()
+ /**
+ * Destroys the control field
+ */
+ function delete()
+ {
+ $this->__destruct();
+ }
+ // }}}
+
+ // {{{ getData()
+ /**
+ * Get control field data
+ *
+ * @return string returns data in control field
+ */
+ function getData()
+ {
+ return $this->data;
+ }
+ // }}}
+
+ // {{{ isEmpty()
+ /**
+ * Is empty
+ *
+ * Checks if the field contains data
+ * @return bool Returns true if the field is empty, otherwise false
+ */
+ function isEmpty()
+ {
+ return ($this->data) ? false : true;
+ }
+ // }}}
+
+ // {{{ setData()
+ /**
+ * Set control field data
+ *
+ * @param string $data data for the control field
+ * @return bool returns the new data in the control field
+ */
+ function setData($data)
+ {
+ $this->data = $data;
+ return $this->getData();
+ }
+ // }}}
+
+ // {{{ __toString()
+ /**
+ * Return as a formatted string
+ *
+ * Return the control field as a formatted string for pretty printing
+ *
+ * @return string Formatted output of control Field
+ */
+ function __toString()
+ {
+ return sprintf("%3s %s", $this->tag, $this->data);
+ }
+ // }}}
+
+ // {{{ toRaw()
+ /**
+ * Return as raw MARC
+ *
+ * Return the control field formatted in Raw MARC for saving into MARC files
+ *
+ * @return string Raw MARC
+ */
+ function toRaw()
+ {
+ return $this->data.File_MARC::END_OF_FIELD;
+ }
+ // }}}
+
+}
+// }}}
+
467 MARC/Data_Field.php
View
@@ -0,0 +1,467 @@
+<?php
+
+/* vim: set expandtab shiftwidth=4 tabstop=4 softtabstop=4 foldmethod=marker: */
+
+/**
+ * Parser for MARC records
+ *
+ * This package is based on the PHP MARC package, originally called "php-marc",
+ * that is part of the Emilda Project (http://www.emilda.org). Christoffer
+ * Landtman generously agreed to make the "php-marc" code available under the
+ * GNU LGPL so it could be used as the basis of this PEAR package.
+ *
+ * PHP version 5
+ *
+ * LICENSE: This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation; either version 2.1 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * @category File Formats
+ * @package File_MARC
+ * @author Christoffer Landtman <landtman@realnode.com>
+ * @author Dan Scott <dscott@laurentian.ca>
+ * @copyright 2003-2006 Oy Realnode Ab, Dan Scott
+ * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
+ * @version CVS: $Id$
+ */
+
+// {{{ class File_MARC_Data_Field extends File_MARC_Field
+/**
+ * The File_MARC_Data_Field class represents a single field in a MARC record.
+ *
+ * A MARC data field consists of a tag name, two indicators which may be null,
+ * and zero or more subfields represented by {@link File_MARC_Subfield} objects.
+ * Subfields are held within a linked list structure.
+ *
+ * @category File Formats
+ * @package File_MARC
+ * @author Christoffer Landtman <landtman@realnode.com>
+ * @author Dan Scott <dscott@laurentian.ca>
+ * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
+ * @link http://pear.php.net/package/File_MARC
+ */
+class File_MARC_Data_Field extends File_MARC_Field {
+
+ // {{{ properties
+ /**
+ * Value of the first indicator
+ * @var string
+ */
+ protected $ind1;
+
+ /**
+ * Value of the second indicator
+ * @var string
+ */
+ protected $ind2;
+
+ /**
+ * Linked list of subfields
+ * @var File_MARC_List
+ */
+ protected $subfields;
+
+ // }}}
+
+ // {{{ Constructor: function __construct()
+ /**
+ * {@link File_MARC_Data_Field} constructor
+ *
+ * Create a new {@link File_MARC_Data_Field} object. The only required
+ * parameter is a tag. This enables programs to build up new fields
+ * programmatically.
+ *
+ * <code>
+ * // Example: Create a new data field
+ *
+ * // We can optionally create an array of subfields first
+ * $subfields[] = new File_MARC_Data_Subfield('a', 'Scott, Daniel.');
+ *
+ * // Create the new 100 field complete with a _a subfield and an indicator
+ * $new_field = new File_MARC_Data_Field('100', $subfields, 0, null);
+ * </code>
+
+ * @param string $tag tag
+ * @param array $subfields array of {@link File_MARC_Subfield} objects
+ * @param string $ind1 first indicator
+ * @param string $ind2 second indicator
+ */
+ function __construct($tag, array $subfields = null, $ind1 = null, $ind2 = null)
+ {
+ $this->subfields = new File_MARC_List();
+
+ parent::__construct($tag);
+
+ $this->ind1 = $this->_validateIndicator($ind1);
+ $this->ind2 = $this->_validateIndicator($ind2);
+
+ // we'll let users add subfields after if they so desire
+ if ($subfields) {
+ $this->addSubfields($subfields);
+ }
+ }
+ // }}}
+
+ // {{{ Destructor: function __destruct()
+ /**
+ * Destroys the data field
+ */
+ function __destruct()
+ {
+ $this->subfields = null;
+ $this->ind1 = null;
+ $this->ind2 = null;
+ parent::__destruct();
+ }
+ // }}}
+
+ // {{{ Explicit destructor: function delete()
+ /**
+ * Destroys the data field
+ */
+ function delete()
+ {
+ $this->__destruct();
+ }
+ // }}}
+
+ // {{{ protected function _validateIndicator()
+ /**
+ * Validates an indicator field
+ *
+ * Validates the value passed in for an indicator. This routine ensures
+ * that an indicator is a single character. If the indicator value is null,
+ * then this method returns a single character.
+ *
+ * If the indicator value contains more than a single character, this
+ * throws an exception.
+ *
+ * @param string $indicator Value of the indicator to be validated
+ * @return string Returns the indicator, or space if the indicator was null
+ */
+ private function _validateIndicator($indicator)
+ {
+ if ($indicator == null) {
+ $indicator = ' ';
+ } elseif (strlen($indicator) > 1) {
+ $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_INDICATOR], array("tag" => $this->getTag(), "indicator" => $indicator));
+ throw new File_MARC_Exception($errorMessage, File_MARC_Exception::ERROR_INVALID_INDICATOR);
+ }
+ return $indicator;
+ }
+ // }}}
+
+ // {{{ appendSubfield()
+ /**
+ * Appends subfield to subfield list
+ *
+ * Adds a File_MARC_Subfield object to the end of the existing list
+ * of subfields.
+ *
+ * @param File_MARC_Subfield $new_subfield The subfield to add
+ * @return File_MARC_Subfield the new File_MARC_Subfield object
+ */
+ function appendSubfield(File_MARC_Subfield $new_subfield)
+ {
+ /* Append as the last field in the record */
+ $this->subfields->appendNode($new_subfield);
+ return $new_subfield;
+ }
+ // }}}
+
+ // {{{ prependSubfield()
+ /**
+ * Prepends subfield to subfield liss
+ *
+ * Adds a File_MARC_Subfield object to the start of the existing list
+ * of subfields.
+ *
+ * @param File_MARC_Subfield $new_subfield The subfield to add
+ * @return File_MARC_Subfield the new File_MARC_Subfield object
+ */
+ function prependSubfield(File_MARC_Subfield $new_subfield)
+ {
+ $this->subfields->prependNode($new_subfield);
+ return $new_subfield;
+ }
+ // }}}
+
+ // {{{ insertSubfield()
+ /**
+ * Inserts a field in the MARC record relative to an existing field
+ *
+ * Inserts a {@link File_MARC_Subfield} object before or after an existing
+ * subfield.
+ *
+ * @param File_MARC_Subfield $new_field The subfield to add
+ * @param File_MARC_Subfield $existing_field The target subfield
+ * @param bool $before Insert the subfield before the existing subfield
+ * if true, after the existing subfield if false
+ * @return File_MARC_Subfield The new subfield
+ */
+ function insertSubfield(File_MARC_Subfield $new_field, File_MARC_Subfield $existing_field, $before = false)
+ {
+ switch ($before) {
+ /* Insert before the specified subfield in the record */
+ case true:
+ $this->subfields->insertNode($new_field, $existing_field, true);
+ break;
+
+ /* Insert after the specified subfield in the record */
+ case false:
+ $this->subfields->insertNode($new_field, $existing_field);
+ break;
+
+ default:
+ $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INSERTSUBFIELD_MODE], array("mode" => $mode));
+ throw new File_MARC_Exception($errorMessage, File_MARC_Exception::ERROR_INSERTSUBFIELD_MODE);
+ return false;
+ }
+ return $new_field;
+ }
+ // }}}
+
+ // {{{ addSubfields()
+ /**
+ * Adds an array of subfields to a {@link File_MARC_Data_Field} object
+ *
+ * Appends subfields to existing subfields in the order in which
+ * they appear in the array. For finer grained control of the subfield
+ * order, use {@link appendSubfield()}, {@link prependSubfield()},
+ * or {@link insertSubfield()} to add each subfield individually.
+ *
+ * @param array $subfields array of {@link File_MARC_Subfield} objects
+ * @return int returns the number of subfields that were added
+ */
+ function addSubfields(array $subfields)
+ {
+ /*
+ * Just in case someone passes in a single File_MARC_Subfield
+ * instead of an array
+ */
+ if ($subfields instanceof File_MARC_Subfield) {
+ $this->appendSubfield($subfields);
+ return 1;
+ }
+
+ // Add subfields
+ $cnt = 0;
+ foreach ($subfields as $subfield) {
+ $this->appendSubfield($subfield);
+ $cnt++;
+ }
+
+ return $cnt;
+ }
+ // }}}
+
+ // {{{ deleteSubfield()
+ /**
+ * Delete a subfield from the field.
+ *
+ * @return bool Success or failure
+ */
+ function deleteSubfield(File_MARC_Subfield $subfield)
+ {
+ if ($this->subfields->deleteNode($subfield)) {
+ return true;
+ }
+ return false;
+ }
+ // }}}
+
+ // {{{ getIndicator()
+ /**
+ * Get the value of an indicator
+ *
+ * @param int $ind number of the indicator (1 or 2)
+ * @return string returns indicator value if it exists, otherwise false
+ */
+ function getIndicator($ind)
+ {
+ if ($ind == 1) {
+ return $this->ind1;
+ } elseif ($ind == 2) {
+ return $this->ind2;
+ } else {
+ $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_INDICATOR_REQUEST], array("indicator" => $indicator));
+ throw new File_MARC_Exception($errorMessage, File_MARC_Exception::ERROR_INVALID_INDICATOR_REQUEST);
+ }
+ return false;
+ }
+ // }}}
+
+ // {{{ setIndicator()
+ /**
+ * Set the value of an indicator
+ *
+ * @param int $ind number of the indicator (1 or 2)
+ * @param string $value value of the indicator
+ * @return string returns indicator value if it exists, otherwise false
+ */
+ function setIndicator($ind, $value)
+ {
+ switch ($ind) {
+
+ case 1:
+ $this->ind1 = $this->_validateIndicator($value);
+ break;
+
+ case 2:
+ $this->ind2 = $this->_validateIndicator($value);
+ break;
+
+ default:
+ $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_INDICATOR_REQUEST], array("indicator" => $ind));
+ throw new File_MARC_Exception($errorMessage, File_MARC_Exception::ERROR_INVALID_INDICATOR_REQUEST);
+ return false;
+ }
+
+ return getIndicator($ind);
+ }
+ // }}}
+
+ // {{{ getSubfield()
+ /**
+ * Returns the first subfield that matches a requested code.
+ *
+ * @param string $code subfield code for which the
+ * {@link File_MARC_Subfield} is retrieved
+ * @return File_MARC_Subfield returns the first subfield that matches
+ * $code, or false if no codes match $code
+ */
+ function getSubfield($code = null)
+ {
+ // iterate merrily through the subfields looking for the requested code
+ foreach ($this->subfields as $sf) {
+ if ($sf->getCode() == $code) {
+ return $sf;
+ }
+ }
+
+ // No matches were found
+ return false;
+ }
+ // }}}
+
+ // {{{ getSubfields()
+ /**
+ * Returns an array of subfields that match a requested code,
+ * or a {@link File_MARC_List} that contains all of the subfields
+ * if the requested code is null.
+ *
+ * @param string $code subfield code for which the
+ * {@link File_MARC_Subfield} is retrieved
+ * @return File_MARC_List|array returns a linked list of all subfields
+ * if $code is null, an array of {@link File_MARC_Subfield} objects if
+ * one or more subfields match, or false if no codes match $code
+ */
+ function getSubfields($code = null)
+ {
+ $results = array();
+
+ // return all subfields if no specific subfields were requested
+ if ($code === null) {
+ $results = $this->subfields;
+ return $results;
+ }
+
+ // iterate merrily through the subfields looking for the requested code
+ foreach ($this->subfields as $sf) {
+ if ($sf->getCode() == $code) {
+ $results[] = $sf;
+ }
+ }
+ return $results;
+ }
+ // }}}
+
+ // {{{ isEmpty()
+ /**
+ * Checks if the field is empty.
+ *
+ * Checks if the field is empty. If the field has at least one subfield
+ * with data, it is not empty.
+ *
+ * @return bool Returns true if the field is empty, otherwise false
+ */
+ function isEmpty()
+ {
+ // If $this->subfields is null, we must have deleted it
+ if (!$this->subfields) {
+ return true;
+ }
+
+ // Iterate through the subfields looking for some data
+ foreach ($this->subfields as $subfield) {
+ // Check if subfield has data
+ if (!$subfield->isEmpty()) {
+ return false;
+ }
+ }
+ // It is empty
+ return true;
+ }
+ // }}}
+
+ /**
+ * ========== OUTPUT METHODS ==========
+ */
+
+ // {{{ __toString()
+ /**
+ * Return Field formatted
+ *
+ * Return Field as a formatted string.
+ *
+ * @return string Formatted output of Field
+ */
+ function __toString()
+ {
+ // Variables
+ $lines = array();
+ // Process tag and indicators
+ $pre = sprintf("%3s %1s%1s", $this->tag, $this->ind1, $this->ind2);
+
+ // Process subfields
+ foreach ($this->subfields as $subfield) {
+ $lines[] = sprintf("%6s _%1s%s", $pre, $subfield->getCode(), $subfield->getData());
+ $pre = "";
+ }
+
+ return join("\n", $lines);
+ }
+ // }}}
+
+ // {{{ toRaw()
+ /**
+ * Return Field in Raw MARC
+ *
+ * Return the Field formatted in Raw MARC for saving into MARC files
+ *
+ * @return string Raw MARC
+ */
+ function toRaw()
+ {
+ $subfields = array();
+ foreach ($this->subfields as $subfield) {
+ if (!$subfield->isEmpty()) {
+ $subfields[] = $subfield->toRaw();
+ }
+ }
+ return $this->ind1.$this->ind2.implode("", $subfields).File_MARC::END_OF_FIELD;
+ }
+ // }}}
+}
+// }}}
+
211 MARC/Exception.php
View
@@ -0,0 +1,211 @@
+<?php
+
+/* vim: set expandtab shiftwidth=4 tabstop=4 softtabstop=4 foldmethod=marker: */
+
+/**
+ * Parser for MARC records
+ *
+ * This package is based on the PHP MARC package, originally called "php-marc",
+ * that is part of the Emilda Project (http://www.emilda.org). Christoffer
+ * Landtman generously agreed to make the "php-marc" code available under the
+ * GNU LGPL so it could be used as the basis of this PEAR package.
+ *
+ * PHP version 5
+ *
+ * LICENSE: This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation; either version 2.1 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * @category File Formats
+ * @package File_MARC
+ * @author Christoffer Landtman <landtman@realnode.com>
+ * @author Dan Scott <dscott@laurentian.ca>
+ * @copyright 2003-2006 Oy Realnode Ab, Dan Scott
+ * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
+ * @version CVS: $Id$
+ */
+
+// {{{ class File_MARC_Exception extends PEAR_Exception
+/**
+ * The File_MARC_Exception class enables error-handling
+ * for the File_MARC package.
+ *
+ * @category File Formats
+ * @package File_MARC
+ * @author Dan Scott <dscott@laurentian.ca>
+ * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
+ * @link http://pear.php.net/package/File_MARC
+ */
+class File_MARC_Exception extends PEAR_Exception {
+ // {{{ Error codes
+ /**
+ * File could not be opened
+ */
+ const ERROR_INVALID_FILE = -1;
+
+ /**
+ * User passed an unknown SOURCE_ constant
+ */
+ const ERROR_INVALID_SOURCE = -2;
+
+ /**
+ * MARC record ended with an invalid terminator
+ */
+ const ERROR_INVALID_TERMINATOR = -3;
+
+ /**
+ * No directory was found for the MARC record
+ */
+ const ERROR_NO_DIRECTORY = -4;
+
+ /**
+ * An entry in the MARC directory was not 12 bytes
+ */
+ const ERROR_INVALID_DIRECTORY_LENGTH = -5;
+
+ /**
+ * An entry in the MARC directory specified an invalid tag
+ */
+ const ERROR_INVALID_DIRECTORY_TAG = -6;
+
+ /**
+ * An entry in the MARC directory specified an invalid tag length
+ */
+ const ERROR_INVALID_DIRECTORY_TAG_LENGTH = -7;
+
+ /**
+ * An entry in the MARC directory specified an invalid field offset
+ */
+ const ERROR_INVALID_DIRECTORY_OFFSET = -8;
+
+ /**
+ * An entry in the MARC directory runs past the end of the record
+ */
+ const ERROR_INVALID_DIRECTORY = -9;
+
+ /**
+ * A field does not end with the expected end-of-field character
+ */
+ const ERROR_FIELD_EOF = -10;
+
+ /**
+ * A field has invalid indicators
+ */
+ const ERROR_INVALID_INDICATORS = -11;
+
+ /**
+ * A subfield is defined, but has no data
+ */
+ const ERROR_EMPTY_SUBFIELD = -12;
+
+ /**
+ * An indicator other than 1 or 2 was requested
+ */
+ const ERROR_INVALID_INDICATOR_REQUEST = -13;
+
+ /**
+ * An invalid mode for adding a field was specified
+ */
+ const ERROR_INSERTFIELD_MODE = -14;
+
+ /**
+ * An invalid object was passed instead of a File_MARC_Field object
+ */
+ const ERROR_INVALID_FIELD = -15;
+
+ /**
+ * An invalid object was passed instead of a File_MARC_Subfield object
+ */
+ const ERROR_INVALID_SUBFIELD = -16;
+
+ /**
+ * An invalid mode for adding a subfield was specified
+ */
+ const ERROR_INSERTSUBFIELD_MODE = -17;
+
+ /**
+ * The length in the MARC leader does not match the actual record length
+ */
+ const ERROR_INCORRECT_LENGTH = -18;
+
+ /**
+ * The length field in the leader was less than five characters long
+ */
+ const ERROR_MISSING_LENGTH = -19;
+
+ /**
+ * A five-digit length could not be found in the MARC leader
+ */
+ const ERROR_NONNUMERIC_LENGTH = -20;
+
+ /**
+ * Tag does not adhere to MARC standards
+ */
+ const ERROR_INVALID_TAG = -21;
+
+ /**
+ * A field has invalid indicators
+ */
+ const ERROR_INVALID_INDICATOR = -22;
+ // }}}
+
+ // {{{ error messages
+ public static $messages = array(
+ self::ERROR_EMPTY_SUBFIELD => 'No subfield data found in tag "%tag%"',
+ self::ERROR_FIELD_EOF => 'Field for tag "%tag%" does not end with an end of field character',
+ self::ERROR_INCORRECT_LENGTH => 'Invalid record length: Leader says "%record_length%" bytes; actual record length is "%actual%"',
+ self::ERROR_INSERTFIELD_MODE => 'insertField() mode "%mode%" was not recognized',
+ self::ERROR_INSERTSUBFIELD_MODE => 'insertSubfield() mode "%mode%" was not recognized',
+ self::ERROR_INVALID_DIRECTORY => 'Directory entry for tag "%tag%" runs past the end of the record',
+ self::ERROR_INVALID_DIRECTORY_LENGTH => 'Invalid directory length',
+ self::ERROR_INVALID_DIRECTORY_OFFSET => 'Invalid offset "%offset%" for tag "%tag%" in directory',
+ self::ERROR_INVALID_DIRECTORY_TAG => 'Invalid tag "%tag%" in directory',
+ self::ERROR_INVALID_DIRECTORY_TAG_LENGTH => 'Invalid length "%len%" in directory for tag "%tag%"',
+ self::ERROR_INVALID_FIELD => 'Specified field must be a File_MARC_Data_Field or File_MARC_Control_Field object, but was "%field%"',
+ self::ERROR_INVALID_FILE => 'Invalid input file "%filename%"',
+ self::ERROR_INVALID_INDICATOR_REQUEST => 'Attempt to access indicator "%indicator%" failed; 1 and 2 are the only valid indicators',
+ self::ERROR_INVALID_INDICATORS => 'Invalid indicators "%indicators%" forced to blanks for tag "%tag%"',
+ self::ERROR_INVALID_SOURCE => "Invalid source for MARC records",
+ self::ERROR_INVALID_SUBFIELD => 'Specified field must be a File_MARC_Subfield object, but was "%class%"',
+ self::ERROR_INVALID_TAG => 'Tag "%tag%" is not a valid tag.',
+ self::ERROR_INVALID_TERMINATOR => 'Invalid record terminator',
+ self::ERROR_MISSING_LENGTH => "Couldn't find record length",
+ self::ERROR_NO_DIRECTORY => 'No directory found',
+ self::ERROR_NONNUMERIC_LENGTH => 'Record length "%record_length%" is not numeric',
+ self::ERROR_INVALID_INDICATOR => 'Illegal indicator "%indicator%" in field "%tag%" forced to blank',
+ );
+ // }}}
+
+ // {{{ formatError()
+ /**
+ * Replaces placeholder tokens in an error message with actual values.
+ *
+ * This method enables you to internationalize the messages for the
+ * File_MARC class by simply replacing the File_MARC_Exception::$messages
+ * array with translated values for the messages.
+ *
+ * @param string $message Error message containing placeholders
+ * @param array $errorValues Actual values to substitute for placeholders
+ * @return string Formatted message
+ */
+ public static function formatError($message, $errorValues)
+ {
+ foreach ($errorValues as $token => $value) {
+ $message = preg_replace("/\%$token\%/", $value, $message);
+ }
+ return $message;
+ }
+ // }}}
+}
+// }}}
+
176 MARC/Field.php
View
@@ -0,0 +1,176 @@
+<?php
+
+/* vim: set expandtab shiftwidth=4 tabstop=4 softtabstop=4 foldmethod=marker: */
+
+/**
+ * Parser for MARC records
+ *
+ * This package is based on the PHP MARC package, originally called "php-marc",
+ * that is part of the Emilda Project (http://www.emilda.org). Christoffer
+ * Landtman generously agreed to make the "php-marc" code available under the
+ * GNU LGPL so it could be used as the basis of this PEAR package.
+ *
+ * PHP version 5
+ *
+ * LICENSE: This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation; either version 2.1 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * @category File Formats
+ * @package File_MARC
+ * @author Christoffer Landtman <landtman@realnode.com>
+ * @author Dan Scott <dscott@laurentian.ca>
+ * @copyright 2003-2006 Oy Realnode Ab, Dan Scott
+ * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
+ * @version CVS: $Id$
+ */
+
+// {{{ class File_MARC_Field extends Structures_LinkedList_DoubleNode
+/**
+ * The File_MARC_Field class is expected to be extended to reflect the
+ * requirements of control and data fields.
+ *
+ * Every MARC field contains a tag name.
+ *
+ * @category File Formats
+ * @package File_MARC
+ * @author Christoffer Landtman <landtman@realnode.com>
+ * @author Dan Scott <dscott@laurentian.ca>
+ * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
+ * @link http://pear.php.net/package/File_MARC
+ */
+class File_MARC_Field extends Structures_LinkedList_DoubleNode {
+
+ // {{{ properties
+ /**
+ * The tag name of the Field
+ * @var string
+ */
+ protected $tag;
+ // }}}
+
+ // {{{ Constructor: function __construct()
+ /**
+ * File_MARC_Field constructor
+ *
+ * Create a new {@link File_MARC_Field} object from passed arguments. We
+ * define placeholders for the arguments required by child classes.
+ *
+ * @param string $tag tag
+ * @param string $subfields placeholder for subfields or control data
+ * @param string $ind1 placeholder for first indicator
+ * @param string $ind2 placeholder for second indicator
+ */
+ function __construct($tag, $subfields = null, $ind1 = null, $ind2 = null)
+ {
+ $this->tag = $tag;
+
+ // Check if valid tag
+ if (!preg_match("/^[0-9A-Za-z]{3}$/", $tag)) {
+ $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_TAG], array("tag" => $tag));
+ throw new File_MARC_Exception($errorMessage, File_MARC_Exception::ERROR_INVALID_TAG);
+ }
+
+ }
+ // }}}
+
+ // {{{ Destructor: function __destruct()
+ /**
+ * Destroys the data field
+ */
+ function __destruct()
+ {
+ $this->tag = null;
+ parent::__destruct();
+ }
+ // }}}
+
+ // {{{ getTag()
+ /**
+ * Returns the tag for this {@link File_MARC_Field} object
+ *
+ * @return string returns the tag number of the field
+ */
+ function getTag()
+ {
+ return $this->tag;
+ }
+ // }}}
+
+ // {{{ setTag()
+ /**
+ * Sets the tag for this {@link File_MARC_Field} object
+ *
+ * @param string $tag new value for the tag
+ * @return string returns the tag number of the field
+ */
+ function setTag($tag)
+ {
+ $this->tag = $tag;
+ return $this->getTag();
+ }
+ // }}}
+
+ // {{{ isEmpty()
+ /**
+ * Is empty
+ *
+ * Checks if the field is empty.
+ *
+ * @return bool Returns true if the field is empty, otherwise false
+ */
+ function isEmpty()
+ {
+ if ($this->getTag()) {
+ return false;
+ }
+ // It is empty
+ return true;
+ }
+ // }}}
+
+ /**
+ * ========== OUTPUT METHODS ==========
+ */
+
+ // {{{ __toString()
+ /**
+ * Return Field formatted
+ *
+ * Return Field as a formatted string.
+ *
+ * @return string Formatted output of Field
+ */
+ function __toString()
+ {
+ return $this->getTag();
+ }
+ // }}}
+
+ // {{{ toRaw()
+ /**
+ * Return field in raw MARC format (stub)
+ *
+ * Return the field formatted in raw MARC for saving into MARC files. This
+ * stub method is extended by the child classes.
+ *
+ * @return bool Raw MARC
+ */
+ function toRaw()
+ {
+ return false;
+ }
+ // }}}
+}
+// }}}
+
97 MARC/List.php
View
@@ -0,0 +1,97 @@
+<?php
+
+/* vim: set expandtab shiftwidth=4 tabstop=4 softtabstop=4 foldmethod=marker: */
+
+/**
+ * Parser for MARC records
+ *
+ * This package is based on the PHP MARC package, originally called "php-marc",
+ * that is part of the Emilda Project (http://www.emilda.org). Christoffer
+ * Landtman generously agreed to make the "php-marc" code available under the
+ * GNU LGPL so it could be used as the basis of this PEAR package.
+ *
+ * PHP version 5
+ *
+ * LICENSE: This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation; either version 2.1 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * @category File Formats
+ * @package File_MARC
+ * @author Christoffer Landtman <landtman@realnode.com>
+ * @author Dan Scott <dscott@laurentian.ca>
+ * @copyright 2003-2006 Oy Realnode Ab, Dan Scott
+ * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
+ * @version CVS: $Id$
+ */
+
+// {{{ class File_MARC_List extends Structures_LinkedList_Double
+/**
+ * The File_MARC_List class extends the Structures_LinkedList_Double class
+ * to override the key() method in a meaningful way for foreach() iterators.
+ *
+ * For the list of {@link File_MARC_Field} objects in a {@link File_MARC_Record}
+ * object, the key() method returns the tag name of the field.
+ *
+ * For the list of {@link File_MARC_Subfield} objects in a {@link
+ * File_MARC_Data_Field} object, the key() method returns the code of
+ * the subfield.
+ *
+ * <code>
+ * // Iterate through the fields in a record with key=>value iteration
+ * foreach ($record->getFields() as $tag=>$value) {
+ * print "$tag: ";
+ * if ($value instanceof File_MARC_Control_Field) {
+ * print $value->getData();
+ * }
+ * else {
+ * // Iterate through the subfields in this data field
+ * foreach ($value->getSubfields() as $code=>$subdata) {
+ * print "_$code";
+ * }
+ * }
+ * print "\n";
+ * }
+ * </code>
+ *
+ * @category File Formats
+ * @package File_MARC
+ * @author Dan Scott <dscott@laurentian.ca>
+ * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
+ * @link http://pear.php.net/package/File_MARC
+ */
+class File_MARC_List extends Structures_LinkedList_Double
+{
+ // {{{ key()
+ /**
+ * Returns the tag for a {@link File_MARC_Field} object, or the code
+ * for a {@link File_MARC_Subfield} object.
+ *
+ * This method enables you to use a foreach iterator to retrieve
+ * the tag or code as the key for the iterator.
+ *
+ * @return string returns the tag or code
+ */
+ function key()
+ {
+ if ($this->current() instanceof File_MARC_Field) {
+ return $this->current()->getTag();
+ } elseif ($this->current() instanceof File_MARC_Subfield) {
+ return $this->current()->getCode();
+ }
+ return false;
+ }
+ // }}}
+}
+// }}}
+
476 MARC/Record.php
View
@@ -0,0 +1,476 @@
+<?php
+
+/* vim: set expandtab shiftwidth=4 tabstop=4 softtabstop=4 foldmethod=marker: */
+
+/**
+ * Parser for MARC records
+ *
+ * This package is based on the PHP MARC package, originally called "php-marc",
+ * that is part of the Emilda Project (http://www.emilda.org). Christoffer
+ * Landtman generously agreed to make the "php-marc" code available under the
+ * GNU LGPL so it could be used as the basis of this PEAR package.
+ *
+ * PHP version 5
+ *
+ * LICENSE: This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation; either version 2.1 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * @category File Formats
+ * @package File_MARC
+ * @author Christoffer Landtman <landtman@realnode.com>
+ * @author Dan Scott <dscott@laurentian.ca>
+ * @copyright 2003-2006 Oy Realnode Ab, Dan Scott
+ * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
+ * @version CVS: $Id$
+ */
+
+// {{{ class File_MARC_Record
+/**
+ * Represents a single MARC record
+ *
+ * A MARC record contains a leader and zero or more fields held within a
+ * linked list structure. Fields are represented by {@link File_MARC_Data_Field}
+ * objects.
+ *
+ * @category File Formats
+ * @package File_MARC
+ * @author Christoffer Landtman <landtman@realnode.com>
+ * @author Dan Scott <dscott@laurentian.ca>
+ * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
+ * @link http://pear.php.net/package/File_MARC
+ */
+class File_MARC_Record {
+
+ // {{{ properties
+ /**
+ * Contains a linked list of {@link File_MARC_Data_Field} objects for
+ * this record
+ * @var File_MARC_List
+ */
+ protected $fields;
+
+ /**
+ * Record leader
+ * @var string
+ */
+ protected $leader;
+
+ /**
+ * Non-fatal warnings generated during parsing
+ * @var array
+ */
+ protected $warnings;
+ // }}}
+
+ // {{{ Constructor: function __construct()
+ /**
+ * Start function
+ *
+ * Set all variables to defaults to create new File_MARC_Record object
+ * @return true
+ */
+ function __construct()
+ {
+ $this->fields = new File_MARC_List();
+ $this->leader = str_repeat(' ', 24);
+ }
+ // }}}
+
+ // {{{ Destructor: function __destruct()
+ /**
+ * Destroys the data field
+ */
+ function __destruct()
+ {
+ $this->fields = null;
+ $this->warnings = null;
+ }
+ // }}}
+
+ // {{{ getLeader()
+ /**
+ * Get MARC leader
+ *
+ * Returns the leader for the MARC record. No validation
+ * on the specified leader is performed.
+ *
+ * @return string returns the leader
+ */
+ function getLeader()
+ {
+ return $this->leader;
+ }
+ // }}}
+
+ // {{{ setLeader()
+ /**
+ * Set MARC record leader
+ *
+ * Sets the leader for the MARC record. No validation
+ * on the specified leader is performed.
+ *
+ * @param string $leader Leader
+ * @return string returns the leader
+ */
+ function setLeader($leader)
+ {
+ $this->leader = $leader;
+ return $this->leader;
+ }
+ // }}}
+
+ // {{{ appendField()
+ /**
+ * Appends field to MARC record
+ *
+ * Adds a {@link File_MARC_Control_Field} or {@link File_MARC_Data_Field}
+ * object to the end of the existing list of fields.
+ *
+ * @param File_MARC_Field $new_field The field to add
+ * @return File_MARC_Field The field that was added
+ */
+ function appendField(File_MARC_Field $new_field)
+ {
+ /* Append as the last field in the record */
+ $this->fields->appendNode($new_field);
+ return $new_field;
+ }
+ // }}}
+
+ // {{{ prependField()
+ /**
+ * Prepends field to MARC record
+ *
+ * Adds a {@link File_MARC_Control_Field} or {@link File_MARC_Data_Field}
+ * object to the start of to the existing list of fields.
+ *
+ * @param File_MARC_Field $new_field The field to add
+ * @return File_MARC_Field The field that was added
+ */
+ function prependField(File_MARC_Field $new_field)
+ {
+ $this->fields->prependNode($new_field);
+ return $new_field;
+ }
+ // }}}
+
+ // {{{ insertField()
+ /**
+ * Inserts a field in the MARC record relative to an existing field
+ *
+ * Inserts a {@link File_MARC_Control_Field} or {@link File_MARC_Data_Field}
+ * object before or after a specified existing field.
+ *
+ * <code>
+ * // Example: Insert a new field before the first 650 field
+ *
+ * // Create the new field
+ * $subfields[] = new File_MARC_Data_Subfield('a', 'Scott, Daniel.');
+ * $new_field = new File_MARC_Data_Field('100', $subfields, 0, null);
+ *
+ * // Retrieve the target field for our insertion point
+ * $subject = $record->getFields('650');
+ *
+ * // Insert the new field
+ * if (is_array($subject)) {
+ * $record->insertField($new_field, $subject[0], true);
+ * }
+ * elseif ($subject) {
+ * $record->insertField($new_field, $subject, true);
+ * }
+ * </code>
+ *
+ * @param File_MARC_Field $new_field The field to add
+ * @param File_MARC_Field $existing_field The target field
+ * @param bool $before Insert the new field before the existing field
+ * if true, after the existing field if false
+ * @return File_MARC_Field The field that was added
+ */
+ function insertField(File_MARC_Field $new_field, File_MARC_Field $existing_field, $before = false)
+ {
+ switch ($before) {
+ /* Insert before the specified field in the record */
+ case true:
+ $this->fields->insertNode($new_field, $existing_field, true);
+ break;
+
+ /* Insert after the specified field in the record */
+ case false:
+ $this->fields->insertNode($new_field, $existing_field);
+ break;
+
+ default:
+ $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INSERTFIELD_MODE], array("mode" => $mode));
+ throw new File_MARC_Exception($errorMessage, File_MARC_Exception::ERROR_INSERTFIELD_MODE);
+ return false;
+ }
+ return $new_field;
+ }
+ // }}}
+
+ // {{{ _buildDirectory()
+ /**
+ * Build record directory
+ *
+ * Generate the directory of the record according to the current contents
+ * of the record.
+ *
+ * @return array Array ($fields, $directory, $total, $base_address)
+ */
+ private function _buildDirectory()
+ {
+ // Vars
+ $fields = array();
+ $directory = array();
+ $data_end = 0;
+
+ foreach ($this->fields as $field) {
+ // No empty fields allowed
+ if (!$field->isEmpty()) {
+ // Get data in raw format
+ $str = $field->toRaw();
+ $fields[] = $str;
+
+ // Create directory entry
+ $len = strlen($str);
+ $direntry = sprintf("%03s%04d%05d", $field->getTag(), $len, $data_end);
+ $directory[] = $direntry;
+ $data_end += $len;
+ }
+ }
+
+ /**
+ * Rules from MARC::Record::USMARC
+ */
+ $base_address =
+ File_MARC::LEADER_LEN + // better be 24
+ (count($directory) * File_MARC::DIRECTORY_ENTRY_LEN) +
+ // all the directory entries
+ 1; // end-of-field marker
+
+
+ $total =
+ $base_address + // stuff before first field
+ $data_end + // Length of the fields
+ 1; // End-of-record marker
+
+
+
+ return array($fields, $directory, $total, $base_address);
+ }
+ // }}}
+
+ // {{{ setLeaderLengths()
+ /**
+ * Set MARC record leader lengths
+ *
+ * Set the Leader lengths of the record according to defaults specified in
+ * {@link http://www.loc.gov/marc/bibliographic/ecbdldrd.html}
+ *
+ * @param int $record_length Record length
+ * @param int $base_address Base address of data
+ * @return bool Success or failure
+ */
+ function setLeaderLengths($record_length, $base_address)
+ {
+ if (!is_int($record_length)) {
+ return false;
+ }
+ if (!is_int($base_address)) {
+ return false;
+ }
+
+ // Set record length
+ $this->leader = substr_replace($this->leader, sprintf("%05d", $record_length), 0, 5);
+ $this->leader = substr_replace($this->leader, sprintf("%05d", $base_address), 12, 5);
+ $this->leader = substr_replace($this->leader, '22', 10, 2);
+ $this->leader = substr_replace($this->leader, '4500', 20, 4);
+ return true;
+ }
+ // }}}
+
+ // {{{ getField()
+ /**
+ * Return the first {@link File_MARC_Data_Field} or
+ * {@link File_MARC_Control_Field} object that matches the specified tag
+ * name. Returns false if no match is found.
+ *
+ * @param string $spec tag name
+ * @param bool $pcre if true, then match as a regular expression
+ * @return {@link File_MARC_Data_Field}|{@link File_MARC_Control_Field} first field that matches the requested tag name
+ */
+ function getField($spec = null, $pcre = null)
+ {
+ foreach ($this->fields as $field) {
+ if (($pcre
+ && preg_match("/$spec/", $field->getTag()))
+ || (!$pcre
+ && $spec == $field->getTag())
+ ) {
+ return $field;
+ }
+ }
+ return false;
+ }
+ // }}}
+
+ // {{{ getFields()
+ /**
+ * Return an array or {@link File_MARC_List} containing all
+ * {@link File_MARC_Data_Field} or {@link File_MARC_Control_Field} objects
+ * that match the specified tag name. If the tag name is omitted all
+ * fields are returned.
+ *
+ * @param string $spec tag name
+ * @param bool $pcre if true, then match as a regular expression
+ * @return File_MARC_List|array {@link File_MARC_Data_Field} or
+ * {@link File_MARC_Control_Field} objects that match the requested tag name
+ */
+ function getFields($spec = null, $pcre = null)
+ {
+ if (!$spec) {
+ return $this->fields;
+ }
+
+ // Okay, we're actually looking for something specific
+ $matches = array();
+ foreach ($this->fields as $field) {
+ if (($pcre && preg_match("/$spec/", $field->getTag()))
+ || (!$pcre && $spec == $field->getTag())
+ ) {
+ $matches[] = $field;
+ }
+ }
+ return $matches;
+ }
+ // }}}
+
+ // {{{ deleteFields()
+ /**
+ * Delete all occurrences of a field matching a tag name from the record.
+ *
+ * @param string $tag tag for the fields to be deleted
+ * @param bool $pcre if true, then match as a regular expression
+ * @return int number of fields that were deleted
+ */
+ function deleteFields($tag, $pcre = null)
+ {
+ $cnt = 0;
+ foreach ($this->getFields() as $field) {
+ if (($pcre
+ && preg_match("/$tag/", $field->getTag()))
+ || (!$pcre
+ && $tag == $field->getTag())
+ ) {
+ $field->delete();
+ $cnt++;
+ }
+ }
+ return $cnt;
+ }
+ // }}}
+
+ // {{{ addWarnings()
+ /**
+ * Add a warning to the MARC record that something non-fatal occurred during
+ * parsing.
+ *
+ * @param string $warning warning message
+ */
+ public function addWarnings($warning)
+ {
+ $this->warnings[] = $warning;
+ }
+ // }}}
+
+ // {{{ getWarnings()
+ /**
+ * Return the array of warnings from the MARC record.
+ *
+ * @return array warning messages
+ */
+ public function getWarnings($warning)
+ {
+ return $this->warnings;
+ }
+ // }}}
+
+ // {{{ output methods
+ /**
+ * ========== OUTPUT METHODS ==========
+ */
+
+ // {{{ toRaw()
+ /**
+ * Return the record in raw MARC format.
+ *
+ * If you have modified an existing MARC record or created a new MARC
+ * record, use this method to save the record for use in other programs
+ * that accept the MARC format -- for example, your integrated library
+ * system.
+ *
+ * <code>
+ * // Example: Modify a record and save the output to a file
+ * $record->deleteFields('650');
+ *
+ * // Now that the record has no subject fields, save it to disk
+ * fopen($file, '/home/dan/no_subject.mrc', 'w');
+ * fwrite($file, $record->toRaw());
+ * fclose($file);
+ * </code>
+ *
+ * @return string Raw MARC data
+ */
+ function toRaw()
+ {
+ list($fields, $directory, $record_length, $base_address) = $this->_buildDirectory();
+ $this->setLeaderLengths($record_length, $base_address);
+
+ /**
+ * Glue together all parts
+ */