Compare commits

...

No commits in common. '7.x-1.3' and '2.x' have entirely different histories.
7.x-1.3 ... 2.x

  1. 43
      .github/PULL_REQUEST_TEMPLATE.md
  2. 125
      .github/workflows/build-2.x.yml
  3. 26
      .github/workflows/gitlab-mirror.yml
  4. 6
      .gitignore
  5. 21
      .travis.yml
  6. 73
      CONTRIBUTING.md
  7. 15
      COPYRIGHT
  8. 339
      LICENSE
  9. 674
      LICENSE.txt
  10. 112
      README.md
  11. 105
      build.xml
  12. 1627
      build/Doxyfile
  13. 57
      composer.json
  14. 4
      config/install/islandora.settings.yml
  15. 13
      config/install/system.action.delete_media_and_file.yml
  16. 244
      config/schema/islandora.schema.yml
  17. 23
      css/islandora.admin.css
  18. 73
      css/islandora.base.css
  19. 3
      css/islandora.css
  20. 39
      css/islandora.objects.css
  21. 64
      css/islandora.print.css
  22. 43
      css/islandora.theme.css
  23. 6
      drush.services.yml
  24. BIN
      images/folder.png
  25. BIN
      images/print-icon.png
  26. 236
      includes/add_datastream.form.inc
  27. 148
      includes/admin.form.inc
  28. 136
      includes/authtokens.inc
  29. 121
      includes/breadcrumb.inc
  30. 57
      includes/content_model.autocomplete.inc
  31. 534
      includes/datastream.inc
  32. 268
      includes/datastream.version.inc
  33. 71
      includes/delete_datastream.form.inc
  34. 48
      includes/delete_object.form.inc
  35. 201
      includes/derivatives.inc
  36. 170
      includes/dublin_core.inc
  37. 974
      includes/ingest.form.inc
  38. 340
      includes/manage_deleted_objects.inc
  39. 171
      includes/metadata.inc
  40. 401
      includes/mime_detect.inc
  41. 27
      includes/mime_type.autocomplete.inc
  42. 56
      includes/object.entity_controller.inc
  43. 217
      includes/object_properties.form.inc
  44. 178
      includes/regenerate_derivatives.form.inc
  45. 843
      includes/solution_packs.inc
  46. 116
      includes/tuque.inc
  47. 385
      includes/tuque_wrapper.inc
  48. 997
      includes/utilities.inc
  49. 758
      islandora.api.php
  50. 201
      islandora.drush.inc
  51. 25
      islandora.info
  52. 33
      islandora.info.yml
  53. 287
      islandora.install
  54. 5
      islandora.libraries.yml
  55. 29
      islandora.links.action.yml
  56. 20
      islandora.links.menu.yml
  57. 2253
      islandora.module
  58. 12
      islandora.permissions.yml
  59. 16
      islandora.post_update.php
  60. 111
      islandora.routing.yml
  61. 118
      islandora.rules.inc
  62. 80
      islandora.services.yml
  63. 192
      islandora.tokens.inc
  64. 54
      islandora.views.inc
  65. 18
      js/add_print.js
  66. 21
      js/spin/LICENSE.txt
  67. 11
      js/spin/README.md
  68. 1
      js/spin/spin.min.js
  69. 58
      js/spinner.js
  70. 19
      migrate/tags.csv
  71. 73
      modules/islandora_advanced_search/CONTRIBUTING.md
  72. 339
      modules/islandora_advanced_search/LICENSE
  73. 261
      modules/islandora_advanced_search/README.md
  74. 37
      modules/islandora_advanced_search/css/islandora_advanced_search.form.css
  75. 111
      modules/islandora_advanced_search/css/islandora_advanced_search.pager.css
  76. BIN
      modules/islandora_advanced_search/docs/advanced_search_block_settings.png
  77. BIN
      modules/islandora_advanced_search/docs/basic-input.png
  78. BIN
      modules/islandora_advanced_search/docs/contextual_filter_settings.png
  79. BIN
      modules/islandora_advanced_search/docs/demo.gif
  80. BIN
      modules/islandora_advanced_search/docs/enable_index_hierarchy.png
  81. BIN
      modules/islandora_advanced_search/docs/enable_index_hierarchy_processor.png
  82. BIN
      modules/islandora_advanced_search/docs/exclude_facet_settings_exclude.png
  83. BIN
      modules/islandora_advanced_search/docs/exclude_facet_settings_url_alias.png
  84. BIN
      modules/islandora_advanced_search/docs/facet_block_settings.png
  85. BIN
      modules/islandora_advanced_search/docs/field_decedent_of.png
  86. BIN
      modules/islandora_advanced_search/docs/include_exclude_facets.png
  87. BIN
      modules/islandora_advanced_search/docs/include_exclude_facets_settings.png
  88. BIN
      modules/islandora_advanced_search/docs/islandora_advanced_search_settings.png
  89. BIN
      modules/islandora_advanced_search/docs/pager.png
  90. BIN
      modules/islandora_advanced_search/docs/pager_settings.png
  91. BIN
      modules/islandora_advanced_search/docs/sort_criteria.png
  92. BIN
      modules/islandora_advanced_search/docs/view_advanced_setting.png
  93. 13
      modules/islandora_advanced_search/islandora_advanced_search.info.yml
  94. 17
      modules/islandora_advanced_search/islandora_advanced_search.libraries.yml
  95. 6
      modules/islandora_advanced_search/islandora_advanced_search.links.menu.yml
  96. 89
      modules/islandora_advanced_search/islandora_advanced_search.module
  97. 17
      modules/islandora_advanced_search/islandora_advanced_search.routing.yml
  98. 113
      modules/islandora_advanced_search/js/islandora_advanced_search.admin.js
  99. 124
      modules/islandora_advanced_search/js/islandora_advanced_search.form.js
  100. 254
      modules/islandora_advanced_search/src/AdvancedSearchQuery.php
  101. Some files were not shown because too many files have changed in this diff Show More

43
.github/PULL_REQUEST_TEMPLATE.md

@ -0,0 +1,43 @@
**GitHub Issue**: (link)
* Other Relevant Links (Google Groups discussion, related pull requests,
Release pull requests, etc.)
# What does this Pull Request do?
A brief description of what the intended result of the PR will be and/or what
problem it solves.
# What's new?
A in-depth description of the changes made by this PR. Technical details and
possible side effects.
* Changes x feature to such that y
* Added x
* Removed y
* Does this change add any new dependencies?
* Does this change require any other modifications to be made to the repository
(i.e. Regeneration activity, etc.)?
* Could this change impact execution of existing code?
# How should this be tested?
A description of what steps someone could take to:
* Reproduce the problem you are fixing (if applicable)
* Test that the Pull Request does what is intended.
* Please be as detailed as possible.
* Good testing instructions help get your PR completed faster.
# Documentation Status
* Does this change existing behaviour that's currently documented?
* Does this change require new pages or sections of documentation?
* Who does this need to be documented for?
* Associated documentation pull request(s): ___ or documentation issue ___
# Additional Notes:
Any additional information that you think would be helpful when reviewing this
PR.
# Interested parties
Tag (@ mention) interested parties or, if unsure, @Islandora/committers

125
.github/workflows/build-2.x.yml

@ -0,0 +1,125 @@
name: CI
on:
push:
branches: [ 2.x ]
pull_request:
branches: [ 2.x ]
workflow_dispatch:
jobs:
build:
env:
DRUPAL_VERSION: ${{ matrix.drupal-version }}
SCRIPT_DIR: ${{ github.workspace }}/islandora_ci
DRUPAL_DIR: /opt/drupal
PHPUNIT_FILE: ${{ github.workspace }}/build_dir/phpunit.xml
runs-on: ubuntu-latest
continue-on-error: ${{ matrix.allowed_failure }}
strategy:
fail-fast: false
matrix:
php-versions: ["8.1", "8.2", "8.3"]
test-suite: ["kernel", "functional", "functional-javascript"]
drupal-version: ["10.1.x", "10.2.x", "10.3.x-dev"]
mysql: ["8.0"]
allowed_failure: [false]
exclude:
- php-versions: "8.3"
drupal-version: "10.1.x"
name: PHP ${{ matrix.php-versions }} | drupal ${{ matrix.drupal-version }} | mysql ${{ matrix.mysql }} | test-suite ${{ matrix.test-suite }}
services:
mysql:
image: mysql:${{ matrix.mysql }}
env:
MYSQL_ALLOW_EMPTY_PASSWORD: yes
MYSQL_DATABASE: drupal
ports:
- 3306:3306
activemq:
image: webcenter/activemq:5.14.3
ports:
- 8161:8161
- 61616:61616
- 61613:61613
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
path: build_dir
- name: Checkout islandora_ci
uses: actions/checkout@v4
with:
repository: islandora/islandora_ci
ref: github-actions
path: islandora_ci
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-versions }}
tools: composer:v2
- name: Setup Mysql client
run: |
sudo apt-get update
sudo apt-get remove -y mysql-client mysql-common
sudo apt-get install -y mysql-client
- name: Cache Composer dependencies
uses: actions/cache@v3
with:
path: /tmp/composer-cache
key: ${{ runner.os }}-${{ hashFiles('**/composer.lock') }}
- name: Setup Drupal
run: |
mkdir $DRUPAL_DIR
$SCRIPT_DIR/travis_setup_drupal.sh
cd $DRUPAL_DIR
chmod -R u+w web/sites/default
mkdir -p web/sites/simpletest/browser_output
- name: Setup composer paths
run: |
git -C "$GITHUB_WORKSPACE/build_dir" checkout -b github-testing
cd $DRUPAL_DIR
composer config repositories.local path "$GITHUB_WORKSPACE/build_dir"
composer config minimum-stability dev
composer require "islandora/islandora:dev-github-testing as dev-2.x"
- name: Install modules
run: |
cd $DRUPAL_DIR/web
drush --uri=127.0.0.1:8282 en -y islandora_audio islandora_breadcrumbs islandora_iiif islandora_image islandora_video islandora_text_extraction_defaults
- name: Copy PHPunit file
run: cp $PHPUNIT_FILE $DRUPAL_DIR/web/core/phpunit.xml
- name: Test scripts
run: $SCRIPT_DIR/travis_scripts.sh
- name: Start chromedriver
if: matrix.test-suite == 'functional-javascript'
run: |-
/usr/local/share/chromedriver-linux64/chromedriver \
--log-path=/tmp/chromedriver.log \
--verbose \
--allowed-ips= \
--allowed-origins=* &
- name: PHPUNIT tests
run: |
cd $DRUPAL_DIR/web/core
$DRUPAL_DIR/vendor/bin/phpunit --verbose --testsuite "${{ matrix.test-suite }}"
- name: Print chromedriver logs
if: matrix.test-suite == 'functional-javascript'
run: cat /tmp/chromedriver.log

26
.github/workflows/gitlab-mirror.yml

@ -0,0 +1,26 @@
name: Mirror and run GitLab CI
on:
push:
branches: [2.x]
tags: '*'
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Mirror + trigger CI
uses: SvanBoxel/gitlab-mirror-and-ci-action@master
with:
args: "https://git.drupalcode.org/project/islandora"
env:
FOLLOW_TAGS: "true"
FORCE_PUSH: "false"
GITLAB_HOSTNAME: "git.drupal.org"
GITLAB_USERNAME: "project_34868_bot"
GITLAB_PASSWORD: ${{ secrets.GITLAB_PASSWORD }}
GITLAB_PROJECT_ID: "34868"
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

6
.gitignore vendored

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

21
.travis.yml

@ -1,21 +0,0 @@
language: php
php:
- 5.3.3
- 5.4
branches:
only:
- /^7.x/
env:
- FEDORA_VERSION="3.5"
- FEDORA_VERSION="3.6.2"
- FEDORA_VERSION="3.7.0"
before_install:
- export ISLANDORA_DIR=$TRAVIS_BUILD_DIR
- $TRAVIS_BUILD_DIR/tests/scripts/travis_setup.sh
- cd $HOME/drupal-*
script:
- ant -buildfile sites/all/modules/islandora/build.xml lint
- $ISLANDORA_DIR/tests/scripts/line_endings.sh sites/all/modules/islandora
- drush coder-review --reviews=production,security,style,i18n,potx,sniffer islandora
- phpcpd --names *.module,*.inc,*.test sites/all/modules/islandora
- drush test-run --uri=http://localhost:8081 Islandora

73
CONTRIBUTING.md

@ -0,0 +1,73 @@
# Welcome!
If you are reading this document then you are interested in contributing to Islandora 8. All contributions are welcome: use-cases, documentation, code, patches, bug reports, feature requests, etc. You do not need to be a programmer to speak up!
We also have an IRC channel -- #islandora -- on freenode.net. Feel free to hang out there, ask questions, and help others out if you can.
Please note that this project operates under the [Islandora Community Code of Conduct](http://islandora.ca/codeofconduct). By participating in this project you agree to abide by its terms.
## Workflows
The Islandora 8 Tech Call meets each Wednesday at 1:00 PM Eastern, and the Islandora 8 User Call meets every second Thursday at 1:00 PM Eastern. Meeting notes and announcements are posted to the [Islandora community list](https://groups.google.com/forum/#!forum/islandora) and the [Islandora developers list](https://groups.google.com/forum/#!forum/islandora-dev). You can view meeting agendas, notes, and call-in information [here](https://github.com/Islandora/documentation/wiki#islandora-8-tech-calls). Anybody is welcome to join the calls, and add items to the agenda.
### Use cases
If you would like to submit a use case to the Islandora 8 project, please submit an issue [here](https://github.com/Islandora/documentation/issues/new) using the [Use Case template](https://github.com/Islandora/documentation/wiki/Use-Case-template), prepending "Use Case:" to the title of the issue.
### Documentation
You can contribute documentation in two different ways. One way is to create an issue [here](https://github.com/Islandora/documentation/issues/new), prepending "Documentation:" to the title of the issue. Another way is by pull request, which is the same process as [Contribute Code](https://github.com/Islandora/documentation/blob/master/CONTRIBUTING.md#contribute-code). All documentation resides in [`docs`](https://github.com/Islandora/documentation/tree/master/docs).
### Request a new feature
To request a new feature you should [open an issue in the Islandora 8 repository](https://github.com/Islandora/documentation/issues/new) or create a use case (see the _Use cases_ section above), and summarize the desired functionality. Prepend "Enhancement:" if creating an issue on the project repo, and "Use Case:" if creating a use case.
### Report a bug
To report a bug you should [open an issue in the Islandora 8 repository](https://github.com/Islandora/documentation/issues/new) that summarizes the bug. Prepend the label "Bug:" to the title of the issue.
In order to help us understand and fix the bug it would be great if you could provide us with:
1. The steps to reproduce the bug. This includes information about e.g. the Islandora version you were using along with the versions of stack components.
2. The expected behavior.
3. The actual, incorrect behavior.
Feel free to search the issue queue for existing issues (aka tickets) that already describe the problem; if there is such a ticket please add your information as a comment.
**If you want to provide a pull along with your bug report:**
That is great! In this case please send us a pull request as described in the section _Create a pull request_ below.
### Contribute code
Before you set out to contribute code you will need to have completed a [Contributor License Agreement](http://islandora.ca/sites/default/files/islandora_cla.pdf) or be covered by a [Corporate Contributor License Agreement](http://islandora.ca/sites/default/files/islandora_ccla.pdf). The signed copy of the license agreement should be sent to <mailto:community@islandora.ca>
_If you are interested in contributing code to Islandora but do not know where to begin:_
In this case you should [browse open issues](https://github.com/Islandora/documentation/issues) and check out [use cases](https://github.com/Islandora/documentation/labels/use%20case).
If you are contributing Drupal code, it must adhere to [Drupal Coding Standards](https://www.drupal.org/coding-standards); Travis CI will check for this on pull requests.
Contributions to the Islandora codebase should be sent as GitHub pull requests. See section _Create a pull request_ below for details. If there is any problem with the pull request we can work through it using the commenting features of GitHub.
* For _small patches_, feel free to submit pull requests directly for those patches.
* For _larger code contributions_, please use the following process. The idea behind this process is to prevent any wasted work and catch design issues early on.
1. [Open an issue](https://github.com/Islandora/documentation/issues), prepending "Enhancement:" in the title if a similar issue does not exist already. If a similar issue does exist, then you may consider participating in the work on the existing issue.
2. Comment on the issue with your plan for implementing the issue. Explain what pieces of the codebase you are going to touch and how everything is going to fit together.
3. Islandora committers will work with you on the design to make sure you are on the right track.
4. Implement your issue, create a pull request (see below), and iterate from there.
### Create a pull request
Take a look at [Creating a pull request](https://help.github.com/articles/creating-a-pull-request). In a nutshell you need to:
1. [Fork](https://help.github.com/articles/fork-a-repo) this repository to your personal or institutional GitHub account (depending on the CLA you are working under). Be cautious of which branches you work from though (you'll want to base your work off the default branch). See [Fork a repo](https://help.github.com/articles/fork-a-repo) for detailed instructions.
2. Commit any changes to your fork.
3. Send a [pull request](https://help.github.com/articles/creating-a-pull-request) using the [pull request template](https://github.com/Islandora/documentation/blob/master/.github/PULL_REQUEST_TEMPLATE.md) to the Islandora GitHub repository that you forked in step 1. If your pull request is related to an existing issue -- for instance, because you reported a [bug/issue](https://github.com/Islandora/documentation/issues) earlier -- prefix the title of your pull request with the corresponding issue number (e.g. `issue-123: ...`). Please also include a reference to the issue in the description of the pull. This can be done by using '#' plus the issue number like so '#123', also try to pick an appropriate name for the branch in which you're issuing the pull request from.
You may want to read [Syncing a fork](https://help.github.com/articles/syncing-a-fork) for instructions on how to keep your fork up to date with the latest changes of the upstream (official) repository.
## License Agreements
The Islandora Foundation requires that contributors complete a [Contributor License Agreement](http://islandora.ca/sites/default/files/islandora_cla.pdf) or be covered by a [Corporate Contributor License Agreement](http://islandora.ca/sites/default/files/islandora_ccla.pdf). The signed copy of the license agreement should be sent to <a href="mailto:community@islandora.ca?Subject=Contributor%20License%20Agreement" target="_top">community@islandora.ca</a>. This license is for your protection as a contributor as well as the protection of the Foundation and its users; it does not change your rights to use your own contributions for any other purpose. A list of current CLAs is kept [here](https://github.com/Islandora/islandora/wiki/Contributor-License-Agreements).

15
COPYRIGHT

@ -0,0 +1,15 @@
Copyright (C) 2015 The Islandora Foundation and contributors
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 2 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 as the file LICENSE.txt; if not, please see
http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.

339
LICENSE

@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) 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
this service 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 make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. 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.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the 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 a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE 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.
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
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the 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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision 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, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This 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.

674
LICENSE.txt

@ -1,674 +0,0 @@
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>.

112
README.md

@ -1,50 +1,84 @@
# Islandora [![Build Status](https://travis-ci.org/Islandora/islandora.png?branch=7.x)](https://travis-ci.org/Islandora/islandora) # Islandora
## Introduction [![Minimum PHP Version](https://img.shields.io/badge/php-%3E%3D%207.4-8892BF.svg?style=flat-square)](https://php.net/)
[![Build Status](https://github.com/islandora/islandora/actions/workflows/build-2.x.yml/badge.svg)](https://github.com/Islandora/islandora/actions)
Islandora Fedora Repository Module [![Contribution Guidelines](http://img.shields.io/badge/CONTRIBUTING-Guidelines-blue.svg)](./CONTRIBUTING.md)
[![LICENSE](https://img.shields.io/badge/license-GPLv2-blue.svg?style=flat-square)](./LICENSE)
For installation and customization instructions please see the [documentation and the DuraSpace Wiki](https://wiki.duraspace.org/display/ISLANDORA/Islandora). [![codecov](https://codecov.io/gh/Islandora/islandora/branch/2.x/graph/badge.svg)](https://codecov.io/gh/Islandora/islandora)
All bugs, feature requests and improvement suggestions are tracked at the [DuraSpace JIRA](https://jira.duraspace.org/browse/ISLANDORA). ## Introduction
This is the core module of Islandora's digital repository ecosystem. The `islandora` module provides:
- Fedora 5 integration via the [flysystem](https://drupal.org/project/flysystem) module
- Integration with the [context](https://drupal.org/project/context) module to control your digital repository's behaviour
- Publishing messages to a queue so they can be processed in the background
`islandora` contains several submodules and features:
- `islandora_core_feature` (**required**)
- Configuration required by the `islandora` module
- `islandora_image`
- Integrates with a [Houdini](https://github.com/Islandora/Crayfish/tree/dev/Houdini) (Imagemagick) server for image processing
- `islandora_audio` and `islandora_video`
- Integrate with a [Homarus](https://github.com/Islandora/Crayfish/tree/dev/Homarus) (`ffmpeg`) server for audio/video processing
- `islandora_text_extraction` and `islandora_text_extraction_defaults`
- Integrate with a [Hypercube](https://github.com/Islandora/Crayfish/tree/dev/Hypercube) (`tessseract` and `pdftotext`) server for text extraction
- `islandora_breadcrumbs`
- Provides breadcrumbs following collection structure
- `islandora_iiif`
- Provides IIIF manifests for repository content
## Requirements ## Requirements
This module requires the following modules/libraries: Installing via composer will download all required libraries and modules. However, for reference, `islandora` requires the following drupal modules:
* [Tuque](https://github.com/islandora/tuque)
Tuque is expected to be in one of two paths:
* sites/all/libraries/tuque (libraries directory may need to be created) - [context](http://drupal.org/project/context)
* islandora_folder/libraries/tuque - [search_api](http://drupal.org/project/search_api)
- [jsonld](http://drupal.org/project/jsonld)
- [jwt](http://drupal.org/project/jwt)
- [filehash](http://drupal.org/project/filehash)
- [prepopulate](http://drupal.org/project/prepopulate)
- [eva](http://drupal.org/project/eva)
- [features](http://drupal.org/project/features)
- [migrate_plus](http://drupal.org/project/migrate_plus)
- [migrate_source_csv](http://drupal.org/project/migrate_source_csv)
- [flysystem](http://drupal.org/project/flysystem)
More detailed requirements are outlined in the [Installing the Islandora Module](https://wiki.duraspace.org/display/ISLANDORA712/Installing+the+Islandora+Module) chapter of the documentation. It also requires the following PHP libraries:
### Optional Requirements - [Crayfish Commons](https://packagist.org/packages/islandora/crayfish-commons)
- [Stomp PHP](http://drupal.org/project/)
If you want to support languages other than English download and enable [String Translation](https://drupal.org/project/i18n), and follow our [guide](wiki/Multilingual-Support) for setting up additional languges. If you are using a Drush version less than 10.4 you will also need to install and enable [migrate_tools](http://drupal.org/project/migrate_tools) separately.
## Installation ## 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. It is to be noted that the `permit-upload-to-anonymous-user.xml` and `permit-apim-to-anonymous-user.xml` files do not need to be present unless requirements for anonymous ingesting are present. For a full digital repository solution, see our [installation documentation](https://islandora.github.io/documentation/installation/component_overview/).
You will also have to remove some default policies if you want full functionality as well. To download/enable just this module, use the following from the command line:
Remove deny-purge-datastream-if-active-or-inactive.xml to allow for purging of datastream versions. ```bash
$ composer require islandora/islandora
More detailed information can be found in the 'Set XACML Policies' in the [Installing Fedora](https://wiki.duraspace.org/display/ISLANDORA712/Installing+Fedora) chapter of the documentation. $ drush en islandora_core_feature
$ drush mim islandora_tags
```
## Configuration ## 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. ![image](https://user-images.githubusercontent.com/20773151/67234502-ac171900-f41b-11e9-964e-c7d4cfadbd67.png)
Drupal's cron can be run to remove expired authentication tokens. You can set the following configuration at `admin/config/islandora/core`:
- Broker URL
- The URL to your message broker (i.e. Activemq)
- JWT Expiry
- Set to increase the amount of time that authorization tokens remain valid. If you have a long running derivative processes or a migration, you may need to set this to be a very long time, e.g. `500d`. Otherwise, it's best to leave it alone.
- Gemini URL
- The URL to your Gemini server, which keeps track of where Islandora content is in Fedora.
- Fedora URL Display
- Selected bundles can display the Fedora URL for repository content.
### Customization ## Documentation
[Customize ingest forms](http://github.com/Islandora/islandora/wiki/Multi-paged-Ingest-Forms) Further documentation for this module is available on the [Islandora 8 documentation site](https://islandora.github.io/documentation/).
## Troubleshooting/Issues ## Troubleshooting/Issues
@ -53,17 +87,35 @@ Having problems or solved a problem? Check out the Islandora google groups for a
* [Islandora Group](https://groups.google.com/forum/?hl=en&fromgroups#!forum/islandora) * [Islandora Group](https://groups.google.com/forum/?hl=en&fromgroups#!forum/islandora)
* [Islandora Dev Group](https://groups.google.com/forum/?hl=en&fromgroups#!forum/islandora-dev) * [Islandora Dev Group](https://groups.google.com/forum/?hl=en&fromgroups#!forum/islandora-dev)
## Maintainers/Sponsors ## Maintainers
Current maintainers: Current maintainers:
* [Nick Ruest](https://github.com/ruebot) * [Islandora Technical Advisory Group](https://github.com/Islandora/islandora-community/wiki/Technical-Advisory-Group-%28TAG%29)
## Sponsors
* [American Philosophical Society](https://www.amphilsoc.org/)
* [Born-Digital, Inc.](https://www.born-digital.com/)
* [discoverygarden inc.](https://www.discoverygarden.ca/)
* [LYRASIS](https://www.lyrasis.org/)
* [McMaster University](https://www.mcmaster.ca/)
* [PALS](https://www.mnpals.org/)
* [University of Limerick](https://www.ul.ie/)
* [University of Manitoba](https://umanitoba.ca/)
* [UPEI](https://www.upei.ca/)
* [Simon Fraser University](https://www.sfu.ca/)
* [York University](https://www.yorku.ca/)
## Development ## Development
If you would like to contribute to this module, please check out our helpful [Documentation for Developers](https://github.com/Islandora/islandora/wiki#wiki-documentation-for-developers) info, as well as our [Developers](http://islandora.ca/developers) section on the Islandora.ca site. If you would like to contribute, please get involved by attending our weekly [Tech Call](https://github.com/Islandora/islandora-community/wiki/Weekly-Open-Tech-Call). We love to hear from you!
If you would like to contribute code to the project, you need to be covered by an Islandora Foundation [Contributor License Agreement](https://github.com/Islandora/islandora-community/wiki/Onboarding-Checklist#contributor-license-agreements) or [Corporate Contributor License Agreement](https://github.com/Islandora/islandora-community/wiki/Onboarding-Checklist#contributor-license-agreements). Please see the [Contributor License Agreements](https://github.com/Islandora/islandora-community/wiki/Contributor-License-Agreements) page on the islandora-community wiki for more information.
We recommend using the [islandora-playbook](https://github.com/Islandora-Devops/islandora-playbook) to get started.
## License ## License
[GPLv3](http://www.gnu.org/licenses/gpl-3.0.txt) [GPLv2](http://www.gnu.org/licenses/gpl-2.0.txt)

105
build.xml

@ -1,105 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="islandora" default="build">
<target name="build" depends="clean,prepare,php-eval,lint,phploc,code_sniff,phpcpd,pdepend,doxygen,phpcb,test,cc-process,cc-export" />
<target name="clean" description="Cleanup build artifacts">
<delete dir="${basedir}/build/test" />
<delete dir="${basedir}/build/logs" />
<delete dir="${basedir}/build/pdepend" />
<delete dir="${basedir}/build/api" />
<delete dir="${basedir}/build/code-browser" />
<delete dir="${basedir}/build/code_coverage" />
</target>
<target name="prepare" description="Prepares workspace for artifacts" >
<mkdir dir="${basedir}/build/test" />
<mkdir dir="${basedir}/build/logs" />
<mkdir dir="${basedir}/build/pdepend" />
<mkdir dir="${basedir}/build/api" />
<mkdir dir="${basedir}/build/code-browser" />
<mkdir dir="${basedir}/build/code_coverage" />
</target>
<target name="php-eval" description="Use php-eval to set the code_coverage_filter_files variable">
<exec executable="drush">
<arg line="php-eval &quot;variable_set('code_coverage_files', array('sites/all/modules/islandora/islandora.module', 'sites/all/modules/islandora/islandora.install', 'sites/all/modules/islandora/islandora.api.php', 'sites/all/modules/islandora/islandora.drush.inc', 'sites/all/modules/islandora/islandora.rules.inc', 'sites/all/modules/islandora/includes/add_datastream.form.inc', 'sites/all/modules/islandora/includes/admin.form.inc', 'sites/all/modules/islandora/includes/authtokens.inc', 'sites/all/modules/islandora/includes/breadcrumb.inc', 'sites/all/modules/islandora/includes/content_model.autocomplete.inc', 'sites/all/modules/islandora/includes/datastream.inc', 'sites/all/modules/islandora/includes/delete_datastream.form.inc', 'sites/all/modules/islandora/includes/delete_object.form.inc', 'sites/all/modules/islandora/includes/derivatives.inc', 'sites/all/modules/islandora/includes/dublin_core.inc', 'sites/all/modules/islandora/includes/ingest.form.inc', 'sites/all/modules/islandora/includes/manage_deleted_objects.inc', 'sites/all/modules/islandora/includes/metadata.inc', 'sites/all/modules/islandora/includes/mime_detect.inc', 'sites/all/modules/islandora/includes/object.entity_controller.inc', 'sites/all/modules/islandora/includes/object_properties.form.inc', 'sites/all/modules/islandora/includes/solution_packs.inc', 'sites/all/modules/islandora/includes/tuque.inc', 'sites/all/modules/islandora/includes/tuque_wrapper.inc', 'sites/all/modules/islandora/includes/utilities.inc', 'sites/all/modules/islandora/tests/datastream_validators.inc', 'sites/all/modules/islandora/tests/islandora_web_test_case.inc', 'sites/all/modules/islandora/theme/islandora-dublin-core-description.tpl.php', 'sites/all/modules/islandora/theme/islandora-dublin-core-display.tpl.php', 'sites/all/modules/islandora/theme/islandora-object-edit.tpl.php', 'sites/all/modules/islandora/theme/islandora-object-img-print.tpl.php', 'sites/all/modules/islandora/theme/islandora-object.tpl.php', 'sites/all/modules/islandora/theme/islandora-objects-grid.tpl.php', 'sites/all/modules/islandora/theme/islandora-objects-list.tpl.php', 'sites/all/modules/islandora/theme/islandora-objects.tpl.php', 'sites/all/modules/islandora/theme/theme.inc')); variable_set('code_coverage_modules', array());&quot;"/>
</exec>
</target>
<target name="lint" description="Perform syntax check of sourcecode files">
<apply executable="php" failonerror="true">
<arg value="-l" />
<fileset dir="${basedir}">
<include name="**/*.php" />
<include name="**/*.inc" />
<include name="**/*.module" />
<include name="**/*.install" />
<include name="**/*.test" />
<modified />
</fileset>
</apply>
</target>
<target name="phploc" description="Measure project size using PHPLOC">
<exec executable="phploc">
<arg line="--log-csv ${basedir}/build/logs/phploc.csv --exclude build --exclude css --exclude images --exclude xml --names *.php,*.module,*.inc,*.test,*.install ${basedir}" />
</exec>
</target>
<target name="code_sniff" description="Checks the code for Drupal coding standard violations" >
<exec executable="phpcs">
<arg line="--standard=Drupal --report=checkstyle --report-file=${basedir}/build/logs/checkstyle.xml --extensions=php,inc,test,module,install --ignore=build/,xml/,images/,css/ ${basedir}" />
</exec>
</target>
<target name="phpcpd" description="Copy/Paste code detection">
<exec executable="phpcpd">
<arg line="--log-pmd ${basedir}/build/logs/pmd-cpd.xml --exclude build --exclude css --exclude images --exclude xml --names *.php,*.module,*.inc,*.test,*.install ${basedir}" />
</exec>
</target>
<target name="pdepend" description="Calculate software metrics using PHP_Depend">
<exec executable="pdepend">
<arg line="--jdepend-xml=${basedir}/build/logs/jdepend.xml --jdepend-chart=${basedir}/build/pdepend/dependencies.svg --overview-pyramid=${basedir}/build/pdepend/overview-pyramid.svg ${basedir}"/>
</exec>
</target>
<target name="doxygen" description="Generate API documentation with doxygen" depends="prepare">
<exec executable="bash">
<arg line='-c "sed -i s/PROJECT_NUMBER\ \ \ \ \ \ \ \ \ =/PROJECT_NUMBER\ \ \ \ \ \ \ \ \ =\ `git log -1 --pretty=format:%h`/ build/Doxyfile"'/>
</exec>
<exec executable="doxygen">
<arg line="${basedir}/build/Doxyfile" />
</exec>
<exec executable="git">
<arg line="checkout ${basedir}/build/Doxyfile"/>
</exec>
</target>
<target name="phpcb" description="Aggregate tool output with PHP_CodeBrowser">
<exec executable="phpcb">
<arg line="--log ${basedir}/build/logs --source ${basedir} --output ${basedir}/build/code-browser"/>
</exec>
</target>
<target name="test">
<exec executable="bash">
<arg line='-c "php ../../../../scripts/run-tests.sh --xml ${basedir}/build/test Islandora"' />
</exec>
</target>
<target name="cc-process" description="Processes the code coverage output so it can be exported">
<exec executable="drush">
<arg line="cc-process all"/>
</exec>
</target>
<target name="cc-export" description="Generate a code coverage report for the simpletest run">
<exec executable="drush">
<arg line="cc-export latest --html --csv --tag-html --generate-index --path=${basedir}/build/code_coverage"/>
</exec>
</target>
</project>

1627
build/Doxyfile

File diff suppressed because it is too large Load Diff

57
composer.json

@ -0,0 +1,57 @@
{
"name": "islandora/islandora",
"description": "Core Islandora module",
"type": "drupal-module",
"keywords": ["Drupal", "Islandora"],
"homepage": "https://github.com/Islandora/islandora",
"support": {
"issues": "https://github.com/Islandora/documentation/issues"
},
"repositories": [
{
"type": "composer",
"url": "https://packages.drupal.org/8"
}
],
"require": {
"drupal/context": "^4 || ^5@RC",
"drupal/ctools": "^3.8 || ^4",
"drupal/eva" : "^3.0",
"drupal/file_replace": "^1.1",
"drupal/filehash": "^2 || ^3",
"drupal/flysystem" : "^2.0@alpha",
"drupal/jwt": "^1.1 || ^2",
"drupal/migrate_plus" : "^5.1 || ^6",
"drupal/migrate_source_csv" : "^3.4",
"drupal/prepopulate" : "^2.2",
"drupal/search_api": "^1.8",
"drupal/token" : "^1.3",
"islandora/chullo": "^2.0",
"islandora/fedora-entity-mapper": "^1.0",
"islandora/jsonld": "^2 || ^3",
"stomp-php/stomp-php": "4.* || ^5"
},
"require-dev": {
"phpunit/phpunit": "^6",
"squizlabs/php_codesniffer": "^2.7.1",
"drupal/coder": "*",
"sebastian/phpcpd": "*"
},
"suggest": {
"drupal/transliterate_filenames": "Sanitizes filenames when they are uploaded so they don't break your repository.",
"drupal/coi": "Some configuration fields work with Config Override Inspector."
},
"license": "GPL-2.0-or-later",
"authors": [
{
"name": "Islandora Foundation",
"email": "community@islandora.ca",
"role": "Owner"
},
{
"name": "Daniel Lamb",
"email": "dlamb@islandora.ca",
"role": "Maintainer"
}
]
}

4
config/install/islandora.settings.yml

@ -0,0 +1,4 @@
broker_url: 'tcp://localhost:61613'
jwt_expiry: '+2 hour'
delete_media_and_files: TRUE
gemini_pseudo_bundles: []

13
config/install/system.action.delete_media_and_file.yml

@ -0,0 +1,13 @@
langcode: en
status: true
dependencies:
enforced:
module:
- islandora
module:
- islandora
id: delete_media_and_file
label: 'Delete media and file(s)'
type: media
plugin: delete_media_and_file
configuration: { }

244
config/schema/islandora.schema.yml

@ -0,0 +1,244 @@
islandora.settings:
type: config_object
label: 'Islandora Core Settings'
mapping:
broker_url:
type: string
label: 'Url to connect to message broker'
fedora_rest_endpoint:
type: string
label: 'Url to Fedora instance'
broadcast_queue:
type: string
label: 'Queue that handles distributing messages amongst multiple recipients'
jwt_expiry:
type: string
label: 'How long JWTs should last before expiring.'
delete_media_and_files:
type: boolean
label: 'Node Delete with Media and Files'
redirect_after_media_save:
type: boolean
label: 'Redirect to node after media save.'
upload_form_location:
type: string
label: 'Upload Form Location'
upload_form_allowed_mimetypes:
type: string
label: 'Upload Form Allowed Extensions'
gemini_pseudo_bundles:
type: sequence
label: 'List of node, media and taxonomy terms that should include the linked Fedora URI'
sequence:
type: string
action.configuration.emit_node_event:
type: mapping
label: 'Emit a Node event to a queue/topic'
mapping:
queue:
type: text
label: 'Queue'
event:
type: text
label: 'Event Type'
action.configuration.emit_media_event:
type: mapping
label: 'Emit a Media event to a queue/topic'
mapping:
queue:
type: text
label: 'Queue'
event:
type: text
label: 'Event Type'
action.configuration.emit_file_event:
type: mapping
label: 'Emit a File event to a queue/topic'
mapping:
queue:
type: text
label: 'Queue'
event:
type: text
label: 'Event Type'
action.configuration.emit_term_event:
type: mapping
label: 'Emit a Taxonomy Term event to a queue/topic'
mapping:
queue:
type: text
label: 'Queue'
event:
type: text
label: 'Event Type'
action.configuration.delete_media_and_file:
type: action_configuration_default
label: 'Delete media and file'
condition.plugin.node_has_term:
type: condition.plugin
mapping:
uri:
type: text
label: 'Taxonomy Term URI'
logic:
type: string
label: 'Logic (AND or OR)'
tids:
type: sequence
sequence:
type: mapping
mapping:
target_id:
type: integer
label: The target taxonomy term IDs
condition.plugin.node_has_parent:
type: condition.plugin
mapping:
parent_nid:
type: integer
label: 'Parent node'
parent_reference_field:
type: string
label: 'Parent reference field'
condition.plugin.media_has_term:
type: condition.plugin
mapping:
uri:
type: text
label: 'Taxonomy Term URI'
logic:
type: string
label: 'Logic (AND or OR)'
condition.plugin.parent_node_has_term:
type: condition.plugin
mapping:
uri:
type: text
label: 'Taxonomy Term URI'
logic:
type: string
label: 'Logic (AND or OR)'
condition.plugin.file_uses_filesystem:
type: condition.plugin
mapping:
filesystems:
type: sequence
sequence:
type: string
condition.plugin.media_uses_filesystem:
type: condition.plugin
mapping:
filesystems:
type: sequence
sequence:
type: string
condition.plugin.media_has_mimetype:
type: condition.plugin
mapping:
mimetypes:
type: text
label: 'Mime types'
condition.plugin.content_entity_type:
type: condition.plugin
mapping:
types:
type: sequence
sequence:
type: string
condition.plugin.node_had_namespace:
type: condition.plugin
mapping:
namespace:
type: text
label: 'Namespace'
pid_field:
type: ignore
label: 'PID field'
field.formatter.settings.islandora_image:
type: field.formatter.settings.image
label: 'Islandora image field display format settings'
condition.plugin.islandora_entity_bundle:
type: condition.plugin
mapping:
bundles:
type: sequence
sequence:
type: string
condition.plugin.media_source_mimetype:
type: condition.plugin
mapping:
mimetype:
type: string
reaction.plugin.alter_jsonld_type:
type: islandora.reaction_plugin_with_saved
mapping:
source_field:
type: string
islandora.reaction_plugin_with_saved:
type: reaction.plugin
mapping:
saved:
type: boolean
label: Default config upstream; however, left undefined in the schema.
reaction.plugin.islandora_map_uri_predicate:
type: islandora.reaction_plugin_with_saved
mapping:
drupal_uri_predicate:
type: string
reaction.plugin.view_mode_alter:
type: islandora.reaction_plugin_with_saved
mapping:
mode:
type: string
label: The view mode to which to switch
islandora.reaction.actions:
type: islandora.reaction_plugin_with_saved
mapping:
actions:
type: sequence
sequence:
type: string
reaction.plugin.index:
type: islandora.reaction.actions
reaction.plugin.delete:
type: islandora.reaction.actions
reaction.plugin.derivative:
type: islandora.reaction.actions
field.widget.settings.media_track:
type: field.widget.settings.file_generic
field.field_settings.media_track:
type: field.field_settings.file
mapping:
languages:
type: string
field.storage_settings.media_track:
type: field.storage_settings.file

23
css/islandora.admin.css

@ -1,23 +0,0 @@
/**
* @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: 30%;
}
.islandora-solution-pack-fieldset table th:first-child,
.islandora-solution-pack-fieldset table td:first-child
{
width: 10%;
}

73
css/islandora.base.css

@ -1,73 +0,0 @@
/*
Document : islandora_basic_collection.base.css
Created on : May 23, 2012, 11:22:04 AM
Description:
Purpose of the stylesheet follows.
*/
.islandora img {
max-width: 100%;
*width: 100%;
}
.islandora * {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
/*
* These rules will display DTs/DDs as columns.
* Constructs must follow a key/value pair pattern.
* The three last declarations are meant to kill white space between DTs/DDs
* (result of inline-block styling)
*/
dl.islandora-inline-metadata {
margin: 0 auto;
letter-spacing: -0.31em;
*letter-spacing:normal;
word-spacing: -0.43em;
}
.islandora-inline-metadata dt {
margin-right: -1px;
width: 20.625%;
font-weight: bold;
padding-right: 0;
word-wrap: normal;
}
.islandora-inline-metadata dd {
width: 79.375%;
padding-left: 40px;
}
dl.islandora-metadata-fields {
width:100%;
}
.islandora-metadata dt,
.islandora-metadata dd {
border-top:1px solid #e5e5e5;
}
.islandora-metadata dt.first,
.islandora-metadata dd.first {
border-top:0;
}
/*
* In this rule, we reset the white-space (see hack above)
*/
.islandora-inline-metadata dt,
.islandora-inline-metadata dd {
display: inline-block;
*display: inline;
zoom: 1;
letter-spacing: normal;
word-spacing: normal;
vertical-align: top;
padding-top: 6px;
padding-bottom: 4px;
margin: 0;
}

3
css/islandora.css

@ -0,0 +1,3 @@
.container .islandora-media-items {
margin: 0;
}

39
css/islandora.objects.css

@ -1,39 +0,0 @@
/**
* @file
* Styles for rendering grids/lists of objects.
*/
.islandora-objects-display-switch {
float: right;
}
.islandora-objects-grid-item {
display: inline-block;
width: 20%;
min-width: 100px;
min-height: 180px;
display: -moz-inline-stack;
display: inline-block;
vertical-align: top;
margin: 1.5em 1.84%;
zoom: 1;
*display: inline;
_height: 180px;
}
.islandora-objects-list-item {
padding-bottom: 1.5em;
border-bottom: 1px solid #ddd;
}
.islandora-objects-list-item .islandora-object-thumb {
clear: left;
float: left;
padding: 3px 0 0;
text-align: center;
width: 100px;
}
.islandora-objects-list-item .islandora-object-caption, .islandora-objects-list-item .islandora-object-description {
margin: 0 0 0 130px;
padding-top: 2px;
padding-bottom: 2px;
}
.islandora-object-thumb img {
width: 100%;
}

64
css/islandora.print.css

@ -1,64 +0,0 @@
/**
* @file
* Print styling
*
* We provide some sane print styling for Drupal, hiding most visuals.
*/
#content a[href^="javascript:"]:after,
#content a[href^="#"]:after { /* Only display useful links. */
/* content: ""; */
}
#content abbr[title]:after { /* Add visible title after abbreviations. */
/* content: " (" attr(title) ")"; */
}
#content {
left: 0 !important;
width: 100% !important;
}
uncomment when ready to test printing
#header {
display: none !important;
}
#content { /* Un-float the content */
float: none !important;
width: 100% !important;
margin: 0 !important;
padding: 0 !important;
}
body,
#page,
#main,
#content { /* Turn off any background colors or images */
color: #000;
background-color: transparent !important;
background-image: none !important;
}
body.sidebar-first {
left: 0 !important;
width: 100% !important;
}
#skip-link,
#toolbar,
#navigation,
/* .region-sidebar-first, */
/* .region-sidebar-second, */
#header,
#footer,
.breadcrumb,
.tabs,
.action-links,
.links,
.book-navigation,
.forum-topic-navigation,
.pager,
.contextual-links-region,
.feed-icons { /* Hide sidebars and nav elements */
visibility: hidden !important;
display: none !important;
}

43
css/islandora.theme.css

@ -1,43 +0,0 @@
/*
Document : islandora_basic_collection.theme
Created on : May 23, 2012, 11:23:56 AM
Description:
Purpose of the stylesheet follows.
*/
/*
* Thumbnails float optionally to the left or right of descriptive lists.
*/
dl.islandora-object-tn {
float: left;
margin: 1.5em 0;
padding: 0 10px 0 0;
width: 20.8333%;
}
dl.islandora-object-fields {
border-top: 0px solid #ddd;
float: right;
margin: 1.5em 0;
width: 79.1666%;
}
.islandora-object-fields dt {
font-weight: bold;
}
.islandora-object-fields dt.first {
border-top: 0;
}
.islandora-object-fields dt,
.islandora-object-fields dd {
border-top: 1px solid #ddd;
padding: 6px 2% 4px;
}
.islandora-object-fields dt.first,
.islandora-object-fields dd.first {
border-top: 0;
}

6
drush.services.yml

@ -0,0 +1,6 @@
services:
islandora.commands:
class: \Drupal\islandora\Commands\IslandoraCommands
arguments: ['@entity_type.manager', '@current_user', '@account_switcher']
tags:
- { name: drush.command }

BIN
images/folder.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.0 KiB

BIN
images/print-icon.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

236
includes/add_datastream.form.inc

@ -1,236 +0,0 @@
<?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 AbstractObject $object
* The object to be deleted.
*
* @return array
* The drupal form definition.
*/
function islandora_add_datastream_form(array $form, array &$form_state, AbstractObject $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_id'] = $object->id;
// @deprecated Storing objects in $form_state is asking for a bad time...
// Causes issues with derivative generation when we try to use it.
$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',
),
'dsid_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, dashes and underscores. The following datastreams are defined by this content model but 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) {
$object = islandora_object_load($form_state['object_id']);
if (isset($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 certain 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();
foreach ($allowed_types as $mime) {
$allowed_extensions = array_merge($allowed_extensions, $mime_detect->getValidExtensions($mime));
}
$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 = islandora_object_load($form_state['object_id']);
$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 AbstractObject $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(AbstractObject $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);
}

148
includes/admin.form.inc

@ -1,148 +0,0 @@
<?php
/**
* @file
* This administration form for this module.
*/
/**
* 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');
drupal_add_css(drupal_get_path('module', 'islandora') . '/css/islandora.admin.css');
$url = islandora_system_settings_form_default_value('islandora_base_url', 'http://localhost:8080/fedora', $form_state);
$restrict_namespaces = islandora_system_settings_form_default_value('islandora_namespace_restriction_enforced', FALSE, $form_state);
$confirmation_message = islandora_admin_settings_form_repository_access_message($url);
$form = array(
'islandora_tabs' => array(
'#type' => 'vertical_tabs',
'islandora_general' => array(
'#type' => 'fieldset',
'#title' => t('General Configuration'),
'wrapper' => array(
'#prefix' => '<div id="islandora-url">',
'#suffix' => '</div>',
'#type' => 'markup',
'islandora_base_url' => array(
'#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', array(
'!confirmation_message' => $confirmation_message)),
'#required' => TRUE,
'#ajax' => array(
'callback' => 'islandora_update_url_div',
'wrapper' => 'islandora-url',
'effect' => 'fade',
'event' => 'blur',
'progress' => array('type' => 'throbber'),
),
),
),
'islandora_repository_pid' => array(
'#type' => 'textfield',
'#title' => t('Root Collection PID'),
'#default_value' => variable_get('islandora_repository_pid', 'islandora:root'),
'#description' => t('The PID of the Root Collection Object'),
'#required' => TRUE,
),
'islandora_use_datastream_cache_headers' => array(
'#type' => 'checkbox',
'#title' => t('Generate/parse datastream HTTP cache headers'),
'#description' => t('HTTP caching can reduce network traffic, by allowing clients to used cached copies.'),
'#default_value' => variable_get('islandora_use_datastream_cache_headers', TRUE),
),
),
'islandora_namespace' => array(
'#type' => 'fieldset',
'#title' => t('Namespaces'),
'islandora_namespace_restriction_enforced' => array(
'#type' => 'checkbox',
'#title' => t('Enforce namespace restrictions'),
'#description' => t("Allow administrator to restrict user's access to the PID namepaces listed below"),
'#default_value' => $restrict_namespaces,
),
'islandora_pids_allowed' => array(
'#type' => 'textarea',
'#title' => t('PID namespaces allowed in this Drupal install'),
'#description' => t('A list of PID namespaces, separated by spaces, that users are permitted to access from this Drupal installation. <br /> This could be more than a simple namespace, e.g. <b>demo:mydemos</b>. <br /> The namespace <b>islandora:</b> is reserved, and is always allowed.'),
'#default_value' => variable_get('islandora_pids_allowed', 'default: demo: changeme: ilives: islandora-book: books: newspapers: '),
'#states' => array(
'invisible' => array(
':input[name="islandora_namespace_restriction_enforced"]' => array('checked' => FALSE),
),
),
),
),
),
);
return system_settings_form($form);
}
/**
* Gets a message which describes if the repository is accessible.
*
* Also describes if the user is considered an authenticated user by the
* repository.
*
* @param string $url
* The url to the Fedora Repository.
*
* @return string
* A message describing the accessibility of the repository at the given url.
*/
function islandora_admin_settings_form_repository_access_message($url) {
$info = $dc = FALSE;
$connection = islandora_get_tuque_connection(NULL, $url);
if ($connection) {
try {
$info = $connection->api->a->describeRepository();
// If we are able to successfully call API-M::getDatastream, assume we are
// an authenticated user, as API-M is usally locked down.
$dc = $connection->api->m->getDatastream('fedora-system:ContentModel-3.0', 'DC');
}
catch (RepositoryException $e) {
// Ignore, we only testing to see what is accessible.
}
}
if ($info && $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']));
}
elseif ($info) {
$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 = 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));
}
return $confirmation_message;
}
/**
* 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(array $form, array $form_state) {
return $form['islandora_tabs']['islandora_general']['wrapper'];
}

136
includes/authtokens.inc

@ -1,136 +0,0 @@
<?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('ISLANDORA_AUTHTOKEN_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 - ISLANDORA_AUTHTOKEN_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 - ISLANDORA_AUTHTOKEN_TOKEN_TIMEOUT, '<')
->execute();
}

121
includes/breadcrumb.inc

@ -1,121 +0,0 @@
<?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 AbstractObject $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 = islandora_get_breadcrumbs_recursive($object->id, $object->repository);
array_pop($breadcrumbs);
$context = 'islandora';
drupal_alter('islandora_breadcrumbs', $breadcrumbs, $context, $object);
return $breadcrumbs;
}
/**
* Builds an array of drupal links for use in breadcrumbs.
*
* @todo Make fully recursive...
*
* @param string $pid
* The object id whose parent will be fetched for the next link.
* @param FedoraRepository $repository
* The fedora repository.
* @param array $context
* An associative array of context for internal use when recursing. Currently
* only used to track a single value:
* - level: The number of child-parent relationships to follow. Defaults to
* 10.
*
* @return array
* An array of links representing the breadcrumb trail, "root" first.
*/
function islandora_get_breadcrumbs_recursive($pid, FedoraRepository $repository, array &$context = NULL) {
// Before executing the query, we have a base case of accessing the top-level
// collection.
if ($context === NULL) {
$context['level'] = 10;
}
$root = variable_get('islandora_repository_pid', 'islandora:root');
if ($pid == $root) {
$title = 'Islandora Repository';
$mlid = db_select('menu_links', 'ml')
->condition('ml.link_path', 'islandora')
->fields('ml', array('mlid'))
->execute()
->fetchField();
if ($mlid) {
$link = menu_link_load($mlid);
$title = (isset($link['title']) ? $link['title'] : $title);
}
return array(
l(t('Home'), '<front>'),
l($title, 'islandora'),
);
}
else {
$query_string = 'select $parentObject $title $content from <#ri>
where (
<info:fedora/' . $pid . '> <fedora-model:label> $title
and $parentObject <fedora-model:hasModel> $content
and (
<info:fedora/' . $pid . '> <fedora-rels-ext:isMemberOfCollection> $parentObject
or <info:fedora/' . $pid . '> <fedora-rels-ext:isMemberOf> $parentObject
or <info:fedora/' . $pid . '> <fedora-rels-ext:isPartOf> $parentObject
)
and $parentObject <fedora-model:state> <info:fedora/fedora-system:def/model#Active>
)
minus $content <mulgara:is> <info:fedora/fedora-system:FedoraObject-3.0>
minus $parentObject <mulgara:is> <info:fedora/' . $pid . '>
order by $title desc';
$results = $repository->ri->itqlQuery($query_string);
if (count($results) > 0 && $context['level'] > 0) {
$parent = $results[0]['parentObject']['value'];
$this_title = $results[0]['title']['value'];
if (empty($this_title)) {
$this_title = t('-');
}
$context['level']--;
return array_merge(
islandora_get_breadcrumbs_recursive($parent, $repository, $context),
array(
l($this_title, "islandora/object/$pid"),
)
);
}
else {
// Add an non-link, as we don't know how to get back to the root, and
// render the last two links and break (on the next pass).
return array_merge(
islandora_get_breadcrumbs_recursive($root, $repository, $context),
array('...')
);
}
}
}

57
includes/content_model.autocomplete.inc

@ -1,57 +0,0 @@
<?php
/**
* @file
* Autocomplete functionality for content models in Islandora.
*/
/**
* Autocomplete the content model name.
*
* @param string $string
* A search string.
*
* @return string
* The rendered JSON results.
*/
function islandora_content_model_autocomplete($string) {
$content_models = islandora_get_content_model_names();
$output = array();
foreach ($content_models as $model => $label) {
if (preg_match("/{$string}/i", $label) !== 0) {
$output[$model] = $label;
}
}
return drupal_json_output($output);
}
/**
* Gets a map of form names suitable for use as select #options.
*/
function islandora_get_content_model_names() {
module_load_include('inc', 'islandora', 'includes/utilities');
$results = islandora_get_content_models();
$ret = array();
foreach ($results as $result) {
$ret[$result['pid']] = "{$result['label']} ({$result['pid']})";
}
return $ret;
}
/**
* Minor array transformation.
*
* @param array $content
* The array of results as returned from Tuque's RI query interface.
*
* @return array
* An array of results in a more usable format.
*/
function islandora_parse_query($content) {
$content_models = array();
foreach ($content as $model) {
$content_models[] = $model['object']['value'];
}
$content_models = array_unique($content_models);
$content_models = array_values($content_models);
return $content_models;
}

534
includes/datastream.inc

@ -1,534 +0,0 @@
<?php
/**
* @file
* Contains the admin form and callback functions for datastream manipulations.
*/
/**
* Callback to download the given datastream to the users computer.
*
* @param AbstractDatastream $datastream
* The datastream to download.
*/
function islandora_download_datastream(AbstractDatastream $datastream) {
islandora_view_datastream($datastream, TRUE);
}
/**
* Callback function to view or download a datastream.
*
* @note
* This function calls exit().
*
* @param AbstractDatastream $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.
* @param int $version
* The version of the datastream to display
*/
function islandora_view_datastream(AbstractDatastream $datastream, $download = FALSE, $version = NULL) {
// XXX: Certain features of the Devel module rely on the use of "shutdown
// handlers", such as query logging... The problem is that they might blindly
// add additional output which will break things if what is actually being
// output is anything but a webpage... like an image or video or audio or
// whatever the datastream is here.
$GLOBALS['devel_shutdown'] = FALSE;
if ($version !== NULL) {
if (isset($datastream[$version])) {
$datastream = $datastream[$version];
}
else {
return drupal_not_found();
}
}
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);
// Prevent adding on a duplicate extension.
$label = $datastream->label;
$extension_length = strlen($extension);
$duplicate_extension_position = strlen($label) > $extension_length ?
strripos($label, $extension, -$extension_length) :
FALSE;
$filename = $label;
if ($duplicate_extension_position === FALSE) {
$filename .= $extension;
}
header("Content-Disposition: attachment; filename=\"$filename\"");
}
$cache_check = islandora_view_datastream_cache_check($datastream);
if ($cache_check !== 200) {
if ($cache_check === 304) {
header('HTTP/1.1 304 Not Modified');
}
elseif ($cache_check === 412) {
header('HTTP/1.0 412 Precondition Failed');
}
}
islandora_view_datastream_set_cache_headers($datastream);
drupal_page_is_cacheable(FALSE);
// New content needed.
if ($cache_check === 200) {
// We need to see if the chunking is being requested. This will mainly
// happen with iOS video requests as they do not support any other way
// to receive content for playback.
$chunk_headers = FALSE;
if (isset($_SERVER['HTTP_RANGE'])) {
// Set headers specific to chunking.
$chunk_headers = islandora_view_datastream_set_chunk_headers($datastream);
}
// Try not to load the file into PHP memory!
// Close and flush ALL the output buffers!
while (@ob_end_flush()) {
};
if (isset($_SERVER['HTTP_RANGE'])) {
if ($chunk_headers) {
islandora_view_datastream_deliver_chunks($datastream, $chunk_headers);
}
}
else {
$datastream->getContent('php://output');
}
}
exit();
}
/**
* Parse "etags" from HTTP If-Match or If-None-Match headers.
*
* Parses from the CSV-like struture supported by HTTP headers into an array,
* so `"asdf", "fdsa", W/"2132"` should become an array containing the strings:
* - asdf
* - fdsa
* - 2132
*
* @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.24
* @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
*
* @param string $header_value
* The value from the headers.
*
* @return array
* An array containing all the etags present.
*/
function islandora_parse_http_match_headers($header_value) {
$matches = array();
// Match the CSV-like structure supported by the HTTP headers.
$count = preg_match_all('/(((W\/)?("?)(\*|.+?)\4)(, +)?)/', $header_value, $matches);
// The fifth sub-expression/group is which will contain the etags.
return $matches[5];
}
/**
* Validate cache headers.
*
* @param AbstractDatastream $datastream
* The datastream for which to check the request headers against.
*
* @return int
* An integer representing the HTTP response code. One of:
* - 200: Proceed as normal. (Full download).
* - 304: Resource hasn't changed; pass cache validation.
* - 412: Resource has changed; fail cache validation.
*
* @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
*/
function islandora_view_datastream_cache_check(AbstractDatastream $datastream) {
if (!variable_get('islandora_use_datastream_cache_headers', TRUE)) {
return 200;
}
// Let's assume that if we get here, we'll be able to complete the request.
$return = 200;
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
$modified_since = DateTime::createFromFormat('D, d M Y H:i:s e', $_SERVER['HTTP_IF_MODIFIED_SINCE']);
if ($datastream->createdDate->getTimestamp() - $modified_since->getTimestamp() > 0) {
// Changed!
return $return;
}
else {
$return = 304;
}
}
if ($return === 200 && isset($_SERVER['HTTP_IF_UNMODIFIED_SINCE'])) {
$unmodified_since = DateTime::createFromFormat('D, d M Y H:i:s e', $_SERVER['HTTP_IF_UNMODIFIED_SINCE']);
if ($datastream->createdDate->getTimestamp() !== $unmodified_since->getTimestamp()) {
// Changed!
$return = 412;
}
else {
return $return;
}
}
// Only consider Etags we have provided.
if (isset($datastream->checksum)) {
$tags = array();
foreach ($datastream as $offset => $version) {
if (isset($version->checksum)) {
$tags[$offset] = $version->checksum;
}
}
if ($return === 200 && isset($_SERVER['HTTP_IF_MATCH'])) {
$request_tags = islandora_parse_http_match_headers($_SERVER['HTTP_IF_MATCH']);
if (in_array('*', $request_tags) || count(array_intersect($tags, $request_tags)) > 0) {
// There's a match... Let things go ahead.
return $return;
}
else {
$return = 412;
}
}
if (in_array($return, array(200, 304), TRUE) && isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
$request_tags = islandora_parse_http_match_headers($_SERVER['HTTP_IF_NONE_MATCH']);
if (in_array('*', $request_tags) || count(array_intersect($tags, $request_tags)) > 0) {
$return = 304;
}
else {
$return = 200;
}
}
}
return $return;
}
/**
* Set various HTTP headers for caching.
*
* @param AbstractDatastream $datastream
* The datastream being viewed/downloaded.
*/
function islandora_view_datastream_set_cache_headers(AbstractDatastream $datastream) {
if (variable_get('islandora_use_datastream_cache_headers', TRUE)) {
// Force cache revalidation.
header('Expires: Sun, 19 Nov 1978 05:00:00 GMT');
$cache_control = array();
if ($datastream->parent->repository->api->connection->username == 'anonymous') {
$cache_control[] = 'public';
}
else {
$cache_control[] = 'private';
}
$cache_control[] = 'must-revalidate';
$cache_control[] = 'max-age=0';
header('Cache-Control: ' . implode(', ', $cache_control));
header('Last-Modified: ' . $datastream->createdDate->format('D, d M Y H:i:s \G\M\T'));
if (isset($datastream->checksum)) {
header("Etag: \"{$datastream->checksum}\"");
}
}
else {
header_remove('Cache-Control');
header_remove('Expires');
}
}
/**
* Get the human readable size of the given datastream.
*
* @param AbstractDatastream $datastream
* The datastream to check.
*
* @return string
* A human readable size of the given datastream, or '-' if the size could not
* be determined.
*/
function islandora_datastream_get_human_readable_size(AbstractDatastream $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) : '-';
}
/**
* Get either the 'view' or 'download' url for the given datastream if possible.
*
* @param AbstractDatastream $datastream
* The datastream to generated the url to.
* @param string $type
* One of:
* - download
* - view
* @param int $version
* (Optional) The version of the datastream to get a URL for.
*
* @return string
* either the 'view' or 'download' url for the given datastream.
*/
function islandora_datastream_get_url(AbstractDatastream $datastream, $type = 'download', $version = NULL) {
if ($version === NULL) {
$link = "islandora/object/{$datastream->parent->id}/datastream/{$datastream->id}/$type";
}
else {
$link = "islandora/object/{$datastream->parent->id}/datastream/{$datastream->id}/version/$version/$type";
$datastream = $datastream[$version];
}
if ($datastream->controlGroup == 'R') {
return $datastream->url;
}
else {
return $link;
}
}
/**
* Gets the delete link.
*
* @param AbstractDatastream $datastream
* The datastream to generated the url to.
*
* @return string
* Markup containing the link to the confirm form to delete the datastream.
*/
function islandora_datastream_get_delete_link(AbstractDatastream $datastream) {
$message = islandora_deprecated('7.x-1.2', 'Use the "islandora_datastream_delete_link" theme implementation.');
trigger_error(filter_xss($message), E_USER_DEPRECATED);
return theme('islandora_datastream_delete_link', array(
'datastream' => $datastream,
));
}
/**
* Gets the edit link.
*
* @param AbstractDatastream $datastream
* The datastream to generated the url to.
*
* @return string
* Markup containing the link to edit the datastream.
*/
function islandora_datastream_edit_get_link(AbstractDatastream $datastream) {
$message = islandora_deprecated('7.x-1.2', 'Use the "islandora_datastream_edit_link" theme implementation.');
trigger_error(filter_xss($message), E_USER_DEPRECATED);
return theme('islandora_datastream_edit_link', array(
'datastream' => $datastream,
));
}
/**
* Display the edit datastream page.
*
* @param AbstractDatastream $datastream
* The datastream to edit.
*/
function islandora_edit_datastream(AbstractDatastream $datastream) {
$edit_registry = module_invoke_all('islandora_edit_datastream_registry', $datastream->parent, $datastream);
$edit_count = count($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/{$datastream->parent->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);
}
}
/**
* Displays links to all the edit datastream registry items.
*
* @param array $edit_registry
* A list of 'islandora_edit_datastream_registry' values.
*
* @return array
* A Drupal renderable array containing the "edit" markup.
*/
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,
);
}
/**
* Get markup for a download link.
*
* @param AbstractDatastream $datastream
* The datastream for which to generate a link.
*
* @return string
* Either the link markup if the user has access or an empty string if the
* user is not allowed to see the given datastream.
*/
function islandora_datastream_get_download_link(AbstractDatastream $datastream) {
$message = islandora_deprecated('7.x-1.2', 'Use the "islandora_datastream_download_link" theme implementation.');
trigger_error(filter_xss($message), E_USER_DEPRECATED);
return theme('islandora_datastream_download_link', array(
'datastream' => $datastream,
));
}
/**
* Get markup for a view link.
*
* @param AbstractDatastream $datastream
* The datastream for which to generate a link.
*
* @return string
* Either the link markup if the user has access or a string containing the
* datastream ID if the user is not allowed to see the given datastream.
*/
function islandora_datastream_get_view_link(AbstractDatastream $datastream) {
$message = islandora_deprecated('7.x-1.2', 'Use the "islandora_datastream_view_link" theme implementation.');
trigger_error(filter_xss($message), E_USER_DEPRECATED);
return theme('islandora_datastream_view_link', array(
'datastream' => $datastream,
));
}
/**
* Set the headers for the chunking of our content.
*
* @param AbstractDatastream $datastream
* An AbstractDatastream representing a datastream on a Fedora object.
*
* @return bool
* TRUE if there are chunks to be returned, FALSE otherwise.
*/
function islandora_view_datastream_set_chunk_headers(AbstractDatastream $datastream) {
$file_uri = islandora_view_datastream_retrieve_file_uri($datastream);
// The meat of this has been taken from:
// http://mobiforge.com/design-development/content-delivery-mobile-devices.
$size = filesize($file_uri);
$length = $size;
$start = 0;
$end = $size - 1;
header("Accept-Ranges: 0-$length");
if (isset($_SERVER['HTTP_RANGE'])) {
$c_start = $start;
$c_end = $end;
// Extract the range string.
list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
// Make sure the client hasn't sent us a multibyte range.
if (strpos($range, ',') !== FALSE) {
// Not a valid range, notify the client.
header('HTTP/1.1 416 Requested Range Not Satisfiable');
header("Content-Range: bytes $start-$end/$size");
exit;
}
// If the range starts with an '-' we start from the beginning. If not, we
// forward the file pointer and make sure to get the end byte if specified.
if (strpos($range, '-') === 0) {
// The n-number of the last bytes is requested.
$c_start = $size - substr($range, 1);
}
else {
$range = explode('-', $range);
$c_start = $range[0];
$c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
}
/* Check the range and make sure it's treated according to the specs.
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
*/
// End bytes can not be larger than $end.
$c_end = ($c_end > $end) ? $end : $c_end;
// Validate the requested range and return an error if it's not correct.
if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
header('HTTP/1.1 416 Requested Range Not Satisfiable');
header("Content-Range: bytes $start-$end/$size");
exit;
}
$start = $c_start;
$end = $c_end;
// Calculate new content length.
$length = $end - $start + 1;
header('HTTP/1.1 206 Partial Content');
}
// Notify the client the byte range we'll be outputting.
header("Content-Range: bytes $start-$end/$size");
header("Content-Length: $length");
return array(
'start' => $start,
'end' => $end,
);
}
/**
* Deliver back the specified chunks of a file.
*
* @param AbstractDatastream $datastream
* An AbstractDatastream representing a datastream on a Fedora object.
* @param array $params
* An associate array containing the start and ending chunk bytes.
*/
function islandora_view_datastream_deliver_chunks(AbstractDatastream $datastream, $params) {
$file_uri = islandora_view_datastream_retrieve_file_uri($datastream);
// The meat of this has been taken from:
// http://mobiforge.com/design-development/content-delivery-mobile-devices.
$fp = @fopen($file_uri, 'rb');
fseek($fp, $params['start']);
// Start buffered download.
$buffer = 1024 * 8;
while (!feof($fp) && ($p = ftell($fp)) <= $params['end']) {
if ($p + $buffer > $params['end']) {
// In case we're only outputting a chunk, make sure we don't read past the
// length.
$buffer = $params['end'] - $p + 1;
}
// Reset time limit for big files.
set_time_limit(0);
echo fread($fp, $buffer);
}
fclose($fp);
}
/**
* Creates/returns the file URI for the content of a datastream for chunking.
*
* @param AbstractDatastream $datastream
* An AbstractDatastream representing a datastream on a Fedora object.
*
* @return string
* The URI of the file.
*/
function islandora_view_datastream_retrieve_file_uri(AbstractDatastream $datastream) {
$mime_detect = new MimeDetect();
$extension = $mime_detect->getExtension($datastream->mimetype);
$file_uri = 'temporary://chunk_' . $datastream->parent->id . '_' . $datastream->id . '_' . $datastream->createdDate->getTimestamp() . '.' . $extension;
if (!file_exists($file_uri)) {
$file = new stdClass();
$file->uri = $file_uri;
$file->filename = drupal_basename($file_uri);
$file->filemime = $datastream->mimeType;
$file->status = 0;
$datastream->getContent($file_uri);
file_save($file);
}
return $file_uri;
}

268
includes/datastream.version.inc

@ -1,268 +0,0 @@
<?php
/**
* @file
* The form displayed that shows the datastream version history.
*/
/**
* Function that returns markup for the datastream versions page.
*/
function islandora_datastream_version_table($datastream) {
module_load_include('inc', 'islandora', 'includes/datastream');
module_load_include('inc', 'islandora', 'includes/utilities');
$parent = $datastream->parent;
drupal_set_title(t("@dsid Previous Versions", array('@dsid' => $datastream->id)));
$audit_values = islandora_get_audit_trail($parent->id, $datastream->id);
$header = array();
$header[] = array('data' => t('Created Date'));
$header[] = array('data' => t('Size'));
$header[] = array('data' => t('Label'));
$header[] = array('data' => t('Responsibility'));
$header[] = array('data' => t('Mime type'));
$header[] = array('data' => t('Operations'), 'colspan' => '2');
$rows = array();
foreach ($datastream as $version => $datastream_version) {
$row = array();
$reponsibility = $parent->owner;
foreach ($audit_values as $audit_value) {
$internal = $datastream_version->createdDate;
if ($audit_value['date'] == $datastream_version->createdDate) {
$reponsibility = $audit_value['responsibility'];
}
}
$user = user_load_by_name($reponsibility);
if ($user) {
$user_id = $user->uid;
$user_val = l($reponsibility, "user/$user_id");
}
else {
$user_val = $reponsibility;
}
$row[] = array(
'class' => 'datastream-date',
'data' => theme('islandora_datastream_view_link', array(
'datastream' => $datastream,
'label' => $datastream_version->createdDate->format(DATE_RFC850),
'version' => $version,
)),
);
$row[] = array(
'class' => 'datastream-size',
'data' => islandora_datastream_get_human_readable_size($datastream_version),
);
$row[] = array(
'class' => 'datastream-label',
'data' => $datastream_version->label,
);
$row[] = array(
'class' => 'datastream-responsibility',
'data' => $user_val,
);
$row[] = array(
'class' => 'datastream-mime',
'data' => $datastream_version->mimeType,
);
$row[] = array(
'class' => 'datastream-delete',
'data' => theme('islandora_datastream_delete_link', array(
'datastream' => $datastream,
'version' => $version,
)),
);
$row[] = array(
'class' => 'datastream-revert',
'data' => theme('islandora_datastream_revert_link', array(
'datastream' => $datastream,
'version' => $version,
)),
);
$rows[] = $row;
}
return theme('table', array('header' => $header, 'rows' => $rows));
}
/**
* The admin delete datastream form.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
* @param AbstractDatastream $datastream
* The datastream to be deleted.
* @param string $version
* The version number of the datastream we are trying to delete.
*
* @return array
* The drupal form definition.
*/
function islandora_delete_datastream_version_form(array $form, array &$form_state, AbstractDatastream $datastream, $version) {
if (!isset($datastream[$version]) || count($datastream) < 2) {
return drupal_not_found();
}
$form_state['datastream'] = $datastream;
$form_state['version'] = $version;
return confirm_form($form,
t('Are you sure you want to delete version @version of the @dsid datastream?', array('@dsid' => $datastream->id, '@version' => $version)),
"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 AbstractDatastream 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_version_form_submit(array $form, array &$form_state) {
$datastream = $form_state['datastream'];
$version = $form_state['version'];
$datastream_id = $datastream->id;
$object = $datastream->parent;
try {
unset($datastream[$version]);
}
catch (Exception $e) {
drupal_set_message(t('Error deleting version %v of %s datastream from object %o %e', array(
'%v' => $version,
'%s' => $datastream_id,
'%o' => $object->label,
'%e' => $e->getMessage())), 'error');
}
drupal_set_message(t('%d datastream version successfully deleted from Islandora object %o', array(
'%d' => $datastream_id,
'%o' => $object->label)));
$form_state['redirect'] = "islandora/object/{$object->id}/datastream/{$datastream->id}/version";
}
/**
* The admin revert datastream form.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
* @param AbstractDatastream $datastream
* The datastream to be deleted.
* @param string $version
* The version number of the datastream we are trying to revert to.
*
* @return array
* The drupal form definition.
*/
function islandora_revert_datastream_version_form(array $form, array &$form_state, AbstractDatastream $datastream, $version) {
if (!isset($datastream[$version]) || count($datastream) < 2) {
return drupal_not_found();
}
$form_state['dsid'] = $datastream->id;
$form_state['object_id'] = $datastream->parent->id;
$form_state['version'] = $version;
return confirm_form($form,
t('Are you sure you want to revert to version @version of the @dsid datastream?', array('@dsid' => $datastream->id, '@version' => $version)),
"islandora/object/{$datastream->parent->id}",
"",
t('Revert'),
t('Cancel')
);
}
/**
* Submit handler for the revert datastream form.
*
* Reverts the given AbstractDatastream if possible.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*/
function islandora_revert_datastream_version_form_submit(array $form, array &$form_state) {
$islandora_object = islandora_object_load($form_state['object_id']);
$datastream_to_revert = $islandora_object[$form_state['dsid']];
$version = $form_state['version'];
// Create file holding specified datastream version, and set datastream to it.
$datastream_to_revert_to = $datastream_to_revert[$version];
if (in_array($datastream_to_revert->controlGroup, array('R', 'E'))) {
$datastream_to_revert->url = $datastream_to_revert_to->url;
}
else {
$filename = file_create_filename('datastream_temp_file', 'temporary://');
$datastream_to_revert_to->getContent($filename);
$datastream_to_revert->setContentFromFile($filename);
file_unmanaged_delete($filename);
}
if ($datastream_to_revert->mimeType != $datastream_to_revert_to->mimeType) {
$datastream_to_revert->mimeType = $datastream_to_revert_to->mimeType;
}
if ($datastream_to_revert->label != $datastream_to_revert_to->label) {
$datastream_to_revert->label = $datastream_to_revert_to->label;
}
drupal_set_message(t('%d datastream successfully reverted to version %v for Islandora object %o', array(
'%d' => $datastream_to_revert->id,
'%v' => $version,
'%o' => $islandora_object->label)));
$form_state['redirect'] = "islandora/object/{$islandora_object->id}/datastream/{$datastream_to_revert->id}/version";
}
/**
* Gets Audit datastream values from foxml.
*
* @param string $pid
* PID of parent object
*
* @return array
* Array of audit values
*/
function islandora_get_audit_trail($pid, $dsid) {
$url = variable_get('islandora_base_url', 'http://localhost:8080/fedora');
$connection = islandora_get_tuque_connection(NULL, $url);
$xml = $connection->api->m->getObjectXml($pid);
$simple_xml = simplexml_load_string($xml);
$fox_ns = "info:fedora/fedora-system:def/foxml#";
$audit_ns = 'info:fedora/fedora-system:def/audit#';
$foxml_nodes = $simple_xml->children($fox_ns);
foreach ($foxml_nodes as $node) {
if ($node->attributes()->ID == "AUDIT") {
$content = $node->datastreamVersion->xmlContent;
$audit_nodes = $content->children($audit_ns);
}
}
$audit_values = array();
if (isset($audit_nodes)) {
foreach ($audit_nodes->auditTrail->record as $record) {
if ($dsid == $record->componentID) {
$values['responsibility'] = $record->responsibility;
$values['date'] = $record->date;
$audit_values[] = $values;
}
}
}
return $audit_values;
}

71
includes/delete_datastream.form.inc

@ -1,71 +0,0 @@
<?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 AbstractDatastream $datastream
* The datastream to be deleted.
*
* @return array
* The drupal form definition.
*/
function islandora_delete_datastream_form(array $form, array &$form_state, AbstractDatastream $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 AbstractDatastream 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

@ -1,48 +0,0 @@
<?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 AbstractObject $object
* The object to be deleted.
*
* @return array
* The drupal form definition.
*/
function islandora_delete_object_form(array $form, array &$form_state, AbstractObject $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);
}

201
includes/derivatives.inc

@ -1,201 +0,0 @@
<?php
/**
* @file
* Defines functions used when constructing derivatives.
*/
/**
* Kicks off derivative functions based upon hooks and conditions.
*
* @param AbstractObject $object
* An AbstractObject representing a FedoraObject.
* @param array $options
* An array of parameters containing:
* - force: Bool denoting whether we are forcing the generation of
* derivatives.
* - source_dsid: (Optional) String of the datastream id we are generating
* from or NULL if it's the object itself.
* - destination_dsid: (Optional) String of the datastream id that is being
* created. To be used in the UI.
*
* @return array
* An array of messages describing the outcome of the derivative events.
* Each individual message array has the following structure:
* - success: Bool denoting whether the operation was successful.
* - messages: An array structure containing:
* - message: A string passed through t() describing the
* outcome of the operation.
* - message_sub: (Optional) Substitutions to be passed along to t() or
* watchdog.
* - type: A string denoting whether the output is to be
* drupal_set_messaged (dsm) or watchdogged (watchdog).
* - severity: (Optional) A severity level / status to be used when
* logging messages. Uses the defaults of drupal_set_message and
* watchdog if not defined.
*/
function islandora_do_derivatives(AbstractObject $object, array $options) {
module_load_include('inc', 'islandora', 'includes/utilities');
$options += array(
'force' => FALSE,
);
$hooks = islandora_invoke_hook_list(ISLANDORA_DERVIATIVE_CREATION_HOOK, $object->models, array($object));
uasort($hooks, 'drupal_sort_weight');
$results = array();
$hooks = islandora_filter_derivatives($hooks, $options, $object);
foreach ($hooks as $hook) {
if (isset($hook['file'])) {
require_once $hook['file'];
}
foreach ($hook['function'] as $function) {
if (function_exists($function)) {
$logging = call_user_func($function, $object, $options['force']);
if (!empty($logging)) {
$results[] = $logging;
}
}
else {
watchdog('islandora', 'Unable to call derivative function @function as it was not found!', array('@function' => $function), WATCHDOG_ERROR);
}
}
}
return $results;
}
/**
* Handles the logging of derivative messages.
*
* @param array $logging_results
* An array of messages describing the outcome of the derivative events.
* Each individual message array has the following structure:
* - success: Bool denoting whether the operation was successful.
* - messages: An array structure containing:
* - message: A string passed through t() describing the
* outcome of the operation.
* - message_sub: (Optional) Substitutions to be passed along to t() or
* watchdog.
* - type: A string denoting whether the output is to be
* drupal_set_messaged (dsm) or watchdogged (watchdog).
* - severity: (Optional) A severity level / status to be used when
* logging messages. Uses the defaults of drupal_set_message and
* watchdog if not defined.
*/
function islandora_derivative_logging(array $logging_results) {
foreach ($logging_results as $result) {
foreach ($result['messages'] as $message) {
if ($message['type'] === 'dsm') {
if (isset($message['severity']) && $message['severity'] != 'status') {
drupal_set_message(filter_xss(format_string($message['message'], isset($message['message_sub']) ? $message['message_sub'] : array())), $message['severity']);
}
else {
if (!isset($_SESSION['islandora_event_messages'])) {
$_SESSION['islandora_event_messages'] = array();
}
$_SESSION['islandora_event_messages'][] = array(
'message' => filter_xss(format_string($message['message'], isset($message['message_sub']) ? $message['message_sub'] : array())),
'severity' => 'status',
);
drupal_set_message(l(t('Derivatives successfully created.'), 'islandora/event-status'), 'status', FALSE);
}
}
else {
// We know what we are doing here. Passing through the translated
// message and the substitutions needed. We are using
// call_user_func until such time as the @ignore changes
// are merged into the standard release for Coder.
call_user_func('watchdog', 'islandora_derivatives', $message['message'], isset($message['message_sub']) ? $message['message_sub'] : array(), isset($message['severity']) ? $message['severity'] : WATCHDOG_NOTICE);
}
}
}
}
/**
* Kicks off derivative functions based upon hooks and conditions.
*
* @param AbstractObject $object
* An AbstractObject representing a FedoraObject.
* @param array $options
* An array of parameters containing:
* - force: Bool denoting whether we are forcing the generation of
* derivatives.
* - source_dsid: (Optional) String of the datastream id we are generating
* from or NULL if it's the object itself.
* - destination_dsid: (Optional) String of the datastream id that is being
* created. To be used in the UI.
*
* @return array
* An array of operations to be called from within a batch.
*/
function islandora_do_batch_derivatives(AbstractObject $object, array $options) {
module_load_include('inc', 'islandora', 'includes/utilities');
$options += array(
'force' => FALSE,
);
$hooks = islandora_invoke_hook_list(ISLANDORA_DERVIATIVE_CREATION_HOOK, $object->models, array($object));
uasort($hooks, 'drupal_sort_weight');
$operations = array();
$hooks = islandora_filter_derivatives($hooks, $options, $object);
foreach ($hooks as $hook) {
$file = FALSE;
if (isset($hook['file'])) {
$file = $hook['file'];
}
foreach ($hook['function'] as $function) {
$operations[] = array('islandora_derivative_perform_batch_operation', array(
$function,
$file,
$object->id,
$options['force']),
);
}
}
return $operations;
}
/**
* Filter the derivative functions to only call those which are valid.
*
* @param array $hooks
* An array of hooks to be filtered depending on options.
* @param array $options
* An array of options for the derivative generation.
* @param AbstractObject $object
* An AbstractObject representing an object within Fedora.
*
* @return array
* Returns the filtered array of hooks to be ran.
*/
function islandora_filter_derivatives($hooks, $options, AbstractObject $object) {
if (array_key_exists('source_dsid', $options)) {
$hooks = array_filter($hooks, function ($filter_hook) use ($options) {
return array_key_exists('source_dsid', $filter_hook) &&
$filter_hook['source_dsid'] == $options['source_dsid'];
});
}
if (array_key_exists('destination_dsid', $options)) {
$hooks = array_filter($hooks, function ($filter_hook) use ($options) {
return array_key_exists('destination_dsid', $filter_hook) &&
$filter_hook['destination_dsid'] == $options['destination_dsid'];
});
}
// Do a final filtering to make sure that the source DSID exists on the object
// where needed. Using a defined function as opposed to the way above as
// it seems to break PHPCS as of 1.4.8.
$filter_function = function ($filter_hook) use ($object) {
$to_return = FALSE;
if (array_key_exists('source_dsid', $filter_hook)) {
if ($filter_hook['source_dsid'] != NULL) {
if (isset($object[$filter_hook['source_dsid']])) {
$to_return = TRUE;
}
}
else {
$to_return = TRUE;
}
}
return $to_return;
};
$hooks = array_filter($hooks, $filter_function);
return $hooks;
}

170
includes/dublin_core.inc

@ -1,170 +0,0 @@
<?php
/**
* @file
* 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 DublinCore {
public $dc = array(
'dc:title' => array(),
'dc:creator' => array(),
'dc:subject' => array(),
'dc:description' => array(),
'dc:publisher' => array(),
'dc:contributor' => array(),
'dc:date' => array(),
'dc:type' => array(),
'dc:format' => array(),
'dc:identifier' => array(),
'dc:source' => array(),
'dc:language' => array(),
'dc:relation' => array(),
'dc:coverage' => array(),
'dc:rights' => array(),
);
public $owner;
/**
* Constructor.
*
* @param string $dc_xml
* The Dublin Core XML.
*/
public function __construct($dc_xml = NULL) {
if (!empty($dc_xml)) {
$this->dc = self::importFromXMLString($dc_xml);
}
}
/**
* Add an element.
*
* @param string $element_name
* The name of the element to add.
* @param string $value
* The value of the element to add.
*/
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 given values.
*
* @param string $element_name
* The name of the elements to set.
* @param mixed $values
* The values of the set the elements too.
*/
public function setElement($element_name, $values) {
if (is_array($values)) {
$this->dc[$element_name] = $values;
}
elseif (is_string($values)) {
$this->dc[$element_name] = array($values);
}
}
/**
* Serialize this object as an XML string.
*
* @return string
* The serialized XML.
*/
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/');
foreach ($this->dc as $dc_element => $values) {
if (is_array($values) && !empty($values)) {
foreach ($values as $value) {
$new_item = $dc_xml->createElement($dc_element, $value);
$oai_dc->appendChild($new_item);
}
}
else {
$new_item = $dc_xml->createElement($dc_element);
$oai_dc->appendChild($new_item);
}
}
$dc_xml->appendChild($oai_dc);
return $dc_xml->saveXML();
}
/**
* Serializes this object as an array.
*
* @return array
* The serialized object.
*/
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.
if (is_array($values)) {
$value = '';
$i = 0;
foreach ($values as $piece) {
if (!empty($piece)) {
if ($i++) {
$value .= ", ";
}
$value .= $piece;
}
}
}
else {
$value = $values;
}
$dc_label = explode(':', $field);
$element_label = drupal_ucfirst($dc_label[1]);
$i18n_object_id = drupal_strtolower($element_label);
$dc_array[$field]['label'] = function_exists('i18n_string') ?
i18n_string("islandora:dc:{$i18n_object_id}:label", $element_label) :
$element_label;
$dc_array[$field]['value'] = filter_xss($value);
$dc_array[$field]['class'] = drupal_strtolower(preg_replace('/[^A-Za-z0-9]/', '-', $field));
$dc_array[$field]['dcterms'] = preg_replace('/^dc/', 'dcterms', $field);
}
}
}
return $dc_array;
}
/**
* Creates a new instance of the class by parsing dc_xml.
*
* @param string $dc_xml
* Dublin Core XML.
*
* @return DublinCore
* The instantiated object.
*/
public static function importFromXMLString($dc_xml) {
$dc_doc = new DomDocument();
if (!empty($dc_xml) && $dc_doc->loadXML($dc_xml)) {
$oai_dc = $dc_doc->getElementsByTagNameNS('http://purl.org/dc/elements/1.1/', '*');
$new_dc = new DublinCore();
foreach ($oai_dc as $child) {
if (isset($new_dc->dc[$child->nodeName])) {
array_push($new_dc->dc[$child->nodeName], $child->nodeValue);
}
}
return $new_dc;
}
return NULL;
}
}

974
includes/ingest.form.inc

@ -1,974 +0,0 @@
<?php
/**
* @file
* Defines the multi-page ingest form and any relevant hooks and functions.
*/
/**
* Checks if the given configuration can be used to display the ingest form.
*
* @param array $configuration
* The list of key/value pairs of configuration.
*
* @return bool
* TRUE if the give configuration defines one or more form steps, FALSE
* otherwise.
*/
function islandora_ingest_can_display_ingest_form(array $configuration) {
$form_state = array();
islandora_ingest_form_init_form_state_storage($form_state, $configuration);
$form_steps = islandora_ingest_form_get_form_steps($form_state);
// Forget the stubbed steps for the remainder of this request.
drupal_static_reset('islandora_ingest_form_get_steps');
return count($form_steps) > 0;
}
/**
* 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
* - parent: The parent of the child to be ingested. This is needed for XACML
* to correctly apply the parent's POLICY to children.
*
* @return array
* The form definition of the current step.
*/
function islandora_ingest_form(array $form, array &$form_state, array $configuration) {
try {
islandora_ingest_form_init_form_state_storage($form_state, $configuration);
return islandora_ingest_form_execute_step($form, $form_state);
}
catch (Exception $e) {
watchdog(
'islandora',
'Exception during ingest form processing with Message: "@exception", and Trace: @trace',
array('@exception' => $e->getMessage(), '@trace' => $e->getTraceAsString()),
WATCHDOG_ERROR
);
drupal_set_message($e->getMessage(), 'error');
return array(array(
'#markup' => l(t('Back'), 'javascript:window.history.back();', array('external' => TRUE))));
}
}
/**
* 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'])) {
$objects = isset($configuration['objects']) ? $configuration['objects'] : array();
if (empty($objects)) {
$objects[] = islandora_ingest_form_prepare_new_object($configuration);
}
$configuration['models'] = isset($configuration['models']) ? $configuration['models'] : array();
// Make sure the models actually exist.
foreach ($configuration['models'] as $key => $model) {
if (!islandora_object_load($model)) {
unset($configuration['models'][$key]);
}
}
// No need to persist the 'objects' within the configuration.
unset($configuration['objects']);
// Required for step hooks.
$form_state['islandora'] = array(
'step_id' => NULL,
'objects' => $objects,
'shared_storage' => $configuration,
'step_storage' => array(),
);
// Must be called after $form_state['islandora'] is initialized, otherwise,
// the values in 'islandora' would not be availible to the step hooks.
$form_state['islandora']['step_id'] = islandora_ingest_form_get_first_step_id($form_state);
}
}
/**
* Get the first step ID.
*
* @param array $form_state
* The Drupal form state.
*
* @return string
* The 'id' of the very first step.
*/
function islandora_ingest_form_get_first_step_id(array &$form_state) {
$steps = islandora_ingest_form_get_steps($form_state);
$keys = array_keys($steps);
return array_shift($keys);
}
/**
* Get the last step ID.
*
* @param array $form_state
* The Drupal form state.
*
* @return string
* The 'id' of the very last step.
*/
function islandora_ingest_form_get_last_step_id(array &$form_state) {
$steps = islandora_ingest_form_get_steps($form_state);
$keys = array_keys($steps);
return array_pop($keys);
}
/**
* Prepares a new object based on the given configuration.
*
* @param array $configuration
* The list of key/value pairs of configuration.
*
* @return NewFedoraObject
* The new object.
*/
function islandora_ingest_form_prepare_new_object(array $configuration) {
module_load_include('inc', 'islandora', 'includes/utilities');
if (empty($configuration['object'])) {
$message = islandora_deprecated('7.x-1.2', t('Please use "objects" as the default ingest form configuration property.'));
trigger_error(filter_xss($message), E_USER_DEPRECATED);
// ID is more specific than namespace so it will take precedence.
$id = isset($configuration['namespace']) ? $configuration['namespace'] : 'islandora';
$id = isset($configuration['id']) ? $configuration['id'] : $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']);
return islandora_prepare_new_object($id, $label, array(), array(), $relationships);
}
return $configuration['object'];
}
/**
* Gets the given/current step.
*
* If the current step is not defined it's assumed that all steps have executed.
*
* @param array $form_state
* The Drupal form state.
* @param string $step_id
* The ID of the step. The current step is returned if no step ID is given.
*
* @return array
* The given/current step if found, NULL otherwise.
*/
function islandora_ingest_form_get_step(array &$form_state, $step_id = NULL) {
$step_id = isset($step_id) ? $step_id : islandora_ingest_form_get_current_step_id($form_state);
$steps = islandora_ingest_form_get_steps($form_state);
if (isset($step_id) && isset($steps[$step_id])) {
return $steps[$step_id];
}
return NULL;
}
/**
* Gets the next step.
*
* If the current step is not defined it's assumed that all steps have executed.
*
* @param array $form_state
* The Drupal form state.
* @param array $step
* The step relative to the result, if not provided the current step is used.
*
* @return array|null
* The next step if found, NULL otherwise.
*/
function islandora_ingest_form_get_next_step(array &$form_state, array $step = NULL) {
$step = isset($step) ? $step : islandora_ingest_form_get_step($form_state);
$next_step_id = islandora_ingest_form_get_next_step_id($form_state, $step['id']);
return isset($next_step_id) ? islandora_ingest_form_get_step($form_state, $next_step_id) : NULL;
}
/**
* Gets the previous step.
*
* If the current step is not defined it's assumed that all steps have executed.
*
* @param array $form_state
* The Drupal form state.
* @param array $step
* The step relative to the result, if not provided the current step is used.
*
* @return array|null
* The next step if found, NULL otherwise.
*/
function islandora_ingest_form_get_previous_step(array &$form_state, array $step = NULL) {
$step = isset($step) ? $step : islandora_ingest_form_get_step($form_state);
$previous_step_id = islandora_ingest_form_get_previous_step_id($form_state, $step['id']);
return isset($previous_step_id) ? islandora_ingest_form_get_step($form_state, $previous_step_id) : NULL;
}
/**
* Gets the ID of the current step.
*
* If the current step is not defined it's assumed that all steps have executed.
*
* @param array $form_state
* The Drupal form state.
*
* @return string
* The step ID.
*/
function islandora_ingest_form_get_current_step_id(array &$form_state) {
return $form_state['islandora']['step_id'];
}
/**
* Gets the ID of the next step.
*
* If the current step is not defined it's assumed that all steps have executed.
*
* @param array $form_state
* The Drupal form state.
* @param string $step_id
* The ID of the step relative to the result, if not provided the current
* step_id is used.
*
* @return string
* The next step ID if found, NULL otherwise.
*/
function islandora_ingest_form_get_next_step_id(array &$form_state, $step_id = NULL) {
$step_id = isset($step_id) ? $step_id : islandora_ingest_form_get_current_step_id($form_state);
$step_ids = array_keys(islandora_ingest_form_get_steps($form_state));
$index = array_search($step_id, $step_ids);
$count = count($step_ids);
if ($index !== FALSE && ++$index < $count) {
return $step_ids[$index];
}
return NULL;
}
/**
* Gets the ID of the previous step.
*
* If the current step is not defined it's assumed that all steps have executed.
* In such cases the last step will be returned.
*
* @param array $form_state
* The Drupal form state.
* @param string $step_id
* The ID of the step relative to the result, if not provided the current
* step_id is used.
*
* @return string
* The previous step ID if found, NULL otherwise.
*/
function islandora_ingest_form_get_previous_step_id(array &$form_state, $step_id = NULL) {
$step_id = isset($step_id) ? $step_id : islandora_ingest_form_get_current_step_id($form_state);
// If the current step is not defined it's assumed that all steps have
// executed. So return the very last step.
if ($step_id == NULL) {
return islandora_ingest_form_get_last_step_id($form_state);
}
$step_ids = array_keys(islandora_ingest_form_get_steps($form_state));
$index = array_search($step_id, $step_ids);
if ($index !== FALSE && --$index >= 0) {
return $step_ids[$index];
}
return NULL;
}
/**
* Increments the current step if possible.
*
* @param array $form_state
* The Drupal form state.
*/
function islandora_ingest_form_increment_step(array &$form_state) {
// When going to the next step rebuild the list of steps as the submit
// of the current step could have added/removed a step.
drupal_static_reset('islandora_ingest_form_get_steps');
$next_step_id = islandora_ingest_form_get_next_step_id($form_state);
islandora_ingest_form_stash_info($form_state);
$form_state['islandora']['step_id'] = $next_step_id;
islandora_ingest_form_grab_info($form_state);
}
/**
* Decrement the current step if possible.
*
* @param array $form_state
* The Drupal form state.
*/
function islandora_ingest_form_decrement_step(array &$form_state) {
$previous_step_id = islandora_ingest_form_get_previous_step_id($form_state);
// Don't decrement passed the first step.
if (isset($previous_step_id)) {
islandora_ingest_form_stash_info($form_state);
$form_state['islandora']['step_id'] = $previous_step_id;
islandora_ingest_form_grab_info($form_state);
}
}
/**
* Executes the current step.
*
* Builds the form definition and appends on any additonal elements required
* for the step to function.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
* @param string $step_id
* The ID of the step relative to the result, if not provided the current
* step_id is used.
*
* @return array
* The form definition of the current step.
*/
function islandora_ingest_form_execute_step(array $form, array &$form_state, $step_id = NULL) {
// Load any required files for the current step.
islandora_ingest_form_load_include($form_state);
$step = isset($step_id) ? islandora_ingest_form_get_step($form_state) : islandora_ingest_form_get_step($form_state, $step_id);
switch ($step['type']) {
case 'callback':
// Execute all the consecutive callbacks, and move then attempt to process
// the next step.
islandora_ingest_form_execute_consecutive_callback_steps($form, $form_state, $step);
return islandora_ingest_form_execute_step($form, $form_state);
case 'form':
return islandora_ingest_form_execute_form_step($form, $form_state, $step);
case 'batch':
// @todo Implement if possible.
break;
}
return array();
}
/**
* Execute the given 'form' step.
*
* Assumes the given step is a 'form' step.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
* @param array $step
* The step we are executing.
*
* @return array
* The form definition of the given step.
*/
function islandora_ingest_form_execute_form_step(array $form, array &$form_state, array $step) {
$args = array($form, &$form_state);
$args = isset($step['args']) ? array_merge($args, $step['args']) : $args;
$shared_storage = islandora_ingest_form_get_shared_storage($form_state);
// Build the form step.
$form = call_user_func_array($step['form_id'], $args);
// Since the list of steps depends on the shared storage we will rebuild the
// list of steps if the shared storage has changed. This must be done before
// stepifying, so the prev/next buttons get updated.
if ($shared_storage != islandora_ingest_form_get_shared_storage($form_state)) {
drupal_static_reset('islandora_ingest_form_get_steps');
}
return islandora_ingest_form_stepify($form, $form_state, $step);
}
/**
* Execute the given 'callback' step and any consecutive 'callback' steps.
*
* Assumes the given step is a 'callback' step.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
* @param array $step
* The step that execution begins from.
*/
function islandora_ingest_form_execute_consecutive_callback_steps(array $form, array &$form_state, array $step) {
do {
islandora_ingest_form_execute_callback_step($form, $form_state, $step);
islandora_ingest_form_increment_step($form_state);
$step = islandora_ingest_form_get_step($form_state);
} while (isset($step) && $step['type'] == 'callback');
}
/**
* Execute the given 'callback' step.
*
* Assumes the given step is a 'callback' step.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
* @param array $step
* The step currently being executed.
*/
function islandora_ingest_form_execute_callback_step(array $form, array &$form_state, array $step) {
$args = array(&$form_state);
$args = isset($step['do_function']['args']) ? array_merge($args, $step['do_function']['args']) : $args;
if (isset($step['do_function']['file'])) {
require_once drupal_get_path('module', $step['module']) . "/" . $step['do_function']['file'];
}
call_user_func_array($step['do_function']['function'], $args);
}
/**
* Undo the given 'callback' step and any consecutive 'callback' steps.
*
* Assumes the given $step is a 'callback' step.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
* @param array $step
* The step that execution begins from.
*/
function islandora_ingest_form_undo_consecutive_callback_steps(array $form, array &$form_state, array $step) {
do {
islandora_ingest_form_undo_callback_step($form, $form_state, $step);
islandora_ingest_form_decrement_step($form_state);
$step = islandora_ingest_form_get_step($form_state);
} while (isset($step) && $step['type'] == 'callback');
}
/**
* Undo the given 'callback' step.
*
* Assumes the given $step is a 'callback' step.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
* @param array $step
* The step which the undo callback is being called on.
*/
function islandora_ingest_form_undo_callback_step(array $form, array &$form_state, array $step) {
$args = array(&$form_state);
$args = isset($step['undo_function']['args']) ? array_merge($args, $step['undo_function']['args']) : $args;
if (isset($step['undo_function']['file'])) {
require_once drupal_get_path('module', $step['module']) . "/" . $step['undo_function']['file'];
}
call_user_func_array($step['undo_function']['function'], $args);
}
/**
* 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
* An array defining a ingest step.
*
* @return array
* The stepified Drupal form definition for the given step.
*/
function islandora_ingest_form_stepify(array $form, array &$form_state, array $step) {
$first_form_step = islandora_ingest_form_on_first_form_step($form_state);
$last_form_step = islandora_ingest_form_on_last_form_step($form_state);
$form['form_step_id'] = array(
'#type' => 'hidden',
'#value' => islandora_ingest_form_get_current_step_id($form_state),
);
$form['prev'] = $first_form_step ? NULL : islandora_ingest_form_previous_button($form_state);
$form['next'] = $last_form_step ? islandora_ingest_form_ingest_button($form_state) : islandora_ingest_form_next_button($form_state);
// Allow for a hook_form_FORM_ID_alter().
drupal_alter(array('form_' . $step['form_id'], 'form'), $form, $form_state, $step['form_id']);
return $form;
}
/**
* Checks if we are on the first form step.
*
* @param array $form_state
* The Drupal form state.
*
* @return bool
* TRUE if we are currently on the first step, FALSE otherwise.
*/
function islandora_ingest_form_on_first_form_step(array &$form_state) {
return !islandora_ingest_form_get_previous_form_step($form_state);
}
/**
* Checks if we are on the last form step.
*
* @param array $form_state
* The Drupal form state.
*
* @return bool
* TRUE if we are currently on the last step, FALSE otherwise.
*/
function islandora_ingest_form_on_last_form_step(array &$form_state) {
return !islandora_ingest_form_get_next_form_step($form_state);
}
/**
* Get the previous form step relative to the current step.
*
* @param array $form_state
* The Drupal form state.
*
* @return array
* The previous form step if one exists, NULL otherwise.
*/
function islandora_ingest_form_get_previous_form_step(array &$form_state) {
$step = NULL;
do {
$step = islandora_ingest_form_get_previous_step($form_state, $step);
} while (isset($step) && $step['type'] != 'form');
return $step;
}
/**
* Get the next form step relative to the current step.
*
* @param array $form_state
* The Drupal form state.
*
* @return array
* The next form step if one exists, NULL otherwise.
*/
function islandora_ingest_form_get_next_form_step(array &$form_state) {
$step = NULL;
do {
$step = islandora_ingest_form_get_next_step($form_state, $step);
} while (isset($step) && $step['type'] != 'form');
return $step;
}
/**
* Defines the previous button for the ingest form.
*
* Adds submit handlers for the form step if they exist.
*
* @param array $form_state
* The Drupal form state.
*
* @return array
* The previous button for the ingest form.
*/
function islandora_ingest_form_previous_button(array &$form_state) {
// Before we move back to the previous step we should tell the previous steps
// to undo whatever its submit handler did.
$prev_form_step = islandora_ingest_form_get_previous_form_step($form_state);
$form_id = $prev_form_step['form_id'];
$submit_callback = $form_id . '_undo_submit';
$submit = function_exists($submit_callback) ? array('islandora_ingest_form_previous_submit', $submit_callback) : array('islandora_ingest_form_previous_submit');
return array(
'#type' => 'submit',
'#value' => t('Previous'),
'#name' => 'prev',
'#submit' => $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(),
);
}
/**
* 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) {
islandora_ingest_form_decrement_step($form_state);
$step = islandora_ingest_form_get_step($form_state);
// Undo all callbacks that occured after the previous step.
if ($step['type'] == 'callback') {
islandora_ingest_form_undo_consecutive_callback_steps($form, $form_state, $step);
}
$form_state['rebuild'] = TRUE;
}
/**
* Defines the next button for the ingest form.
*
* Adds submit/validate handlers for the form step if they exist.
*
* @param array $form_state
* The Drupal form state.
*
* @return array
* The next button for the ingest form.
*/
function islandora_ingest_form_next_button(array &$form_state) {
$step = islandora_ingest_form_get_step($form_state);
$form_id = $step['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) {
islandora_ingest_form_increment_step($form_state);
$form_state['rebuild'] = TRUE;
}
/**
* Push current info into the current step's storage.
*
* @param array $form_state
* The Drupal form state.
*/
function islandora_ingest_form_stash_info(array &$form_state) {
$storage = &islandora_ingest_form_get_step_storage($form_state);
if ($storage && isset($form_state['values'])) {
$storage['values'] = $form_state['values'];
unset($form_state['values']);
}
}
/**
* Pops the info for the given step from storage into the form_state.
*
* @param array $form_state
* The Drupal 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();
}
/**
* Defines the ingest button for the ingest form.
*
* This button is only shown on the last page of the multi-page ingest form.
*
* @param array $form_state
* The Drupal form state.
*
* @return array
* The ingest button for the ingest form.
*/
function islandora_ingest_form_ingest_button(array &$form_state) {
$step = islandora_ingest_form_get_step($form_state);
$form_id = $step['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'),
'#process' => array('islandora_ingest_form_ingest_button_process'),
'#validate' => $validate,
'#submit' => $submit,
);
}
/**
* Process hook for the ingest button, adds the please wait spinning icon.
*/
function islandora_ingest_form_ingest_button_process(array $element) {
$settings['spinner'][$element['#id']] = array(
'message' => t('Please be patient while the the page loads.'),
'options' => array(
'lines' => 10,
'length' => 20,
'width' => 10,
'radius' => 30,
'corners' => 1,
'rotate' => 0,
'direction' => 1,
'color' => '#000',
'speed' => 1,
'trail' => 60,
'shadow' => FALSE,
'hwaccel' => FALSE,
'className' => 'spinner',
'zIndex' => 2000000000,
'top' => 'auto',
'left' => 'auto',
),
);
drupal_add_js($settings, 'setting');
$islandora_path = drupal_get_path('module', 'islandora');
$element['#attached'] = array(
'js' => array(
"$islandora_path/js/spin/spin.min.js",
"$islandora_path/js/spinner.js",
),
);
return $element;
}
/**
* 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) {
// Execute any remaining callbacks.
islandora_ingest_form_increment_step($form_state);
$step = islandora_ingest_form_get_step($form_state);
if (isset($step) && $step['type'] == 'callback') {
islandora_ingest_form_execute_consecutive_callback_steps($form, $form_state, $step);
}
// Ingest the objects.
$set_redirect = TRUE;
foreach ($form_state['islandora']['objects'] as &$object) {
try {
islandora_add_object($object);
// We want to redirect to the first object as it's considered to be the
// primary object.
if ($set_redirect) {
$form_state['redirect'] = "islandora/object/{$object->id}";
$set_redirect = FALSE;
}
drupal_set_message(
t('"@label" (ID: @pid) has been ingested.', array('@label' => $object->label, '@pid' => $object->id)),
'status');
}
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',
'Exception during ingest with Message: "@exception", and Trace: @trace',
array('@exception' => $e->getMessage(), '@trace' => $e->getTraceAsString()),
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'
);
}
}
// XXX: Foreaching with references can be weird... The reference exists in
// the scope outside.
unset($object);
}
/**
* 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 reset($objects);
}
/**
* Get general storage for the given/current step.
*
* @param array $form_state
* The Drupal form state.
* @param array $step_id
* The ID of the step.
*
* @return array
* The given/current step storage if found, NULL otherwise.
*/
function &islandora_ingest_form_get_step_storage(array &$form_state, $step_id = NULL) {
$step_id = isset($step_id) ? $step_id : islandora_ingest_form_get_current_step_id($form_state);
if (isset($step_id)) {
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];
}
$undefined_step_storage = array();
return $undefined_step_storage;
}
/**
* 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_shared_storage(array &$form_state) {
return $form_state['islandora']['shared_storage'];
}
/**
* 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_load_include(array &$form_state) {
form_load_include($form_state, 'inc', 'islandora', 'includes/ingest.form');
$step = islandora_ingest_form_get_step($form_state);
// Load include files.
if (isset($step['file']) && isset($step['module'])) {
$matches = array();
preg_match('/^(.*)\.(.*)$/', $step['file'], $matches);
list($file, $name, $type) = $matches;
form_load_include($form_state, $type, $step['module'], $name);
}
}
/**
* 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_form_get_steps(array &$form_state) {
module_load_include('inc', 'islandora', 'includes/utilities');
$steps = &drupal_static(__FUNCTION__);
if (isset($steps)) {
return $steps;
}
$steps = array();
$shared_storage = &islandora_ingest_form_get_shared_storage($form_state);
foreach (islandora_build_hook_list(ISLANDORA_INGEST_STEP_HOOK, $shared_storage['models']) as $hook) {
// Required for pass by reference.
// @todo Change this around so that it isn't passed by reference, there
// Is an alter below that can handle that requirement.
foreach (module_implements($hook) as $module) {
$function = $module . '_' . $hook;
$module_steps = (array) $function($form_state);
$steps = array_merge($steps, $module_steps);
}
}
$steps = array_filter($steps);
foreach (islandora_build_hook_list(ISLANDORA_INGEST_STEP_HOOK, $shared_storage['models']) as $hook) {
drupal_alter($hook, $steps, $form_state);
}
// Add any defaults.
foreach ($steps as $key => &$step) {
$step['id'] = $key;
}
uasort($steps, 'drupal_sort_weight');
return $steps;
}
/**
* Filter the ingest steps to only steps of type 'form'.
*
* @param array $form_state
* The Drupal form state.
*
* @return array
* The list of sorted ingest form steps as defined by all implementers
* of ISLANDORA_INGEST_STEP_HOOK.
*/
function islandora_ingest_form_get_form_steps(array &$form_state) {
$steps = islandora_ingest_form_get_steps($form_state);
$form_step_filter = function($o) {
return $o['type'] == 'form';
};
return array_filter($steps, $form_step_filter);
}
/**
* Filter the ingest steps to only steps of type 'form'.
*
* @param array $form_state
* The Drupal form state.
*
* @return array
* The list of sorted ingest callback steps as defined by all implementers
* of ISLANDORA_INGEST_STEP_HOOK.
*/
function islandora_ingest_form_get_callback_steps(array &$form_state) {
$steps = islandora_ingest_form_get_steps($form_state);
$callback_step_filter = function($o) {
return $o['type'] == 'callback';
};
return array_filter($steps, $callback_step_filter);
}

340
includes/manage_deleted_objects.inc

@ -1,340 +0,0 @@
<?php
/**
* @file
* Handles the management of deleted objects.
*/
/**
* The deletion management prep form.
*
* @param array $form
* The Drupal form definition.
* @param array $form_state
* The Drupal form state.
*
* @return array
* The Drupal form definition.
*/
function islandora_deleted_objects_prep_form($form, $form_state, $serialized_chosen = NULL) {
module_load_include('inc', 'islandora', 'includes/utilities');
$chosen_contentmodels = array();
if ($serialized_chosen) {
$chosen_contentmodels = unserialize($serialized_chosen);
}
$contentmodels_with_deleted_members = islandora_get_contentmodels_with_deleted_members();
$elegible_contentmodels = array_keys($contentmodels_with_deleted_members);
if (empty($contentmodels_with_deleted_members)) {
$form['message'] = array(
'#type' => 'markup',
'#markup' => t("There are no deleted objects in this repository."),
);
return $form;
}
$form['message'] = array(
'#type' => 'markup',
'#markup' => t("Select content models of deleted objects."),
);
$form['mapped_contentmodels'] = array(
'#type' => 'hidden',
'#value' => $contentmodels_with_deleted_members,
);
$table_element = islandora_content_model_select_table_form_element(NULL);
foreach ($table_element['#options'] as $option) {
if (!in_array($option['pid'], $elegible_contentmodels)) {
unset($table_element['#options'][$option['pid']]);
}
if (array_key_exists($option['pid'], $chosen_contentmodels)) {
$table_element['#default_value'][$option['pid']] = TRUE;
}
}
$form['contentmodels'] = $table_element;
$form['next'] = array(
'#type' => 'submit',
'#value' => t('Next'),
);
return $form;
}
/**
* Submit handler for deletion management prep form.
*
* @param array $form
* The form.
* @param array $form_state
* The form state.
*/
function islandora_deleted_objects_prep_form_submit($form, $form_state) {
$content_models = $form_state['values']['contentmodels'];
$chosen = function($element) {
return $element;
};
$serialized_contentmodels = serialize(array_filter($content_models, $chosen));
drupal_goto("admin/islandora/restore/manage/$serialized_contentmodels");
}
/**
* The deletion management prep form.
*
* @param array $form
* The Drupal form definition.
* @param array $form_state
* The Drupal form state.
*
* @return array
* The Drupal form definition.
*/
function islandora_deleted_objects_manage_form($form, $form_state, $serialized_chosen = NULL) {
$form['previous'] = array(
'#type' => 'submit',
'#value' => t('Previous'),
'#attributes' => array('source' => 'previous'),
);
$chosen_contentmodels = unserialize($serialized_chosen);
$content_models_with_deleted = islandora_get_contentmodels_with_deleted_members();
foreach ($chosen_contentmodels as $contentmodel) {
if (!array_key_exists($contentmodel, $content_models_with_deleted)) {
unset($chosen_contentmodels[$contentmodel]);
}
}
if (empty($chosen_contentmodels)) {
$form['message'] = array(
'#type' => 'markup',
'#markup' => t("There are no deleted objects with the selected content models in this repository."),
);
return $form;
}
if (is_array($chosen_contentmodels)) {
foreach ($chosen_contentmodels as $key => $value) {
if (in_array($key, $content_models_with_deleted)) {
$chosen_contentmodels[$key] = $content_models_with_deleted[$key];
}
}
}
$tuque = islandora_get_tuque_connection();
$repository = $tuque->repository;
// Query brings back fedora-system:FedoraObject-3.0, doubling the results.
$total = $repository->ri->countQuery(islandora_get_deleted_query($chosen_contentmodels), 'sparql') / 2;
$limit = 25;
if ($total < 28) {
$limit = $total;
}
$current_page = pager_default_initialize($total, $limit);
$query_limit = $limit * 2;
$offset = $current_page * $query_limit;
$options = islandora_get_deleted_objects($chosen_contentmodels, $query_limit, $offset);
foreach ($options as &$option) {
$option['content_model'] = $content_models_with_deleted[$option['content_model']];
}
$form['serialized_chosen'] = array(
'#type' => 'hidden',
'#value' => $serialized_chosen,
);
$form['pager'] = array(
'#type' => 'markup',
'#markup' => theme('pager', array('quantity', count($options))),
);
$form['propogate'] = array(
'#title' => t('Apply changes to related objects?'),
'#default_value' => TRUE,
'#description' => t("Objects associated with selected objects will also be purged/restored. ie page objects associated with a book object."),
'#type' => 'checkbox',
);
$form['chosen'] = array(
'#type' => 'hidden',
'#value' => $chosen_contentmodels,
);
$form['objects_to_process'] = array(
'#type' => 'tableselect',
'#header' => array(
'title' => t('Name'),
'pid' => t('PID'),
'content_model' => t('Content Model'),
),
'#multiple' => TRUE,
'#options' => $options,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Restore selected objects'),
'#attributes' => array('source' => 'restore'),
);
if (user_access(ISLANDORA_PURGE)) {
$form['purge'] = array(
'#type' => 'submit',
'#value' => t('Irrevocably purge selected objects'),
'#attributes' => array('source' => 'purge'),
);
}
return $form;
}
/**
* Submit handler for deletion management form.
*
* @param array $form
* The form.
* @param array $form_state
* The form state.
*/
function islandora_deleted_objects_manage_form_submit($form, $form_state) {
module_load_include('inc', 'islandora', 'includes/utilities');
$serialized_chosen = isset($form_state['values']['serialized_chosen']) ? $form_state['values']['serialized_chosen'] : NULL;
if (isset($form_state['clicked_button']['#attributes']['source']) && $form_state['clicked_button']['#attributes']['source'] == 'previous') {
drupal_goto("admin/islandora/restore/prep/$serialized_chosen");
}
if ($form_state['clicked_button']['#attributes']['source'] == 'restore') {
$descriptor = "Restoring";
$action = 'islandora_restore_object_by_pid';
}
if ($form_state['clicked_button']['#attributes']['source'] == 'purge') {
$descriptor = "Purging";
$action = 'islandora_purge_object_by_pid';
}
$objects_to_process = array_filter($form_state['values']['objects_to_process']);
$pids_to_restore = $objects_to_process;
if ($form_state['values']['propogate']) {
foreach ($objects_to_process as $pid) {
$fedora_object = islandora_object_load($pid);
$temp = islandora_invoke_hook_list(ISLANDORA_UPDATE_RELATED_OBJECTS_PROPERTIES_HOOK, $fedora_object->models, array($fedora_object));
if (!empty($temp)) {
$pids_to_restore = array_merge_recursive($pids_to_restore, $temp);
}
}
}
$batch = array(
'title' => t('@descriptor selected objects', array('@descriptor' => $descriptor)),
'file' => drupal_get_path('module', 'islandora') . '/includes/manage_deleted_objects.inc',
'operations' => array(),
);
foreach ($pids_to_restore as $pid) {
$batch['operations'][] = array(
$action,
array($pid),
);
}
batch_set($batch);
batch_process("admin/islandora/restore/manage/$serialized_chosen");
}
/**
* Gets PIDS of all deleted objects.
*
* @return array
* PIDS of deleted objects
*/
function islandora_get_deleted_objects($content_models, $limit, $offset) {
$tuque = islandora_get_tuque_connection();
$repository = $tuque->repository;
$query = islandora_get_deleted_query($content_models, $offset);
$objects = $repository->ri->sparqlQuery($query, $limit);
$deleted_objects = array();
foreach ($objects as $object) {
if ($object['object']['value'] != "fedora-system:FedoraObject-3.0") {
$pid = $object['subject']['value'];
$cm_pid = $object['object']['value'];
$title = $object['label']['value'];
$deleted_objects[$pid] = array(
'title' => $title, 'pid' => $pid,
'content_model' => $content_models[$cm_pid],
);
}
}
return $deleted_objects;
}
/**
* Gets PIDS of all content models associated with deleted objects.
*
* @return array
* array of content model pids
*/
function islandora_get_contentmodels_with_deleted_members() {
$tuque = new IslandoraTuque();
$repository = $tuque->repository;
$query = "PREFIX fm: <info:fedora/fedora-system:def/model#>
SELECT DISTINCT ?object ?label FROM <#ri>
WHERE {
{?subject fm:state fm:Deleted;
fm:hasModel ?object;
}
OPTIONAL{
?object fm:label ?label
}
}";
$objects = $repository->ri->sparqlQuery($query, -1);
$content_models = array();
foreach ($objects as $object) {
if ($object['object']['value'] != "fedora-system:FedoraObject-3.0") {
$content_models[$object['object']['value']] = $object['label']['value'];
}
}
return $content_models;
}
/**
* Restores deleted object.
*
* @param string $pid
* PID of object to be restored
*/
function islandora_restore_object_by_pid($pid) {
$fedora_object = islandora_object_load($pid);
$fedora_object->state = 'A';
}
/**
* Purges deleted object.
*
* @param string $pid
* PID of object to be restored
*/
function islandora_purge_object_by_pid($pid) {
$fedora_object = islandora_object_load($pid);
$fedora_object->repository->purgeObject($pid);
}
/**
* Get query to find all deleted objects by content type.
*
* @param array $content_models
* Content models to restrict search
* @param int $offset
* offset to be added to search
*
* @return string
* Sparql query
*/
function islandora_get_deleted_query($content_models, $offset = 0) {
$candidates = array_keys($content_models);
$first_contentmodel = array_shift($candidates);
$prefix = "PREFIX fm: <" . FEDORA_MODEL_URI . "> ";
$select = "SELECT DISTINCT ?subject ?label ?object FROM <#ri> WHERE { ";
$where_clause = "{?subject fm:hasModel <info:fedora/$first_contentmodel>;
fm:state fm:Deleted;
fm:hasModel ?object;
}";
$suffix = "} ORDER BY ?subject OFFSET $offset";
$unions = '';
foreach ($candidates as $contentmodel) {
$unions .= "UNION {?subject fm:hasModel <info:fedora/$contentmodel>;
fm:state fm:Deleted;
fm:hasModel ?object;
}
";
}
$optional = "OPTIONAL{?subject fm:label ?label}";
return "$prefix $select $where_clause $unions $optional $suffix";
}

171
includes/metadata.inc

@ -1,171 +0,0 @@
<?php
/**
* @file
* Defines functions used when viewing metadata displays on Islandora objects.
*/
/**
* Retrieves the metadata display markup for an Islandora object.
*
* @param AbstractObject $object
* An AbstractObject representing an object within Fedora.
* @param bool $print
* Whether the object is being printed.
*
* @return string
* Markup to be rendered for display on Islandora object pages.
*/
function islandora_retrieve_metadata_markup(AbstractObject $object, $print = FALSE) {
$viewers = module_invoke_all('islandora_metadata_display_info');
$viewer = variable_get('islandora_metadata_display', 'dublin_core');
$markup = '';
if (isset($viewers[$viewer]['metadata callback'])) {
$markup = call_user_func($viewers[$viewer]['metadata callback'], $object, $print);
// The callback doesn't have any markup provided for this particular object,
// default back to the dublin_core display.
if ($markup === FALSE) {
$markup = call_user_func($viewers['dublin_core']['metadata callback'], $object, $print);
}
}
return $markup;
}
/**
* Retrieves the metadata display description for an Islandora object.
*
* @param AbstractObject $object
* An AbstractObject representing an object within Fedora.
*
* @return string
* Markup to be rendered for description on Islandora object pages.
*/
function islandora_retrieve_description_markup(AbstractObject $object) {
$viewers = module_invoke_all('islandora_metadata_display_info');
$viewer = variable_get('islandora_metadata_display', 'dublin_core');
$markup = '';
if (isset($viewers[$viewer]['description callback'])) {
$markup = call_user_func($viewers[$viewer]['description callback'], $object);
// The callback doesn't have any markup provided for this particular object,
// default back to the dublin_core display.
if ($markup === FALSE) {
$markup = call_user_func($viewers['dublin_core']['description callback'], $object);
}
}
return $markup;
}
/**
* Form used for choosing which default metadata display to use for viewing.
*
* @param array $form
* An array representing a Drupal form.
* @param array $form_state
* An array containing the Drupal form state.
*
* @return array
* An array representing the metadata display viewer form.
*/
function islandora_metadata_display_form($form, $form_state) {
module_load_include('inc', 'islandora', 'includes/solution_packs.inc');
$form = array();
$defined_displays = module_invoke_all('islandora_metadata_display_info');
if (!empty($defined_displays)) {
$no_viewer = array();
$no_viewer['none'] = array(
'label' => t('None'),
'description' => t("Don't show any metadata for displaying"),
);
$viewers = array_merge_recursive($no_viewer, $defined_displays);
$form['viewers'] = array(
'#type' => 'item',
'#title' => t('Select a viewer'),
'#description' => t('Preferred metadata display for Islandora. These may be provided by third-party modules.'),
'#tree' => TRUE,
'#theme' => 'islandora_viewers_table',
);
foreach ($viewers as $name => $profile) {
$options[$name] = '';
$form['viewers']['name'][$name] = array(
'#type' => 'hidden',
'#value' => $name,
);
$form['viewers']['label'][$name] = array(
'#type' => 'item',
'#markup' => $profile['label'],
);
$form['viewers']['description'][$name] = array(
'#type' => 'item',
'#markup' => $profile['description'],
);
$form['viewers']['configuration'][$name] = array(
'#type' => 'item',
'#markup' => (isset($profile['configuration']) AND $profile['configuration'] != '') ? l(t('configure'), $profile['configuration']) : '',
);
}
$form['viewers']['default'] = array(
'#type' => 'radios',
'#options' => isset($options) ? $options : array(),
'#default_value' => variable_get('islandora_metadata_display', 'dublin_core'),
);
}
else {
$form['viewers']['no_viewers'] = array(
'#markup' => t('No viewers detected.'),
);
}
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save configuration'),
);
return $form;
}
/**
* Submit handler for the metadata display form which sets the default viewer.
*
* @param array $form
* An array representing a Drupal form.
* @param array $form_state
* An array containing the Drupal form state.
*/
function islandora_metadata_display_form_submit($form, $form_state) {
variable_set('islandora_metadata_display', $form_state['values']['viewers']['default']);
drupal_set_message(t('The configuration options have been saved.'));
}
/**
* Metadata display callback for rendering Dublin Core metadata.
*
* @param AbstractObject $object
* An AbstractObject representing an object within Fedora.
* @param bool $print
* Whether the display is being printed or not.
*
* @return string
* Markup representing the rendered metadata from Dublin Core.
*/
function islandora_metadata_display_callback(AbstractObject $object, $print = FALSE) {
$elements = array(
'islandora_object' => $object,
'print' => $print,
);
return theme('islandora_dublin_core_display', $elements);
}
/**
* Metadata description callback for rendering Dublin Core description.
*
* @param AbstractObject $islandora_object
* An AbstractObject representing an object within Fedora.
*
* @return string
* Markup representing the rendered metadata from Dublin Core.
*/
function islandora_metadata_description_callback(AbstractObject $islandora_object) {
$elements = array(
'islandora_object' => $islandora_object,
);
return theme('islandora_dublin_core_description', $elements);
}

401
includes/mime_detect.inc

@ -1,401 +0,0 @@
<?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/
*
* It does some MIME trickery, inspired by the need to to deal with Openoffice
* and MS Office 2007 file formats -- which are often mis-interpreted by
* mime-magic, fileinfo, and the *nix `file` command.
*
* In Drupal 6, we also make use of file_get_mimetype. See:
* http://api.drupal.org/api/function/file_get_mimetype/6
* ... however this only provides a uni-directional lookup (ext->mime).
* While I don't have a specific use case for a mime->extension lookup, I think
* it's good to have in here.
*
* Drupal 7 will have better mime handlers. See:
* http://api.drupal.org/api/function/file_default_mimetype_mapping/7
*/
class MimeDetect {
protected $protectedMimeTypes = array(
/*
* This is a shortlist of mimetypes which should catch most
* mimetype<-->extension lookups in the context of Islandora collections.
*
* It has been cut from a much longer list.
*
* Two types of mimetypes should be put in this list:
* 1) Special emerging formats which may not yet be expressed in the system
* mime.types file.
* 2) Heavily used mimetypes of particular importance to the Islandora
* project, as lookups against this list will be quicker and less
* resource intensive than other methods.
*
* Lookups are first checked against this short list. If no results are
* found, then the lookup function may move on to check other sources,
* namely the system's mime.types file.
*
* In most cases though, this short list should suffice.
*
* If modifying this list, please note that for promiscuous mimetypes
* (those which map to multiple extensions, such as text/plain)
* The function get_extension will always return the *LAST* extension in
* this list, so you should put your preferred extension *LAST*.
*
* e.g...
* "jpeg" => "image/jpeg",
* "jpe" => "image/jpeg",
* "jpg" => "image/jpeg",
*
* $this->get_extension('image/jpeg') will always return 'jpg'.
*
*/
// Openoffice:
'odb' => 'application/vnd.oasis.opendocument.database',
'odc' => 'application/vnd.oasis.opendocument.chart',
'odf' => 'application/vnd.oasis.opendocument.formula',
'odg' => 'application/vnd.oasis.opendocument.graphics',
'odi' => 'application/vnd.oasis.opendocument.image',
'odm' => 'application/vnd.oasis.opendocument.text-master',
'odp' => 'application/vnd.oasis.opendocument.presentation',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
'odt' => 'application/vnd.oasis.opendocument.text',
'otg' => 'application/vnd.oasis.opendocument.graphics-template',
'oth' => 'application/vnd.oasis.opendocument.text-web',
'otp' => 'application/vnd.oasis.opendocument.presentation-template',
'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template',
'ott' => 'application/vnd.oasis.opendocument.text-template',
// Staroffice:
'stc' => 'application/vnd.sun.xml.calc.template',
'std' => 'application/vnd.sun.xml.draw.template',
'sti' => 'application/vnd.sun.xml.impress.template',
'stw' => 'application/vnd.sun.xml.writer.template',
'sxc' => 'application/vnd.sun.xml.calc',
'sxd' => 'application/vnd.sun.xml.draw',
'sxg' => 'application/vnd.sun.xml.writer.global',
'sxi' => 'application/vnd.sun.xml.impress',
'sxm' => 'application/vnd.sun.xml.math',
'sxw' => 'application/vnd.sun.xml.writer',
// K-office:
'kil' => 'application/x-killustrator',
'kpt' => 'application/x-kpresenter',
'kpr' => 'application/x-kpresenter',
'ksp' => 'application/x-kspread',
'kwt' => 'application/x-kword',
'kwd' => 'application/x-kword',
// Ms office 97:
'doc' => 'application/msword',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
// Office2007:
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'docm' => 'application/vnd.ms-word.document.macroEnabled.12',
'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
'dotm' => 'application/vnd.ms-word.template.macroEnabled.12',
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',
'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
'sldm' => 'application/vnd.ms-powerpoint.slide.macroEnabled.12',
// Wordperfect (who cares?):
'wpd' => 'application/wordperfect',
// Common and generic containers:
'pdf' => 'application/pdf',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'rtf' => 'text/rtf',
'rtx' => 'text/richtext',
'latex' => 'application/x-latex',
'tex' => 'application/x-tex',
'texi' => 'application/x-texinfo',
'texinfo' => 'application/x-texinfo',
// *ml:
'css' => 'text/css',
'htm' => 'text/html',
'html' => 'text/html',
'wbxml' => 'application/vnd.wap.wbxml',
'xht' => 'application/xhtml+xml',
'xhtml' => 'application/xhtml+xml',
'xsl' => 'text/xml',
'xml' => 'text/xml',
'csv' => 'text/csv',
'tsv' => 'text/tab-separated-values',
'txt' => 'text/plain',
// images:
"bmp" => "image/bmp",
'dng' => 'image/x-adobe-dng',
"gif" => "image/gif",
"ief" => "image/ief",
"jpeg" => "image/jpeg",
"jpe" => "image/jpeg",
"jpg" => "image/jpeg",
"jp2" => "image/jp2",
"png" => "image/png",
"tiff" => "image/tiff",
"tif" => "image/tiff",
"djvu" => "image/vnd.djvu",
"djv" => "image/vnd.djvu",
"wbmp" => "image/vnd.wap.wbmp",
"ras" => "image/x-cmu-raster",
"pnm" => "image/x-portable-anymap",
"pbm" => "image/x-portable-bitmap",
"pgm" => "image/x-portable-graymap",
"ppm" => "image/x-portable-pixmap",
"rgb" => "image/x-rgb",
"xbm" => "image/x-xbitmap",
"xpm" => "image/x-xpixmap",
"xwd" => "image/x-windowdump",
// videos:
"mkv" => "video/x-matroska",
"mpeg" => "video/mpeg",
"mpe" => "video/mpeg",
"mpg" => "video/mpeg",
"m4v" => "video/mp4",
"mp4" => "video/mp4",
"ogv" => "video/ogg",
"qt" => "video/quicktime",
"mov" => "video/quicktime",
"mxu" => "video/vnd.mpegurl",
"avi" => "video/x-msvideo",
"movie" => "video/x-sgi-movie",
"flv" => "video/x-flv",
"swf" => "application/x-shockwave-flash",
// Audio:
"mp3" => "audio/mpeg",
"mp4a" => "audio/mp4",
"m4a" => "audio/mp4",
"oga" => "audio/ogg",
"ogg" => "audio/ogg",
"flac" => "audio/x-flac",
"wav" => "audio/vnd.wave",
// Compressed formats:
// (note: http://svn.cleancode.org/svn/email/trunk/mime.types)
"tgz" => "application/x-gzip",
"gz" => "application/x-gzip",
"tar" => "application/x-tar",
"gtar" => "application/x-gtar",
"zip" => "application/x-zip",
// others:
'bin' => 'application/octet-stream',
);
protected $protectedFileExtensions;
protected $extensionExceptions = array(
// XXX: Deprecated... Only here due to old 'tif' => 'image/tif' mapping...
// The correct MIMEtype is 'image/tiff'.
'image/tif' => 'tif',
);
protected $systemTypes;
protected $systemExts;
protected $etcMimeTypes = '/etc/mime.types';
/**
* Construtor.
*/
public function __construct() {
// Populate the reverse shortlist:
$this->protectedFileExtensions = array_flip($this->protectedMimeTypes);
$this->protectedFileExtensions += $this->extensionExceptions;
// Pick up a local mime.types file if it is available.
if (is_readable('mime.types')) {
$this->etcMimeTypes = 'mime.types';
}
}
/**
* Gets MIME type associated with the give file's extension.
*
* @param string $filename
* The filename
* @param bool $debug
* Returns a debug array.
*
* @return mixed
* string or an array
*/
public function getMimetype($filename, $debug = FALSE) {
$file_name_and_extension = explode('.', $filename);
$ext = drupal_strtolower(array_pop($file_name_and_extension));
if (!empty($this->protectedMimeTypes[$ext])) {
if (TRUE === $debug) {
return array('mime_type' => $this->protectedMimeTypes[$ext], 'method' => 'from_array');
}
return $this->protectedMimeTypes[$ext];
}
if (function_exists('file_get_mimetype')) {
$drupal_mimetype = file_get_mimetype($filename);
if ('application/octet-stream' != $drupal_mimetype) {
if (TRUE == $debug) {
return array('mime_type' => $drupal_mimetype, 'method' => 'file_get_mimetype');
}
return $drupal_mimetype;
}
}
if (!isset($this->systemTypes)) {
$this->systemTypes = $this->systemExtensionMimetypes();
}
if (isset($this->systemTypes[$ext])) {
if (TRUE == $debug) {
return array('mime_type' => $this->systemTypes[$ext], 'method' => 'mime.types');
}
return $this->systemTypes[$ext];
}
if (TRUE === $debug) {
return array('mime_type' => 'application/octet-stream', 'method' => 'last_resort');
}
return 'application/octet-stream';
}
/**
* Gets one valid file extension for a given MIME 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) {
if (!empty($this->protectedFileExtensions[$mime_type])) {
if (TRUE == $debug) {
return array('extension' => $this->protectedFileExtensions[$mime_type], 'method' => 'from_array');
}
return $this->protectedFileExtensions[$mime_type];
}
if (!isset($this->systemExts)) {
$this->systemExts = $this->systemMimetypeExtensions();
}
if (isset($this->systemExts[$mime_type])) {
if (TRUE == $debug) {
return array('extension' => $this->systemExts[$mime_type], 'method' => 'mime.types');
}
return $this->systemExts[$mime_type];
}
if (TRUE == $debug) {
return array('extension' => 'bin', 'method' => 'last_resort');
}
return 'bin';
}
/**
* 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();
if (file_exists($this->etcMimeTypes)) {
$file = fopen($this->etcMimeTypes, 'r');
while (($line = fgets($file)) !== FALSE) {
$line = trim(preg_replace('/#.*/', '', $line));
if (!$line) {
continue;
}
$parts = preg_split('/\s+/', $line);
if (count($parts) == 1) {
continue;
}
// A single part means a mimetype without extensions, which we ignore.
$type = array_shift($parts);
if (!isset($out[$type])) {
$out[$type] = array_shift($parts);
}
// We take the first ext from the line if many are present.
}
fclose($file);
}
return $out;
}
/**
* 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();
if (file_exists($this->etcMimeTypes)) {
$file = fopen($this->etcMimeTypes, 'r');
while (($line = fgets($file)) !== FALSE) {
$line = trim(preg_replace('/#.*/', '', $line));
if (!$line) {
continue;
}
$parts = preg_split('/\s+/', $line);
if (count($parts) == 1) {
continue;
}
// A single part means a mimetype without extensions, which we ignore.
$type = array_shift($parts);
foreach ($parts as $part) {
$out[$part] = $type;
}
}
fclose($file);
}
return $out;
}
/**
* Gets MIME type array.
*
* @return array
* Returns associative array with exts and mimetypes.
*/
public function getMimeTypes() {
return $this->protectedMimeTypes;
}
/**
* Get all valid extensions for this MIME type.
*
* @param string $mimetype
* The MIME type we are searching for.
*
* @return array
* An array of valid extensions for this MIME type.
*/
public function getValidExtensions($mimetype) {
$filter = function ($mime) use ($mimetype) {
return $mime == $mimetype;
};
return array_keys(array_filter($this->protectedMimeTypes, $filter));
}
}

27
includes/mime_type.autocomplete.inc

@ -1,27 +0,0 @@
<?php
/**
* @file
* Autocomplete functionality for MIME types in Islandora.
*/
/**
* Autocomplete the MIME type name.
*
* @param string $string
* A search string.
*
* @return string
* The rendered JSON results.
*/
function islandora_mime_type_autocomplete($string) {
module_load_include('inc', 'islandora', 'includes/mime_detect');
$mime_detect = new MimeDetect();
$mime_types = $mime_detect->getMimeTypes();
$output = array();
foreach ($mime_types as $mime_type) {
if (preg_match("/{$string}/i", $mime_type) !== 0) {
$output[$mime_type] = $mime_type;
}
}
return drupal_json_output($output);
}

56
includes/object.entity_controller.inc

@ -1,56 +0,0 @@
<?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.
*
* @return array
* An array of loaded objects.
*/
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.
}
}

217
includes/object_properties.form.inc

@ -1,217 +0,0 @@
<?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 AbstractObject $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, AbstractObject $object) {
drupal_set_title($object->label);
$form_state['object'] = $object;
$temp = islandora_invoke_hook_list(ISLANDORA_UPDATE_RELATED_OBJECTS_PROPERTIES_HOOK, $object->models, array($object));
$related_objects_pids = array();
if (!empty($temp)) {
$related_objects_pids = array_merge_recursive($related_objects_pids, $temp);
}
$regenerate_derivatives_access = FALSE;
if (islandora_object_access(ISLANDORA_REGENERATE_DERIVATIVES, $object)) {
module_load_include('inc', 'islandora', 'includes/derivatives');
$hooks = islandora_invoke_hook_list(ISLANDORA_DERVIATIVE_CREATION_HOOK, $object->models, array($object));
$hooks = islandora_filter_derivatives($hooks, array('force' => TRUE), $object);
if (count($hooks) > 1) {
$regenerate_derivatives_access = TRUE;
}
}
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's account name"),
'#type' => 'textfield',
),
'object_state' => array(
'#title' => t('State'),
'#default_value' => $object->state,
'#required' => TRUE,
'#description' => t("The object's state (active, inactive or deleted)"),
'#type' => 'select',
'#options' => array('A' => 'Active', 'I' => 'Inactive', 'D' => 'Deleted'),
),
'propogate' => array(
'#title' => t('Apply changes to related objects?'),
'#default_value' => TRUE,
'#description' => t("Changes to owner and state will applied to associated objects. ie page objects associated with a book object."),
'#type' => 'checkbox',
'#access' => count($related_objects_pids),
),
'related_pids' => array(
'#value' => $related_objects_pids,
'#type' => 'hidden',
'#access' => count($related_objects_pids),
),
'submit' => array(
'#type' => 'submit',
'#value' => 'Update Properties',
),
'delete' => array(
'#type' => 'submit',
'#access' => islandora_object_access(ISLANDORA_PURGE, $object),
'#value' => t("Permanently remove '@label' from repository", array(
'@label' => truncate_utf8($object->label, 32, TRUE, TRUE))
),
'#submit' => array('islandora_object_properties_form_delete'),
'#limit_validation_errors' => array(array('pid')),
),
'regenerate' => array(
'#type' => 'submit',
'#access' => $regenerate_derivatives_access,
'#value' => t("Regenerate all derivatives"),
'#submit' => array('islandora_object_properties_regenerate_derivatives'),
),
);
}
/**
* 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'];
$propogate = $form_state['values']['propogate'];
$update_owners = FALSE;
$update_states = FALSE;
if (isset($owner) && $owner != $object->owner) {
try {
$object->owner = $owner;
$update_owners = TRUE;
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($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())));
}
}
if (isset($state) && $state != $object->state) {
try {
$object->state = $state;
$update_states = TRUE;
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 ($propogate && ($update_states || $update_owners)) {
$related_objects_pids = $form_state['values']['related_pids'];
$batch = array(
'title' => t('Updating related objects'),
'file' => drupal_get_path('module', 'islandora') . '/includes/object_properties.form.inc',
'operations' => array(),
);
foreach ($related_objects_pids as $pid) {
$batch['operations'][] = array(
'islandora_update_object_properties',
array($pid, $update_states, $state, $update_owners, $owner),
);
}
batch_set($batch);
}
}
/**
* 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");
}
/**
* Updates object state.
*
* @param string $pid
* PID of object to be updated
* @param bool $update_states
* If TRUE, update object state
* @param string $state
* Desired object state
* @param bool $update_owners
* If TRUE, update Owner
* @param string $owner
* New Owner
*/
function islandora_update_object_properties($pid, $update_states, $state, $update_owners, $owner) {
$fedora_object = islandora_object_load($pid);
if ($fedora_object) {
if ($update_states) {
$fedora_object->state = $state;
}
if ($update_owners) {
$fedora_object->owner = $owner;
}
}
}
/**
* Callback function for object properties regenerate all derivatives.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*/
function islandora_object_properties_regenerate_derivatives(array $form, array &$form_state) {
drupal_goto("islandora/object/{$form_state['object']}/regenerate");
}

178
includes/regenerate_derivatives.form.inc

@ -1,178 +0,0 @@
<?php
/**
* @file
* The confirmation forms used to regenerate derivatives.
*/
/**
* Regenerate a single datastream derivative confirm form.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
* @param AbstractDatastream $datastream
* The datastream to have derivatives regenerated for.
*
* @return array
* The Drupal form definition.
*/
function islandora_regenerate_datastream_derivative_form(array $form, array &$form_state, AbstractDatastream $datastream) {
$form_state['datastream'] = $datastream;
return confirm_form($form,
t('Are you sure you want to regenerate the derivative for the %dsid datastream?', array('%dsid' => $datastream->id)),
"islandora/object/{$datastream->parent->id}/manage/datastreams",
t('This will create a new version of the datastream. Please wait while this happens.'),
t('Regenerate'),
t('Cancel')
);
}
/**
* Submit handler for the regenerate datastream derivative form.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*/
function islandora_regenerate_datastream_derivative_form_submit(array $form, array &$form_state) {
module_load_include('inc', 'islandora', 'includes/derivatives');
$datastream = $form_state['datastream'];
$batch = islandora_regenerate_datastream_derivative_batch($datastream);
batch_set($batch);
$form_state['redirect'] = "islandora/object/{$datastream->parent->id}/manage/datastreams";
}
/**
* Regenerate all derivatives on an object.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
* @param AbstractObject $object
* The object that is having its derivatives regenerated.
*
* @return array
* The Drupal form definition.
*/
function islandora_regenerate_object_derivatives_form(array $form, array &$form_state, AbstractObject $object) {
$form_state['object'] = $object;
return confirm_form($form,
t('Are you sure you want to regenerate all the derivatives for %title?', array('%title' => $object->label)),
"islandora/object/{$object->id}/manage/properties",
t('This will create a new version for every datastream on the object. Please wait while this happens.'),
t('Regenerate'),
t('Cancel')
);
}
/**
* Submit handler for the regenerate object derivativse form.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*/
function islandora_regenerate_object_derivatives_form_submit(array $form, array &$form_state) {
$object = $form_state['object'];
$batch = islandora_regenerate_object_derivatives_batch($object);
batch_set($batch);
$form_state['redirect'] = "islandora/object/{$object->id}/manage/properties";
}
/**
* Creates a batch to go out and re-create all of the derivatives for an object.
*
* @param AbstractObject $object
* A AbstractObject representing an object within Fedora.
*
* @return array
* An array specifying the Drupal batch.
*/
function islandora_regenerate_object_derivatives_batch(AbstractObject $object) {
module_load_include('inc', 'islandora', 'includes/derivatives');
return array(
'title' => t('Regenerating all derivatives for @label', array('@label' => $object->label)),
'operations' => islandora_do_batch_derivatives($object, array('force' => TRUE)),
'init_message' => t('Preparing to regenerate derivatives...'),
'progress_message' => t('Time elapsed: @elapsed <br/>Estimated time remaining @estimate.'),
'error_message' => t('An error has occurred.'),
'file' => drupal_get_path('module', 'islandora') . '/includes/regenerate_derivatives.form.inc',
'finished' => 'islandora_regenerate_derivative_batch_finished',
);
}
/**
* Creates a batch to go out and re-create the derivative for a datastream.
*
* @param AbstractDatastream $datastream
* A AbstractDatastream representing a datastream on an object within Fedora.
*
* @return array
* An array specifying the Drupal batch.
*/
function islandora_regenerate_datastream_derivative_batch(AbstractDatastream $datastream) {
module_load_include('inc', 'islandora', 'includes/derivatives');
return array(
'title' => t('Regenerating derivatives for the @dsid datastream', array('@dsid' => $datastream->id)),
'operations' => islandora_do_batch_derivatives($datastream->parent, array(
'force' => TRUE,
'destination_dsid' => $datastream->id,
)),
'init_message' => t('Preparing to regenerate derivatives...'),
'progress_message' => t('Time elapsed: @elapsed <br/>Estimated time remaining @estimate.'),
'error_message' => t('An error has occurred.'),
'file' => drupal_get_path('module', 'islandora') . '/includes/regenerate_derivatives.form.inc',
'finished' => 'islandora_regenerate_derivative_batch_finished',
);
}
/**
* Wrapper to call out to batch operations.
*
* @param string $function
* The name of the function we are calling for derivatives.
* @param bool|string $file
* FALSE if there is no file to load, the path to require otherwise
* @param string $pid
* The pid of the object we are performing.
* @param bool $force
* Whether we are forcing derivative regeneration or not.
* @param array $context
* The context of the current batch operation.
*/
function islandora_derivative_perform_batch_operation($function, $file, $pid, $force, &$context) {
if ($file) {
require_once $file;
}
if (function_exists($function)) {
$logging = call_user_func($function, islandora_object_load($pid), $force);
if (!empty($logging)) {
$context['results']['logging'][] = $logging;
}
}
else {
watchdog('islandora', 'Unable to call derivative function @function as it was not found!', array('@function' => $function), WATCHDOG_ERROR);
}
}
/**
* Finished function for derivative batch regeneration.
*
* @param array $success
* An array of success passed from the batch.
* @param array $results
* An array of results passed from the batch.
* @param array $operations
* An array of operations passed from the batch.
*/
function islandora_regenerate_derivative_batch_finished($success, $results, $operations) {
module_load_include('inc', 'islandora', 'includes/derivatives');
if (!empty($results['logging'])) {
islandora_derivative_logging($results['logging']);
}
}

843
includes/solution_packs.inc

@ -1,843 +0,0 @@
<?php
/**
* @file
* Admin and callback functions for solution pack management.
*/
/**
* Get the information about required object.
*
* @param string $module
* An optional string, identifying a module for which to get the required
* object information.
*
* @return array
* An associative array of info describing the required objects. If $module
* is not provided (or is NULL), then we provide the info for all modules. If
* $module is provided and we have info for the given module, only the info
* for that module is provided. If $module is provided and we have no info
* for the given module, we throw an exception.
*/
function islandora_solution_packs_get_required_objects($module = NULL) {
// Should make this statically cache, after figuring out how exactly it
// should be called... We occasionally load a module and attempt to install
// it's object right away (in the same request)... This would require
// resetting of the cache. Let's just not cache for now...
$required_objects = array();
if (!$required_objects) {
$connection = islandora_get_tuque_connection();
if (isset($module)) {
// The module may be disabled when this function runs, as modules must be
// disabled before they can be uninstalled. We must manually load the
// module file to use it's islandora_required_objects hook.
module_load_include('module', $module, $module);
$required_objects = module_invoke($module, 'islandora_required_objects', $connection);
}
else {
$required_objects = module_invoke_all('islandora_required_objects', $connection);
}
}
if ($module !== NULL) {
if (isset($required_objects[$module])) {
return $required_objects[$module];
}
else {
watchdog('islandora', 'Attempted to get required objects for %module... %module does not appear to have any required objects. Clear caches?', array(
'%module' => $module,
));
throw new Exception(t('Module "@module" has no required objects!', array(
'@module' => $module,
)));
}
}
else {
return $required_objects;
}
}
/**
* Solution pack admin page callback.
*
* @return array
* Renderable array 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 '';
}
drupal_add_css(drupal_get_path('module', 'islandora') . '/css/islandora.admin.css');
$output = array();
$enabled_solution_packs = islandora_solution_packs_get_required_objects();
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']);
$output[$solution_pack_module] = drupal_get_form('islandora_solution_pack_form_' . $solution_pack_module, $solution_pack_module, $solution_pack_name, $objects);
}
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);
// Prepair for tableselect.
$header = array(
'label' => t('Label'),
'pid' => t('PID'),
'status' => t('Status'));
$object_info = 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']}";
$object_info[] = array(
'label' => $label,
'pid' => $object->id,
'status' => $status_msg);
}
$solution_pack_status = $status_severities[$solution_pack_status_severity];
$solution_pack_status_info = $status_info[$solution_pack_status];
$form = 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' => 'tableselect',
'#header' => $header,
'#options' => $object_info,
),
'tablevalue' => array(
'#type' => 'hidden',
'#value' => json_encode($object_info),
),
'submit' => array(
'#type' => 'submit',
'#name' => $solution_pack_module,
'#value' => $solution_pack_status_info['button'],
'#attributes' => array('class' => array('islandora-solution-pack-submit')),
),
),
);
return $form;
}
/**
* 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) {
$not_checked = array();
$object_info = json_decode($form_state['values']['tablevalue']);
if (isset($form_state['values']['table'])) {
foreach ($form_state['values']['table'] as $key => $value) {
if ($value === 0) {
$not_checked[] = $object_info[$key]->pid;
}
}
}
$solution_pack_module = $form_state['values']['solution_pack_module'];
// Use not_checked instead of checked. Remove not checked item from betch. so
// that get batch function can get all object ingest batch if not checked list
// is empty.
$batch = islandora_solution_pack_get_batch($solution_pack_module, $not_checked);
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);
}
/**
* Get the batch definition to reinstall all the objects for a given module.
*
* @param string $module
* The name of the modules of which to grab the required objects for to setup
* the batch.
* @param array $not_checked
* The object that will bot be install.
*
* @return array
* An array defining a batch which can be passed on to batch_set().
*/
function islandora_solution_pack_get_batch($module, $not_checked = array()) {
$batch = array(
'title' => t('Installing / Updating solution pack objects'),
'file' => drupal_get_path('module', 'islandora') . '/includes/solution_packs.inc',
'operations' => array(),
);
$info = islandora_solution_packs_get_required_objects($module);
foreach ($info['objects'] as $key => $object) {
foreach ($not_checked as $not) {
if ($object->id == $not) {
unset($info['objects'][$key]);
}
}
}
foreach ($info['objects'] as $object) {
$batch['operations'][] = array('islandora_solution_pack_batch_operation_reingest_object', array($object));
}
return $batch;
}
/**
* Batch operation to ingest/reingest required object(s).
*
* @param AbstractObject $object
* The object to ingest/reingest.
* @param array $context
* The context of this batch operation.
*/
function islandora_solution_pack_batch_operation_reingest_object(AbstractObject $object, array &$context) {
$existing_object = islandora_object_load($object->id);
$deleted = FALSE;
if ($existing_object) {
$deleted = islandora_delete_object($existing_object);
if (!$deleted) {
$object_link = l($existing_object->label, "islandora/object/{$existing_object->id}");
drupal_set_message(filter_xss(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;
$object_link = l($label, "islandora/object/{$pid}");
$object = islandora_add_object($object);
$params = array(
'@pid' => $pid,
'@label' => $label,
'!object_link' => $object_link,
);
$msg = '';
if ($object) {
if ($deleted) {
$msg = t('Successfully reinstalled !object_link.', $params);
}
else {
$msg = t('Successfully installed !object_link.', $params);
}
}
elseif ($deleted) {
$msg = t('Failed to reinstall @label, identified by @pid.', $params);
}
else {
$msg = t('Failed to install @label, identified by @pid.', $params);
}
$status = $object ? 'status' : 'error';
drupal_set_message(filter_xss($msg), $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.
* @param bool $force
* Force the (un)installation of object.
*
* @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', $force = FALSE) {
if ($op == 'uninstall') {
islandora_uninstall_solution_pack($module, $force);
return;
}
$t = get_t();
// Some general replacements.
$admin_link = l($t('Solution Pack admin'), 'admin/islandora/solution_packs');
$config_link = l($t('Islandora configuration'), 'admin/islandora/configure');
$t_params = array(
'@module' => $module,
'!config_link' => $config_link,
'!admin_link' => $admin_link,
);
drupal_load('module', 'islandora');
module_load_include('inc', 'islandora', 'includes/utilities');
drupal_load('module', $module);
$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 = $t('@module: Did not install any objects. Could not connect to the repository. Please check the settings on the !config_link page and install the required objects manually on the !admin_link page.', $t_params);
drupal_set_message(filter_xss($msg), 'error');
return;
}
$connection = islandora_get_tuque_connection();
$required_objects = islandora_solution_packs_get_required_objects($module);
$objects = $required_objects['objects'];
$status_messages = array(
'up_to_date' => $t('The object already exists and is up-to-date.', $t_params),
'missing_datastream' => $t('The object already exists but is missing a datastream. Please reinstall the object on the !admin_link page.', $t_params),
'out_of_date' => $t('The object already exists but is out-of-date. Please update the object on the !admin_link page.', $t_params),
'modified_datastream' => $t('The object already exists but datastreams are modified. Please reinstall the object on the !admin_link page.', $t_params),
);
foreach ($objects as $object) {
$already_exists = islandora_object_load($object->id);
$label = $object->label;
$object_link = l($label, "islandora/object/{$object->id}");
$deleted = FALSE;
if ($already_exists) {
if (!$force) {
$object_status = islandora_check_object_status($object);
$here_params = array(
'!summary' => $t("@module: Did not install !object_link.", array(
'!object_link' => $object_link,
) + $t_params),
'!description' => $status_messages[$object_status['status']],
);
drupal_set_message(filter_xss(format_string('!summary !description', $here_params)), 'warning');
continue;
}
else {
$deleted = islandora_delete_object($already_exists);
}
}
if ($already_exists && $deleted || !$already_exists) {
$object = islandora_add_object($object);
if ($object) {
if ($deleted) {
drupal_set_message(filter_xss($t('@module: Successfully reinstalled. !object_link.', array(
'!object_link' => $object_link,
) + $t_params)), 'status');
}
else {
drupal_set_message(filter_xss($t('@module: Successfully installed. !object_link.', array(
'!object_link' => $object_link,
) + $t_params)), 'status');
}
}
else {
drupal_set_message($t('@module: Failed to install. @label.', array(
'@label' => $label,
) + $t_params), 'warning');
}
}
else {
drupal_set_message($t('@module: "@label" already exists and failed to be deleted.', array(
'@label' => $label,
) + $t_params), 'warning');
}
}
}
/**
* Uninstalls the given solution pack.
*
* @param string $module
* The solution pack to uninstall.
* @param bool $force
* Force the objects to be removed.
*
* @todo Implement hook_modules_uninstalled instead of calling this function
* directly for each solution pack.
*/
function islandora_uninstall_solution_pack($module, $force = FALSE) {
$t = get_t();
drupal_load('module', 'islandora');
module_load_include('inc', 'islandora', 'includes/utilities');
drupal_load('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 = $t('@module: Did not uninstall any objects. Could not connect to the repository. Please check the settings on the !config_link page and uninstall the required objects manually if necessary.', array(
'@module' => $module_name,
'!config_link' => $config_link,
));
drupal_set_message(filter_xss($msg), 'error');
return;
}
$connection = islandora_get_tuque_connection();
$required_objects = islandora_solution_packs_get_required_objects($module);
$objects = $required_objects['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);
if (!$force) {
foreach ($existing_objects as $object) {
$object_link = l($object->label, "islandora/object/{$object->id}");
$msg = $t('@module: Did not remove !object_link. It may be used by other sites.', array(
'!object_link' => $object_link,
'@module' => $module_name,
));
drupal_set_message(filter_xss($msg), 'warning');
}
}
else {
foreach ($existing_objects as $object) {
$params = array(
'@id' => $object->id,
'@module' => $module_name,
);
islandora_delete_object($object);
drupal_set_message($t('@module: Deleted @id.', $params));
}
}
}
/**
* Function to check the status of an object against an object model array.
*
* @param AbstractObject $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(AbstractObject $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
// will sometimes replace new-lines with white-space. So first we strip
// leading/tailing white-space and replace all new-lines within the xml
// document to account for Fedora's weird formatting.
$xsl = new DOMDocument();
$xsl->load(drupal_get_path('module', 'islandora') . '/xml/strip_newlines_and_whitespace.xsl');
$xslt = new XSLTProcessor();
$xslt->importStyleSheet($xsl);
$object_definition_dom = new DOMDocument();
$object_definition_dom->preserveWhiteSpace = FALSE;
$object_definition_dom->loadXML(str_replace('info:', 'http://', $ds->content));
$object_definition_dom = $xslt->transformToDoc($object_definition_dom);
$object_actual_dom = new DOMDocument();
$object_actual_dom->preserveWhiteSpace = FALSE;
$object_actual_dom->loadXML(str_replace('info:', 'http://', $existing_object[$ds->id]->content));
$object_actual_dom = $xslt->transformToDoc($object_actual_dom);
// 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 array $mimetype
* List of mimetypes that the viewer supports.
* @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 = array(), $content_model = NULL) {
$viewers = array();
$defined_viewers = module_invoke_all('islandora_viewer_info');
if (!is_array($mimetype)) {
$mimetype = array($mimetype);
}
// 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 (array_intersect($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 AbstractObject $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);
if (function_exists($callback)) {
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".
*/

116
includes/tuque.inc

@ -1,116 +0,0 @@
<?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 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';
@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";
class IslandoraTuque {
/**
* Connection to the repository
*
* @var RepositoryConnection
*/
public $connection = NULL;
/**
* The Fedora API we are using
*
* @var FedoraAPI
*/
public $api = NULL;
/**
* The cache we use to connect.
*
* @var SimpleCache
*/
public $cache = NULL;
/**
* The repository object.
*
* @var FedoraRepository
*/
public $repository = NULL;
/**
* 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 ($user->uid == 0) {
$user_string = 'anonymous';
$pass_string = 'anonymous';
}
else {
$user_string = $user->name;
$pass_string = $user->pass;
}
if (!isset($url)) {
$url = variable_get('islandora_base_url', 'http://localhost:8080/fedora');
}
if (self::exists()) {
module_load_include('inc', 'islandora', 'includes/tuque_wrapper');
$this->connection = new IslandoraRepositoryConnection($url, $user_string, $pass_string);
$this->connection->reuseConnection = TRUE;
$this->api = new IslandoraFedoraApi($this->connection);
$this->cache = new IslandoraSimpleCache();
$this->repository = new IslandoraFedoraRepository($this->api, $this->cache);
}
}
/**
* Checks if the Connection class exists.
*
* @returns bool
* TRUE if the Connection class exists FALSE otherwise.
*/
public static function exists() {
return class_exists('RepositoryConnection');
}
/**
* 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(filter_xss($message), 'error', FALSE);
}
}

385
includes/tuque_wrapper.inc

@ -1,385 +0,0 @@
<?php
/**
* @file
* Wrapper around the tuque library, allows for autoloading of Islandora Tuque
* Objects.
*
* @todo Overload functions and apply pre/post hooks.
*/
// This function may not exist when a batch operation is running from a
// multistep form.
if (function_exists('drupal_get_path')) {
$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(AbstractObject $object, array &$context) {
module_load_include('inc', 'islandora', 'includes/utilities');
drupal_alter(islandora_build_hook_list('islandora_object', $object->models), $object, $context);
}
/**
* Allow modules to alter a datastream before a mutable event occurs.
*/
function islandora_alter_datastream(AbstractObject $object, AbstractDatastream $datastream, array &$context) {
module_load_include('inc', 'islandora', 'includes/utilities');
$types = array();
foreach ($object->models as $model) {
$types[] = "{$model}_{$datastream->id}";
}
drupal_alter(islandora_build_hook_list('islandora_datastream', $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) {
try {
foreach ($object as $dsid => $datastream) {
$datastream_context = array(
'action' => 'ingest',
'block' => FALSE,
);
islandora_alter_datastream($object, $datastream, $datastream_context);
if ($datastream_context['block']) {
throw new Exception(t('Object ingest blocked due to ingest of @dsid being blocked.', array(
'@dsid' => $dsid,
)));
}
}
$object_context = array(
'action' => 'ingest',
'block' => FALSE,
);
islandora_alter_object($object, $object_context);
if ($object_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);
$params = $context['params'];
if (isset($params['lastModifiedDate'])) {
$params['lastModifiedDate'] = (string) $object[$dsid]->createdDate;
}
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);
$params = $context['params'];
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.');
case 'delete':
$object[$dsid]->state = 'D';
return array();
default:
$ret = parent::purgeDatastream($pid, $dsid, $params);
// We need to remove this object from the cache and reload it as
// Tuque may not have an updated copy. That is the datastream could
// still be present within the object even though it's purged out of
// Fedora.
$tuque = islandora_get_tuque_connection();
$tuque->cache->delete($pid);
$non_cached_object = islandora_object_load($pid);
islandora_invoke_datastream_hooks(ISLANDORA_DATASTREAM_PURGED_HOOK, $non_cached_object->models, $dsid, $non_cached_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.');
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 {}

997
includes/utilities.inc

@ -1,997 +0,0 @@
<?php
/**
* @file
* Utility functions.
*
* @todo this file should be broken out into other files.
*/
/**
* Convert bytes to human readable format.
*
* XXX: Shouldn't Drupal's format_size() be preferred?
*
* @param int $bytes
* Size in bytes to convert
* @param int $precision
* The amount of decimal precision to show.
*
* @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;
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) {
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;
}
}
/**
* Checks if the given pid is valid.
*
* @param string $pid
* The object id to check.
*
* @return bool
* TRUE if valid, FALSE otherwise.
*/
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 namespace is valid.
*
* @param string $namespace
* The namespace to check without the ":" character.
*
* @return bool
* TRUE if valid, FALSE otherwise.
*/
function islandora_is_valid_namespace($namespace) {
return drupal_strlen(trim($namespace)) <= 64 && preg_match('/^([A-Za-z0-9]|-|\.)+$/', trim($namespace));
}
/**
* 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;
}
/**
* 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;
}
/**
* 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_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;
}
/**
* 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
);
}
/**
* 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_namespace_accessible($id) {
if (variable_get('islandora_namespace_restriction_enforced', FALSE)) {
$namespace = islandora_get_namespace($id);
$allowed_namespaces = islandora_get_allowed_namespaces();
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 AbstractObject $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(AbstractObject $object) {
try {
$collections = array_merge(
$object->relationships->get(FEDORA_RELS_EXT_URI, 'isMemberOfCollection'),
$object->relationships->get(FEDORA_RELS_EXT_URI, 'isMemberOf'));
}
catch (RepositoryException $e) {
// @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 AbstractObject $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(AbstractObject $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 AbstractObject $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(AbstractObject $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 AbstractObject $object
* The content model whose DS-COMPOSITE-MODEL datastream will be used to
* determine what datastreams are required.
*
* @return array
* An associative array mapping datastream IDs to associative arrays
* containing the values parsed from the DS-COMPOSITE-MODEL on the given
* object--of the form:
* - DSID: A datastream ID being described.
* - "id": A string containing ID of the datastream.
* - "mime": A array containing MIME-types the stream may have.
* - "optional": A boolean indicating if the given stream is optional.
*/
function islandora_get_datastreams_requirements_from_content_model(AbstractObject $object) {
if (empty($object[ISLANDORA_DS_COMP_STREAM]) || !islandora_datastream_access(ISLANDORA_VIEW_OBJECTS, $object[ISLANDORA_DS_COMP_STREAM])) {
return array();
}
$xml = new SimpleXMLElement($object[ISLANDORA_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'];
}
$as_file = FALSE;
if (file_valid_uri($ds['datastream_file'])) {
// A local file with as a Drupal file/stream wrapper URI.
$datastream_file = $ds['datastream_file'];
$as_file = TRUE;
}
elseif (is_readable($ds['datastream_file'])) {
// A local file as a filesystem path.
$datastream_file = drupal_realpath($ds['datastream_file']);
$as_file = TRUE;
}
else {
$scheme = parse_url($ds['datastream_file'], PHP_URL_SCHEME);
if (in_array($scheme, stream_get_wrappers())) {
// A URI which gets handled by one of the PHP-native stream wrappers.
$datastream_file = $ds['datastream_file'];
$as_file = TRUE;
}
else {
// Schema does not match available php stream wrapper. Attempt to
// set datastream_file by url for the given scheme. Https (SSL) can
// cause this to fail, and trigger an output log in watchdog.
$datastream_file = url($ds['datastream_file'], array('absolute' => TRUE));
watchdog('islandora',
'Attempting to ingest %file in islandora_prepare_new_object(), but it does not appear to be readable. We will pass the path through url(), and pass along as such.',
array('%file' => $datastream_file),
WATCHDOG_WARNING);
}
}
$datastream = $object->constructDatastream($dsid, $control_group);
$datastream->label = $label;
$datastream->mimetype = $mimetype;
switch ($control_group) {
case 'M':
if ($as_file) {
$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(filter_xss($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);
}
/**
* Returns basic information about DS-COMPOSITE-MODEL.
*
* @deprecated
* The pre-existing--and more flexible--
* islandora_get_datastreams_requirements_from_content_model() should be
* preferred, as it addresses the case where a stream can be allowed to have
* one of a set of mimetypes (this functions appears to only return the last
* declared mimetype for a given datastream).
*
* @param string $pid
* The PID of content model containing DS_COMP stream.
*
* @return array
* An associative array mapping datastream IDs to an associative array
* representing the parsed DS-COMPOSITE-MODEL of the form:
* - DSID: A string containing the datastream ID.
* - "mimetype": A string containing the last mimetype declared for the
* given datastream ID.
* - "optional": An optional boolean indicating that the given datastream
* is optional.
*/
function islandora_get_comp_ds_mappings($pid) {
$message = islandora_deprecated('7.x-1.2', t('Refactor to use the more flexible islandora_get_datastreams_requirements_from_content_model().'));
trigger_error(filter_xss($message), E_USER_DEPRECATED);
$cm_object = islandora_object_load($pid);
if (!isset($cm_object) || !isset($cm_object['DS-COMPOSITE-MODEL'])) {
return FALSE;
}
$datastream = $cm_object['DS-COMPOSITE-MODEL'];
$ds_comp_stream = $datastream->content;
$sxml = new SimpleXMLElement($ds_comp_stream);
$mappings = array();
foreach ($sxml->dsTypeModel as $ds) {
$dsid = (string) $ds['ID'];
$optional = (string) $ds['optional'];
foreach ($ds->form as $form) {
$mime = (string) $form['MIME'];
if ($optional) {
$mappings[$dsid]['optional'] = $optional;
}
$mappings[$dsid]['mimetype'] = $mime;
}
}
return $mappings;
}
/**
* Checks that the given/current account has all the given permissions.
*
* @param array $perms
* The permissions to check.
* @param mixed $account
* (optional) The account to check, if not given use currently logged in user.
*
* @return bool
* TRUE if the account has all the given permissions, FALSE otherwise.
*/
function islandora_user_access_all(array $perms, $account = NULL) {
$message = islandora_deprecated('7.x-1.2', 'Roll your own code or use islandora_user_access().');
trigger_error(filter_xss($message), E_USER_DEPRECATED);
foreach ($perms as $perm) {
if (!user_access($perm, $account)) {
return FALSE;
}
}
return TRUE;
}
/**
* Checks that the given/current account has at one of the given permissions.
*
* @param array $perms
* The permissions to check.
* @param mixed $account
* (optional) The account to check, if not given use currently logged in user.
*
* @return bool
* TRUE if the account has at least one of the given permissions, FALSE
* otherwise.
*/
function islandora_user_access_any(array $perms, $account = NULL) {
$message = islandora_deprecated('7.x-1.2', 'Roll your own code or use islandora_user_access().');
trigger_error(filter_xss($message), E_USER_DEPRECATED);
foreach ($perms as $perm) {
if (user_access($perm, $account)) {
return TRUE;
}
}
return FALSE;
}
/**
* Gets the list of allowed namespaces as defined by 'islandora_pids_allowed'.
*
* @return array
* The list of namespaces striped of trailing ":" characters.
*/
function islandora_get_allowed_namespaces() {
$matches = array();
$allowed_namespaces = variable_get('islandora_pids_allowed', 'default: demo: changeme: islandora:');
preg_match_all('/([A-Za-z0-9-\.]+):/', $allowed_namespaces, $matches);
$accessible_namespaces = $matches[1];
// Ensure that the "islandora" namespace is explicitly allowed
// no matter what happens.
if (!in_array('islandora', $accessible_namespaces)) {
$accessible_namespaces[] = 'islandora';
}
return $accessible_namespaces;
}
/**
* Gets a list of all existing content models.
*
* If 'islandora_namespace_restriction_enforced' is set to true only return
* content models in the allowed namespace.
*
* @param bool $ignore_system_namespace
* Ignore content models in the 'fedora-system' namespace.
*
* @return array
* An associative array of all existing content models.
* - pid: The PID of the content model object.
* - pid: The PID of the content model object.
* - label: The label of the content model object.
*/
function islandora_get_content_models($ignore_system_namespace = TRUE) {
module_load_include('inc', 'islandora', 'includes/utilities');
$tuque = islandora_get_tuque_connection();
$query = "PREFIX fm: <" . FEDORA_MODEL_URI . ">
PREFIX fr: <" . FEDORA_RELS_EXT_URI . ">
SELECT ?object ?label
FROM <#ri>
WHERE {
{?object fm:hasModel <info:fedora/fedora-system:ContentModel-3.0>;
fm:state fm:Active
}
UNION{
?object fr:isMemberOfCollection <info:fedora/islandora:ContentModelsCollection>;
fm:state fm:Active
}
OPTIONAL{
?object fm:label ?label
}
}";
$content_models = array();
$results = $tuque->repository->ri->sparqlQuery($query, 'unlimited');
foreach ($results as $result) {
$content_model = $result['object']['value'];
$label = $result['label']['value'];
$namespace = islandora_get_namespace($content_model);
$ignore = $ignore_system_namespace && $namespace == 'fedora-system';
$ignore |= !islandora_namespace_accessible($namespace);
if (!$ignore) {
$content_models[$content_model] = array('pid' => $content_model, 'label' => $label);
}
}
return $content_models;
}
/**
* Returns Drupal tableselect element allowing selection of Content Models.
*
* @param string $drupal_variable
* the name of the Drupal variable holding selected content models
* Content models held in this variable will appear at the top of
* the displayed list
* @param array $default_values_array
* default values to display if $drupal_variable is unset
*
* @return array
* Drupal form element allowing content model selection
*/
function islandora_content_model_select_table_form_element($drupal_variable, $default_values_array = array('')) {
$defaults = array();
$rows = array();
$content_models = array();
$options = islandora_get_content_models(TRUE);
foreach ($options as $option) {
$content_models[$option['pid']] = $option['label'];
}
$selected = array_values(variable_get($drupal_variable, $default_values_array));
$comparator = function ($a, $b) use ($selected) {
$a_val = $b_val = 0;
if (in_array($a, $selected)) {
$a_val = 1;
}
if (in_array($b, $selected)) {
$b_val = 1;
}
return $b_val - $a_val;
};
uksort($content_models, $comparator);
foreach ($content_models as $pid => $label) {
$rows[$pid] = array(
'pid' => $pid,
'title' => $label,
);
$defaults[$pid] = in_array($pid, $selected);
}
$header = array(
'pid' => array('data' => t('PID')),
'title' => array('data' => t('Content Model')),
);
// Build and return table element.
$element = array(
'#type' => 'tableselect',
'#header' => $header,
'#options' => $rows,
'#default_value' => $defaults,
'#empty' => t("There are no content models in this Fedora Repository."),
);
return $element;
}
/**
* Convience function for generating a E_USER_DEPRECATED message.
*
* To utilitize this function pass the results to trigger_error() like so:
*
* @code
* $message = islandora_deprecated('7.x-1.1', t('Use more cowbell.'))
* trigger_error(filter_xss($message), E_USER_DEPRECATED)
* @endcode
*
* @param string $release
* The release the calling function was depreciated in.
* @param string $solution
* A message describing an alternative solution to the deprecated function.
* It's assumed to be already passed though the t() function.
*
* @return string
* The deprecated message.
*/
function islandora_deprecated($release, $solution = NULL) {
$bt = debug_backtrace();
assert($bt[0]['function'] == __FUNCTION__);
$function = $bt[1]['function'];
$message = t('@function() has been deprecated. As of @release, please update your code before the next release.', array(
'@function' => $function,
'@release' => $release,
));
if (isset($solution)) {
$message .= "<br/>\n" . $solution;
}
return $message;
}
/**
* Transform recursively-merged array of strings to renderable arrays.
*
* Renderable arrays are passed-through as-is.
*
* Previously, functions/hooks like islandora_view_object would return an
* associative array with string values containing markup. These values were
* then imploded into one large piece of markup. Here, we transform this older
* structure which was generated into a renderable array, because renderable
* arrays are awesome!
*
* @param array $markup_array
* An associative array of which the values are either a string or an array
* of strings, which we transform to renderable markup elements (by
* reference).
*/
function islandora_as_renderable_array(&$markup_array) {
foreach ($markup_array as &$value) {
if (!is_array($value)) {
// Not a renderable array, just a string. Let's convert it to a
// renderable '#markup' element.
$value = array('#markup' => $value);
}
elseif (!isset($value['#type']) && !isset($value['#markup'])) {
// A simple array--possibly the result of a recursive merge? Let's
// look at each, to possibly convert them to a renderable '#markup'
// elements.
foreach ($value as &$inner) {
if (!is_array($inner)) {
// If it is an array at this level, we can assume that it is a
// renderable array. If it is not an array, convert to a renderable
// '#markup' element.
$inner = array('#markup' => $inner);
}
}
unset($inner);
}
}
unset($value);
}
/**
* Sanitizes an input string to be valid XML.
*
* @param string $input
* An input string.
* @param string $replacement
* What we are replacing invalid characters with, defaults to ''.
*
* @return string
* The sanitized string.
*/
function islandora_sanitize_input_for_valid_xml($input, $replacement = '') {
$input = preg_replace('/[^\x9\xA\xD\x20-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]/u', $replacement, $input);
return $input;
}
/**
* Page callback for session status messages to be sent to drupal_set_message().
*
* @return array
* Render array containing markup.
*/
function islandora_event_status() {
$results = FALSE;
if (isset($_SESSION['islandora_event_messages'])) {
foreach ($_SESSION['islandora_event_messages'] as $message) {
drupal_set_message($message['message'], $message['severity']);
$results = TRUE;
}
unset($_SESSION['islandora_event_messages']);
}
$text = ($results) ? t('The status messages above will be deleted after viewing this page.') : t('No messages to display.');
return array('#markup' => $text);
}
/**
* Scales the given image.
*
* @param object $file
* The image file to scale.
* @param int $width
* The width to scale the derived image to.
* @param int $height
* The height to scale the derived image to.
*
* @return bool
* TRUE if successful, FALSE otherwise.
*/
function islandora_scale_thumbnail($file, $width, $height) {
$real_path = drupal_realpath($file->uri);
$image = image_load($real_path);
try {
if (!empty($image)) {
$scale = image_scale($image, $width, $height, TRUE);
if ($scale) {
return image_save($image);
}
}
}
catch (exception $e) {
drupal_set_message(t(
"Islandora failed to scale image with message: '@message'",
array("@message" => $e->getMessage())));
watchdog(
'islandora',
'Islandora failed to scale image.<br/> With stack: @trace',
array('@trace' => $e->getTraceAsString()),
WATCHDOG_ERROR
);
}
return FALSE;
}
/**
* Determines if the server operating system is Windows.
*
* @return bool
* TRUE if Windows, FALSE otherwise.
*/
function islandora_deployed_on_windows() {
// Determine if PHP is currently running on Windows.
if (strpos(strtolower(php_uname('s')), 'windows') !== FALSE) {
return TRUE;
}
return FALSE;
}

758
islandora.api.php

@ -1,758 +0,0 @@
<?php
/**
* @file
* This file documents all available hook functions to manipulate data.
*/
/**
* Generate a repository objects view.
*
* @param AbstractObject $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.
*
* @return array
* An array whose values are markup.
*/
function hook_islandora_view_object($object, $user, $page_number, $page_size) {
$output = array();
if (in_array('islandora:sp_basic_image', $object->models)) {
$resource_url = url("islandora/object/{$object->id}/datastream/OBJ/view");
$params = array(
'title' => $object->label,
'path' => $resource_url,
);
// Theme the image seperatly.
$variables['islandora_img'] = theme('image', $params);
$output = theme('islandora_default_print', array(
'islandora_content' => $variables['islandora_img']));
}
return $output;
}
/**
* Generate a print friendly page for the given object.
*
* @param object $object
* The object form to print.
*/
function hook_islandora_view_print_object($object) {
}
/**
* 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 AbstractObject $object
* A Tuque FedoraObject
*
* @return array
* An array whose values are markup.
*/
function hook_CMODEL_PID_islandora_view_object($object) {
}
/**
* Alter display output after it has been generated.
*
* @param AbstractObject $object
* A Tuque AbstractObject being operated on.
* @param array $rendered
* The array of rendered views.
*/
function hook_islandora_view_object_alter(&$object, &$rendered) {
}
/**
* Alter display output if the object has the given model.
*
* @see hook_islandora_view_object_alter()
*
* @param AbstractObject $object
* A Tuque AbstractObject being operated on.
* @param array $rendered
* The array of rendered views.
*/
function hook_CMODEL_PID_islandora_view_object_alter(&$object, &$rendered) {
}
/**
* Generate an object's datastreams management display.
*
* @param AbstractObject $object
* A Tuque FedoraObject
*
* @return array
* An array whose values are markup.
*/
function hook_islandora_edit_object($object) {
}
/**
* Generate an object's datastreams management display based on content model.
*
* Content models PIDs have colons and hyphens changed to underscores, to
* create the hook name.
*
* @param AbstractObject $object
* A Tuque FedoraObject
*
* @return array
* An array whose values are markup.
*/
function hook_CMODEL_PID_islandora_edit_object($object) {
}
/**
* Allow datastreams management display output to be altered.
*
* @param AbstractObject $object
* A Tuque FedoraObject
* @param array $rendered
* an arr of rendered views
*/
function hook_islandora_edit_object_alter(&$object, &$rendered) {
}
/**
* 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 AbstractObject $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_object_alter(AbstractObject $object, array &$context) {
}
/**
* Allows modules to alter the object or block/modify the given action.
*
* @see hook_islandora_object_alter()
*/
function hook_CMODEL_PID_islandora_object_alter(AbstractObject $object, array &$context) {
}
/**
* 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 AbstractObject 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 AbstractObject $object
* The object to the datastream belong to.
* @param AbstractDatastream $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_datastream_alter(AbstractObject $object, AbstractDatastream $datastream, array &$context) {
}
/**
* Allows modules to alter the datastream or block/modify the given action.
*
* @see hook_islandora_datastream_alter()
*/
function hook_CMODEL_PID_DSID_islandora_datastream_alter(AbstractObject $object, AbstractDatastream $datastream, array &$context) {
}
/**
* 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 AbstractObject $object
* The object that was ingested.
*/
function hook_islandora_object_ingested(AbstractObject $object) {
}
/**
* Notify modules that the given object was ingested.
*
* @see hook_islandora_object_ingested()
*/
function hook_CMODEL_PID_islandora_object_ingested(AbstractObject $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 AbstractObject $object
* The object that was ingested.
*
* @todo We should also include what changes were made in a additional
* parameter.
*/
function hook_islandora_object_modified(AbstractObject $object) {
}
/**
* Notify modules that the given object was ingested.
*
* @see hook_islandora_object_modified()
*/
function hook_CMODEL_PID_islandora_object_modified(AbstractObject $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 AbstractObject $object
* The object the datastream belongs to.
* @param AbstractDatastream $datastream
* The ingested datastream.
*/
function hook_islandora_datastream_ingested(AbstractObject $object, AbstractDatastream $datastream) {
}
/**
* Notify modules that the given datastream was ingested.
*
* @see hook_islandora_object_ingested()
*/
function hook_CMODEL_PID_DSID_islandora_datastream_ingested(AbstractObject $object, AbstractDatastream $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 AbstractObject $object
* The object the datastream belongs to.
* @param AbstractDatastream $datastream
* The datastream that was ingested.
*
* @todo We should also include what changes were made in a additional
* parameter.
*/
function hook_islandora_datastream_modified(AbstractObject $object, AbstractDatastream $datastream) {
}
/**
* Notify modules that the given datastream was modified.
*
* @see hook_islandora_datastream_modified()
*/
function hook_CMODEL_PID_islandora_datastream_modified(AbstractObject $object, AbstractDatastream $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 AbstractObject $object
* The object the datastream belonged to.
* @param string $dsid
* The ID of the datastream that was purged/deleted.
*/
function hook_islandora_datastream_purged(AbstractObject $object, $dsid) {
}
/**
* Notify modules that the given datastream was purged/deleted.
*
* @see hook_islandora_datastream_purged()
*/
function hook_CMODEL_PID_islandora_datastream_purged(AbstractObject $object, $dsid) {
}
/**
* Register a datastream edit route/form.
*
* @param AbstractObject $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.
*
* The list is used to prevent delete links from being shown.
*
* @param array $models
* An array of content models for the current object.
*
* @return array
* An array of DSIDs that shouldn't be deleted.
*/
function hook_islandora_undeletable_datastreams(array $models) {
return array('DC', 'MODS');
}
/**
* 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) which take different paramaters based upon type:
* - type: Type of step. Only "form" and "callback" are implemented so far.
* Required "form" type specific parameters:
* - 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.
* Required "callback" type specific parameters:
* - do_function: An associate array including:
* - 'function': The callback function to be called.
* - 'args': An array of arguments to pass to the callback function.
* - 'file': A file to include (relative to the module's path, including
* the file's extension).
* - undo_function: An associate array including:
* - 'function': The callback function to be called to reverse the
* executed action in the ingest steps.
* - 'args': An array of arguments to pass to the callback function.
* - 'file': A file to include (relative to the module's path, including
* the file's extension).
* Shared parameters between both types:
* - weight: The "weight" of this step--heavier(/"larger") values sink to the
* end of the process while smaller(/"lighter") values are executed first.
* Both types may optionally include:
* - module: A module from which we want to load an include.
* "Form" type may optionally 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'),
),
'my_cool_step_callback' => array(
'type' => 'callback',
'weight' => 2,
'do_function' => array(
'function' => 'my_cool_execute_function',
'args' => array('arg_one', 'numero deux'),
),
'undo_function' => array(
'function' => 'my_cool_undo_function',
'args' => array('arg_one', 'numero deux'),
),
),
);
}
/**
* Alter the generated ingest steps.
*
* @param array $steps
* An array of steps as generated by hook_islandora_ingest_steps().
*
* @param array $form_state
* An array containing the Drupal form_state.
*/
function hook_islandora_ingest_steps_alter(array &$steps, array &$form_state) {
}
/**
* 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) {
}
/**
* Alter the generated ingest steps for the given content model.
*
* @param array $steps
* An array of steps as generated by hook_islandora_ingest_steps().
*
* @param array $form_state
* An array containing the Drupal form_state.
*/
function hook_CMODEL_PID_islandora_ingest_steps_alter(array &$steps, array &$form_state) {
}
/**
* Object-level access callback hook.
*
* @param string $op
* A string define an operation to check. Should be defined via
* hook_permission().
* @param AbstractObject $object
* An object to check the operation on.
* @param object $user
* A loaded user object, as the global $user variable might contain.
*
* @return bool|NULL|array
* Either boolean TRUE or FALSE to explicitly allow or deny the operation on
* the given object, or NULL to indicate that we are making no assertion
* about the outcome. Can also be an array containing multiple
* TRUE/FALSE/NULLs, due to how hooks work.
*/
function hook_islandora_object_access($op, $object, $user) {
switch ($op) {
case 'create stuff':
return TRUE;
case 'break stuff':
return FALSE;
case 'do a barrel roll!':
return NULL;
}
}
/**
* Content model specific version of hook_islandora_object_access().
*
* @see hook_islandora_object_access()
*/
function hook_CMODEL_PID_islandora_object_access($op, $object, $user) {
}
/**
* Datastream-level access callback hook.
*
* @param string $op
* A string define an operation to check. Should be defined via
* hook_permission().
* @param AbstractDatastream $object
* An object to check the operation on.
* @param object $user
* A loaded user object, as the global $user variable might contain.
*
* @return bool|NULL|array
* Either boolean TRUE or FALSE to explicitly allow or deny the operation on
* the given object, or NULL to indicate that we are making no assertion
* about the outcome. Can also be an array containing multiple
* TRUE/FALSE/NULLs, due to how hooks work.
*/
function hook_islandora_datastream_access($op, $object, $user) {
switch ($op) {
case 'create stuff':
return TRUE;
case 'break stuff':
return FALSE;
case 'do a barrel roll!':
return NULL;
}
}
/**
* Content model specific version of hook_islandora_datastream_access().
*
* @see hook_islandora_datastream_access()
*/
function hook_CMODEL_PID_islandora_datastream_access($op, $object, $user) {
}
/**
* Lets one add to the overview tab in object management.
*/
function hook_islandora_overview_object(AbstractObject $object) {
return drupal_render(drupal_get_form('some_form', $object));
}
/**
* Lets one add to the overview tab in object management.
*
* Content model specific.
*/
function hook_CMODEL_PID_islandora_overview_object(AbstractObject $object) {
return drupal_render(drupal_get_form('some_form', $object));
}
/**
* Lets one alter the overview tab in object management.
*/
function hook_islandora_overview_object_alter(AbstractObject &$object, &$output) {
$output = $output . drupal_render(drupal_get_form('some_form', $object));
}
/**
* Lets one alter the overview tab in object management.
*
* Content model specific.
*/
function hook_CMODEL_PID_islandora_overview_object_alter(AbstractObject &$object, &$output) {
$output = $output . drupal_render(drupal_get_form('some_form', $object));
}
/*
* Defines derivative functions to be executed based on certain conditions.
*
* @param AbstractObject $object
* Object to which derivatives will be added
* This hook fires when an object/datastream is ingested or a datastream is
* modified.
*
* @return array
* An array containing an entry for each derivative to be created. Each entry
* is an array of parameters containing:
* - force: Bool denoting whether we are forcing the generation of
* derivatives.
* - source_dsid: (Optional) String of the datastream id we are generating
* from or NULL if it's the object itself.
* - destination_dsid: (Optional) String of the datastream id that is being
* created. To be used in the UI.
* - weight: A string denoting the weight of the function. This value is
* sorted upon to run functions in order.
* - function: An array of function(s) to be ran when constructing
* derivatives. Functions that are defined to be called for derivation
* creation must have the following structure:
* module_name_derivative_creation_function($object, $force = FALSE)
* These functions must return an array in the structure of:
* - success: Bool denoting whether the operation was successful.
* - messages: An array structure containing zero or more array's with the
* following fields:
* - message: A string passed through t() describing the
* outcome of the operation.
* - message_sub: (Optional) Substitutions to be passed along to t() or
* watchdog.
* - type: A string denoting whether the output is to be
* drupal_set_messaged (dsm) or watchdogged (watchdog).
* - severity: (Optional) A severity level / status to be used when
* logging messages. Uses the defaults of drupal_set_message and
* watchdog if not defined.
* - file: A string denoting the path to the file where the function
* is being called from.
*/
function hook_islandora_derivative(AbstractObject $object) {
$derivatives[] = array(
'source_dsid' => 'OBJ',
'destination_dsid' => 'DERIV',
'weight' => '0',
'function' => array(
'islandora_derivatives_test_create_deriv_datastream',
),
);
// Test object before adding this derivative.
if ($object['SOMEWEIRDDATASTREAM']->mimetype == "SOMETHING/ODD") {
$derivatives[] = array(
'source_dsid' => 'SOMEWEIRDDATASTREAM',
'destination_dsid' => 'STANLEY',
'weight' => '-1',
'function' => array(
'islandora_derivatives_test_create_some_weird_datastream',
),
);
}
$derivatives[] = array(
'source_dsid' => NULL,
'destination_dsid' => 'NOSOURCE',
'weight' => '-3',
'function' => array(
'islandora_derivatives_test_create_nosource_datastream',
),
);
return $derivatives;
}
/**
* Content model specific version of hook_islandora_derivative().
*
* @see hook_islandora_derivative()
*/
function hook_CMODEL_PID_islandora_derivative() {
}
/**
* Retrieves PIDS of related objects for property updating.
*
* @param AbstractObject $object
* AbstractObject representing deleted object
*/
function hook_islandora_update_related_objects_properties(AbstractObject $object) {
$related_objects = get_all_children_siblings_and_friends($object);
$pids_to_return = array();
foreach ($related_objects as $related_object) {
$pids_to_return[] = $related_object->id;
}
return $pids_to_return;
}
/**
* Alters breadcrumbs used on Solr search results and within Islandora views.
*
* @param array $breadcrumbs
* Breadcrumbs array to be altered by reference. Each element is markup.
* @param string $context
* Where the alter is originating from for distinguishing.
* @param AbstractObject $object
* (Optional) AbstractObject representing object providing breadcrumb path
*/
function hook_islandora_breadcrumbs_alter(&$breadcrumbs, $context, $object = NULL) {
}
/**
* Registry hook for metadata display viewers.
*
* Modules can use this hook to override the default Dublin Core display.
* This hook lets Islandora know which viewers there are available.
*
* @return array
* An associative array where the values are the following:
* -label: Human readable display label for selection.
* -description: A description of what the metadata display viewer does.
* -metadata callback: A callable function that provides the markup to be
* passed off to the template files. Returns markup or FALSE if the viewer
* wishes to default back to the Dublin Core display for the current object.
* -description callback: A callable function that provides the markup to be
* passed for the description. Returns markup or FALSE if the viewer
* wishes to default back to the Dublin Core display for the current object.
* -configuration (Optional): A path to the administration page for the
* metadata display.
* @see islandora_retrieve_metadata_markup()
*/
function hook_islandora_metadata_display_info() {
return array(
'hookable_displays_yay' => array(
'label' => t('Hookable display yay!'),
'description' => t('This is purely an example of how to implement this.'),
'metadata callback' => 'hookable_displays_some_function_that_returns_metadata_markup',
'description callback' => 'hookable_displays_some_function_that_returns_description_markup',
'configuration' => 'admin/hookable_displays_yay/somepath',
),
);
}

201
islandora.drush.inc

@ -1,201 +0,0 @@
<?php
/**
* @file
* Drush command/hook implementation.
*/
/**
* Implements hook_drush_command().
*/
function islandora_drush_command() {
$commands = array();
$commands['islandora-solution-pack-install-required-objects'] = array(
'description' => dt('Install Solution Pack objects.'),
'options' => array(
'module' => array(
'description' => dt('The module for which to install the required objects.'),
'required' => TRUE,
),
'force' => array(
'description' => dt('Force reinstallation of the objects.'),
),
),
'aliases' => array('ispiro'),
'drupal dependencies' => array(
'islandora',
),
'examples' => array(
'drush -u 1 ispiro --module=islandora' => dt('Install missing solution pack objects for the "islandora" module.'),
'drush -u 1 ispiro --module=islandora --force' => dt('Install all solution pack objects for the "islandora" module, purging any which currently exist.'),
),
'bootstrap' => DRUSH_BOOTSTRAP_DRUPAL_LOGIN,
);
$commands['islandora-solution-pack-uninstall-required-objects'] = array(
'description' => dt('Uninstall Solution Pack objects.'),
'options' => array(
'module' => array(
'description' => dt('The module for which to uninstall the required objects.'),
'required' => TRUE,
),
'force' => array(
'description' => dt('Force uninstallation of the objects.'),
),
),
'aliases' => array('ispuro'),
'drupal dependencies' => array(
'islandora',
),
'examples' => array(
'drush -u 1 ispuro --module=islandora' => dt('Uninstall solution pack objects for the "islandora" module.'),
'drush -u 1 ispuro --module=islandora --force' => dt('Force uninstallation of all solution pack objects for the "islandora" module.'),
),
'bootstrap' => DRUSH_BOOTSTRAP_DRUPAL_LOGIN,
);
$commands['islandora-solution-pack-required-objects-status'] = array(
'description' => dt('Get Solution Pack object status.'),
'options' => array(
'module' => array(
'description' => dt('The module for which to get the status of the required objects.'),
),
),
'aliases' => array('ispros'),
'drupal dependencies' => array(
'islandora',
),
'examples' => array(
'drush -u 1 ispros' => dt('Get the status of all solution pack objects.'),
'drush -u 1 ispros --module=islandora' => dt('Get the status of solution pack objects for the "islandora" module.'),
),
'bootstrap' => DRUSH_BOOTSTRAP_DRUPAL_LOGIN,
);
$commands['islandora-solution-pack-install-content_models'] = array(
'description' => dt('Install Solution Pack content models.'),
'options' => array(
'module' => array(
'description' => dt('The module for which to install the content models.'),
'required' => TRUE,
),
),
'aliases' => array('ispicm'),
'drupal dependencies' => array(
'islandora',
),
'examples' => array(
'drush -u 1 ispicm --module=islandora' => dt('Install missing solution pack objects for the "islandora" module.'),
),
'bootstrap' => DRUSH_BOOTSTRAP_DRUPAL_LOGIN,
);
return $commands;
}
/**
* Command callback to install required objects.
*/
function drush_islandora_solution_pack_install_required_objects() {
module_load_include('inc', 'islandora', 'includes/solution_packs');
$module = drush_get_option('module');
if (module_exists($module)) {
islandora_install_solution_pack(
$module, 'install', drush_get_option('force', FALSE)
);
}
else {
drush_log(dt('"@module" is not installed/enabled?...', array(
'@module' => $module,
)));
}
}
/**
* Command callback to uninstall required objects.
*/
function drush_islandora_solution_pack_uninstall_required_objects() {
module_load_include('inc', 'islandora', 'includes/solution_packs');
$module = drush_get_option('module');
if (module_exists($module)) {
islandora_uninstall_solution_pack(
$module, drush_get_option('force', FALSE)
);
}
else {
drush_log(dt('"@module" is not installed/enabled?...', array(
'@module' => $module,
)));
}
}
/**
* Command callback for object status.
*/
function drush_islandora_solution_pack_required_objects_status() {
module_load_include('inc', 'islandora', 'includes/solution_packs');
$module = drush_get_option('module', FALSE);
$required_objects = array();
if ($module && module_exists($module)) {
$required_objects[$module] = islandora_solution_packs_get_required_objects($module);
}
elseif ($module === FALSE) {
$required_objects = islandora_solution_packs_get_required_objects();
}
else {
drush_log(dt('"@module" is not installed/enabled?...', array(
'@module' => $module,
)));
return;
}
$header = array('PID', 'Machine Status', 'Readable Status');
$widths = array(30, 20, 20);
foreach ($required_objects as $module => $info) {
$rows = array();
drush_print($info['title']);
foreach ($info['objects'] as $object) {
$status = islandora_check_object_status($object);
$rows[] = array(
$object->id,
$status['status'],
$status['status_friendly'],
);
}
drush_print_table($rows, $header, $widths);
}
}
/**
* Command callback to install required objects.
*/
function drush_islandora_solution_pack_install_content_models() {
module_load_include('inc', 'islandora', 'includes/solution_packs');
$module = drush_get_option('module');
if (module_exists($module)) {
$info = islandora_solution_packs_get_required_objects($module);
$objects_to_add = array();
foreach ($info['objects'] as $key => $candidate) {
if (in_array('fedora-system:ContentModel-3.0', $candidate->models)) {
$objects_to_add[] = $candidate;
}
}
if (count($objects_to_add) > 0) {
foreach ($objects_to_add as $object_to_add) {
$old_object = islandora_object_load($object_to_add->id);
if ($old_object) {
$deleted = islandora_delete_object($old_object);
if (!$deleted) {
drush_log(dt('@object did not delete.', array('@object' => $old_object->id), 'error'));
continue;
}
}
$new_object = islandora_add_object($object_to_add);
$verb = $deleted ? dt("Replaced") : dt("Added");
if ($new_object) {
drush_print("$verb " . $object_to_add->id . " - " . $object_to_add->label);
}
}
}
}
}

25
islandora.info

@ -1,25 +0,0 @@
name = Islandora
description = "View and manage Fedora objects"
package = Islandora
dependencies[] = image
dependencies[] = file
version = 7.x-1.3
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/islandora_web_test_case.inc
files[] = tests/authtokens.test
files[] = tests/hooks.test
files[] = tests/ingest.test
files[] = tests/hooked_access.test
files[] = tests/islandora_manage_permissions.test
files[] = tests/datastream_versions.test
files[] = tests/datastream_cache.test
files[] = tests/derivatives.test
php = 5.3

33
islandora.info.yml

@ -0,0 +1,33 @@
# This .info.yml files provides the basic information about our module to Drupal
# More: https://www.drupal.org/node/2000204
name: 'islandora'
description: "Islandora Core"
type: module
package: Islandora
core_version_requirement: ^9 || ^10
dependencies:
- context:context_ui
- ctools:ctools
- drupal:action
- drupal:basic_auth
- drupal:block
- drupal:content_translation
- drupal:link
- drupal:media
- drupal:node
- drupal:options
- drupal:path
- drupal:rest
- drupal:taxonomy
- drupal:text
- drupal:views_ui
- eva:eva
- file_replace:file_replace
- filehash:filehash
- flysystem:flysystem
- jsonld:jsonld
- jwt:jwt
- migrate_source_csv:migrate_source_csv
- prepopulate:prepopulate
- search_api:search_api
- token:token

287
islandora.install

@ -2,114 +2,227 @@
/** /**
* @file * @file
* This file contains all install related hooks. * Install/update hook implementations.
*/ */
use Drupal\Core\Extension\ExtensionNameLengthException;
use Drupal\Core\Extension\MissingDependencyException;
use Drupal\Core\Utility\UpdateException;
/** /**
* Implements hook_requirements(). * Adds common namespaces to jsonld.settings.
*/ */
function islandora_requirements($phase) { function islandora_install() {
$requirements = array(); update_jsonld_included_namespaces();
}
// Ensure translations don't break at install time.
$t = get_t();
if (!class_exists('XSLTProcessor', FALSE)) {
$requirements['islandora_xsltprocessor']['title'] = $t('Islandora XSLTProcessor Prerequisite');
$requirements['islandora_xsltprocessor']['value'] = $t('Not installed');
$link = l($t('PHP XSL extension'), 'http://us2.php.net/manual/en/book.xsl.php', array('attributes' => array('target' => '_blank')));
$requirements['islandora_xsltprocessor']['description'] = $t('The !xsllink is required. Check your installed PHP extensions and php.ini file.', array('!xsllink' => $link));
$requirements['islandora_xsltprocessor']['severity'] = REQUIREMENT_ERROR;
}
return $requirements; /**
* Delete the 'delete_media' action we used to provide, if it exists.
*
* Use the core 'media_delete_action' instead.
*/
function islandora_update_8001(&$sandbox) {
$action = \Drupal::service('entity_type.manager')->getStorage('action')->load('delete_media');
if ($action) {
$action->delete();
}
} }
/** /**
* Implements hook_install(). * Replaces 'entity_bundle' conditions with 'islandora_entity_bundle'.
* *
* @see islandora_islandora_required_objects() * This prevents plugin naming collisions between islandora and ctools.
*/ */
function islandora_install() { function islandora_update_8002(&$sandbox) {
module_load_include('inc', 'islandora', 'includes/solution_packs');
islandora_install_solution_pack('islandora'); // Find contexts that have the old 'entity_bundle' condition.
$results = \Drupal::entityQuery('context')->condition('conditions.entity_bundle.id', 'entity_bundle')->execute();
if (empty($results)) {
return;
}
// Set each context config to use 'islandora_entity_bundle' instead.
foreach ($results as $result) {
$config = \Drupal::configFactory()->getEditable("context.context.$result");
$condition = $config->get('conditions.entity_bundle');
$condition['id'] = 'islandora_entity_bundle';
$config->set('conditions.islandora_entity_bundle', $condition);
$config->clear('conditions.entity_bundle');
$config->save();
}
// Force drupal to reload the config.
\Drupal::service('plugin.manager.condition')->clearCachedDefinitions();
} }
/** /**
* Implements hook_uninstall(). * Deletes the islandora_version_count table.
* *
* @see islandora_islandora_required_objects() * We never implemented the functionality.
*/ */
function islandora_uninstall() { function islandora_update_8003(&$sandbox) {
module_load_include('inc', 'islandora', 'includes/solution_packs'); \Drupal::service('database')
islandora_install_solution_pack('islandora', 'uninstall'); ->schema()
->dropTable('islandora_version_count');
} }
/** /**
* Implements hook_schema(). * Renames migration source keys -> ids.
*/ */
function islandora_schema() { function islandora_update_8004() {
$schema['islandora_authtokens'] = array( $config_factory = \Drupal::configFactory();
'description' => 'The hub for all islandora authentication tokens', $config = $config_factory->getEditable('migrate_plus.migration.islandora__tags');
'fields' => array( if ($config) {
'id' => array( if (!$config->get('source.ids')) {
'description' => 'key', $config->set('source.ids', $config->get('source.keys'));
'type' => 'serial', $config->clear('source.keys');
'unsigned' => TRUE, $config->save(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(). * Makes migrate_tags an array.
*
* Add the required table for handling authentication tokens.
* This is the first instance that has this table.
*/ */
function islandora_update_7001(&$sandbox) { function islandora_update_8005() {
drupal_install_schema('islandora'); $config_factory = \Drupal::configFactory();
$t = get_t(); $config_factory->getEditable('migrate_plus.migration.islandora__tags')->delete();
return $t("Islandora database updates complete"); $config = $config_factory->getEditable('migrate_plus.migration.islandora_tags');
if ($config) {
if (!is_array($config->get('migration_tags'))) {
$config->set('migration_tags', [$config->get('migration_tags')]);
$config->save(TRUE);
}
if (!$config->get('source.ids')) {
$config->set('source.ids', $config->get('source.keys'));
$config->clear('source.keys');
$config->save(TRUE);
}
}
}
/**
* Adds adds previously hardcoded namespaces to configuration.
*/
function islandora_update_8006() {
update_jsonld_included_namespaces();
}
/**
* Used by install and update_8006 to add namespaces to jsonld.settings.yml.
*/
function update_jsonld_included_namespaces() {
$namespaces = [
[
'prefix' => 'ldp',
'namespace' => 'http://www.w3.org/ns/ldp#',
], [
'prefix' => 'dc11',
'namespace' => 'http://purl.org/dc/elements/1.1/',
], [
'prefix' => 'dcterms',
'namespace' => 'http://purl.org/dc/terms/',
], [
'prefix' => 'nfo',
'namespace' => 'http://www.semanticdesktop.org/ontologies/2007/03/22/nfo/v1.1/',
], [
'prefix' => 'ebucore',
'namespace' => 'http://www.ebu.ch/metadata/ontologies/ebucore/ebucore#',
], [
'prefix' => 'fedora',
'namespace' => 'http://fedora.info/definitions/v4/repository#',
], [
'prefix' => 'owl',
'namespace' => 'http://www.w3.org/2002/07/owl#',
], [
'prefix' => 'ore',
'namespace' => 'http://www.openarchives.org/ore/terms/',
], [
'prefix' => 'rdf',
'namespace' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
], [
'prefix' => 'rdau',
'namespace' => 'http://rdaregistry.info/Elements/u/',
], [
'prefix' => 'islandora',
'namespace' => 'http://islandora.ca/',
], [
'prefix' => 'pcdm',
'namespace' => 'http://pcdm.org/models#',
], [
'prefix' => 'use',
'namespace' => 'http://pcdm.org/use#',
], [
'prefix' => 'iana',
'namespace' => 'http://www.iana.org/assignments/relation/',
], [
'prefix' => 'premis',
'namespace' => 'http://www.loc.gov/premis/rdf/v1#',
], [
'prefix' => 'premis3',
'namespace' => 'http://www.loc.gov/premis/rdf/v3/',
], [
'prefix' => 'co',
'namespace' => 'http://purl.org/co/',
],
];
$config = \Drupal::configFactory()->getEditable('jsonld.settings');
if ($config && !is_array($config->get('rdf_namespaces'))) {
$config->set('rdf_namespaces', $namespaces);
$config->save(TRUE);
}
else {
\Drupal::logger('islandora')
->warning("Could not find required jsonld.settings to add default RDF namespaces.");
}
}
/**
* Ensure that ctools is enabled.
*/
function islandora_update_8007() {
$module_handler = \Drupal::moduleHandler();
if ($module_handler->moduleExists('ctools')) {
return t('The "@module_name" module is already enabled, no action necessary.', [
'@module_name' => 'ctools',
]);
}
/** @var \Drupal\Core\Extension\ModuleInstallerInterface $installer */
$installer = \Drupal::service('module_installer');
try {
if ($installer->install(['ctools'], TRUE)) {
return t('The "@module_name" module was enabled successfully.', [
'@module_name' => 'ctools',
]);
}
}
catch (ExtensionNameLengthException | MissingDependencyException $e) {
throw new UpdateException('Failed; ensure that the ctools module is available in the Drupal installation.', 0, $e);
}
catch (\Exception $e) {
throw new UpdateException('Failed; encountered an exception while trying to enable ctools.', 0, $e);
}
// Theoretically impossible to hit, as ModuleInstaller::install() only returns
// TRUE (or throws/propagates an exception), but... probably a good idea to
// have the here, just in case?
throw new UpdateException('Failed; hit the end of the update hook implementation, which is not expected.');
}
/**
* Set config to no redirect after media save.
*/
function islandora_update_8008() {
$config = \Drupal::configFactory()->getEditable('islandora.settings');
if ($config) {
$config->set('redirect_after_media_save', FALSE);
$config->save(TRUE);
return t('A new configuration option, "Redirect after media save" is now available.
It has been turned off to preserve existing behaviour. To enable this setting visit
Configuration > Islandora > Core Settings.');
}
} }

5
islandora.libraries.yml

@ -0,0 +1,5 @@
islandora:
version: VERSION
css:
theme:
css/islandora.css: {}

29
islandora.links.action.yml

@ -0,0 +1,29 @@
islandora.upload_media:
route_name: islandora.upload_media
title: Batch Upload Media
appears_on:
- view.media_of.page_1
islandora.add_media_to_node:
route_name: islandora.add_media_to_node_page
title: Add Media
appears_on:
- view.media_of.page_1
islandora.upload_children:
route_name: islandora.upload_children
title: Batch Upload Children
appears_on:
- view.manage_members.page_1
islandora.add_member_to_node:
route_name: islandora.add_member_to_node_page
title: Add Child
appears_on:
- view.manage_members.page_1
islandora.reorder_children:
route_name: view.reorder_children.page_1
title: Reorder Children
appears_on:
- view.manage_members.page_1

20
islandora.links.menu.yml

@ -0,0 +1,20 @@
# Menu list of Islandora configuration forms
system.admin_config_islandora:
title: Islandora
parent: system.admin_config
route_name: system.admin_config_islandora
weight: 100
# Core Islandora configuration form
system.islandora_settings:
title: 'Core Settings'
parent: system.admin_config_islandora
route_name: system.islandora_settings
description: 'Confgure core Islandora settings'
# RDF property mappings
system.islandora_rdf_mappings:
title: 'Field and term RDF mappings'
parent: system.admin_reports
description: 'List of configured Drupal field to RDF property mappings and taxonomy term linked data URIs.'
route_name: system.islandora_rdf_mappings

2253
islandora.module

File diff suppressed because it is too large Load Diff

12
islandora.permissions.yml

@ -0,0 +1,12 @@
view checksums:
title: 'View Checksums'
description: 'Allows access to viewing file checksums'
manage members:
title: 'Manage Members'
description: 'Allows access to managing members for content'
manage media:
title: 'Manage Media'
description: 'Allows access to managing media for content'

16
islandora.post_update.php

@ -0,0 +1,16 @@
<?php
/**
* @file
* Post updates.
*/
/**
* Set default value for delete_media_and_files field in settings.
*/
function islandora_post_update_delete_media_and_files() {
$config_factory = \Drupal::configFactory();
$config = $config_factory->getEditable('islandora.settings');
$config->set('delete_media_and_files', TRUE);
$config->save(TRUE);
}

111
islandora.routing.yml

@ -0,0 +1,111 @@
# Menu list of Islandora configuration forms
system.admin_config_islandora:
path: '/admin/config/islandora'
defaults:
_controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
_title: 'Islandora'
requirements:
_permission: 'access administration pages'
# Core Islandora configuration form
system.islandora_settings:
path: '/admin/config/islandora/core'
defaults:
_form: '\Drupal\islandora\Form\IslandoraSettingsForm'
_title: 'Islandora Settings'
requirements:
_permission: 'administer site configuration'
# RDF properties report
system.islandora_rdf_mappings:
path: '/admin/reports/islandora/rdf_mappings'
defaults:
_controller: '\Drupal\islandora\Controller\RdfMappingsReportController::main'
_title: 'Field and term RDF mappings'
requirements:
_permission: 'administer site configuration'
islandora.add_member_to_node_page:
path: '/node/{node}/members/add'
defaults:
_controller: '\Drupal\islandora\Controller\ManageMembersController::addToNodePage'
_title_callback: '\Drupal\islandora\Controller\ManageMembersController::addTitle'
entity_type_id: node
options:
_admin_route: 'true'
requirements:
_entity_create_any_access: 'node'
islandora.upload_children:
path: '/node/{node}/members/upload/{step}'
defaults:
_wizard: '\Drupal\islandora\Form\AddChildrenWizard\ChildForm'
_title: 'Upload Children'
step: 'type_selection'
options:
_admin_route: 'TRUE'
requirements:
_custom_access: '\Drupal\islandora\Form\AddChildrenWizard\Access::childAccess'
islandora.add_media_to_node_page:
path: '/node/{node}/media/add'
defaults:
_controller: '\Drupal\islandora\Controller\ManageMediaController::addToNodePage'
_title_callback: '\Drupal\islandora\Controller\ManageMediaController::addTitle'
entity_type_id: media
options:
_admin_route: 'true'
requirements:
_entity_create_any_access: 'media'
islandora.upload_media:
path: '/node/{node}/media/upload/{step}'
defaults:
_wizard: '\Drupal\islandora\Form\AddChildrenWizard\MediaForm'
_title: 'Add media'
step: 'type_selection'
options:
_admin_route: 'TRUE'
requirements:
_custom_access: '\Drupal\islandora\Form\AddChildrenWizard\Access::mediaAccess'
islandora.media_source_update:
path: '/media/{media}/source'
defaults:
_controller: '\Drupal\islandora\Controller\MediaSourceController::put'
methods: [PUT]
requirements:
_permission: 'update media'
options:
_auth: ['basic_auth', 'cookie', 'jwt_auth']
islandora.media_source_put_to_node:
path: '/node/{node}/media/{media_type}/{taxonomy_term}'
defaults:
_controller: '\Drupal\islandora\Controller\MediaSourceController::putToNode'
methods: [PUT]
requirements:
_custom_access: '\Drupal\islandora\Controller\MediaSourceController::putToNodeAccess'
options:
_auth: ['basic_auth', 'cookie', 'jwt_auth']
islandora.attach_file_to_media:
path: '/media/add_derivative/{media}/{destination_field}'
defaults:
_controller: '\Drupal\islandora\Controller\MediaSourceController::attachToMedia'
methods: [GET, PUT]
requirements:
_custom_access: '\Drupal\islandora\Controller\MediaSourceController::attachToMediaAccess'
options:
_auth: ['basic_auth', 'cookie', 'jwt_auth']
no_cache: 'TRUE'
parameters:
media:
type: entity:media
islandora.confirm_delete_media_and_file:
path: '/media/delete_with_files'
defaults:
_form: 'Drupal\islandora\Form\ConfirmDeleteMediaAndFile'
requirements:
_permission: 'administer media+delete any media'

118
islandora.rules.inc

@ -1,118 +0,0 @@
<?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 AbstractObject 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 AbstractObject 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 AbstractObject 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);
}

80
islandora.services.yml

@ -0,0 +1,80 @@
# Islandora Services
# islandora.services.yml:
services:
islandora.eventgenerator:
class: Drupal\islandora\EventGenerator\EventGenerator
arguments: ['@islandora.utils', '@islandora.media_source_service']
islandora.stomp:
class: Stomp\StatefulStomp
factory: ['Drupal\islandora\StompFactory', create]
arguments: ['@config.factory']
islandora.jwt-subscriber:
class: Drupal\islandora\EventSubscriber\JwtEventSubscriber
factory: ['Drupal\islandora\EventSubscriber\JwtEventSubscriber', create]
arguments: ['@entity_type.manager', '@current_user']
tags:
- { name: event_subscriber }
islandora.media_link_header_subscriber:
class: Drupal\islandora\EventSubscriber\MediaLinkHeaderSubscriber
arguments: ['@entity_type.manager', '@entity_field.manager', '@access_manager', '@current_user', '@current_route_match', '@request_stack', '@islandora.utils']
tags:
- { name: event_subscriber }
islandora.node_link_header_subscriber:
class: Drupal\islandora\EventSubscriber\NodeLinkHeaderSubscriber
arguments: ['@entity_type.manager', '@entity_field.manager', '@access_manager', '@current_user', '@current_route_match', '@request_stack', '@islandora.utils']
tags:
- { name: event_subscriber }
islandora.admin_view_route_subscriber:
class: Drupal\islandora\EventSubscriber\AdminViewsRouteSubscriber
tags:
- { name: event_subscriber }
logger.channel.islandora:
parent: logger.channel_base
arguments: ['islandora']
logger.channel.fedora_flysystem:
parent: logger.channel_base
arguments: ['fedora_flysystem']
islandora.media_route_context_provider:
class: Drupal\islandora\ContextProvider\MediaRouteContextProvider
arguments: ['@current_route_match']
tags:
- { name: 'context_provider' }
islandora.file_route_context_provider:
class: Drupal\islandora\ContextProvider\FileRouteContextProvider
arguments: ['@current_route_match']
tags:
- { name: 'context_provider' }
islandora.taxonomy_term_route_context_provider:
class: Drupal\islandora\ContextProvider\TermRouteContextProvider
arguments: ['@current_route_match']
tags:
- { name: 'context_provider' }
islandora.media_source_service:
class: Drupal\islandora\MediaSource\MediaSourceService
arguments: ['@entity_type.manager', '@current_user', '@language_manager', '@file_system', '@islandora.utils']
islandora.utils:
class: Drupal\islandora\IslandoraUtils
arguments: ['@entity_type.manager', '@entity_field.manager', '@context.manager', '@flysystem_factory', '@language_manager']
islandora.entity_mapper:
class: Islandora\EntityMapper\EntityMapper
islandora.stomp.auth_header_listener:
class: Drupal\islandora\EventSubscriber\StompHeaderEventSubscriber
arguments: ['@jwt.authentication.jwt']
tags:
- { name: event_subscriber }
islandora.upload_children.batch_processor:
class: Drupal\islandora\Form\AddChildrenWizard\ChildBatchProcessor
arguments:
- '@entity_type.manager'
- '@database'
- '@current_user'
- '@messenger'
- '@date.formatter'
islandora.upload_media.batch_processor:
class: Drupal\islandora\Form\AddChildrenWizard\MediaBatchProcessor
arguments:
- '@entity_type.manager'
- '@database'
- '@current_user'
- '@messenger'
- '@date.formatter'

192
islandora.tokens.inc

@ -0,0 +1,192 @@
<?php
/**
* @file
* Contains islandora.tokens.inc.
*
* This file provides islandora tokens.
*/
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\media\Entity\Media;
use Drupal\file\Entity\File;
/**
* Implements hook_token_info().
*/
function islandora_token_info() {
$type = [
'name' => t('Islandora Tokens'),
'description' => t('Tokens for Islandora objects.'),
];
$node['media-original-file:filename'] = [
'name' => t('Media: Original File filename without extension.'),
'description' => t('File name without extension of original uploaded file associated with Islandora Object via Media.'),
];
$node['media-original-file:basename'] = [
'name' => t('Media: Original File filename with extension.'),
'description' => t('File name with extension of original uploaded file associated with Islandora Object via Media.'),
];
$node['media-original-file:extension'] = [
'name' => t('Media: Original File extension.'),
'description' => t('File extension of original uploaded file associated with Islandora Object via Media.'),
];
$node['media-thumbnail-image:url'] = [
'name' => t('Media: Thumbnail Image URL.'),
'description' => t('URL of Thumbnail Image associated with Islandora Object via Media.'),
];
$node['media-thumbnail-image:alt'] = [
'name' => t('Alternative text for Media: Thumbnail Image.'),
'description' => t('Alternative text for Thumbnail Image associated with Islandora Object via Media.'),
];
// Deprecated in favour if hyphenated version.
$node['media_thumbnail_image:url'] = [
'name' => t('Media: Thumbnail Image URL.'),
'description' => t('Deprecated: URL of Thumbnail Image associated with Islandora Object via Media.'),
];
// Deprecated in favour if hyphenated version.
$node['media_thumbnail_image:alt'] = [
'name' => t('Alternative text for Media: Thumbnail Image.'),
'description' => t('Deprecated: Alternative text for Thumbnail Image associated with Islandora Object via Media.'),
];
$node['pdf_url'] = [
'name' => t("PDF Url"),
'description' => t('URL to related media file if "Original file" is a PDF file'),
];
return [
'types' => ['islandoratokens' => $type],
'tokens' => ['islandoratokens' => $node],
];
}
/**
* Implements hook_tokens().
*/
function islandora_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
$replacements = [];
if ($type == 'islandoratokens' && !empty($data['node'])) {
if (!is_array($tokens) || empty($tokens)) {
\Drupal::logger('islandora')
->alert(
'Tokens not correct format: @tokens', [
'@tokens' => print_r($tokens, 1),
]
);
return;
}
$islandoraUtils = \Drupal::service('islandora.utils');
foreach ($tokens as $name => $original) {
switch ($name) {
case 'media-original-file:basename':
case 'media-original-file:filename':
case 'media-original-file:extension':
$term = $islandoraUtils->getTermForUri('http://pcdm.org/use#OriginalFile');
$media = $islandoraUtils->getMediaWithTerm($data['node'], $term);
// Is there media?
if ($media) {
$file = \Drupal::service('islandora.media_source_service')->getSourceFile($media);
if (!empty($file)) {
$path_info = pathinfo($file->createFileUrl());
$key = explode(':', $name)[1];
if (array_key_exists($key, $path_info)) {
$replacements[$original] = $path_info[$key];
}
}
}
break;
case 'media-thumbnail-image:url':
case 'media_thumbnail_image:url':
$term = $islandoraUtils->getTermForUri('http://pcdm.org/use#ThumbnailImage');
$media = $islandoraUtils->getMediaWithTerm($data['node'], $term);
// Is there media?
// @todo is this single or multiple?
if ($media) {
$file = \Drupal::service('islandora.media_source_service')->getSourceFile($media);
if (!empty($file)) {
$url = $file->createFileUrl();
$replacements[$original] = $url;
}
}
break;
case 'media-thumbnail-image:alt':
case 'media_thumbnail_image:alt':
$alt = '';
$term = $islandoraUtils->getTermForUri('http://pcdm.org/use#ThumbnailImage');
$media = $islandoraUtils->getMediaWithTerm($data['node'], $term);
// Is there media?
// @todo is this single or multiple?
if ($media) {
// Is the media an image?
if (isset($media->field_media_image)) {
$alt = $media->field_media_image[0]->alt;
}
}
// @todo get alt from original or service file, if thumbnail
// alt is empty.
$replacements[$original] = $alt;
break;
case 'pdf_url':
$replacements[$original] = islandora_url_to_service_file_media_by_mimetype($data['node'], 'application/pdf');
break;
}
}
}
return $replacements;
}
/**
* Gets Original File PDF file URL.
*
* @param object $node
* A core drupal node object.
* @param string $mime_type
* The name of the node's field to check for the specific relationship.
*
* @return string
* The tokenized value for the given data.
*/
function islandora_url_to_service_file_media_by_mimetype($node, $mime_type) {
$islandora_utils = \Drupal::service('islandora.utils');
$origfile_term = $islandora_utils->getTermForUri('http://pcdm.org/use#OriginalFile');
$origfile_media = $islandora_utils->getMediaWithTerm($node, $origfile_term);
// Get the media file's mime_type value.
if (is_object($origfile_media)) {
$origfile_mime_type = ($origfile_media->hasField('field_mime_type')) ?
$origfile_media->get('field_mime_type')->getValue() : NULL;
$origfile_mime_type = (is_array($origfile_mime_type) &&
array_key_exists(0, $origfile_mime_type) &&
is_array($origfile_mime_type[0]) &&
array_key_exists('value', $origfile_mime_type[0])) ?
$origfile_mime_type[0]['value'] : '';
// Compare the media file's mime_type to the given value.
if ($origfile_mime_type == $mime_type) {
$vid = $origfile_media->id();
if (!is_null($vid)) {
$media = Media::load($vid);
$bundle = $media->bundle();
// Since this is Islandora and we assume the Original File is a
// Document type... but doing it dynamically.
$fid = $media->get('field_media_' . $bundle)->getValue();
$fid_value = (is_array($fid) && array_key_exists(0, $fid) &&
array_key_exists('target_id', $fid[0])) ?
$fid[0]['target_id'] : NULL;
if (!is_null($fid_value)) {
$file = File::load($fid_value);
if ($file) {
$url = $islandora_utils->getDownloadUrl($file);
return $url;
}
}
}
}
}
return '';
}

54
islandora.views.inc

@ -0,0 +1,54 @@
<?php
/**
* @file
* Provide Views data for integer-weight fields.
*/
/**
* Implements hook_views_data_alter().
*/
function islandora_views_data_alter(&$data) {
// For now only support Nodes and Media.
foreach (['node', 'media'] as $entity_type) {
$fields = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions($entity_type);
foreach ($fields as $field => $field_storage_definition) {
if ($field_storage_definition->getType() == 'integer' && strpos($field, "field_") === 0) {
$prefixed_field = $entity_type . '__' . $field;
if (isset($data[$prefixed_field])) {
$data[$prefixed_field][$field . '_value']['field'] = $data[$prefixed_field][$field]['field'];
$data[$prefixed_field][$field]['title'] = t('Integer Weight Selector (@field)', [
'@field' => $field,
]);
$data[$prefixed_field][$field]['help'] = t('Provides a drag-n-drop reordering of integer-based weight fields.');
$data[$prefixed_field][$field]['title short'] = t('Integer weight selector');
$data[$prefixed_field][$field]['field']['id'] = 'integer_weight_selector';
}
}
}
}
// Add Has Media filter.
$data['node_field_data']['islandora_has_media'] = [
'title' => t('Node has Media Use'),
'group' => t('Content'),
'filter' => [
'title' => t('Node has media use filter'),
'help' => t('Provides a custom filter for nodes that do or do not have media with a given use.'),
'field' => 'nid',
'id' => 'islandora_node_has_media_use',
],
];
// Add Is Islandora filter.
$data['node_field_data']['islandora_node_is_islandora'] = [
'title' => t('Node is Islandora'),
'group' => t('Content'),
'filter' => [
'title' => t('Node is Islandora'),
'help' => t('Node has a content type that possesses the mandatory Islandora fields.'),
'field' => 'nid',
'id' => 'islandora_node_is_islandora',
],
];
}

18
js/add_print.js

@ -1,18 +0,0 @@
/**
* @file
* JavaScript file responsable for the print button behaviour.
*
* The print button is added automatically to every view, as metadata
* can be printed from every object.
*
*/
(function ($) {
$(document).ready(function() {
$('.tabs .primary').append('<img id="print_btn" title="Print" src="' + Drupal.settings.basePath + Drupal.settings.islandora.print_img + '"></img>');
$('#print_btn').css("cursor","pointer");
$('#print_btn').click(function() {
window.location=Drupal.settings.basePath + Drupal.settings.islandora.print_link;
});
});
})(jQuery);

21
js/spin/LICENSE.txt

@ -1,21 +0,0 @@
The MIT License
Copyright (c) 2011 Felix Gnass [fgnass at neteye dot de]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

11
js/spin/README.md

@ -1,11 +0,0 @@
CONTENTS OF THIS FILE
---------------------
* summary
SUMMARY
-------
This directory contains the spin.js library: http://fgnass.github.io/spin.js/
downloaded from http://fgnass.github.io/spin.js/dist/spin.min.js on Sept 27th
2013. This project is under version control: https://github.com/fgnass/spin.js.

1
js/spin/spin.min.js vendored

@ -1 +0,0 @@
(function(t,e){if(typeof exports=="object")module.exports=e();else if(typeof define=="function"&&define.amd)define(e);else t.Spinner=e()})(this,function(){"use strict";var t=["webkit","Moz","ms","O"],e={},i;function o(t,e){var i=document.createElement(t||"div"),o;for(o in e)i[o]=e[o];return i}function n(t){for(var e=1,i=arguments.length;e<i;e++)t.appendChild(arguments[e]);return t}var r=function(){var t=o("style",{type:"text/css"});n(document.getElementsByTagName("head")[0],t);return t.sheet||t.styleSheet}();function s(t,o,n,s){var a=["opacity",o,~~(t*100),n,s].join("-"),f=.01+n/s*100,l=Math.max(1-(1-t)/o*(100-f),t),u=i.substring(0,i.indexOf("Animation")).toLowerCase(),d=u&&"-"+u+"-"||"";if(!e[a]){r.insertRule("@"+d+"keyframes "+a+"{"+"0%{opacity:"+l+"}"+f+"%{opacity:"+t+"}"+(f+.01)+"%{opacity:1}"+(f+o)%100+"%{opacity:"+t+"}"+"100%{opacity:"+l+"}"+"}",r.cssRules.length);e[a]=1}return a}function a(e,i){var o=e.style,n,r;i=i.charAt(0).toUpperCase()+i.slice(1);for(r=0;r<t.length;r++){n=t[r]+i;if(o[n]!==undefined)return n}if(o[i]!==undefined)return i}function f(t,e){for(var i in e)t.style[a(t,i)||i]=e[i];return t}function l(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var o in i)if(t[o]===undefined)t[o]=i[o]}return t}function u(t){var e={x:t.offsetLeft,y:t.offsetTop};while(t=t.offsetParent)e.x+=t.offsetLeft,e.y+=t.offsetTop;return e}function d(t,e){return typeof t=="string"?t:t[e%t.length]}var p={lines:12,length:7,width:5,radius:10,rotate:0,corners:1,color:"#000",direction:1,speed:1,trail:100,opacity:1/4,fps:20,zIndex:2e9,className:"spinner",top:"auto",left:"auto",position:"relative"};function c(t){if(typeof this=="undefined")return new c(t);this.opts=l(t||{},c.defaults,p)}c.defaults={};l(c.prototype,{spin:function(t){this.stop();var e=this,n=e.opts,r=e.el=f(o(0,{className:n.className}),{position:n.position,width:0,zIndex:n.zIndex}),s=n.radius+n.length+n.width,a,l;if(t){t.insertBefore(r,t.firstChild||null);l=u(t);a=u(r);f(r,{left:(n.left=="auto"?l.x-a.x+(t.offsetWidth>>1):parseInt(n.left,10)+s)+"px",top:(n.top=="auto"?l.y-a.y+(t.offsetHeight>>1):parseInt(n.top,10)+s)+"px"})}r.setAttribute("role","progressbar");e.lines(r,e.opts);if(!i){var d=0,p=(n.lines-1)*(1-n.direction)/2,c,h=n.fps,m=h/n.speed,y=(1-n.opacity)/(m*n.trail/100),g=m/n.lines;(function v(){d++;for(var t=0;t<n.lines;t++){c=Math.max(1-(d+(n.lines-t)*g)%m*y,n.opacity);e.opacity(r,t*n.direction+p,c,n)}e.timeout=e.el&&setTimeout(v,~~(1e3/h))})()}return e},stop:function(){var t=this.el;if(t){clearTimeout(this.timeout);if(t.parentNode)t.parentNode.removeChild(t);this.el=undefined}return this},lines:function(t,e){var r=0,a=(e.lines-1)*(1-e.direction)/2,l;function u(t,i){return f(o(),{position:"absolute",width:e.length+e.width+"px",height:e.width+"px",background:t,boxShadow:i,transformOrigin:"left",transform:"rotate("+~~(360/e.lines*r+e.rotate)+"deg) translate("+e.radius+"px"+",0)",borderRadius:(e.corners*e.width>>1)+"px"})}for(;r<e.lines;r++){l=f(o(),{position:"absolute",top:1+~(e.width/2)+"px",transform:e.hwaccel?"translate3d(0,0,0)":"",opacity:e.opacity,animation:i&&s(e.opacity,e.trail,a+r*e.direction,e.lines)+" "+1/e.speed+"s linear infinite"});if(e.shadow)n(l,f(u("#000","0 0 4px "+"#000"),{top:2+"px"}));n(t,n(l,u(d(e.color,r),"0 0 1px rgba(0,0,0,.1)")))}return t},opacity:function(t,e,i){if(e<t.childNodes.length)t.childNodes[e].style.opacity=i}});function h(){function t(t,e){return o("<"+t+' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">',e)}r.addRule(".spin-vml","behavior:url(#default#VML)");c.prototype.lines=function(e,i){var o=i.length+i.width,r=2*o;function s(){return f(t("group",{coordsize:r+" "+r,coordorigin:-o+" "+-o}),{width:r,height:r})}var a=-(i.width+i.length)*2+"px",l=f(s(),{position:"absolute",top:a,left:a}),u;function p(e,r,a){n(l,n(f(s(),{rotation:360/i.lines*e+"deg",left:~~r}),n(f(t("roundrect",{arcsize:i.corners}),{width:o,height:i.width,left:i.radius,top:-i.width>>1,filter:a}),t("fill",{color:d(i.color,e),opacity:i.opacity}),t("stroke",{opacity:0}))))}if(i.shadow)for(u=1;u<=i.lines;u++)p(u,-2,"progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)");for(u=1;u<=i.lines;u++)p(u);return n(e,l)};c.prototype.opacity=function(t,e,i,o){var n=t.firstChild;o=o.shadow&&o.lines||0;if(n&&e+o<n.childNodes.length){n=n.childNodes[e+o];n=n&&n.firstChild;n=n&&n.firstChild;if(n)n.opacity=i}}}var m=f(o("group"),{behavior:"url(#default#VML)"});if(!a(m,"transform")&&m.adj)h();else i=a(m,"animation");return c});

58
js/spinner.js

@ -1,58 +0,0 @@
/**
* @file
* Triggers the display of a spinning icon when the form is submitted.
*/
(function ($) {
Drupal.behaviors.spinner = {
attach: function(context, settings) {
// Store what triggered the submit.
$('form').once('submit-resolver', function() {
$(this).click(function(event) {
$(this).data('clicked', $(event.target));
});
$(this).keypress(function(event) {
// On enter the first submit button is assumed as is most often the
// case and this is part of the HTML 5 specification, although some
// Browsers may choose the button with the lowest tab-index.
if (event.which == 13) {
$(this).data('clicked', $(':submit', this).first());
}
});
});
for (var base in settings.spinner) {
var id = '#' + base;
$(id, context).once('spinner', function () {
var spinner = new Spinner(settings.spinner[base].opts);
$(id).parents('form').one('submit', function(event) {
if ($(this).data('clicked').is(id)) {
event.preventDefault();
// Add Message.
var message = $('<div/>').text(settings.spinner[base].message);
$(id).after(message);
// Make UI changes.
spinner.spin(this);
$('#edit-next').hide();
$('#edit-prev').hide();
// Submit the form after a set timeout, this handles problems with
// safari, in that safari submit's immediately..
if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {
$(':submit').attr('disabled', 'disabled');
}
setTimeout(function() {
// Allow for the button to be clicked, then click it then
// prevent the default behavoir.
$(id).removeAttr('disabled')
.click()
.click(function(event) {
event.preventDefault();
});
}, 500);
}
return true;
});
});
}
}
};
})(jQuery);

19
migrate/tags.csv

@ -0,0 +1,19 @@
vid,name,description,external_uri
islandora_media_use,"Extracted Text","A textual representation of the Object appropriate for fulltext indexing, such as a plaintext version of a document, or OCR text",http://pcdm.org/use#ExtractedText
islandora_media_use,"Intermediate File","High quality representation of the Object, appropriate for generating derivatives or other additional processing",http://pcdm.org/use#IntermediateFile
islandora_media_use,"Original File","The original creation format of a file",http://pcdm.org/use#OriginalFile
islandora_media_use,"Preservation Master File","Best quality representation of the Object appropriate for long-term preservation",http://pcdm.org/use#PreservationMasterFile
islandora_media_use,"Service File","A medium quality representation of the Object appropriate for serving to users",http://pcdm.org/use#ServiceFile
islandora_media_use,"Thumbnail Image","A low resolution image representation of the Object appropriate for using as an icon",http://pcdm.org/use#ThumbnailImage
islandora_media_use,"Transcript","A textual representation of the Object appropriate for presenting to users, such as subtitles or transcript of a video. Can be used as a substitute or complement to other files for accessibility purposes",http://pcdm.org/use#Transcript
islandora_models,"Audio","A resource primarily intended to be heard. Examples include a music playback file format, an audio compact disc, and recorded speech or sounds",http://purl.org/coar/resource_type/c_18cc
islandora_models,"Binary","A generic binary file for repository items that don't fall into any other category or cannot be shown in a browser",http://purl.org/coar/resource_type/c_1843
islandora_models,"Collection","A collection is an aggregation of items",http://purl.org/dc/dcmitype/Collection
islandora_models,"Image","A visual representation other than text, including all types of moving image and still image",http://purl.org/coar/resource_type/c_c513
islandora_models,"Video","A recording of visual images, usually in motion and with sound accompaniment",http://purl.org/coar/resource_type/c_12ce
islandora_models,"Digital Document","An electronic file or document.",https://schema.org/DigitalDocument
islandora_models,"Paged Content","An Electronic Book, object with pages",https://schema.org/Book
islandora_models,"Page","A page in an Electronic Paged Content Object",http://id.loc.gov/ontologies/bibframe/part
islandora_models,"Publication Issue","A part of a successively published publication such as a periodical or publication volume, often numbered, usually containing a grouping of works such as articles.",https://schema.org/PublicationIssue
islandora_models,"Compound Object","A special type of collection where the parent item may also have complex metadata",http://vocab.getty.edu/aat/300242735
islandora_models,"Newspaper","A special type of collection which only has Newspaper Issues for children.",https://schema.org/Newspaper
1 vid name description external_uri
2 islandora_media_use Extracted Text A textual representation of the Object appropriate for fulltext indexing, such as a plaintext version of a document, or OCR text http://pcdm.org/use#ExtractedText
3 islandora_media_use Intermediate File High quality representation of the Object, appropriate for generating derivatives or other additional processing http://pcdm.org/use#IntermediateFile
4 islandora_media_use Original File The original creation format of a file http://pcdm.org/use#OriginalFile
5 islandora_media_use Preservation Master File Best quality representation of the Object appropriate for long-term preservation http://pcdm.org/use#PreservationMasterFile
6 islandora_media_use Service File A medium quality representation of the Object appropriate for serving to users http://pcdm.org/use#ServiceFile
7 islandora_media_use Thumbnail Image A low resolution image representation of the Object appropriate for using as an icon http://pcdm.org/use#ThumbnailImage
8 islandora_media_use Transcript A textual representation of the Object appropriate for presenting to users, such as subtitles or transcript of a video. Can be used as a substitute or complement to other files for accessibility purposes http://pcdm.org/use#Transcript
9 islandora_models Audio A resource primarily intended to be heard. Examples include a music playback file format, an audio compact disc, and recorded speech or sounds http://purl.org/coar/resource_type/c_18cc
10 islandora_models Binary A generic binary file for repository items that don't fall into any other category or cannot be shown in a browser http://purl.org/coar/resource_type/c_1843
11 islandora_models Collection A collection is an aggregation of items http://purl.org/dc/dcmitype/Collection
12 islandora_models Image A visual representation other than text, including all types of moving image and still image http://purl.org/coar/resource_type/c_c513
13 islandora_models Video A recording of visual images, usually in motion and with sound accompaniment http://purl.org/coar/resource_type/c_12ce
14 islandora_models Digital Document An electronic file or document. https://schema.org/DigitalDocument
15 islandora_models Paged Content An Electronic Book, object with pages https://schema.org/Book
16 islandora_models Page A page in an Electronic Paged Content Object http://id.loc.gov/ontologies/bibframe/part
17 islandora_models Publication Issue A part of a successively published publication such as a periodical or publication volume, often numbered, usually containing a grouping of works such as articles. https://schema.org/PublicationIssue
18 islandora_models Compound Object A special type of collection where the parent item may also have complex metadata http://vocab.getty.edu/aat/300242735
19 islandora_models Newspaper A special type of collection which only has Newspaper Issues for children. https://schema.org/Newspaper

73
modules/islandora_advanced_search/CONTRIBUTING.md

@ -0,0 +1,73 @@
# Welcome!
If you are reading this document then you are interested in contributing to Islandora 8. All contributions are welcome: use-cases, documentation, code, patches, bug reports, feature requests, etc. You do not need to be a programmer to speak up!
We also have an IRC channel -- #islandora -- on freenode.net. Feel free to hang out there, ask questions, and help others out if you can.
Please note that this project operates under the [Islandora Community Code of Conduct](http://islandora.ca/codeofconduct). By participating in this project you agree to abide by its terms.
## Workflows
The group meets each Wednesday at 1:00 PM Eastern. Meeting notes and announcements are posted to the [Islandora community list](https://groups.google.com/forum/#!forum/islandora) and the [Islandora developers list](https://groups.google.com/forum/#!forum/islandora-dev). You can view meeting agendas, notes, and call-in information [here](https://github.com/Islandora/documentation/wiki#islandora-8-tech-calls). Anybody is welcome to join the calls, and add items to the agenda.
### Use cases
If you would like to submit a use case to the Islandora 8 project, please submit an issue [here](https://github.com/Islandora/documentation/issues/new) using the [Use Case template](https://github.com/Islandora/documentation/wiki/Use-Case-template), prepending "Use Case:" to the title of the issue.
### Documentation
You can contribute documentation in two different ways. One way is to create an issue [here](https://github.com/Islandora/documentation/issues/new), prepending "Documentation:" to the title of the issue. Another way is by pull request, which is the same process as [Contribute Code](https://github.com/Islandora/documentation/blob/main/CONTRIBUTING.md#contribute-code). All documentation resides in [`docs`](https://github.com/Islandora/documentation/tree/main/docs).
### Request a new feature
To request a new feature you should [open an issue in the Islandora 8 repository](https://github.com/Islandora/documentation/issues/new) or create a use case (see the _Use cases_ section above), and summarize the desired functionality. Prepend "Enhancement:" if creating an issue on the project repo, and "Use Case:" if creating a use case.
### Report a bug
To report a bug you should [open an issue in the Islandora 8 repository](https://github.com/Islandora/documentation/issues/new) that summarizes the bug. Prepend the label "Bug:" to the title of the issue.
In order to help us understand and fix the bug it would be great if you could provide us with:
1. The steps to reproduce the bug. This includes information about e.g. the Islandora version you were using along with the versions of stack components.
2. The expected behavior.
3. The actual, incorrect behavior.
Feel free to search the issue queue for existing issues (aka tickets) that already describe the problem; if there is such a ticket please add your information as a comment.
**If you want to provide a pull along with your bug report:**
That is great! In this case please send us a pull request as described in the section _Create a pull request_ below.
### Contribute code
Before you set out to contribute code you will need to have completed a [Contributor License Agreement](http://islandora.ca/sites/default/files/islandora_cla.pdf) or be covered by a [Corporate Contributor License Agreement](http://islandora.ca/sites/default/files/islandora_ccla.pdf). The signed copy of the license agreement should be sent to <mailto:community@islandora.ca>
_If you are interested in contributing code to Islandora but do not know where to begin:_
In this case you should [browse open issues](https://github.com/Islandora/documentation/issues) and check out [use cases](https://github.com/Islandora/documentation/labels/use%20case).
If you are contributing Drupal code, it must adhere to [Drupal Coding Standards](https://www.drupal.org/coding-standards); Travis CI will check for this on pull requests.
Contributions to the Islandora codebase should be sent as GitHub pull requests. See section _Create a pull request_ below for details. If there is any problem with the pull request we can work through it using the commenting features of GitHub.
* For _small patches_, feel free to submit pull requests directly for those patches.
* For _larger code contributions_, please use the following process. The idea behind this process is to prevent any wasted work and catch design issues early on.
1. [Open an issue](https://github.com/Islandora/documentation/issues), prepending "Enhancement:" in the title if a similar issue does not exist already. If a similar issue does exist, then you may consider participating in the work on the existing issue.
2. Comment on the issue with your plan for implementing the issue. Explain what pieces of the codebase you are going to touch and how everything is going to fit together.
3. Islandora committers will work with you on the design to make sure you are on the right track.
4. Implement your issue, create a pull request (see below), and iterate from there.
### Create a pull request
Take a look at [Creating a pull request](https://help.github.com/articles/creating-a-pull-request). In a nutshell you need to:
1. [Fork](https://help.github.com/articles/fork-a-repo) this repository to your personal or institutional GitHub account (depending on the CLA you are working under). Be cautious of which branches you work from though (you'll want to base your work off the default branch). See [Fork a repo](https://help.github.com/articles/fork-a-repo) for detailed instructions.
2. Commit any changes to your fork.
3. Send a [pull request](https://help.github.com/articles/creating-a-pull-request) using the [pull request template](https://github.com/Islandora/documentation/blob/main/.github/PULL_REQUEST_TEMPLATE.md) to the Islandora GitHub repository that you forked in step 1. If your pull request is related to an existing issue -- for instance, because you reported a [bug/issue](https://github.com/Islandora/documentation/issues) earlier -- prefix the title of your pull request with the corresponding issue number (e.g. `issue-123: ...`). Please also include a reference to the issue in the description of the pull. This can be done by using '#' plus the issue number like so '#123', also try to pick an appropriate name for the branch in which you're issuing the pull request from.
You may want to read [Syncing a fork](https://help.github.com/articles/syncing-a-fork) for instructions on how to keep your fork up to date with the latest changes of the upstream (official) repository.
## License Agreements
The Islandora Foundation requires that contributors complete a [Contributor License Agreement](http://islandora.ca/sites/default/files/islandora_cla.pdf) or be covered by a [Corporate Contributor License Agreement](http://islandora.ca/sites/default/files/islandora_ccla.pdf). The signed copy of the license agreement should be sent to <a href="mailto:community@islandora.ca?Subject=Contributor%20License%20Agreement" target="_top">community@islandora.ca</a>. This license is for your protection as a contributor as well as the protection of the Foundation and its users; it does not change your rights to use your own contributions for any other purpose. A list of current CLAs is kept [here](https://github.com/Islandora/islandora/wiki/Contributor-License-Agreements).

339
modules/islandora_advanced_search/LICENSE

@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) 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
this service 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 make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. 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.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the 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 a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE 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.
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
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the 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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision 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, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This 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.

261
modules/islandora_advanced_search/README.md

@ -0,0 +1,261 @@
# Islandora Advanced Search <!-- omit in toc -->
- [Introduction](#introduction)
- [Requirements](#requirements)
- [Installation](#installation)
- [Configuration](#configuration)
- [Configuring Solr](#configuring-solr)
- [Configure Collection Search](#configure-collection-search)
- [Configure Views](#configure-views)
- [Exposed Form](#exposed-form)
- [Collection Search](#collection-search)
- [Paging](#paging)
- [Sorting](#sorting)
- [Configure Facets](#configure-facets)
- [Include / Exclude Facets](#include--exclude-facets)
- [Configure Blocks](#configure-blocks)
- [Advanced Search Block](#advanced-search-block)
- [Documentation](#documentation)
- [Troubleshooting/Issues](#troubleshootingissues)
- [Maintainers](#maintainers)
- [Sponsors](#sponsors)
- [Development](#development)
- [License](#license)
## Introduction
This module creates several blocks to support searching. It also enables the use
of Ajax with search blocks, facets, and search results.
![image](./docs/demo.gif)
## Requirements
Use composer to download the required libraries and modules.
```bash
composer require drupal/facets "^1.3"
composer require drupal/search_api_solr "^4.1"
composer require drupal/search_api "^1.5"
```
However, for reference, `islandora_advanced_search` requires the following
drupal modules:
- [facets](https://www.drupal.org/project/facets)
- [search_api_solr](https://www.drupal.org/project/search_api_solr)
## Installation
To download/enable just this module, use the following from the command line:
```bash
composer require islandora/islandora
drush en islandora_advanced_search
```
## Configuration
You can set the following configuration at
`admin/config/islandora/advanced_search`:
![image](./docs/islandora_advanced_search_settings.png)
## Configuring Solr
Please review
[Islandora Documentation](https://islandora.github.io/documentation/user-documentation/searching/)
before continuing. The following assumes you already have a working Solr and the
Drupal Search API setup.
## Configure Collection Search
To support collection based searches you need to index the `field_member_of` for
every repository item as well define a new field that captures the full
hierarchy of `field_member_of` for each repository item.
Add a new `Content` solr field `field_decedent_of` to the solr index at
`admin/config/search/search-api/index/default_solr_index/fields`.
![image](./docs/field_decedent_of.png)
Then under `admin/config/search/search-api/index/default_solr_index/processors`
enable `Index hierarchy` and setup the new field to index the hierarchy.
![image](./docs/enable_index_hierarchy.png)
![image](./docs/enable_index_hierarchy_processor.png)
The field can now be used limit a search to all the decedents of a given object.
> N.B. You may have to re-index to make sure the field is populated.
## Configure Views
The configuration of views is outside of the scope of this document, please read
the [Drupal Documentation](https://www.drupal.org/docs/8/core/modules/views), as
well as the
[Search API Documentation](https://www.drupal.org/docs/contributed-modules/search-api).
### Exposed Form
Solr views allow the user to configure an exposed form (_optionally as a
block_). This form / block is **different** from the
[Advanced Search Block](#advanced-search-block). This module does not make any
changes to the form, but this form can cause the Advanced Search Block to not
function if configured incorrectly.
The Advanced Search Block requires that if present the Exposed forms
`Exposed form style` is set to `Basic` rather than `Input Required`. As
`Input Required` will prevent any search from occurring unless the user puts an
additional query in the Exposed form as well.
![Form Style](./docs/basic-input.png)
### Collection Search
That being said it will be typical that you require the following
`Relationships` and `Contextual Filters` when setting up a search view to enable
`Collection Search` searches.
![image](./docs/view_advanced_setting.png)
Here a relationship is setup with `Member Of` field and we have **two**
contextual filters:
1. `field_member_of` (Direct decedents of the Entity)
2. `field_decedent_of` (All decedents of the Entity)
Both of these filters are configured the exact same way.
![image](./docs/contextual_filter_settings.png)
These filters are toggled by the Advanced Search block to allow the search to
include all decedents or just direct decedents (*documented below*).
### Paging
The paging options specified here can have an affect on the pager block
(*documented below*).
![image](./docs/pager_settings.png)
### Sorting
Additional the fields listed as `Sort Criteria` as `Exposed` will be made
available in the pager block (*documented below*).
![image](./docs/sort_criteria.png)
## Configure Facets
The facets can be configured at `admin/config/search/facets`. Facets are linked
to a **Source** which is a **Search API View Display** so it will be typically
to have to duplicate your configuration for a given facet across each of the
displays where you want it to show up.
### Include / Exclude Facets
To be able to display exclude facet links as well as include links in the facets
block we have to duplicate the configuration for the facet like so.
![image](./docs/include_exclude_facets.png)
Both the include / exclude facets must use the widget
`List of links that allow the user to include / exclude facets`
![image](./docs/include_exclude_facets_settings.png)
The excluded facet also needs the following settings to appear and function
correctly.
The `URL alias` must match the same value as the include facet except it must be
prefixed with `~` character that is what links to the two facets to each other.
![image](./docs/exclude_facet_settings_url_alias.png)
And it must also explicitly be set to exclude:
![image](./docs/exclude_facet_settings_exclude.png)
You may also want to enable `Hide active items` and `Hide non-narrowing results`
for a cleaner presentation of facets.
## Configure Blocks
For each block type:
- Facet
- Pager
- Advanced Search
There will be **one block** per `View Display`. The block should be limited to
only appear when the view it was derived from is also being displayed on the
same page.
This requires configuring the `visibility` of the block as appropriate. For
collection based searches be sure to limit the display of the Facets block to
the models you want to display the search on, e.g:
![image](./docs/facet_block_settings.png)
### Advanced Search Block
For any valid search field, you can drag / drop and reorder the fields to
display in the advanced search form on. The configuration resides on the block
so this can differ across views / displays if need be. Additionally if the View
the block was derived from has multiple contextual filters you can choose which
one corresponds to direct children, this will enable the recursive search
checkbox.
![image](./docs/advanced_search_block_settings.png)
> N.B. Be aware that the Search views [Exposed Form](#exposed-form) can have an
> affect on the function of the
> [Advanced Search Block](#advanced-search-block). Please refer to that section
> to learn more.
## Documentation
Further documentation for this module is available on the
[Islandora 8 documentation site](https://islandora.github.io/documentation/).
## Troubleshooting/Issues
Having problems or solved a problem? Check out the Islandora google groups for
a solution.
- [Islandora Group](https://groups.google.com/forum/?hl=en&fromgroups#!forum/islandora)
- [Islandora Dev Group](https://groups.google.com/forum/?hl=en&fromgroups#!forum/islandora-dev)
## Maintainers
Current maintainers:
- [Nigel Banks](https://github.com/nigelgbanks)
## Sponsors
- LYRASIS
## Development
If you would like to contribute, please get involved by attending our weekly
[Tech Call](https://github.com/Islandora/documentation/wiki). We love to hear
from you!
If you would like to contribute code to the project, you need to be covered by
an Islandora Foundation
[Contributor License Agreement](http://islandora.ca/sites/default/files/islandora_cla.pdf)
or
[Corporate Contributor License Agreement](http://islandora.ca/sites/default/files/islandora_ccla.pdf).
Please see the [Contributors](http://islandora.ca/resources/contributors) pages
on Islandora.ca for more information.
We recommend using the
[islandora-playbook](https://github.com/Islandora-Devops/islandora-playbook) to
get started.
## License
[GPLv2](http://www.gnu.org/licenses/gpl-2.0.txt)

37
modules/islandora_advanced_search/css/islandora_advanced_search.form.css

@ -0,0 +1,37 @@
.islandora-advanced-search-form .form-type-select {
display: inline-block;
}
.islandora-advanced-search-form .form-type-select__select-wrapper {
width: auto;
}
.islandora-advanced-search-form .form-select {
margin-right: 0.25em;
}
input.islandora-advanced-search-form__add,
input.islandora-advanced-search-form__remove {
display: inline-block;
background: none !important;
border: none;
box-shadow: none;
color: #0c6170;
padding: 0 !important;
text-decoration: none;
margin: 0 0 1rem;
}
input.islandora-advanced-search-form__add:hover,
input.islandora-advanced-search-form__add:focus,
input.islandora-advanced-search-form__remove:hover,
input.islandora-advanced-search-form__remove:focus {
text-decoration: underline;
color: #0c6170;
outline: none;
}
input.islandora-advanced-search-form__reset,
input.islandora-advanced-search-form__search {
display: inline-block;
}

111
modules/islandora_advanced_search/css/islandora_advanced_search.pager.css

@ -0,0 +1,111 @@
.islandora_advanced_search_result_pager .pager__summary {
font-weight: 700;
}
.islandora_advanced_search_result_pager .pager__group {
margin: 1.25rem 0;
padding: 1rem 0;
border-top: 1px solid;
border-bottom: 1px solid;
border-color: #e5e5e5;
display: flex;
justify-content: flex-start;
align-items: center;
flex-flow: row wrap;
}
@media all and (min-width: 45.063em) {
.islandora_advanced_search_result_pager .pager__group {
justify-content: flex-end;
}
.islandora_advanced_search_result_pager .pager__group > * {
margin: 0.47214rem 0 0.47214rem 2.61803rem;
}
.islandora_advanced_search_result_pager .pager__group > *:first-child {
margin-left: 0;
}
}
.islandora_advanced_search_result_pager .pager__group > * {
margin: 0.47214rem 2rem 0.47214rem 0;
}
.islandora_advanced_search_result_pager .pager__group > *:last-child {
margin-right: 0;
}
.islandora_advanced_search_result_pager .pager__group .item-list__list,
.islandora_advanced_search_result_pager .pager__group .item-list__title,
.islandora_advanced_search_result_pager .pager__group .item-list__item {
display: inline;
}
.islandora_advanced_search_result_pager .pager__group .item-list__title {
font-size: initial;
margin: 0.25rem;
}
.pager {
margin: initial;
}
.pager__item {
margin: 0.125rem;
text-align: center;
}
.pager__items {
text-align: right;
}
@media all and (max-width: 45em) {
.pager__items {
text-align: center;
}
}
.pager__items__first-previous,
.pager__items__num-pages,
.pager__items__next-last {
display: inline;
}
.pager__items__first-previous,
.pager__items__next-last {
float: none;
}
.pager__items__first-previous .pager__item,
.pager__items__next-last .pager__item {
display: inline;
}
.pager .pager__link,
.pager__results .pager__link {
display: inline-block;
border-radius: 0.125em;
border: 1px solid;
transition: all, 0.2s, ease-in-out;
min-width: 1.75em;
padding: 0.125rem 0.4375rem 0;
}
.pager .pager__link:focus,
.pager .pager__link:hover,
.pager__results .pager__link:focus,
.pager__results .pager__link:hover {
text-decoration: underline;
}
.pager__display .pager__link {
background-color: #ffffff;
}
.pager__display .pager__link:hover,
.pager__display .pager__link:focus {
background-color: #ffffff;
}
.pager__link--is-active {
text-decoration: underline;
}

BIN
modules/islandora_advanced_search/docs/advanced_search_block_settings.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

BIN
modules/islandora_advanced_search/docs/basic-input.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

BIN
modules/islandora_advanced_search/docs/contextual_filter_settings.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

BIN
modules/islandora_advanced_search/docs/demo.gif

Binary file not shown.

After

Width:  |  Height:  |  Size: 645 KiB

BIN
modules/islandora_advanced_search/docs/enable_index_hierarchy.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

BIN
modules/islandora_advanced_search/docs/enable_index_hierarchy_processor.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

BIN
modules/islandora_advanced_search/docs/exclude_facet_settings_exclude.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

BIN
modules/islandora_advanced_search/docs/exclude_facet_settings_url_alias.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

BIN
modules/islandora_advanced_search/docs/facet_block_settings.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

BIN
modules/islandora_advanced_search/docs/field_decedent_of.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

BIN
modules/islandora_advanced_search/docs/include_exclude_facets.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

BIN
modules/islandora_advanced_search/docs/include_exclude_facets_settings.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

BIN
modules/islandora_advanced_search/docs/islandora_advanced_search_settings.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

BIN
modules/islandora_advanced_search/docs/pager.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

BIN
modules/islandora_advanced_search/docs/pager_settings.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

BIN
modules/islandora_advanced_search/docs/sort_criteria.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

BIN
modules/islandora_advanced_search/docs/view_advanced_setting.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

13
modules/islandora_advanced_search/islandora_advanced_search.info.yml

@ -0,0 +1,13 @@
# This .info.yml files provides the basic information about our module to Drupal
# More: https://www.drupal.org/node/2000204
name: 'Islandora Advanced Search'
description: "Creates an Advanced Search block and other enhancements to search."
type: module
package: Islandora
core_version_requirement: ^9 || ^10
dependencies:
- drupal:facets
- drupal:facets_summary
- drupal:search_api_solr
lifecycle: deprecated
lifecycle_link: https://groups.google.com/g/islandora/c/SEOAWJrfE_M

17
modules/islandora_advanced_search/islandora_advanced_search.libraries.yml

@ -0,0 +1,17 @@
advanced.search.admin:
js:
js/islandora_advanced_search.admin.js: {}
dependencies:
- core/drupal.tabledrag
advanced.search.form:
js:
js/islandora_advanced_search.form.js: {}
css:
component:
css/islandora_advanced_search.form.css: {}
advanced.search.pager:
css:
component:
css/islandora_advanced_search.pager.css: {}

6
modules/islandora_advanced_search/islandora_advanced_search.links.menu.yml

@ -0,0 +1,6 @@
islandora_advanced_search.settings:
title: 'Advanced Search Settings'
route_name: islandora_advanced_search.settings
description: 'Configure Islandora Advanced Search settings'
parent: system.admin_config_islandora
weight: 99

89
modules/islandora_advanced_search/islandora_advanced_search.module

@ -0,0 +1,89 @@
<?php
/**
* @file
* Contains islandora_advanced_search.module.
*
* This file is part of the Islandora Project.
*
* (c) Islandora Foundation
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Drupal\block\Entity\Block;
use Drupal\Core\Form\FormStateInterface;
use Drupal\islandora_advanced_search\AdvancedSearchQuery;
use Drupal\islandora_advanced_search\Utilities;
use Drupal\search_api\Query\QueryInterface as DrupalQueryInterface;
use Drupal\views\ViewExecutable;
use Solarium\Core\Query\QueryInterface as SolariumQueryInterface;
/**
* Implements hook_search_api_solr_converted_query_alter().
*/
function islandora_advanced_search_search_api_solr_converted_query_alter(SolariumQueryInterface $solarium_query, DrupalQueryInterface $search_api_query) {
// We must modify the query itself rather than the representation the
// search_api presents as it is not possible to use the 'OR' operator
// with it as it converts conditions into separate filter queries.
// Additionally filter queries do not affect the score so are not
// suitable for use in the advanced search queries.
$advanced_search_query = new AdvancedSearchQuery();
$advanced_search_query->alterQuery(\Drupal::request(), $solarium_query, $search_api_query);
}
/**
* Implements hook_form_form_id_alter().
*/
function islandora_advanced_search_form_block_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// Islandora removes this condition from the form, but we require it.
// So we can show blocks for nodes which belong to specific models.
// Allowing us to add a block for collections only.
$visibility = [];
$entity_id = $form['id']['#default_value'];
$block = Block::load($entity_id);
if ($block) {
$visibility = $block->getVisibility();
}
$manager = \Drupal::getContainer()->get('plugin.manager.condition');
$condition_id = 'node_has_term';
/** @var \Drupal\Core\Condition\ConditionInterface $condition */
$condition = $manager->createInstance($condition_id, isset($visibility[$condition_id]) ? $visibility[$condition_id] : []);
$form_state->set(['conditions', $condition_id], $condition);
$condition_form = $condition->buildConfigurationForm([], $form_state);
$condition_form['#type'] = 'details';
$condition_form['#title'] = $condition->getPluginDefinition()['label'];
$condition_form['#group'] = 'visibility_tabs';
// Not all blocks are required to give this field.
$condition_form['term']['#required'] = FALSE;
$form['visibility'][$condition_id] = $condition_form;
}
/**
* Implements hook_preprocess_preprocess_views_view().
*/
function islandora_advanced_search_preprocess_views_view(&$variables) {
/** @var \Drupal\views\ViewExecutable $view */
$view = &$variables['view'];
$views = Utilities::getPagerViewDisplays();
// Only add the toggle class for view display on displays in which the pager
// has been created for.
if (in_array([$view->id(), $view->current_display], $views)) {
// Toggle between 'list' and 'grid' display depending on url parameter.
$format = \Drupal::request()->query->get('display') ?? 'list';
$variables['attributes']['class'][] = "view-{$format}";
$view->element['#attached']['library'][] = 'islandora_advanced_search/advanced.search.pager';
}
$view = &$variables['view'];
}
/**
* Implements hook_views_pre_view().
*/
function islandora_advanced_search_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
// Allow for recursive searches by disabling contextual filter.
$advanced_search_query = new AdvancedSearchQuery();
$advanced_search_query->alterView(\Drupal::request(), $view, $display_id);
}

17
modules/islandora_advanced_search/islandora_advanced_search.routing.yml

@ -0,0 +1,17 @@
islandora_advanced_search.ajax.blocks:
path: '/islandora-advanced-search-ajax-blocks'
defaults:
_controller: '\Drupal\islandora_advanced_search\Controller\AjaxBlocksController::respond'
requirements:
# Allow public access to search blocks.
_access: 'TRUE'
islandora_advanced_search.settings:
path: '/admin/config/search/advanced'
defaults:
_form: '\Drupal\islandora_advanced_search\Form\SettingsForm'
_title: 'Islandora Advanced Search Settings'
requirements:
_permission: 'administer site configuration'
options:
_admin_route: TRUE

113
modules/islandora_advanced_search/js/islandora_advanced_search.admin.js

@ -0,0 +1,113 @@
//# sourceURL=modules/contrib/islandora_advanced_search/js/islandora-advanced-search.admin.js
/**
* @file
* Largely based on core/modules/blocks/js/blocks.js
*
* This file allows for moving rows between two regions in a table and have the
* 'region' field update appropriately.
*/
(function ($, window, Drupal) {
Drupal.behaviors.islandoraAdvancedSearchAdmin = {
attach: function attach(context, settings) {
if (typeof Drupal.tableDrag === 'undefined' || typeof Drupal.tableDrag['advanced-search-fields'] === 'undefined') {
return;
}
function checkEmptyRegions(table, rowObject) {
table.find('tr.region-message').each(function () {
var $this = $(this);
if ($this.prev('tr').get(0) === rowObject.element) {
if (rowObject.method !== 'keyboard' || rowObject.direction === 'down') {
rowObject.swap('after', this);
}
}
if ($this.next('tr').is(':not(.draggable)') || $this.next('tr').length === 0) {
$this.removeClass('region-populated').addClass('region-empty');
} else if ($this.is('.region-empty')) {
$this.removeClass('region-empty').addClass('region-populated');
}
});
}
function updateLastPlaced(table, rowObject) {
table.find('.color-success').removeClass('color-success');
var $rowObject = $(rowObject);
if (!$rowObject.is('.drag-previous')) {
table.find('.drag-previous').removeClass('drag-previous');
$rowObject.addClass('drag-previous');
}
}
function updateFieldWeights(table, region) {
var weight = -Math.round(table.find('.draggable').length / 2);
table.find('.region-' + region + '-message').nextUntil('.region-title').find('select.field-weight').val(function () {
return ++weight;
});
}
var table = $('#advanced-search-fields');
var tableDrag = Drupal.tableDrag['advanced-search-fields'];
tableDrag.row.prototype.onSwap = function (swappedRow) {
checkEmptyRegions(table, this);
updateLastPlaced(table, this);
};
tableDrag.onDrop = function () {
var dragObject = this;
var $rowElement = $(dragObject.rowObject.element);
var regionRow = $rowElement.prevAll('tr.region-message').get(0);
var regionName = regionRow.className.replace(/([^ ]+[ ]+)*region-([^ ]+)-message([ ]+[^ ]+)*/, '$2');
var regionField = $rowElement.find('select.field-display');
if (regionField.find('option[value=' + regionName + ']').length === 0) {
window.alert(Drupal.t('The field cannot be placed in this region.'));
regionField.trigger('change');
}
if (!regionField.is('.field-display-' + regionName)) {
var weightField = $rowElement.find('select.field-weight');
var oldRegionName = weightField[0].className.replace(/([^ ]+[ ]+)*field-weight-([^ ]+)([ ]+[^ ]+)*/, '$2');
regionField.removeClass('field-display-' + oldRegionName).addClass('field-display-' + regionName);
weightField.removeClass('field-weight-' + oldRegionName).addClass('field-weight-' + regionName);
regionField.val(regionName);
}
updateFieldWeights(table, regionName);
};
$(context).find('select.field-display').once('field-display').on('change', function (event) {
var row = $(this).closest('tr');
var select = $(this);
tableDrag.rowObject = new tableDrag.row(row[0]);
var regionMessage = table.find('.region-' + select[0].value + '-message');
var regionItems = regionMessage.nextUntil('.region-message, .region-title');
if (regionItems.length) {
regionItems.last().after(row);
} else {
regionMessage.after(row);
}
updateFieldWeights(table, select[0].value);
checkEmptyRegions(table, tableDrag.rowObject);
updateLastPlaced(table, row);
if (!tableDrag.changed) {
$(Drupal.theme('tableDragChangedWarning')).insertBefore(tableDrag.table).hide().fadeIn('slow');
tableDrag.changed = true;
}
select.trigger('blur');
});
}
};
})(jQuery, window, Drupal);

124
modules/islandora_advanced_search/js/islandora_advanced_search.form.js

@ -0,0 +1,124 @@
//# sourceURL=modules/contrib/islandora/modules/islandora_advanced_search/js/islandora-advanced-search.form.js
/**
* @file
* Handles Ajax submission / updating form action on url change, etc.
*/
(function ($, Drupal, drupalSettings) {
// Gets current parameters minus ones provided by the form.
function getParams(query_parameter, recurse_parameter) {
const url_search_params = new URLSearchParams(window.location.search);
const params = Object.fromEntries(url_search_params.entries());
// Remove Advanced Search Query Parameters.
const param_match = "query\\[\\d+\\]\\[.+\\]".replace("query", query_parameter);
const param_regex = new RegExp(param_match, "g");
for (const param in params) {
if (param.match(param_regex)) {
delete params[param];
}
}
// Remove Recurse parameter.
delete params[recurse_parameter];
// Remove the page if set as submitting the form should always take
// the user to the first page (facets do the same).
delete params["page"];
return params;
}
// Groups form inputs by search term.
function getTerms(inputs) {
const input_regex = /terms\[(?<index>\d+)\]\[(?<component>.*)\]/;
const terms = [];
for (const input in inputs) {
const name = inputs[input].name;
const value = inputs[input].value;
const found = name.match(input_regex);
if (found) {
const index = parseInt(found.groups.index);
const component = found.groups.component;
if (typeof terms[index] !== 'object') {
terms[index] = {};
}
terms[index][component] = value;
}
}
return terms;
}
// Checks if the form user has set recursive to true in the form.
function getRecurse(inputs) {
for (const input in inputs) {
const name = inputs[input].name;
const value = inputs[input].value;
if (name == "recursive" && value == "1") {
return true;
}
}
return false;
}
function url(inputs, settings) {
const terms = getTerms(inputs);
const recurse = getRecurse(inputs);
const params = getParams(settings.query_parameter, settings.recurse_parameter);
for (const index in terms) {
const term = terms[index];
// Do not include terms with no value.
if (term.value.length != 0) {
for (const component in term) {
const value = term[component];
const param = "query[index][component]"
.replace("query", settings.query_parameter)
.replace("index", index)
.replace("component", settings.mapping[component]);
params[param] = value;
}
}
}
if (recurse) {
params[settings.recurse_parameter] = '1';
}
return window.location.href.split("?")[0] + "?" + $.param(params);
}
Drupal.behaviors.islandora_advanced_search_form = {
attach: function (context, settings) {
if (settings.islandora_advanced_search_form.id !== 'undefined') {
const $form = $('form#' + settings.islandora_advanced_search_form.id).once();
if ($form.length > 0) {
window.addEventListener("pushstate", function (e) {
$form.attr('action', window.location.pathname + window.location.search);
});
window.addEventListener("popstate", function (e) {
if (e.state != null) {
$form.attr('action', window.location.pathname + window.location.search);
}
});
// Prevent form submission and push state instead.
//
// Logic server side / client side should match to generate the
// appropriate URL with javascript enabled or disable.
//
// If a route is set for the view display that this form is derived
// from, and we are not on the same page as that route, rely on the
// normal submit which will redirect to the appropriate page.
if (!settings.islandora_advanced_search_form.redirect) {
$form.submit(function (e) {
e.preventDefault();
e.stopPropagation();
const inputs = $form.serializeArray();
const href = url(inputs, settings.islandora_advanced_search_form);
window.history.pushState(null, document.title, href);
});
}
// Reset should trigger refresh of AJAX Blocks / Views.
$form.find('input[data-drupal-selector = "edit-reset"]').mousedown(function (e) {
const inputs = [];
const href = url(inputs, settings.islandora_advanced_search_form);
window.history.pushState(null, document.title, href);
});
}
}
}
};
})(jQuery, Drupal, drupalSettings);

254
modules/islandora_advanced_search/src/AdvancedSearchQuery.php

@ -0,0 +1,254 @@
<?php
namespace Drupal\islandora_advanced_search;
use Drupal\block\Entity\Block;
use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Url;
use Drupal\islandora_advanced_search\Form\SettingsForm;
use Drupal\islandora_advanced_search\Plugin\Block\AdvancedSearchBlock;
use Drupal\search_api\Query\QueryInterface as DrupalQueryInterface;
use Drupal\views\ViewExecutable;
use Solarium\Core\Query\QueryInterface as SolariumQueryInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Alter current search query / view from using URL parameters.
*/
class AdvancedSearchQuery {
use GetConfigTrait;
// User can set this configuration for the module.
const DEFAULT_QUERY_PARAM = 'a';
const DEFAULT_RECURSE_PARAM = 'r';
/**
* The query parameter is how terms are passed to the query.
*
* @var string
*/
protected $queryParameter;
/**
* The recurse parameter indicates the search should be recursive or not.
*
* @var string
*/
protected $recurseParameter;
/**
* Constructs a FacetBlockAjaxController object.
*
* @param string $query_parameter
* The field to search against.
* @param string $recurse_parameter
* The field that signifies the search should be recursive.
*/
public function __construct(string $query_parameter = self::DEFAULT_QUERY_PARAM, string $recurse_parameter = self::DEFAULT_RECURSE_PARAM) {
$this->queryParameter = $query_parameter;
$this->recurseParameter = $recurse_parameter;
}
/**
* Gets the query parameter to use that stores the search terms.
*
* @return string
* The query parameter to use that stores the search terms.
*/
public static function getQueryParameter() {
return self::getConfig(SettingsForm::SEARCH_QUERY_PARAMETER, self::DEFAULT_QUERY_PARAM);
}
/**
* Gets the query parameter to use that stores the search terms.
*
* @return string
* The recurse parameter used to indicate that the search should be
* recursive.
*/
public static function getRecurseParameter() {
return self::getConfig(SettingsForm::SEARCH_RECURSIVE_PARAMETER, self::DEFAULT_RECURSE_PARAM);
}
/**
* Extracts a list of AdvancedSearchQueryTerms from the given request.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The request to parse terms from.
*
* @return \Drupal\islandora_advanced_search\AdvancedSearchQueryTerm[]
* A list of search terms.
*/
public function getTerms(Request $request) {
$terms = [];
if ($request->query->has($this->queryParameter)) {
$query_params = $request->query->get($this->queryParameter);
if (is_array($query_params)) {
foreach ($query_params as $params) {
$terms[] = AdvancedSearchQueryTerm::fromQueryParams($params);
}
}
}
return array_filter($terms);
}
/**
* Checks if the query should recursively include sub-collections.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The request to parse.
*
* @return bool
* TRUE if the search should recurse FALSE otherwise.
*/
public function shouldRecurse(Request $request) {
if ($request->query->has($this->recurseParameter)) {
$recurse_param = $request->query->get($this->recurseParameter);
return filter_var($recurse_param, FILTER_VALIDATE_BOOLEAN);
}
return FALSE;
}
/**
* Checks if the all of the given terms are negations or not.
*
* @param \Drupal\islandora_advanced_search\AdvancedSearchQueryTerm[] $terms
* The terms to search for.
*
* @return bool
* TRUE if all terms are to be excluded otherwise FALSE.
*/
protected function negativeQuery(array $terms) {
foreach ($terms as $term) {
if ($term->getInclude()) {
return FALSE;
}
}
return TRUE;
}
/**
* Alters the given query using search terms provided in the given request.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The request to parse terms from.
* @param \Solarium\Core\Query\QueryInterface $solarium_query
* The solr query to modify.
* @param \Drupal\search_api\Query\QueryInterface $search_api_query
* The search api query from which the solr query was build.
*/
public function alterQuery(Request $request, SolariumQueryInterface &$solarium_query, DrupalQueryInterface $search_api_query) {
// Only apply if a Advanced Search Query was made.
$terms = $this->getTerms($request);
if (!empty($terms)) {
$index = $search_api_query->getIndex();
/** @var \Drupal\search_api_solr\Plugin\search_api\backend\SearchApiSolrBackend $backend */
$backend = $index->getServerInstance()->getBackend();
$language_ids = $search_api_query->getLanguages();
$field_mapping = $backend->getSolrFieldNamesKeyedByLanguage($language_ids, $index);
$q[] = "{!boost b=boost_document}";
// To support negative queries we must first bring in all documents.
$q[] = $this->negativeQuery($terms) ? "*:*" : "";
$term = array_shift($terms);
$q[] = $term->toSolrQuery($field_mapping);
foreach ($terms as $term) {
$q[] = $term->getConjunction();
$q[] = $term->toSolrQuery($field_mapping);
}
$q = implode(' ', $q);
/** @var Solarium\QueryType\Select\Query\Query $solarium_query */
$solarium_query->setQuery($q);
}
}
/**
* Alters the given view to be recursive if applicable.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The request to parse terms from.
* @param \Drupal\views\ViewExecutable $view
* The view to modify.
* @param string $display_id
* The view display to potentially alter.
*/
public function alterView(Request $request, ViewExecutable $view, $display_id) {
$views = Utilities::getAdvancedSearchViewDisplays();
// Only specify contextual filters for views which the advanced search
// blocks are derived from.
$block_id = array_search([$view->id(), $display_id], $views);
if ($block_id !== FALSE) {
$block = Block::load($block_id);
$settings = $block->get('settings');
// Ignore the immediate children contextual filter in the query to allow
// for recursive search.
if (isset($settings[AdvancedSearchBlock::SETTING_CONTEXTUAL_FILTER])) {
$display = $view->getDisplay();
$display_arguments = $display->getOption('arguments');
$immediate_children_contextual_filter = $settings[AdvancedSearchBlock::SETTING_CONTEXTUAL_FILTER];
$index = array_search($immediate_children_contextual_filter, array_keys($display_arguments));
if ($this->shouldRecurse($request)) {
// Change the argument to the exception value which should cause the
// contextual filter to be ignored.
$view->args[$index] = $display_arguments[$immediate_children_contextual_filter]['exception']['value'];
}
else {
// Explicitly set the default argument for AJAX requests.
// We need to restore the default as that functionality is currently
// broken. @see https://www.drupal.org/project/drupal/issues/3173778
//
// We fake the current request from the refer only to set the default
// argument in case it is build from the URL. If this is not an AJAX
// request this logic can be ignored.
if ($request->isXmlHttpRequest()) {
$view->initHandlers();
$request_stack = \Drupal::requestStack();
$refer = Request::create($request->server->get('HTTP_REFERER'));
$refer->getPathInfo();
$refer->attributes->add(\Drupal::getContainer()->get('router')->matchRequest($refer));
$request_stack->push($refer);
$plugin = $view->argument[$immediate_children_contextual_filter]->getPlugin('argument_default');
if ($plugin) {
$view->args[$index] = $plugin->getArgument();
}
$request_stack->pop();
}
}
}
}
}
/**
* Get query parameter for all search terms.
*
* @return \Drupal\Core\Url
* Url for the given request combined with search query parameters.
*/
public function toUrl(Request $request, array $terms, bool $recurse, $route = NULL) {
$query_params = $request->query->all();
if ($route) {
$url = Url::fromRoute($route);
// The form that built the url may use AJAX, but we are redirecting to a
// new page, so it should be disabled.
unset($query_params[FormBuilderInterface::AJAX_FORM_REQUEST]);
unset($query_params[MainContentViewSubscriber::WRAPPER_FORMAT]);
}
else {
$url = Url::createFromRequest($request);
}
unset($query_params[$this->queryParameter]);
foreach ($terms as $term) {
$query_params[$this->queryParameter][] = $term->toQueryParams();
}
if ($recurse) {
$query_params[$this->recurseParameter] = '1';
}
else {
unset($query_params[$this->recurseParameter]);
}
$url->setOptions(['query' => $query_params]);
return $url;
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save