Browse Source

Merge branch '7.x' of github.com:Islandora/islandora into 7.x-release

pull/261/merge
jonathangreen 12 years ago
parent
commit
72a6c29ee6
  1. 2
      .gitignore
  2. 674
      LICENSE.txt
  3. 9
      README
  4. 70
      README.txt
  5. 20
      css/islandora.admin.css
  6. BIN
      images/Crystal_Clear_action_filenew.png
  7. BIN
      images/folder.png
  8. 228
      includes/add_datastream.form.inc
  9. 106
      includes/admin.form.inc
  10. 136
      includes/authtokens.inc
  11. 58
      includes/breadcrumb.inc
  12. 536
      includes/datastream.inc
  13. 71
      includes/delete_datastream.form.inc
  14. 48
      includes/delete_object.form.inc
  15. 93
      includes/dublin_core.inc
  16. 46
      includes/ingest-menu.inc
  17. 551
      includes/ingest.form.inc
  18. 65
      includes/ingest.menu.inc
  19. 27
      includes/islandora.ingest.inc
  20. 63
      includes/mime_detect.inc
  21. 53
      includes/object.entity_controller.inc
  22. 122
      includes/object_properties.form.inc
  23. 115
      includes/object_properties.inc
  24. 160
      includes/purge.form.inc
  25. 668
      includes/solution_packs.inc
  26. 54
      includes/tuque.inc
  27. 360
      includes/tuque_wrapper.inc
  28. 597
      includes/utilities.inc
  29. 443
      islandora.api.php
  30. 10
      islandora.info
  31. 95
      islandora.install
  32. 928
      islandora.module
  33. 118
      islandora.rules.inc
  34. 31
      policies/permit-apim-to-authenticated-user.xml
  35. 25
      policies/permit-getDatastream-unrestricted.xml
  36. 25
      policies/permit-getDatastreamHistory-unrestricted.xml
  37. 31
      policies/permit-upload-to-authenticated-user.xml
  38. 3
      tests/README.txt
  39. 110
      tests/authtokens.test
  40. 6
      tests/default.test_config.ini
  41. BIN
      tests/fixtures/bug.jp2
  42. 192979
      tests/fixtures/testfixture_10001.xml
  43. 213
      tests/hooks.test
  44. 6
      tests/islandora_test.info
  45. 152
      tests/islandora_test.module
  46. 124
      tests/web_test_case.inc
  47. 49
      theme/islandora-object-edit.tpl.php
  48. 81
      theme/islandora-object.tpl.php
  49. 92
      theme/theme.inc
  50. 21
      xml/islandora_collection_policy.xml

2
.gitignore vendored

@ -1 +1,3 @@
cache.properties
.DS_Store
tests/test_config.ini

674
LICENSE.txt

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, 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
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state 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 program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

9
README

@ -1,9 +0,0 @@
Islandora Fedora Repository Module
For installation and customization instructions please see the documentation and the DuraSpace Wiki:
https://wiki.duraspace.org/display/ISLANDORA/Islandora
All bugs, feature requests and improvement suggestions are tracked at the DuraSpace JIRA:
https://jira.duraspace.org/browse/ISLANDORA

70
README.txt

@ -0,0 +1,70 @@
CONTENTS OF THIS FILE
---------------------
* summary
* requirements
* installation
* configuration
* customization
* troubleshooting
* faq
* contact
* sponsors
SUMMARY
-------
Islandora Fedora Repository Module
For installation and customization instructions please see the documentation
and the DuraSpace Wiki:
https://wiki.duraspace.org/display/ISLANDORA/Islandora
All bugs, feature requests and improvement suggestions are tracked at the
DuraSpace JIRA:
https://jira.duraspace.org/browse/ISLANDORA
REQUIREMENTS
------------
INSTALLATION
------------
Before installing Islandora the XACML policies located in the policies folder
should be copied into the Fedora global XACML policies folder. This will allow
"authenticated users" in Drupal to access Fedora API-M functions.
CONFIGURATION
-------------
The islandora_drupal_filter passes the username of 'anonymous' through to
Fedora for unauthenticated Drupal Users. A user with the name of 'anonymous'
may have XACML policies applied to them that are meant to be applied to Drupal
users that are not logged in or vice-versa. This is a potential security issue
that can be plugged by creating a user named 'anonymous' and restricting access
to the account.
Drupal's cron will can be ran to remove expired authentication tokens.
CUSTOMIZATION
-------------
TROUBLESHOOTING
---------------
F.A.Q.
------
CONTACT
-------
SPONSORS
--------

20
css/islandora.admin.css

@ -1,9 +1,17 @@
/*
Document : islandora_basic_collection.admin.css
Created on : May 23, 2012, 11:23:06 AM
Description:
Purpose of the stylesheet follows.
*/
/**
* @file
* Css file for Islandora admin pages
*/
/* Solution pack admin page */
.islandora-solution-pack-fieldset
{
padding-top: 0.5em;
}
.islandora-solution-pack-fieldset table th,
.islandora-solution-pack-fieldset table td
{
width: 33%;
}

BIN
images/Crystal_Clear_action_filenew.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

BIN
images/folder.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

228
includes/add_datastream.form.inc

@ -0,0 +1,228 @@
<?php
/**
* @file
* Functions for generating/validating/submitting the add datastream form.
*/
/**
* The admin add datastream form.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
* @param FedoraObject $object
* The object to be deleted.
*
* @return array
* The drupal form definition.
*/
function islandora_add_datastream_form(array $form, array &$form_state, FedoraObject $object) {
module_load_include('inc', 'islandora', 'includes/content_model');
module_load_include('inc', 'islandora', 'includes/utilities');
form_load_include($form_state, 'inc', 'islandora', 'includes/add_datastream.form');
$form_state['object'] = $object;
$form_state['datastream_requirements'] = islandora_get_missing_datastreams_requirements($object);
$unused_datastreams = array_keys($form_state['datastream_requirements']);
$unused_datastreams = "'" . implode("', '", $unused_datastreams) . "'";
$upload_size = min((int) ini_get('post_max_size'), (int) ini_get('upload_max_filesize'));
return array(
'#redirect' => "islandora/object/{$object->id}",
'#attributes' => array(
'enctype' => 'multipart/form-data',
),
'fieldset' => array(
'#type' => 'fieldset',
'#title' => 'Add a datastream',
'#collapsible' => FALSE,
'#collapsed' => FALSE,
'dsid' => array(
'#title' => 'Datastream ID',
'#description' => t("An ID for this stream that is unique to this object. Must start with a letter and contain only alphanumeric characters and dashes and underscores. Datastreams that are defined by the content model don't currently exist: <b>@unused_dsids</b>.", array('@unused_dsids' => $unused_datastreams)),
),
'#type' => 'textfield',
'#size' => 64,
'#maxlength' => 64,
'#required' => TRUE,
'#element_validate' => array(
'islandora_add_datastream_form_field_is_not_an_existing_datastream_id',
'islandora_add_datastream_form_field_starts_with_a_letter',
'islandora_add_datastream_form_field_is_valid_dsid',
),
'#autocomplete_path' => "islandora/object/{$object->id}/manage/datastreams/add/autocomplete",
),
'label' => array(
'#title' => 'Datastream Label',
'#required' => TRUE,
'#size' => 64,
'#maxlength' => 64,
'#description' => t('A Human readable label'),
'#type' => 'textfield',
'#element_validate' => array('islandora_add_datastream_form_field_does_not_contain_a_forward_slash'),
),
'file' => array(
'#type' => 'managed_file',
'#required' => TRUE,
'#title' => t('Upload Document'),
'#size' => 48,
'#description' => t('Select a file to upload.<br/>Files must be less than <b>@size MB.</b>', array('@size' => $upload_size)),
'#default_value' => isset($form_state['values']['files']) ? $form_state['values']['files'] : NULL,
'#upload_location' => 'temporary://',
'#upload_validators' => array(
'file_validate_extensions' => array(NULL),
// Assume its specified in MB.
'file_validate_size' => array($upload_size * 1024 * 1024),
),
),
'submit' => array(
'#type' => 'submit',
'#value' => t('Add Datastream'),
),
);
}
/**
* Checks if the given form field doesn't already repersent a Datastream ID.
*
* @param array $element
* The form field to check.
* @param array $form_state
* The Drupal form state.
* @param array $form
* The Drupal form.
*/
function islandora_add_datastream_form_field_is_not_an_existing_datastream_id(array $element, array &$form_state, array $form) {
if (isset($form_state['object'][$element['#value']])) {
form_error($element, t("@title already exists in the object.", array('@title' => $element['#title'])));
}
}
/**
* Checks if the given form field starts with a letter.
*
* @param array $element
* The form field to check.
* @param array $form_state
* The Drupal form state.
* @param array $form
* The Drupal form.
*/
function islandora_add_datastream_form_field_starts_with_a_letter(array $element, array &$form_state, array $form) {
if (!(preg_match("/^[a-zA-Z]/", $element['#value']))) {
form_error($element, t("@title has to start with a letter.", array('@title' => $element['#title'])));
}
}
/**
* Checks if the given form field contains a valid datastream ID.
*
* @param array $element
* The form field to check.
* @param array $form_state
* The Drupal form state.
* @param array $form
* The Drupal form.
*/
function islandora_add_datastream_form_field_is_valid_dsid(array $element, array &$form_state, array $form) {
module_load_include('inc', 'islandora', 'includes/utilities');
if (!islandora_is_valid_dsid($element['#value'])) {
form_error($element, t("@title contains invalid characters.", array('@title' => $element['#title'])));
}
}
/**
* Checks if the given form field contains a "/" character.
*
* @param array $element
* The form field to check.
* @param array $form_state
* The Drupal form state.
* @param array $form
* The Drupal form.
*/
function islandora_add_datastream_form_field_does_not_contain_a_forward_slash(array $element, array &$form_state, array $form) {
if (strpos($element['#value'], '/') !== FALSE) {
form_error($element, t('@title cannot contain a "/" character.', array('@title' => $element['#title'])));
}
}
/**
* Checks if the given datastream requires the upload to be a certian MIME type.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*/
function islandora_add_datastream_form_validate(array $form, array &$form_state) {
$file = file_load($form_state['values']['file']);
$dsid = $form_state['values']['dsid'];
if (isset($form_state['datastream_requirements'][$dsid]) && $file) {
$allowed_types = $form_state['datastream_requirements'][$dsid]['mime'];
$mime_detect = new MimeDetect();
$allowed_extensions = array_map(array($mime_detect, 'getExtension'), $allowed_types);
$errors = file_validate_extensions($file, implode(' ', $allowed_extensions));
if (count($errors) > 0) {
form_set_error('file', $errors[0]);
}
}
}
/**
* Adds the new datastream based on the submitted values.
*
* Only creates managed datastreams at the moment.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*/
function islandora_add_datastream_form_submit(array $form, array &$form_state) {
$object = $form_state['object'];
$form_state['redirect'] = "islandora/object/{$object->id}";
$file = file_load($form_state['values']['file']);
try {
$ds = $object->constructDatastream($form_state['values']['dsid'], 'M');
$ds->label = $form_state['values']['label'];
$ds->mimetype = $file->filemime;
$path = drupal_realpath($file->uri);
$ds->setContentFromFile($path);
$object->ingestDatastream($ds);
file_delete($file);
}
catch (exception $e) {
drupal_set_message(t('@message', array('@message' => check_plain($e->getMessage()))), 'error');
// Make sure to delete anyways.
file_delete($file);
return;
}
drupal_set_message(t("Successfully Added Datastream!"));
}
/**
* Callback for an autocomplete field in the admin add datastream form.
*
* It lists the missing required (may be optional) datastreams.
*
* @param FedoraObject $object
* The object used to check for missing required datastreams used to populate
* the options in this callback.
* @param string $query
* vThe user query to match against the missing required datastreams.
*/
function islandora_add_datastream_form_autocomplete_callback(FedoraObject $object, $query = '') {
module_load_include('inc', 'islandora', 'includes/content_model');
module_load_include('inc', 'islandora', 'includes/utilities');
$dsids = array_keys(islandora_get_missing_datastreams_requirements($object));
$dsids = array_combine($dsids, $dsids);
$query = trim($query);
if (!empty($query)) {
$filter = function($id) use($query) {
return stripos($id, $query) !== FALSE;
};
$dsids = array_filter($dsids, $filter);
}
drupal_json_output($dsids);
}

106
admin/islandora.admin.inc → includes/admin.form.inc

@ -1,31 +1,38 @@
<?php
/**
* @file islandora.admin.inc
* Create admin form
* @return array
* @file
* This administration form for this module.
*/
function islandora_repository_admin($form, &$form_state) {
module_load_include('inc', 'islandora', 'includes/tuque');
/**
* The administration form for the fedora repository connection.
*
* @param array $form
* The Drupal form definition.
* @param array $form_state
* The Drupal form state.
*
* @return array
* The Drupal form definition.
*/
function islandora_repository_admin(array $form, array &$form_state) {
module_load_include('inc', 'islandora', 'includes/utilities');
if (!IslandoraTuque::exists()) {
IslandoraTuque::getError();
return;
}
drupal_add_css(drupal_get_path('module', 'islandora') . '/css/islandora.admin.css');
$form = array();
if(isset($form_state['values']['islandora_base_url'])) {
if (isset($form_state['values']['islandora_base_url'])) {
$url = $form_state['values']['islandora_base_url'];
}
else {
$url = variable_get('islandora_base_url', 'http://localhost:8080/fedora');
}
module_load_include('inc', 'islandora', 'includes/tuque');
$connection = new IslandoraTuque(NULL, $url);
$connection = islandora_get_tuque_connection(NULL, $url);
if (!$connection) {
return;
}
try {
$info = $connection->api->a->describeRepository();
}
@ -33,7 +40,7 @@ function islandora_repository_admin($form, &$form_state) {
$info = FALSE;
}
if($info) {
if ($info) {
try {
$dc = $connection->api->m->getDatastream('fedora-system:ContentModel-3.0', 'DC');
}
@ -41,20 +48,23 @@ function islandora_repository_admin($form, &$form_state) {
$dc = FALSE;
}
}
if($info) {
if($dc) {
$confirmation_message = '<img src="' . url('misc/watchdog-ok.png') . '"/>'
. t('Successfully connected to Fedora Server (Version !version).', array('!version' => $info['repositoryVersion']));
if ($info) {
if ($dc) {
$confirmation_message = theme_image(array('path' => 'misc/watchdog-ok.png', 'attributes' => array()));
$confirmation_message .= t('Successfully connected to Fedora Server (Version !version).', array(
'!version' => $info['repositoryVersion']));
}
else {
$confirmation_message = '<img src="' . url('misc/watchdog-warning.png') . '"/>'
. t('Unable to authenticate when connecting to to Fedora Server (Version !version). Please configure the !filter.', array('!version' => $info['repositoryVersion'], '!filter' => 'Drupal Filter'));
$confirmation_message = theme_image(array('path' => 'misc/watchdog-warning.png', 'attributes' => array()));
$confirmation_message .= t('Unable to authenticate when connecting to to Fedora Server (Version !version). Please configure the !filter.',
array('!version' => $info['repositoryVersion'], '!filter' => 'Drupal Filter'));
}
}
else {
$confirmation_message = '<img src="' . url('misc/watchdog-error.png') . '"/> '
. t('Unable to connect to Fedora server at !islandora_url', array('!islandora_url' => $url));
$confirmation_message = theme_image(array('path' => 'misc/watchdog-error.png', 'attributes' => array()));
$confirmation_message .= t('Unable to connect to Fedora server at !islandora_url', array(
'!islandora_url' => $url));
}
$form['islandora_tabs'] = array(
@ -66,7 +76,7 @@ function islandora_repository_admin($form, &$form_state) {
'#title' => t('General Configuarion'),
);
// ajax wrapper for url checking
// Ajax wrapper for url checking.
$form['islandora_tabs']['islandora_general']['wrapper'] = array(
'#prefix' => '<div id="islandora-url">',
'#suffix' => '</div>',
@ -77,7 +87,9 @@ function islandora_repository_admin($form, &$form_state) {
'#type' => 'textfield',
'#title' => t('Fedora base URL'),
'#default_value' => variable_get('islandora_base_url', 'http://localhost:8080/fedora'),
'#description' => t('The URL to use for REST connections <br>' . $confirmation_message),
'#description' => t('The URL to use for REST connections <br /> !confirmation_message', array(
'!confirmation_message' => $confirmation_message,
)),
'#required' => TRUE,
'#ajax' => array(
'callback' => 'islandora_update_url_div',
@ -111,7 +123,7 @@ function islandora_repository_admin($form, &$form_state) {
'#weight' => -1,
'#type' => 'checkbox',
'#title' => t('Enforce namespace restrictions'),
'#description' => t('Allow administrator to restrict user\'s access to the PID namepaces listed below'),
'#description' => t("Allow administrator to restrict user's access to the PID namepaces listed below"),
'#default_value' => variable_get('islandora_namespace_restriction_enforced', FALSE),
'#ajax' => array(
'callback' => 'islandora_update_namespace_div',
@ -121,20 +133,20 @@ function islandora_repository_admin($form, &$form_state) {
'progress' => array('type' => 'throbber'),
),
);
if(isset($form_state['values']['islandora_namespace_restriction_enforced'])) {
if (isset($form_state['values']['islandora_namespace_restriction_enforced'])) {
$namespaces = $form_state['values']['islandora_namespace_restriction_enforced'];
}
else {
$namespaces = variable_get('islandora_namespace_restriction_enforced', FALSE);
}
if($namespaces) {
if ($namespaces) {
$form['islandora_tabs']['islandora_namespace']['wrapper']['islandora_pids_allowed'] = array(
'#type' => 'textfield',
'#title' => t('PID namespaces allowed in this Drupal install'),
'#default_value' => variable_get('islandora_pids_allowed', 'default: demo: changeme: ilives: islandora-book: books: newspapers: '),
'#description' => t('A space separated list of PID namespaces that users are permitted to access from this Drupal installation. <br /> This could be more than a simple namespace ie demo:mydemos. <br> islandora: is reserved and is always allowed.'),
'#description' => t('A space separated list of PID namespaces that users are permitted to access from this Drupal installation. <br /> This could be more than a simple namespace ie demo:mydemos. <br /> islandora: is reserved and is always allowed.'),
'#weight' => 0,
);
}
@ -143,21 +155,31 @@ function islandora_repository_admin($form, &$form_state) {
}
/**
* Checks url validity and refreshes requestHandler dropdown list
* Get the element to render for the AJAX event that triggered this callback.
*
* @param array $form
* The Drupal form definition.
* @param array $form_state
* The Drupal form state.
*
* @return array
* The form element to render.
*/
function islandora_update_url_div($form, $form_state) {
unset($form_state['submit_handlers']);
$form_state['rebuild'] = TRUE;
function islandora_update_url_div(array $form, array $form_state) {
return $form['islandora_tabs']['islandora_general']['wrapper'];
}
/**
* Checks url validity and refreshes requestHandler dropdown list
* Get the element to render for the AJAX event that triggered this callback.
*
* @param array $form
* The Drupal form definition.
* @param array $form_state
* The Drupal form state.
*
* @return array
* The form element to render.
*/
function islandora_update_namespace_div($form, $form_state) {
unset($form_state['submit_handlers']);
$form_state['rebuild'] = TRUE;
function islandora_update_namespace_div(array $form, array $form_state) {
return $form['islandora_tabs']['islandora_namespace']['wrapper'];
}
}

136
includes/authtokens.inc

@ -0,0 +1,136 @@
<?php
/**
* @file
* Handles the generation and validation of authentication tokens.
*
* These are to be used when dealing with applications such as Djatoka that do
* not pass through credentials.
*/
// Token lifespan(seconds): after this duration the token expires.
// 5 minutes.
define('TOKEN_TIMEOUT', 300);
/**
* Request Islandora to construct an object/datastream authentication token.
*
* This token can later be turned in for access to the requested object or
* datastream.
*
* @param string $pid
* The Fedora PID to generate the token for.
* @param string $dsid
* The Fedora datastream ID to generate the token for.
* @param int $uses
* Defaults to 1.
* The number of uses the token should be used for. There are
* times when this should be greater than 1: ie. Djatoka needs
* to make two calls. This is the number of times it can be called
* from different php sessions, not in the run of a program. (it is
* statically cached).
*
* @return string
* The generated authentication token.
*/
function islandora_get_object_token($pid, $dsid, $uses = 1) {
global $user;
$time = time();
// The function mt_rand is not considered cryptographically secure
// and openssl_rando_pseudo_bytes() is only available in PHP > 5.3.
// We might be safe in this case because mt_rand should never be using
// the same seed, but this is still more secure.
$token = hash("sha256", mt_rand() . $time);
$id = db_insert("islandora_authtokens")->fields(
array(
'token' => $token,
'uid' => $user->uid,
'pid' => $pid,
'dsid' => $dsid,
'time' => $time,
'remaining_uses' => $uses,
))->execute();
return $token;
}
/**
* Submit a token to islandora for authentication.
*
* Supply islandora with the token and the object/datastream it is for and you
* will receive access if authentication passes. Tokens can only be redeemed
* in a short window after their creation.
*
* @param string $pid
* The PID of the object to retrieve.
* @param string $dsid
* The datastream id to retrieve.
* @param string $token
* The registered token that allows access to this object.
*
* @return mixed
* The user credentials for access if the token validation passes,
* FALSE otherwise
*/
function islandora_validate_object_token($pid, $dsid, $token) {
static $accounts = array();
if (!empty($accounts[$pid][$dsid][$token])) {
return $accounts[$pid][$dsid][$token];
}
// Check for database token.
$time = time();
$query = db_select('islandora_authtokens', 'tokens');
$query->join('users', 'u', 'tokens.uid = u.uid');
// The results will look like user objects.
$result = $query
->fields('u', array('uid', 'name', 'pass'))
->fields('tokens', array('remaining_uses'))
->condition('token', $token, '=')
->condition('pid', $pid, '=')
->condition('dsid', $dsid, '=')
->condition('time', $time, '<=')
->condition('time', $time - TOKEN_TIMEOUT, '>')
->execute()
->fetchAll();
if ($result) {
$remaining_uses = $result[0]->remaining_uses;
$remaining_uses--;
// Remove the authentication token so it can't be used again.
if ($remaining_uses == 0) {
db_delete("islandora_authtokens")
->condition('token', $token, '=')
->condition('pid', $pid, '=')
->condition('dsid', $dsid, '=')
->execute();
}
// Decrement authentication token uses.
else {
db_update("islandora_authtokens")
->fields(array('remaining_uses' => $remaining_uses))
->condition('token', $token, '=')
->condition('pid', $pid, '=')
->condition('dsid', $dsid, '=')
->execute();
}
unset($result[0]->remaining_uses);
$accounts[$pid][$dsid][$token] = $result[0];
}
else {
$accounts[$pid][$dsid][$token] = FALSE;
}
return $accounts[$pid][$dsid][$token];
}
/**
* Will remove any expired authentication tokens.
*/
function islandora_remove_expired_tokens() {
$time = time();
db_delete("islandora_authtokens")
->condition('time', $time - TOKEN_TIMEOUT, '<')
->execute();
}

58
includes/breadcrumb.inc

@ -1,16 +1,37 @@
<?php
/**
* @file
* This file contains functions to create breadcrumbs on Islandora object pages.
*/
/**
* Get an array of links to be passed to drupal_set_breadcrumb().
*
* This is used for generating the bread-crumbs for the view object page.
*
* Each link in the bread-crumbs represents a member of the given objects
* ancestry which is identified by any of the following RELS-EXT terms
* (isMemberOf,isMemberOfCollection,isPartOf).
*
* @param FedoraObject $object
* An object whose ancestry will be mapped to bread-crumbs.
*
* @see drupal_set_breadcrumb()
*
* @return array
* Array of links, starting with most distant ancestor proceeding up to but
* not including the given object. For use in the function
* drupal_set_breadcrumb().
*/
function islandora_get_breadcrumbs($object) {
$breadcrumbs = array();
islandora_get_breadcrumbs_recursive($object->id, $breadcrumbs, $object->repository);
if(isset($breadcrumbs[0])) {
if (isset($breadcrumbs[0])) {
// Remove the actual object.
unset($breadcrumbs[0]);
}
$breadcrumbs = array_reverse($breadcrumbs);
return $breadcrumbs;
}
@ -19,14 +40,19 @@ function islandora_get_breadcrumbs($object) {
*
* @todo Make fully recursive...
*
* @global type $base_url
* @param type $pid
* @param type $breadcrumbs
* @param type $level
* @todo Could use some clean up, can't be called multiple times safely due to
* the use of static variables.
*
* @param string $pid
* THe object id whose parent will be fetched for the next link.
* @param array $breadcrumbs
* The list of existing bread-crumb links in reverse order.
* @param FedoraRepository $repository
* The fedora repository.
*/
function islandora_get_breadcrumbs_recursive($pid, &$breadcrumbs, $repository) {
// Before executing the query, we hve a base case of accessing the top-level collection
global $base_url;
function islandora_get_breadcrumbs_recursive($pid, array &$breadcrumbs, FedoraRepository $repository) {
// Before executing the query, we have a base case of accessing the top-level
// collection.
static $max_level = 10;
static $level = -1;
@ -69,8 +95,10 @@ function islandora_get_breadcrumbs_recursive($pid, &$breadcrumbs, $repository) {
islandora_get_breadcrumbs_recursive($parent, $breadcrumbs, $repository);
}
else {
$breadcrumbs[] = '...'; //Add an non-link, as we don't know how to get back to the root.
islandora_get_breadcrumbs_recursive($root, $breadcrumbs, $repository); //And render the last two links and break (on the next pass).
// Add an non-link, as we don't know how to get back to the root.
$breadcrumbs[] = '...';
// And render the last two links and break (on the next pass).
islandora_get_breadcrumbs_recursive($root, $breadcrumbs, $repository);
}
}
}
}

536
includes/datastream.inc

@ -1,471 +1,145 @@
<?php
/**
* @file datastream.inc
* @file
* Contains the admin form and callback functions for datastream manipulations.
*/
define('DS_COMP_STREAM', 'DS-COMPOSITE-MODEL');
/**
* Callback to download the given datastream to the users computer.
*
* @global object $user
* @param string $object_id
* @param string $dsid
* @return stream
* prints datastream to browser
* @param FedoraDatastream $datastream
* The datastream to download.
*/
function islandora_view_datastream($object, $dsid, $method = 'view') {
// if the object exists but the datastream doesn't
if(!isset($object[$dsid])) {
return drupal_not_found();
}
header('Content-type: ' . $object[$dsid]->mimetype);
if($object[$dsid]->controlGroup == 'M' || $object[$dsid]->controlGroup == 'X') {
header('Content-length: ' . $object[$dsid]->size);
}
if ($method == 'download') {
header("Content-Disposition: attachment; filename=\"" . $object[$dsid]->label);
}
print($object[$dsid]->content);
exit();
}
function islandora_datastream_get_parents($islandora_object) {
$parent_collections = array();
try {
$repository = $islandora_object->repository;
$collections1 = $islandora_object->relationships->get(FEDORA_RELS_EXT_URI, 'isMemberOfCollection');
$collections2 = $islandora_object->relationships->get(FEDORA_RELS_EXT_URI, 'isMemberOf');
}
catch (RepositoryException $e) {
$collections1 = array();
$collections2 = array();
}
$collections = array_merge($collections1, $collections2);
foreach($collections as $collection) {
try {
$pid = $collection['object']['value'];
$object = $repository->getObject($collection['object']['value']);
$parent_collections[$pid] = array();
$parent_collections[$pid]['object'] = $object;
$parent_collections[$pid]['url'] = 'islandora/object/' . $object->id;
$parent_collections[$pid]['label'] = $object->label;
$parent_collections[$pid]['label_link'] = l($parent_collections[$pid]['label'], $parent_collections[$pid]['url']);
}
catch (RepositoryException $e) {}
}
return $parent_collections;
function islandora_download_datastream(FedoraDatastream $datastream) {
islandora_view_datastream($datastream, TRUE);
}
/**
* Callback function to view or download a datastream.
*
* @param array $arr
* an array of dsids that are defined by this objects cmodels
* @param string $ds_comp_stream
* the dscomposite stream as xml
* @note
* This function calls exit().
*
* @param FedoraDatastream $datastream
* The datastream to view/download.
* @param bool $download
* If TRUE the file is download to the user computer for viewing otherwise it
* will attempt to display in the browser natively.
*/
function islandora_get_defined_dsids_array(&$arr, $ds_comp_stream) {
$sxml = new SimpleXMLElement($ds_comp_stream);
foreach ($sxml->dsTypeModel as $ds) {
//$arr[$ds['ID']]
$mimes = array();
foreach ($ds->form as $form) {
$mimetype = (string) $form['MIME'];
$mimes[] = $mimetype;
}
$dsid = (string) $ds['ID'];
if ($dsid != 'AUDIT') {
$arr[(string) $ds['ID']] = $mimes;
}
}
function islandora_view_datastream(FedoraDatastream $datastream, $download = FALSE) {
header_remove('Cache-Control');
header_remove('Expires');
header('Content-type: ' . $datastream->mimetype);
if ($datastream->controlGroup == 'M' || $datastream->controlGroup == 'X') {
header('Content-length: ' . $datastream->size);
}
if ($download) {
// Browsers will not append all extensions.
$mime_detect = new MimeDetect();
$extension = $mime_detect->getExtension($datastream->mimetype);
$filename = $datastream->label . '.' . $extension;
header("Content-Disposition: attachment; filename=\"$filename\"");
}
drupal_page_is_cacheable(FALSE);
// Try not to load the file into PHP memory!
$datastream->getContent('php://output');
exit();
}
/**
* Get the human readable size of the given datastream.
*
* @param FedoraDatastream $datastream
* The datastream to check.
*
* @global type $user
* @param string $object_id
* @return string|array
* @return string
* A human readable size of the given datastream, or '-' if the size could not
* be determined.
*/
function islandora_get_unused_dsids($object) {
$defined_dsids = array();
if(!$object) {
return $defined_dsids;
}
$models = $object->models;
if (isset($models)) {
foreach ($models as $model) {
try {
$model_object = $object->repository->getObject($model);
if (isset($model_object[DS_COMP_STREAM])) {
$dscomposite_stream = $model_object[DS_COMP_STREAM]->content;
islandora_get_defined_dsids_array($defined_dsids, $dscomposite_stream);
}
} catch (Exception $e) {
//do nothing as other objects may have a dscompsite stream
}
}
}
foreach ($defined_dsids as $key => $value) {
if (isset($fedora_object[$key])) {
unset($defined_dsids[$key]); //ds exists in the object so don't show in the dropdown
}
}
return $defined_dsids;
function islandora_datastream_get_human_readable_size(FedoraDatastream $datastream) {
module_load_include('inc', 'islandora', 'includes/utilities');
$size_is_calculatable = $datastream->controlGroup == 'M' || $datastream->controlGroup == 'X';
return $size_is_calculatable ? islandora_convert_bytes_to_human_readable($datastream->size) : '-';
}
/**
* buids the default add datastream form
* @param string $object_id
* @param array $form_state
* @return array
* a form ready to be rendered with a call to Drupal render
* Get either the 'view' or 'download' url for the given datastream if possible.
*
* @param FedoraDatastream $datastream
* The datastream to generated the url to.
*
* @return string
* either the 'view' or 'download' url for the given datastream.
*/
function islandora_get_add_datastream_form($object, &$form_state) {
$unused_dsids = islandora_get_unused_dsids($object);
$form = array();
$form['add_fieldset'] = array(
'#type' => 'fieldset',
'#title' => 'Add a datastream',
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['add_fieldset']['add_datastream_label'] = array(
'#value' => t('<br /><h3>Add Datastream:</h3>'),
'#weight' => -10,
);
$form['pid'] = array(
'#type' => 'hidden',
'#value' => "$object->id"
);
$form['add_fieldset']['stream_label'] = array(
'#title' => 'Datastream Label',
'#required' => 'TRUE',
'#description' => t('A Human readable label'),
'#type' => 'textfield'
);
$form['#attributes']['enctype'] = 'multipart/form-data';
$form['add_fieldset']['add-stream-file-location'] = array(
'#type' => 'file',
'#title' => t('Upload Document'),
'#size' => 48,
// '#required'=>'TRUE',
'#description' => t('The file to upload.')
);
$form['#redirect'] = "islandora/object/$object->id/";
$form['add_fieldset']['submit'] = array(
'#type' => 'submit',
'#value' => t('Add Datastream')
);
if (!empty($unused_dsids)) {
$dsidsForForm = array();
foreach ($unused_dsids as $key => $value) {
$dsidsForForm[$key] = $key;
}
$form['add_fieldset']['stream_id'] = array(
'#type' => 'select',
'#title' => t('Datastream ID'),
'#default_value' => variable_get('feed_item_length', 'teaser'),
'#weight' => '-1',
'#description' => t('Datastream IDs defined by the content model.'),
);
$form['add_fieldset']['stream_id']['#options'] = $dsidsForForm;
}
else {
$form['add_fieldset']['stream_id'] = array(
'#title' => 'Datastream ID',
'#required' => 'TRUE',
'#description' => t('An ID for this stream that is unique to this object. Must start with a letter and contain only alphanumeric characters and dashes and underscores.'),
'#type' => 'textfield',
'#weight' => -1,
);
}
return $form;
function islandora_datastream_get_url(FedoraDatastream $datastream, $type = 'download') {
return $datastream->controlGroup == 'R' ? $datastream->url : "islandora/object/{$datastream->parent->id}/datastream/{$datastream->id}/$type";
}
/**
* Default implmentation currently only does M (managed datastreams)
* other modules can hook form alter to add other functionality
* @global string $base_url
* @global object $user
* Drupal user
* @param array $form
* @param array $form_state
* @return type
* Gets the delete link.
*
* @param FedoraDatastream $datastream
* The datastream to generated the url to.
*/
function islandora_add_datastream_form_submit($form, &$form_state) {
global $base_url;
if (!empty($form_state['submit']) && $form_state['submit'] == 'OK') {
$form_state['rebuild'] = TRUE;
return;
}
module_load_include('inc', 'islandora', 'includes/mime.detect');
$mimetype = new MimeDetect();
$file = $form_state['values']['add-stream-file-location'];
$file = drupal_realpath($file);
$object_id = $form_state['values']['pid'];
$dsid = $form_state['values']['stream_id'];
$ds_label = $form_state['values']['stream_label'];
$dformat = $mimetype->getMimeType($file);
$controlGroup = "M";
try {
$fedora_object = islandora_object_load($object_id);
$ds = $fedora_object->constructDatastream($dsid, $controlGroup);
$ds->label = $ds_label;
$ds->mimetype = $dformat;
$ds->setContentFromFile($file);
$fedora_object->ingestDatastream($ds);
$d_file = file_load($form_state['values']['fid']);
file_delete($d_file);
} catch (exception $e) {
drupal_set_message(t('@message', array('@message' => check_plain($e->getMessage()))), 'error');
return;
}
drupal_set_message("Successfully Added Datastream!");
drupal_goto("islandora/object/$object_id");
function islandora_datastream_get_delete_link(FedoraDatastream $datastream) {
$datastreams = module_invoke_all('islandora_undeletable_datastreams', $datastream->parent->models);
$can_delete = !in_array($datastream->id, $datastreams);
return $can_delete ? l(t('delete'), "islandora/object/{$datastream->parent->id}/datastream/{$datastream->id}/delete") : '';
}
/**
* validates this datastream id against its allowed mimetypes in the dscomposite
* of its content models.
* @param array $form
* @param array $form_state
* @return boolean
* Gets the edit link.
*
* @param FedoraDatastream $datastream
* The datastream to generated the url to.
*/
function islandora_add_datastream_form_validate($form, &$form_state) {
module_load_include('inc', 'islandora', 'includes/mime.detect');
$mimetype = new MimeDetect();
if ($form_state['clicked_button']['#value'] == 'OK') {
$form_state['rebuild'] = TRUE;
return;
}
$dsid = $form_state['values']['stream_id'];
$dsLabel = $form_state['values']['stream_label'];
if (strlen($dsid) > 64) {
form_set_error('', t('Data stream ID cannot be more than 64 characters.'));
return FALSE;
}
if (!(preg_match("/^[a-zA-Z]/", $dsid))) {
form_set_error('', t("Data stream ID (@dsid) has to start with a letter.", array('@dsid' => check_plain($dsid))));
return FALSE;
}
if (strlen($dsLabel) > 64) {
form_set_error('', t('Data stream Label cannot be more than 64 characters.'));
return FALSE;
}
if (strpos($dsLabel, '/')) {
form_set_error('', t('Data stream Label cannot contain a "/".'));
return FALSE;
}
$object_id = $form_state['values']['pid'];
$fedora_object = islandora_object_load($object_id);
if(isset($fedora_object[$dsid])) {
form_set_error('', t('Data stream ID already exists in object.'));
return FALSE;
}
$mimetype = new MimeDetect();
$object = islandora_object_load($form_state['values']['pid']);
$unused_dsids = islandora_get_unused_dsids($object);
if(isset($unused_dsids[$dsid])) {
$types_allowed = $unused_dsids[$dsid];
$arr = array();
foreach ($types_allowed as $type) {
$arr[] = $mimetype->getExtension($type);
}
}
else {
// todo: this is unsafe, should probably be fixed see:
// http://api.drupal.org/api/drupal/includes!file.inc/function/file_save_upload/7
$arr = array();
}
$file = file_save_upload('add-stream-file-location', array('file_validate_extensions' => $arr));
if ($file) {
$form_state['values']['add-stream-file-location'] = $file->uri;
$form_state['values']['fid'] = $file->fid; //so we can load it to delete later
}
else {
form_set_error('add-stream-file-location', t('There was no file uploaded'));
}
function islandora_datastream_edit_get_link(FedoraDatastream $datastream) {
$edit_registry = module_invoke_all('islandora_edit_datastream_registry', $datastream->parent, $datastream);
$can_edit = count($edit_registry) > 0 && user_access(FEDORA_METADATA_EDIT);
return $can_edit ? l(t('edit'), "islandora/object/{$datastream->parent->id}/datastream/{$datastream->id}/edit") : '';
}
/**
* buids the default add datastream form
* @param string $object_id
* @param array $form_state
* @return array
* a form ready to be rendered with a call to Drupal render
* Display the edit datastream page.
*
* @param FedoraDatastream $datastream
* The datastream to edit.
*/
function islandora_add_datastream_form($form, &$form_state, $object) {
$unused_dsids = islandora_get_unused_dsids($object); //$defined_dsids;
$form = array();
$form['add_fieldset'] = array(
'#type' => 'fieldset',
'#title' => 'Add a datastream',
'#collapsible' => FALSE,
'#collapsed' => FALSE,
);
$form['add_fieldset']['add_datastream_label'] = array(
'#value' => t('<br /><h3>Add Datastream:</h3>'),
'#weight' => -10,
);
$form['pid'] = array(
'#type' => 'hidden',
'#value' => "$object->id"
);
$form['add_fieldset']['stream_label'] = array(
'#title' => 'Datastream Label',
'#required' => 'TRUE',
'#description' => t('A Human readable label'),
'#type' => 'textfield'
);
$form['#attributes']['enctype'] = 'multipart/form-data';
$form['add_fieldset']['add-stream-file-location'] = array(
'#type' => 'file',
'#title' => t('Upload Document'),
'#size' => 48,
// '#required'=>'TRUE',
'#description' => t('The file to upload.')
);
$form['#redirect'] = "islandora/object/$object->id/";
$form['add_fieldset']['submit'] = array(
'#type' => 'submit',
'#value' => t('Add Datastream')
);
$unused_dsids = islandora_get_unused_dsids($object);
$dsidsForForm = '';
$i = 0;
foreach ($unused_dsids as $key => $value) {
if($i++) {
$dsidsForForm .= ", ";
}
$dsidsForForm .= "'$key'";
}
$form['add_fieldset']['stream_id'] = array(
'#title' => 'Datastream ID',
'#required' => 'TRUE',
'#description' => t('An ID for this stream that is unique to this object. Must start with a letter and contain only alphanumeric characters and dashes and underscores. Datastreams that are defined by the content model dont currently exist: <b>' . $dsidsForForm . '</b>.'),
'#type' => 'textfield',
'#weight' => -1,
'#autocomplete_path' => "islandora/object/$object->id/manage/datastreams/add/autocomplete",
);
return $form;
}
function islandora_datastream_autocomplete_callback($object, $string = '') {
$dsids = islandora_get_unused_dsids($object);
$output = array();
foreach($dsids as $id => $ds) {
if(trim($string) == '') {
$output[$id] = $id;
}
else {
$ret = stripos($id, $string);
if($ret !== FALSE) {
$output[$id] = $id;
}
}
}
drupal_json_output($output);
}
function islandora_datastream_get_human_readable_size($ds) {
module_load_include('inc', 'islandora', 'includes/utilities');
// we return - if we don't have a size
if($ds->controlGroup == 'M' || $ds->controlGroup == 'X') {
return islandora_convert_bytes_to_human_readable($ds->size);
}
else {
return '-';
}
}
function islandora_datastream_get_url($ds, $type = 'download') {
if($ds->controlGroup == 'R') {
return $ds->url;
}
else {
return "islandora/object/{$ds->parent->id}/datastream/{$ds->id}/$type";
}
}
function islandora_datastream_get_delete_link($ds) {
$datastreams = module_invoke_all('islandora_undeletable_datastreams', $ds->parent->models);
if(in_array($ds->id, $datastreams)) {
return '';
}
else {
return l(t('delete'), 'islandora/object/' . $ds->parent->id . '/datastream/' . $ds->id . '/delete');
}
}
function islandora_islandora_undeletable_datastreams($models) {
return array('DC');
}
function islandora_datastream_edit_get_link($object, $ds_id) {
$edit_registry = module_invoke_all('islandora_edit_datastream_registry', $object, $ds_id);
if (count($edit_registry) > 0 && user_access(FEDORA_METADATA_EDIT)) {
return l(t('edit'), 'islandora/object/' . $object->id . '/datastream/' . $ds_id . '/edit');
}
else {
return '';
}
}
function islandora_edit_datastream($object, $ds_id) {
$edit_registry = module_invoke_all('islandora_edit_datastream_registry', $object, $ds_id);
function islandora_edit_datastream(FedoraDatastream $datastream) {
$edit_registry = module_invoke_all('islandora_edit_datastream_registry', $datastream->parent, $datastream);
$edit_count = count($edit_registry);
if ($edit_count == 0) {
// No edit implementations.
drupal_set_message(t('There are no edit methods specified for this datastream.'));
drupal_goto('islandora/object/' . $object->id . '/manage/datastreams');
}
elseif ($edit_count == 1) {
// One registry implementation, go there
drupal_goto($edit_registry[0]['url']);
}
else {
// Multiple edit routes registered
return islandora_edit_datastream_registry_render($edit_registry);
switch ($edit_count) {
case 0:
// No edit implementations.
drupal_set_message(t('There are no edit methods specified for this datastream.'));
drupal_goto("islandora/object/{$object->id}/manage/datastreams");
break;
case 1:
// One registry implementation, go there.
drupal_goto($edit_registry[0]['url']);
break;
default:
// Multiple edit routes registered.
return islandora_edit_datastream_registry_render($edit_registry);
}
}
//@TODO: theme / preprocess
function islandora_edit_datastream_registry_render($edit_registry) {
$output = array(
/**
* Displays links to all the edit datastream registry items.
*
* @param array $edit_registry
* A list of 'islandora_edit_datastream_registry' values.
*/
function islandora_edit_datastream_registry_render(array $edit_registry) {
$markup = '';
foreach ($edit_registry as $edit_route) {
$markup .= l($edit_route['name'], $edit_route['url']) . '<br/>';
}
return array(
'#type' => 'markup',
'#markup' => '',
'#markup' => $markup,
);
foreach ($edit_registry AS $edit_route) {
$output['#markup'] .= l($edit_route['name'], $edit_route['url']) . '<br/>';
}
return $output;
}
}

71
includes/delete_datastream.form.inc

@ -0,0 +1,71 @@
<?php
/**
* @file
* The admin/confirmation form to delete/purge a datastream.
*/
/**
* The admin delete datastream form.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
* @param FedoraDatastream $datastream
* The datastream to be deleted.
*
* @return array
* The drupal form definition.
*/
function islandora_delete_datastream_form(array $form, array &$form_state, FedoraDatastream $datastream) {
$form_state['datastream'] = $datastream;
return confirm_form($form,
t('Are you sure you want to delete the %dsid datastream?', array('%dsid' => $datastream->id)),
"islandora/object/{$datastream->parent->id}",
t('This action cannot be undone.'),
t('Delete'),
t('Cancel')
);
}
/**
* Submit handler for the delete datastream form.
*
* Purges/Delete's the given FedoraDatastream if possible.
*
* The ISLANDORA_PRE_PURGE_DATASTREAM_HOOK will query other modules as to
* whether the given FedoraDatastream
* should be: blocked from purging; state set to 'Deleted'; or purged.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*/
function islandora_delete_datastream_form_submit(array $form, array &$form_state) {
$datastream = $form_state['datastream'];
$datastream_id = $datastream->id;
$object = $datastream->parent;
$deleted = FALSE;
try {
$deleted = islandora_delete_datastream($datastream);
}
catch (Exception $e) {
drupal_set_message(t('Error deleting %s datastream from object %o %e', array(
'%s' => $datastream_id,
'%o' => $object->label,
'%e' => $e->getMessage())), 'error');
}
if ($deleted) {
drupal_set_message(t('%d datastream sucessfully deleted from Islandora object %o', array(
'%d' => $datastream_id,
'%o' => $object->label)));
}
else {
drupal_set_message(t('Error deleting %s datastream from object %o', array(
'%s' => $datastream_id,
'%o' => $object->label)), 'error');
}
$form_state['redirect'] = "islandora/object/{$object->id}";
}

48
includes/delete_object.form.inc

@ -0,0 +1,48 @@
<?php
/**
* @file
* The admin/confirmation form to purge an object.
*/
/**
* The admin delete object form.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
* @param FedoraObject $object
* The object to be deleted.
*
* @return array
* The drupal form definition.
*/
function islandora_delete_object_form(array $form, array &$form_state, FedoraObject $object) {
$form_state['object'] = $object;
return confirm_form($form,
t('Are you sure you want to delete %title?', array('%title' => $object->label)),
"islandora/object/$object->id",
t('This action cannot be undone.'),
t('Delete'),
t('Cancel')
);
}
/**
* Delete's the given object.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*/
function islandora_delete_object_form_submit(array $form, array &$form_state) {
module_load_include('inc', 'islandora', 'includes/datastream');
module_load_include('inc', 'islandora', 'includes/utilities');
$object = $form_state['object'];
$parents = islandora_get_parents_from_rels_ext($object);
$parent = array_pop($parents);
$form_state['redirect'] = isset($parent) ? "islandora/object/{$parent->id}" : 'islandora';
islandora_delete_object($object);
}

93
includes/islandora_dublin_core.inc → includes/dublin_core.inc

@ -2,15 +2,16 @@
/**
* @file
* Implements a simple class for working with Dublin Core data and exporting it
* back to XML. Inspiration and design shamelessly stolen from the pyfedora
* Implements a simple class for working with Dublin Core data.
*
* Inspiration and design shamelessly stolen from the pyfedora
* project at http://pypi.python.org/pypi/pyfedora/0.1.0
*/
/**
* Dublin Core Class
*/
class Dublin_Core {
class DublinCore {
public $dc = array(
'dc:title' => array(),
@ -32,33 +33,40 @@ class Dublin_Core {
public $owner;
/**
* Constructs a Dublin_Core object from a Fedora_Item object and populates
* the $dc array.
* @param <type> $item
* Constructor.
*
* @param string $dc_xml
* The Dublin Core XML.
*/
function Dublin_Core($dc_xml = NULL) {
if (!empty($dc_string)) {
$this->dc = self::import_from_xml_string($dc_xml);
public function __construct($dc_xml = NULL) {
if (!empty($dc_xml)) {
$this->dc = self::importFromXMLString($dc_xml);
}
}
/**
* Add Elements
* @param <type> $element_name
* @param <type> $value
* Add an element.
*
* @param string $element_name
* The name of the element to add.
* @param string $value
* The value of the element to add.
*/
function add_element($element_name, $value) {
public function addElement($element_name, $value) {
if (is_string($value) && is_array($this->dc[$element_name])) {
$this->dc[$element_name][] = $value;
}
}
/**
* Replace the given DC element with the values in $values
* @param string $elemnt_name
* @param array $values
* Replace the given DC element with the given values.
*
* @param string $element_name
* The name of the elements to set.
* @param mixed $values
* The values of the set the elements too.
*/
function set_element($element_name, $values) {
public function setElement($element_name, $values) {
if (is_array($values)) {
$this->dc[$element_name] = $values;
}
@ -68,11 +76,12 @@ class Dublin_Core {
}
/**
* Serialize this object to XML and return it.
* @param type $with_preamble
* @return type
* Serialize this object as an XML string.
*
* @return string
* The serialized XML.
*/
function as_xml($with_preamble = FALSE) {
public function asXML() {
$dc_xml = new DomDocument();
$oai_dc = $dc_xml->createElementNS('http://www.openarchives.org/OAI/2.0/oai_dc/', 'oai_dc:dc');
$oai_dc->setAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/');
@ -93,24 +102,23 @@ class Dublin_Core {
}
/**
* Create dc from dict ( does nothing )
* Serializes this object as an array.
*
* @return array
* The serialized object.
*/
static function create_dc_from_dict() {
}
function as_formatted_array() {
public function asArray() {
$dc_array = array();
foreach ($this as $element) {
if (!empty($element)) {
foreach ($element as $field => $values) {
// split value if the result value is an array
// Split value if the result value is an array.
if (is_array($values)) {
$value = '';
$i = 0;
foreach($values as $piece) {
if(!empty($piece)) {
if($i++) {
foreach ($values as $piece) {
if (!empty($piece)) {
if ($i++) {
$value .= ", ";
}
$value .= $piece;
@ -121,29 +129,35 @@ class Dublin_Core {
$value = $values;
}
$dc_label = explode(':', $field);
$element_label = ucfirst($dc_label[1]);
$element_label = drupal_ucfirst($dc_label[1]);
$dc_array[$field]['label'] = $element_label;
$dc_array[$field]['value'] = $value;
$dc_array[$field]['class'] = strtolower(preg_replace('/[^A-Za-z0-9]/', '-', $field));
$dc_array[$field]['class'] = drupal_strtolower(preg_replace('/[^A-Za-z0-9]/', '-', $field));
}
}
}
return $dc_array;
}
/**
* Creates a new instance of the class by parsing dc_xml
* Creates a new instance of the class by parsing dc_xml.
*
* @param string $dc_xml
* @return Dublin_Core
* Dublin Core XML.
*
* @return DublinCore
* The instantiated object.
*/
static function import_from_xml_string($dc_xml) {
public static function importFromXMLString($dc_xml) {
$dc_doc = new DomDocument();
if ($dc_doc->loadXML($dc_xml)) {
$oai_dc = $dc_doc->getElementsByTagNameNS('http://purl.org/dc/elements/1.1/', '*');
$new_dc = new Dublin_Core();
$new_dc = new DublinCore();
foreach ($oai_dc as $child) {
array_push($new_dc->dc[$child->nodeName], $child->nodeValue);
if (isset($new_dc->dc[$child->nodeName])) {
array_push($new_dc->dc[$child->nodeName], $child->nodeValue);
}
}
return $new_dc;
}
@ -153,4 +167,3 @@ class Dublin_Core {
}
}

46
includes/ingest-menu.inc

@ -1,46 +0,0 @@
<?php
/**
* @file
* Menu callback functionality for islandora/ingest
*/
/**
* Callback function for islandora/ingest/%collection_pid
* @TODO: validate?: pid, registry return
* @param string $pid
*/
function islandora_ingest_callback($collection_object) {
if(!$collection_object) {
return drupal_not_found();
}
$ingest_registry = module_invoke_all('islandora_ingest_registry', $collection_object);
$registry_count = count($ingest_registry);
if ($registry_count == 0) {
// No ingest implementations.
drupal_set_message(t('There are no ingest methods specified for @name.', array('@name', $collection_object->label)));
drupal_goto('islandora/object/' . $collection_object->id);
}
elseif ($registry_count == 1) {
// One registry implementation, go there
drupal_goto($ingest_registry[0]['url']);
}
else {
// Multiple ingest routes registered
return islandora_ingest_registry_render($ingest_registry);
}
}
//@TODO: theme
function islandora_ingest_registry_render($ingest_registry) {
$output = array(
'#type' => 'markup',
'#markup' => '',
);
foreach ($ingest_registry AS $ingest_route) {
$output['#markup'] .= l($ingest_route['name'], $ingest_route['url']) . '<br/>';
}
return $output;
}

551
includes/ingest.form.inc

@ -0,0 +1,551 @@
<?php
/**
* @file
* Defines the multi-page ingest form and any relevant hooks and functions.
*/
/**
* Ingest form build function.
*
* Initializes the form state, and builds the initial list of steps, excutes
* the current step.
*
* @param array $form
* The drupal form.
* @param array $form_state
* The drupal form state.
* @param array $configuration
* An associative array of configuration values that are used to build the
* list of steps to be executed, including:
* - id: The PID with which the object should be created.
* - namespace: The PID namespace in which the object should be created.
* (id is used first, if it is given).
* - label: The initial label for the object. Defaults to "New Object".
* - collections: An array of collection PIDs, to which the new object should
* be related.
* - models: An array of content model PIDs, to which the new object might
* subscribe
*
* @return array
* The form definition of the current step.
*/
function islandora_ingest_form(array $form, array &$form_state, array $configuration) {
islandora_ingest_form_init_form_state($form_state, $configuration);
$form = islandora_ingest_form_execute_step($form, $form_state);
return $form;
}
/**
* Prepares/Initializes the form state for use.
*
* Also cleans up or loads any data required.
*
* @param array $form_state
* The drupal form state.
* @param array $configuration
* A list of key value pairs that are used to build the list of steps to be
* executed.
*/
function islandora_ingest_form_init_form_state(array &$form_state, array $configuration) {
// First time initialization of storage.
islandora_ingest_form_init_form_state_storage($form_state, $configuration);
}
/**
* Initializes the form_state storage for use in the ingest multi-page forms.
*
* @param array $form_state
* The drupal form state.
* @param array $configuration
* A list of key value pairs that are used to build the list of steps to be
* executed.
*/
function islandora_ingest_form_init_form_state_storage(array &$form_state, array $configuration) {
if (empty($form_state['islandora'])) {
module_load_include('inc', 'islandora', 'includes/utilities');
// Use ID if given.
$id = isset($configuration['id']) ? $configuration['id'] : NULL;
// Use namespace if ID not given.
$namespace = isset($configuration['namespace']) && !isset($id) ? $configuration['namespace'] : $id;
$label = isset($configuration['label']) ? $configuration['label'] : 'New Object';
$relationship_map = function($o) {
return array('relationship' => 'isMemberOfCollection', 'pid' => $o);
};
$relationships = empty($configuration['collections']) ? array() : array_map($relationship_map, $configuration['collections']);
$object = islandora_prepare_new_object($namespace, $label, array(), array(), $relationships);
$form_state['islandora'] = array(
'step_id' => NULL,
'objects' => array($object),
'configuration' => $configuration,
'step_storage' => array(),
);
}
$steps = islandora_ingest_get_steps($form_state);
if ($form_state['islandora']['step_id'] === NULL || !array_key_exists(
$form_state['islandora']['step_id'], $steps)) {
reset($steps);
$form_state['islandora']['step_id'] = key($steps);
}
// Stash the current configuration in the step.
$storage = &islandora_ingest_form_get_step_storage($form_state);
$storage['configuration'] = $form_state['islandora']['configuration'];
}
/**
* Build a list of steps given only configuration.
*
* XXX: This is used to give an indication of whether there are any steps for a
* given list of content models.
*
* @param array $configuration
* The list of key/value pairs of configuration.
*/
function islandora_ingest_get_approximate_steps(array $configuration) {
$fake_form_state = array(
'islandora' => array(
'configuration' => $configuration,
),
);
$steps = islandora_ingest_get_steps($fake_form_state);
drupal_static_reset('islandora_ingest_get_steps');
return $steps;
}
/**
* Executes the current step.
*
* Builds the form definition and appends any additonal elements required for
* the step to function.
*
* @param array $form
* The drupal form.
* @param array $form_state
* The drupal form state.
*
* @return array
* The form definition of the current step.
*/
function islandora_ingest_form_execute_step(array $form, array &$form_state) {
// Load any required files for the current step.
islandora_ingest_form_step_form_load_include($form_state);
$step_info = islandora_ingest_form_get_step_info($form_state);
switch ($step_info['type']) {
case 'form':
$args = array($form, &$form_state);
$args = isset($step_info['args']) ? array_merge($args, $step_info['args']) : $args;
$form = call_user_func_array($step_info['form_id'], $args);
return islandora_ingest_form_stepify($form, $form_state, $step_info);
case 'batch':
// @todo Implement if possible.
break;
}
return array();
}
/**
* Append Prev/Next buttons submit/validation handlers etc.
*
* @param array $form
* The drupal form.
* @param array $form_state
* The drupal form state.
* @param array $step_info
* The info for building the current form step.
*
* @return array
* The stepified drupal form definition for the given step.
*/
function islandora_ingest_form_stepify(array $form, array &$form_state, array $step_info) {
$step = islandora_ingest_form_get_step_number($form_state);
$first_step = $step > 0;
$last_step = $step == (islandora_ingest_form_get_step_count($form_state) - 1);
$form['prev'] = $first_step ? islandora_ingest_form_previous_button() : NULL;
$form['next'] = $last_step ? islandora_ingest_form_ingest_button($step_info) : islandora_ingest_form_next_button($step_info);
return $form;
}
/**
* Defines the previous button for the ingest form.
*
* @return array
* The previous button for the ingest form.
*/
function islandora_ingest_form_previous_button() {
return array(
'#type' => 'submit',
'#value' => t('Previous'),
'#name' => 'prev',
'#submit' => array('islandora_ingest_form_previous_submit'),
// #limit_validation_errors, is why when the previous button is pressed no
// values persisted in the form_state, but its also what allows us to go
// back when validation errors occur. To have a better solution going
// forward we can either limit validation only on required fields, or we can
// convert all required fields to use #element_validation functions, and
// Remove the need for #limit_validation_errors. Or maybe there is some
// other solution, regardless of what it is, it won't be standard.
'#limit_validation_errors' => array(),
);
}
/**
* Get the current step.
*
* @param array $form_state
* The Drupal form state.
* @param string $step_id
* The ID of the step to get.
*/
function islandora_ingest_form_get_step_number(array $form_state, $step_id = NULL) {
if ($step_id === NULL) {
$step_id = islandora_ingest_form_get_step_id($form_state);
}
$steps = array_flip(array_keys(islandora_ingest_form_get_steps($form_state)));
return $steps[$step_id];
}
/**
* The submit handler for the ingest form previous button.
*
* Stores the current form steps values in the form storage.
* Moves the focus of the multi-page ingest form back one step.
* Restores the form values for the previous step.
*
* @param array $form
* The drupal form.
* @param array $form_state
* The drupal form state.
*/
function islandora_ingest_form_previous_submit(array $form, array &$form_state) {
$step = islandora_ingest_form_get_step_number($form_state);
islandora_ingest_form_stash_info($form_state);
$step = max(array($step - 1, 0));
$form_state['islandora']['step_id'] = islandora_ingest_form_get_step_id($form_state, $step);
islandora_ingest_form_grab_info($form_state);
$form_state['rebuild'] = TRUE;
}
/**
* Defines the next button for the ingest form.
*
* Adds submit/validate handlers for the form step if they exist.
*
* @return array
* The next button for the ingest form.
*/
function islandora_ingest_form_next_button(array $step_info) {
$form_id = $step_info['form_id'];
$validate_callback = $form_id . '_validate';
$validate = function_exists($validate_callback) ? array($validate_callback) : NULL;
$submit_callback = $form_id . '_submit';
$submit = function_exists($submit_callback) ? array($submit_callback, 'islandora_ingest_form_next_submit') : array('islandora_ingest_form_next_submit');
return array(
'#type' => 'submit',
'#value' => t('Next'),
'#name' => 'next',
'#validate' => $validate,
'#submit' => $submit,
);
}
/**
* The submit handler for the ingest form next button.
*
* Stores the current form steps values in the form storage.
* Moves the focus of the multi-page ingest form forward one step.
* Restores the form values for the next step if present.
*
* @param array $form
* The drupal form.
* @param array $form_state
* The drupal form state.
*/
function islandora_ingest_form_next_submit(array $form, array &$form_state) {
$step = islandora_ingest_form_get_step_number($form_state);
drupal_static_reset('islandora_ingest_form_get_steps');
islandora_ingest_form_stash_info($form_state);
$step = min(array($step + 1, islandora_ingest_form_get_step_count($form_state) - 1));
$form_state['islandora']['step_id'] = islandora_ingest_form_get_step_id($form_state, $step);
islandora_ingest_form_grab_info($form_state);
$form_state['rebuild'] = TRUE;
}
/**
* Push current info into the current step's storage.
*/
function islandora_ingest_form_stash_info(array &$form_state) {
$storage = &islandora_ingest_form_get_step_storage($form_state);
$storage['values'] = $form_state['values'];
unset($form_state['values']);
}
/**
* Pops the info for the given step from storage into the form_state.
*/
function islandora_ingest_form_grab_info(array &$form_state) {
$storage = islandora_ingest_form_get_step_storage($form_state);
$form_state['values'] = isset($storage['values']) ? $storage['values'] : array();
if (isset($storage['configuration'])) {
$form_state['islandora']['configuration'] = $storage['configuration'];
}
}
/**
* Defines the ingest button for the ingest form.
*
* This button is only shown on the last page of the multi-page ingest form.
*
* @return array
* The ingest button for the ingest form.
*/
function islandora_ingest_form_ingest_button(array $step_info) {
$form_id = $step_info['form_id'];
$validate_callback = $form_id . '_validate';
$validate = function_exists($validate_callback) ? array($validate_callback) : NULL;
$submit_callback = $form_id . '_submit';
$submit = function_exists($submit_callback) ? array($submit_callback, 'islandora_ingest_form_submit') : array('islandora_ingest_form_submit');
return array(
'#type' => 'submit',
'#name' => 'ingest',
'#value' => t('Ingest'),
'#validate' => $validate,
'#submit' => $submit,
);
}
/**
* The submit handler for the ingest form.
*
* Attempts to ingest every object built by the previous steps.
*
* @param array $form
* The drupal form.
* @param array $form_state
* The drupal form state.
*/
function islandora_ingest_form_submit(array $form, array &$form_state) {
foreach ($form_state['islandora']['objects'] as $object) {
try {
islandora_add_object($object);
$form_state['redirect'] = "islandora/object/{$object->id}";
}
catch (Exception $e) {
// If post hooks throws it may already exist at this point but may be
// invalid, so don't say failed.
watchdog('islandora', $e->getMessage(), NULL, WATCHDOG_ERROR);
drupal_set_message(t('A problem occured while ingesting "@label" (ID: @pid), please notifiy the administrator.', array('@label' => $object->label, '@pid' => $object->id)), 'error');
}
}
}
/**
* Gets the configuration used to create the multi-page ingest form.
*
* @param array $form_state
* The drupal form state.
*
* @return array
* The configuration used to generate the multi-page ingest forms.
*/
function &islandora_ingest_form_get_configuration(array &$form_state) {
return $form_state['islandora']['configuration'];
}
/**
* Gets a reference to the stored NewFedoraObject's.
*
* @param array $form_state
* The drupal form state.
*
* @return array
* A reference to the stored NewFedoraObjects to be ingested when the final
* step submits.
*/
function &islandora_ingest_form_get_objects(array $form_state) {
return $form_state['islandora']['objects'];
}
/**
* Gets a single object from the stored NewFedoraObject's.
*
* @note - In our current use case we are only dealing with a single object
* ingest, this makes it convenient to access it. Ideally the steps
* implementations will be abstracted to be indifferent to what object it's
* currently working on. This will act as a placeholder for such
* functionality.
*
* @param array $form_state
* The drupal form state.
*
* @return NewFedoraObject
* Returns the 'current' object in the array of NewFedoraObjects, generally
* this is only used when there is one object in the list of objects.
*/
function islandora_ingest_form_get_object(array $form_state) {
$objects = &islandora_ingest_form_get_objects($form_state);
return current($objects);
}
/**
* Get a reference to the current step index.
*
* @param array $form_state
* The drupal form state.
*
* @return string
* The current step index.
*/
function islandora_ingest_form_get_step_id(array &$form_state, $step_number = NULL) {
if ($step_number === NULL) {
return $form_state['islandora']['step_id'];
}
else {
$steps = array_keys(islandora_ingest_form_get_steps($form_state));
return $steps[$step_number];
}
}
/**
* Get the step info of the given step or the current step if none is given.
*
* @param array $form_state
* The drupal form state.
* @param int $step
* The index of the step to get.
*
* @return int
* The step info of the requested step if found, NULL otherwise.
*/
function islandora_ingest_form_get_step_info(array &$form_state, $step = NULL) {
$step = isset($step) ? $step : islandora_ingest_form_get_step_id($form_state);
$steps = islandora_ingest_form_get_steps($form_state);
if (!empty($steps[$step])) {
return $steps[$step];
}
// @todo deal with unknown case.
return NULL;
}
/**
* Get general storage for the given/current step.
*
* @param array $form_state
* The drupal form state.
* @param string $step_id
* The ID of the step.
*/
function &islandora_ingest_form_get_step_storage(array &$form_state, $step_id = NULL) {
if ($step_id === NULL) {
$step_id = islandora_ingest_form_get_step_id($form_state);
}
if (!isset($form_state['islandora']['step_storage'][$step_id])) {
$form_state['islandora']['step_storage'][$step_id] = array();
}
return $form_state['islandora']['step_storage'][$step_id];
}
/**
* Get a reference to the steps stored in the form state.
*
* @param array $form_state
* The drupal form state.
*
* @return array
* All the steps to be used in the ingest process.
*/
function islandora_ingest_form_get_steps(array &$form_state) {
return islandora_ingest_get_steps($form_state);
}
/**
* Call form_load_include, for the current step if it defines a required file.
*
* @param array $form_state
* The drupal form state.
*/
function islandora_ingest_form_step_form_load_include(array &$form_state) {
form_load_include($form_state, 'inc', 'islandora', 'includes/ingest.form');
$step_info = islandora_ingest_form_get_step_info($form_state);
// Load include files.
if (isset($step_info['file']) && isset($step_info['module'])) {
$matches = array();
preg_match('/^(.*)\.(.*)$/', $step_info['file'], $matches);
list($file, $name, $type) = $matches;
form_load_include($form_state, $type, $step_info['module'], $name);
}
}
/**
* Get the number of steps.
*
* @param array $form_state
* The drupal form state.
*
* @return int
* The number of steps.
*/
function islandora_ingest_form_get_step_count(array $form_state) {
$steps = islandora_ingest_form_get_steps($form_state);
return count($steps);
}
/**
* Buildes the initial list of ingest steps.
*
* Sorted by weight expected range between -50 to 50.
*
* The sort order is undefined for steps which have the same weight.
*
* @param array $form_state
* The Drupal form state.
*
* @return array
* The list of sorted ingest steps as defined by all implementers
* of ISLANDORA_INGEST_STEP_HOOK.
*/
function &islandora_ingest_get_steps(array &$form_state) {
module_load_include('inc', 'islandora', 'includes/utilities');
$steps = &drupal_static(__FUNCTION__);
if (!isset($steps)) {
$steps = array();
$configuration = islandora_ingest_form_get_configuration($form_state);
$models = array();
if (isset($configuration['selected_models'])) {
$models = $configuration['selected_models'];
}
elseif (isset($configuration['models'])) {
$models = $configuration['models'];
}
foreach (islandora_build_hook_list(ISLANDORA_INGEST_STEP_HOOK, $models) as $hook) {
// Need to pass by ref... But don't really want an alter.
foreach (module_implements($hook) as $module) {
$function = $module . '_' . $hook;
$module_steps = (array) $function($form_state);
$steps = array_merge($steps, $module_steps);
}
}
// Remove NULL values.
$steps = array_filter($steps);
uasort($steps, 'drupal_sort_weight');
foreach (islandora_build_hook_list(ISLANDORA_INGEST_STEP_HOOK, $models) as $hook) {
$form_state_copy = $form_state;
drupal_alter($hook, $steps, $form_state_copy);
}
uasort($steps, 'drupal_sort_weight');
}
return $steps;
}

65
includes/ingest.menu.inc

@ -0,0 +1,65 @@
<?php
/**
* @file
* Ingest Menu callback hooks.
*/
/**
* Menu callback, Renders the multi-page ingest form if possible.
*
* @return string
* HTML representing the mult-page ingest form.
*/
function islandora_ingest_callback() {
$configuration = islandora_ingest_get_configuration();
if ($configuration === FALSE) {
drupal_set_message(t('Invalid ingest configuration.'), 'error');
$redirect = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '<front>';
// Redirect back to referer or top level collection.
drupal_goto($redirect);
}
module_load_include('inc', 'islandora', 'includes/ingest.form');
return drupal_get_form('islandora_ingest_form', $configuration);
}
/**
* Fetches/validates the ingest configuration from the $_GET parameters.
*
* Generic parameters as accepted by all ingest processes, other modules may
* add to this list.
* id -> The pid of the object to create. optional.
* models -> Comma delimited list of all the content models the created object
* should have.
* collections -> Comma delimited list of all the collections the created
* object should belong to.
*
* @return array
* The configuration options used to build the multi-paged ingest process.
*/
function islandora_ingest_get_configuration() {
$configuration = $_GET;
unset($configuration['q']);
$convert_to_array_keys = array_intersect(array('models', 'collections'), array_keys($configuration));
foreach ($convert_to_array_keys as $key) {
$configuration[$key] = explode(',', $configuration[$key]);
}
// @todo add hook for manipulating/validating the configuration.
return islandora_valid_ingest_configuration($configuration) ? $configuration : FALSE;
}
/**
* Validates the given ingest configuration.
*
* At the moment it requires that models and collections are present.
*
* @param array $configuration
* The key value pairs that are used to build the multi-paged ingest process.
*
* @return bool
* TRUE if the configuration is valid, FALSE otherwise.
*/
function islandora_valid_ingest_configuration(array $configuration) {
// @todo Add more robust validation, add watchdog logs, etc.
return isset($configuration['models']) && isset($configuration['collections']);
}

27
includes/islandora.ingest.inc

@ -1,27 +0,0 @@
<?php
function islandora_ingest_get_information(AbstractFedoraObject $collection_object) {
$models = $collection_object->models;
$collection_info = module_invoke_all('islandora_ingest_get_information', $models, $collection_object);
return $collection_info;
}
function islandora_ingest_get_object($content_models, $collection_pid, $relationship, $namespace) {
module_load_include('inc', 'islandora', 'includes/tuque');
global $user;
$connection = new IslandoraTuque($user);
$object = $connection->repository->constructObject($namespace);
foreach($content_models as $content_model) {
$object->relationships->add(FEDORA_MODEL_URI, 'hasModel', $content_model['pid']);
}
$object->relationships->add(FEDORA_RELS_EXT_URI, $relationship, $collection_pid);
module_invoke_all('islandora_ingest_pre_ingest', $object, $content_models, $collection_pid);
return $object;
}
function islandora_ingest_add_object(&$object) {
$object->repository->ingestObject($object);
module_invoke_all('islandora_ingest_post_ingest', $object);
return $object;
}

63
includes/mime.detect.inc → includes/mime_detect.inc

@ -1,9 +1,9 @@
<?php
/**
* @file
* Class for determining MIME types and file extensions.
*
* This class inspired by Chris Jean's work, here:
* http://chrisjean.com/2009/02/14/generating-mime-type-in-php-is-not-magic/
*
@ -19,7 +19,6 @@
*
* Drupal 7 will have better mime handlers. See:
* http://api.drupal.org/api/function/file_default_mimetype_mapping/7
*
*/
class MimeDetect {
@ -199,7 +198,7 @@ class MimeDetect {
protected $etcMimeTypes = '/etc/mime.types';
/**
* Construtor
* Construtor.
*/
public function __construct() {
@ -213,12 +212,11 @@ class MimeDetect {
}
/**
* description: returns a mimetype associated with the file extension of
* $filename
* Gets MIME type associated with the give file's extension.
*
* @param string $filename
* The filename
* @param boolean $debug
* @param bool $debug
* Returns a debug array.
*
* @return mixed
@ -227,7 +225,7 @@ class MimeDetect {
public function getMimetype($filename, $debug = FALSE) {
$file_name_and_extension = explode('.', $filename);
$ext = strtolower(array_pop($file_name_and_extension));
$ext = drupal_strtolower(array_pop($file_name_and_extension));
if (!empty($this->protectedMimeTypes[$ext])) {
if (TRUE === $debug) {
@ -263,12 +261,15 @@ class MimeDetect {
}
/**
* function: get_extension
* description: returns *one* valid file extension for a given $mime_type
* Gets one valid file extension for a given MIME type.
*
* @param type $mime_type
* @param type $debug
* @return type
* @param string $mime_type
* The MIME type.
* @param bool $debug
* Generated debug information?
*
* @return string
* The file extensions associated with the given MIME type.
*/
public function getExtension($mime_type, $debug = FALSE) {
@ -296,11 +297,14 @@ class MimeDetect {
}
/**
* function: systemMimetypeExtensions
* description: populates an internal array of mimetype/extension associations
* from the system mime.types file, or a local mime.types if one is found (see
* __constuctor).
* return: array of mimetype => extension
* Gets an associative array of MIME type and extension associations.
*
* Users the system mime.types file, or a local mime.types if one is found
* @see MIMEDetect::__constuctor()
*
* @return array
* An associative array where the keys are MIME types and the values
* extensions.
*/
protected function systemMimetypeExtensions() {
$out = array();
@ -328,11 +332,14 @@ class MimeDetect {
}
/**
* function: systemMimetypeExtensions
* description: populates an internal array of mimetype/extension associations
* from the system mime.types file, or a local mime.types if one is found (see
* __constuctor).
* return: array of extension => mimetype
* Gets a associative array of extensions and MIME types.
*
* Users the system mime.types file, or a local mime.types if one is found
* @see MIMEDetect::__constuctor()
*
* @return array
* An associative array where the keys are extensions and the values
* MIME types.
*/
protected function systemExtensionMimetypes() {
$out = array();
@ -340,15 +347,18 @@ class MimeDetect {
$file = fopen($this->etcMimeTypes, 'r');
while (($line = fgets($file)) !== FALSE) {
$line = trim(preg_replace('/#.*/', '', $line));
if (!$line)
if (!$line) {
continue;
}
$parts = preg_split('/\s+/', $line);
if (count($parts) == 1)
if (count($parts) == 1) {
continue;
}
// A single part means a mimetype without extensions, which we ignore.
$type = array_shift($parts);
foreach ($parts as $part)
foreach ($parts as $part) {
$out[$part] = $type;
}
}
fclose($file);
}
@ -356,4 +366,3 @@ class MimeDetect {
}
}

53
includes/object.entity_controller.inc

@ -0,0 +1,53 @@
<?php
/**
* @file
* Very basic entity controller.
*/
class IslandoraObjectEntityController implements DrupalEntityControllerInterface {
/**
* Constructor.
*
* @param string $entity_type
* The type of entity.
*/
public function __construct($entity_type) {
// No-op...
}
/**
* Load all the entities.
*
* @param array $ids
* The ID's of the entities.
* @param array $conditions
* The conditions to apply.
*/
public function load($ids = array(), $conditions = array()) {
if (!empty($conditions)) {
throw new Exception('Conditions not implemented.');
}
$loaded = array();
foreach ($ids as $id) {
$load = islandora_object_load($id);
if ($load) {
$loaded[] = $load;
}
}
return $loaded;
}
/**
* Reset the cache.
*
* @param array $ids
* The ID's of the entities.
*/
public function resetCache(array $ids = NULL) {
// no-op.
}
}

122
includes/object_properties.form.inc

@ -0,0 +1,122 @@
<?php
/**
* @file
* Contains admin form functions for editing an object's properties.
*/
/**
* Object properties admin form.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
* @param FedoraObject $object
* The object whose properties this form will modify.
*
* @return array
* The drupal form definition.
*/
function islandora_object_properties_form(array $form, array &$form_state, FedoraObject $object) {
drupal_set_title($object->label);
$form_state['object'] = $object;
return array(
'pid' => array(
'#type' => 'hidden',
'#value' => $object->id,
),
'object_label' => array(
'#title' => t('Item Label'),
'#default_value' => $object->label,
'#required' => 'TRUE',
'#description' => t('A Human readable label'),
// Double the normal length.
'#size' => 120,
// Max length for a Fedora Label.
'#maxlength' => 255,
'#type' => 'textfield',
),
// @todo Make this into an autocomplete field that list the users in the
// system as well.
'object_owner' => array(
'#title' => t('Owner'),
'#default_value' => $object->owner,
'#required' => FALSE,
'#description' => t('The owner id'),
'#type' => 'textfield',
),
'object_state' => array(
'#title' => t('State'),
'#default_value' => $object->state,
'#required' => TRUE,
'#description' => t('The items state one of active, inactive or deleted'),
'#type' => 'select',
'#options' => array('A' => 'Active', 'I' => 'Inactive', 'D' => 'Deleted'),
),
'submit' => array(
'#type' => 'submit',
'#value' => 'Update Properties',
),
'delete' => array(
'#type' => 'submit',
'#value' => t('Delete'),
'#submit' => array('islandora_object_properties_form_delete'),
'#limit_validation_errors' => array(array('pid')),
),
);
}
/**
* Submit handler for object properties admin form.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*/
function islandora_object_properties_form_submit(array $form, array &$form_state) {
$object = $form_state['object'];
$owner = $form_state['values']['object_owner'];
$state = $form_state['values']['object_state'];
$label = $form_state['values']['object_label'];
if (isset($owner) && $owner != $object->owner) {
try {
$object->owner = $owner;
drupal_set_message(t('Successfully updated owner %s', array('%s' => $owner)));
}
catch (Exception $e) {
form_set_error('object_owner', t('Error updating owner %s', array('%s' => $e->getMessage())));
}
}
if (isset($state) && $state != $object->state) {
try {
$object->state = $state;
drupal_set_message(t('Successfully updated state %s', array('%s' => $state)));
}
catch (Exception $e) {
form_set_error('object_state', t('Error updating state %s', array('%s' => $e->getMessage())));
}
}
if (isset($label) && $label != $object->label) {
try {
$object->label = $label;
drupal_set_message(t('Successfully updated label %s', array('%s' => check_plain($label))));
}
catch (Exception $e) {
form_set_error(t('Error updating label %s', array('%s' => $e->getMessage())));
}
}
}
/**
* Callback function for object properties admin form delete button.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*/
function islandora_object_properties_form_delete(array $form, array &$form_state) {
drupal_goto("islandora/object/{$form_state['values']['pid']}/delete");
}

115
includes/object_properties.inc

@ -1,115 +0,0 @@
<?php
/**
* may want more validation here the only restrictions i see on
* the object label and owner is the foxml schema says they should be
* an xsd:string there maybe further restrictions such as length but they aren't
* defined in the schema.
* @param array $form
* @param array $form_state
* @return boolean
*/
function islandora_edit_properties_form_validate($form, &$form_state) {
$islandora_object = islandora_object_load($form_state['values']['pid']);
if (!isset($islandora_object)) {
form_set_error('', t('Could not update properties object not found.'));
return FALSE;
}
}
/**
*
* @param array $form
* @param array $form_state
*/
function islandora_edit_properties_form_submit($form, &$form_state) {
$islandora_object = islandora_object_load($form_state['values']['pid']);
$owner = $form_state['values']['object_owner'];
$state = $form_state['values']['object_state'];
$label = $form_state['values']['object_label'];
if (isset($owner) && $owner != $islandora_object->owner) {
try {
$islandora_object->owner = $owner;
drupal_set_message(t('Successfully updated owner %s', array('%s' => $owner)));
} catch (Exception $e) {
form_set_error('object_owner',t('Error updating owner %s', array('%s'=> $e->getMessage())));
}
}
if (isset($state) && $state != $islandora_object->state) {
try {
$islandora_object->state = $state;
drupal_set_message(t('Successfully updated state %s', array('%s' => $state)));
} catch (Exception $e) {
form_set_error('object_state',t('Error updating state %s', array('%s'=> $e->getMessage())));
}
}
if (isset($label) && $label != $islandora_object->label) {
try {
$islandora_object->label = $label;
drupal_set_message(t('Successfully updated label %s', array('%s' => check_plain($label))));
} catch (Exception $e) {
form_set_error(t('Error updating label %s', array('%s' => $e->getMessage())));
}
}
}
function islandora_edit_properties_form_delete($form, &$form_state) {
$islandora_object = $form_state['values']['pid'];
drupal_goto("islandora/object/$islandora_object/delete");
}
/**
*
* @param array $form
* @param array $form_state
* @param string $object_id
* an object id
* @return array
*/
function islandora_edit_properties_form($form, &$form_state, $object) {
$form = array();
if (!isset($object)) {
return NULL;
}
drupal_set_title($object->label);
$form['pid'] = array(
'#type' => 'hidden',
'#value' => $object->id,
);
$form['object_label'] = array(
'#title' => t('Item Label'),
'#default_value' => $object->label,
'#required' => 'TRUE',
'#description' => t('A Human readable label'),
'#type' => 'textfield'
);
$form['object_owner'] = array(
'#title' => t('Owner'),
'#default_value' => $object->owner,
'#required' => FALSE,
'#description' => t('The owner id'),
'#type' => 'textfield',
);
$form['object_state'] = array(
'#title' => t('State'),
'#default_value' => $object->state,
'#required' => TRUE,
'#description' => t('The items state one of active, inactive or deleted'),
'#type' => 'select',
'#options' => array('A' => 'Active', 'I' => 'Inactive', 'D' => 'Deleted'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Update Properties',
);
$form['delete'] = array(
'#type' => 'submit',
'#value' => t('Delete'),
'#submit' => array('islandora_edit_properties_form_delete'),
'#limit_validation_errors' => array(array('pid')),
);
return $form;
}
?>

160
includes/purge.form.inc

@ -1,160 +0,0 @@
<?php
/**
* Gives the option of deleting or purging and object.
*
* The default behaviour is to purge the object to reduce maintenance.
* If a solution pack wants to change this behaviour and have the object set to deleted then
* it can respond to the 'islandora_pre_purge_object' hook with an array containing the pair
* 'delete' => TRUE.
* Once the object has been deleted/purged then a second call lets the solution packs know that
* the object has been dealt with. In this call the object id and content models are sent out so
* that the solution packs can act on this news. There is no guarantee that the object still exists
* and so the object object isn't sent.
*
* @param string $object_id
* ID of the object
* @return type
*/
function islandora_purge_object_submit($form, &$form_state) {
$object_id = $form_state['values']['pid'];
$collection = $form_state['values']['col'];
if (!$object_id) {
drupal_set_message(t('Cannot remove object, object id not set'));
return;
}
$object = islandora_object_load($object_id);
if (!$object) {
drupal_set_message(t('Could not remove object, object not found'));
return;
}
$content_models = $object->models;
$arr = module_invoke_all('islandora_pre_purge_object', $object); //notify modules of pending deletion
if (isset($arr['delete']) && $arr['delete']) {
try {
$object->delete();
} catch (Exception $e) {
drupal_set_message(t('Error deleting Islandora object %s %e', array('%s' => $object_id, '%e' => $e)), 'error');
return "";
}
}
else {
try {
$object->repository->purgeObject($object_id);
} catch (Exception $e) {
drupal_set_message(t('Error purging Islandora object %s %e', array('%s' => $object_id, '%e' => $e)), 'error');
return "";
}
}
module_invoke_all('islandora_post_purge_object', $object_id, $content_models); //notify modules post deletion
drupal_goto($collection);
}
function islandora_purge_object($form, &$form_state, $object) {
module_load_include('inc', 'islandora', 'includes/datastream');
$parent = islandora_datastream_get_parents($object);
$key = array_keys($parent);
if (count($key) > 0) {
$redirect = "islandora/object/$key[0]";
}
else {
$redirect = "islandora";
}
$form['pid'] = array('#type' => 'value', '#value' => $object->id);
$form['col'] = array('#type' => 'value', '#value' => $redirect);
return confirm_form($form,
t('Are you sure you want to delete %title?', array('%title' => $object->label)),
"islandora/object/$object->id",
t('This action cannot be undone.'),
t('Delete'),
t('Cancel')
);
}
function islandora_purge_datastream($form, &$form_state, $object, $datastream_id) {
module_load_include('inc', 'islandora', 'includes/datastream');
$datastream = $object->getDatastream($datastream_id);
$redirect = "islandora/object/$object->id";
$form['pid'] = array('#type' => 'value', '#value' => $object->id);
$form['dsid'] = array('#type' => 'value', '#value' => $datastream_id);
$form['col'] = array('#type' => 'value', '#value' => $redirect);
return confirm_form($form,
t('Are you sure you want to delete the %dsid datastream?', array('%dsid' => $datastream->id)),
"islandora/object/$object->id",
t('This action cannot be undone.'),
t('Delete'),
t('Cancel')
);
}
/**
* Gives the option of purging or deleting a datastream.
*
* The default behaviour is to purge the datastream but this can be overridden using the
* 'islandora_pre_purge_datastream' hook. The returned array can include a 'block' => TRUE
* pair which will prevent the datastream from being deleted if it particularly needed for
* a certain function. Returning 'delete' => TRUE will cause the datastream to be put into
* a deleted state.
*
* @param string $object_id
* ID of the object
* @param string $datastream_id
* ID of the datastream
*
*/
function islandora_purge_datastream_submit($form, &$form_state) {
$object_id = $form_state['values']['pid'];
$datastream_id = $form_state['values']['dsid'];
if (!isset($datastream_id)) {
drupal_set_message(t('Cannot remove datastream, datastream id not set'));
return;
}
$object = islandora_object_load($object_id);
if (!isset($object)) {
drupal_set_message(t('Could not remove object, object not found'));
return;
}
//notify modules of pending deletion so we can update rels etc
$arr = module_invoke_all('islandora_pre_purge_datastream', $object[$datastream_id]);
if (isset($arr['block']) && $arr['block']) {
drupal_set_message(t('Purging of the %d datastream was blocked', array('%d' => $datastream_id)), 'warning');
return;
}
if (isset($arr['delete']) && $arr['delete']) {
try {
$object[$datastream_id]->state = 'D';
} catch (Exception $e) {
drupal_set_message(t('Error deleting %s datastream from Islandora object %o %e', array('%s' => $datastream_id, '%o' => $object->id, '%e' => $e)), 'error');
return;
}
}
else {
try {
$object->purgeDatastream($datastream_id);
} catch (Exception $e) {
drupal_set_message(t('Error purging %s datastream from Islandora object %o %e', array('%s' => $datastream_id, '%o' => $object_id, '%e' => $e)), 'error');
return;
}
}
//notify modules post deletion
module_invoke_all('islandora_post_purge_datastream', $object, $datastream_id);
drupal_set_message(t('%d datastream sucessfully purged from Islandora object %o', array('%d' => $datastream_id, '%o' => $object->label)));
drupal_goto('islandora/object/' . $object->id);
}

668
includes/solution_packs.inc

@ -0,0 +1,668 @@
<?php
/**
* @file
* Admin and callback functions for solution pack management.
*/
/**
* Solution pack admin page callback.
*
* @return string
* The html repersentation of all solution pack forms for required objects.
*/
function islandora_solution_packs_admin() {
module_load_include('inc', 'islandora', 'includes/utilities');
if (!islandora_describe_repository()) {
islandora_display_repository_inaccessible_message();
return '';
}
$connection = islandora_get_tuque_connection();
drupal_add_css(drupal_get_path('module', 'islandora') . '/css/islandora.admin.css');
$output = '';
$enabled_solution_packs = module_invoke_all('islandora_required_objects', $connection);
foreach ($enabled_solution_packs as $solution_pack_module => $solution_pack_info) {
// @todo We should probably get the title of the solution pack from the
// systems table for consistency in the interface.
$solution_pack_name = $solution_pack_info['title'];
$objects = array_filter($solution_pack_info['objects']);
$form = drupal_get_form('islandora_solution_pack_form_' . $solution_pack_module, $solution_pack_module, $solution_pack_name, $objects);
$output .= drupal_render($form);
}
return $output;
}
/**
* A solution pack form for the given module.
*
* It lists all the given objects and their status, allowing the user to
* re-ingest them.
*
* @param array $form
* The Drupal form definition.
* @param array $form_state
* The Drupal form state.
* @param string $solution_pack_module
* The module which requires the given objects.
* @param string $solution_pack_name
* The name of the solution pack to display to the users.
* @param array $objects
* An array of NewFedoraObjects which describe the state in which objects
* should exist.
*
* @return array
* The Drupal form definition.
*/
function islandora_solution_pack_form(array $form, array &$form_state, $solution_pack_module, $solution_pack_name, $objects = array()) {
// The order is important in terms of severity of the status, where higher
// index indicates the status is more serious, this will be used to determine
// what messages get displayed to the user.
$ok_image = theme_image(array('path' => 'misc/watchdog-ok.png', 'attributes' => array()));
$warning_image = theme_image(array('path' => 'misc/watchdog-warning.png', 'attributes' => array()));
$status_info = array(
'up_to_date' => array(
'solution_pack' => t('All required objects are installed and up-to-date.'),
'image' => $ok_image,
'button' => t("Force reinstall objects"),
),
'modified_datastream' => array(
'solution_pack' => t('Some objects must be reinstalled. See objects list for details.'),
'image' => $warning_image,
'button' => t("Reinstall objects"),
),
'out_of_date' => array(
'solution_pack' => t('Some objects must be reinstalled. See objects list for details.'),
'image' => $warning_image,
'button' => t("Reinstall objects"),
),
'missing_datastream' => array(
'solution_pack' => t('Some objects must be reinstalled. See objects list for details.'),
'image' => $warning_image,
'button' => t("Reinstall objects"),
),
'missing' => array(
'solution_pack' => t('Some objects are missing and must be installed. See objects list for details.'),
'image' => $warning_image,
'button' => t("Install objects"),
),
);
$status_severities = array_keys($status_info);
$solution_pack_status_severity = array_search('up_to_date', $status_severities);
$table_rows = array();
foreach ($objects as $object) {
$object_status = islandora_check_object_status($object);
$object_status_info = $status_info[$object_status['status']];
$object_status_severity = array_search($object_status['status'], $status_severities);
// The solution pack status severity will be the highest severity of
// the objects.
$solution_pack_status_severity = max($solution_pack_status_severity, $object_status_severity);
$exists = $object_status['status'] != 'missing';
$label = $exists ? l($object->label, "islandora/object/{$object->id}") : $object->label;
$status_msg = "{$object_status_info['image']}&nbsp{$object_status['status_friendly']}";
$table_rows[] = array($label, $object->id, $status_msg);
}
$solution_pack_status = $status_severities[$solution_pack_status_severity];
$solution_pack_status_info = $status_info[$solution_pack_status];
return array(
'solution_pack' => array(
'#type' => 'fieldset',
'#collapsible' => FALSE,
'#collapsed' => FALSE,
'#attributes' => array('class' => array('islandora-solution-pack-fieldset')),
'solution_pack_module' => array(
'#type' => 'value',
'#value' => $solution_pack_module,
),
'solution_pack_name' => array(
'#type' => 'value',
'#value' => $solution_pack_name,
),
'objects' => array(
'#type' => 'value',
'#value' => $objects,
),
'solution_pack_label' => array(
'#markup' => $solution_pack_name,
'#prefix' => '<h3>',
'#suffix' => '</h3>',
),
'install_status' => array(
'#markup' => t('<strong>Object status:</strong> !image !status', array(
'!image' => $solution_pack_status_info['image'],
'!status' => $solution_pack_status_info['solution_pack'],
)),
'#prefix' => '<div class="islandora-solution-pack-install-status">',
'#suffix' => '</div>',
),
'table' => array(
'#type' => 'item',
'#markup' => theme('table', array(
'header' => array(t('Label'), t('PID'), t('Status')),
'rows' => $table_rows)),
),
'submit' => array(
'#type' => 'submit',
'#name' => $solution_pack_module,
'#value' => $solution_pack_status_info['button'],
'#attributes' => array('class' => array('islandora-solution-pack-submit')),
),
),
);
}
/**
* Submit handler for solution pack form.
*
* @param array $form
* The form submitted.
* @param array $form_state
* The state of the form submited.
*/
function islandora_solution_pack_form_submit(array $form, array &$form_state) {
$solution_pack_module = $form_state['values']['solution_pack_module'];
$objects = $form_state['values']['objects'];
$batch = array(
'title' => t('Installing / Updating solution pack objects'),
'file' => drupal_get_path('module', 'islandora') . '/includes/solution_packs.inc',
'operations' => array(),
);
foreach ($objects as $object) {
$batch['operations'][] = array('islandora_solution_pack_batch_operation_reingest_object', array($object));
}
batch_set($batch);
// Hook to let solution pack objects be modified.
// Not using module_invoke so solution packs can be expanded by other modules.
// @todo shouldn't we send the object list along as well?
module_invoke_all('islandora_postprocess_solution_pack', $solution_pack_module);
}
/**
* Batch operation to ingest/reingest required object(s).
*
* @param NewFedoraObject $object
* The object to ingest/reingest.
* @param array $context
* The context of this batch operation.
*/
function islandora_solution_pack_batch_operation_reingest_object(NewFedoraObject $object, array &$context) {
$deleted = FALSE;
$existing_object = islandora_object_load($object->id);
if ($existing_object) {
$deleted = islandora_delete_object($existing_object);
$purged = $deleted && $existing_object == NULL;
if (!$purged) {
$object_link = l($existing_object->label, "islandora/object/{$existing_object->id}");
drupal_set_message(t('Failed to purge existing object !object_link.', array(
'!object_link' => $object_link,
)), 'error');
// Failed to purge don't attempt to ingest.
return;
}
}
// Object was deleted or did not exist.
$pid = $object->id;
$label = $object->label;
$action = $deleted ? 'reinstalled' : 'installed';
$object_link = l($label, "islandora/object/{$pid}");
$object = islandora_add_object($object);
$msg = $object ? "Successfully $action !object_link." : "Failed to $action @label identified by @pid.";
$status = $object ? 'status' : 'error';
drupal_set_message(t($msg, array(
'@pid' => $pid,
'@label' => $label,
'!object_link' => $object_link,
)), $status);
}
/**
* Install the given solution pack.
*
* This is to be called from the solution pack's hook_install() and
* hook_uninstall() functions.
*
* It provides a convient way to have a solution pack's required objects
* ingested at install time.
*
* @param string $module
* The name of the module that is calling this function in its
* install/unistall hooks.
* @param string $op
* The operation to perform, either install or uninstall.
*
* @todo Implement hook_modules_installed/hook_modules_uninstalled instead of
* calling this function directly.
* @todo Remove the second parameter and have two seperate functions.
*/
function islandora_install_solution_pack($module, $op = 'install') {
if ($op == 'uninstall') {
islandora_uninstall_solution_pack($module);
return;
}
module_load_include('module', 'islandora', 'islandora');
module_load_include('inc', 'islandora', 'includes/utilities');
module_load_include('module', $module, $module);
$info_file = drupal_get_path('module', $module) . "/{$module}.info";
$info_array = drupal_parse_info_file($info_file);
$module_name = $info_array['name'];
$admin_link = l(t('Solution Pack admin'), 'admin/islandora/solution_packs');
$config_link = l(t('Islandora configuration'), 'admin/islandora/configure');
if (!islandora_describe_repository()) {
$msg = '@module: Did not install any objects. Could not connect to the ';
$msg .= 'repository. Please check the settings on the !config_link page ';
$msg .= 'and install the required objects manually on the !admin_link page.';
drupal_set_message(st($msg, array(
'@module' => $module_name,
'!config_link' => $config_link,
'@admin_link' => $admin_link,
)), 'error');
return;
}
$connection = islandora_get_tuque_connection();
$required_objects = module_invoke($module, 'islandora_required_objects', $connection);
$objects = $required_objects[$module]['objects'];
$status_messages = array(
'up_to_date' => 'The object already exists and is up-to-date',
'missing_datastream' => 'The object already exists but is missing a datastream. Please reinstall the object on the !admin_link page',
'out_of_date' => 'The object already exists but is out-of-date. Please update the object on the !admin_link page',
'modified_datastream' => 'The object already exists but datastreams are modified. Please reinstall the object on the !admin_link page',
);
foreach ($objects as $object) {
$query = $connection->api->a->findObjects('query', 'pid=' . $object->id);
$already_exists = !empty($query['results']);
$label = $object->label;
$object_link = l($label, "islandora/object/{$object->id}");
if ($already_exists) {
$object_status = islandora_check_object_status($object);
$status_msg = $status_messages[$object_status['status']];
drupal_set_message(st("@module: Did not install !object_link. $status_msg.", array(
'@module' => $module_name,
'!object_link' => $object_link,
'!admin_link' => $admin_link,
)), 'warning');
}
else {
$object = islandora_add_object($object);
if ($object) {
drupal_set_message(t('@module: Successfully installed. !object_link.', array(
'@module' => $module_name,
'!object_link' => $object_link,
)), 'status');
}
else {
drupal_set_message(t('@module: Failed to install. @label.', array(
'@module' => $module_name,
'@label' => $label,
)), 'warning');
}
}
}
}
/**
* Uninstalls the given solution pack.
*
* @param string $module
* The solution pack to uninstall.
*
* @todo Implement hook_modules_uninstalled instead of calling this function
* directly for each solution pack.
*/
function islandora_uninstall_solution_pack($module) {
module_load_include('module', 'islandora', 'islandora');
module_load_include('inc', 'islandora', 'includes/utilities');
module_load_include('module', $module, $module);
$config_link = l(t('Islandora configuration'), 'admin/islandora/configure');
$info_file = drupal_get_path('module', $module) . "/{$module}.info";
$info_array = drupal_parse_info_file($info_file);
$module_name = $info_array['name'];
if (!islandora_describe_repository()) {
$msg = '@module: Did not uninstall any objects. Could not connect to the ';
$msg .= 'repository. Please check the settings on the !config_link page ';
$msg .= 'and uninstall the required objects manually if necessary.';
drupal_set_message(st($msg, array(
'@module' => $module_name,
'!config_link' => $config_link,
)), 'error');
return;
}
$connection = islandora_get_tuque_connection();
$required_objects = module_invoke($module, 'islandora_required_objects', $connection);
$objects = $required_objects[$module]['objects'];
$filter = function($o) use($connection) {
$param = "pid={$o->id}";
$query = $connection->api->a->findObjects('query', $param);
return !empty($query['results']);
};
$existing_objects = array_filter($objects, $filter);
foreach ($existing_objects as $object) {
$msg = '@module: Did not remove !object_link. It may be used by other sites.';
$object_link = l($object->label, "islandora/object/{$object->id}");
drupal_set_message(st($msg, array(
'!object_link' => $object_link,
'@module' => $module_name,
)), 'warning');
}
}
/**
* Function to check the status of an object against an object model array.
*
* @param NewFedoraObject $object_definition
* A new fedora object that defines what the object should contain.
*
* @return string
* Returns one of the following values:
* up_to_date, missing, missing_datastream or out_of_date
* You can perform an appropriate action based on this value.
*
* @see islandora_solution_pack_form()
* @see islandora_install_solution_pack()
*/
function islandora_check_object_status(NewFedoraObject $object_definition) {
$existing_object = islandora_object_load($object_definition->id);
if (!$existing_object) {
return array('status' => 'missing', 'status_friendly' => t('Missing'));
}
$existing_datastreams = array_keys(iterator_to_array($existing_object));
$expected_datastreams = array_keys(iterator_to_array($object_definition));
$datastream_diff = array_diff($expected_datastreams, $existing_datastreams);
if (!empty($datastream_diff)) {
$status_friendly = format_plural(count($datastream_diff), 'Missing Datastream: %dsids.', 'Missing Datastreams: %dsids.', array('%dsids' => implode(', ', $datastream_diff)));
return array(
'status' => 'missing_datastream',
'status_friendly' => $status_friendly,
'data' => $datastream_diff,
);
}
$is_xml_datastream = function($ds) {
return $ds->mimetype == 'text/xml';
};
$xml_datastreams = array_filter(iterator_to_array($object_definition), $is_xml_datastream);
$out_of_date_datastreams = array();
foreach ($xml_datastreams as $ds) {
$installed_version = islandora_get_islandora_datastream_version($existing_object, $ds->id);
$available_version = islandora_get_islandora_datastream_version($object_definition, $ds->id);
if ($available_version > $installed_version) {
$out_of_date_datastreams[] = $ds->id;
}
}
if (count($out_of_date_datastreams)) {
$status_friendly = format_plural(count($out_of_date_datastreams), 'Datastream out of date: %dsids.', 'Datastreams out of date: %dsids.', array('%dsids' => implode(', ', $out_of_date_datastreams)));
return array(
'status' => 'out_of_date',
'status_friendly' => $status_friendly,
'data' => $out_of_date_datastreams,
);
}
// This is a pretty heavy function, but I'm not sure a better way. If we have
// performance trouble, we should maybe remove this.
$modified_datastreams = array();
foreach ($object_definition as $ds) {
if ($ds->mimetype == 'text/xml'
|| $ds->mimetype == 'application/rdf+xml'
|| $ds->mimetype == 'application/xml') {
// If the datastream is XML we use the domdocument C14N cannonicalization
// function to test if they are equal, because the strings likely won't
// be equal as Fedora does some XML mangling. In order for C14N to work
// we need to replace the info:fedora namespace, as C14N hates it.
// C14N also doesn't normalize whitespace at the end of lines and Fedora
// may add some whitespace on some lines.
$object_definition_dom = new DOMDocument();
$object_definition_dom->preserveWhiteSpace = FALSE;
$object_definition_dom->loadXML(str_replace('info:', 'http://', $ds->content));
$object_actual_dom = new DOMDocument();
$object_actual_dom->preserveWhiteSpace = FALSE;
$object_actual_dom->loadXML(str_replace('info:', 'http://', $existing_object[$ds->id]->content));
// Fedora changes the xml structure so we need to cannonize it.
if ($object_actual_dom->C14N() != $object_definition_dom->C14N()) {
$modified_datastreams[] = $ds->id;
}
}
else {
$object_definition_hash = md5($ds->content);
$object_actual_hash = md5($existing_object[$ds->id]->content);
if ($object_definition_hash != $object_actual_hash) {
$modified_datastreams[] = $ds->id;;
}
}
}
if (count($modified_datastreams)) {
$status_friendly = format_plural(count($modified_datastreams), 'Modified Datastream: %dsids.', 'Modified Datastreams: %dsids.', array('%dsids' => implode(', ', $modified_datastreams)));
return array(
'status' => 'modified_datastream',
'data' => $modified_datastreams,
'status_friendly' => $status_friendly,
);
}
// If not anything else we can assume its up to date.
return array('status' => 'up_to_date', 'status_friendly' => t('Up-to-date'));
}
/**
* @defgroup viewer-functions
* @{
* Helper functions to include viewers for solution packs.
*/
/**
* A form construct to create a viewer selection table.
*
* The list of selectable viewers is limited by the $mimetype and the $model
* parameters. When neither are given all defined viewers are listed. If only
* $mimetype is given only viewers that support that mimetype will be listed,
* the same goes for the $model parameter. If both are given, than any viewer
* that supports either the give $mimetype or $model will be listed.
*
* @param string $variable_id
* The ID of the Drupal variable to save the viewer settings in
* @param string $mimetype
* The table will be populated with viewers supporting this mimetype
* @param string $model
* The table will be populated with viewers supporting this content model
*
* @return array
* A form api array which defines a themed table to select a viewer.
*/
function islandora_viewers_form($variable_id = NULL, $mimetype = NULL, $model = NULL) {
$form = array();
$viewers = islandora_get_viewers($mimetype, $model);
if (!empty($viewers)) {
$no_viewer = array();
$no_viewer['none'] = array(
'label' => t('None'),
'description' => t("Don't use a viewer for this solution pack."),
);
$viewers = array_merge_recursive($no_viewer, $viewers);
}
$viewers_config = variable_get($variable_id, array());
$form['viewers'] = array(
'#type' => 'fieldset',
'#title' => t('Viewers'),
'#collapsible' => FALSE,
'#collapsed' => FALSE,
);
if (!empty($viewers)) {
$form['viewers'][$variable_id] = array(
'#type' => 'item',
'#title' => t('Select a viewer'),
'#description' => t('Preferred viewer for your solution pack. These may be provided by third-party modules.'),
'#tree' => TRUE,
'#theme' => 'islandora_viewers_table',
);
foreach ($viewers as $name => $profile) {
$options[$name] = '';
$form['viewers'][$variable_id]['name'][$name] = array(
'#type' => 'hidden',
'#value' => $name,
);
$form['viewers'][$variable_id]['label'][$name] = array(
'#type' => 'item',
'#markup' => $profile['label'],
);
$form['viewers'][$variable_id]['description'][$name] = array(
'#type' => 'item',
'#markup' => $profile['description'],
);
$form['viewers'][$variable_id]['configuration'][$name] = array(
'#type' => 'item',
'#markup' => (isset($profile['configuration']) AND $profile['configuration'] != '') ? l(t('configure'), $profile['configuration']) : '',
);
}
$form['viewers'][$variable_id]['default'] = array(
'#type' => 'radios',
'#options' => isset($options) ? $options : array(),
'#default_value' => !empty($viewers_config) ? $viewers_config['default'] : 'none',
);
}
else {
$form['viewers'][$variable_id . '_no_viewers'] = array(
'#markup' => t('No viewers detected.'),
);
variable_del($variable_id);
}
return $form;
}
/**
* Returns all defined viewers.
*
* The list of selectable viewers is limited by the $mimetype and the
* $content_model parameters. When neither are given all defined viewers are
* listed. If only $mimetype is given only viewers that support that mimetype
* will be listed, the same goes for the $content_model parameter. If both are
* given, than any viewer that supports either the give $mimetype or $model will
* be listed.
*
* @param string $mimetype
* Specify a mimetype to return only viewers that support this certain
* mimetype.
* @param string $content_model
* Specify a content model to return only viewers that support the content
* model.
*
* @return array
* Viewer definitions, or FALSE if none are found.
*/
function islandora_get_viewers($mimetype = NULL, $content_model = NULL) {
$viewers = array();
$defined_viewers = module_invoke_all('islandora_viewer_info');
// Filter viewers by MIME type.
foreach ($defined_viewers as $key => $value) {
$value['mimetype'] = isset($value['mimetype']) ? $value['mimetype'] : array();
$value['model'] = isset($value['model']) ? $value['model'] : array();
if (in_array($mimetype, $value['mimetype']) OR in_array($content_model, $value['model'])) {
$viewers[$key] = $value;
}
}
if (!empty($viewers)) {
return $viewers;
}
return FALSE;
}
/**
* Implements theme_hook().
*/
function theme_islandora_viewers_table($variables) {
$form = $variables['form'];
$rows = array();
foreach ($form['name'] as $key => $element) {
if (is_array($element) && element_child($key)) {
$row = array();
$row[] = array('data' => drupal_render($form['default'][$key]));
$row[] = array('data' => drupal_render($form['label'][$key]));
$row[] = array('data' => drupal_render($form['description'][$key]));
$row[] = array('data' => drupal_render($form['configuration'][$key]));
$rows[] = array('data' => $row);
}
}
$header = array();
$header[] = array('data' => t('Default'));
$header[] = array('data' => t('Label'));
$header[] = array('data' => t('Description'));
$header[] = array('data' => t('Configuration'));
$output = '';
$output .= theme('table', array(
'header' => $header,
'rows' => $rows,
'attributes' => array('id' => 'islandora-viewers-table'),
));
$output .= drupal_render_children($form);
return $output;
}
/**
* Gather information and return a rendered viewer.
*
* @param array/string $params
* Array or string with data the module needs in order to render a full viewer
* @param string $variable_id
* The id of the Drupal variable the viewer settings are saved in
* @param FedoraObject $fedora_object
* The tuque object representing the fedora object being displayed
*
* @return string
* The callback to the viewer module. Returns a rendered viewer. Returns FALSE
* if no viewer is set.
*/
function islandora_get_viewer($params = NULL, $variable_id = NULL, $fedora_object = NULL) {
$settings = variable_get($variable_id, array());
if (!empty($settings) AND $settings['default'] !== 'none') {
$viewer_id = islandora_get_viewer_id($variable_id);
if ($viewer_id AND $params !== NULL) {
$callback = islandora_get_viewer_callback($viewer_id);
return $callback($params, $fedora_object);
}
}
return FALSE;
}
/**
* Get id of the enabled viewer.
*
* @param string $variable_id
* The ID of the Drupal variable the viewer settings are saved in
*
* @return string
* The enabled viewer id. Returns FALSE if no viewer config is set.
*/
function islandora_get_viewer_id($variable_id) {
$viewers_config = variable_get($variable_id, array());
if (!empty($viewers_config)) {
return $viewers_config['default'];
}
return FALSE;
}
/**
* Get callback function for a viewer.
*
* @param string $viewer_id
* The ID of a viewer.
*
* @return string
* The callback function as a string as defined by the viewer.
*/
function islandora_get_viewer_callback($viewer_id = NULL) {
if ($viewer_id !== NULL) {
$viewers = module_invoke_all('islandora_viewer_info');
if (isset($viewers[$viewer_id]['callback'])) {
return $viewers[$viewer_id]['callback'];
}
}
return FALSE;
}
/**
* @} End of "defgroup viewer-functions".
*/

54
includes/tuque.inc

@ -1,8 +1,13 @@
<?php
/**
* @file
* This file contains a class to include the Tuque php library.
*/
$islandora_module_path = drupal_get_path('module', 'islandora');
//do this until we expost these in a module or library
// Do this until we expose these in a module or library.
@include_once 'sites/all/libraries/tuque/Datastream.php';
@include_once 'sites/all/libraries/tuque/FedoraApi.php';
@include_once 'sites/all/libraries/tuque/FedoraApiSerializer.php';
@ -53,15 +58,24 @@ class IslandoraTuque {
*/
public $repository = NULL;
function __construct($user = NULL, $url = NULL) {
if(!isset($user)) {
/**
* Constructor.
*
* @param array $user
* A Drupal user.
* @param string $url
* The url to the fedora instance.
*/
public function __construct($user = NULL, $url = NULL) {
if (!isset($user)) {
global $user;
}
if(!isset($user) || $user->uid == 0){
if ($user->uid == 0) {
$user_string = 'anonymous';
$pass_string = 'anonymous';
} else {
}
else {
$user_string = $user->name;
$pass_string = $user->pass;
}
@ -70,24 +84,32 @@ class IslandoraTuque {
$url = variable_get('islandora_base_url', 'http://localhost:8080/fedora');
}
if(self::exists()) {
$this->connection = new RepositoryConnection($url, $user_string, $pass_string);
if (self::exists()) {
$this->connection = new IslandoraRepositoryConnection($url, $user_string, $pass_string);
$this->connection->reuseConnection = TRUE;
$this->api = new FedoraApi($this->connection);
$this->cache = new SimpleCache();
$this->repository = new FedoraRepository($this->api, $this->cache);
$this->api = new IslandoraFedoraApi($this->connection);
$this->cache = new IslandoraSimpleCache();
$this->repository = new IslandoraFedoraRepository($this->api, $this->cache);
}
}
static function exists() {
/**
* Checks if the Connection class exists.
*
* @returns bool
* TRUE if the Connection class exists FALSE otherwise.
*/
public static function exists() {
return class_exists('RepositoryConnection');
}
static function getError() {
/**
* Displays and error for use when Tuque is not installed.
*/
public static function getError() {
$islandora_doc_link = l(t('Islandora documentation'), 'https://wiki.duraspace.org/display/ISLANDORA/Islandora');
$tuque_link = l(t('Tuque Fedora API'), 'http://github.com/islandora/tuque');
$message = t('Islandora requires the !tuque_url. Please install in /sites/all/libraries/tuque before continuing. See the !islandora_url.', array( '!tuque_url' => $tuque_link, '!islandora_url' => $islandora_doc_link));
drupal_set_message($message, 'error', FALSE);
$message = t('Islandora requires the !tuque_url. Please install in /sites/all/libraries/tuque before continuing. See the !islandora_url.', array('!tuque_url' => $tuque_link, '!islandora_url' => $islandora_doc_link));
drupal_set_message(filter_xss($message), 'error', FALSE);
}
}

360
includes/tuque_wrapper.inc

@ -0,0 +1,360 @@
<?php
/**
* @file
* Wrapper around the tuque library, allows for autoloading of Islandora Tuque
* Objects.
*
* @todo Overload functions and apply pre/post hooks.
*/
$islandora_module_path = drupal_get_path('module', 'islandora');
// @todo this until we expost these in a module or library
@include_once 'sites/all/libraries/tuque/Datastream.php';
@include_once 'sites/all/libraries/tuque/FedoraApi.php';
@include_once 'sites/all/libraries/tuque/FedoraApiSerializer.php';
@include_once 'sites/all/libraries/tuque/Object.php';
@include_once 'sites/all/libraries/tuque/RepositoryConnection.php';
@include_once 'sites/all/libraries/tuque/Cache.php';
@include_once 'sites/all/libraries/tuque/RepositoryException.php';
@include_once 'sites/all/libraries/tuque/Repository.php';
@include_once 'sites/all/libraries/tuque/FedoraRelationships.php';
@include_once "$islandora_module_path/libraries/tuque/Datastream.php";
@include_once "$islandora_module_path/libraries/tuque/FedoraApi.php";
@include_once "$islandora_module_path/libraries/tuque/FedoraApiSerializer.php";
@include_once "$islandora_module_path/libraries/tuque/Object.php";
@include_once "$islandora_module_path/libraries/tuque/RepositoryConnection.php";
@include_once "$islandora_module_path/libraries/tuque/Cache.php";
@include_once "$islandora_module_path/libraries/tuque/RepositoryException.php";
@include_once "$islandora_module_path/libraries/tuque/Repository.php";
@include_once "$islandora_module_path/libraries/tuque/FedoraRelationships.php";
/**
* Allow modules to alter an object before a mutable event occurs.
*/
function islandora_alter_object(AbstractFedoraObject $object, array &$context) {
$types = array('islandora_object');
foreach ($object->models as $model) {
$types[] = "{$model}_islandora_object";
}
drupal_alter($types, $object, $context);
}
/**
* Allow modules to alter a datastream before a mutable event occurs.
*/
function islandora_alter_datastream(AbstractFedoraObject $object, AbstractDatastream $datastream, array &$context) {
$types = array('islandora_datastream');
foreach ($object->models as $model) {
$types[] = "{$model}_{$datastream->id}_islandora_datastream";
}
drupal_alter($types, $object, $datastream, $context);
}
/**
* Constructs a list of hooks from the given paramenters and invokes them.
*/
function islandora_invoke_object_hooks($hook, array $models) {
module_load_include('inc', 'islandora', 'includes/utilities');
return islandora_invoke_hook_list($hook, $models, array_slice(func_get_args(), 2));
}
/**
* Constructs a list of hooks from the given paramenters and invokes them.
*/
function islandora_invoke_datastream_hooks($hook, array $models, $dsid) {
module_load_include('inc', 'islandora', 'includes/utilities');
$refinements = array();
foreach ($models as $model) {
$refinements[] = "{$model}_{$dsid}";
}
return islandora_invoke_hook_list($hook, $refinements, array_slice(func_get_args(), 3));
}
class IslandoraFedoraRepository extends FedoraRepository {
protected $queryClass = 'IslandoraRepositoryQuery';
protected $newObjectClass = 'IslandoraNewFedoraObject';
protected $objectClass = 'IslandoraFedoraObject';
/**
* Ingest the given object.
*
* @see FedoraRepository::ingestObject()
*/
public function ingestObject(NewFedoraObject &$object) {
$context = array(
'action' => 'ingest',
'block' => FALSE,
);
islandora_alter_object($object, $context);
try {
if ($context['block']) {
throw new Exception('Ingest Object was blocked.');
}
$ret = parent::ingestObject($object);
islandora_invoke_object_hooks(ISLANDORA_OBJECT_INGESTED_HOOK, $object->models, $object);
// Call the ingested datastream hooks for NewFedoraObject's after the
// object had been ingested.
foreach ($object as $dsid => $datastream) {
islandora_invoke_datastream_hooks(ISLANDORA_DATASTREAM_INGESTED_HOOK, $object->models, $dsid, $object, $datastream);
}
return $ret;
}
catch (Exception $e) {
watchdog('islandora', 'Failed to ingest object: @pid</br>code: @code<br/>message: @msg', array(
'@pid' => $object->id,
'@code' => $e->getCode(),
'@msg' => $e->getMessage()), WATCHDOG_ERROR);
throw $e;
}
}
}
class IslandoraRepositoryQuery extends RepositoryQuery {}
class IslandoraNewFedoraObject extends NewFedoraObject {
protected $newFedoraDatastreamClass = 'IslandoraNewFedoraDatastream';
protected $fedoraDatastreamClass = 'IslandoraFedoraDatastream';
protected $fedoraRelsExtClass = 'IslandoraFedoraRelsExt';
}
class IslandoraFedoraObject extends FedoraObject {
protected $newFedoraDatastreamClass = 'IslandoraNewFedoraDatastream';
protected $fedoraDatastreamClass = 'IslandoraFedoraDatastream';
protected $fedoraRelsExtClass = 'IslandoraFedoraRelsExt';
/**
* Ingest the given datastream.
*
* @see FedoraObject::ingestDatastream()
*/
public function ingestDatastream(&$datastream) {
$object = $datastream->parent;
$context = array(
'action' => 'ingest',
'block' => FALSE,
);
islandora_alter_datastream($object, $datastream, $context);
try {
if ($context['block']) {
throw new Exception('Ingest Datastream was blocked.');
}
$ret = parent::ingestDatastream($datastream);
islandora_invoke_datastream_hooks(ISLANDORA_DATASTREAM_INGESTED_HOOK, $object->models, $datastream->id, $object, $datastream);
return $ret;
}
catch (Exception $e) {
watchdog('islandora', 'Failed to ingest object: @pid</br>code: @code<br/>message: @msg', array(
'@pid' => $object->id,
'@dsid' => $datastream->id,
'@code' => $e->getCode(),
'@msg' => $e->getMessage()), WATCHDOG_ERROR);
throw $e;
}
}
}
class IslandoraRepositoryConnection extends RepositoryConnection {}
class IslandoraFedoraApi extends FedoraApi {
/**
* Instantiate a IslandoraFedoraApi object.
*
* @see FedoraApi::__construct()
*/
public function __construct(IslandoraRepositoryConnection $connection, FedoraApiSerializer $serializer = NULL) {
if (!$serializer) {
$serializer = new FedoraApiSerializer();
}
$this->a = new FedoraApiA($connection, $serializer);
$this->m = new IslandoraFedoraApiM($connection, $serializer);
$this->connection = $connection;
}
}
class IslandoraFedoraApiM extends FedoraApiM {
/**
* Update a datastream.
*
* Either changing its metadata, updaing the datastream contents or both.
*
* @throws Exception
* If the modify datastream request was block by some module.
*
* @see FedoraApiM::modifyDatastream
*/
public function modifyDatastream($pid, $dsid, $params = array()) {
$object = islandora_object_load($pid);
$datastream = $object[$dsid];
$context = array(
'action' => 'modify',
'block' => FALSE,
'params' => $params,
);
islandora_alter_datastream($object, $datastream, $context);
try {
if ($context['block']) {
throw new Exception('Modify Datastream was blocked.');
}
$ret = parent::modifyDatastream($pid, $dsid, $params);
islandora_invoke_datastream_hooks(ISLANDORA_DATASTREAM_MODIFIED_HOOK, $object->models, $dsid, $object, $datastream);
if (isset($params['dsState']) && $params['dsState'] == 'D') {
islandora_invoke_datastream_hooks(ISLANDORA_DATASTREAM_PURGED_HOOK, $object->models, $dsid, $object, $dsid);
}
return $ret;
}
catch(Exception $e) {
watchdog('islandora', 'Failed to modify datastream @dsid from @pid</br>code: @code<br/>message: @msg', array(
'@pid' => $pid,
'@dsid' => $dsid,
'@code' => $e->getCode(),
'@msg' => $e->getMessage()), WATCHDOG_ERROR);
throw $e;
}
}
/**
* Update Fedora Object parameters.
*
* @see FedoraApiM::modifyObject
*/
public function modifyObject($pid, $params = NULL) {
$object = islandora_object_load($pid);
$context = array(
'action' => 'modify',
'block' => FALSE,
'params' => $params,
);
islandora_alter_object($object, $context);
try {
if ($context['block']) {
throw new Exception('Modify Object was blocked.');
}
$ret = parent::modifyObject($pid, $params);
islandora_invoke_object_hooks(ISLANDORA_OBJECT_MODIFIED_HOOK, $object->models, $object);
if (isset($params['state']) && $params['state'] == 'D') {
islandora_invoke_object_hooks(ISLANDORA_OBJECT_PURGED_HOOK, $object->models, $object->id);
}
return $ret;
}
catch(Exception $e) {
watchdog('islandora', 'Failed to modify object: @pid</br>code: @code<br/>message: @msg', array(
'@pid' => $pid,
'@code' => $e->getCode(),
'@msg' => $e->getMessage()), WATCHDOG_ERROR);
throw $e;
}
}
/**
* Purge a datastream from from Fedora.
*
* @see FedoraApiM::purgeDatastream
*/
public function purgeDatastream($pid, $dsid, $params = array()) {
$object = islandora_object_load($pid);
$context = array(
'action' => 'purge',
'purge' => TRUE,
'delete' => FALSE,
'block' => FALSE,
);
islandora_alter_datastream($object, $object[$dsid], $context);
try {
$action = $context['block'] ? 'block' : FALSE;
$action = (!$action && $context['delete']) ? 'delete' : $action;
$action = !$action ? 'purge' : $action;
switch ($action) {
case 'block':
throw new Exception('Purge Datastream was blocked.');
break;
case 'delete':
$object[$dsid]->state = 'D';
return array();
default:
$ret = parent::purgeDatastream($pid, $dsid, $params);
islandora_invoke_datastream_hooks(ISLANDORA_DATASTREAM_PURGED_HOOK, $object->models, $dsid, $object, $dsid);
return $ret;
}
}
catch(Exception $e) {
watchdog('islandora', 'Failed to purge datastream @dsid from @pid</br>code: @code<br/>message: @msg', array(
'@pid' => $pid,
'@dsid' => $dsid,
'@code' => $e->getCode(),
'@msg' => $e->getMessage()), WATCHDOG_ERROR);
throw $e;
}
}
/**
* Purge an object.
*
* @see FedoraApiM::purgeObject
*/
public function purgeObject($pid, $log_message = NULL) {
$object = islandora_object_load($pid);
$context = array(
'action' => 'purge',
'purge' => TRUE,
'delete' => FALSE,
'block' => FALSE,
);
islandora_alter_object($object, $context);
try {
$action = $context['block'] ? 'block' : FALSE;
$action = (!$action && $context['delete']) ? 'delete' : $action;
$action = !$action ? 'purge' : $action;
$models = $object->models;
switch ($action) {
case 'block':
throw new Exception('Purge object was blocked.');
break;
case 'delete':
$object->state = 'D';
return '';
default:
$ret = parent::purgeObject($pid, $log_message);
islandora_invoke_object_hooks(ISLANDORA_OBJECT_PURGED_HOOK, $models, $pid);
return $ret;
}
}
catch(Exception $e) {
watchdog('islandora', 'Failed to purge object @pid</br>code: @code<br/>message: @msg', array(
'@pid' => $pid,
'@code' => $e->getCode(),
'@msg' => $e->getMessage()), WATCHDOG_ERROR);
throw $e;
}
}
}
class IslandoraSimpleCache extends SimpleCache {}
class IslandoraNewFedoraDatastream extends NewFedoraDatastream {
protected $fedoraRelsIntClass = 'IslandoraFedoraRelsInt';
protected $fedoraDatastreamVersionClass = 'IslandoraFedoraDatastreamVersion';
}
class IslandoraFedoraDatastream extends FedoraDatastream {
protected $fedoraRelsIntClass = 'IslandoraFedoraRelsInt';
protected $fedoraDatastreamVersionClass = 'IslandoraFedoraDatastreamVersion';
}
class IslandoraFedoraDatastreamVersion extends FedoraDatastreamVersion {
protected $fedoraRelsIntClass = 'IslandoraFedoraRelsInt';
protected $fedoraDatastreamVersionClass = 'IslandoraFedoraDatastreamVersion';
}
class IslandoraFedoraRelsExt extends FedoraRelsExt {}
class IslandoraFedoraRelsInt extends FedoraRelsInt {}

597
includes/utilities.inc

@ -1,98 +1,579 @@
<?php
/**
* Convert bytes to human readable format
* @file
* Utility functions.
*
* @param integer bytes Size in bytes to convert
* @return string
* @todo this file should be broken out into other files.
*/
function islandora_convert_bytes_to_human_readable($bytes, $precision = 2)
{
$kilobyte = 1024;
$megabyte = $kilobyte * 1024;
$gigabyte = $megabyte * 1024;
$terabyte = $gigabyte * 1024;
if (($bytes >= 0) && ($bytes < $kilobyte)) {
return $bytes . ' B';
} elseif (($bytes >= $kilobyte) && ($bytes < $megabyte)) {
return round($bytes / $kilobyte, $precision) . ' KB';
} elseif (($bytes >= $megabyte) && ($bytes < $gigabyte)) {
return round($bytes / $megabyte, $precision) . ' MB';
} elseif (($bytes >= $gigabyte) && ($bytes < $terabyte)) {
return round($bytes / $gigabyte, $precision) . ' GB';
/**
* Convert bytes to human readable format.
*
* XXX: Shouldn't Drupal's format_size() be preferred?
*
* @param int $bytes
* Size in bytes to convert
*
* @return string
* Human readable size.
*/
function islandora_convert_bytes_to_human_readable($bytes, $precision = 2) {
$kilobyte = 1024;
$megabyte = $kilobyte * 1024;
$gigabyte = $megabyte * 1024;
$terabyte = $gigabyte * 1024;
} elseif ($bytes >= $terabyte) {
return round($bytes / $terabyte, $precision) . ' TB';
} else {
return $bytes . ' B';
}
if (($bytes >= 0) && ($bytes < $kilobyte)) {
return $bytes . ' B';
}
elseif (($bytes >= $kilobyte) && ($bytes < $megabyte)) {
return round($bytes / $kilobyte, $precision) . ' KB';
}
elseif (($bytes >= $megabyte) && ($bytes < $gigabyte)) {
return round($bytes / $megabyte, $precision) . ' MB';
}
elseif (($bytes >= $gigabyte) && ($bytes < $terabyte)) {
return round($bytes / $gigabyte, $precision) . ' GB';
}
elseif ($bytes >= $terabyte) {
return round($bytes / $terabyte, $precision) . ' TB';
}
else {
return $bytes . ' B';
}
}
/**
* Creates a label for control group symbols.
*/
function islandora_control_group_to_human_readable($control_group) {
switch($control_group) {
switch ($control_group) {
case 'M':
return '<b>M</b>anaged';
case 'X':
return 'Inline <b>X</b>ML';
case 'R':
return '<b>R</b>edirect';
case 'E':
return '<b>E</b>xternally Referenced';
default:
return $control_group;
}
}
/**
* valid pid ??
* @param type $pid
* @return boolean
* Checks if the given pid is valid.
*
* @param string $pid
* The object id to check.
*
* @return bool
* TRUE if valid, FALSE otherwise.
*/
function islandora_validate_pid($pid) {
$valid = FALSE;
if (strlen(trim($pid)) <= 64 && preg_match('/^([A-Za-z0-9]|-|\.)+:(([A-Za-z0-9])|-|\.|~|_|(%[0-9A-F]{2}))+$/', trim($pid))) {
$valid = TRUE;
function islandora_is_valid_pid($pid) {
return drupal_strlen(trim($pid)) <= 64 && preg_match('/^([A-Za-z0-9]|-|\.)+:(([A-Za-z0-9])|-|\.|~|_|(%[0-9A-F]{2}))+$/', trim($pid));
}
/**
* Checks if the given datastream id is valid.
*
* @param string $dsid
* The datastream id to check.
*
* @return bool
* TRUE if valid, FALSE otherwise.
*/
function islandora_is_valid_dsid($dsid) {
return drupal_strlen(trim($dsid)) <= 64 && preg_match('/^[a-zA-Z0-9\_\-\.]+$/', trim($dsid));
}
/**
* Helper function to describe a Fedora repository.
*
* Can be used to check if Fedora is available.
*
* @param string $url
* A url to a Fedora repository, if NULL the default is used.
*
* @return array
* Returns an array describing the repository. Returns FALSE if Fedora is down
* or if the url is incorrect.
*/
function islandora_describe_repository($url = NULL) {
$url = isset($url) ? $url : variable_get('islandora_base_url', 'http://localhost:8080/fedora');
$connection = islandora_get_tuque_connection();
if ($connection) {
try {
$info = $connection->api->a->describeRepository();
return $info;
}
catch (RepositoryException $e) {
return FALSE;
}
}
return FALSE;
}
return $valid;
/**
* Build and invoke a list of hooks by combining the given hook and refinements.
*
* The given hook will be called as MODULE_HOOK, and for each hook refinement
* as MODULE_REFINEMENT_HOOK. Any additional arguments passed to this function
* will be passed as arguments to module_invoke_all().
*
* @see islandora_build_hook_list()
*
* @param string $hook
* A hook to call.
* @param array $refinements
* An array of strings, that will be escaped and concatinated with the given
* hook. This will most likely be PIDs/DSIDs/Labels etc. We often refine our
* hooks using an objects model.
* @param array $args
* Any arguments to pass onto module_invoke_all().
*
* @return array
* The merged results from all the hooks.
*/
function islandora_invoke_hook_list($hook, array $refinements, array $args) {
$return = array();
foreach (islandora_build_hook_list($hook, $refinements) as $hook) {
array_unshift($args, $hook);
$result = call_user_func_array('module_invoke_all', $args);
$return = array_merge_recursive($return, $result);
array_shift($args);
}
return $return;
}
/**
* Valid Dsid ??
* @param type $dsid
* @return boolean
* Build a list of all the hooks to call.
*
* Concatenates each hook $refinement (escaped) to the hook name, for calling
* with module_invoke_all().
*
* Any non-valid PHP function characters in the given refinements are
* converted to "_" characters.
*
* @param string $hook
* The base hook to concatenate.
* @param array $refinements
* An array of strings, that will be escaped and concatinated with the given
* hook. This will most likely be PIDs/DSIDs/Labels etc. We often refine our
* hooks using an objects model.
*
* @return array
* An array with each refinement escaped and concatenated with the base hook
* name, in addition to the base hook name.
*/
function islandora_validate_dsid($dsid) {
$valid = FALSE;
if (strlen(trim($dsid)) <= 64 && preg_match('/^[a-zA-Z0-9\_\-\.]+$/', trim($dsid))) {
$valid = TRUE;
function islandora_build_hook_list($hook, $refinements = array()) {
$refinements = array_unique($refinements);
$hooks = array($hook);
foreach ($refinements as $refinement) {
$refinement = preg_replace('/[^a-zA-Z0-9_]/', '_', $refinement);
$hooks[] = "{$refinement}_{$hook}";
}
return $hooks;
}
return $valid;
/**
* Escape a Fedora PID to be valid inside of a PHP function name.
*
* Originally intended to allow inclusion of a PID in a module_invoke_all()
* call.
*/
function islandora_escape_pid_for_function($pid) {
// Apparently, case doesn't matter for function calls in PHP, so let's not
// really worry about changing the case.
return str_replace(
// Any PID characters which are not valid in the name of a PHP function.
array(
':',
'-',
),
'_',
$pid
);
}
/* Helper function to describe a Fedora repository.
*
* Can be used to check if Fedora is available.
*
* @param $url
* A url to a Fedora repository.
* @return
* Returns an array describing the repository. Returns FALSE if Fedora is down
* or if the url is incorrect.
/**
* Gets the namespace of the given id.
*
* @param string $id
* Either a PID or namespace to check for accessibility. Any string like those
* below are fine.
*
* @code
* 'islandora',
* 'islandora:',
* 'islandora:1234',
* @endcode
*
* @return string
* The namespace portion of the given string.
*/
function islandora_get_namespace($id) {
$matches = array();
preg_match('/^([^:]*)/', $id, $matches);
return $matches[0];
}
/**
* Checks the given namespace/PID is/has an accessible namespace.
*
* Accessible is defined by the "islandora_pids_allowed" variable.
*
* @param string $id
* Either a PID or namespace to check for accessibility. Any string like those
* below are fine.
*
* @code
* 'islandora',
* 'islandora:',
* 'islandora:1234',
* @endcode
*
* @return bool
* TRUE if accessible, FALSE otherwise.
*/
function islandora_describe_repository($url) {
$connection = new IslandoraTuque(NULL, $url);
function islandora_namespace_accessible($id) {
if (variable_get('islandora_namespace_restriction_enforced', FALSE)) {
$namespace = islandora_get_namespace($id) . ':';
$allowed_namespaces = explode(" ", variable_get('islandora_pids_allowed', 'default: demo: changeme: islandora: ilives: islandora-book: books: newspapers: '));
return in_array($namespace, $allowed_namespaces);
}
return TRUE;
}
/**
* Gets any objects that the given object has a parent relationship with.
*
* Parent relationships are defined as (isMemberOf, isMemberOfCollection).
*
* This function gets its info from the RELS-EXT directly rather than through an
* risearch.
*
* @param FedoraObject $object
* The object whose parents will be returned.
*
* @return array
* An array of FedoraObject's that the given object has a
* (isMemberOf, isMemberOfCollection) relationship with.
*/
function islandora_get_parents_from_rels_ext(FedoraObject $object) {
try {
$info = $connection->api->a->describeRepository();
return $info;
$collections = array_merge(
$object->relationships->get(FEDORA_RELS_EXT_URI, 'isMemberOfCollection'),
$object->relationships->get(FEDORA_RELS_EXT_URI, 'isMemberOf'));
}
catch (RepositoryException $e) {
return FALSE;
// @todo some logging would be nice, not sure what this throws.
return array();
}
$map = function($o) {
return islandora_object_load($o['object']['value']);
};
$collections = array_map($map, $collections);
return array_filter($collections);
}
/**
* Gets the datastreams requirments that are missing.
*
* @param FedoraObject $object
* The object which models will be used to determine what datastreams it
* should have.
*
* @return array
* The DS-COMPOSITE-MODEL defined datastreams that are required for the given
* object, but not already present.
*/
function islandora_get_missing_datastreams_requirements(FedoraObject $object) {
module_load_include('inc', 'islandora', 'includes/utilities');
$datastreams = islandora_get_datastreams_requirements($object);
foreach ($datastreams as $dsid => $requirements) {
if (isset($object[$dsid])) {
unset($datastreams[$dsid]);
}
}
}
return $datastreams;
}
/**
* Gets the required datastreams for the given object.
*
* Checks the object's content model's for which datastream are expected to be
* used with this object, as defined by the DS-COMPOSITE-MODEL datastreams.
*
* For duplicate datastreams in the models, the first model defines the
* datastreams attributes regardless of what other models define.
* This should be undefined behavior according to the documentation.
*
* @link https://wiki.duraspace.org/display/FEDORA34/Fedora+Digital+Object+Model#FedoraDigitalObjectModel-ContentModelObjectCMODEL @endlink
*
* @see islandora_get_required_datastreams_from_content_model()
*
* @param FedoraObject $object
* The object which models will be used to determine what datastreams it
* should have.
*
* @return array
* The DS-COMPOSITE-MODEL defined datastreams that are required for the given
* object.
*/
function islandora_get_datastreams_requirements(FedoraObject $object) {
return islandora_get_datastreams_requirements_from_models($object->models);
}
/**
* Get the list of which datastreams are valid in the given set of models.
*
* @param array $models
* An array of content models PIDs from which to parse the DS-COMPOSITE-MODEL
* stream.
*
* @return array
* An associative array of associative arrays, merged from calls to
* islandora_get_datastreams_requirements_from_content_model().
*/
function islandora_get_datastreams_requirements_from_models(array $models) {
$dsids = array();
foreach ($models as $model_pid) {
$model = islandora_object_load($model_pid);
if (isset($model) && $model) {
$dsids += islandora_get_datastreams_requirements_from_content_model($model);
}
}
// The AUDIT Datastream can not really be added, so it can't really be
// missing.
unset($dsids['AUDIT']);
return $dsids;
}
/**
* Checks the given content model for which datastreams are required.
*
* As defined by it's DS-COMPOSITE-MODEL datastream.
*
* @todo Add support for fetching the schema information.
*
* @param FedoraObject $object
* The content model whose DS-COMPOSITE-MODEL datastream will be used to
* determine what datastreams are required.
*
* @return array
* The DS-COMPOSITE-MODEL defined datastreams that are required for the given
* object.
*
* @code
* array(
* 'DC' => array(
* 'id' => 'DC',
* 'mime' => 'text/xml',
* 'optional' => FALSE,
* )
* )
* @endcode
*/
function islandora_get_datastreams_requirements_from_content_model(FedoraObject $object) {
if (empty($object[DS_COMP_STREAM])) {
return array();
}
$xml = new SimpleXMLElement($object[DS_COMP_STREAM]->content);
foreach ($xml->dsTypeModel as $ds) {
$dsid = (string) $ds['ID'];
$optional = strtolower((string) $ds['optional']);
$mime = array();
foreach ($ds->form as $form) {
$mime[] = (string) $form['MIME'];
}
$dsids[$dsid] = array(
'id' => $dsid,
'mime' => $mime,
'optional' => ($optional == 'true') ? TRUE : FALSE,
);
}
return $dsids;
}
/**
* Prepare an ingestable object.
*
* @param string $namespace
* The namespace in which the PID for the new object will be created.
* @param string $label
* An optional label to apply to the object.
* @param array $datastreams
* A array of datastreams to add, where each datastream definition is an
* associative array containing:
* - dsid: The datastream ID.
* - label: An optional label for the datastream.
* - mimetype: A MIMEtype for the datastream; defaults to text/xml.
* - control_group: One of X, M, R and E; defaults to M.
* - datastream_file: A web-accessible path, for which we try to get an
* absolute path using url().
* @param array $content_models
* An array of content model PIDs to which the new object should subscribe.
* @param array $relationships
* An array of relationships, where each relationship is an associative array
* containing:
* - relationship: The predicate for the relationship, from the Fedora
* RELS-EXT namespace.
* - pid: The object for the relationship, to which we are creating the
* relationhsip.
*
* @return NewFedoraObject
* An ingestable NewFedoraObject.
*/
function islandora_prepare_new_object($namespace = NULL, $label = NULL, $datastreams = array(), $content_models = array(), $relationships = array()) {
global $user;
$tuque = islandora_get_tuque_connection();
$object = isset($namespace) ? $tuque->repository->constructObject($namespace) : new IslandoraNewFedoraObject(NULL, $tuque->repository);
$object->owner = isset($user->name) ? $user->name : $object->owner;
$object->label = isset($label) ? $label : $object->label;
foreach ($content_models as $content_model) {
$object->relationships->add(FEDORA_MODEL_URI, 'hasModel', $content_model);
}
foreach ($relationships as $relationship) {
$object->relationships->add(FEDORA_RELS_EXT_URI, $relationship['relationship'], $relationship['pid']);
}
foreach ($datastreams as $ds) {
$dsid = $ds['dsid'];
$label = isset($ds['label']) ? $ds['label'] : '';
$mimetype = isset($ds['mimetype']) ? $ds['mimetype'] : 'text/xml';
// Default 'Managed'
$control_group = 'M';
$groups = array('X', 'M', 'R', 'E');
if (isset($ds['control_group']) && in_array($ds['control_group'], $groups)) {
$control_group = $ds['control_group'];
}
$ds_uri = FALSE;
if (file_valid_uri($ds['datastream_file'])) {
$datastream_file = $ds['datastream_file'];
$ds_uri = TRUE;
}
else {
$datastream_file = url($ds['datastream_file'], array('absolute' => TRUE));
}
$datastream = $object->constructDatastream($dsid, $control_group);
$datastream->label = $label;
$datastream->mimetype = $mimetype;
switch ($control_group) {
case 'M':
if ($ds_uri) {
$datastream->setContentFromFile($datastream_file);
}
else {
$datastream->setContentFromUrl($datastream_file);
}
break;
case 'X':
$datastream->setContentFromString(file_get_contents($datastream_file));
break;
}
$object->ingestDatastream($datastream);
}
return $object;
}
/**
* Displays the repository is inaccessible message.
*
* Use anywhere we want to ensure a consitent error message when the repository
* is not accessible.
*/
function islandora_display_repository_inaccessible_message() {
$text = t('Islandora configuration');
$link = l($text, 'admin/islandora/configure', array('attributes' => array('title' => $text)));
$message = t('Could not connect to the repository. Please check the settings on the !link page.',
array('!link' => $link));
drupal_set_message($message, 'error', FALSE);
}
/**
* Create a message stating if the given executable is available.
*
* If the both the version and required version are given then only if the
* version is equal to or greater than the required version the executable
* will be considered correct.
*
* @param string $path
* The absolute path to an executable to check for availability.
* @param string $version
* The version of exectuable.
* @param string $required_version
* The required version of exectuable.
*
* @return string
* A message in html detailing if the given executable is accessible.
*/
function islandora_executable_available_message($path, $version = NULL, $required_version = NULL) {
$available = is_executable($path);
if ($available) {
$image = theme_image(array('path' => 'misc/watchdog-ok.png', 'attributes' => array()));
$message = t('Executable found at @path', array('@path' => $path));
if ($version) {
$message .= t('<br/>Version: @version', array('@version' => $version));
}
if ($required_version) {
$message .= t('<br/>Required Version: @version', array('@version' => $required_version));
if (version_compare($version, $required_version) < 0) {
$image = theme_image(array('path' => 'misc/watchdog-error.png', 'attributes' => array()));
}
}
}
else {
$image = theme_image(array('path' => 'misc/watchdog-error.png', 'attributes' => array()));
$message = t('Unable to locate executable at @path', array('@path' => $path));
}
return $image . $message;
}
/**
* Create a message stating if the given directory exists.
*
* @param string $path
* The absolute path to an executable to check for availability.
*
* @return string
* A message in HTML detailing if the given directory is exists.
*/
function islandora_directory_exists_message($path) {
$available = is_dir($path);
if ($available) {
$image = theme_image(array('path' => 'misc/watchdog-ok.png', 'attributes' => array()));
$message = t('Directory found at @path', array('@path' => $path));
}
else {
$image = theme_image(array('path' => 'misc/watchdog-error.png', 'attributes' => array()));
$message = t('Unable to locate directory at @path', array('@path' => $path));
}
return $image . $message;
}
/**
* Gets the default value for the given system_settings_form() element.
*
* Checks the $form_state for the default value if not it checks variable_get().
* Assumes #tree is FALSE. This is only really required for elements that utilize
* AJAX, as their value can change before the submit actually takes place.
*
* @param string $name
* The name of the system settings form element.
* @param mixed $default_value
* The default value for the system settings form element.
* @param array $form_state
* The Drupal form state.
*
* @return mixed
* The default value for use in a the system_settings_form().
*/
function islandora_system_settings_form_default_value($name, $default_value, array &$form_state) {
return isset($form_state['values'][$name]) ? $form_state['values'][$name] : variable_get($name, $default_value);
}

443
islandora.api.php

@ -1,120 +1,409 @@
<?php
/**
* remove a datastream from a repository object
* @param object $fedora_object
* tuque FedoraObject
* @param string $datastream_id
* @file
* This file documents all available hook functions to manipulate data.
*/
function hook_islandora_purge_datastream ($fedora_object, $datastream_id){}
/**
* Generate a repository objects view.
*
* @param FedoraObject $object
* The object to display
* @param object $user
* The user accessing the object.
* @param string $page_number
* The page in the content.
* @param string $page_size
* The size of the page.
*
* @param type $object
* tuque FedoraObject
* @return array
* An array whose values are markup.
*/
function hook_islandora_purge_object($islandora_object) {}
function hook_islandora_view_object($object, $user, $page_number, $page_size) {
}
/**
* allows modules to add to a repository objects display. If you implement this
* hook you should also register your module for view with the get types hook.
*
* islandora gets all displays back in an array and iterates over them. the order
* they are displayed is based on the order of the key of the array that each
* module returns.
*
* your module may also want to register a varible that says whether or not it
* should be part of the default display. Modules can also add secondary tabs as
* a way to add there output to an islandora display. the basic image module has
* samples of both (the secondary tabs examples are commented out)
*
* @param type $islandora_object
* tuque FedoraObject
* Generate an object's display for the given content model.
*
* Content models PIDs have colons and hyphens changed to underscores, to
* create the hook name.
*
* @param FedoraObject $object
* A Tuque FedoraObject
*
* @return array
* An array whose values are markup.
*/
function hook_islandora_view_object($islandora_object){}
function hook_CMODEL_PID_islandora_view_object($object) {
}
/**
* returns an array listing object types provided by sub modules
* Ex. array($types['islandora:collectionCModel'][ISLANDORA_VIEW_HOOK] = variable_get('islandora_basic_collection_use_for_default_tab', TRUE);
* $types['islandora:collectionCModel'][ISLANDORA_EDIT_HOOK] = FALSE;
*
* @return array
* Alter display output after it has been generated.
*
* @param FedoraObject $object
* A Tuque FedoraObject being operated on.
* @param array $rendered
* An arr of rendered views.
*/
function hook_islandora_get_types(){}
function hook_islandora_view_object_alter(&$object, &$rendered) {
}
/**
* allows modules to define an object edit page by cmodel
*
* your module should return true for ISLANDORA_EDIT_HOOK in its get_types function
*
* islandora provides a default implementation that should work for most use cases
* @param string $islandora_object
* @return string
*
* Generate an object's management display.
*
* @param FedoraObject $object
* A Tuque FedoraObject
*
* @return array
* An array whose values are markup.
*/
function hook_islandora_edit_object($islandora_object){}
function hook_islandora_edit_object($object) {
}
/**
* allows modules to alter the fedora object before it is pass through the edit
* hooks
* @param type $islandora_object
* a tugue FedoraObject
* Generate an object's management display for the given content model.
*
* Content models PIDs have colons and hyphens changed to underscores, to
* create the hook name.
*
* @param FedoraObject $object
* A Tuque FedoraObject
*
* @return array
* An array whose values are markup.
*/
function islandora_islandora_edit_object_alter ($islandora_object){}
function hook_CMODEL_PID_islandora_edit_object($object) {
}
/**
* Allow management display output to be altered.
*
* @param FedoraObject $object
* A Tuque FedoraObject
* @param array $rendered
* an arr of rendered views
*/
function hook_islandora_edit_object_alter(&$object, &$rendered) {
}
/**
* creates and populates a php Fedora object.
* Allows modules to alter the object or block/modify the given action.
*
* This alter hook will be called before any object is ingested, modified or
* purged.
*
* Changing object properties such as "label", or "state", are considered
* modifications, where as manipulating an object's datstreams are not.
*
* @param AbstractFedoraObject $object
* The object to alter.
* @param array $context
* An associative array containing:
* - action: A string either 'ingest', 'purge', 'modify'.
* - block: Either TRUE or FALSE, if TRUE the action won't take place.
* Defaults to FALSE.
* - purge: Either TRUE or FALSE, only present when the action is 'purge'.
* If 'delete' or 'block' is set to TRUE, they will take precedence.
* Defaults to TRUE.
* - delete: Either TRUE or FALSE, only present when the action is 'purge'.
* If TRUE it will cause the object's state to be set to 'D' instead.
* If 'block' is set to TRUE, it will take precedence.
* Defaults to FALSE,
* - params: An associative array, only present when the action is 'modify'.
* The key value pairs repersent what values will be changed. The params
* will match the same params as passed to FedoraApiM::modifyObject().
*
* @see FedoraApiM::modifyObject()
*/
function hook_islandora_preingest_alter(){}
function hook_islandora_object_alter(AbstractFedoraObject $object, array &$context) {
}
/**
* modules can implement this hook to add or remove datastreams after an
* object has been ingested.
*
* Each module should check for the newly ingested repository objects content
* model to make sure it is a type of object they want to act on.
*
* @param type $islandora_object
* tugue FeodoraObject
* Allows modules to alter the object or block/modify the given action.
*
* @see hook_islandora_object_alter()
*/
function hook_islandora_postingest($islandora_object){}
function hook_CMODEL_PID_islandora_object_alter(AbstractFedoraObject $object, array &$context) {
}
/**
* Register potential ingest routes. Implementations should return an array containing possible routes.
* Ex. array(
* array('name' => t('Ingest Route Name'), 'url' => 'ingest_route/url', 'weight' => 0),
* );
* Allows modules to alter the datastream or block/modify the given action.
*
* This alter hook will be called before any datastream is ingested, modified or
* purged.
*
* Adding datastreams to NewFedoraObject's will not trigger this alter hook
* immediately, instead it will be triggered for all datastreams at the time
* of the NewFedoraObject's ingest.
*
* Purging datastreams from a NewFedoraObject will not trigger this alter hook
* at all.
*
* Changing datastream's properties such as "label", or "state", are considered
* modifications, as well as changing the datastreams content.
*
* @param AbstractFedoraObject $object
* The object to the datastream belong to.
* @param AbstractFedoraDatastream $datastream
* The datastream to alter.
* @param array $context
* An associative array containing:
* - action: A string either 'ingest', 'purge', 'modify'.
* - block: Either TRUE or FALSE, if TRUE the action won't take place.
* Defaults to FALSE.
* - purge: Either TRUE or FALSE, only present when the action is 'purge'.
* If 'delete' or 'block' is set to TRUE, they will take precedence.
* Defaults to TRUE.
* - delete: Either TRUE or FALSE, only present when the action is 'purge'.
* If TRUE it will cause the object's state to be set to 'D' instead.
* If 'block' is set to TRUE, it will take precedence.
* Defaults to FALSE,
* - params: An associative array, only present when the action is 'modify'.
* The key value pairs repersent what values will be changed. The params
* will match the same params as passed to FedoraApiM::modifyDatastream().
*
* @see FedoraApiM::modifyDatastream()
*/
function hook_islandora_ingest_registry($collection_object) {}
function hook_islandora_datastream_alter(AbstractFedoraObject $object, AbstractFedoraDatastream $datastream, array &$context) {
}
/**
* Register a datastream edit route/form.
* @param $islandora_object
* @param $ds_id
* Allows modules to alter the datastream or block/modify the given action.
*
* @see hook_islandora_datastream_alter()
*/
function hook_islandora_edit_datastream_registry($islandora_object, $ds_id) {}
function hook_CMODEL_PID_DSID_islandora_datastream_alter(AbstractFedoraObject $object, AbstractFedoraDatastream $datastream, array &$context) {
}
/**
* alter an object before it gets used further down the stack
* @param type $object
* a tuque FedoraObject
* Notify modules that the given object was ingested.
*
* This hook is called after an object has been successfully ingested via a
* FedoraRepository object.
*
* @note
* If ingested directly via the FedoraApiM object this will not be called as we
* don't have access to the ingested object at that time.
*
* @param FedoraObject $object
* The object that was ingested.
*/
function hook_islandora_object_alter ($fedora_object){}
function hook_islandora_object_ingested(FedoraObject $object) {
}
/**
* insert or remove rendered elements by implementing this function
* in your module
* @param type $arr
* an arr of rendered views
* Notify modules that the given object was ingested.
*
* @see hook_islandora_object_ingested()
*/
function hook_CMODEL_PID_islandora_object_ingested(FedoraObject $object) {
}
/**
* Notify modules that the given object was modified.
*
* This hook is called after an object has been successfully modified.
*
* Changing object properties such as "label", or "state", are considered
* modifications, where as manipulating an object's datstreams are not.
*
* @param FedoraObject $object
* The object that was ingested.
*
* @todo We should also include what changes were made in a additional
* parameter.
*/
function hook_islandora_object_modified(FedoraObject $object) {
}
/**
* Notify modules that the given object was ingested.
*
* @see hook_islandora_object_modified()
*/
function hook_CMODEL_PID_islandora_object_modified(FedoraObject $object) {
}
/**
* Notify modules that the given object was purged/deleted.
*
* This hook is called after an object has been successfully purged, or
* when its state has been changed to "Deleted".
*
* @param string $pid
* The ID of the object that was purged/deleted.
*/
function hook_islandora_object_purged($pid) {
}
/**
* Notify modules that the given object was purged/deleted.
*
* @see hook_islandora_object_purged()
*/
function hook_CMODEL_PID_islandora_object_purged($pid) {
}
/**
* Notify modules that the given datastream was ingested.
*
* This hook is called after the datastream has been successfully ingested.
*
* @note
* If ingested directly via the FedoraApiM object this will not be called as we
* don't have access to the ingested datastream at that time.
*
* @param FedoraObject $object
* The object the datastream belongs to.
* @param FedoraDatastream $datastream
* The ingested datastream.
*/
function hook_islandora_datastream_ingested(FedoraObject $object, FedoraDatastream $datastream) {
}
/**
* Notify modules that the given datastream was ingested.
*
* @see hook_islandora_object_ingested()
*/
function hook_CMODEL_PID_DSID_islandora_datastream_ingested(FedoraObject $object, FedoraDatastream $datastream) {
}
/**
* Notify modules that the given datastream was modified.
*
* This hook is called after an datastream has been successfully modified.
*
* Changing datastream properties such as "label", or "state", are considered
* modifications, as well as the datastreams content.
*
* @param FedoraObject $object
* The object the datastream belongs to.
* @param FedoraDatastream $datastream
* The datastream that was ingested.
*
* @todo We should also include what changes were made in a additional
* parameter.
*/
function hook_islandora_datastream_modified(FedoraObject $object, FedoraDatastream $datastream) {
}
/**
* Notify modules that the given datastream was ingested.
*
* @see hook_islandora_datastream_modified()
*/
function hook_CMODEL_PID_islandora_datastream_modified(FedoraObject $object, FedoraDatastream $datastream) {
}
/**
* Notify modules that the given datastream was purged/deleted.
*
* This hook is called after an datastream has been successfully purged, or
* when its state has been changed to "Deleted".
*
* @param FedoraObject $object
* The object the datastream belonged to.
* @param string $dsid
* The ID of the datastream that was purged/deleted.
*/
function hook_islandora_display_alter ($arr){}
function hook_islandora_datastream_purged(FedoraObject $object, $dsid) {
}
/**
* Notify modules that the given datastream was purged/deleted.
*
* @param type $islandora_object
* a tuque FedoraObject
* @param array $content_models
* @param string $collection_pid
* @see hook_islandora_datastream_purged()
*/
function hook_islandora_ingest_pre_ingest($islandora_object, $content_models, $collection_pid){}
function hook_CMODEL_PID_islandora_datastream_purged(FedoraObject $object, $dsid) {
}
/**
* Register a datastream edit route/form.
*
* @param FedoraObject $object
* The object to check.
* @param string $dsid
* todo
*/
function hook_islandora_edit_datastream_registry($object, $dsid) {
}
/**
* Registry hook for required objects.
*
* Solution packs can include data to create certain objects that describe or
* help the objects it would create. This includes collection objects and
* content models.
*
* @see islandora_solution_packs_admin()
* @see islandora_install_solution_pack()
* @example islandora_islandora_required_objects()
*/
function hook_islandora_required_objects() {
}
/**
* Registry hook for viewers that can be implemented by solution packs.
*
* Solution packs can use viewers for their data. This hook lets Islandora know
* which viewers there are available.
*
* @see islandora_get_viewers()
* @see islandora_get_viewer_callback()
*/
function hook_islandora_viewer_info() {
}
/**
* Returns a list of datastreams that are determined to be undeletable.
*/
function hook_islandora_undeletable_datastreams(array $models) {
}
/**
* Define steps used in the islandora_ingest_form() ingest process.
*
* @param array $form_state
* An array containing the form_state, on which infomation from step storage
* might be extracted. Note that the
*
* @return array
* An associative array of associative arrays which define each step in the
* ingest process. Each step should consist of a unique name mapped to an
* array of properties (keys) including:
* - type: The type of step. Currently, only "form" is implemented.
* - weight: The "weight" of this step--heavier(/"larger") values sink to the
* end of the process while smaller(/"lighter") values are executed first.
* - form_id: The form building function to call to get the form structure
* for this step.
* - args: An array of arguments to pass to the form building function.
* And may optionally include both:
* - module: A module from which we want to load an include.
* - file: A file to include (relative to the module's path, including the
* file's extension).
*/
function hook_islandora_ingest_steps(array $form_state) {
return array(
'my_cool_step_definition' => array(
'type' => 'form',
'weight' => 1,
'form_id' => 'my_cool_form',
'args' => array('arg_one', 'numero deux'),
),
);
}
/**
* Content model specific version of hook_islandora_ingest_steps().
*
* XXX: Content models are not selected in a generic manner. Currently, this
* gets called for every content model in the "configuration", yet the
* configuration never changes. We should determine a consistent way to bind
* content models, so as to consistently be able to build steps.
*
* @see hook_islandora_ingest_steps()
*/
function hook_CMODEL_PID_islandora_ingest_steps(array $form_state) {
}

10
islandora.info

@ -1,4 +1,4 @@
name = Islandora Repository
name = Islandora
description = "View and manage Fedora objects"
package = Islandora
version = 7.x-1.0
@ -6,4 +6,12 @@ core = 7.x
configure = admin/islandora/configure
stylesheets[all][] = css/islandora.base.css
stylesheets[all][] = css/islandora.theme.css
files[] = includes/mime_detect.inc
files[] = includes/dublin_core.inc
files[] = includes/tuque.inc
files[] = includes/tuque_wrapper.inc
files[] = includes/object.entity_controller.inc
files[] = tests/web_test_case.inc
files[] = tests/authtokens.test
files[] = tests/hooks.test
php = 5.3

95
islandora.install

@ -0,0 +1,95 @@
<?php
/**
* @file
* This file contains all install related hooks.
*/
/**
* Implements hook_install().
*
* @see islandora_islandora_required_objects()
*/
function islandora_install() {
module_load_include('inc', 'islandora', 'includes/solution_packs');
islandora_install_solution_pack('islandora');
}
/**
* Implements hook_uninstall().
*
* @see islandora_islandora_required_objects()
*/
function islandora_uninstall() {
module_load_include('inc', 'islandora', 'includes/solution_packs');
islandora_install_solution_pack('islandora', 'uninstall');
}
/**
* Implements hook_schema().
*/
function islandora_schema() {
$schema['islandora_authtokens'] = array(
'description' => 'The hub for all islandora authentication tokens',
'fields' => array(
'id' => array(
'description' => 'key',
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
),
'token' => array(
'description' => 'a unique identifier for this token',
'type' => 'varchar',
'length' => 64,
),
'remaining_uses' => array(
'description' => 'How many uses until this should be removed',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
),
'uid' => array(
'description' => 'the user id that requested this token',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
),
'time' => array(
'description' => 'when this token was created',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
),
'pid' => array(
'description' => 'the pid of the object this token unlocks',
'type' => 'varchar',
'length' => 128,
'not null' => TRUE,
),
'dsid' => array(
'description' => 'the datasteram id of the object this token unlocks',
'type' => 'varchar',
'length' => 32,
'not null' => TRUE,
),
),
'unique keys' => array(
'id' => array('id'),
),
'primary key' => array('id'),
);
return $schema;
}
/**
* Implements hook_update_N().
*
* Add the required table for handling authentication tokens.
* This is the first instance that has this table.
*/
function islandora_update_7001(&$sandbox) {
drupal_install_schema('islandora');
$t = get_t();
return $t("Islandora database updates complete");
}

928
islandora.module

File diff suppressed because it is too large Load Diff

118
islandora.rules.inc

@ -0,0 +1,118 @@
<?php
/**
* @file
* Does rule type stuff,
*/
/**
* Helper function to get reused "parameter" array.
*/
function islandora_rules_relationship_parameter_array() {
$to_return = array(
'subject' => array(
'type' => 'islandora_object',
'label' => t('Subject'),
'description' => t('An object of which we should check the relationships (The "subject" of the relationship).'),
),
'pred_uri' => array(
'type' => 'text',
'label' => t('Predicate URI'),
'description' => t('The URI namespace to which the predicate belongs.'),
),
'pred' => array(
'type' => 'text',
'label' => t('Predicate'),
'description' => t('The predicate of the relationship.'),
),
'object' => array(
'type' => 'text',
'label' => t('Object'),
'description' => t('The object of the relationship.'),
'allow null' => TRUE,
'default value' => NULL,
),
'type' => array(
'type' => 'integer',
'label' => t('Object type in the relationship'),
'description' => t('0=URI, 1=plain literal'),
'default value' => 0,
),
);
return $to_return;
}
/**
* Implements hook_rules_condition_info().
*/
function islandora_rules_condition_info() {
$cond = array();
$cond['islandora_object_has_relationship'] = array(
'label' => t('Check object for a relationship'),
'group' => t('Islandora'),
'parameter' => islandora_rules_relationship_parameter_array(),
);
return $cond;
}
/**
* Implements hook_rules_action_info().
*/
function islandora_rules_action_info() {
$cond = array();
$cond['islandora_object_remove_relationship'] = array(
'label' => t('Remove a relationship from an object'),
'group' => t('Islandora'),
'parameter' => islandora_rules_relationship_parameter_array(),
);
$cond['islandora_object_add_relationship'] = array(
'label' => t('Add a relationship to an object'),
'group' => t('Islandora'),
'parameter' => islandora_rules_relationship_parameter_array(),
);
return $cond;
}
/**
* Checks that there is a relationship match on the given object.
*
* Takes a subject (either a FedoraObject or a FedoraDatastream), as well as
* the parameters for FedoraRelsExt::get() or FedoraRelsInt::get(), to try to
* find a match.
*
* @see FedoraRelsExt::get()
*/
function islandora_object_has_relationship($sub, $pred_uri, $pred, $object, $type) {
$relationships = $sub->relationships->get($pred_uri, $pred, $object, $type);
return !empty($relationships);
}
/**
* Remove a relationship from the given object.
*
* Takes a subject (either a FedoraObject or a FedoraDatastream), as well as
* the parameters for FedoraRelsExt::remove() or FedoraRelsInt::remove(), to
* try to find a match.
*
* @see FedoraRelsExt::get()
*/
function islandora_object_remove_relationship($sub, $pred_uri, $pred, $object, $type) {
$sub->relationships->remove($pred_uri, $pred, $object, $type);
}
/**
* Add a relationship to the given object.
*
* Takes a subject (either a FedoraObject or a FedoraDatastream), as well as
* the parameters for FedoraRelsExt::add() or FedoraRelsInt::add(), and adds
* the represented relationship.
*
* @see FedoraRelsExt::get()
*/
function islandora_object_add_relationship($sub, $pred_uri, $pred, $object, $type) {
$sub->relationships->add($pred_uri, $pred, $object, $type);
}

31
policies/permit-apim-to-authenticated-user.xml

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<Policy xmlns="urn:oasis:names:tc:xacml:1.0:policy"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
PolicyId="permit-apim-to-authenticated-user"
RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable">
<Description>note that other policies may provide exceptions to this broad policy. This policy assumes api-m users have to be authenticated</Description>
<Target>
<Subjects>
<Subject>
<SubjectMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">authenticated user</AttributeValue>
<SubjectAttributeDesignator AttributeId="fedoraRole" MustBePresent="false"
DataType="http://www.w3.org/2001/XMLSchema#string"/>
</SubjectMatch>
</Subject>
</Subjects>
<Resources>
<AnyResource/>
</Resources>
<Actions>
<Action>
<ActionMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">urn:fedora:names:fedora:2.1:action:api-m</AttributeValue>
<ActionAttributeDesignator DataType="http://www.w3.org/2001/XMLSchema#string"
AttributeId="urn:fedora:names:fedora:2.1:action:api"/>
</ActionMatch>
</Action>
</Actions>
</Target>
<Rule RuleId="1" Effect="Permit"/>
</Policy>

25
policies/permit-getDatastream-unrestricted.xml

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<Policy xmlns="urn:oasis:names:tc:xacml:1.0:policy"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
PolicyId="permit-getDatastreamHistory-to-authenticated"
RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable">
<Description>Note that other policies may provide exceptions to this broad policy. This policy assumes api-m users have to be authenticated</Description>
<Target>
<Subjects>
<AnySubject/>
</Subjects>
<Resources>
<AnyResource/>
</Resources>
<Actions>
<Action>
<ActionMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">urn:fedora:names:fedora:2.1:action:id-getDatastream</AttributeValue>
<ActionAttributeDesignator DataType="http://www.w3.org/2001/XMLSchema#string"
AttributeId="urn:fedora:names:fedora:2.1:action:id"/>
</ActionMatch>
</Action>
</Actions>
</Target>
<Rule RuleId="1" Effect="Permit"/>
</Policy>

25
policies/permit-getDatastreamHistory-unrestricted.xml

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<Policy xmlns="urn:oasis:names:tc:xacml:1.0:policy"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
PolicyId="permit-getDatastreamHistory-to-authenticated"
RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable">
<Description>Note that other policies may provide exceptions to this broad policy. This policy assumes api-m users have to be authenticated</Description>
<Target>
<Subjects>
<AnySubject/>
</Subjects>
<Resources>
<AnyResource/>
</Resources>
<Actions>
<Action>
<ActionMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">urn:fedora:names:fedora:2.1:action:id-getDatastreamHistory</AttributeValue>
<ActionAttributeDesignator DataType="http://www.w3.org/2001/XMLSchema#string"
AttributeId="urn:fedora:names:fedora:2.1:action:id"/>
</ActionMatch>
</Action>
</Actions>
</Target>
<Rule RuleId="1" Effect="Permit"/>
</Policy>

31
policies/permit-upload-to-authenticated-user.xml

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<Policy xmlns="urn:oasis:names:tc:xacml:1.0:policy"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
PolicyId="permit-upload-to-authenticated-user"
RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable">
<Description></Description>
<Target>
<Subjects>
<Subject>
<SubjectMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">authenticated user</AttributeValue>
<SubjectAttributeDesignator AttributeId="fedoraRole" MustBePresent="false"
DataType="http://www.w3.org/2001/XMLSchema#string"/>
</SubjectMatch>
</Subject>
</Subjects>
<Resources>
<AnyResource/>
</Resources>
<Actions>
<Action>
<ActionMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">urn:fedora:names:fedora:2.1:action:id-upload</AttributeValue>
<ActionAttributeDesignator DataType="http://www.w3.org/2001/XMLSchema#string"
AttributeId="urn:fedora:names:fedora:2.1:action:id"/>
</ActionMatch>
</Action>
</Actions>
</Target>
<Rule RuleId="1" Effect="Permit"/>
</Policy>

3
tests/README.txt

@ -0,0 +1,3 @@
You can define your own configurations specific to your enviroment by copying
default.test_config.ini to test_config.ini, making your changes in the copied
file.

110
tests/authtokens.test

@ -0,0 +1,110 @@
<?php
/**
* @file
* Test Authentication Tokens.
*/
class IslandoraAuthtokensTestCase extends IslandoraWebTestCase {
/**
* Get test information for display.
*/
public static function getInfo() {
return array(
'name' => 'Islandora Authorization Tokens',
'description' => 'Ensure the correct functionality of the tokens to pass authorization to Djatoka in Islandora.',
'group' => 'Islandora',
);
}
/**
* Set up data for the tests.
*/
public function setUp() {
parent::setUp();
}
/**
* Test redeeming invalid tokens.
*/
public function testRedeemInvalidToken() {
module_load_include('inc', 'islandora', 'includes/authtokens');
$token = islandora_get_object_token('test:pid', 'woot', 1);
$this->assertTrue($token, 'Token was generated correctly.', 'Unit Tests');
// Redeem a token that doesn't exist with real pid and dsid.
$account = islandora_validate_object_token('test:pid', 'woot', 'foo');
$this->assertFalse($account, 'Redeeming an token that doesn\'t exist returns FALSE', 'Unit Tests');
}
/**
* Test redeeming valid tokens.
*/
public function testRedeemValidToken() {
module_load_include('inc', 'islandora', 'includes/authtokens');
// Change the current user.
global $user;
$user_backup = $user;
$test_account = $this->drupalCreateUser();
$user = $test_account;
$token = islandora_get_object_token('test:pid', 'woot', 1);
// Logout again.
$user = $user_backup;
$token_account = islandora_validate_object_token('test:pid', 'woot', $token);
$this->assertEqual($token_account->uid, $test_account->uid, 'UID from token is correct', 'Unit Tests');
$this->assertEqual($token_account->pass, $test_account->pass, 'Pass from token is correct', 'Unit Tests');
$this->assertEqual($token_account->name, $test_account->name, 'Name from token is correct', 'Unit Tests');
}
/**
* Test tokened datastream view without XACML.
*/
public function testTokenedViewDatastreamWithoutXacml() {
// Ingest the fixture.
$fixture_path = drupal_get_path('module', 'islandora') . '/tests/fixtures/bug.jp2';
$tuque = islandora_get_tuque_connection();
$newpid = "{$this->randomName()}:{$this->randomName()}";
$fixture_object = $tuque->repository->constructObject($newpid);
$fixture_datastream = $fixture_object->constructDatastream('JP2');
$fixture_datastream->setContentFromFile($fixture_path, TRUE);
$fixture_object->ingestDatastream($fixture_datastream);
$tuque->repository->ingestObject($fixture_object);
$this->drupalGet("islandora/object/{$newpid}/datastream/JP2/view");
$this->assertResponse(403, 'Page not found as anonymous');
$account = $this->drupalCreateUser(array(FEDORA_VIEW_OBJECTS));
$this->drupalLogin($account);
$this->drupalGet("islandora/object/{$newpid}/datastream/JP2/view");
$this->assertResponse(200, 'Page loaded as the authorized user');
// Do some voodoo to get a token as the user we are connecting as
// to do this we need to change the user we are logged in as.
module_load_include('inc', 'islandora', 'includes/authtokens');
global $user;
$backup = $user;
$user = $account;
$token = islandora_get_object_token($newpid, 'JP2', 1);
$user = $backup;
$this->drupalLogout();
$this->drupalGet("islandora/object/{$newpid}/datastream/JP2/view", array('query' => array('token' => $token)));
$this->assertResponse(200, 'Page loaded with the token');
$this->drupalGet("islandora/object/{$newpid}/datastream/JP2/view", array('query' => array('token' => $token)));
$this->assertResponse(403, 'Token is unable to be reused');
// Delete fixture object.
$tuque->repository->purgeObject($newpid);
}
/**
* This will test something someday.
*/
public function testTokenedViewDatastreamWithXacml() {
// We need to add this test.
}
}

6
tests/default.test_config.ini

@ -0,0 +1,6 @@
[fedora]
fedora_url = "http://localhost:8080/fedora"
use_drupal_filter = TRUE
drupal_filter_file = "/usr/local/fedora/server/config/filter-drupal.xml"
admin_user = "fedoraAdmin"
admin_pass = "fedoraAdmin"

BIN
tests/fixtures/bug.jp2 vendored

Binary file not shown.

192979
tests/fixtures/testfixture_10001.xml vendored

File diff suppressed because it is too large Load Diff

213
tests/hooks.test

@ -0,0 +1,213 @@
<?php
/**
* @file
* Tests to see if the hooks get called when appropriate.
*
* In the test module 'islandora_hooks_test' there are implementations
* of hooks being tested. These implementations modifies the session, and
* that's how we test if the hook gets called.
*
* To make sense of these tests reference islandora_hooks_test.module.
*/
class IslandoraHooksTestCase extends IslandoraWebTestCase {
/**
* Gets info to display to describe this test.
*
* @see IslandoraWebTestCase::getInfo()
*/
public static function getInfo() {
return array(
'name' => 'Islandora Hooks',
'description' => 'Ensure that the hooks for ingestion/purge/modification are called at the appropriate times.',
'group' => 'Islandora',
);
}
/**
* Creates an admin user and a connection to a fedora repository.
*
* @see IslandoraWebTestCase::setUp()
*/
public function setUp() {
parent::setUp('islandora_hooks_test', 'devel');
$this->repository = $this->admin->repository;
$this->purgeTestObjects();
}
/**
* Free any objects/resources created for this test.
*
* @see IslandoraWebTestCase::tearDown()
*/
public function tearDown() {
$this->purgeTestObjects();
unset($this->repository);
parent::tearDown();
}
/**
* Purge any objects created by the test's in this class.
*/
public function purgeTestObjects() {
$objects = array(
'test:testIngestedObjectHook',
'test:testBlockedIngestedObjectHook',
'test:testModifiedObjectHook',
'test:testPurgedObjectHook',
'test:testIngestedDatastreamHook',
'test:testModifiedDatastreamHook',
'test:testPurgedDatastreamHook',
);
foreach ($objects as $object) {
try {
$object = $this->repository->getObject($object);
$object->label = "Don't Block";
$this->repository->purgeObject($object->id);
}
catch(Exception $e) {
// Meh... Either it didn't exist or the purge failed.
}
}
}
/**
* Test ALL THE HOOKS!.
*/
public function testHooks() {
// Test ingesting with FedoraRepository::ingestObject().
$object = $this->repository->constructObject('test:testIngestedObjectHook');
$_SESSION['islandora_hooks']['hook'][ISLANDORA_OBJECT_INGESTED_HOOK] = FALSE;
$_SESSION['islandora_hooks']['alter'][ISLANDORA_OBJECT_INGESTED_HOOK] = FALSE;
$this->repository->ingestObject($object);
$this->assert($_SESSION['islandora_hooks']['alter'][ISLANDORA_OBJECT_INGESTED_HOOK], 'Called "hook_islandora_object_alter" when ingesting via FedoraRepository::ingestObject.');
$this->assert($_SESSION['islandora_hooks']['hook'][ISLANDORA_OBJECT_INGESTED_HOOK], 'Called ISLANDORA_OBJECT_INGESTED_HOOK when ingesting via FedoraRepository::ingestObject.');
$this->repository->purgeObject($object->id);
// Test blocking the ingest.
$object = $this->repository->constructObject('test:testIngestedObjectHook');
$object->label = 'block';
try {
$_SESSION['islandora_hooks']['hook'][ISLANDORA_OBJECT_INGESTED_HOOK] = FALSE;
$_SESSION['islandora_hooks']['alter'][ISLANDORA_OBJECT_INGESTED_HOOK] = FALSE;
$this->repository->ingestObject($object);
$this->fail('Blocked ingest should throw an Exception.');
$this->repository->purgeObject($object->id);
}
catch(Exception $e) {
$this->pass('Ingest blocked and exception thrown.');
$this->assert($_SESSION['islandora_hooks']['alter'][ISLANDORA_OBJECT_INGESTED_HOOK], 'Called "hook_islandora_object_alter" when blocking ingesting via FedoraRepository::ingestObject.');
$this->assertFalse($_SESSION['islandora_hooks']['hook'][ISLANDORA_OBJECT_INGESTED_HOOK], 'Did not called ISLANDORA_OBJECT_INGESTED_HOOK when blocking ingesting via FedoraRepository::ingestObject.');
}
// Test modifying via set magic functions.
$object = $this->repository->constructObject('test:testModifiedObjectHook');
$this->repository->ingestObject($object);
$_SESSION['islandora_hooks']['hook'][ISLANDORA_OBJECT_MODIFIED_HOOK] = FALSE;
$_SESSION['islandora_hooks']['alter'][ISLANDORA_OBJECT_MODIFIED_HOOK] = FALSE;
$object->label = "New Label!";
$this->assert($_SESSION['islandora_hooks']['alter'][ISLANDORA_OBJECT_MODIFIED_HOOK], 'Called "hook_islandora_object_alter" when modifying via set magic functions.');
$this->assert($_SESSION['islandora_hooks']['hook'][ISLANDORA_OBJECT_MODIFIED_HOOK], 'Called ISLANDORA_OBJECT_MODIFIED_HOOK when modifying via set magic functions.');
// Test blocking the modification.
try {
$_SESSION['islandora_hooks']['hook'][ISLANDORA_OBJECT_MODIFIED_HOOK] = FALSE;
$_SESSION['islandora_hooks']['alter'][ISLANDORA_OBJECT_MODIFIED_HOOK] = FALSE;
$object->label = 'block';
$this->fail('Blocked modify should throw an Exception.');
}
catch(Exception $e) {
$this->pass('Modify blocked and exception thrown.');
$this->assertNotEqual($object->label, 'block', 'Modification did not stick.');
$this->assert($_SESSION['islandora_hooks']['alter'][ISLANDORA_OBJECT_MODIFIED_HOOK], 'Called "hook_islandora_object_alter" when blocking modifying via set magic functions.');
$this->assertFALSE($_SESSION['islandora_hooks']['hook'][ISLANDORA_OBJECT_MODIFIED_HOOK], 'Called ISLANDORA_OBJECT_MODIFIED_HOOK when blocking modifying via set magic functions.');
}
$this->repository->purgeObject($object->id);
// Test purging with FedoraRepository::purgeObject().
$object = $this->repository->constructObject('test:testPurgedObjectHook');
$this->repository->ingestObject($object);
$_SESSION['islandora_hooks']['hook'][ISLANDORA_OBJECT_PURGED_HOOK] = FALSE;
$_SESSION['islandora_hooks']['alter'][ISLANDORA_OBJECT_PURGED_HOOK] = FALSE;
$this->repository->purgeObject($object->id);
$this->assert($_SESSION['islandora_hooks']['alter'][ISLANDORA_OBJECT_PURGED_HOOK], 'Called "hook_islandora_object_alter" when purging via FedoraRepository::purgeObject.');
$this->assert($_SESSION['islandora_hooks']['hook'][ISLANDORA_OBJECT_PURGED_HOOK], 'Called ISLANDORA_OBJECT_PURGED_HOOK when purging via FedoraRepository::purgeObject.');
// Test deleting.
$object = $this->repository->constructObject('test:testPurgedObjectHook');
$this->repository->ingestObject($object);
$_SESSION['islandora_hooks']['hook'][ISLANDORA_OBJECT_PURGED_HOOK] = FALSE;
$_SESSION['islandora_hooks']['alter'][ISLANDORA_OBJECT_PURGED_HOOK] = FALSE;
$object->delete();
$this->assert($_SESSION['islandora_hooks']['alter'][ISLANDORA_OBJECT_PURGED_HOOK], 'Called "hook_islandora_object_alter" when deleting via FedoraObject::delete.');
$this->assert($_SESSION['islandora_hooks']['hook'][ISLANDORA_OBJECT_PURGED_HOOK], 'Called ISLANDORA_OBJECT_PURGED_HOOK when purging via FedoraObject::delete.');
$this->repository->purgeObject($object->id);
// Test alter blocking.
$object = $this->repository->constructObject('test:testPurgedObjectHook');
$this->repository->ingestObject($object);
try {
$_SESSION['islandora_hooks']['hook'][ISLANDORA_OBJECT_PURGED_HOOK] = FALSE;
$_SESSION['islandora_hooks']['alter'][ISLANDORA_OBJECT_PURGED_HOOK] = FALSE;
$object->label = 'block';
$this->repository->purgeObject($object->id);
$this->fail('Blocked modify should throw an Exception.');
}
catch(Exception $e) {
$this->pass('Modify blocked and exception thrown.');
$this->assert($_SESSION['islandora_hooks']['alter'][ISLANDORA_OBJECT_PURGED_HOOK], 'Called "hook_islandora_object_alter" when blocking purge via FedoraRepository::purgeObject.');
$this->assertFalse($_SESSION['islandora_hooks']['hook'][ISLANDORA_OBJECT_PURGED_HOOK], 'Called ISLANDORA_OBJECT_PURGED_HOOK when blocking purge via FedoraRepository::purgeObject.');
}
// Test alter delete.
$_SESSION['islandora_hooks']['hook'][ISLANDORA_OBJECT_PURGED_HOOK] = FALSE;
$_SESSION['islandora_hooks']['alter'][ISLANDORA_OBJECT_PURGED_HOOK] = FALSE;
$object->label = 'delete';
$this->repository->purgeObject($object->id);
$this->assertEqual($object->state, 'D', '"hook_islandora_object_alter" prevented purge and deleted the object.');
$this->assert($_SESSION['islandora_hooks']['alter'][ISLANDORA_OBJECT_PURGED_HOOK], 'Called "hook_islandora_object_alter" when preventing purge and deleting.');
$this->assert($_SESSION['islandora_hooks']['hook'][ISLANDORA_OBJECT_PURGED_HOOK], 'Called ISLANDORA_OBJECT_PURGED_HOOK when preventing purge and deleting.');
$object->label = 'Something other than delete';
$this->repository->purgeObject($object->id);
// Test ingesting with FedoraRepository::ingestObject().
$object = $this->repository->constructObject('test:testIngestedDatastreamHook');
$this->repository->ingestObject($object);
$ds = $object->constructDatastream('TEST');
$_SESSION['islandora_hooks']['hook'][ISLANDORA_DATASTREAM_INGESTED_HOOK] = FALSE;
$_SESSION['islandora_hooks']['alter'][ISLANDORA_DATASTREAM_INGESTED_HOOK] = FALSE;
$object->ingestDatastream($ds);
$this->assert($_SESSION['islandora_hooks']['alter'][ISLANDORA_DATASTREAM_INGESTED_HOOK], 'Called "hook_islandora_datastream_alter" when ingesting via FedoraObject::ingestDatastream.');
$this->assert($_SESSION['islandora_hooks']['hook'][ISLANDORA_DATASTREAM_INGESTED_HOOK], 'Called ISLANDORA_DATASTREAM_INGESTED_HOOK when ingesting via FedoraObject::ingestDatastream.');
$this->repository->purgeObject($object->id);
// Test modifying a datastream.
$object = $this->repository->constructObject('test:testModifiedDatastreamHook');
$this->repository->ingestObject($object);
$ds = $object->constructDatastream('TEST');
$object->ingestDatastream($ds);
$_SESSION['islandora_hooks']['hook'][ISLANDORA_DATASTREAM_MODIFIED_HOOK] = FALSE;
$_SESSION['islandora_hooks']['alter'][ISLANDORA_DATASTREAM_MODIFIED_HOOK] = FALSE;
$ds->label = "New Label!";
$this->assert($_SESSION['islandora_hooks']['alter'][ISLANDORA_DATASTREAM_MODIFIED_HOOK], 'Called "hook_islandora_datastream_alter" when modifying via set magic functions.');
$this->assert($_SESSION['islandora_hooks']['hook'][ISLANDORA_DATASTREAM_MODIFIED_HOOK], 'Called ISLANDORA_DATASTREAM_MODIFIED_HOOK when modifying via set magic functions.');
// Test blocking modifying.
try {
$_SESSION['islandora_hooks']['hook'][ISLANDORA_DATASTREAM_MODIFIED_HOOK] = FALSE;
$_SESSION['islandora_hooks']['alter'][ISLANDORA_DATASTREAM_MODIFIED_HOOK] = FALSE;
$ds->label = 'block';
$this->fail('Blocked modify should throw an Exception.');
}
catch(Exception $e) {
$this->pass('Modify blocked and exception thrown.');
$this->assert($_SESSION['islandora_hooks']['alter'][ISLANDORA_DATASTREAM_MODIFIED_HOOK], 'Called "hook_islandora_datastream_alter" when blocking modifying via set magic functions.');
$this->assertFALSE($_SESSION['islandora_hooks']['hook'][ISLANDORA_DATASTREAM_MODIFIED_HOOK], 'Called ISLANDORA_DATASTREAM_MODIFIED_HOOK when blocking modifying via set magic functions.');
}
$this->repository->purgeObject($object->id);
// Test purging with FedoraRepository::purgeObject().
$object = $this->repository->constructObject('test:testPurgedDatastreamHook');
$this->repository->ingestObject($object);
$ds = $object->constructDatastream('TEST');
$object->ingestDatastream($ds);
$_SESSION['islandora_hooks']['hook'][ISLANDORA_DATASTREAM_PURGED_HOOK] = FALSE;
$_SESSION['islandora_hooks']['alter'][ISLANDORA_DATASTREAM_PURGED_HOOK] = FALSE;
$object->purgeDatastream($ds->id);
$this->assert($_SESSION['islandora_hooks']['alter'][ISLANDORA_DATASTREAM_PURGED_HOOK], 'Called "hook_islandora_datastream_alter" when purging via FedoraObject::purgeDatastream.');
$this->assert($_SESSION['islandora_hooks']['hook'][ISLANDORA_DATASTREAM_PURGED_HOOK], 'Called ISLANDORA_DATASTREAM_PURGED_HOOK when purging via FedoraObject::purgeDatastream.');
$this->repository->purgeObject($object->id);
}
}

6
tests/islandora_test.info

@ -0,0 +1,6 @@
name = Islandora Test Module
description = Tests Hooks. Do not enable.
core = 7.x
package = Testing
hidden = TRUE
dependencies[] = islandora

152
tests/islandora_test.module

@ -0,0 +1,152 @@
<?php
/**
* @file
* Implements hooks that get tested by islandora_hooks.test
*/
/**
* Implements hook_islandora_object_alter().
*/
function islandora_hooks_test_islandora_object_alter(AbstractFedoraObject $object, array &$context) {
switch ($context['action']) {
case 'ingest':
if ($object->id == 'test:testIngestedObjectHook') {
$_SESSION['islandora_hooks']['alter'][ISLANDORA_OBJECT_INGESTED_HOOK] = TRUE;
if ($object->label == 'block') {
$context['block'] = TRUE;
}
}
break;
case 'modify':
if ($object->id == 'test:testModifiedObjectHook') {
$_SESSION['islandora_hooks']['alter'][ISLANDORA_OBJECT_MODIFIED_HOOK] = TRUE;
if (isset($context['params']['label']) && $context['params']['label'] == 'block') {
$context['block'] = TRUE;
}
}
elseif ($object->id == 'test:testPurgedObjectHook') {
$_SESSION['islandora_hooks']['alter'][ISLANDORA_OBJECT_PURGED_HOOK] = TRUE;
if (isset($context['params']['label']) && $context['params']['label'] == 'block') {
$context['block'] = TRUE;
}
elseif (isset($context['params']['label']) && $context['params']['label'] == 'delete') {
$context['delete'] = TRUE;
}
}
break;
case 'purge':
if ($object->id == 'test:testPurgedObjectHook') {
$_SESSION['islandora_hooks']['alter'][ISLANDORA_OBJECT_PURGED_HOOK] = TRUE;
if ($object->label == 'block') {
$context['block'] = TRUE;
}
elseif ($object->label == 'delete') {
$context['delete'] = TRUE;
}
}
break;
}
}
/**
* Implements hook_islandora_object_alter().
*/
function islandora_hooks_test_islandora_datastream_alter(AbstractFedoraObject $object, AbstractFedoraDatastream $datastream, array &$context) {
switch ($context['action']) {
case 'ingest':
if ($object->id == 'test:testIngestedDatastreamHook') {
$_SESSION['islandora_hooks']['alter'][ISLANDORA_DATASTREAM_INGESTED_HOOK] = TRUE;
if ($datastream->label == 'block') {
$context['block'] = TRUE;
}
}
break;
case 'modify':
if ($object->id == 'test:testModifiedDatastreamHook') {
$_SESSION['islandora_hooks']['alter'][ISLANDORA_DATASTREAM_MODIFIED_HOOK] = TRUE;
if (isset($context['params']['dsLabel']) && $context['params']['dsLabel'] == 'block') {
$context['block'] = TRUE;
}
}
elseif ($object->id == 'test:testPurgedDatastreamHook') {
$_SESSION['islandora_hooks']['alter'][ISLANDORA_DATASTREAM_PURGED_HOOK] = TRUE;
if (isset($context['params']['dsLabel']) && $context['params']['dsLabel'] == 'block') {
$context['block'] = TRUE;
}
elseif (isset($context['params']['dsLabel']) && $context['params']['dsLabel'] == 'delete') {
$context['delete'] = TRUE;
}
}
break;
case 'purge':
if ($object->id == 'test:testPurgedDatastreamHook') {
$_SESSION['islandora_hooks']['alter'][ISLANDORA_DATASTREAM_PURGED_HOOK] = TRUE;
if ($datastream->label == 'block') {
$context['block'] = TRUE;
}
elseif ($datastream->label == 'delete') {
$context['delete'] = TRUE;
}
}
break;
}
}
/**
* Implements hook_islandora_object_ingested().
*/
function islandora_hooks_test_islandora_object_ingested(FedoraObject $object) {
if ($object->id == 'test:testIngestedObjectHook') {
$_SESSION['islandora_hooks']['hook'][ISLANDORA_OBJECT_INGESTED_HOOK] = TRUE;
}
}
/**
* Implements hook_islandora_object_modified().
*/
function islandora_hooks_test_islandora_object_modified(FedoraObject $object) {
if ($object->id == 'test:testModifiedObjectHook') {
$_SESSION['islandora_hooks']['hook'][ISLANDORA_OBJECT_MODIFIED_HOOK] = TRUE;
}
}
/**
* Implements hook_islandora_object_purged().
*/
function islandora_hooks_test_islandora_object_purged($pid) {
if ($pid == 'test:testPurgedObjectHook') {
$_SESSION['islandora_hooks']['hook'][ISLANDORA_OBJECT_PURGED_HOOK] = TRUE;
}
}
/**
* Implements hook_islandora_datastream_ingested().
*/
function islandora_hooks_test_islandora_datastream_ingested(FedoraObject $object, FedoraDatastream $datastream) {
if ($object->id == 'test:testIngestedDatastreamHook' && $datastream->id == "TEST") {
$_SESSION['islandora_hooks']['hook'][ISLANDORA_DATASTREAM_INGESTED_HOOK] = TRUE;
}
}
/**
* Implements hook_islandora_datastream_modified().
*/
function islandora_hooks_test_islandora_datastream_modified(FedoraObject $object, FedoraDatastream $datastream) {
if ($object->id == 'test:testModifiedDatastreamHook' && $datastream->id == "TEST") {
$_SESSION['islandora_hooks']['hook'][ISLANDORA_DATASTREAM_MODIFIED_HOOK] = TRUE;
}
}
/**
* Implements hook_islandora_datastream_purged().
*/
function islandora_hooks_test_islandora_datastream_purged(FedoraObject $object, $dsid) {
if ($object->id == 'test:testPurgedDatastreamHook' && $dsid == "TEST") {
$_SESSION['islandora_hooks']['hook'][ISLANDORA_DATASTREAM_PURGED_HOOK] = TRUE;
}
}

124
tests/web_test_case.inc

@ -0,0 +1,124 @@
<?php
/**
* @file
* Defines the class IslandoraWebTestCase, which allows tests to access Fedora.
*/
class IslandoraWebTestCase extends DrupalWebTestCase {
/**
* Sets up the Drupal filter to access this test Drupal instances database.
*
* @see DrupalWebTestCase::setUp()
*/
public function setUp() {
$args = func_get_args();
$args = (isset($args[0]) && is_array($args[0])) ? $args[0] : $args;
// Always enable islandora.
$args[] = 'islandora';
parent::setUp($args);
$this->configuration = $this->getTestConfiguration();
if ($this->configuration['use_drupal_filter']) {
$this->backUpDrupalFilter();
$this->setUpDrupalFilter();
}
$this->createAdminUser();
}
/**
* Parses and returns the settings from the test configuration file.
*
* If no install specific test_config.ini file is found, it will use the
* assumed default configs found in default.test_config.ini.
*
* @return array
* The test configuration.
*
* @see parse_ini_file()
*/
protected function getTestConfiguration() {
$path = drupal_get_path('module', 'islandora');
if (file_exists("$path/tests/test_config.ini")) {
$this->pass('Using custom test configuration.');
return parse_ini_file("$path/tests/test_config.ini");
}
elseif (file_exists("$path/tests/default.test_config.ini")) {
$this->pass('Using default test configuration.');
return parse_ini_file("$path/tests/default.test_config.ini");
}
throw new Exception('Required default.test_config.ini/test_config.ini file not found');
}
/**
* Stores the content of the Drupal Filter for later restoration.
*/
protected function backUpDrupalFilter() {
if (file_exists($this->configuration['drupal_filter_file'])) {
$this->originalDrupalFilterContent = file_get_contents($this->configuration['drupal_filter_file']);
}
else {
throw new Exception('Failed to find the required Drupal Filter configuration file.');
}
}
/**
* Sets up a drupal filter that can read for the tests users table.
*/
protected function setUpDrupalFilter() {
$connection_info = Database::getConnectionInfo('default');
$drupal_filter_dom = new DomDocument();
$drupal_filter_dom->loadXML($this->originalDrupalFilterContent);
$drupal_filter_xpath = new DOMXPath($drupal_filter_dom);
$server = $connection_info['default']['host'];
$dbname = $connection_info['default']['database'];
$user = $connection_info['default']['username'];
$password = $connection_info['default']['password'];
$port = $connection_info['default']['port'] ? $connection_info['default']['port'] : '3306';
$prefix = $connection_info['default']['prefix']['default'];
$results = $drupal_filter_xpath->query("/FilterDrupal_Connection/connection[@server='$server' and @dbname='$dbname' and @user='$user' and @password='$password' and @port='$port']/sql");
$results->item(0)->nodeValue = "SELECT DISTINCT u.uid AS userid, u.name AS Name, u.pass AS Pass, r.name AS Role FROM ({$prefix}users u LEFT JOIN {$prefix}users_roles ON u.uid={$prefix}users_roles.uid) LEFT JOIN {$prefix}role r ON r.rid={$prefix}users_roles.rid WHERE u.name=? AND u.pass=?;";
file_put_contents($this->configuration['drupal_filter_file'], $drupal_filter_dom->saveXML());
}
/**
* Creates the a full fedora admin user with a repository connection.
*/
protected function createAdminUser() {
$this->admin = new stdClass();
$this->admin->uid = 1;
$this->admin->name = $this->configuration['admin_user'];
$this->admin->pass = $this->configuration['admin_pass'];
$url = variable_get('islandora_base_url', $this->configuration['fedora_url']);
$connection = islandora_get_tuque_connection($this->admin, $url);
$this->admin->repository = $connection->repository;
return $this->admin;
}
/**
* Stores the content of the Drupal Filter for later restoration.
*/
protected function restoreDrupalFilter() {
$file = $this->configuration['drupal_filter_file'];
if (isset($this->originalDrupalFilterContent)) {
file_put_contents($file, $this->originalDrupalFilterContent);
}
elseif (file_exists($file)) {
// Remove if there was never an original.
drupal_unlink($file);
}
}
/**
* Restores the original Drupal filter, frees any allocated resources.
*
* @see DrupalWebTestCase::tearDown()
*/
public function tearDown() {
if ($this->configuration['use_drupal_filter']) {
$this->restoreDrupalFilter();
}
unset($this->admin);
unset($this->configuration);
parent::tearDown();
}
}

49
theme/islandora-object-edit.tpl.php

@ -1,51 +1,20 @@
<?php
/*
* islandora-object-edit.tpl.php
*
/**
* @file
* The default manage datastreams view for objects.
*
*
* This file is part of Islandora.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the program. If not, see <http ://www.gnu.org/licenses/>.
*/
?>
<?php
/*
* this is a template for objects that do not have a module to registered to build their display.
*
* islandora_object is a fedora tuque Object
* $object->label
* $object->id
* to get the contents of a datastream
* $object['dsid']->content
*
* $dublin_core is a Dublin_Core object
* $object['dsid']->content
*
* $dublin_core is a DublinCore object
* which is an array of elements, such as dc.title
* and each element has an array of values. dc.title can have none, one or many titles
* and each element has an array of values.
* dc.title can have none, one or many titles
* this is the case for all dc elements.
*
*
*
*/
//dsm($object);
drupal_set_title($islandora_object->label);
//print($islandora_object->label . ' ' . $islandora_object->id);
print ($variables['datastream_table']);
?>
<?php print (theme_table($variables['datastream_table'])); ?>

81
theme/islandora-object.tpl.php

@ -1,31 +1,12 @@
<?php
/*
* islandora-object.tpl.php
*
/**
* @file
* The default object view.
*
* This is a template for objects that do not have a module to registered to
* build their display.
*
*
* This file is part of Islandora.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the program. If not, see <http ://www.gnu.org/licenses/>.
*/
?>
<?php
/*
* this is a template for objects that do not have a module to registered to build their display.
*
* islandora_object is a fedora tuque Object
* $object->label - The label for this object.
* $object->id - The identifier of the object.
@ -39,7 +20,7 @@
* to test if a datastream exists isset($object['dsid'])
*
* to iterate over datastreams:
* foreach($object as $ds) {
* foreach ($object as $ds) {
* $ds->label, etc
* }
*
@ -57,40 +38,38 @@
* $ds->size - The size of the datastream
* $ds->checksum - The checksum of the datastream
* $ds->checksumType - The type of checksum for the datastream.
* $ds->createdDate->format("Y-m-d") - The created date with an option to use a format of your choice
* $ds->createdDate->format("Y-m-d") - The created date with an option to use
* a format of your choice
* $ds->content - The content of the datastream
* $ds->url - The URL. This is only valid for R and E datastreams.
*
* $dublin_core is a Dublin_Core object
* $ds->url - The URL. This is only valid for R and E
* datastreams.
*
* $dublin_core is a DublinCore object
* which is an array of elements, such as dc.title
* and each element has an array of values. dc.title can have none, one or many titles
* and each element has an array of values.
* dc.title can have none, one or many titles
* this is the case for all dc elements.
*
*
*
*
* we can get a list of datastreams by doing
* foreach ($object as $ds){
* foreach ($object as $ds) {
* do something here
* }
*
*/
?>
<?php if(isset($islandora_object_label)): ?>
<?php drupal_set_title("$islandora_object_label"); ?>
<?php endif; ?>
<div class="islandora-object islandora">
<h2>Details</h2>
<h2><?php print t('Details'); ?></h2>
<dl class="islandora-object-tn">
<dt>
<?php if(isset($variables['islandora_thumbnail_url'])): ?>
<?php print('<img src = "'.$variables['islandora_thumbnail_url'].'"/>'); ?></dt>
<?php if (isset($variables['islandora_thumbnail_url'])): ?>
<img src="<?php print $variables['islandora_thumbnail_url']; ?>"/></dt>
<?php endif; ?>
<dd></dd>
</dl>
<dl class="islandora-inline-metadata islandora-object-fields">
<?php $row_field = 0; ?>
<?php foreach($dc_array as $key => $value): ?>
<?php foreach ($dc_array as $key => $value): ?>
<dt class="<?php print $value['class']; ?><?php print $row_field == 0 ? ' first' : ''; ?>">
<?php print $value['label']; ?>
</dt>
@ -99,26 +78,26 @@
</dd>
<?php $row_field++; ?>
<?php endforeach; ?>
<?php if($parent_collections): ?>
<?php if ($parent_collections): ?>
<dt>Collections</dt>
<dd>
<?php foreach($parent_collections as $key => $value): ?>
<div><?php print $value['label_link'] ?></div>
<?php foreach ($parent_collections as $collection): ?>
<div><?php print l($collection->label, "islandora/object/{$collection->id}"); ?></div>
<?php endforeach; ?>
</dd>
<?php endif; ?>
</dl>
</div>
<fieldset class="collapsible collapsed" style="display: block; clear:both">
<legend><span class="fieldset-legend">File Details</span></legend>
<legend><span class="fieldset-legend"><?php print t('File details'); ?></span></legend>
<div class="fieldset-wrapper">
<table>
<tr>
<th>ID</th>
<th>Label</th>
<th>Size</th>
<th>Mimetype</th>
<th>Created</th>
<th><?php print t('ID'); ?></th>
<th><?php print t('Label'); ?></th>
<th><?php print t('Size'); ?></th>
<th><?php print t('Mimetype'); ?></th>
<th><?php print t('Created'); ?></th>
</tr>
<?php foreach($datastreams as $key => $value): ?>
<tr>

92
theme/islandora.theme.inc → theme/theme.inc

@ -1,19 +1,20 @@
<?php
/**
* preprocess the edit template
* @global string $base_url
* @param array $variables
* theme variables for the edit template
* @file
* This file contains all theme and preprocess functions.
*/
function islandora_preprocess_islandora_default_edit(&$variables) {
$islandora_object = $variables['islandora_object'];
/**
* Implements hook_preprocess_theme().
*/
function islandora_preprocess_islandora_default_edit(array &$variables) {
global $base_url;
$islandora_object = $variables['islandora_object'];
$datastreams = array();
$variables['islandora_editmetadata_url'] = $base_url . '/islandora/edit_form/' . $islandora_object->id;
module_load_include('inc', 'islandora', 'includes/datastream');
module_load_include('inc', 'islandora', 'includes/utilities');
// $variables['add_datastream_form'] = drupal_get_form('islandora_add_datastream_form', $islandora_object->id);
$header = array(
array('data' => t('ID')),
array('data' => t('Label')),
@ -21,42 +22,69 @@ function islandora_preprocess_islandora_default_edit(&$variables) {
array('data' => t('Mime type')),
array('data' => t('Size')),
array('data' => t('Operations'), 'colspan' => '3'),
//array('data' => t('Delete')),
);
$table_attributes = array('class' => array('manage-datastreams'));
$rows = array();
foreach ($islandora_object as $ds) {
$rows[] = array(
array('class' => 'datastream-id', 'data' => l($ds->id, islandora_datastream_get_url($ds, 'view'))),
array('class' => 'datastream-label', 'data' => $ds->label),
array('class' => 'datastream-control', 'data' => islandora_control_group_to_human_readable($ds->controlGroup)),
array('class' => 'datastream-mime', 'data' => $ds->mimeType),
array('class' => 'datastream-size', 'data' => islandora_datastream_get_human_readable_size($ds)),
array('class' => 'datastream-download', 'data' => l(t('download'), islandora_datastream_get_url($ds, 'download'))),
array('class' => 'datstream-edit', 'data' => islandora_datastream_edit_get_link($islandora_object, $ds->id)),
array('class' => 'datastream-delete', 'data' => islandora_datastream_get_delete_link($ds)),
array(
'class' => 'datastream-id',
'data' => l($ds->id, islandora_datastream_get_url($ds, 'view')),
),
array(
'class' => 'datastream-label',
'data' => $ds->label,
),
array(
'class' => 'datastream-control',
'data' => islandora_control_group_to_human_readable($ds->controlGroup),
),
array(
'class' => 'datastream-mime',
'data' => $ds->mimeType,
),
array(
'class' => 'datastream-size',
'data' => islandora_datastream_get_human_readable_size($ds),
),
array(
'class' => 'datastream-download',
'data' => l(t('download'), islandora_datastream_get_url($ds, 'download')),
),
array(
'class' => 'datstream-edit',
'data' => islandora_datastream_edit_get_link($ds),
),
array(
'class' => 'datastream-delete',
'data' => islandora_datastream_get_delete_link($ds),
),
);
}
$caption = $islandora_object->label . ' - ' . $islandora_object->id;
$table = array('colgroups' => NULL, 'sticky' => TRUE, 'empty' => 'Error loading datastreams', 'caption' => $caption, 'header' => $header, 'rows' => $rows, 'attributes' => $table_attributes);
$variables['datastream_table'] = theme_table($table);
$table = array(
'colgroups' => NULL,
'sticky' => TRUE,
'empty' => 'Error loading datastreams',
'caption' => $caption,
'header' => $header,
'rows' => $rows,
'attributes' => $table_attributes,
);
$variables['datastream_table'] = $table;
}
/**
* preprocess for the default view template
* @global string $base_url
* @param array $variables
* Implements hook_preprocess_theme().
*/
function islandora_preprocess_islandora_default(&$variables) {
drupal_add_js('misc/form.js');
drupal_add_js('misc/collapse.js');
$islandora_object = $variables['islandora_object'];
module_load_include('inc', 'islandora', 'includes/islandora_dublin_core');
module_load_include('inc', 'islandora', 'includes/utilities');
module_load_include('inc', 'islandora', 'includes/datastream');
$variables['parent_collections'] = islandora_datastream_get_parents($islandora_object);
$variables['parent_collections'] = islandora_get_parents_from_rels_ext($islandora_object);
$datastreams = array();
foreach ($islandora_object as $ds) {
@ -72,17 +100,19 @@ function islandora_preprocess_islandora_default(&$variables) {
$datastreams[$id]['mimetype'] = $ds->mimetype;
$datastreams[$id]['size'] = islandora_datastream_get_human_readable_size($ds);
$datastreams[$id]['created_date'] = $ds->createdDate->format("Y-m-d");
$datastreams[$id]['class'] = strtolower(preg_replace('/[^A-Za-z0-9]/', '-', $id));
$datastreams[$id]['class'] = drupal_strtolower(preg_replace('/[^A-Za-z0-9]/', '-', $id));
}
catch (RepositoryException $e) {
}
catch (RepositoryException $e) {}
}
$variables['datastreams'] = $datastreams;
try {
$dc = $islandora_object['DC']->content;
//$dc_xml = simplexml_load_string($dc);
$dc_object = Dublin_Core::import_from_xml_string($dc);
$dc_array = $dc_object->as_formatted_array();
} catch (Exception $e) {
$dc_object = DublinCore::importFromXMLString($dc);
$dc_array = $dc_object->asArray();
}
catch (Exception $e) {
drupal_set_message(t('Error retrieving object %s %t', array('%s' => $islandora_object->id, '%t' => $e->getMessage())), 'error', FALSE);
}
$variables['dc_array'] = isset($dc_array) ? $dc_array : array();
@ -92,4 +122,4 @@ function islandora_preprocess_islandora_default(&$variables) {
if (isset($islandora_object['TN'])) {
$variables['islandora_thumbnail_url'] = $base_url . '/islandora/object/' . $islandora_object->id . '/datastream/TN/view';
}
}
}

21
xml/islandora_collection_policy.xml

@ -0,0 +1,21 @@
<collection_policy name="" xmlns="http://www.islandora.ca" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.islandora.ca http://syn.lib.umanitoba.ca/collection_policy.xsd">
<content_models>
<content_model dsid="ISLANDORACM" name="Collection" namespace="islandora:collection" pid="islandora:collectionCModel"/>
</content_models>
<search_terms>
<term field="dc.title">dc.title</term>
<term field="dc.creator">dc.creator</term>
<term default="true" field="dc.description">dc.description</term>
<term field="dc.date">dc.date</term>
<term field="dc.identifier">dc.identifier</term>
<term field="dc.language">dc.language</term>
<term field="dc.publisher">dc.publisher</term>
<term field="dc.rights">dc.rights</term>
<term field="dc.subject">dc.subject</term>
<term field="dc.relation">dc.relation</term>
<term field="dcterms.temporal">dcterms.temporal</term>
<term field="dcterms.spatial">dcterms.spatial</term>
<term field="fgs.DS.first.text">Full text</term>
</search_terms>
<relationship>isMemberOfCollection</relationship>
</collection_policy>
Loading…
Cancel
Save