Compare commits

...

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

  1. 33
      .github/PULL_REQUEST_TEMPLATE.md
  2. 125
      .github/workflows/build-2.x.yml
  3. 26
      .github/workflows/gitlab-mirror.yml
  4. 6
      .gitignore
  5. 52
      .travis.yml
  6. 96
      CONTRIBUTING.md
  7. 15
      COPYRIGHT
  8. 339
      LICENSE
  9. 674
      LICENSE.txt
  10. 133
      README.md
  11. 57
      composer.json
  12. 4
      config/install/islandora.settings.yml
  13. 13
      config/install/system.action.delete_media_and_file.yml
  14. 244
      config/schema/islandora.schema.yml
  15. 23
      css/islandora.admin.css
  16. 73
      css/islandora.base.css
  17. 3
      css/islandora.css
  18. 66
      css/islandora.objects.css
  19. 64
      css/islandora.print.css
  20. 43
      css/islandora.theme.css
  21. 6
      drush.services.yml
  22. BIN
      images/folder.png
  23. BIN
      images/print-icon.png
  24. 236
      includes/add_datastream.form.inc
  25. 256
      includes/admin.form.inc
  26. 131
      includes/authtokens.inc
  27. 173
      includes/breadcrumb.inc
  28. 57
      includes/content_model.autocomplete.inc
  29. 536
      includes/datastream.inc
  30. 402
      includes/datastream.version.inc
  31. 145
      includes/delete_datastream.form.inc
  32. 48
      includes/delete_object.form.inc
  33. 311
      includes/derivatives.inc
  34. 170
      includes/dublin_core.inc
  35. 1029
      includes/ingest.form.inc
  36. 384
      includes/manage_deleted_objects.inc
  37. 176
      includes/metadata.inc
  38. 265
      includes/mime_detect.inc
  39. 26
      includes/mime_type.autocomplete.inc
  40. 278
      includes/mimetype.utils.inc
  41. 57
      includes/object.entity_controller.inc
  42. 252
      includes/object_properties.form.inc
  43. 278
      includes/orphaned_objects.inc
  44. 182
      includes/regenerate_derivatives.form.inc
  45. 839
      includes/solution_packs.inc
  46. 116
      includes/tuque.inc
  47. 629
      includes/tuque_wrapper.inc
  48. 968
      includes/utilities.inc
  49. 947
      islandora.api.php
  50. 201
      islandora.drush.inc
  51. 30
      islandora.info
  52. 33
      islandora.info.yml
  53. 307
      islandora.install
  54. 5
      islandora.libraries.yml
  55. 29
      islandora.links.action.yml
  56. 20
      islandora.links.menu.yml
  57. 2585
      islandora.module
  58. 12
      islandora.permissions.yml
  59. 16
      islandora.post_update.php
  60. 111
      islandora.routing.yml
  61. 580
      islandora.rules.inc
  62. 26
      islandora.rules_defaults.inc
  63. 80
      islandora.services.yml
  64. 192
      islandora.tokens.inc
  65. 54
      islandora.views.inc
  66. 21
      js/spin/LICENSE.txt
  67. 11
      js/spin/README.md
  68. 1
      js/spin/spin.min.js
  69. 70
      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

33
.github/PULL_REQUEST_TEMPLATE.md

@ -1,24 +1,18 @@
**GitHub Issue**: (link)
**JIRA Ticket**: (link)
* Other Relevant Links (Google Groups discussion, related pull requests,
Release pull requests, etc.)
* 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.
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.
A in-depth description of the changes made by this PR. Technical details and possible side effects.
Example:
* 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?
@ -28,16 +22,15 @@ A description of what steps someone could take to:
* 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.
Any additional information that you think would be helpful when reviewing this PR.
Example:
* Does this change require documentation to be updated?
* Does this change add any new dependencies?
* Does this change require any other modifications to be made to the repository (ie. Regeneration activity, etc.)?
* Could this change impact execution of existing code?
# Interested parties
Tag (@ mention) interested parties or, if unsure, @Islandora/committers
Tag (@ mention) interested parties or, if unsure, @Islandora/7-x-1-x-committers

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

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

@ -1,26 +0,0 @@
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 @@
vendor
/.idea/
/.vscode
cache.properties
.DS_Store
tests/test_config.ini

52
.travis.yml

@ -0,0 +1,52 @@
sudo: required
dist: trusty
language: php
matrix:
include:
#5.3.3 Ubuntu Precise exceptions
- php: 5.3.3
dist: precise
env: FEDORA_VERSION="3.5"
- php: 5.3.3
dist: precise
env: FEDORA_VERSION="3.6.2"
- php: 5.3.3
dist: precise
env: FEDORA_VERSION="3.7.0"
- php: 5.3.3
dist: precise
env: FEDORA_VERSION="3.8.1"
php:
- 5.4
- 5.5
- 5.6
- 7.0
- 7.1
env:
- FEDORA_VERSION="3.5"
- FEDORA_VERSION="3.6.2"
- FEDORA_VERSION="3.7.0"
- FEDORA_VERSION="3.8.1"
branches:
only:
- /^7.x/
global:
# This key is unique to the Islandora/islandora repository; logging will
# fail on forked repositories unless a new unique key is generated for them.
- secure: "nTv2Zb/qKlECK+xE5ahbfXI9ZZbf2ZMd796q7oPlTxUwvu6nomHnUOjJATl6tq2cj23PyJ89Jlgl5cMZ5h0QMUzYpN5hPyY6oCJxWgFamFaE3bv5E/rBd1f6WVTJW7S4UKn8Mr9R2PrX+ZxQZGVIigAfR8VfhQuP8PcuO5eMLBk="
before_install:
- export ISLANDORA_DIR=$TRAVIS_BUILD_DIR
- $TRAVIS_BUILD_DIR/tests/scripts/travis_setup.sh
- cd $HOME/drupal-*
before_script:
# Mysql might time out for long tests, increase the wait timeout.
- mysql -e 'SET @@GLOBAL.wait_timeout=1200'
script:
- $ISLANDORA_DIR/tests/scripts/travis_scripts.sh
- $ISLANDORA_DIR/tests/scripts/run_tests.sh "Islandora"
after_failure:
- $ISLANDORA_DIR/tests/scripts/travis_after_failure.sh
notifications:
irc: "irc.freenode.org#islandora"

96
CONTRIBUTING.md

@ -1,34 +1,53 @@
# 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!
If you are reading this document then you are interested in contributing to Islandora, and that's awesome! 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.
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.
Islandora Committers Calls happen every Thursday at 2PM EST. The meetings are generally held on Skype, and you can join the calls by sending a request to community@islandora.ca.
### Use cases
### Documentation
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.
You can contribute documentation in two different ways. One way is to join the [Documentation Interest Group](https://github.com/islandora-interest-groups/Islandora-Documentation-Interest-Group). Another way is to [open an issue](https://jira.duraspace.org/secure/CreateIssue!default.jspa). You will need a JIRA account to do this. If you don't have one, you can sign up [here](https://jira.duraspace.org/secure/Signup!default.jspa). Set the Issue Type to "Documentation".
### Documentation
### Request a new feature (use cases).
To request a new feature you should [open an issue](https://jira.duraspace.org/secure/CreateIssue!default.jspa). You will need a JIRA account to do this. If you don't have one, you can sign up [here](https://jira.duraspace.org/secure/Signup!default.jspa). Set the Issue Type to "New Feature".
In order to help us understand the feature request, it would be great if you could provide us with a use case:
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).
| Title (Goal) | The title or goal of your use case |
--------------- |------------------------------------ |
| Primary Actor | Repository architect, implementer, repository admin, user |
| Scope | The scope of the project. Example: architecture, access |
| Level | The priority the use case should be given; High, Medium, Low |
| Story | This is a [user story](http://en.wikipedia.org/wiki/User_story).
### 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.
***
**Examples**:
* Bullet
* Listed
* Examples should you want to provide them.
**Remarks**:
* Bullet
* Listed
* Remarks should you want to provide them.
### 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.
To report a bug you should [open an issue](https://jira.duraspace.org/secure/CreateIssue!default.jspa) that summarizes the bug. Set the Issue Type to "Bug".
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.
1. The steps to reproduce the bug. This includes information about e.g. the Islandora version you were using along with version of stack components.
2. The expected behavior.
3. The actual, incorrect behavior.
@ -36,37 +55,74 @@ Feel free to search the issue queue for existing issues (aka tickets) that alrea
**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.
That is great! In this case please send us a pull request as described in section _Create a pull request_ below.
### Participate in a Release
Islandora releases occur twice yearly, at the end of April and October. Two to three months before a release, a Call for Volunteers will be issued across Islandora communication channels (website, Twitter, listservs). The Release team consists of both developers and end-users who fix bugs, test fixes, verify improvements and new features; update documentation; and review README and LICENSE files. A Release VM is issued with each release so that testers can have a stable, easy-to-deploy environment in which to work.
To join an Islandora Release Team, sign up for one or more modules in any of the following roles:
* **Component Manager** (Very familiar with module code; reviews commits)
* **Tester** (Tests JIRA tickets marked "Ready for test" and does a general workover of the module)
* **Documentor** (Reviews and updates existing documentation or writes new documentation for new modules)
* **Auditor** (Reviews and updates README and LICENSE files to ensure complaince with templates and standards)
### 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>
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 Licencse 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).
In this case you should [browse open issues](https://jira.duraspace.org/issues/?jql=project%20%3D%20ISLANDORA%20AND%20resolution%20%3D%20Unresolved%20ORDER%20BY%20priority%20DESC).
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.
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. You should also follow the Islandora community's [Git Guidelines and Best Practices](https://github.com/Islandora/islandora/wiki/Git-Guidelines-and-Best-Practices).
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.
1. [Open an issue](https://jira.duraspace.org/secure/CreateIssue!default.jspa) and assign it the label of "New Feature" or "Improvement", 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.
Developer questions? We have a lot of excellent developer documentation that can be found [here](https://github.com/islandora/islandora/wiki#documentation-for-developers).
#### Issue / Topic Branches
All JIRA issues should be worked on in separate git branches. The branch name should be the same as the JIRA issue number, including all-caps, so ISLANDORA-153, ISLANDORA-118, etc.
Example: `git checkout -b 7.x-ISLANDORA-977` or `git checkout -b 7.x-1.4-ISLANDORA-977`
### 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:
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.
1. [Fork](https://help.github.com/articles/fork-a-repo) a given Islandora Foundation component repository at [https://github.com/islandora](https://github.com/islandora) to your personal GitHub account. 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.
3. Send a [pull request](https://help.github.com/articles/creating-a-pull-request) to the Islandora GitHub repository that you forked in step 1. If your pull request is related to an existing JIRA issue -- for instance, because you reported a bug/issue earlier -- then prefix the title of your pull request with the corresponding issue number (e.g. `ISLANDORA-123: ...`). The branch name should also correspond to the JIRA issue number.
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) `islandora` repository.
Community members who have push/merge permissions on a repository should **never** push directly to a repo, nor merge their own pull requests.
#### Release branch pull requests
The pull request process will roughly look like this:
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.
1. fork from Islandora repo if that has not already been done
2. `git remote add islandora git@github.com:Islandora/islandora_checksum.git`
3. `git pull islandora 7.x`
4. Make changes, commit
5. `git push origin 7.x` and issue a pull request on 7.x
6. `git fetch --all`
7. `git checkout 7.x-1.4` if that does not work, `git checkout islandora/7.x-1.4` then `git checkout -b 7.x-1.4`
8. Make changes/cherry pick/copy changes from earlier, commit
9. `git push origin 7.x-1.4` and issue a pull request on 7.x-1.4
## License Agreements

15
COPYRIGHT

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

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

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

133
README.md

@ -1,121 +1,90 @@
# Islandora
[![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)
[![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)
[![codecov](https://codecov.io/gh/Islandora/islandora/branch/2.x/graph/badge.svg)](https://codecov.io/gh/Islandora/islandora)
# Islandora [![Build Status](https://travis-ci.org/Islandora/islandora.png?branch=7.x)](https://travis-ci.org/Islandora/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
This module includes the core functionality for interacting with Fedora Repository objects through the Drupal interface.
For installation and customization instructions please see the [documentation and the DuraSpace Wiki](https://wiki.duraspace.org/display/ISLANDORA/Islandora).
All bugs, feature requests and improvement suggestions are tracked at the [DuraSpace JIRA](https://jira.duraspace.org/browse/ISLANDORA).
## Requirements
Installing via composer will download all required libraries and modules. However, for reference, `islandora` requires the following drupal modules:
This module requires the following modules/libraries:
* [Tuque](https://github.com/islandora/tuque)
Tuque is expected to be in one of two paths:
- [context](http://drupal.org/project/context)
- [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)
* sites/all/libraries/tuque (libraries directory may need to be created)
* islandora_folder/libraries/tuque
It also requires the following PHP libraries:
More detailed requirements are outlined in the [Installing the Islandora Essential Modules](https://wiki.duraspace.org/display/ISLANDORA/milestone+5+-++Installing+the+Islandora+Essential+Modules) chapter of the documentation.
- [Crayfish Commons](https://packagist.org/packages/islandora/crayfish-commons)
- [Stomp PHP](http://drupal.org/project/)
### Optional Requirements
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.
If you want to support languages other than English, download and enable [String Translation](https://drupal.org/project/i18n), and follow our [guide](https://github.com/Islandora/islandora/wiki/Multilingual-Support) for setting up additional languages.
## Installation
For a full digital repository solution, see our [installation documentation](https://islandora.github.io/documentation/installation/component_overview/).
This is one Drupal module in a suite of modules (and stack of related software) which are required for Islandora to function correctly. For full installation instructions please see the [documentation in the DuraSpace Wiki](https://wiki.duraspace.org/display/ISLANDORA/Islandora).
To download/enable just this module, use the following from the command line:
### Global Fedora XACML policies
Before installing Islandora, the XACML policies located [here](https://github.com/Islandora/islandora-xacml-policies) should be copied into the Fedora global XACML policies folder. This will allow "authenticated users" in Drupal to access Fedora API-M functions (create, edit, and delete objects in Fedora).
Notes:
* Delete the `permit-upload-to-anonymous-user.xml` and `permit-apim-to-anonymous-user.xml` policies unless you want to allow anonymous (unauthenticated) users to create Islandora objects (not recommended).
* Delete the `deny-purge-datastream-if-active-or-inactive.xml` to allow users to purge (permanently remove) datastream versions.
More detailed information can be found in the 'Set XACML Policies' in the [Installing Fedora](https://wiki.duraspace.org/display/ISLANDORA/milestone+1+-+Installing+Fedora) chapter of the documentation.
### Protecting the 'anonymous' username
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. If this is done after installing Islandora, Drupal's cron can be run to remove expired authentication tokens.
```bash
$ composer require islandora/islandora
$ drush en islandora_core_feature
$ drush mim islandora_tags
```
## Configuration
![image](https://user-images.githubusercontent.com/20773151/67234502-ac171900-f41b-11e9-964e-c7d4cfadbd67.png)
Configuration that applies to all solution packs, including the location of the Fedora Repository, the namespaces accessible by this instance of Islandora, and whether to generate derivatives on ingest, are available at `admin/islandora/configure`.
![Configuration](https://user-images.githubusercontent.com/1943338/40320855-724afcba-5d03-11e8-9109-0b8413349839.png)
### Breadcrumb Generation
Whether Drupal breadcrumbs (showing an object's parent hierarchy) should be displayed, and how they are generated, can be set on the configuration page. Other modules (such as [Islandora Solr](https://github.com/Islandora/islandora_solr_search)) may provide alternatives that perform better at large scales than the built-in Resource Index query.
### Inactive and Deleted Objects
By default, objects with the [Fedora state](https://wiki.duraspace.org/display/FEDORA38/Fedora+Digital+Object+Model) of "Inactive" or "Deleted" are accessible to all users with the Drupal permission "View repository objects". It is possible to use a separate permission to control access to these non-"Active" objects, but this permission must first be enabled at `admin/islandora/configure`, then the permssion can be granted to desired roles at `admin/people/permissions`.
### Customization
Hooks provided by Islandora are documented in `islandora.api.php`. A [detailed tutorial](https://github.com/Islandora/islandora/wiki/Multi-paged-Ingest-Forms) on extending the multi-page ingest forms is available on the Github (developers') Wiki.
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.
## Documentation
Further documentation for this module is available on the [Islandora 8 documentation site](https://islandora.github.io/documentation/).
Further documentation for this module is available at [our documentation wiki](https://wiki.duraspace.org/display/ISLANDORA/Islandora+Core+Module).
## Troubleshooting/Issues
NOTE: There has been a function signature change for the `ingestDatastream` function within Tuque which will be deprecated after the 7.x-1.10 release. To read about it in detail please see the [JIRA ticket](https://jira.duraspace.org/browse/ISLANDORA-1995). For the time being there is a warning stating that this will become deprecated and that code that utilizes this specific behavior should be updated. Once this code is updated the `islandora_deprecation_return_false_when_datastream_exists` variable may be set to FALSE so the warning no longer displays. An example for doing this with drush: `drush vset islandora_deprecation_return_false_when_datastream_exists FALSE`.
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
## Maintainers/Sponsors
Current maintainers:
* [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/)
* [Diego Pino](https://github.com/DiegoPino)
## Development
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.
If you would like to contribute to this module, please check out [CONTRIBUTING.md](CONTRIBUTING.md). In addition, we have 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](http://islandora.ca) site.
## License
[GPLv2](http://www.gnu.org/licenses/gpl-2.0.txt)
[GPLv3](http://www.gnu.org/licenses/gpl-3.0.txt)

57
composer.json

@ -1,57 +0,0 @@
{
"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

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

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

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

@ -0,0 +1,23 @@
/**
* @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

@ -0,0 +1,73 @@
/*
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

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

66
css/islandora.objects.css

@ -0,0 +1,66 @@
/**
* @file
* Styles for rendering grids/lists of objects.
*/
div.islandora-objects > div {
overflow: hidden;
margin: 0 auto;
width: 100%;
display: inline-block;
}
/* img styling (max-width) - Setting a max width to ensure a thumbnails width
* does not exceed that of its parent container (ex: 20%).
*
* img styling (max-height) - Avoid making assumptions on max height here, allowing auto
* height based on max-width of 100%. Consider overriding this file in your theme,
* or adding your own CSS to address a maximum thumbnail height.
*/
.islandora-object img {
max-width: 100%;
}
.islandora-objects-list-item {
clear: both;
width: 100%;
}
.islandora-objects-list-item dl dt {
clear: left;
float: left;
padding: 3px 0 0;
text-align: center;
width: 100px;
}
.islandora-objects-list-item dl dd {
margin: 0 0 0 130px;
}
/*Grid - Displays grid using dl formatted inline */
.islandora-objects-grid dl {
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-grid-item {
display: inline;
}
.islandora-objects-grid dd {
margin: 0;
padding: 0;
}
.islandora-objects-display-switch {
float: right;
}

64
css/islandora.print.css

@ -0,0 +1,64 @@
/**
* @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

@ -0,0 +1,43 @@
/*
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

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

After

Width:  |  Height:  |  Size: 5.0 KiB

BIN
images/print-icon.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

236
includes/add_datastream.form.inc

@ -0,0 +1,236 @@
<?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;
$datastream_requirements = islandora_get_missing_datastreams_requirements($object);
$unused_datastreams = array_keys($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' => t('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: <strong>@unused_dsids</strong>.", 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 <strong>@size MB.</strong>', array('@size' => $upload_size)),
'#default_value' => isset($form_state['values']['files']) ? $form_state['values']['files'] : NULL,
'#upload_location' => file_default_scheme() . '://',
'#upload_validators' => array(
// Disable default file_validate_extensions; we need direct control.
'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'])));
}
}
/**
* Validation callback for islandora_add_datastream_form.
*
* Checks if the given datastream can accept the given MIME type.
*/
function islandora_add_datastream_form_validate(array $form, array &$form_state) {
module_load_include('inc', 'islandora', 'includes/mimetype.utils');
$extensions = islandora_get_extensions_for_datastream(
$form_state['object'],
$form_state['values']['dsid']
);
$file = file_load($form_state['values']['file']);
// Only validate extensions if mimes defined in ds-composite.
if ($file && $extensions) {
$errors = file_validate_extensions($file, implode(' ', $extensions));
if (count($errors) > 0) {
form_set_error(
'file',
t("!error (for the set DSID)", array('!error' => $errors[0]))
);
}
}
}
/**
* 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'])));
}
}
/**
* 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);
}

256
includes/admin.form.inc

@ -0,0 +1,256 @@
<?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);
$breadcrumb_backend_options = module_invoke_all('islandora_breadcrumbs_backends');
$map_to_title = function ($backend) {
return $backend['title'];
};
// In case the selected breadcrumb backend is no longer available.
$breadcrumb_backend = variable_get('islandora_breadcrumbs_backends', ISLANDORA_BREADCRUMB_LEGACY_BACKEND);
if (!isset($breadcrumb_backend_options[$breadcrumb_backend])) {
$breadcrumb_backend = ISLANDORA_BREADCRUMB_LEGACY_BACKEND;
}
$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_use_object_semaphores' => array(
'#type' => 'checkbox',
'#title' => t('Make Processes Claim Objects for Modification'),
'#description' => t('Enabling this will increase stability of Fedora at high concurrency but will incur a heavy performance hit.'),
'#default_value' => variable_get('islandora_use_object_semaphores', FALSE),
),
'islandora_semaphore_period' => array(
'#type' => 'textfield',
'#title' => t('Time to Claim Objects for'),
'#default_value' => variable_get('islandora_semaphore_period', 600),
'#description' => t('Maximum time in seconds to claim objects for modification.'),
'#states' => array(
'invisible' => array(
':input[name="islandora_use_object_semaphores"]' => array('checked' => FALSE),
),
),
),
'islandora_defer_derivatives_on_ingest' => array(
'#type' => 'checkbox',
'#title' => t('Defer derivative generation during ingest'),
'#description' => t('Prevent derivatives from running during ingest,
useful if derivatives are to be created by an external service.'),
'#default_value' => variable_get('islandora_defer_derivatives_on_ingest', FALSE),
),
'islandora_render_context_ingeststep' => array(
'#type' => 'checkbox',
'#title' => t('Render applicable Content Model label(s) during ingest steps'),
'#description' => t('This enables contextual titles, displaying Content Model label(s), to be added on top of ingest forms.'),
'#default_value' => variable_get('islandora_render_context_ingeststep', FALSE),
),
'islandora_show_print_option' => array(
'#type' => 'checkbox',
'#title' => t('Show print option on objects'),
'#description' => t('Displays an extra print tab, allowing an object to be printed'),
'#default_value' => variable_get('islandora_show_print_option', FALSE),
),
'islandora_render_drupal_breadcrumbs' => array(
'#type' => 'checkbox',
'#title' => t('Render Drupal breadcrumbs'),
'#description' => t('Larger sites may experience a notable performance improvement when disabled due to how breadcrumbs are constructed.'),
'#default_value' => variable_get('islandora_render_drupal_breadcrumbs', TRUE),
),
'islandora_breadcrumbs_backends' => array(
'#type' => 'radios',
'#title' => t('Breadcrumb generation'),
'#description' => t('How breadcrumbs for Islandora objects are generated for display.'),
'#default_value' => $breadcrumb_backend,
'#options' => array_map($map_to_title, $breadcrumb_backend_options),
'#states' => array(
'visible' => array(
':input[name="islandora_render_drupal_breadcrumbs"]' => array('checked' => TRUE),
),
),
),
'islandora_risearch_use_itql_when_necessary' => array(
'#type' => 'checkbox',
'#title' => t('Use iTQL for particular queries'),
'#description' => t('Sparql is the preferred language for querying the resource index; however, some features in the implementation of Sparql in Mulgara may not work properly. If you are using the default triple store with Fedora this should be left on to maintain legacy behaviour.'),
'#default_value' => variable_get('islandora_risearch_use_itql_when_necessary', TRUE),
),
'islandora_require_obj_upload' => array(
'#type' => 'checkbox',
'#title' => t('Require a file upload during ingest'),
'#description' => t('During the ingest workflow, make the OBJ file upload step mandatory.'),
'#default_value' => variable_get('islandora_require_obj_upload', TRUE),
),
'islandora_deny_inactive_and_deleted' => array(
'#type' => 'checkbox',
'#title' => t('Lock down inactive and deleted objects.'),
'#description' => t('Require a separate permission to access inactive and deleted objects.'),
'#default_value' => variable_get('islandora_deny_inactive_and_deleted', FALSE),
),
),
'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. <strong>demo:mydemos</strong>. <br /> The namespace <strong>islandora:</strong> 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),
),
),
),
),
'islandora_ds_replace_exclude' => array(
'#type' => 'fieldset',
'#title' => t('Excluded DSID'),
'islandora_ds_replace_exclude_enforced' => array(
'#type' => 'textfield',
'#title' => t('Enforce DSID restrictions'),
'#description' => t("A comma seperated list, allowing administrator to restrict user's access to replace a versionable datastreams latest version"),
'#default_value' => variable_get('islandora_ds_replace_exclude_enforced', 'RELS-EXT,RELS-INT'),
),
),
),
);
return system_settings_form($form);
}
/**
* Validate the admin form.
*/
function islandora_repository_admin_validate($form, &$form_state) {
// Only validate semaphore period if semaphores are enabled.
if ($form_state['values']['islandora_use_object_semaphores']) {
if ($form_state['values']['islandora_semaphore_period']) {
element_validate_integer_positive($form['islandora_tabs']['islandora_general']['islandora_semaphore_period'], $form_state);
}
else {
form_set_error('islandora_semaphore_period', t('<em>Time to Claim Objects for</em> must not be empty if <em>Make Processes Claim Objects for Modification</em> is checked.'));
}
}
}
/**
* 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'];
}

131
includes/authtokens.inc

@ -0,0 +1,131 @@
<?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();
$token = bin2hex(drupal_random_bytes(32));
$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();
}

173
includes/breadcrumb.inc

@ -0,0 +1,173 @@
<?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(AbstractObject $object) {
$breadcrumbs = array();
if (variable_get('islandora_render_drupal_breadcrumbs', TRUE)) {
$backend = variable_get('islandora_breadcrumbs_backends', ISLANDORA_BREADCRUMB_LEGACY_BACKEND);
$backends = module_invoke_all('islandora_breadcrumbs_backends');
if ($backend === ISLANDORA_BREADCRUMB_LEGACY_BACKEND || !isset($backends[$backend])) {
$breadcrumbs = islandora_get_breadcrumbs_legacy($object->id, $object->repository);
}
else {
if (isset($backends[$backend]['file'])) {
require_once $backends[$backend]['file'];
}
$breadcrumbs = call_user_func($backends[$backend]['callable'], $object);
}
$context = 'islandora';
drupal_alter('islandora_breadcrumbs', $breadcrumbs, $context, $object);
}
return $breadcrumbs;
}
/**
* Call the legacy SPARQL recursive function and return the correct breadcrumbs.
*
* @param string $pid
* The object id whose parent will be fetched for the next link.
* @param \IslandoraFedoraRepository $repository
* The fedora repository.
*
* @return array
* An array of links representing the breadcrumb trail, "root" first.
*/
function islandora_get_breadcrumbs_legacy($pid, IslandoraFedoraRepository $repository) {
$breadcrumbs = islandora_get_breadcrumbs_recursive($pid, $repository);
array_pop($breadcrumbs);
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) {
module_load_include('inc', 'islandora', 'includes/utilities');
// 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 = <<<EOQ
PREFIX islandora-rels-ext: <http://islandora.ca/ontology/relsext#>
PREFIX fedora-rels-ext: <info:fedora/fedora-system:def/relations-external#>
SELECT DISTINCT ?object ?label
FROM <#ri>
WHERE {
<info:fedora/!pid> ?collection_predicate ?object;
<fedora-model:label> ?label .
?object <fedora-model:state> <fedora-model:Active>
.
!optionals
!filters
}
!order
EOQ;
$query_optionals = (array) module_invoke('islandora_xacml_api', 'islandora_basic_collection_get_query_optionals', 'view');
$query_filters = (array) module_invoke('islandora_xacml_api', 'islandora_basic_collection_get_query_filters');
$filter_map = function ($filter) {
return "FILTER($filter)";
};
$object = islandora_object_load($pid);
$breadcrumb_predicates = islandora_invoke_hook_list(ISLANDORA_BREADCRUMB_FILTER_PREDICATE_HOOK, $object->models, array($object));
$same_term_map = function ($predicate) {
return "sameTerm(?collection_predicate, <$predicate>)";
};
$collection_predicate_filters = array_map($same_term_map, $breadcrumb_predicates);
$query_filters[] = implode(' || ', $collection_predicate_filters);
$query_order = "ORDER BY DESC(?label)";
$query = format_string($query, array(
'!optionals' => !empty($query_optionals) ? ('OPTIONAL {{' . implode('} UNION {', $query_optionals) . '}}') : '',
'!filters' => implode(' ', array_map($filter_map, $query_filters)),
'!order' => $query_order,
));
$query = format_string($query, array(
'!pid' => $pid,
));
$results = $repository->ri->sparqlQuery($query, 'unlimited');
if (count($results) > 0 && $context['level'] > 0) {
$parent = $results[0]['object']['value'];
$this_label = $results[0]['label']['value'];
if (empty($this_label)) {
$this_label = t('-');
}
$context['level']--;
return array_merge(islandora_get_breadcrumbs_recursive($parent, $repository, $context), array(
l($this_label, "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

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

536
includes/datastream.inc

@ -0,0 +1,536 @@
<?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) {
module_load_include('inc', 'islandora', 'includes/mimetype.utils');
// 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.
$extension = '.' . islandora_get_extension_for_mimetype($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'])) {
// XXX: Can't make assertions on byte ranging of redirect datastreams.
// @see https://jira.duraspace.org/browse/ISLANDORA-2084.
if (!$download && $datastream->controlGroup == 'R') {
drupal_goto($datastream->url);
}
// 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 ($modified_since === FALSE) {
return $return;
}
else {
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 ($unmodified_since === FALSE) {
return $return;
}
else {
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;
}
}
/**
* Display the edit datastream page.
*
* @param AbstractDatastream $datastream
* The datastream to edit.
*/
function islandora_edit_datastream(AbstractDatastream $datastream) {
module_load_include('inc', 'islandora', 'includes/utilities');
$edit_registry = islandora_build_datastream_edit_registry($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.
$entry = reset($edit_registry);
drupal_goto($entry['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,
);
}
/**
* 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.
*
* File locks are used to ensure the datastream is completely downloaded before
* attempting to serve up chunks from the file.
*
* @throws RepositoryException|Exception
* Exceptions may be thrown if the file was unable to be reliably acquired.
*
* @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) {
module_load_include('inc', 'islandora', 'includes/mimetype.utils');
module_load_include('inc', 'islandora', 'includes/utilities');
$extension = islandora_get_extension_for_mimetype($datastream->mimetype);
$file_uri = 'temporary://chunk_' . $datastream->parent->id . '_' . $datastream->id . '_' . $datastream->createdDate->getTimestamp() . '.' . $extension;
touch(drupal_realpath($file_uri));
$fp = fopen($file_uri, 'r+b');
if (flock($fp, LOCK_SH)) {
try {
fseek($fp, 0, SEEK_END);
if (ftell($fp) === 0 && $datastream->size > 0) {
// Just opened at beginning of file, if beginning == EOF, need to grab
// it.
if (!flock($fp, LOCK_EX | LOCK_NB)) {
// Hypothetically, two threads could have a "shared" lock with an
// unpopulated file, so to avoid deadlock on the "exclusive" lock,
// drop the "shared" lock before blocking to obtain the "exclusive"
// lock.
flock($fp, LOCK_UN);
}
if (flock($fp, LOCK_EX)) {
// Get exclusive lock, write file.
$file = islandora_temp_file_entry($file_uri, $datastream->mimeType);
if ($file->filesize == $datastream->size) {
// Populated in another thread while we were waiting for the
// "exclusive" lock; drop lock and return.
flock($fp, LOCK_UN);
fclose($fp);
return $file_uri;
}
try {
$datastream->getContent($file->uri);
clearstatcache($file->uri);
$file = file_save($file);
if ($file->filesize != $datastream->size) {
throw new RepositoryException(t('Size of file downloaded for chunking does not match: Got @apparent bytes when expecting @actual.', array(
'@apparent' => $file->filesize,
'@actual' => $datastream->size,
)));
}
}
catch (RepositoryException $e) {
file_delete($file);
throw $e;
}
}
else {
throw new Exception(t('Failed to acquire write lock when downloading @pid/@dsid for chunking.', array(
'@pid' => $datastream->parent->id,
'@dsid' => $datastream->id,
)));
}
}
flock($fp, LOCK_UN);
fclose($fp);
return $file_uri;
}
catch (Exception $e) {
flock($fp, LOCK_UN);
fclose($fp);
throw $e;
}
}
throw new Exception(t('Failed to acquire shared lock when chunking @pid/@dsid.', array(
'@pid' => $datastream->parent->id,
'@dsid' => $datastream->id,
)));
}

402
includes/datastream.version.inc

@ -0,0 +1,402 @@
<?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";
}
/**
* Process available dsids, mime and extensions for a given object.
*
* @param AbstractObject $object
* The FedoraObject to process available extensions
*
* @return array()
* An associative array, merged from calls to
* islandora_get_datastreams_requirements_from_content_models()
* and an objects dsid's.
*/
function islandora_get_object_extensions(AbstractObject $object) {
$extensions = islandora_get_datastreams_requirements_from_models($object->models);
foreach ($object as $datastream) {
// Could be a datastream not associated in a content model,
// such as user added.
if (!isset($extensions[$datastream->id])) {
// Add the extensions manually.
$extensions[$datastream->id] = array(
'id' => $datastream->id,
'optional' => TRUE,
'mime' => array($datastream->mimeType),
);
}
}
return $extensions;
}
/**
* The admin replace datastream form.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
* @param AbstractDatastream $datastream
* The datastream to be updated.
*
* @return array
* The drupal form definition.
*/
function islandora_datastream_version_replace_form($form, &$form_state, AbstractDatastream $datastream) {
module_load_include('inc', 'islandora', 'includes/content_model');
module_load_include('inc', 'islandora', 'includes/utilities');
module_load_include('inc', 'islandora', 'includes/mimetype.utils');
$object = islandora_object_load($datastream->parent->id);
$form_state['object_id'] = $object->id;
$form_state['dsid'] = $datastream->id;
$form_state['object'] = $object;
$extensions = islandora_get_extensions_for_datastream($object, $datastream->id);
if (empty($extensions)) {
// In case no extensions are returned, don't limit.
$valid_extensions = NULL;
}
else {
$valid_extensions = implode(' ', $extensions);
}
$upload_size = min((int) ini_get('post_max_size'), (int) ini_get('upload_max_filesize'));
return array(
'dsid_fieldset' => array(
'#type' => 'fieldset',
'#title' => t("Update Datastream"),
'#collapsible' => FALSE,
'#collapsed' => FALSE,
'dsid' => array(
'#type' => 'markup',
'#markup' => t("<div>DSID: <strong>@dsid</strong></div>", array('@dsid' => $datastream->id)),
),
'label' => array(
'#type' => 'markup',
'#markup' => t("<div>Label: <strong>@label</strong></div>", array('@label' => $datastream->label)),
),
'file' => array(
'#type' => 'managed_file',
'#required' => TRUE,
'#title' => t('Upload Document'),
'#size' => 64,
'#description' => t('Select a file to upload.<br/>Files must be less than <strong>@size MB.</strong>', array('@size' => $upload_size)),
'#upload_location' => file_default_scheme() . '://',
'#upload_validators' => array(
'file_validate_extensions' => array($valid_extensions),
// Assume its specified in MB.
'file_validate_size' => array($upload_size * 1024 * 1024),
),
),
'submit' => array(
'#type' => 'submit',
'#value' => t('Add Contents'),
),
),
);
}
/**
* Submit handler for the replace datastream form.
*
* Adds a new datastream version as latest.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*/
function islandora_datastream_version_replace_form_submit($form, &$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[$form_state['dsid']];
if ($ds->mimetype != $file->filemime) {
$ds->mimetype = $file->filemime;
}
$path = drupal_realpath($file->uri);
$ds->setContentFromFile($path);
file_delete($file);
}
catch (exception $e) {
drupal_set_message(t('An error occurred during datastream updates. See watchlog for more information.'), 'error');
watchdog('islandora',
'Failed to add new versionable datastream.<br/>code: @code<br/>message: @msg',
array(
'@code' => $e->getCode(),
'@msg' => $e->getMessage(),
),
WATCHDOG_ERROR
);
file_delete($file);
return;
}
drupal_set_message(t("Successfully Updated Datastream"));
}
/**
* 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;
}

145
includes/delete_datastream.form.inc

@ -0,0 +1,145 @@
<?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) {
// XXX: Stashed version of datastream is deprecated... Use object and
// datastream IDs from 'datastream_info' to acquire.
$form_state['datastream'] = $datastream;
$form_state['datastream_info'] = array(
'object_id' => $datastream->parent->id,
'datastream_id' => $datastream->id,
);
$object = $datastream->parent;
$dsid = $datastream->id;
$dsids = array_merge(array($dsid), islandora_datastream_to_purge($object, $dsid));
$dsids = array_unique($dsids);
$form['delete_derivatives'] = array(
'#title' => t('Delete Derivatives'),
'#type' => 'checkbox',
'#default_value' => 0,
'#description' => t('Derivatives can be regenerated at a later time.'),
);
$form['base_info'] = array(
'#type' => 'item',
'#title' => t('Datastream to be purged'),
'#markup' => $dsid,
'#states' => array(
'invisible' => array(
':input[name="delete_derivatives"]' => array('checked' => TRUE),
),
),
);
$form['derivative_info'] = array(
'#type' => 'item',
'#title' => t('Datastream(s) to be purged'),
'#description' => t('Including detectable derivatives.'),
'#markup' => implode(', ', $dsids),
'#states' => array(
'visible' => array(
':input[name="delete_derivatives"]' => array('checked' => TRUE),
),
),
);
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')
);
}
/**
* Return $dsids based on a given DSID and filter.
*/
function islandora_datastream_to_purge(AbstractObject $object, $dsid) {
module_load_include('inc', 'islandora', 'includes/utilities');
$hooks = islandora_invoke_hook_list(ISLANDORA_DERIVATIVE_CREATION_HOOK, $object->models, array($object));
$hook_filter = function ($hook_def) use ($dsid) {
return isset($hook_def['source_dsid']) && isset($hook_def['destination_dsid']) ?
($hook_def['source_dsid'] == $dsid && $hook_def['destination_dsid'] != $dsid) :
FALSE;
};
$hooks = array_filter($hooks, $hook_filter);
$dsid_map = function ($hook_definition) {
return $hook_definition['destination_dsid'];
};
$dsids = array();
$derived_dsids = array_map($dsid_map, $hooks);
while ($current = array_pop($derived_dsids)) {
$dsids[] = $current;
$current_derived = islandora_datastream_to_purge($object, $current);
$current_diff = array_diff($current_derived, $derived_dsids, $dsids);
$derived_dsids = array_merge($derived_dsids, $current_diff);
}
return $dsids;
}
/**
* Purge a given DSID's derivative datastreams on an object.
*/
function islandora_datastream_derivatives_purged(AbstractObject $object, $dsid) {
$dsids = islandora_datastream_to_purge($object, $dsid);
array_map(array($object, 'purgeDatastream'), $dsids);
}
/**
* 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) {
$object = islandora_object_load($form_state['datastream_info']['object_id']);
$datastream_id = $form_state['datastream_info']['datastream_id'];
$datastream = $object[$datastream_id];
$deleted = FALSE;
if ($form_state['values']['delete_derivatives']) {
islandora_datastream_derivatives_purged($object, $datastream_id);
}
try {
$deleted = islandora_delete_datastream($datastream);
}
catch (Exception $e) {
drupal_set_message(t('Error deleting %s datastream from object %o %e', array(
'%s' => $datastream_id,
'%o' => $object->label,
'%e' => $e->getMessage())), 'error');
}
if ($deleted) {
drupal_set_message(t('%d datastream sucessfully deleted from Islandora object %o', array(
'%d' => $datastream_id,
'%o' => $object->label)));
}
else {
drupal_set_message(t('Error deleting %s datastream from object %o', array(
'%s' => $datastream_id,
'%o' => $object->label)), 'error');
}
$form_state['redirect'] = "islandora/object/{$object->id}";
}

48
includes/delete_object.form.inc

@ -0,0 +1,48 @@
<?php
/**
* @file
* The admin/confirmation form to purge an object.
*/
/**
* The admin delete object form.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
* @param 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);
}

311
includes/derivatives.inc

@ -0,0 +1,311 @@
<?php
/**
* @file
* Defines functions used when constructing derivatives.
*/
// Relations.
define('ISLANDORA_DEFER_DERIVATIVES_FLAG', 'deferDerivatives');
/**
* Decides which derivative function to call and runs it.
*
* @param AbstractObject $object
* The object to run the derivative function for.
* @param string $dsid
* The DSID to run the derivative function for.
*/
function islandora_run_derivatives(AbstractObject $object, $dsid) {
$batch_array = batch_get();
if (empty($batch_array)) {
$logging_results = islandora_do_derivatives($object, array(
'source_dsid' => $dsid,
));
islandora_derivative_logging($logging_results);
}
else {
$operations = islandora_do_batch_derivatives(
$object,
array(
'source_dsid' => $dsid,
)
);
if ($operations) {
batch_set(
// Title won't show for batch in a batch.
array(
'init_message' => t('Preparing derivatives for @label', array('@label' => $object->label)),
'error_message' => t('An error occured creating derivatives.'),
'progress_message' => t(
'Creating derivatives for @label <br/>Time elapsed: @elapsed <br/>
Estimated time remaining @estimate.',
array('@label' => $object->label)
),
'file' => drupal_get_path('module', 'islandora') . '/includes/regenerate_derivatives.form.inc',
'operations' => $operations,
)
);
}
}
}
/**
* 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.
* - ds_modified_params: (Optional, typically internally used) The array of
* parameters originally sent to FedoraDatastream::modifyDatastream(). Used
* to refine the derivative list; typically should't be passed in manually.
*
* @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) {
$results = array();
$derivatives = islandora_get_derivative_list($object, $options);
foreach ($derivatives as $derivative) {
if (isset($derivative['file'])) {
require_once $derivative['file'];
}
foreach ($derivative['function'] as $function) {
if (function_exists($function)) {
$logging = call_user_func($function, $object, $options['force'], $derivative);
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) {
$operations = array();
$derivatives = islandora_get_derivative_list($object, $options);
foreach ($derivatives as $derivative) {
$file = FALSE;
if (isset($derivative['file'])) {
$file = $derivative['file'];
}
foreach ($derivative['function'] as $function) {
$operations[] = array(
'islandora_derivative_perform_batch_operation',
array(
$function,
$file,
$object->id,
$options['force'],
$derivative,
),
);
}
}
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;
}
/**
* Set the defer derivatives flag on an object.
*/
function islandora_set_defer_derivatives_flag(AbstractObject $object) {
$object->relationships->add(
ISLANDORA_RELS_EXT_URI,
ISLANDORA_DEFER_DERIVATIVES_FLAG,
'true',
RELS_TYPE_PLAIN_LITERAL
);
}
/**
* Get the defer derivatives flag on an object.
*/
function islandora_get_defer_derivatives_flag(AbstractObject $object) {
return $object->relationships->get(
ISLANDORA_RELS_EXT_URI,
ISLANDORA_DEFER_DERIVATIVES_FLAG,
'true',
RELS_TYPE_PLAIN_LITERAL
);
}
/**
* Remove the defer derivatives flag on an object.
*/
function islandora_remove_defer_derivatives_flag(AbstractObject $object) {
$object->relationships->remove(
ISLANDORA_RELS_EXT_URI,
ISLANDORA_DEFER_DERIVATIVES_FLAG,
'true',
RELS_TYPE_PLAIN_LITERAL
);
}
/**
* Get the list of derivatives.
*
* @param AbstractObject $object
* The object to find derivatives for.
* @param &array $options
* Options for derivatives, will be updated to default force to FALSE.
*/
function islandora_get_derivative_list(AbstractObject $object, &$options) {
module_load_include('inc', 'islandora', 'includes/utilities');
$ds_modified_params = isset($options['ds_modified_params']) ? $options['ds_modified_params'] : array();
$options += array(
'force' => FALSE,
);
$derivatives = islandora_invoke_hook_list(
ISLANDORA_DERIVATIVE_CREATION_HOOK,
$object->models,
array($object),
$ds_modified_params
);
foreach (islandora_build_hook_list(ISLANDORA_DERIVATIVE_CREATION_HOOK, $object->models) as $hook) {
drupal_alter($hook, $derivatives, $object, $ds_modified_params);
}
uasort($derivatives, 'drupal_sort_weight');
return islandora_filter_derivatives($derivatives, $options, $object);
}

170
includes/dublin_core.inc

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

1029
includes/ingest.form.inc

File diff suppressed because it is too large Load Diff

384
includes/manage_deleted_objects.inc

@ -0,0 +1,384 @@
<?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.
* @param string $serialized_chosen
* A serialized array of chosen content models.
*
* @return array
* The Drupal form definition.
*/
function islandora_deleted_objects_prep_form(array $form, array $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(array $form, array $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.
* @param string $serialized_chosen
* A serialized array of chosen content models.
*
* @return array
* The Drupal form definition.
*/
function islandora_deleted_objects_manage_form(array $form, array $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(array $form, array $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.
*
* @param array $content_models
* Get deleted object with one of these content models.
* @param int $limit
* Max to get at one time.
* @param int $offset
* Where to start for paging.
*
* @return array
* PIDS of deleted objects
*/
function islandora_get_deleted_objects(array $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;
$filter = _islandora_get_manage_deleted_query_filter();
$query = "PREFIX fm: <info:fedora/fedora-system:def/model#>
SELECT DISTINCT ?object ?label FROM <#ri>
WHERE {
{?subject fm:state fm:Deleted;
fm:hasModel ?object;
$filter
}
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(array $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}";
$filter = _islandora_get_manage_deleted_query_filter();
return "$prefix $select $where_clause $unions $optional $filter $suffix";
}
/**
* Reuse namespace restriction filters for basic collection.
*
* This reuses the hook implementation function to make a local
* namespace filter for managing deleted objects.
*
* @return string
* The Sparql filter statement.
*/
function _islandora_get_manage_deleted_query_filter() {
// Reusing the basic collection query filter.
$filter_modules = array(
'islandora_xacml_api',
'islandora',
);
$filters = array();
foreach ($filter_modules as $module) {
$filters = array_merge_recursive($filters, (array) module_invoke($module, 'islandora_basic_collection_get_query_filters', 'view'));
}
$filter_map = function ($filter) {
return "FILTER($filter)";
};
$filter = implode(' ', array_map($filter_map, $filters));
// Hook filters ?object we need to filter ?subject.
$filter = str_replace('?object', '?subject', $filter);
return $filter;
}

176
includes/metadata.inc

@ -0,0 +1,176 @@
<?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'])) {
module_load_include('inc', 'islandora', 'includes/utilities');
$hooks = islandora_build_hook_list(ISLANDORA_METADATA_OBJECT_ALTER, $object->models);
drupal_alter($hooks, $object);
$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'])) {
$hooks = islandora_build_hook_list(ISLANDORA_METADATA_OBJECT_DESCRIPTION_ALTER, $object->models);
drupal_alter($hooks, $object);
$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);
}

265
includes/mime_detect.inc

@ -0,0 +1,265 @@
<?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'.
*
*/
);
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() {
module_load_include('inc', 'islandora', 'includes/mimetype.utils');
$this->protectedMimeTypes = islandora_mime_mapping();
// 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));
}
}

26
includes/mime_type.autocomplete.inc

@ -0,0 +1,26 @@
<?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) {
require_once DRUPAL_ROOT . "/includes/file.mimetypes.inc";
$mime_types = file_mimetype_mapping();
$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);
}

278
includes/mimetype.utils.inc

@ -0,0 +1,278 @@
<?php
/**
* @file
* Mimetype specific utility functions.
*/
/**
* Retrieve the correct file extension for a give mimetype.
*
* @param string $mimetype
* The mimetype whose extension is required.
*
* @return string
* The extension mapped to the given mimetype. Defaults to 'bin'.
*/
function islandora_get_extension_for_mimetype($mimetype) {
// file.mimetypes.inc is a part of Drupal core, however is not
// automatically loaded. Manually require it.
require_once DRUPAL_ROOT . "/includes/file.mimetypes.inc";
$extension = 'bin';
$mimetype_mapping = file_mimetype_mapping();
$extension_index = array_search($mimetype, $mimetype_mapping['mimetypes']);
if ($extension_index !== FALSE) {
// Reversing such that any altered values take precedence over the default
// mappings.
$mime_array_flipped = array_reverse($mimetype_mapping['extensions']);
$extension = array_search($extension_index, $mime_array_flipped);
}
// We can only have one mapping in drupal for 'xml'.
if ($mimetype == "text/xml") {
return "xml";
}
return $extension;
}
/**
* Retrieve all file extensions for a give mimetype.
*
* @param string $mimetype
* The mimetype whose extensions are required.
*
* @return array
* All known legal extensions.
*/
function islandora_get_extensions_for_mimetype($mimetype) {
// file.mimetypes.inc is a part of Drupal core, however is not
// automatically loaded. Manually require it.
require_once DRUPAL_ROOT . "/includes/file.mimetypes.inc";
$mimetype_mapping = file_mimetype_mapping();
$index = array_search($mimetype, $mimetype_mapping['mimetypes']);
$extensions = array();
if ($index !== FALSE) {
$extensions = array_keys($mimetype_mapping['extensions'], $index);
}
// We can only have one mapping in drupal for 'xml'.
if ($mimetype == "text/xml") {
$extensions[] = 'xml';
}
return $extensions;
}
/**
* Extensions for the mimes accepted by a datastream.
*
* @param AbstractObject $object
* Object to check for extensions.
* @param string $dsid
* Datastream ID to check for extensions.
*
* @return string[]
* Extensions for the mimes accepted by the datastream ID on the object.
*/
function islandora_get_extensions_for_datastream(AbstractObject $object, $dsid) {
module_load_include('inc', 'islandora', 'includes/utilities');
$datastream_mime_map = islandora_get_datastreams_requirements_from_models($object->models);
$mimes = isset($datastream_mime_map[$dsid]) ? $datastream_mime_map[$dsid]['mime'] : array();
// If no restriction set via DS-COMPOSITE-MODEL return an empty array.
if (empty($mimes)) {
return array();
}
if (isset($object[$dsid])) {
$current_mime = $object[$dsid]->mimetype;
if (!in_array($current_mime, $mimes)) {
$mimes[] = $current_mime;
}
}
$extensions = array();
foreach ($mimes as $mime) {
$extensions = array_merge($extensions, islandora_get_extensions_for_mimetype($mime));
}
return array_unique($extensions);
}
/**
* Retrieve custom Islandora mime mappings.
*
* Our mime needs are rather extreme and we need to modify/extend Drupal's map.
*/
function islandora_mime_mapping() {
return array(
// 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/xsl',
'xslt' => 'text/xsl',
'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",
// Chemical:
// MDL Molfile.
"mol" => "chemical/x-mdl-molfile",
// XYZ format.
"xyz" => "chemical/x-xyz",
// PDB.
"pdb" => "chemical/x-pdb",
// ChemDraw CDX.
'cdx' => 'chemical/x-cdx',
// ChemDraw 3D.
"c3d" => "chemical/x-chem3d",
// ChemDraw file.
"chm" => "chemical/x-chemdraw",
// Crystallographic Information File.
"cif" => "chemical/x-cif",
// Chemical Markup Language.
"cml" => "chemical/x-cml",
// GAMESS Input.
"inp" => "chemical/x-gamess-input",
// GAMESS Output.
"gam" => "chemical/x-gamess-output",
// Gaussian Cube.
"cub" => "chemical/x-gaussian-cube",
// Gaussian 98/03 Cartesian Input.
"gau" => "chemical/x-gaussian-input",
// JCAMP Spectroscopic Data Exchange Format.
"jdx" => "chemical/x-jcamp-dx",
// OpenDX Grid.
"dx" => "chemical/x-jcamp-dx",
// MOPAC Cartesian.
"mop" => "chemical/x-mopac-input",
// 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",
"dat" => "application/octet-stream",
// others:
'bin' => 'application/octet-stream',
// Web Archives:
"warc" => "application/warc",
"json" => "application/json",
// JSON-LD
"jsonld" => "application/ld+json",
);
}

57
includes/object.entity_controller.inc

@ -0,0 +1,57 @@
<?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)) {
// TODO: Allow loading by specifying IDs in the condition.
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.
}
}

252
includes/object_properties.form.inc

@ -0,0 +1,252 @@
<?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) {
if (isset($form_state['islandora']['needs_confirmation'])) {
return islandora_object_properties_confirm_form($form_state);
}
$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_DERIVATIVE_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) {
if (isset($form_state['islandora']['needs_confirmation'])) {
$form_state['values'] = $form_state['islandora']['values'];
}
else {
// Confirm if user is about to lock themselves out of this object.
if (variable_get('islandora_deny_inactive_and_deleted', FALSE) && in_array($form_state['values']['object_state'], array('I', 'D'))) {
if ($form_state['object']->state == 'A') {
if (!user_access(ISLANDORA_ACCESS_INACTIVE_AND_DELETED_OBJECTS)) {
$form_state['islandora']['needs_confirmation'] = TRUE;
$form_state['islandora']['values'] = $form_state['values'];
$form_state['rebuild'] = TRUE;
return;
}
}
}
}
$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");
}
/**
* Confirmation form for object properties admin form.
*
* @param array $form_state
* The Drupal form state.
*/
function islandora_object_properties_confirm_form(array &$form_state) {
$desc = t('You do not have permission to view Inactive or Deleted objects, so you will no longer be able to view or manage this object. Are you sure?');
$path = "islandora/object/{$form_state['object']->id}/manage/properties";
return confirm_form(array(),
t('Are you sure you want to set the object state?'),
$path,
$desc,
t('Continue'),
t('Cancel'));
}

278
includes/orphaned_objects.inc

@ -0,0 +1,278 @@
<?php
/**
* @file
* A list of orphaned Islandora objects.
*/
/**
* Builds the Orphaned Islandora Objects management form.
*
* @param array $form
* An array representing a form within Drupal.
* @param array $form_state
* An array containing the Drupal form state.
*
* @return array
* An array containing the form to be rendered.
*/
function islandora_manage_orphaned_objects_form($form, $form_state) {
if (isset($form_state['show_confirm'])) {
$pids = $form_state['pids_to_delete'];
$form['confirm_message'] = array(
'#type' => 'item',
'#markup' => format_plural(count($form_state['pids_to_delete']),
'Are you sure you want to delete this object? This action cannot be reversed.',
'Are you sure you want to delete these @count objects? This action cannot be reversed.'),
);
if (count($pids) <= 10) {
$form['pids_to_delete'] = array(
'#type' => 'markup',
'#theme' => 'item_list',
'#list_type' => 'ol',
);
$options = array('attributes' => array('target' => '_blank'));
foreach ($pids as $pid) {
$form['pids_to_delete']['#items'][] = l($pid, "/islandora/object/{$pid}", $options);
}
}
$form['confirm_submit'] = array(
'#type' => 'submit',
'#value' => t('Confirm'),
'#weight' => 2,
'#submit' => array('islandora_manage_orphaned_objects_confirm_submit'),
);
$form['cancel_submit'] = array(
'#type' => 'submit',
'#value' => t('Cancel'),
'#weight' => 3,
);
}
else {
drupal_set_message(t('This page lists objects that have at least one parent, according to their RELS-EXT, that does not
exist in the Fedora repository. These orphans might exist due to a failed batch ingest, their parents being deleted,
or a variety of other reasons. Some of these orphans may exist intentionally.
Please be cautious when deleting, as this action is irreversible.'), 'warning');
$orphaned_objects = islandora_get_orphaned_objects();
$rows = array();
foreach ($orphaned_objects as $orphaned_object) {
$pid = $orphaned_object['object']['value'];
if (islandora_namespace_accessible($pid)) {
$rows[$pid] = array(l($orphaned_object['title']['value'] . " (" . $pid . ")", "islandora/object/$pid"));
}
}
ksort($rows);
$form['management_table'] = array(
'#type' => 'tableselect',
'#header' => array(t('Object')),
'#options' => $rows,
'#attributes' => array(),
'#empty' => t('No orphaned objects were found.'),
);
if (!empty($rows)) {
$form['submit_selected'] = array(
'#type' => 'submit',
'#name' => 'islandora-orphaned-objects-submit-selected',
'#validate' => array('islandora_delete_selected_orphaned_objects_validate'),
'#submit' => array('islandora_delete_orphaned_objects_submit'),
'#value' => t('Delete Selected'),
);
$form['submit_all'] = array(
'#type' => 'submit',
'#name' => 'islandora-orphaned-objects-submit-all',
'#submit' => array('islandora_delete_orphaned_objects_submit'),
'#value' => t('Delete All'),
);
}
}
return $form;
}
/**
* Validation for the Islandora Orphaned Objects management form.
*
* @param array $form
* An array representing a form within Drupal.
* @param array $form_state
* An array containing the Drupal form state.
*/
function islandora_delete_selected_orphaned_objects_validate($form, $form_state) {
$selected = array_filter($form_state['values']['management_table']);
if (empty($selected)) {
form_error($form['management_table'], t('At least one object must be selected to delete!'));
}
}
/**
* Submit handler for the delete buttons in the workflow management form.
*
* @param array $form
* An array representing a form within Drupal.
* @param array $form_state
* An array containing the Drupal form state.
*/
function islandora_delete_orphaned_objects_submit(&$form, &$form_state) {
if ($form_state['triggering_element']['#name'] == 'islandora-orphaned-objects-submit-selected') {
$selected = array_keys(array_filter($form_state['values']['management_table']));
}
else {
$selected = array_keys($form_state['values']['management_table']);
}
$form_state['pids_to_delete'] = $selected;
// Rebuild to show the confirm form.
$form_state['rebuild'] = TRUE;
$form_state['show_confirm'] = TRUE;
}
/**
* Submit handler for the workflow management confirm form.
*
* @param array $form
* An array representing a form within Drupal.
* @param array $form_state
* An array containing the Drupal form state.
*/
function islandora_manage_orphaned_objects_confirm_submit($form, &$form_state) {
$batch = islandora_delete_orphaned_objects_create_batch($form_state['pids_to_delete']);
batch_set($batch);
}
/**
* Query for orphaned objects.
*
* @return array
* An array containing the results of the orphaned objects queries.
*/
function islandora_get_orphaned_objects() {
$connection = islandora_get_tuque_connection();
// SPARQL: get orphaned objects, exclude any with a living parent.
$object_query = <<<EOQ
PREFIX islandora: <http://islandora.ca/ontology/relsext#>
SELECT DISTINCT ?object ?title
WHERE {
?object <fedora-model:hasModel> <info:fedora/fedora-system:FedoraObject-3.0> ;
?p ?otherobject .
?object <fedora-model:label> ?title;
OPTIONAL {
?otherobject <fedora-model:hasModel> ?model .
} .
FILTER (!bound(?model))
# Filter by "parent" relationships - isMemberOf, isMemberOfCollection, isPageOf.
FILTER (?p = <fedora-rels-ext:isMemberOfCollection> || ?p = <fedora-rels-ext:isMemberOf> || ?p = <islandora:isPageOf>)
# Exclude objects with live parents - isMemberOf, isMemberOfCollection, isPageOf.
OPTIONAL {
{?object <fedora-rels-ext:isMemberOfCollection> ?liveparent }
UNION {?object <fedora-rels-ext:isMemberOf> ?liveparent }
UNION { ?object <islandora:isPageOf> ?liveparent } .
?liveparent <fedora-model:hasModel> <info:fedora/fedora-system:FedoraObject-3.0> .
}
!optionals
!filters
FILTER (!bound(?liveparent))
} ORDER BY ?object
EOQ;
$optionals = (array) module_invoke('islandora_xacml_api', 'islandora_basic_collection_get_query_optionals', 'view');
$filter_modules = array(
'islandora_xacml_api',
'islandora',
);
$filters = array();
foreach ($filter_modules as $module) {
$filters = array_merge_recursive($filters, (array) module_invoke($module, 'islandora_basic_collection_get_query_filters', 'view'));
}
$filter_map = function ($filter) {
return "FILTER($filter)";
};
// Use separate queries for different object types.
$sparql_query_objects = format_string($object_query, array(
'!optionals' => !empty($optionals) ? ('OPTIONAL {{' . implode('} UNION {', $optionals) . '}}') : '',
'!filters' => !empty($filters) ? implode(' ', array_map($filter_map, $filters)) : '',
));
$results = $connection->repository->ri->sparqlQuery($sparql_query_objects);
return $results;
}
/**
* Constructs the batch that will go out and delete objects.
*
* @param array $pids
* The array of pids to be deleted.
*
* @return array
* An array detailing the batch that is about to be run.
*/
function islandora_delete_orphaned_objects_create_batch($pids) {
// Set up a batch operation.
$batch = array(
'operations' => array(
array('islandora_delete_orphaned_objects_batch_operation', array($pids)),
),
'title' => t('Deleting the selected objects...'),
'init_message' => t('Preparing to delete objects.'),
'progress_message' => t('Time elapsed: @elapsed <br/>Estimated time remaining @estimate.'),
'error_message' => t('An error has occurred.'),
'finished' => 'islandora_delete_orphaned_objects_batch_finished',
'file' => drupal_get_path('module', 'islandora') . '/includes/orphaned_objects.inc',
);
return $batch;
}
/**
* Constructs and performs the deleting batch operation.
*
* @param array $pids
* An array of pids to be deleted.
* @param array $context
* The context of the Drupal batch.
*/
function islandora_delete_orphaned_objects_batch_operation($pids, &$context) {
if (empty($context['sandbox'])) {
$context['sandbox'] = array();
$context['sandbox']['progress'] = 0;
$context['sandbox']['pids'] = $pids;
$context['sandbox']['total'] = count($pids);
$context['results']['success'] = array();
}
if (!empty($context['sandbox']['pids'])) {
$target_pid = array_pop($context['sandbox']['pids']);
$target_object = islandora_object_load($target_pid);
$context['message'] = t('Deleting @label (@pid) (@current of @total)...', array(
'@label' => $target_object->label,
'@pid' => $target_pid,
'@current' => $context['sandbox']['progress'],
'@total' => $context['sandbox']['total'],
));
islandora_delete_object($target_object);
$object_check = islandora_object_load($target_pid);
if ($object_check) {
drupal_set_message(t('Could not delete %pid. You may not have permission to manage this object.',
array(
'%pid' => $target_pid,
)), 'error');
}
else {
$context['results']['success'][] = $target_pid;
}
$context['sandbox']['progress']++;
}
$context['finished'] = ($context['sandbox']['total'] == 0) ? 1 : ($context['sandbox']['progress'] / $context['sandbox']['total']);
}
/**
* Finished function for the orphaned objects delete batch.
*
* @param bool $success
* Whether the batch was successful or not.
* @param array $results
* An array containing the results of the batch operations.
* @param array $operations
* The operations array that was used in the batch.
*/
function islandora_delete_orphaned_objects_batch_finished($success, $results, $operations) {
if ($success) {
$message = format_plural(count($results['success']), 'One object deleted.', '@count objects deleted.');
}
else {
$message = t('Finished with an error.');
}
drupal_set_message($message);
}

182
includes/regenerate_derivatives.form.inc

@ -0,0 +1,182 @@
<?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');
islandora_remove_defer_derivatives_flag($object);
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');
islandora_remove_defer_derivatives_flag($datastream->parent);
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 $hook
* The derivative definition.
* @param array $context
* The context of the current batch operation.
*/
function islandora_derivative_perform_batch_operation($function, $file, $pid, $force, $hook, &$context) {
if ($file) {
require_once $file;
}
if (function_exists($function)) {
$logging = call_user_func($function, islandora_object_load($pid), $force, $hook);
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']);
}
}

839
includes/solution_packs.inc

@ -0,0 +1,839 @@
<?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 convenient 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_pack_config');
$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;
}
$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;
}
$required_objects = islandora_solution_packs_get_required_objects($module);
$objects = $required_objects['objects'];
$filter = function ($o) {
return islandora_object_load($o->id);
};
$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), LIBXML_NOWARNING);
$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), LIBXML_NOWARNING);
$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

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

629
includes/tuque_wrapper.inc

@ -0,0 +1,629 @@
<?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 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";
/**
* 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 parameters 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 parameters 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;
}
}
/**
* Constructs a Fedora Object.
*
* @see FedoraRepository::constructObject
*/
public function constructObject($id = NULL, $create_uuid = NULL) {
// Enforces UUID when set, but allows to override if called
// with $create_uuid set to bool.
return parent::constructObject($id, static::useUUIDs($create_uuid));
}
/**
* Get the next PID(s) from Repo.
*
* @see FedoraRepository::getNextIdentifier()
*/
public function getNextIdentifier($namespace = NULL, $create_uuid = NULL, $count = 1) {
// Enforces UUID when set, but allows to override if called
// with $create_uuid set to bool.
return parent::getNextIdentifier($namespace, static::useUUIDs($create_uuid), $count);
}
/**
* Helper for three-valued logic with UUIDs.
*
* @param bool|NULL $to_create
* The variable to test.
*
* @return bool
* If $to_create is NULL, the value of the
* 'islandora_basic_collection_generate_uuid' Drupal variable; otherwise,
* the value of $to_create itself.
*/
protected static function useUUIDs($to_create) {
return is_null($to_create) ?
variable_get('islandora_basic_collection_generate_uuid', FALSE) :
$to_create;
}
}
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';
/**
* Magical magic, to allow recursive modifications.
*
* So... Magic functions in PHP are not re-entrant... Meaning that if you
* have something which tries to call __set on an object anywhere later in
* the callstack after it has already been called, it will not call the
* magic method again; instead, it will set the property on the object
* proper. Here, we detect the property being set on the object proper, and
* restore the magic functionality as long as it keeps getting set...
*
* Not necessary to try to account for this in Tuque proper, as Tuque itself
* does not have a mechanism to trigger modifications resulting from other
* modifications.
*
* @param string $name
* The name of the property being set.
* @param mixed $value
* The value to which the property should be set.
*/
public function __set($name, $value) {
parent::__set($name, $value);
// Recursion only matters for magic properties... "Plain" properties cannot
// call other code in order to start recursing, and in fact we would get
// stuck looping with a "plain" property.
if ($this->propertyIsMagical($name)) {
// XXX: Due to the structure of the code, we cannot use property_exists()
// (because many of the properties are declared in the class, and the
// magic triggers due them being NULLed), nor can we use isset() (because
// it is implemented as another magic function...).
$vars = get_object_vars($this);
while (isset($vars[$name])) {
$new_value = $this->$name;
unset($this->$name);
parent::__set($name, $new_value);
$vars = get_object_vars($this);
}
}
}
/**
* 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) {
if ($e instanceof DatastreamExistsException && variable_get('islandora_deprecation_return_false_when_datastream_exists', TRUE)) {
$message = format_string('The datastream @dsid already exists on the object: @pid. As of 7.x-1.10 the function signature for ingestDatastream will be changed from returning FALSE on failure to throwing an exception.', array(
'@dsid' => $datastream->id,
'@pid' => $object->id,
));
trigger_error(filter_xss($message), E_USER_DEPRECATED);
return FALSE;
}
watchdog('islandora', 'Failed to ingest datastream @dsid on 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;
}
}
/**
* Inherits.
*
* Calls parent and invokes object modified and deleted(/purged) hooks.
*
* @see FedoraObject::modifyObject()
*/
protected function modifyObject($params) {
try {
parent::modifyObject($params);
islandora_invoke_object_hooks(ISLANDORA_OBJECT_MODIFIED_HOOK, $this->models, $this);
if ($this->state == 'D') {
islandora_invoke_object_hooks(ISLANDORA_OBJECT_PURGED_HOOK, $this->models, $this->id);
}
}
catch (Exception $e) {
watchdog('islandora', 'Failed to modify object: @pid</br>code: @code<br/>message: @msg', array(
'@pid' => $this->id,
'@code' => $e->getCode(),
'@msg' => $e->getMessage()), WATCHDOG_ERROR);
throw $e;
}
}
/**
* Purge a datastream.
*
* Invokes datastream altered/purged hooks and calls the API-M method.
*
* @see FedoraObject::purgeObject()
*/
public function purgeDatastream($id) {
$this->populateDatastreams();
if (!array_key_exists($id, $this->datastreams)) {
return FALSE;
}
$context = array(
'action' => 'purge',
'purge' => TRUE,
'delete' => FALSE,
'block' => FALSE,
);
try {
islandora_alter_datastream($this, $this[$id], $context);
$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':
$this[$id]->state = 'D';
return array();
default:
$to_return = parent::purgeDatastream($id);
islandora_invoke_datastream_hooks(ISLANDORA_DATASTREAM_PURGED_HOOK, $this->models, $id, $this, $id);
return $to_return;
}
}
catch (Exception $e) {
watchdog('islandora', 'Failed to purge datastream @dsid from @pid</br>code: @code<br/>message: @msg', array(
'@pid' => $this->id,
'@dsid' => $id,
'@code' => $e->getCode(),
'@msg' => $e->getMessage()), WATCHDOG_ERROR);
throw $e;
}
}
}
class IslandoraRepositoryConnection extends RepositoryConnection {
/**
* Constructor.
*
* Invokes parent, but additionally invokes an alter to allow modules to
* effect the configuration of the connection.
*/
public function __construct($url = NULL, $username = NULL, $password = NULL) {
if ($url === NULL) {
$url = static::FEDORA_URL;
}
parent::__construct($url, $username, $password);
drupal_alter('islandora_repository_connection_construction', $this);
}
}
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'];
// Anything may be altered during the alter_datastream hook invocation so
// we need to update our time to the change we know about.
if (isset($params['lastModifiedDate']) && $params['lastModifiedDate'] < (string) $object->lastModifiedDate) {
$params['lastModifiedDate'] = (string) $object->lastModifiedDate;
}
if ($context['block']) {
throw new Exception('Modify Datastream was blocked.');
}
return $this->callParentWithLocking('modifyDatastream', $pid, $pid, $dsid, $params);
}
/**
* 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'];
if ($context['block']) {
throw new Exception('Modify Object was blocked.');
}
return $this->callParentWithLocking('modifyObject', $pid, $pid, $params);
}
/**
* 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 = $this->callParentWithLocking('purgeObject', $pid, $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;
}
}
/**
* Wraps purgeDatastream for semaphore locking.
*
* @see FedoraApiM::purgeDatastream
*/
public function purgeDatastream($pid, $dsid, $params = array()) {
return $this->callParentWithLocking('purgeDatastream', $pid, $pid, $dsid, $params);
}
/**
* Wraps ingest for semaphore locking.
*
* @see FedoraApiM::ingest
*/
public function ingest($params = array()) {
if (isset($params['pid'])) {
return $this->callParentWithLocking('ingest', $params['pid'], $params);
}
else {
return parent::ingest($params);
}
}
/**
* Wraps addDatastream for semaphore locking.
*
* @see FedoraApiM::addDatastream
*/
public function addDatastream($pid, $dsid, $type, $file, $params) {
return $this->callParentWithLocking('addDatastream', $pid, $pid, $dsid, $type, $file, $params);
}
/**
* Wraps addRelationship for semaphore locking.
*
* @see FedoraApiM::addRelationship
*/
public function addRelationship($pid, $relationship, $is_literal, $datatype = NULL) {
return $this->callParentWithLocking('addRelationship', $pid, $pid, $relationship, $is_literal, $datatype);
}
/**
* Call a parent function while using semaphores as configured.
*
* All extra arguments are passed along to the callback.
*
* @param callable $callback
* The method we are wrapping.
* @param string $pid
* The PID to create a semaphore for.
*/
protected function callParentWithLocking($callback, $pid) {
$args = array_slice(func_get_args(), 2);
$locked = FALSE;
if (variable_get('islandora_use_object_semaphores', FALSE)) {
$lock_period = variable_get('islandora_semaphore_period', 600);
while (!lock_acquire($pid, $lock_period)) {
// Wait for the lock to be free. In the worst case forever.
while (lock_wait($pid)) {
}
}
$locked = TRUE;
}
if ($locked) {
try {
$to_return = call_user_func_array(array($this, "parent::$callback"), $args);
}
catch (Exception $e) {
// Release the lock in event of exception.
lock_release($pid);
throw $e;
}
lock_release($pid);
return $to_return;
}
else {
return call_user_func_array(array($this, "parent::$callback"), $args);
}
}
}
class IslandoraSimpleCache extends SimpleCache {}
class IslandoraNewFedoraDatastream extends NewFedoraDatastream {
protected $fedoraRelsIntClass = 'IslandoraFedoraRelsInt';
protected $fedoraDatastreamVersionClass = 'IslandoraFedoraDatastreamVersion';
}
class IslandoraFedoraDatastream extends FedoraDatastream {
protected $fedoraRelsIntClass = 'IslandoraFedoraRelsInt';
protected $fedoraDatastreamVersionClass = 'IslandoraFedoraDatastreamVersion';
/**
* Magical magic, to allow recursive modifications.
*
* So... Magic functions in PHP are not re-entrant... Meaning that if you
* have something which tries to call __set on an object anywhere later in
* the callstack after it has already been called, it will not call the
* magic method again; instead, it will set the property on the object
* proper. Here, we detect the property being set on the object proper, and
* restore the magic functionality as long as it keeps getting set...
*
* Not necessary to try to account for this in Tuque proper, as Tuque itself
* does not have a mechanism to trigger modifications resulting from other
* modifications.
*
* @param string $name
* The name of the property being set.
* @param mixed $value
* The value to which the property should be set.
*/
public function __set($name, $value) {
parent::__set($name, $value);
// Recursion only matters for magic properties... "Plain" properties cannot
// call other code in order to start recursing, and in fact we would get
// stuck looping with a "plain" property.
if ($this->propertyIsMagical($name)) {
// XXX: Due to the structure of the code, we cannot use property_exists()
// (because many of the properties are declared in the class, and the
// magic triggers due them being NULLed), nor can we use isset() (because
// it is implemented as another magic function...).
$vars = get_object_vars($this);
while (isset($vars[$name])) {
$new_value = $this->$name;
unset($this->$name);
parent::__set($name, $new_value);
$vars = get_object_vars($this);
}
}
}
/**
* Inherits.
*
* Calls parent and invokes modified and purged hooks.
*
* @see FedoraDatastream::modifyDatastream()
*/
protected function modifyDatastream(array $args) {
try {
parent::modifyDatastream($args);
islandora_invoke_datastream_hooks(ISLANDORA_DATASTREAM_MODIFIED_HOOK, $this->parent->models, $this->id, $this->parent, $this, $args);
if ($this->state == 'D') {
islandora_invoke_datastream_hooks(ISLANDORA_DATASTREAM_PURGED_HOOK, $this->parent->models, $this->id, $this->parent, $this->id);
}
}
catch (Exception $e) {
watchdog('islandora', 'Failed to modify datastream @dsid from @pid</br>code: @code<br/>message: @msg', array(
'@pid' => $this->parent->id,
'@dsid' => $this->id,
'@code' => $e->getCode(),
'@msg' => $e->getMessage()), WATCHDOG_ERROR);
throw $e;
}
}
}
class IslandoraFedoraDatastreamVersion extends FedoraDatastreamVersion {
protected $fedoraRelsIntClass = 'IslandoraFedoraRelsInt';
protected $fedoraDatastreamVersionClass = 'IslandoraFedoraDatastreamVersion';
}
class IslandoraFedoraRelsExt extends FedoraRelsExt {}
class IslandoraFedoraRelsInt extends FedoraRelsInt {}

968
includes/utilities.inc

@ -0,0 +1,968 @@
<?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) . ' KiB';
}
elseif (($bytes >= $megabyte) && ($bytes < $gigabyte)) {
return round($bytes / $megabyte, $precision) . ' MiB';
}
elseif (($bytes >= $gigabyte) && ($bytes < $terabyte)) {
return round($bytes / $gigabyte, $precision) . ' GiB';
}
elseif ($bytes >= $terabyte) {
return round($bytes / $terabyte, $precision) . ' TiB';
}
else {
return $bytes . ' B';
}
}
/**
* Add a file as managed if is not already.
*
* @param string $file_uri
* The given file URI location.
*
* @return object
* The file, as returned from file_save().
*/
function islandora_temp_file_entry($file_uri, $mime = NULL) {
$query = new EntityFieldQuery();
$result = $query
->entityCondition('entity_type', 'file')
->propertyCondition('uri', $file_uri)
->execute();
if (isset($result['file'])) {
$fid = current($result['file'])->fid;
$file = file_load($fid);
}
else {
$file = new stdClass();
$file->uri = $file_uri;
$file->filename = drupal_basename($file_uri);
if (isset($mime)) {
$file->filemime = $mime;
}
else {
$file->filemime = file_get_mimetype($file_uri);
}
}
$file->status = 0;
return file_save($file);
}
/**
* Creates a label for control group symbols.
*/
function islandora_control_group_to_human_readable($control_group) {
switch ($control_group) {
case 'M':
return '<strong>M</strong>anaged';
case 'X':
return 'Inline <strong>X</strong>ML';
case 'R':
return '<strong>R</strong>edirect';
case 'E':
return '<strong>E</strong>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 $refined_hook) {
array_unshift($args, $refined_hook);
$result = call_user_func_array('module_invoke_all', $args);
$return = array_merge_recursive($return, $result);
array_shift($args);
}
if (module_exists('rules')) {
$event_info = rules_get_event_info($hook);
if (isset($event_info['module'])) {
$parameters = $event_info['variables'];
$rule_args = array_slice($args, 0, count($parameters));
array_unshift($rule_args, $hook);
$result = call_user_func_array('rules_invoke_event', $rule_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 $name_source
* Either a pid or 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($name_source = NULL, $label = NULL, $datastreams = array(), $content_models = array(), $relationships = array()) {
global $user;
$tuque = islandora_get_tuque_connection();
$object = isset($name_source) ? $tuque->repository->constructObject($name_source) : 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);
}
/**
* 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;
}
/**
* Build the edit registry for a given datastream.
*
* @param AbstractDatastream $datastream
* The datastream being edited.
*
* @return array
* The built edit registry array.
*/
function islandora_build_datastream_edit_registry(AbstractDatastream $datastream) {
$edit_registry = module_invoke_all(ISLANDORA_EDIT_DATASTREAM_REGISTRY_HOOK, $datastream->parent, $datastream);
$context = array(
'object' => $datastream->parent,
'datastream' => $datastream,
'original_edit_registry' => $edit_registry,
);
drupal_alter(ISLANDORA_EDIT_DATASTREAM_REGISTRY_HOOK, $edit_registry, $context);
return $edit_registry;
}

947
islandora.api.php

@ -0,0 +1,947 @@
<?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 represent 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 represent 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 modified.
*
* @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 modified.
*
* @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 modified.
* @param array $params
* The parameters from FedoraDatastream::modifyDatastream() used to modify the
* datastream.
*/
function hook_islandora_datastream_modified(AbstractObject $object, AbstractDatastream $datastream, array $params) {
// Sample of sanitizing a label.
$datastream->label = trim($datastream->label);
// Sample of using modifyDatastream parameters.
if (isset($params['mimetype'])) {
$datastream->label .= " ({$params['mimetype']})";
}
}
/**
* Notify modules that the given datastream was modified.
*
* @see hook_islandora_datastream_modified()
*/
function hook_cmodel_pid_dsid_islandora_datastream_modified(AbstractObject $object, AbstractDatastream $datastream, array $params) {
}
/**
* 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_dsid_islandora_datastream_purged(AbstractObject $object, $dsid) {
}
/**
* Register a datastream edit route/form.
*
* @param AbstractObject $object
* The object to check.
* @param string $dsid
* A string indicating the datastream for which to get the registry.
*
* @return array
* An array of associative arrays, each mapping:
* - name: A string containg a human-readable name for the entry.
* - url: A string containing the URL to which to the user will be routed.
*/
function hook_islandora_edit_datastream_registry($object, $dsid) {
$routes = array();
$routes[] = array(
'name' => t('My Awesome Edit Route'),
'url' => "go/edit/here/{$object->id}/{$dsid}",
);
return $routes;
}
/**
* 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.
* "Callback" type specific parameters:
* - do_function: A required associative 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 optional associative 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.
*
* This hook fires when an object/datastream is ingested or a datastream is
* modified. It may also be called to discover the datastream derivative
* hierarchy.
*
* @param AbstractObject $object
* Optional object to which derivatives will be added
* @param array $ds_modified_params
* An array that will contain the properties changed on the datastream if
* derivatives were triggered from a datastream_modified hook, as well as a
* 'dsid' key naming the datastream that was modified. Can be populated
* manually, but likely empty otherwise.
*
* @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. Does not impact function
* ordering.
* - destination_dsid: (Optional) String of the datastream id that is being
* created. To be used in the UI. Does not impact function ordering.
* - 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, $hook)
* 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) A substitution array as acceptable by 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 = NULL, $ds_modified_params = array()) {
$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() {
}
/**
* Allows for the altering of defined derivative functions.
*/
function hook_islandora_derivative_alter(&$derivatives, AbstractObject $object = NULL, $ds_modified_params = array()) {
foreach ($derivatives as $key => $derivative) {
if ($derivative['destination_dsid'] == 'TN') {
unset($derivatives[$key]);
}
}
// Example of altering out derivative generation if only a specified set of
// datastream parameters have been modified.
$mask = array(
'label' => NULL,
'dateLastModified' => NULL,
'dsid' => NULL,
);
$param_diff = array_diff_key($ds_modified_params, $mask);
if (empty($param_diff)) {
$derivatives = array();
}
}
/**
* Content model specific version of hook_islandora_derivative_alter().
*
* @see hook_islandora_derivative_alter()
*/
function hook_cmodel_pid_islandora_derivative_alter() {
}
/**
* 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',
),
);
}
/**
* Allows modifications to the object whose metadata is being rendered.
*
* @param AbstractObject $object
* An AbstractObject representing an object within Fedora.
*/
function hook_islandora_metadata_object_alter(AbstractObject &$object) {
$this_other_object = islandora_object_load('awild:indirectionappears');
$object = $this_other_object;
}
/**
* Allows modifications to the object whose metadata is being rendered.
*
* @param AbstractObject $object
* An AbstractObject representing an object within Fedora.
*/
function hook_islandora_metadata_object_description_alter(AbstractObject &$object) {
$this_other_object = islandora_object_load('awild:indirectionappears');
$object = $this_other_object;
}
/**
* Defines predicates to be searched for when constructing breadcrumbs.
*
* @return array
* An array containing strings of predicates to be ORed together to be
* matched on in SPARQL.
*/
function hook_islandora_get_breadcrumb_query_predicates() {
return array(
'somepredicate',
'someotherpredicate',
);
}
/**
* Use alter hook to modify registry paths before the paths are rendered.
*
* @param array $edit_registry
* The array of registry paths.
* @param array $context
* An associative array containing:
* - object: The object that owns the datastream being edited.
* - datastream: The datastream being edited.
* - original_edit_registry: The original edit_registry prior to any
* modifications.
*/
function hook_islandora_edit_datastream_registry_alter(&$edit_registry, $context) {
// Example: Remove xml form builder edit registry.
if (isset($edit_registry['xml_form_builder_edit_form_registry'])) {
unset($edit_registry['xml_form_builder_edit_form_registry']);
}
// Add custom form to replace the removed form builder edit_form.
$edit_registry['somemodule_custom_form'] = array(
'name' => t('Somemodule Custom Form'),
'url' => "islandora/custom_form/{$context['object']->id}/{$context['datastream']->id}",
);
}
/**
* Permit configuration of connection parameters.
*
* @param RepositoryConnection $instance
* The connection being constructed. See the relevant Tuque ancestor classes
* for the particulars.
*
* @see https://github.com/Islandora/tuque/blob/1.x/HttpConnection.php
*/
function hook_islandora_repository_connection_construction_alter(RepositoryConnection $instance) {
$instance->userAgent = "Tuque/cURL";
}
/**
* Allow a overridable backend for generating breadcrumbs.
*
* Stolen shamelessly from @adam-vessey.
*
* @return array
* Should return an associative array mapping unique (module-prefixed,
* preferably) keys to associative arrays containing:
* - title: A human-readable title for the backend.
* - callable: A PHP callable to call for this backend, implementing
* callback_islandora_basic_collection_query_backends().
* - file: An optional file to load before attempting to call the callable.
*/
function hook_islandora_breadcrumbs_backends() {
return array(
'awesome_backend' => array(
'title' => t('Awesome Backend'),
'callable' => 'callback_islandora_breadcrumbs_backends',
),
);
}
/**
* Generate an array of links for breadcrumbs leading to $object, root first.
*
* Stolen shamelessly from @adam-vessey.
*
* @param AbstractObject $object
* The object to generate breadcrumbs for.
*
* @return array
* Array of links from root to the parent of $object.
*/
function callback_islandora_breadcrumbs_backends(AbstractObject $object) {
// Do something to get an array of breadcrumb links for $object, root first.
return array($root_link, $collection_link, $object_link);
}

201
islandora.drush.inc

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

30
islandora.info

@ -0,0 +1,30 @@
name = Islandora
description = "View and manage Fedora objects"
package = Islandora
dependencies[] = image
dependencies[] = file
version = 7.x-1.11
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/includes/datastream_validators.inc
files[] = tests/includes/islandora_web_test_case.inc
files[] = tests/includes/islandora_unit_test_case.inc
files[] = tests/includes/utilities.inc
files[] = tests/includes/test_utility_abstraction.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
files[] = tests/datastream_validator_tests.test
php = 5.3

33
islandora.info.yml

@ -1,33 +0,0 @@
# 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

307
islandora.install

@ -2,227 +2,134 @@
/**
* @file
* Install/update hook implementations.
* This file contains all install related hooks.
*/
use Drupal\Core\Extension\ExtensionNameLengthException;
use Drupal\Core\Extension\MissingDependencyException;
use Drupal\Core\Utility\UpdateException;
/**
* Adds common namespaces to jsonld.settings.
*/
function islandora_install() {
update_jsonld_included_namespaces();
}
/**
* Delete the 'delete_media' action we used to provide, if it exists.
*
* Use the core 'media_delete_action' instead.
* Implements hook_requirements().
*/
function islandora_update_8001(&$sandbox) {
$action = \Drupal::service('entity_type.manager')->getStorage('action')->load('delete_media');
if ($action) {
$action->delete();
function islandora_requirements($phase) {
$requirements = array();
// 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;
}
}
/**
* Replaces 'entity_bundle' conditions with 'islandora_entity_bundle'.
*
* This prevents plugin naming collisions between islandora and ctools.
*/
function islandora_update_8002(&$sandbox) {
// 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();
return $requirements;
}
/**
* Deletes the islandora_version_count table.
* Implements hook_install().
*
* We never implemented the functionality.
* @see islandora_islandora_required_objects()
*/
function islandora_update_8003(&$sandbox) {
\Drupal::service('database')
->schema()
->dropTable('islandora_version_count');
}
/**
* Renames migration source keys -> ids.
*/
function islandora_update_8004() {
$config_factory = \Drupal::configFactory();
$config = $config_factory->getEditable('migrate_plus.migration.islandora__tags');
if ($config) {
if (!$config->get('source.ids')) {
$config->set('source.ids', $config->get('source.keys'));
$config->clear('source.keys');
$config->save(TRUE);
}
}
}
/**
* Makes migrate_tags an array.
*/
function islandora_update_8005() {
$config_factory = \Drupal::configFactory();
$config_factory->getEditable('migrate_plus.migration.islandora__tags')->delete();
$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();
function islandora_install() {
module_load_include('inc', 'islandora', 'includes/solution_packs');
islandora_install_solution_pack('islandora');
}
/**
* Used by install and update_8006 to add namespaces to jsonld.settings.yml.
* Implements hook_uninstall().
*
* @see islandora_islandora_required_objects()
*/
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.");
}
function islandora_uninstall() {
module_load_include('inc', 'islandora', 'includes/solution_packs');
islandora_install_solution_pack('islandora', 'uninstall');
// Add new variables to clean up.
$variables = array(
'islandora_ds_replace_exclude_enforced',
'islandora_defer_derivatives_on_ingest',
'islandora_base_url',
'islandora_repository_pid',
'islandora_use_datastream_cache_headers',
'islandora_show_print_option',
'islandora_render_drupal_breadcrumbs',
'islandora_namespace_restriction_enforced',
'islandora_pids_allowed',
'islandora_risearch_use_itql_when_necessary',
'islandora_use_object_semaphores',
'islandora_semaphore_period',
'islandora_require_obj_upload',
'islandora_breadcrumbs_backends',
'islandora_render_context_ingeststep',
'islandora_deny_inactive_and_deleted',
);
array_walk($variables, 'variable_del');
}
/**
* Ensure that ctools is enabled.
* Implements hook_schema().
*/
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.');
function islandora_schema() {
$schema['islandora_authtokens'] = array(
'description' => 'The hub for all islandora authentication tokens',
'fields' => array(
'id' => array(
'description' => 'key',
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
),
'token' => array(
'description' => 'a unique identifier for this token',
'type' => 'varchar',
'length' => 64,
),
'remaining_uses' => array(
'description' => 'How many uses until this should be removed',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
),
'uid' => array(
'description' => 'the user id that requested this token',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
),
'time' => array(
'description' => 'when this token was created',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
),
'pid' => array(
'description' => 'the pid of the object this token unlocks',
'type' => 'varchar',
'length' => 128,
'not null' => TRUE,
),
'dsid' => array(
'description' => 'the datasteram id of the object this token unlocks',
'type' => 'varchar',
'length' => 32,
'not null' => TRUE,
),
),
'unique keys' => array(
'id' => array('id'),
),
'primary key' => array('id'),
);
return $schema;
}
/**
* Set config to no redirect after media save.
* Implements hook_update_N().
*
* Add the required table for handling authentication tokens.
* This is the first instance that has this table.
*/
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.');
}
function islandora_update_7001(&$sandbox) {
drupal_install_schema('islandora');
$t = get_t();
return $t("Islandora database updates complete");
}

5
islandora.libraries.yml

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

29
islandora.links.action.yml

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

@ -1,20 +0,0 @@
# 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

2585
islandora.module

File diff suppressed because it is too large Load Diff

12
islandora.permissions.yml

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

@ -1,16 +0,0 @@
<?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

@ -1,111 +0,0 @@
# 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'

580
islandora.rules.inc

@ -0,0 +1,580 @@
<?php
/**
* @file
* Does rule type stuff,
*/
/**
* Implements hook_rules_event_info().
*/
function islandora_rules_event_info() {
return array(
'islandora_object_ingested' => array(
'group' => t('Islandora'),
'label' => t('Object ingested'),
'variables' => array(
'object' => array(
'type' => 'islandora_object',
'label' => t('The ingested object'),
'description' => t('A Tuque object for the ingested Fedora object, as an entity.'),
),
),
),
'islandora_datastream_ingested' => array(
'group' => t('Islandora'),
'label' => t('Datastream ingested'),
'variables' => array(
'object' => array(
'type' => 'islandora_object',
'label' => t('The ingested object'),
'description' => t('A Tuque object for the Fedora object on which the datastream exists, as an entity.'),
),
'datastream' => array(
'type' => 'islandora_datastream',
'label' => t('Datastream ID'),
'description' => t('The ID of the ingested datastream.'),
),
),
),
'islandora_object_modified' => array(
'group' => t('Islandora'),
'label' => t('Object modified'),
'variables' => array(
'object' => array(
'type' => 'islandora_object',
'label' => t('The modified object'),
'description' => t('A Tuque object for the modified Fedora object, as an entity.'),
),
),
),
'islandora_datastream_modified' => array(
'group' => t('Islandora'),
'label' => t('Datastream modified'),
'variables' => array(
'object' => array(
'type' => 'islandora_object',
'label' => t('The modified object'),
'description' => t('A Tuque object for the Fedora object on which the datastream exists, as an entity.'),
),
'datastream' => array(
'type' => 'islandora_datastream',
'label' => t('Datastream'),
'description' => t('The modified datastream.'),
),
),
),
'islandora_object_purged' => array(
'group' => t('Islandora'),
'label' => t('Object purged'),
'variables' => array(
'object' => array(
'type' => 'text',
'label' => t('Object ID'),
'description' => t('The ID of the purged object.'),
),
),
),
'islandora_datastream_purged' => array(
'group' => t('Islandora'),
'label' => t('Datastream purged'),
'variables' => array(
'object' => array(
'type' => 'islandora_object',
'label' => t('Object'),
'description' => t('A Tuque object for the Fedora object on which the datastream existed, as an entity.'),
),
'datastream' => array(
'type' => 'text',
'label' => t('Datastream ID'),
'description' => t('The identifier of the purged datastream.'),
),
),
),
);
}
/**
* Helper function to get reused "parameter" array.
*/
function islandora_rules_relationship_parameter_array() {
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,
),
);
}
/**
* Helper function; get default parameters for the XPath condition and action.
*/
function islandora_rules_base_xpath_parameters() {
return array(
'object' => array(
'type' => 'islandora_object',
'label' => t('Object'),
'description' => t('The object containing the datastream to check.'),
),
'datastream_id' => array(
'type' => 'text',
'label' => t('Datastream'),
'description' => t('The identifier of the XML datastream to check.'),
),
'xpath' => array(
'type' => 'text',
'label' => t('XPath'),
'description' => t('An XPath to evaluate.'),
),
'xpath_namespaces' => array(
'type' => 'taxonomy_vocabulary',
'label' => t('XPath Namespace Taxonomy'),
'description' => t('A flat taxonomy of which the terms are namespace prefixes and the description contains the URI for the namespace.'),
),
);
}
/**
* 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(),
);
$cond['islandora_object_has_datastream'] = array(
'label' => t('Check object for existence of a datastream'),
'group' => t('Islandora'),
'parameter' => array(
'object' => array(
'type' => 'islandora_object',
'label' => t('Object'),
'description' => t('The object containing the datastream to check.'),
),
'datastream_id' => array(
'type' => 'text',
'label' => t('Datastream'),
'description' => t('The identifier of the datastream to check.'),
),
),
);
$cond['islandora_rules_datastream_has_xpath'] = array(
'label' => t('Check for an XPath match in an XML datastream'),
'group' => t('Islandora'),
'parameter' => islandora_rules_base_xpath_parameters(),
);
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(),
);
$cond['islandora_rules_datastream_load'] = array(
'label' => t('Load a datastream from an object.'),
'group' => t('Islandora'),
'parameter' => array(
'object' => array(
'type' => 'islandora_object',
'label' => t('Object'),
'description' => t('A Tuque object for the Fedora object from which to load the datastream, as an entity.'),
),
'datastream_id' => array(
'type' => 'text',
'label' => t('Datastream ID'),
'description' => t('A string containing the identity of the datastream to load from the object.'),
),
),
'provides' => array(
'datastream' => array(
'type' => 'islandora_datastream',
'label' => t('Loaded datastream instance'),
),
),
);
$cond['islandora_rules_datastream_load_domxpath'] = array(
'label' => t('Load a DOMXPath for a given XML.'),
'group' => t('Islandora DOMXPath'),
'parameter' => array(
'datastream' => array(
'type' => 'text',
'label' => t('XML'),
'description' => t('A string containing the XML to load.'),
),
),
'provides' => array(
'islandora_domxpath' => array(
'type' => 'islandora_domxpath',
'label' => t('Loaded DOMXPath instance'),
),
),
);
$cond['islandora_rules_datastream_load_xpath'] = array(
'label' => t('Load a DOMXPath from a datastream.'),
'group' => t('Islandora DOMXPath'),
'parameter' => array(
'datastream' => array(
'type' => 'islandora_datastream',
'label' => t('Datastream'),
'description' => t('A datastream containing the XML to load.'),
),
),
'provides' => array(
'islandora_domxpath' => array(
'type' => 'islandora_domxpath',
'label' => t('Loaded DOMXPath instance'),
),
),
);
$cond['islandora_rules_datastream_load_namespace_vocab'] = array(
'label' => t('Register namespaces on a DOMXPath instance.'),
'group' => t('Islandora DOMXPath'),
'parameter' => array(
'value' => array(
'type' => 'islandora_domxpath',
'label' => t('DOMXPath instance'),
'description' => t('The DOMXPath instance on which to register the namespaces.'),
),
'xpath_namespaces' => array(
'type' => 'taxonomy_vocabulary',
'label' => t('XPath Namespace Taxonomy'),
'description' => t('A flat taxonomy of which the terms are namespace prefixes and the description contains the URI for the namespace.'),
),
),
);
$cond['islandora_rules_datastream_query_xpath'] = array(
'label' => t('Query nodes from DOMXPath instance.'),
'group' => t('Islandora DOMXPath'),
'parameter' => array(
'xpath' => array(
'type' => 'islandora_domxpath',
'label' => t('DOMXPath instance'),
'description' => t('The DOMXPath instance on which to perform the query.'),
),
'query' => array(
'type' => 'text',
'label' => t('XPath query'),
'description' => t('The XPath query to perform.'),
),
'context_node' => array(
'type' => 'islandora_domnode',
'label' => t('Context Node'),
'description' => t('If provided, the query will be performed relative to the provided node.'),
'optional' => TRUE,
'default value' => NULL,
'allow null' => TRUE,
),
),
'provides' => array(
'nodes' => array(
'type' => 'list<islandora_domnode>',
'label' => t('Queried DOMNode elements'),
),
),
);
$cond['islandora_rules_datastream_set_xpath'] = array(
'label' => t('Set value in elements matched by an XPath in an XML datastream'),
'group' => t('Islandora'),
'parameter' => islandora_rules_base_xpath_parameters() + array(
'value' => array(
'type' => 'text',
'label' => t('Value'),
'description' => t('The value to set in the XML on elements matched by the XPath.'),
),
),
);
return $cond;
}
/**
* Rules action callback; grab a datastream from an object.
*/
function islandora_rules_datastream_load(AbstractObject $object, $datastream_id) {
return array('datastream' => $object[$datastream_id]);
}
/**
* 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);
}
/**
* Rules Action callback; instantiate a DOMXPath with some XML.
*/
function islandora_rules_datastream_load_domxpath($string) {
$doc = new DOMDocument();
$doc->loadXML($string);
$xpath = new DOMXPath($doc);
return array('islandora_domxpath' => $xpath);
}
/**
* Rules Action callback; load namespaces onto a DOMXPath instance.
*
* @param DOMXPath $xpath
* A DOMXPath instance.
* @param object $xpath_vocab
* A loaded Drupal taxonomy vocabulary object, in which terms are understood
* to be namespace prefixes and descriptions are the namespace URIs.
*/
function islandora_rules_datastream_load_namespace_vocab($xpath, $xpath_vocab) {
foreach (taxonomy_get_tree($xpath_vocab->vid, 0, 1, FALSE) as $term) {
$xpath->registerNamespace($term->name, $term->description);
}
}
/**
* Rules XPath helper; grab the datastream content and build a DOMXPath.
*/
function islandora_rules_datastream_load_xpath(AbstractDatastream $datastream, $xpath_vocab = NULL) {
$result = islandora_rules_datastream_load_domxpath($datastream->content);
if (is_object($xpath_vocab)) {
islandora_rules_datastream_load_namespace_vocab($result['islandora_domxpath'], $xpath_vocab);
}
return $result;
}
/**
* Rules Condition callback; test that an XPath returns a non-empty result set.
*/
function islandora_rules_datastream_has_xpath(AbstractObject $object, $datastream_id, $search_xpath, $xpath_vocab) {
$datastream = $object[$datastream_id];
$xpath = islandora_rules_datastream_load_xpath($datastream, $xpath_vocab);
$result = $xpath['islandora_domxpath']->query($search_xpath);
return $result->length > 0;
}
/**
* Rules Action callback; set the value of all matched nodes.
*/
function islandora_rules_datastream_set_xpath(AbstractObject $object, $datastream_id, $search_xpath, $xpath_vocab, $value) {
$datastream = $object[$datastream_id];
$xpath = islandora_rules_datastream_load_xpath($datastream, $xpath_vocab);
$result = $xpath['islandora_domxpath']->query($search_xpath);
foreach ($result as $node) {
$node->nodeValue = $value;
}
$datastream->content = $xpath['islandora_domxpath']->document->saveXML();
}
/**
* Implements hook_rules_data_info().
*/
function islandora_rules_data_info() {
return array(
'islandora_domxpath' => array(
'label' => t('DOMXPath instance'),
'group' => t('Islandora'),
'property info' => array(
'content' => array(
'type' => 'text',
'label' => t('XML Content'),
'computed' => TRUE,
'getter callback' => 'islandora_rules_get_domxpath_document_content',
'token type' => 'string',
),
),
'wrap' => TRUE,
),
'islandora_domnode' => array(
'label' => t('DOMNode instance'),
'group' => t('Islandora'),
'property info' => array(
'node_value' => array(
'type' => 'text',
'label' => t('Node value'),
'computed' => TRUE,
'getter callback' => 'islandora_rules_property_get',
'setter callback' => 'islandora_rules_property_set',
'property' => 'nodeValue',
'token type' => 'string',
),
'text_content' => array(
'type' => 'text',
'label' => t('Text content'),
'computed' => TRUE,
'getter callback' => 'islandora_rules_property_get',
'property' => 'textContent',
'token type' => 'string',
),
),
'wrap' => TRUE,
),
'islandora_domelement' => array(
'label' => t('DOMElement instance'),
'group' => t('Islandora'),
'parent' => 'islandora_domnode',
'wrap' => TRUE,
),
);
}
/**
* Property setter helper; set a property on an object.
*
* In Rules, properties can contain lowercase and numeric characters. Since
* we want to refer to "nodeValue", we have to step around the Rules constraint.
*
* @param object $data
* The object on which to set the property, described by $info['property'].
* @param array $options
* An array of options... Not sure how it's used? Not touched by us, in any
* case. :P
* @param string $name
* The name of the property to set, as used by Rules.
* @param string $type
* The type of object on which the property is being set, as used by Rules.
* @param array $info
* An associative array describing this property. In addition to that
* required by Rules/the Entity API, should contain:
* - property: A string indicate the actual property on the $data we wish to
* set.
*/
function islandora_rules_property_get($data, array $options, $name, $type, $info) {
return $data->$info['property'];
}
/**
* Property setter helper; set a property on an object.
*
* In Rules, properties can contain lowercase and numeric characters. Since
* we want to refer to "nodeValue", we have to step around the Rules constraint.
*
* @param object $data
* The object on which to set the property, described by $info['property'].
* @param string $name
* The name of the property to set, as used by Rules.
* @param mixed $value
* The value to set on the property.
* @param string $langcode
* A string indicating the language being set, or NULL.
* @param string $type
* The type of object on which the property is being set, as used by Rules.
* @param array $info
* An associative array describing this property. In addition to that
* required by Rules/the Entity API, should contain:
* - property: A string indicate the actual property on the $data we wish to
* set.
*/
function islandora_rules_property_set(&$data, $name, $value, $langcode, $type, $info) {
$data->$info['property'] = $value;
}
/**
* Rules property "get" callback; get XML contained in a DOMXPath instance.
*
* @param DOMXPath $xpath
* A DOMXPath instance.
*
* @return string
* The XML contained inside of the DOMXPath instance.
*/
function islandora_rules_get_domxpath_document_content(DOMXPath $xpath) {
return $xpath->document->saveXML();
}
/**
* Rules action callback; perform a query on a DOMXPath instance.
*
* @param DOMXPath $xpath
* A DOMXPath instance.
* @param string $query
* An XPath query.
* @param DOMNode $context_node
* An optional DOMNode. If provided, the query will be performed relative to
* the given node.
*
* @return array
* An array containing:
* - nodes: An array containing the results of the query.
*/
function islandora_rules_datastream_query_xpath(DOMXPath $xpath, $query, DOMNode $context_node = NULL) {
return array('nodes' => iterator_to_array($xpath->query($query, $context_node)));
}
/**
* Rules condition callback; check for the datastream on an object.
*/
function islandora_object_has_datastream(AbstractObject $object, $datastream_id) {
return isset($object[$datastream_id]);
}

26
islandora.rules_defaults.inc

@ -0,0 +1,26 @@
<?php
/**
* @file
* Implementation of Rules hooks, giving default configurations.
*/
/**
* Implements hook_default_rules_configuration().
*/
function islandora_default_rules_configuration() {
$rule = rules_reaction_rule();
$rule->label = 'E-mail admin';
$rule->active = FALSE;
$rule
->event('islandora_object_ingested')
->action(
'mail',
array(
'to' => '[site:mail]',
'subject' => '[[site:name]] "[object:label]" has been ingested',
'message' => '[object:label] has been ingested as [object:id].',
)
);
return array('islandora_object_ingested_notify_admin' => $rule);
}

80
islandora.services.yml

@ -1,80 +0,0 @@
# 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

@ -1,192 +0,0 @@
<?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

@ -1,54 +0,0 @@
<?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',
],
];
}

21
js/spin/LICENSE.txt

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

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

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

70
js/spinner.js

@ -0,0 +1,70 @@
/*jshint browser: true, devel:true*/
/*global jQuery, Drupal, Spinner*/
/**
* @file
* Triggers the display of a spinning icon when the form is submitted.
*/
(function ($) {
'use strict';
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());
}
});
});
$.each(settings.spinner, function (base, value) {
var id = '#' + base,
message = $('<div/>').text(settings.spinner[base].message);
if (id !== '#edit-hidden-next') {
$(id, context).once('spinner', function () {
var spinner = new Spinner(settings.spinner[base].opts);
$(id).parents('form').submit(function (event) {
// If some other widget is preventing form submission we should
// not attempt to submit at this time.
if (event.isDefaultPrevented()) {
return;
}
if ($(this).data('clicked').is(id) && $(this).data('submitted') === undefined) {
event.preventDefault();
// Prevent this from being entered a second time.
$(this).data('submitted', true);
// Add Message.
$(id).after(message);
// Make UI changes.
spinner.spin(this);
$('#edit-next').hide();
$('#edit-prev').hide();
$('.islandora-spinner-submit').hide();
// Submit the form after a set timeout, this handles problems with
// safari, in that safari submits 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 behaviour.
$(id).removeAttr('disabled')
.click()
.click(function (event) {
event.preventDefault();
});
}, 500);
}
return true;
});
});
}
});
}
};
})(jQuery);

19
migrate/tags.csv

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

@ -1,73 +0,0 @@
# 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

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

@ -1,261 +0,0 @@
# 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

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

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

Before

Width:  |  Height:  |  Size: 82 KiB

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 85 KiB

BIN
modules/islandora_advanced_search/docs/contextual_filter_settings.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

BIN
modules/islandora_advanced_search/docs/demo.gif

Binary file not shown.

Before

Width:  |  Height:  |  Size: 645 KiB

BIN
modules/islandora_advanced_search/docs/enable_index_hierarchy.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.2 KiB

BIN
modules/islandora_advanced_search/docs/enable_index_hierarchy_processor.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

BIN
modules/islandora_advanced_search/docs/exclude_facet_settings_exclude.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

BIN
modules/islandora_advanced_search/docs/exclude_facet_settings_url_alias.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.7 KiB

BIN
modules/islandora_advanced_search/docs/facet_block_settings.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

BIN
modules/islandora_advanced_search/docs/field_decedent_of.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.1 KiB

BIN
modules/islandora_advanced_search/docs/include_exclude_facets.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

BIN
modules/islandora_advanced_search/docs/include_exclude_facets_settings.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

BIN
modules/islandora_advanced_search/docs/islandora_advanced_search_settings.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

BIN
modules/islandora_advanced_search/docs/pager.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

BIN
modules/islandora_advanced_search/docs/pager_settings.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 KiB

BIN
modules/islandora_advanced_search/docs/sort_criteria.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.7 KiB

BIN
modules/islandora_advanced_search/docs/view_advanced_setting.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

13
modules/islandora_advanced_search/islandora_advanced_search.info.yml

@ -1,13 +0,0 @@
# 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

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

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

@ -1,89 +0,0 @@
<?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

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

@ -1,113 +0,0 @@
//# 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

@ -1,124 +0,0 @@
//# 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

@ -1,254 +0,0 @@
<?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