Compare commits

..

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

  1. 43
      .github/PULL_REQUEST_TEMPLATE.md
  2. 125
      .github/workflows/build-2.x.yml
  3. 26
      .github/workflows/gitlab-mirror.yml
  4. 6
      .gitignore
  5. 19
      .travis.yml
  6. 73
      CONTRIBUTING.md
  7. 15
      COPYRIGHT
  8. 339
      LICENSE
  9. 674
      LICENSE.txt
  10. 146
      README.md
  11. 84
      build.xml
  12. 1627
      build/Doxyfile
  13. 57
      composer.json
  14. 4
      config/install/islandora.settings.yml
  15. 13
      config/install/system.action.delete_media_and_file.yml
  16. 244
      config/schema/islandora.schema.yml
  17. 17
      css/islandora.admin.css
  18. 60
      css/islandora.base.css
  19. 3
      css/islandora.css
  20. 39
      css/islandora.objects.css
  21. 43
      css/islandora.theme.css
  22. 6
      drush.services.yml
  23. BIN
      images/folder.png
  24. 228
      includes/add_datastream.form.inc
  25. 142
      includes/admin.form.inc
  26. 136
      includes/authtokens.inc
  27. 121
      includes/breadcrumb.inc
  28. 57
      includes/content_model.autocomplete.inc
  29. 190
      includes/datastream.inc
  30. 71
      includes/delete_datastream.form.inc
  31. 48
      includes/delete_object.form.inc
  32. 167
      includes/dublin_core.inc
  33. 887
      includes/ingest.form.inc
  34. 385
      includes/mime_detect.inc
  35. 53
      includes/object.entity_controller.inc
  36. 123
      includes/object_properties.form.inc
  37. 695
      includes/solution_packs.inc
  38. 115
      includes/tuque.inc
  39. 358
      includes/tuque_wrapper.inc
  40. 867
      includes/utilities.inc
  41. 521
      islandora.api.php
  42. 20
      islandora.info
  43. 33
      islandora.info.yml
  44. 283
      islandora.install
  45. 5
      islandora.libraries.yml
  46. 29
      islandora.links.action.yml
  47. 20
      islandora.links.menu.yml
  48. 1745
      islandora.module
  49. 12
      islandora.permissions.yml
  50. 16
      islandora.post_update.php
  51. 111
      islandora.routing.yml
  52. 118
      islandora.rules.inc
  53. 80
      islandora.services.yml
  54. 192
      islandora.tokens.inc
  55. 54
      islandora.views.inc
  56. 19
      migrate/tags.csv
  57. 73
      modules/islandora_advanced_search/CONTRIBUTING.md
  58. 339
      modules/islandora_advanced_search/LICENSE
  59. 261
      modules/islandora_advanced_search/README.md
  60. 37
      modules/islandora_advanced_search/css/islandora_advanced_search.form.css
  61. 111
      modules/islandora_advanced_search/css/islandora_advanced_search.pager.css
  62. BIN
      modules/islandora_advanced_search/docs/advanced_search_block_settings.png
  63. BIN
      modules/islandora_advanced_search/docs/basic-input.png
  64. BIN
      modules/islandora_advanced_search/docs/contextual_filter_settings.png
  65. BIN
      modules/islandora_advanced_search/docs/demo.gif
  66. BIN
      modules/islandora_advanced_search/docs/enable_index_hierarchy.png
  67. BIN
      modules/islandora_advanced_search/docs/enable_index_hierarchy_processor.png
  68. BIN
      modules/islandora_advanced_search/docs/exclude_facet_settings_exclude.png
  69. BIN
      modules/islandora_advanced_search/docs/exclude_facet_settings_url_alias.png
  70. BIN
      modules/islandora_advanced_search/docs/facet_block_settings.png
  71. BIN
      modules/islandora_advanced_search/docs/field_decedent_of.png
  72. BIN
      modules/islandora_advanced_search/docs/include_exclude_facets.png
  73. BIN
      modules/islandora_advanced_search/docs/include_exclude_facets_settings.png
  74. BIN
      modules/islandora_advanced_search/docs/islandora_advanced_search_settings.png
  75. BIN
      modules/islandora_advanced_search/docs/pager.png
  76. BIN
      modules/islandora_advanced_search/docs/pager_settings.png
  77. BIN
      modules/islandora_advanced_search/docs/sort_criteria.png
  78. BIN
      modules/islandora_advanced_search/docs/view_advanced_setting.png
  79. 13
      modules/islandora_advanced_search/islandora_advanced_search.info.yml
  80. 17
      modules/islandora_advanced_search/islandora_advanced_search.libraries.yml
  81. 6
      modules/islandora_advanced_search/islandora_advanced_search.links.menu.yml
  82. 89
      modules/islandora_advanced_search/islandora_advanced_search.module
  83. 17
      modules/islandora_advanced_search/islandora_advanced_search.routing.yml
  84. 113
      modules/islandora_advanced_search/js/islandora_advanced_search.admin.js
  85. 124
      modules/islandora_advanced_search/js/islandora_advanced_search.form.js
  86. 254
      modules/islandora_advanced_search/src/AdvancedSearchQuery.php
  87. 294
      modules/islandora_advanced_search/src/AdvancedSearchQueryTerm.php
  88. 165
      modules/islandora_advanced_search/src/Controller/AjaxBlocksController.php
  89. 423
      modules/islandora_advanced_search/src/Form/AdvancedSearchForm.php
  90. 122
      modules/islandora_advanced_search/src/Form/SettingsForm.php
  91. 24
      modules/islandora_advanced_search/src/GetConfigTrait.php
  92. 394
      modules/islandora_advanced_search/src/Plugin/Block/AdvancedSearchBlock.php
  93. 17
      modules/islandora_advanced_search/src/Plugin/Block/AdvancedSearchBlockDeriver.php
  94. 97
      modules/islandora_advanced_search/src/Plugin/Block/SearchApiDisplayBlockDeriver.php
  95. 314
      modules/islandora_advanced_search/src/Plugin/Block/SearchResultsPagerBlock.php
  96. 17
      modules/islandora_advanced_search/src/Plugin/Block/SearchResultsPagerBlockDeriver.php
  97. 30
      modules/islandora_advanced_search/src/Plugin/Block/ViewAndDisplayIdentifiersTrait.php
  98. 63
      modules/islandora_advanced_search/src/Plugin/Field/FieldFormatter/EntityReferenceCountFormatter.php
  99. 84
      modules/islandora_advanced_search/src/Plugin/facets/widget/IncludeExcludeLinksWidget.php
  100. 42
      modules/islandora_advanced_search/src/Plugin/facets_summary/processor/ResetRemovePage.php
  101. Some files were not shown because too many files have changed in this diff Show More

43
.github/PULL_REQUEST_TEMPLATE.md

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

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

@ -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 cache.properties
/.idea/ .DS_Store
/.vscode tests/test_config.ini

19
.travis.yml

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

73
CONTRIBUTING.md

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

15
COPYRIGHT

@ -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>.

146
README.md

@ -1,121 +1,69 @@
# Islandora BUILD STATUS
------------
Current build status:
[![Build Status](https://travis-ci.org/Islandora/islandora.png?branch=7.x)](https://travis-ci.org/Islandora/islandora)
[![Minimum PHP Version](https://img.shields.io/badge/php-%3E%3D%207.4-8892BF.svg?style=flat-square)](https://php.net/) CI Server:
[![Build Status](https://github.com/islandora/islandora/actions/workflows/build-2.x.yml/badge.svg)](https://github.com/Islandora/islandora/actions) http://jenkins.discoverygarden.ca
[![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)
## Introduction SUMMARY
-------
This is the core module of Islandora's digital repository ecosystem. The `islandora` module provides: Islandora Fedora Repository Module
- 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: For installation and customization instructions please see the documentation
- `islandora_core_feature` (**required**) and the DuraSpace Wiki:
- Configuration required by the `islandora` module
- `islandora_image`
- Integrates with a [Houdini](https://github.com/Islandora/Crayfish/tree/dev/Houdini) (Imagemagick) server for image processing
- `islandora_audio` and `islandora_video`
- Integrate with a [Homarus](https://github.com/Islandora/Crayfish/tree/dev/Homarus) (`ffmpeg`) server for audio/video processing
- `islandora_text_extraction` and `islandora_text_extraction_defaults`
- Integrate with a [Hypercube](https://github.com/Islandora/Crayfish/tree/dev/Hypercube) (`tessseract` and `pdftotext`) server for text extraction
- `islandora_breadcrumbs`
- Provides breadcrumbs following collection structure
- `islandora_iiif`
- Provides IIIF manifests for repository content
## Requirements https://wiki.duraspace.org/display/ISLANDORA/Islandora
Installing via composer will download all required libraries and modules. However, for reference, `islandora` requires the following drupal modules: All bugs, feature requests and improvement suggestions are tracked at the
DuraSpace JIRA:
- [context](http://drupal.org/project/context) https://jira.duraspace.org/browse/ISLANDORA
- [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)
It also requires the following PHP libraries: REQUIREMENTS
------------
The Tuque library must be installed to use Islandora. It can be found here:
http://github.com/Islandora/tuque
It is expected to be in one of two paths:
- sites/all/libraries/tuque (libraries directory may need to be created)
- islandora_folder/libraries/tuque
- [Crayfish Commons](https://packagist.org/packages/islandora/crayfish-commons) INSTALLATION
- [Stomp PHP](http://drupal.org/project/) ------------
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. Before installing Islandora the XACML policies located in the policies folder
should be copied into the Fedora global XACML policies folder. This will allow
"authenticated users" in Drupal to access Fedora API-M functions.
## Installation CONFIGURATION
-------------
For a full digital repository solution, see our [installation documentation](https://islandora.github.io/documentation/installation/component_overview/). 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.
To download/enable just this module, use the following from the command line: Drupal's cron will can be ran to remove expired authentication tokens.
```bash CUSTOMIZATION
$ composer require islandora/islandora -------------
$ drush en islandora_core_feature
$ drush mim islandora_tags
```
## Configuration [Customize ingest forms](http://github.com/Islandora/islandora/wiki/Multi-paged-Ingest-Forms)
![image](https://user-images.githubusercontent.com/20773151/67234502-ac171900-f41b-11e9-964e-c7d4cfadbd67.png) TROUBLESHOOTING
---------------
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 F.A.Q.
------
Further documentation for this module is available on the [Islandora 8 documentation site](https://islandora.github.io/documentation/).
## Troubleshooting/Issues CONTACT
-------
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:
* [Islandora Technical Advisory Group](https://github.com/Islandora/islandora-community/wiki/Technical-Advisory-Group-%28TAG%29)
## Sponsors
* [American Philosophical Society](https://www.amphilsoc.org/)
* [Born-Digital, Inc.](https://www.born-digital.com/)
* [discoverygarden inc.](https://www.discoverygarden.ca/)
* [LYRASIS](https://www.lyrasis.org/)
* [McMaster University](https://www.mcmaster.ca/)
* [PALS](https://www.mnpals.org/)
* [University of Limerick](https://www.ul.ie/)
* [University of Manitoba](https://umanitoba.ca/)
* [UPEI](https://www.upei.ca/)
* [Simon Fraser University](https://www.sfu.ca/)
* [York University](https://www.yorku.ca/)
## Development
If you would like to contribute, please get involved by attending our weekly [Tech Call](https://github.com/Islandora/islandora-community/wiki/Weekly-Open-Tech-Call). We love to hear from you!
If you would like to contribute code to the project, you need to be covered by an Islandora Foundation [Contributor License Agreement](https://github.com/Islandora/islandora-community/wiki/Onboarding-Checklist#contributor-license-agreements) or [Corporate Contributor License Agreement](https://github.com/Islandora/islandora-community/wiki/Onboarding-Checklist#contributor-license-agreements). Please see the [Contributor License Agreements](https://github.com/Islandora/islandora-community/wiki/Contributor-License-Agreements) page on the islandora-community wiki for more information.
We recommend using the [islandora-playbook](https://github.com/Islandora-Devops/islandora-playbook) to get started.
## License
[GPLv2](http://www.gnu.org/licenses/gpl-2.0.txt)
SPONSORS
--------

84
build.xml

@ -0,0 +1,84 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="islandora" default="build">
<target name="build" depends="clean,prepare,lint,phploc,code_sniff,phpcpd,pdepend,doxygen,phpcb,test" />
<target name="clean" description="Cleanup build artifacts">
<delete dir="${basedir}/build/test" />
<delete dir="${basedir}/build/logs" />
<delete dir="${basedir}/build/pdepend" />
<delete dir="${basedir}/build/api" />
<delete dir="${basedir}/build/code-browser" />
</target>
<target name="prepare" description="Prepares workspace for artifacts" >
<mkdir dir="${basedir}/build/test" />
<mkdir dir="${basedir}/build/logs" />
<mkdir dir="${basedir}/build/pdepend" />
<mkdir dir="${basedir}/build/api" />
<mkdir dir="${basedir}/build/code-browser" />
</target>
<target name="lint" description="Perform syntax check of sourcecode files">
<apply executable="php" failonerror="true">
<arg value="-l" />
<fileset dir="${basedir}">
<include name="**/*.php" />
<include name="**/*.inc" />
<include name="**/*.module" />
<include name="**/*.install" />
<include name="**/*.test" />
<modified />
</fileset>
</apply>
</target>
<target name="phploc" description="Measure project size using PHPLOC">
<exec executable="phploc">
<arg line="--log-csv ${basedir}/build/logs/phploc.csv --exclude build --exclude css --exclude images --exclude xml --names *.php,*.module,*.inc,*.test,*.install ${basedir}" />
</exec>
</target>
<target name="code_sniff" description="Checks the code for Drupal coding standard violations" >
<exec executable="phpcs">
<arg line="--standard=Drupal --report=checkstyle --report-file=${basedir}/build/logs/checkstyle.xml --extensions=php,inc,test,module,install --ignore=build/,xml/,images/,css/ ${basedir}" />
</exec>
</target>
<target name="phpcpd" description="Copy/Paste code detection">
<exec executable="phpcpd">
<arg line="--log-pmd ${basedir}/build/logs/pmd-cpd.xml --exclude build --exclude css --exclude images --exclude xml --names *.php,*.module,*.inc,*.test,*.install ${basedir}" />
</exec>
</target>
<target name="pdepend" description="Calculate software metrics using PHP_Depend">
<exec executable="pdepend">
<arg line="--jdepend-xml=${basedir}/build/logs/jdepend.xml --jdepend-chart=${basedir}/build/pdepend/dependencies.svg --overview-pyramid=${basedir}/build/pdepend/overview-pyramid.svg ${basedir}"/>
</exec>
</target>
<target name="doxygen" description="Generate API documentation with doxygen" depends="prepare">
<exec executable="bash">
<arg line='-c "sed -i s/PROJECT_NUMBER\ \ \ \ \ \ \ \ \ =/PROJECT_NUMBER\ \ \ \ \ \ \ \ \ =\ `git log -1 --pretty=format:%h`/ build/Doxyfile"'/>
</exec>
<exec executable="doxygen">
<arg line="${basedir}/build/Doxyfile" />
</exec>
<exec executable="git">
<arg line="checkout ${basedir}/build/Doxyfile"/>
</exec>
</target>
<target name="phpcb" description="Aggregate tool output with PHP_CodeBrowser">
<exec executable="phpcb">
<arg line="--log ${basedir}/build/logs --source ${basedir} --output ${basedir}/build/code-browser"/>
</exec>
</target>
<target name="test">
<exec executable="bash">
<arg line='-c "php ../../../../scripts/run-tests.sh --xml ${basedir}/build/test Islandora"' />
</exec>
</target>
</project>

1627
build/Doxyfile

File diff suppressed because it is too large Load Diff

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

17
css/islandora.admin.css

@ -0,0 +1,17 @@
/**
* @file
* Css file for Islandora admin pages
*/
/* Solution pack admin page */
.islandora-solution-pack-fieldset
{
padding-top: 0.5em;
}
.islandora-solution-pack-fieldset table th,
.islandora-solution-pack-fieldset table td
{
width: 33%;
}

60
css/islandora.base.css

@ -0,0 +1,60 @@
/*
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;
}
/*
* 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;
}

39
css/islandora.objects.css

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

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;
width: 20.8333%;
padding: 0 10px 0 0;
margin: 1.5em 0;
}
dl.islandora-object-fields {
float: right;
width:79.1666%;
border-top:0px solid #ddd;
margin: 1.5em 0;
}
.islandora-object-fields dt {
font-weight: bold;
}
.islandora-object-fields dt.first {
border-top:0;
}
.islandora-object-fields dt,
.islandora-object-fields dd {
padding:6px 2% 4px;
border-top:1px solid #ddd;
}
.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

228
includes/add_datastream.form.inc

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

142
includes/admin.form.inc

@ -0,0 +1,142 @@
<?php
/**
* @file
* This administration form for this module.
*/
/**
* The administration form for the fedora repository connection.
*
* @param array $form
* The Drupal form definition.
* @param array $form_state
* The Drupal form state.
*
* @return array
* The Drupal form definition.
*/
function islandora_repository_admin(array $form, array &$form_state) {
module_load_include('inc', 'islandora', 'includes/utilities');
drupal_add_css(drupal_get_path('module', 'islandora') . '/css/islandora.admin.css');
$url = islandora_system_settings_form_default_value('islandora_base_url', 'http://localhost:8080/fedora', $form_state);
$restrict_namespaces = islandora_system_settings_form_default_value('islandora_namespace_restriction_enforced', FALSE, $form_state);
$confirmation_message = islandora_admin_settings_form_repository_access_message($url);
$form = array(
'islandora_tabs' => array(
'#type' => 'vertical_tabs',
'islandora_general' => array(
'#type' => 'fieldset',
'#title' => t('General Configuarion'),
'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_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' => 'textfield',
'#title' => t('PID namespaces allowed in this Drupal install'),
'#description' => t('A list of PID namespaces, separated by spaces, that users are permitted to access from this Drupal installation. <br /> This could be more than a simple namespace, e.g. <b>demo:mydemos</b>. <br /> The namespace <b>islandora:</b> is reserved, and is always allowed.'),
'#default_value' => variable_get('islandora_pids_allowed', 'default: demo: changeme: ilives: islandora-book: books: newspapers: '),
'#states' => array(
'invisible' => array(
':input[name="islandora_namespace_restriction_enforced"]' => array('checked' => FALSE),
),
),
),
),
),
);
return system_settings_form($form);
}
/**
* Gets a message which describes if the repository is accessible.
*
* Also describes if the user is considered an authenticated user by the
* repository.
*
* @param string $url
* The url to the Fedora Repository.
*
* @return string
* A message describing the accessibility of the repository at the given url.
*/
function islandora_admin_settings_form_repository_access_message($url) {
$info = $dc = FALSE;
$connection = islandora_get_tuque_connection(NULL, $url);
if ($connection) {
try {
$info = $connection->api->a->describeRepository();
// If we are able to successfully call API-M::getDatastream, assume we are
// an authenticated user, as API-M is usally locked down.
$dc = $connection->api->m->getDatastream('fedora-system:ContentModel-3.0', 'DC');
}
catch (RepositoryException $e) {
// Ignore, we only testing to see what is accessible.
}
}
if ($info && $dc) {
$confirmation_message = theme_image(array('path' => 'misc/watchdog-ok.png', 'attributes' => array()));
$confirmation_message .= t('Successfully connected to Fedora Server (Version !version).', array(
'!version' => $info['repositoryVersion']));
}
elseif ($info) {
$confirmation_message = theme_image(array('path' => 'misc/watchdog-warning.png', 'attributes' => array()));
$confirmation_message .= t('Unable to authenticate when connecting to to Fedora Server (Version !version). Please configure the !filter.', array(
'!version' => $info['repositoryVersion'], '!filter' => 'Drupal Filter'));
}
else {
$confirmation_message = theme_image(array('path' => 'misc/watchdog-error.png', 'attributes' => array()));
$confirmation_message .= t('Unable to connect to Fedora server at !islandora_url', array(
'!islandora_url' => $url));
}
return $confirmation_message;
}
/**
* Get the element to render for the AJAX event that triggered this callback.
*
* @param array $form
* The Drupal form definition.
* @param array $form_state
* The Drupal form state.
*
* @return array
* The form element to render.
*/
function islandora_update_url_div(array $form, array $form_state) {
return $form['islandora_tabs']['islandora_general']['wrapper'];
}

136
includes/authtokens.inc

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

121
includes/breadcrumb.inc

@ -0,0 +1,121 @@
<?php
/**
* @file
* This file contains functions to create breadcrumbs on Islandora object pages.
*/
/**
* Get an array of links to be passed to drupal_set_breadcrumb().
*
* This is used for generating the bread-crumbs for the view object page.
*
* Each link in the bread-crumbs represents a member of the given objects
* ancestry which is identified by any of the following RELS-EXT terms
* (isMemberOf,isMemberOfCollection,isPartOf).
*
* @param AbstractObject $object
* An object whose ancestry will be mapped to bread-crumbs.
*
* @see drupal_set_breadcrumb()
*
* @return array
* Array of links, starting with most distant ancestor proceeding up to but
* not including the given object. For use in the function
* drupal_set_breadcrumb().
*/
function islandora_get_breadcrumbs($object) {
$breadcrumbs = islandora_get_breadcrumbs_recursive($object->id, $object->repository);
array_pop($breadcrumbs);
return $breadcrumbs;
}
/**
* Builds an array of drupal links for use in breadcrumbs.
*
* @todo Make fully recursive...
*
* @param string $pid
* The object id whose parent will be fetched for the next link.
* @param FedoraRepository $repository
* The fedora repository.
* @param array $context
* An associative array of context for internal use when recursing. Currently
* only used to track a single value:
* - level: The number of child-parent relationships to follow. Defaults to
* 10.
*
* @return array
* An array of links representing the breadcrumb trail, "root" first.
*/
function islandora_get_breadcrumbs_recursive($pid, FedoraRepository $repository, array &$context = NULL) {
// Before executing the query, we have a base case of accessing the top-level
// collection.
if ($context === NULL) {
$context['level'] = 10;
}
$root = variable_get('islandora_repository_pid', 'islandora:root');
if ($pid == $root) {
$title = 'Islandora Repository';
$mlid = db_select('menu_links', 'ml')
->condition('ml.link_path', 'islandora')
->fields('ml', array('mlid'))
->execute()
->fetchField();
if ($mlid) {
$link = menu_link_load($mlid);
$title = (isset($link['title']) ? $link['title'] : $title);
}
return array(
l(t('Home'), '<front>'),
l($title, 'islandora'),
);
}
else {
$query_string = 'select $parentObject $title $content from <#ri>
where (
<info:fedora/' . $pid . '> <fedora-model:label> $title
and $parentObject <fedora-model:hasModel> $content
and (
<info:fedora/' . $pid . '> <fedora-rels-ext:isMemberOfCollection> $parentObject
or <info:fedora/' . $pid . '> <fedora-rels-ext:isMemberOf> $parentObject
or <info:fedora/' . $pid . '> <fedora-rels-ext:isPartOf> $parentObject
)
and $parentObject <fedora-model:state> <info:fedora/fedora-system:def/model#Active>
)
minus $content <mulgara:is> <info:fedora/fedora-system:FedoraObject-3.0>
minus $parentObject <mulgara:is> <info:fedora/' . $pid . '>
order by $title desc';
$results = $repository->ri->itqlQuery($query_string);
if (count($results) > 0 && $context['level'] > 0) {
$parent = $results[0]['parentObject']['value'];
$this_title = $results[0]['title']['value'];
if (empty($this_title)) {
$this_title = t('-');
}
$context['level']--;
return array_merge(
islandora_get_breadcrumbs_recursive($parent, $repository, $context),
array(
l($this_title, "islandora/object/$pid"),
)
);
}
else {
// Add an non-link, as we don't know how to get back to the root, and
// render the last two links and break (on the next pass).
return array_merge(
islandora_get_breadcrumbs_recursive($root, $repository, $context),
array(
'...',
)
);
}
}
}

57
includes/content_model.autocomplete.inc

@ -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;
}

190
includes/datastream.inc

@ -0,0 +1,190 @@
<?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.
*/
function islandora_view_datastream(AbstractDatastream $datastream, $download = FALSE) {
header_remove('Cache-Control');
header_remove('Expires');
header('Content-type: ' . $datastream->mimetype);
if ($datastream->controlGroup == 'M' || $datastream->controlGroup == 'X') {
header('Content-length: ' . $datastream->size);
}
if ($download) {
// Browsers will not append all extensions.
$mime_detect = new MimeDetect();
$extension = $mime_detect->getExtension($datastream->mimetype);
$filename = $datastream->label . '.' . $extension;
header("Content-Disposition: attachment; filename=\"$filename\"");
}
drupal_page_is_cacheable(FALSE);
// Try not to load the file into PHP memory!
ob_end_flush();
$datastream->getContent('php://output');
exit();
}
/**
* 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.
*
* @return string
* either the 'view' or 'download' url for the given datastream.
*/
function islandora_datastream_get_url(AbstractDatastream $datastream, $type = 'download') {
return $datastream->controlGroup == 'R' ? $datastream->url : "islandora/object/{$datastream->parent->id}/datastream/{$datastream->id}/$type";
}
/**
* Gets the delete link.
*
* @param AbstractDatastream $datastream
* The datastream to generated the url to.
*/
function islandora_datastream_get_delete_link(AbstractDatastream $datastream) {
$message = islandora_deprecated('7.x-1.2', 'Use the "islandora_datastream_delete_link" theme implementation.');
trigger_error(filter_xss($message), E_USER_DEPRECATED);
return theme('islandora_datastream_delete_link', array(
'datastream' => $datastream,
));
}
/**
* Gets the edit link.
*
* @param AbstractDatastream $datastream
* The datastream to generated the url to.
*/
function islandora_datastream_edit_get_link(AbstractDatastream $datastream) {
$message = islandora_deprecated('7.x-1.2', 'Use the "islandora_datastream_edit_link" theme implementation.');
trigger_error(filter_xss($message), E_USER_DEPRECATED);
return theme('islandora_datastream_edit_link', array(
'datastream' => $datastream,
));
}
/**
* Display the edit datastream page.
*
* @param AbstractDatastream $datastream
* The datastream to edit.
*/
function islandora_edit_datastream(AbstractDatastream $datastream) {
$edit_registry = module_invoke_all('islandora_edit_datastream_registry', $datastream->parent, $datastream);
$edit_count = count($edit_registry);
switch ($edit_count) {
case 0:
// No edit implementations.
drupal_set_message(t('There are no edit methods specified for this datastream.'));
drupal_goto("islandora/object/{$object->id}/manage/datastreams");
break;
case 1:
// One registry implementation, go there.
drupal_goto($edit_registry[0]['url']);
break;
default:
// Multiple edit routes registered.
return islandora_edit_datastream_registry_render($edit_registry);
}
}
/**
* Displays links to all the edit datastream registry items.
*
* @param array $edit_registry
* A list of 'islandora_edit_datastream_registry' values.
*/
function islandora_edit_datastream_registry_render(array $edit_registry) {
$markup = '';
foreach ($edit_registry as $edit_route) {
$markup .= l($edit_route['name'], $edit_route['url']) . '<br/>';
}
return array(
'#type' => 'markup',
'#markup' => $markup,
);
}
/**
* Get markup for a download link.
*
* @param AbstractDatastream $datastream
* The datastream for which to generate a link.
*
* @return string
* Either the link markup if the user has access or an empty string if the
* user is not allowed to see the given datastream.
*/
function islandora_datastream_get_download_link(AbstractDatastream $datastream) {
$message = islandora_deprecated('7.x-1.2', 'Use the "islandora_datastream_download_link" theme implementation.');
trigger_error(filter_xss($message), E_USER_DEPRECATED);
return theme('islandora_datastream_download_link', array(
'datastream' => $datastream,
));
}
/**
* Get markup for a view link.
*
* @param AbstractDatastream $datastream
* The datastream for which to generate a link.
*
* @return string
* Either the link markup if the user has access or a string containing the
* datastream ID if the user is not allowed to see the given datastream.
*/
function islandora_datastream_get_view_link(AbstractDatastream $datastream) {
$message = islandora_deprecated('7.x-1.2', 'Use the "islandora_datastream_view_link" theme implementation.');
trigger_error(filter_xss($message), E_USER_DEPRECATED);
return theme('islandora_datastream_view_link', array(
'datastream' => $datastream,
));
}

71
includes/delete_datastream.form.inc

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

48
includes/delete_object.form.inc

@ -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);
}

167
includes/dublin_core.inc

@ -0,0 +1,167 @@
<?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]);
$dc_array[$field]['label'] = $element_label;
$dc_array[$field]['value'] = $value;
$dc_array[$field]['class'] = drupal_strtolower(preg_replace('/[^A-Za-z0-9]/', '-', $field));
}
}
}
return $dc_array;
}
/**
* Creates a new instance of the class by parsing dc_xml.
*
* @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;
}
}

887
includes/ingest.form.inc

@ -0,0 +1,887 @@
<?php
/**
* @file
* Defines the multi-page ingest form and any relevant hooks and functions.
*/
/**
* Checks if the given configuration can be used to display the ingest form.
*
* @param array $configuration
* The list of key/value pairs of configuration.
*
* @return bool
* TRUE if the give configuration defines one or more form steps, FALSE
* otherwise.
*/
function islandora_ingest_can_display_ingest_form(array $configuration) {
$form_state = array();
islandora_ingest_form_init_form_state_storage($form_state, $configuration);
$form_steps = islandora_ingest_form_get_form_steps($form_state);
// Forget the stubbed steps for the remainder of this request.
drupal_static_reset('islandora_ingest_form_get_steps');
return count($form_steps) > 0;
}
/**
* Ingest form build function.
*
* Initializes the form state, and builds the initial list of steps, excutes
* the current step.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
* @param array $configuration
* An associative array of configuration values that are used to build the
* list of steps to be executed, including:
* - id: The PID with which the object should be created.
* - namespace: The PID namespace in which the object should be created.
* (id is used first, if it is given).
* - label: The initial label for the object. Defaults to "New Object".
* - collections: An array of collection PIDs, to which the new object should
* be related.
* - models: An array of content model PIDs, to which the new object might
* subscribe
* - parent: The parent of the child to be ingested. This is needed for XACML
* to correctly apply the parent's POLICY to children.
*
* @return array
* The form definition of the current step.
*/
function islandora_ingest_form(array $form, array &$form_state, array $configuration) {
try {
islandora_ingest_form_init_form_state_storage($form_state, $configuration);
return islandora_ingest_form_execute_step($form, $form_state);
}
catch (Exception $e) {
drupal_set_message($e->getMessage(), 'error');
return array(array(
'#markup' => l(t('Back'), 'javascript:window.history.back();', array('external' => TRUE))));
}
}
/**
* Initializes the form_state storage for use in the ingest multi-page forms.
*
* @param array $form_state
* The Drupal form state.
* @param array $configuration
* A list of key value pairs that are used to build the list of steps to be
* executed.
*/
function islandora_ingest_form_init_form_state_storage(array &$form_state, array $configuration) {
if (empty($form_state['islandora'])) {
$objects = isset($configuration['objects']) ? $configuration['objects'] : array();
if (empty($objects)) {
$objects[] = islandora_ingest_form_prepare_new_object($configuration);
}
$configuration['models'] = isset($configuration['models']) ? $configuration['models'] : array();
// Make sure the models actually exist.
foreach ($configuration['models'] as $key => $model) {
if (!islandora_object_load($model)) {
unset($configuration['models'][$key]);
}
}
// No need to persist the 'objects' within the configuration.
unset($configuration['objects']);
// Required for step hooks.
$form_state['islandora'] = array(
'step_id' => NULL,
'objects' => $objects,
'shared_storage' => $configuration,
'step_storage' => array(),
);
// Must be called after $form_state['islandora'] is initialized, otherwise,
// the values in 'islandora' would not be availible to the step hooks.
$form_state['islandora']['step_id'] = islandora_ingest_form_get_first_step_id($form_state);
}
}
/**
* Get the first step ID.
*
* @param array $form_state
* The Drupal form state.
*
* @return string
* The 'id' of the very first step.
*/
function islandora_ingest_form_get_first_step_id(array &$form_state) {
$steps = islandora_ingest_form_get_steps($form_state);
$keys = array_keys($steps);
return array_shift($keys);
}
/**
* Get the last step ID.
*
* @param array $form_state
* The Drupal form state.
*
* @return string
* The 'id' of the very last step.
*/
function islandora_ingest_form_get_last_step_id(array &$form_state) {
$steps = islandora_ingest_form_get_steps($form_state);
$keys = array_keys($steps);
return array_pop($keys);
}
/**
* Prepares a new object based on the given configuration.
*
* @param array $configuration
* The list of key/value pairs of configuration.
*
* @return NewFedoraObject
* The new object.
*/
function islandora_ingest_form_prepare_new_object(array $configuration) {
module_load_include('inc', 'islandora', 'includes/utilities');
if (empty($configuration['object'])) {
$message = islandora_deprecated('7.x-1.2', t('Please use "objects" as the default ingest form configuration property.'));
trigger_error(filter_xss($message), E_USER_DEPRECATED);
// ID is more specific than namespace so it will take precedence.
$id = isset($configuration['namespace']) ? $configuration['namespace'] : 'islandora';
$id = isset($configuration['id']) ? $configuration['id'] : $id;
$label = isset($configuration['label']) ? $configuration['label'] : 'New Object';
$relationship_map = function($o) {
return array('relationship' => 'isMemberOfCollection', 'pid' => $o);
};
$relationships = empty($configuration['collections']) ? array() : array_map($relationship_map, $configuration['collections']);
return islandora_prepare_new_object($id, $label, array(), array(), $relationships);
}
return $configuration['object'];
}
/**
* Gets the given/current step.
*
* If the current step is not defined it's assumed that all steps have executed.
*
* @param array $form_state
* The Drupal form state.
* @param string $step_id
* The ID of the step. The current step is returned if no step ID is given.
*
* @return array
* The given/current step if found, NULL otherwise.
*/
function islandora_ingest_form_get_step(array &$form_state, $step_id = NULL) {
$step_id = isset($step_id) ? $step_id : islandora_ingest_form_get_current_step_id($form_state);
$steps = islandora_ingest_form_get_steps($form_state);
if (isset($step_id) && isset($steps[$step_id])) {
return $steps[$step_id];
}
return NULL;
}
/**
* Gets the next step.
*
* If the current step is not defined it's assumed that all steps have executed.
*
* @param array $form_state
* The Drupal form state.
* @param string $step
* The step relative to the result, if not provided the current step is used.
*
* @return string
* The next step if found, NULL otherwise.
*/
function islandora_ingest_form_get_next_step(array &$form_state, array $step = NULL) {
$step = isset($step) ? $step : islandora_ingest_form_get_step($form_state);
$next_step_id = islandora_ingest_form_get_next_step_id($form_state, $step['id']);
return isset($next_step_id) ? islandora_ingest_form_get_step($form_state, $next_step_id) : NULL;
}
/**
* Gets the previous step.
*
* If the current step is not defined it's assumed that all steps have executed.
*
* @param array $form_state
* The Drupal form state.
* @param string $step
* The step relative to the result, if not provided the current step is used.
*
* @return string
* The next step if found, NULL otherwise.
*/
function islandora_ingest_form_get_previous_step(array &$form_state, array $step = NULL) {
$step = isset($step) ? $step : islandora_ingest_form_get_step($form_state);
$previous_step_id = islandora_ingest_form_get_previous_step_id($form_state, $step['id']);
return isset($previous_step_id) ? islandora_ingest_form_get_step($form_state, $previous_step_id) : NULL;
}
/**
* Gets the ID of the current step.
*
* If the current step is not defined it's assumed that all steps have executed.
*
* @param array $form_state
* The Drupal form state.
*
* @return string
* The step ID.
*/
function islandora_ingest_form_get_current_step_id(array &$form_state) {
return $form_state['islandora']['step_id'];
}
/**
* Gets the ID of the next step.
*
* If the current step is not defined it's assumed that all steps have executed.
*
* @param array $form_state
* The Drupal form state.
* @param string $step_id
* The ID of the step relative to the result, if not provided the current
* step_id is used.
*
* @return string
* The next step ID if found, NULL otherwise.
*/
function islandora_ingest_form_get_next_step_id(array &$form_state, $step_id = NULL) {
$step_id = isset($step_id) ? $step_id : islandora_ingest_form_get_current_step_id($form_state);
$step_ids = array_keys(islandora_ingest_form_get_steps($form_state));
$index = array_search($step_id, $step_ids);
$count = count($step_ids);
if ($index !== FALSE && ++$index < $count) {
return $step_ids[$index];
}
return NULL;
}
/**
* Gets the ID of the previous step.
*
* If the current step is not defined it's assumed that all steps have executed.
* In such cases the last step will be returned.
*
* @param array $form_state
* The Drupal form state.
* @param string $step_id
* The ID of the step relative to the result, if not provided the current
* step_id is used.
*
* @return string
* The previous step ID if found, NULL otherwise.
*/
function islandora_ingest_form_get_previous_step_id(array &$form_state, $step_id = NULL) {
$step_id = isset($step_id) ? $step_id : islandora_ingest_form_get_current_step_id($form_state);
// If the current step is not defined it's assumed that all steps have
// executed. So return the very last step.
if ($step_id == NULL) {
return islandora_ingest_form_get_last_step_id($form_state);
}
$step_ids = array_keys(islandora_ingest_form_get_steps($form_state));
$index = array_search($step_id, $step_ids);
if ($index !== FALSE && --$index >= 0) {
return $step_ids[$index];
}
return NULL;
}
/**
* Increments the current step if possible.
*
* @param array $form_state
* The Drupal form state.
*/
function islandora_ingest_form_increment_step(array &$form_state) {
// When going to the next step rebuild the list of steps as the submit
// of the current step could have added/removed a step.
drupal_static_reset('islandora_ingest_form_get_steps');
$next_step_id = islandora_ingest_form_get_next_step_id($form_state);
islandora_ingest_form_stash_info($form_state);
$form_state['islandora']['step_id'] = $next_step_id;
islandora_ingest_form_grab_info($form_state);
}
/**
* Decrement the current step if possible.
*
* @param array $form_state
* The Drupal form state.
*/
function islandora_ingest_form_decrement_step(array &$form_state) {
$previous_step_id = islandora_ingest_form_get_previous_step_id($form_state);
// Don't decrement passed the first step.
if (isset($previous_step_id)) {
islandora_ingest_form_stash_info($form_state);
$form_state['islandora']['step_id'] = $previous_step_id;
islandora_ingest_form_grab_info($form_state);
}
}
/**
* Executes the current step.
*
* Builds the form definition and appends on any additonal elements required
* for the step to function.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*
* @return array
* The form definition of the current step.
*/
function islandora_ingest_form_execute_step(array $form, array &$form_state, $step_id = NULL) {
// Load any required files for the current step.
islandora_ingest_form_load_include($form_state);
$step = isset($step_id) ? islandora_ingest_form_get_step($form_state) : islandora_ingest_form_get_step($form_state, $step_id);
switch ($step['type']) {
case 'callback':
// Execute all the consecutive callbacks, and move then attempt to process
// the next step.
islandora_ingest_form_execute_consecutive_callback_steps($form, $form_state, $step);
return islandora_ingest_form_execute_step($form, $form_state);
case 'form':
return islandora_ingest_form_execute_form_step($form, $form_state, $step);
case 'batch':
// @todo Implement if possible.
break;
}
return array();
}
/**
* Execute the given 'form' step.
*
* Assumes the given step is a 'form' step.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*
* @return array
* The form definition of the given step.
*/
function islandora_ingest_form_execute_form_step(array $form, array &$form_state, array $step) {
$args = array($form, &$form_state);
$args = isset($step['args']) ? array_merge($args, $step['args']) : $args;
$shared_storage = islandora_ingest_form_get_shared_storage($form_state);
// Build the form step.
$form = call_user_func_array($step['form_id'], $args);
// Since the list of steps depends on the shared storage we will rebuild the
// list of steps if the shared storage has changed. This must be done before
// stepifying, so the prev/next buttons get updated.
if ($shared_storage != islandora_ingest_form_get_shared_storage($form_state)) {
drupal_static_reset('islandora_ingest_form_get_steps');
}
return islandora_ingest_form_stepify($form, $form_state, $step);
}
/**
* Execute the given 'callback' step and any consecutive 'callback' steps.
*
* Assumes the given step is a 'callback' step.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*/
function islandora_ingest_form_execute_consecutive_callback_steps(array $form, array &$form_state, array $step) {
do {
islandora_ingest_form_execute_callback_step($form, $form_state, $step);
islandora_ingest_form_increment_step($form_state);
$step = islandora_ingest_form_get_step($form_state);
} while (isset($step) && $step['type'] == 'callback');
}
/**
* Execute the given 'callback' step.
*
* Assumes the given step is a 'callback' step.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*/
function islandora_ingest_form_execute_callback_step(array $form, array &$form_state, array $step) {
$args = array(&$form_state);
$args = isset($step['do_function']['args']) ? array_merge($args, $step['do_function']['args']) : $args;
call_user_func_array($step['do_function']['function'], $args);
}
/**
* Undo the given 'callback' step and any consecutive 'callback' steps.
*
* Assumes the given $step is a 'callback' step.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*/
function islandora_ingest_form_undo_consecutive_callback_steps(array $form, array &$form_state, array $step) {
do {
islandora_ingest_form_undo_callback_step($form, $form_state, $step);
islandora_ingest_form_decrement_step($form_state);
$step = islandora_ingest_form_get_step($form_state);
} while (isset($step) && $step['type'] == 'callback');
}
/**
* Undo the given 'callback' step.
*
* Assumes the given $step is a 'callback' step.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*/
function islandora_ingest_form_undo_callback_step(array $form, array &$form_state, array $step) {
$args = array(&$form_state);
$args = isset($step['undo_function']['args']) ? array_merge($args, $step['undo_function']['args']) : $args;
call_user_func_array($step['undo_function']['function'], $args);
}
/**
* Append Prev/Next buttons submit/validation handlers etc.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*
* @return array
* The stepified Drupal form definition for the given step.
*/
function islandora_ingest_form_stepify(array $form, array &$form_state, $step) {
$first_form_step = islandora_ingest_form_on_first_form_step($form_state);
$last_form_step = islandora_ingest_form_on_last_form_step($form_state);
$form['form_step_id'] = array(
'#type' => 'hidden',
'#value' => islandora_ingest_form_get_current_step_id($form_state),
);
$form['prev'] = $first_form_step ? NULL : islandora_ingest_form_previous_button($form_state);
$form['next'] = $last_form_step ? islandora_ingest_form_ingest_button($form_state) : islandora_ingest_form_next_button($form_state);
// Allow for a hook_form_FORM_ID_alter().
drupal_alter(array('form_' . $step['form_id'], 'form'), $form, $form_state, $step['form_id']);
return $form;
}
/**
* Checks if we are on the first form step.
*
* @param array $form_state
* The Drupal form state.
*
* @return bool
* TRUE if we are currently on the first step, FALSE otherwise.
*/
function islandora_ingest_form_on_first_form_step(array &$form_state) {
return !islandora_ingest_form_get_previous_form_step($form_state);
}
/**
* Checks if we are on the last form step.
*
* @param array $form_state
* The Drupal form state.
*
* @return bool
* TRUE if we are currently on the last step, FALSE otherwise.
*/
function islandora_ingest_form_on_last_form_step(array &$form_state) {
return !islandora_ingest_form_get_next_form_step($form_state);
}
/**
* Get the previous form step relative to the current step.
*
* @param array $form_state
* The Drupal form state.
*
* @return array
* The previous form step if one exists, NULL otherwise.
*/
function islandora_ingest_form_get_previous_form_step(array &$form_state) {
$step = NULL;
do {
$step = islandora_ingest_form_get_previous_step($form_state, $step);
} while (isset($step) && $step['type'] != 'form');
return $step;
}
/**
* Get the next form step relative to the current step.
*
* @param array $form_state
* The Drupal form state.
*
* @return array
* The next form step if one exists, NULL otherwise.
*/
function islandora_ingest_form_get_next_form_step(array &$form_state) {
$step = NULL;
do {
$step = islandora_ingest_form_get_next_step($form_state, $step);
} while (isset($step) && $step['type'] != 'form');
return $step;
}
/**
* Defines the previous button for the ingest form.
*
* Adds submit handlers for the form step if they exist.
*
* @param array $form_state
* The Drupal form state.
*
* @return array
* The previous button for the ingest form.
*/
function islandora_ingest_form_previous_button(array &$form_state) {
// Before we move back to the previous step we should tell the previous steps
// to undo whatever its submit handler did.
$prev_form_step = islandora_ingest_form_get_previous_form_step($form_state);
$form_id = $prev_form_step['form_id'];
$submit_callback = $form_id . '_undo_submit';
$submit = function_exists($submit_callback) ? array('islandora_ingest_form_previous_submit', $submit_callback) : array('islandora_ingest_form_previous_submit');
return array(
'#type' => 'submit',
'#value' => t('Previous'),
'#name' => 'prev',
'#submit' => $submit,
// #limit_validation_errors, is why when the previous button is pressed no
// values persisted in the form_state, but its also what allows us to go
// back when validation errors occur. To have a better solution going
// forward we can either limit validation only on required fields, or we can
// convert all required fields to use #element_validation functions, and
// Remove the need for #limit_validation_errors. Or maybe there is some
// other solution, regardless of what it is, it won't be standard.
'#limit_validation_errors' => array(),
);
}
/**
* The submit handler for the ingest form previous button.
*
* Stores the current form steps values in the form storage.
* Moves the focus of the multi-page ingest form back one step.
* Restores the form values for the previous step.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*/
function islandora_ingest_form_previous_submit(array $form, array &$form_state) {
islandora_ingest_form_decrement_step($form_state);
$step = islandora_ingest_form_get_step($form_state);
// Undo all callbacks that occured after the previous step.
if ($step['type'] == 'callback') {
islandora_ingest_form_undo_consecutive_callback_steps($form, $form_state, $step);
}
$form_state['rebuild'] = TRUE;
}
/**
* Defines the next button for the ingest form.
*
* Adds submit/validate handlers for the form step if they exist.
*
* @param array $form_state
* The Drupal form state.
*
* @return array
* The next button for the ingest form.
*/
function islandora_ingest_form_next_button(array &$form_state) {
$step = islandora_ingest_form_get_step($form_state);
$form_id = $step['form_id'];
$validate_callback = $form_id . '_validate';
$validate = function_exists($validate_callback) ? array($validate_callback) : NULL;
$submit_callback = $form_id . '_submit';
$submit = function_exists($submit_callback) ? array($submit_callback, 'islandora_ingest_form_next_submit') : array('islandora_ingest_form_next_submit');
return array(
'#type' => 'submit',
'#value' => t('Next'),
'#name' => 'next',
'#validate' => $validate,
'#submit' => $submit,
);
}
/**
* The submit handler for the ingest form next button.
*
* Stores the current form steps values in the form storage.
* Moves the focus of the multi-page ingest form forward one step.
* Restores the form values for the next step if present.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*/
function islandora_ingest_form_next_submit(array $form, array &$form_state) {
islandora_ingest_form_increment_step($form_state);
$form_state['rebuild'] = TRUE;
}
/**
* Push current info into the current step's storage.
*
* @param array $form_state
* The Drupal form state.
*/
function islandora_ingest_form_stash_info(array &$form_state) {
$storage = &islandora_ingest_form_get_step_storage($form_state);
if ($storage && isset($form_state['values'])) {
$storage['values'] = $form_state['values'];
unset($form_state['values']);
}
}
/**
* Pops the info for the given step from storage into the form_state.
*
* @param array $form_state
* The Drupal form state.
*/
function islandora_ingest_form_grab_info(array &$form_state) {
$storage = islandora_ingest_form_get_step_storage($form_state);
$form_state['values'] = isset($storage['values']) ? $storage['values'] : array();
}
/**
* Defines the ingest button for the ingest form.
*
* This button is only shown on the last page of the multi-page ingest form.
*
* @param array $form_state
* The Drupal form state.
*
* @return array
* The ingest button for the ingest form.
*/
function islandora_ingest_form_ingest_button(array &$form_state) {
$step = islandora_ingest_form_get_step($form_state);
$form_id = $step['form_id'];
$validate_callback = $form_id . '_validate';
$validate = function_exists($validate_callback) ? array($validate_callback) : NULL;
$submit_callback = $form_id . '_submit';
$submit = function_exists($submit_callback) ? array($submit_callback, 'islandora_ingest_form_submit') : array('islandora_ingest_form_submit');
return array(
'#type' => 'submit',
'#name' => 'ingest',
'#value' => t('Ingest'),
'#validate' => $validate,
'#submit' => $submit,
);
}
/**
* The submit handler for the ingest form.
*
* Attempts to ingest every object built by the previous steps.
*
* @param array $form_state
* The Drupal form state.
*/
function islandora_ingest_form_submit(array $form, array &$form_state) {
// Execute any remaining callbacks.
islandora_ingest_form_increment_step($form_state);
$step = islandora_ingest_form_get_step($form_state);
if (isset($step) && $step['type'] == 'callback') {
islandora_ingest_form_execute_consecutive_callback_steps($form, $form_state, $step);
}
// Ingest the objects.
foreach ($form_state['islandora']['objects'] as $object) {
try {
islandora_add_object($object);
$form_state['redirect'] = "islandora/object/{$object->id}";
}
catch (Exception $e) {
// If post hooks throws it may already exist at this point but may be
// invalid, so don't say failed.
watchdog('islandora', 'Exception Message: @exception.', array('@exception' => $e->getMessage()), WATCHDOG_ERROR);
drupal_set_message(t('A problem occured while ingesting "@label" (ID: @pid), please notifiy the administrator.', array('@label' => $object->label, '@pid' => $object->id)), 'error');
}
}
}
/**
* Gets a reference to the stored NewFedoraObject's.
*
* @param array $form_state
* The Drupal form state.
*
* @return array
* A reference to the stored NewFedoraObjects to be ingested when the final
* step submits.
*/
function &islandora_ingest_form_get_objects(array &$form_state) {
return $form_state['islandora']['objects'];
}
/**
* Gets a single object from the stored NewFedoraObject's.
*
* @note In our current use case we are only dealing with a single object
* ingest, this makes it convenient to access it. Ideally the steps
* implementations will be abstracted to be indifferent to what object it's
* currently working on. This will act as a placeholder for such
* functionality.
*
* @param array $form_state
* The Drupal form state.
*
* @return NewFedoraObject
* Returns the 'current' object in the array of NewFedoraObjects, generally
* this is only used when there is one object in the list of objects.
*/
function islandora_ingest_form_get_object(array &$form_state) {
$objects = &islandora_ingest_form_get_objects($form_state);
return reset($objects);
}
/**
* Get general storage for the given/current step.
*
* @param array $form_state
* The Drupal form state.
* @param array $step_id
* The ID of the step.
*
* @return array
* The given/current step storage if found, NULL otherwise.
*/
function &islandora_ingest_form_get_step_storage(array &$form_state, $step_id = NULL) {
$step_id = isset($step_id) ? $step_id : islandora_ingest_form_get_current_step_id($form_state);
if (isset($step_id)) {
if (!isset($form_state['islandora']['step_storage'][$step_id])) {
$form_state['islandora']['step_storage'][$step_id] = array();
}
return $form_state['islandora']['step_storage'][$step_id];
}
$undefined_step_storage = array();
return $undefined_step_storage;
}
/**
* Gets the configuration used to create the multi-page ingest form.
*
* @param array $form_state
* The Drupal form state.
*
* @return array
* The configuration used to generate the multi-page ingest forms.
*/
function &islandora_ingest_form_get_shared_storage(array &$form_state) {
return $form_state['islandora']['shared_storage'];
}
/**
* Call form_load_include, for the current step if it defines a required file.
*
* @param array $form_state
* The Drupal form state.
*/
function islandora_ingest_form_load_include(array &$form_state) {
form_load_include($form_state, 'inc', 'islandora', 'includes/ingest.form');
$step = islandora_ingest_form_get_step($form_state);
// Load include files.
if (isset($step['file']) && isset($step['module'])) {
$matches = array();
preg_match('/^(.*)\.(.*)$/', $step['file'], $matches);
list($file, $name, $type) = $matches;
form_load_include($form_state, $type, $step['module'], $name);
}
}
/**
* Buildes the initial list of ingest steps.
*
* Sorted by weight expected range between -50 to 50.
*
* The sort order is undefined for steps which have the same weight.
*
* @param array $form_state
* The Drupal form state.
*
* @return array
* The list of sorted ingest steps as defined by all implementers
* of ISLANDORA_INGEST_STEP_HOOK.
*/
function islandora_ingest_form_get_steps(array &$form_state) {
module_load_include('inc', 'islandora', 'includes/utilities');
$steps = &drupal_static(__FUNCTION__);
if (isset($steps)) {
return $steps;
}
$steps = array();
$shared_storage = &islandora_ingest_form_get_shared_storage($form_state);
foreach (islandora_build_hook_list(ISLANDORA_INGEST_STEP_HOOK, $shared_storage['models']) as $hook) {
// Required for pass by reference.
// @todo Change this around so that it isn't passed by reference, there
// Is an alter below that can handle that requirement.
foreach (module_implements($hook) as $module) {
$function = $module . '_' . $hook;
$module_steps = (array) $function($form_state);
$steps = array_merge($steps, $module_steps);
}
}
$steps = array_filter($steps);
foreach (islandora_build_hook_list(ISLANDORA_INGEST_STEP_HOOK, $shared_storage['models']) as $hook) {
drupal_alter($hook, $steps, $form_state);
}
// Add any defaults.
foreach ($steps as $key => &$step) {
$step['id'] = $key;
}
uasort($steps, 'drupal_sort_weight');
return $steps;
}
/**
* Filter the ingest steps to only steps of type 'form'.
*
* @param array $form_state
* The Drupal form state.
*
* @return array
* The list of sorted ingest form steps as defined by all implementers
* of ISLANDORA_INGEST_STEP_HOOK.
*/
function islandora_ingest_form_get_form_steps(array &$form_state) {
$steps = islandora_ingest_form_get_steps($form_state);
$form_step_filter = function($o) {
return $o['type'] == 'form';
};
return array_filter($steps, $form_step_filter);
}
/**
* Filter the ingest steps to only steps of type 'form'.
*
* @param array $form_state
* The Drupal form state.
*
* @return array
* The list of sorted ingest callback steps as defined by all implementers
* of ISLANDORA_INGEST_STEP_HOOK.
*/
function islandora_ingest_form_get_callback_steps(array &$form_state) {
$steps = islandora_ingest_form_get_steps($form_state);
$callback_step_filter = function($o) {
return $o['type'] == 'callback';
};
return array_filter($steps, $callback_step_filter);
}

385
includes/mime_detect.inc

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

53
includes/object.entity_controller.inc

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

123
includes/object_properties.form.inc

@ -0,0 +1,123 @@
<?php
/**
* @file
* Contains admin form functions for editing an object's properties.
*/
/**
* Object properties admin form.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
* @param AbstractObject $object
* The object whose properties this form will modify.
*
* @return array
* The drupal form definition.
*/
function islandora_object_properties_form(array $form, array &$form_state, AbstractObject $object) {
drupal_set_title($object->label);
$form_state['object'] = $object;
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'),
),
'submit' => array(
'#type' => 'submit',
'#value' => 'Update Properties',
),
'delete' => array(
'#type' => 'submit',
'#access' => islandora_object_access(FEDORA_PURGE, $object),
'#value' => t('Delete'),
'#submit' => array('islandora_object_properties_form_delete'),
'#limit_validation_errors' => array(array('pid')),
),
);
}
/**
* Submit handler for object properties admin form.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*/
function islandora_object_properties_form_submit(array $form, array &$form_state) {
$object = $form_state['object'];
$owner = $form_state['values']['object_owner'];
$state = $form_state['values']['object_state'];
$label = $form_state['values']['object_label'];
if (isset($owner) && $owner != $object->owner) {
try {
$object->owner = $owner;
drupal_set_message(t('Successfully updated owner %s', array('%s' => $owner)));
}
catch (Exception $e) {
form_set_error('object_owner', t('Error updating owner %s', array('%s' => $e->getMessage())));
}
}
if (isset($state) && $state != $object->state) {
try {
$object->state = $state;
drupal_set_message(t('Successfully updated state %s', array('%s' => $state)));
}
catch (Exception $e) {
form_set_error('object_state', t('Error updating state %s', array('%s' => $e->getMessage())));
}
}
if (isset($label) && $label != $object->label) {
try {
$object->label = $label;
drupal_set_message(t('Successfully updated label %s', array('%s' => check_plain($label))));
}
catch (Exception $e) {
form_set_error(t('Error updating label %s', array('%s' => $e->getMessage())));
}
}
}
/**
* Callback function for object properties admin form delete button.
*
* @param array $form
* The Drupal form.
* @param array $form_state
* The Drupal form state.
*/
function islandora_object_properties_form_delete(array $form, array &$form_state) {
drupal_goto("islandora/object/{$form_state['values']['pid']}/delete");
}

695
includes/solution_packs.inc

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

115
includes/tuque.inc

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

358
includes/tuque_wrapper.inc

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

867
includes/utilities.inc

@ -0,0 +1,867 @@
<?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
*
* @return string
* Human readable size.
*/
function islandora_convert_bytes_to_human_readable($bytes, $precision = 2) {
$kilobyte = 1024;
$megabyte = $kilobyte * 1024;
$gigabyte = $megabyte * 1024;
$terabyte = $gigabyte * 1024;
if (($bytes >= 0) && ($bytes < $kilobyte)) {
return $bytes . ' B';
}
elseif (($bytes >= $kilobyte) && ($bytes < $megabyte)) {
return round($bytes / $kilobyte, $precision) . ' KB';
}
elseif (($bytes >= $megabyte) && ($bytes < $gigabyte)) {
return round($bytes / $megabyte, $precision) . ' MB';
}
elseif (($bytes >= $gigabyte) && ($bytes < $terabyte)) {
return round($bytes / $gigabyte, $precision) . ' GB';
}
elseif ($bytes >= $terabyte) {
return round($bytes / $terabyte, $precision) . ' TB';
}
else {
return $bytes . ' B';
}
}
/**
* Creates a label for control group symbols.
*/
function islandora_control_group_to_human_readable($control_group) {
switch ($control_group) {
case 'M':
return '<b>M</b>anaged';
case 'X':
return 'Inline <b>X</b>ML';
case 'R':
return '<b>R</b>edirect';
case 'E':
return '<b>E</b>xternally Referenced';
default:
return $control_group;
}
}
/**
* Checks if the given pid is valid.
*
* @param string $pid
* The object id to check.
*
* @return bool
* TRUE if valid, FALSE otherwise.
*/
function islandora_is_valid_pid($pid) {
return drupal_strlen(trim($pid)) <= 64 && preg_match('/^([A-Za-z0-9]|-|\.)+:(([A-Za-z0-9])|-|\.|~|_|(%[0-9A-F]{2}))+$/', trim($pid));
}
/**
* Checks if the given namespace is valid.
*
* @param string $namespace
* The namespace to check without the ":" character.
*
* @return bool
* TRUE if valid, FALSE otherwise.
*/
function islandora_is_valid_namespace($namespace) {
return drupal_strlen(trim($namespace)) <= 64 && preg_match('/^([A-Za-z0-9]|-|\.)+$/', trim($namespace));
}
/**
* Checks if the given datastream id is valid.
*
* @param string $dsid
* The datastream id to check.
*
* @return bool
* TRUE if valid, FALSE otherwise.
*/
function islandora_is_valid_dsid($dsid) {
return drupal_strlen(trim($dsid)) <= 64 && preg_match('/^[a-zA-Z0-9\_\-\.]+$/', trim($dsid));
}
/**
* Helper function to describe a Fedora repository.
*
* Can be used to check if Fedora is available.
*
* @param string $url
* A url to a Fedora repository, if NULL the default is used.
*
* @return array
* Returns an array describing the repository. Returns FALSE if Fedora is down
* or if the url is incorrect.
*/
function islandora_describe_repository($url = NULL) {
$url = isset($url) ? $url : variable_get('islandora_base_url', 'http://localhost:8080/fedora');
$connection = islandora_get_tuque_connection();
if ($connection) {
try {
$info = $connection->api->a->describeRepository();
return $info;
}
catch (RepositoryException $e) {
return FALSE;
}
}
return FALSE;
}
/**
* Build and invoke a list of hooks by combining the given hook and refinements.
*
* The given hook will be called as MODULE_HOOK, and for each hook refinement
* as MODULE_REFINEMENT_HOOK. Any additional arguments passed to this function
* will be passed as arguments to module_invoke_all().
*
* @see islandora_build_hook_list()
*
* @param string $hook
* A hook to call.
* @param array $refinements
* An array of strings, that will be escaped and concatinated with the given
* hook. This will most likely be PIDs/DSIDs/Labels etc. We often refine our
* hooks using an objects model.
* @param array $args
* Any arguments to pass onto module_invoke_all().
*
* @return array
* The merged results from all the hooks.
*/
function islandora_invoke_hook_list($hook, array $refinements, array $args) {
$return = array();
foreach (islandora_build_hook_list($hook, $refinements) as $hook) {
array_unshift($args, $hook);
$result = call_user_func_array('module_invoke_all', $args);
$return = array_merge_recursive($return, $result);
array_shift($args);
}
return $return;
}
/**
* Build a list of all the hooks to call.
*
* Concatenates each hook $refinement (escaped) to the hook name, for calling
* with module_invoke_all().
*
* Any non-valid PHP function characters in the given refinements are
* converted to "_" characters.
*
* @param string $hook
* The base hook to concatenate.
* @param array $refinements
* An array of strings, that will be escaped and concatinated with the given
* hook. This will most likely be PIDs/DSIDs/Labels etc. We often refine our
* hooks using an objects model.
*
* @return array
* An array with each refinement escaped and concatenated with the base hook
* name, in addition to the base hook name.
*/
function islandora_build_hook_list($hook, $refinements = array()) {
$refinements = array_unique($refinements);
$hooks = array($hook);
foreach ($refinements as $refinement) {
$refinement = preg_replace('/[^a-zA-Z0-9_]/', '_', $refinement);
$hooks[] = "{$refinement}_{$hook}";
}
return $hooks;
}
/**
* Escape a Fedora PID to be valid inside of a PHP function name.
*
* Originally intended to allow inclusion of a PID in a module_invoke_all()
* call.
*/
function islandora_escape_pid_for_function($pid) {
// Apparently, case doesn't matter for function calls in PHP, so let's not
// really worry about changing the case.
return str_replace(
// Any PID characters which are not valid in the name of a PHP function.
array(
':',
'-',
),
'_',
$pid
);
}
/**
* Gets the namespace of the given id.
*
* @param string $id
* Either a PID or namespace to check for accessibility. Any string like those
* below are fine.
*
* @code
* 'islandora',
* 'islandora:',
* 'islandora:1234',
* @endcode
*
* @return string
* The namespace portion of the given string.
*/
function islandora_get_namespace($id) {
$matches = array();
preg_match('/^([^:]*)/', $id, $matches);
return $matches[0];
}
/**
* Checks the given namespace/PID is/has an accessible namespace.
*
* Accessible is defined by the "islandora_pids_allowed" variable.
*
* @param string $id
* Either a PID or namespace to check for accessibility. Any string like those
* below are fine.
*
* @code
* 'islandora',
* 'islandora:',
* 'islandora:1234',
* @endcode
*
* @return bool
* TRUE if accessible, FALSE otherwise.
*/
function islandora_namespace_accessible($id) {
if (variable_get('islandora_namespace_restriction_enforced', FALSE)) {
$namespace = islandora_get_namespace($id);
$allowed_namespaces = islandora_get_allowed_namespaces();
return in_array($namespace, $allowed_namespaces);
}
return TRUE;
}
/**
* Gets any objects that the given object has a parent relationship with.
*
* Parent relationships are defined as (isMemberOf, isMemberOfCollection).
*
* This function gets its info from the RELS-EXT directly rather than through an
* risearch.
*
* @param AbstractObject $object
* The object whose parents will be returned.
*
* @return array
* An array of FedoraObject's that the given object has a
* (isMemberOf, isMemberOfCollection) relationship with.
*/
function islandora_get_parents_from_rels_ext(AbstractObject $object) {
try {
$collections = array_merge(
$object->relationships->get(FEDORA_RELS_EXT_URI, 'isMemberOfCollection'),
$object->relationships->get(FEDORA_RELS_EXT_URI, 'isMemberOf'));
}
catch (RepositoryException $e) {
// @todo some logging would be nice, not sure what this throws.
return array();
}
$map = function($o) {
return islandora_object_load($o['object']['value']);
};
$collections = array_map($map, $collections);
return array_filter($collections);
}
/**
* Gets the datastreams requirments that are missing.
*
* @param AbstractObject $object
* The object which models will be used to determine what datastreams it
* should have.
*
* @return array
* The DS-COMPOSITE-MODEL defined datastreams that are required for the given
* object, but not already present.
*/
function islandora_get_missing_datastreams_requirements(AbstractObject $object) {
module_load_include('inc', 'islandora', 'includes/utilities');
$datastreams = islandora_get_datastreams_requirements($object);
foreach ($datastreams as $dsid => $requirements) {
if (isset($object[$dsid])) {
unset($datastreams[$dsid]);
}
}
return $datastreams;
}
/**
* Gets the required datastreams for the given object.
*
* Checks the object's content model's for which datastream are expected to be
* used with this object, as defined by the DS-COMPOSITE-MODEL datastreams.
*
* For duplicate datastreams in the models, the first model defines the
* datastreams attributes regardless of what other models define.
* This should be undefined behavior according to the documentation.
*
* @link https://wiki.duraspace.org/display/FEDORA34/Fedora+Digital+Object+Model#FedoraDigitalObjectModel-ContentModelObjectCMODEL @endlink
*
* @see islandora_get_required_datastreams_from_content_model()
*
* @param AbstractObject $object
* The object which models will be used to determine what datastreams it
* should have.
*
* @return array
* The DS-COMPOSITE-MODEL defined datastreams that are required for the given
* object.
*/
function islandora_get_datastreams_requirements(AbstractObject $object) {
return islandora_get_datastreams_requirements_from_models($object->models);
}
/**
* Get the list of which datastreams are valid in the given set of models.
*
* @param array $models
* An array of content models PIDs from which to parse the DS-COMPOSITE-MODEL
* stream.
*
* @return array
* An associative array of associative arrays, merged from calls to
* islandora_get_datastreams_requirements_from_content_model().
*/
function islandora_get_datastreams_requirements_from_models(array $models) {
$dsids = array();
foreach ($models as $model_pid) {
$model = islandora_object_load($model_pid);
if (isset($model) && $model) {
$dsids += islandora_get_datastreams_requirements_from_content_model($model);
}
}
// The AUDIT Datastream can not really be added, so it can't really be
// missing.
unset($dsids['AUDIT']);
return $dsids;
}
/**
* Checks the given content model for which datastreams are required.
*
* As defined by it's DS-COMPOSITE-MODEL datastream.
*
* @todo Add support for fetching the schema information.
*
* @param AbstractObject $object
* The content model whose DS-COMPOSITE-MODEL datastream will be used to
* determine what datastreams are required.
*
* @return array
* An associative array mapping datastream IDs to associative arrays
* containing the values parsed from the DS-COMPOSITE-MODEL on the given
* object--of the form:
* - DSID: A datastream ID being described.
* - "id": A string containing ID of the datastream.
* - "mime": A array containing MIME-types the stream may have.
* - "optional": A boolean indicating if the given stream is optional.
*/
function islandora_get_datastreams_requirements_from_content_model(AbstractObject $object) {
if (empty($object[DS_COMP_STREAM]) || !islandora_datastream_access(FEDORA_VIEW_OBJECTS, $object[DS_COMP_STREAM])) {
return array();
}
$xml = new SimpleXMLElement($object[DS_COMP_STREAM]->content);
foreach ($xml->dsTypeModel as $ds) {
$dsid = (string) $ds['ID'];
$optional = strtolower((string) $ds['optional']);
$mime = array();
foreach ($ds->form as $form) {
$mime[] = (string) $form['MIME'];
}
$dsids[$dsid] = array(
'id' => $dsid,
'mime' => $mime,
'optional' => ($optional == 'true') ? TRUE : FALSE,
);
}
return $dsids;
}
/**
* Prepare an ingestable object.
*
* @param string $namespace
* The namespace in which the PID for the new object will be created.
* @param string $label
* An optional label to apply to the object.
* @param array $datastreams
* A array of datastreams to add, where each datastream definition is an
* associative array containing:
* - dsid: The datastream ID.
* - label: An optional label for the datastream.
* - mimetype: A MIMEtype for the datastream; defaults to text/xml.
* - control_group: One of X, M, R and E; defaults to M.
* - datastream_file: A web-accessible path, for which we try to get an
* absolute path using url().
* @param array $content_models
* An array of content model PIDs to which the new object should subscribe.
* @param array $relationships
* An array of relationships, where each relationship is an associative array
* containing:
* - relationship: The predicate for the relationship, from the Fedora
* RELS-EXT namespace.
* - pid: The object for the relationship, to which we are creating the
* relationhsip.
*
* @return NewFedoraObject
* An ingestable NewFedoraObject.
*/
function islandora_prepare_new_object($namespace = NULL, $label = NULL, $datastreams = array(), $content_models = array(), $relationships = array()) {
global $user;
$tuque = islandora_get_tuque_connection();
$object = isset($namespace) ? $tuque->repository->constructObject($namespace) : new IslandoraNewFedoraObject(NULL, $tuque->repository);
$object->owner = isset($user->name) ? $user->name : $object->owner;
$object->label = isset($label) ? $label : $object->label;
foreach ($content_models as $content_model) {
$object->relationships->add(FEDORA_MODEL_URI, 'hasModel', $content_model);
}
foreach ($relationships as $relationship) {
$object->relationships->add(FEDORA_RELS_EXT_URI, $relationship['relationship'], $relationship['pid']);
}
foreach ($datastreams as $ds) {
$dsid = $ds['dsid'];
$label = isset($ds['label']) ? $ds['label'] : '';
$mimetype = isset($ds['mimetype']) ? $ds['mimetype'] : 'text/xml';
// Default 'Managed'
$control_group = 'M';
$groups = array('X', 'M', 'R', 'E');
if (isset($ds['control_group']) && in_array($ds['control_group'], $groups)) {
$control_group = $ds['control_group'];
}
$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(check_plain($message), 'error', FALSE);
}
/**
* Create a message stating if the given executable is available.
*
* If the both the version and required version are given then only if the
* version is equal to or greater than the required version the executable
* will be considered correct.
*
* @param string $path
* The absolute path to an executable to check for availability.
* @param string $version
* The version of exectuable.
* @param string $required_version
* The required version of exectuable.
*
* @return string
* A message in html detailing if the given executable is accessible.
*/
function islandora_executable_available_message($path, $version = NULL, $required_version = NULL) {
$available = is_executable($path);
if ($available) {
$image = theme_image(array('path' => 'misc/watchdog-ok.png', 'attributes' => array()));
$message = t('Executable found at @path', array('@path' => $path));
if ($version) {
$message .= t('<br/>Version: @version', array('@version' => $version));
}
if ($required_version) {
$message .= t('<br/>Required Version: @version', array('@version' => $required_version));
if (version_compare($version, $required_version) < 0) {
$image = theme_image(array('path' => 'misc/watchdog-error.png', 'attributes' => array()));
}
}
}
else {
$image = theme_image(array('path' => 'misc/watchdog-error.png', 'attributes' => array()));
$message = t('Unable to locate executable at @path', array('@path' => $path));
}
return $image . $message;
}
/**
* Create a message stating if the given directory exists.
*
* @param string $path
* The absolute path to an executable to check for availability.
*
* @return string
* A message in HTML detailing if the given directory is exists.
*/
function islandora_directory_exists_message($path) {
$available = is_dir($path);
if ($available) {
$image = theme_image(array('path' => 'misc/watchdog-ok.png', 'attributes' => array()));
$message = t('Directory found at @path', array('@path' => $path));
}
else {
$image = theme_image(array('path' => 'misc/watchdog-error.png', 'attributes' => array()));
$message = t('Unable to locate directory at @path', array('@path' => $path));
}
return $image . $message;
}
/**
* Gets the default value for the given system_settings_form() element.
*
* Checks the $form_state for the default value if not it checks
* variable_get(). Assumes #tree is FALSE. This is only really required
* for elements that utilize AJAX, as their value can change before the
* submit actually takes place.
*
* @param string $name
* The name of the system settings form element.
* @param mixed $default_value
* The default value for the system settings form element.
* @param array $form_state
* The Drupal form state.
*
* @return mixed
* The default value for use in a the system_settings_form().
*/
function islandora_system_settings_form_default_value($name, $default_value, array &$form_state) {
return isset($form_state['values'][$name]) ? $form_state['values'][$name] : variable_get($name, $default_value);
}
/**
* Returns basic information about DS-COMPOSITE-MODEL.
*
* @deprecated
* The pre-existing--and more flexible--
* islandora_get_datastreams_requirements_from_content_model() should be
* preferred, as it addresses the case where a stream can be allowed to have
* one of a set of mimetypes (this functions appears to only return the last
* declared mimetype for a given datastream).
*
* @param string $pid
* The PID of content model containing DS_COMP stream.
*
* @return array
* An associative array mapping datastream IDs to an associative array
* representing the parsed DS-COMPOSITE-MODEL of the form:
* - DSID: A string containing the datastream ID.
* - "mimetype": A string containing the last mimetype declared for the
* given datastream ID.
* - "optional": An optional boolean indicating that the given datastream
* is optional.
*/
function islandora_get_comp_ds_mappings($pid) {
$message = islandora_deprecated('7.x-1.2', t('Refactor to use the more flexible islandora_get_datastreams_requirements_from_content_model().'));
trigger_error(filter_xss($message), E_USER_DEPRECATED);
$cm_object = islandora_object_load($pid);
if (!isset($cm_object) || !isset($cm_object['DS-COMPOSITE-MODEL'])) {
return FALSE;
}
$datastream = $cm_object['DS-COMPOSITE-MODEL'];
$ds_comp_stream = $datastream->content;
$sxml = new SimpleXMLElement($ds_comp_stream);
$mappings = array();
foreach ($sxml->dsTypeModel as $ds) {
$dsid = (string) $ds['ID'];
$optional = (string) $ds['optional'];
foreach ($ds->form as $form) {
$mime = (string) $form['MIME'];
if ($optional) {
$mappings[$dsid]['optional'] = $optional;
}
$mappings[$dsid]['mimetype'] = $mime;
}
}
return $mappings;
}
/**
* Checks that the given/current account has all the given permissions.
*
* @param array $perms
* The permissions to check.
* @param mixed $account
* (optional) The account to check, if not given use currently logged in user.
*
* @return bool
* TRUE if the account has all the given permissions, FALSE otherwise.
*/
function islandora_user_access_all(array $perms, $account = NULL) {
$message = islandora_deprecated('7.x-1.2', 'Roll your own code or use islandora_user_access().');
trigger_error(filter_xss($message), E_USER_DEPRECATED);
foreach ($perms as $perm) {
if (!user_access($perm, $account)) {
return FALSE;
}
}
return TRUE;
}
/**
* Checks that the given/current account has at one of the given permissions.
*
* @param array $perms
* The permissions to check.
* @param mixed $account
* (optional) The account to check, if not given use currently logged in user.
*
* @return bool
* TRUE if the account has at least one of the given permissions, FALSE
* otherwise.
*/
function islandora_user_access_any(array $perms, $account = NULL) {
$message = islandora_deprecated('7.x-1.2', 'Roll your own code or use islandora_user_access().');
trigger_error(filter_xss($message), E_USER_DEPRECATED);
foreach ($perms as $perm) {
if (user_access($perm, $account)) {
return TRUE;
}
}
return FALSE;
}
/**
* Gets the list of allowed namespaces as defined by 'islandora_pids_allowed'.
*
* @return array
* The list of namespaces striped of trailing ":" characters.
*/
function islandora_get_allowed_namespaces() {
$matches = array();
$allowed_namespaces = variable_get('islandora_pids_allowed', 'default: demo: changeme: islandora:');
preg_match_all('/([A-Za-z0-9-\.]+):/', $allowed_namespaces, $matches);
$accessible_namespaces = $matches[1];
// Ensure that the "islandora" namespace is explicitly allowed
// no matter what happens.
if (!in_array('islandora', $accessible_namespaces)) {
$accessible_namespaces[] = 'islandora';
}
return $accessible_namespaces;
}
/**
* Gets a list of all existing content models.
*
* If 'islandora_namespace_restriction_enforced' is set to true only return
* content models in the allowed namespace.
*
* @param bool $ignore_system_namespace
* Ignore content models in the 'fedora-system' namespace.
*
* @return array
* An associative array of all existing content models.
* - pid: The PID of the content model object.
* - pid: The PID of the content model object.
* - label: The label of the content model object.
*/
function islandora_get_content_models($ignore_system_namespace = TRUE) {
module_load_include('inc', 'islandora', 'includes/utilities');
$tuque = islandora_get_tuque_connection();
$query = "PREFIX fm: <" . FEDORA_MODEL_URI . ">
PREFIX fr: <" . FEDORA_RELS_EXT_URI . ">
SELECT ?object ?label
FROM <#ri>
WHERE {
{?object fm:hasModel <info:fedora/fedora-system:ContentModel-3.0>;
fm:state fm:Active
}
UNION{
?object fr:isMemberOfCollection <info:fedora/islandora:ContentModelsCollection>;
fm:state fm:Active
}
OPTIONAL{
?object fm:label ?label
}
}";
$content_models = array();
$results = $tuque->repository->ri->sparqlQuery($query, 'unlimited');
foreach ($results as $result) {
$content_model = $result['object']['value'];
$label = $result['label']['value'];
$namespace = islandora_get_namespace($content_model);
$ignore = $ignore_system_namespace && $namespace == 'fedora-system';
$ignore |= !islandora_namespace_accessible($namespace);
if (!$ignore) {
$content_models[$content_model] = array('pid' => $content_model, 'label' => $label);
}
}
return $content_models;
}
/**
* Returns Drupal tableselect element allowing selection of Content Models.
*
* @param string $drupal_variable
* the name of the Drupal variable holding selected content models
* Content models held in this variable will appear at the top of
* the displayed list
* @param array $default_values_array
* default values to display if $drupal_variable is unset
*
* @return array
* Drupal form element allowing content model selection
*/
function islandora_content_model_select_table_form_element($drupal_variable, $default_values_array = array('')) {
$defaults = array();
$rows = array();
$content_models = array();
$options = islandora_get_content_models(TRUE);
foreach ($options as $option) {
$content_models[$option['pid']] = $option['label'];
}
$selected = array_values(variable_get($drupal_variable, $default_values_array));
$comparator = function ($a, $b) use ($selected) {
$a_val = $b_val = 0;
if (in_array($a, $selected)) {
$a_val = 1;
}
if (in_array($b, $selected)) {
$b_val = 1;
}
return $b_val - $a_val;
};
uksort($content_models, $comparator);
foreach ($content_models as $pid => $label) {
$rows[$pid] = array(
'pid' => $pid,
'title' => $label,
);
$defaults[$pid] = in_array($pid, $selected);
}
$header = array(
'pid' => array('data' => t('PID')),
'title' => array('data' => t('Content Model')),
);
// Build and return table element.
$element = array(
'#type' => 'tableselect',
'#header' => $header,
'#options' => $rows,
'#default_value' => $defaults,
'#empty' => t("There are no content models in this Fedora Repository."),
);
return $element;
}
/**
* Convience function for generating a E_USER_DEPRECATED message.
*
* To utilitize this function pass the results to trigger_error() like so:
*
* @code
* $message = islandora_deprecated('7.x-1.1', t('Use more cowbell.'))
* trigger_error(filter_xss($message), E_USER_DEPRECATED)
* @endcode
*
* @param string $release
* The release the calling function was depreciated in.
* @param string $solution
* A message describing an alternative solution to the deprecated function.
* It's assumed to be already passed though the t() function.
*
* @return string
* The deprecated message.
*/
function islandora_deprecated($release, $solution = NULL) {
$bt = debug_backtrace();
assert($bt[0]['function'] == __FUNCTION__);
$function = $bt[1]['function'];
$message = t('@function() has been deprecated. As of @release, please update your code before the next release.', array(
'@function' => $function,
'@release' => $release,
));
if (isset($solution)) {
$message .= "<br/>\n" . $solution;
}
return $message;
}

521
islandora.api.php

@ -0,0 +1,521 @@
<?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) {
}
/**
* 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 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 management 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_edit_object($object) {
}
/**
* Allow management display output to be altered.
*
* @param AbstractObject $object
* A Tuque FedoraObject
* @param array $rendered
* an arr of rendered views
*/
function hook_islandora_edit_object_alter(&$object, &$rendered) {
}
/**
* Allows modules to alter the object or block/modify the given action.
*
* This alter hook will be called before any object is ingested, modified or
* purged.
*
* Changing object properties such as "label", or "state", are considered
* modifications, where as manipulating an object's datstreams are not.
*
* @param AbstractObject $object
* The object to alter.
* @param array $context
* An associative array containing:
* - action: A string either 'ingest', 'purge', 'modify'.
* - block: Either TRUE or FALSE, if TRUE the action won't take place.
* Defaults to FALSE.
* - purge: Either TRUE or FALSE, only present when the action is 'purge'.
* If 'delete' or 'block' is set to TRUE, they will take precedence.
* Defaults to TRUE.
* - delete: Either TRUE or FALSE, only present when the action is 'purge'.
* If TRUE it will cause the object's state to be set to 'D' instead.
* If 'block' is set to TRUE, it will take precedence.
* Defaults to FALSE,
* - params: An associative array, only present when the action is 'modify'.
* The key value pairs repersent what values will be changed. The params
* will match the same params as passed to FedoraApiM::modifyObject().
*
* @see FedoraApiM::modifyObject()
*/
function hook_islandora_object_alter(AbstractObject $object, array &$context) {
}
/**
* Allows modules to alter the object or block/modify the given action.
*
* @see hook_islandora_object_alter()
*/
function hook_CMODEL_PID_islandora_object_alter(AbstractObject $object, array &$context) {
}
/**
* Allows modules to alter the datastream or block/modify the given action.
*
* This alter hook will be called before any datastream is ingested, modified or
* purged.
*
* Adding datastreams to NewFedoraObject's will not trigger this alter hook
* immediately, instead it will be triggered for all datastreams at the time
* of the NewFedoraObject's ingest.
*
* Purging datastreams from a AbstractObject will not trigger this alter hook
* at all.
*
* Changing datastream's properties such as "label", or "state", are considered
* modifications, as well as changing the datastreams content.
*
* @param AbstractObject $object
* The object to the datastream belong to.
* @param AbstractDatastream $datastream
* The datastream to alter.
* @param array $context
* An associative array containing:
* - action: A string either 'ingest', 'purge', 'modify'.
* - block: Either TRUE or FALSE, if TRUE the action won't take place.
* Defaults to FALSE.
* - purge: Either TRUE or FALSE, only present when the action is 'purge'.
* If 'delete' or 'block' is set to TRUE, they will take precedence.
* Defaults to TRUE.
* - delete: Either TRUE or FALSE, only present when the action is 'purge'.
* If TRUE it will cause the object's state to be set to 'D' instead.
* If 'block' is set to TRUE, it will take precedence.
* Defaults to FALSE,
* - params: An associative array, only present when the action is 'modify'.
* The key value pairs repersent what values will be changed. The params
* will match the same params as passed to FedoraApiM::modifyDatastream().
*
* @see FedoraApiM::modifyDatastream()
*/
function hook_islandora_datastream_alter(AbstractObject $object, AbstractDatastream $datastream, array &$context) {
}
/**
* Allows modules to alter the datastream or block/modify the given action.
*
* @see hook_islandora_datastream_alter()
*/
function hook_CMODEL_PID_DSID_islandora_datastream_alter(AbstractObject $object, AbstractDatastream $datastream, array &$context) {
}
/**
* Notify modules that the given object was ingested.
*
* This hook is called after an object has been successfully ingested via a
* FedoraRepository object.
*
* @note
* If ingested directly via the FedoraApiM object this will not be called as we
* don't have access to the ingested object at that time.
*
* @param AbstractObject $object
* The object that was ingested.
*/
function hook_islandora_object_ingested(AbstractObject $object) {
}
/**
* Notify modules that the given object was ingested.
*
* @see hook_islandora_object_ingested()
*/
function hook_CMODEL_PID_islandora_object_ingested(AbstractObject $object) {
}
/**
* Notify modules that the given object was modified.
*
* This hook is called after an object has been successfully modified.
*
* Changing object properties such as "label", or "state", are considered
* modifications, where as manipulating an object's datstreams are not.
*
* @param AbstractObject $object
* The object that was ingested.
*
* @todo We should also include what changes were made in a additional
* parameter.
*/
function hook_islandora_object_modified(AbstractObject $object) {
}
/**
* Notify modules that the given object was ingested.
*
* @see hook_islandora_object_modified()
*/
function hook_CMODEL_PID_islandora_object_modified(AbstractObject $object) {
}
/**
* Notify modules that the given object was purged/deleted.
*
* This hook is called after an object has been successfully purged, or
* when its state has been changed to "Deleted".
*
* @param string $pid
* The ID of the object that was purged/deleted.
*/
function hook_islandora_object_purged($pid) {
}
/**
* Notify modules that the given object was purged/deleted.
*
* @see hook_islandora_object_purged()
*/
function hook_CMODEL_PID_islandora_object_purged($pid) {
}
/**
* Notify modules that the given datastream was ingested.
*
* This hook is called after the datastream has been successfully ingested.
*
* @note
* If ingested directly via the FedoraApiM object this will not be called as we
* don't have access to the ingested datastream at that time.
*
* @param AbstractObject $object
* The object the datastream belongs to.
* @param AbstractDatastream $datastream
* The ingested datastream.
*/
function hook_islandora_datastream_ingested(AbstractObject $object, AbstractDatastream $datastream) {
}
/**
* Notify modules that the given datastream was ingested.
*
* @see hook_islandora_object_ingested()
*/
function hook_CMODEL_PID_DSID_islandora_datastream_ingested(AbstractObject $object, AbstractDatastream $datastream) {
}
/**
* Notify modules that the given datastream was modified.
*
* This hook is called after an datastream has been successfully modified.
*
* Changing datastream properties such as "label", or "state", are considered
* modifications, as well as the datastreams content.
*
* @param AbstractObject $object
* The object the datastream belongs to.
* @param AbstractDatastream $datastream
* The datastream that was ingested.
*
* @todo We should also include what changes were made in a additional
* parameter.
*/
function hook_islandora_datastream_modified(AbstractObject $object, AbstractDatastream $datastream) {
}
/**
* Notify modules that the given datastream was modified.
*
* @see hook_islandora_datastream_modified()
*/
function hook_CMODEL_PID_islandora_datastream_modified(AbstractObject $object, AbstractDatastream $datastream) {
}
/**
* Notify modules that the given datastream was purged/deleted.
*
* This hook is called after an datastream has been successfully purged, or
* when its state has been changed to "Deleted".
*
* @param AbstractObject $object
* The object the datastream belonged to.
* @param string $dsid
* The ID of the datastream that was purged/deleted.
*/
function hook_islandora_datastream_purged(AbstractObject $object, $dsid) {
}
/**
* Notify modules that the given datastream was purged/deleted.
*
* @see hook_islandora_datastream_purged()
*/
function hook_CMODEL_PID_islandora_datastream_purged(AbstractObject $object, $dsid) {
}
/**
* Register a datastream edit route/form.
*
* @param AbstractObject $object
* The object to check.
* @param string $dsid
* todo
*/
function hook_islandora_edit_datastream_registry($object, $dsid) {
}
/**
* Registry hook for required objects.
*
* Solution packs can include data to create certain objects that describe or
* help the objects it would create. This includes collection objects and
* content models.
*
* @see islandora_solution_packs_admin()
* @see islandora_install_solution_pack()
* @example islandora_islandora_required_objects()
*/
function hook_islandora_required_objects() {
}
/**
* Registry hook for viewers that can be implemented by solution packs.
*
* Solution packs can use viewers for their data. This hook lets Islandora know
* which viewers there are available.
*
* @see islandora_get_viewers()
* @see islandora_get_viewer_callback()
*/
function hook_islandora_viewer_info() {
}
/**
* Returns a list of datastreams that are determined to be undeletable.
*/
function hook_islandora_undeletable_datastreams(array $models) {
}
/**
* Define steps used in the islandora_ingest_form() ingest process.
*
* @param array $form_state
* An array containing the form_state, on which infomation from step storage
* might be extracted. Note that the
*
* @return array
* An associative array of associative arrays which define each step in the
* ingest process. Each step should consist of a unique name mapped to an
* array of properties (keys) which take different paramaters based upon type:
* - type: Type of step. Only "form" and "callback" are implemented so far.
* Required "form" type specific parameters:
* - form_id: The form building function to call to get the form structure
* for this step.
* - args: An array of arguments to pass to the form building function.
* Required "callback" type specific parameters:
* - do_function: An associate array including:
* - 'function': The callback function to be called.
* - 'args': An array of arguments to pass to the callback function.
* - undo_function: An associate array including:
* - 'function': The callback function to be called to reverse the
* executed action in the ingest steps.
* - 'args': An array of arguments to pass to the callback function.
* 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'),
),
),
);
}
/**
* 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) {
}
/**
* 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
* 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.
*/
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
* 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.
*/
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) {
}

20
islandora.info

@ -0,0 +1,20 @@
name = Islandora
description = "View and manage Fedora objects"
package = Islandora
version = 7.x-1.2
core = 7.x
configure = admin/islandora/configure
stylesheets[all][] = css/islandora.base.css
stylesheets[all][] = css/islandora.theme.css
files[] = includes/mime_detect.inc
files[] = includes/dublin_core.inc
files[] = includes/tuque.inc
files[] = includes/tuque_wrapper.inc
files[] = includes/object.entity_controller.inc
files[] = tests/islandora_web_test_case.inc
files[] = tests/authtokens.test
files[] = tests/hooks.test
files[] = tests/ingest.test
files[] = tests/hooked_access.test
files[] = tests/islandora_manage_permissions.test
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

283
islandora.install

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

5
islandora.libraries.yml

@ -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

1745
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'

118
islandora.rules.inc

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

80
islandora.services.yml

@ -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',
],
];
}

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;
}
}

294
modules/islandora_advanced_search/src/AdvancedSearchQueryTerm.php

@ -1,294 +0,0 @@
<?php
namespace Drupal\islandora_advanced_search;
use Drupal\islandora_advanced_search\Form\AdvancedSearchForm;
/**
* Defines a single search term.
*
* Used for parsing query parameters as well as form submission and generating
* search queries.
*/
class AdvancedSearchQueryTerm {
// Conjunctions.
// @see https://lucene.apache.org/solr/guide/7_1/the-standard-query-parser.html#TheStandardQueryParser-BooleanOperatorsSupportedbytheStandardQueryParser
const CONJUNCTION_AND = 'AND';
const CONJUNCTION_OR = 'OR';
// Used for serializing / deserializing query parameters.
// These are also hard-coded in islandora_advanced_search.form.js.
const CONJUNCTION_QUERY_PARAMETER = 'c';
const FIELD_QUERY_PARAMETER = 'f';
const INCLUDE_QUERY_PARAMETER = 'i';
const VALUE_QUERY_PARAMETER = 'v';
// Defaults.
const DEFAULT_CONJUNCTION = self::CONJUNCTION_AND;
const DEFAULT_INCLUDE = TRUE;
/**
* The field to search.
*
* @var string
*/
protected $field;
/**
* Include / exclude results where 'value' is in the 'search' term.
*
* @var bool
*/
protected $include = TRUE;
/**
* The value to filter with.
*
* @var string
*/
protected $value;
/**
* The conjunction to use for the condition group – either 'AND' or 'OR'.
*
* @var string
*/
protected $conjunction;
/**
* Constructs a FacetBlockAjaxController object.
*
* @param string $field
* The field to search against.
* @param string $value
* The value to search the field with.
* @param bool $include
* Limit results to records whose field contains or does not contain the
* given value.
* @param string $conjunction
* The conjunction to apply when combining this search term along with
* others.
*/
public function __construct(string $field, string $value, bool $include = self::DEFAULT_INCLUDE, string $conjunction = self::DEFAULT_CONJUNCTION) {
$this->field = $field;
$this->value = $value;
switch ($conjunction) {
case self::CONJUNCTION_AND:
case self::CONJUNCTION_OR:
$this->conjunction = $conjunction;
break;
default:
throw new \InvalidArgumentException('Invalid value given for argument "conjunction": $conjunction');
}
if ($this->conjunction == self::CONJUNCTION_OR && !$include) {
throw new \InvalidArgumentException('Excluding terms with the conjunction "OR" is not supported');
}
$this->include = $include;
}
/**
* Validate 'include' or fallback to default value.
*
* @param string $include
* The value to cast to a boolean if possible.
*
* @return bool
* The normalized input for 'include' or its default.
*/
protected static function normalizeInclude(string $include) {
switch (strtoupper($include)) {
case AdvancedSearchForm::IS_OP:
return TRUE;
case AdvancedSearchForm::NOT_OP:
return FALSE;
default:
$include = filter_var($include, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
// Ignore include parameter if invalid and fallback to the default.
return is_bool($include) ? $include : self::DEFAULT_INCLUDE;
}
}
/**
* Validate 'conjunction' or fallback to default value.
*
* @param string $conjunction
* The conjunction to validate.
*
* @return string
* The normalized input for 'include' or its default.
*/
protected static function normalizeConjunction(string $conjunction) {
switch (strtoupper($conjunction)) {
case self::CONJUNCTION_AND:
return self::CONJUNCTION_AND;
case self::CONJUNCTION_OR:
return self::CONJUNCTION_OR;
default:
return self::DEFAULT_CONJUNCTION;
}
}
/**
* Creates a AdvancedSearchQueryTerm from the given parameters if possible.
*
* @param array $params
* An array representing the query parameters for a single search term.
*
* @return \Drupal\islandora_advanced_search\AdvancedSearchQueryTerm|null
* An object which represents a valid search term.
*/
public static function fromQueryParams(array $params) {
// Field & value are required values. We do not check if field is a valid
// value only that it is non-empty. All other fields will be cast to
// defaults if they are not valid / missing.
$has_required_params = isset($params[self::FIELD_QUERY_PARAMETER], $params[self::VALUE_QUERY_PARAMETER]);
$search_value_empty = isset($params[self::VALUE_QUERY_PARAMETER]) && empty($params[self::VALUE_QUERY_PARAMETER]);
if (!$has_required_params || $search_value_empty) {
return NULL;
}
$field = $params[self::FIELD_QUERY_PARAMETER];
$value = $params[self::VALUE_QUERY_PARAMETER];
$include = isset($params[self::INCLUDE_QUERY_PARAMETER]) ?
$include = self::normalizeInclude($params[self::INCLUDE_QUERY_PARAMETER]) :
self::DEFAULT_INCLUDE;
$conjunction = isset($params[self::CONJUNCTION_QUERY_PARAMETER]) ?
self::normalizeConjunction($params[self::CONJUNCTION_QUERY_PARAMETER]) :
self::DEFAULT_CONJUNCTION;
return new self($field, $value, $include, $conjunction);
}
/**
* Creates a AdvancedSearchQueryTerm from user submitted form values.
*
* @param array $input
* An array representing the submitted form values for a single search term.
*
* @return \Drupal\islandora_advanced_search\AdvancedSearchQueryTerm|null
* An object which represents a valid search term.
*/
public static function fromUserInput(array $input) {
// Search field & value are required values we do not check if field is a
// valid value only that it is non-empty. All other fields will use
// defaults if they are not valid / missing.
$has_required_inputs = isset($input[AdvancedSearchForm::SEARCH_FORM_FIELD], $input[AdvancedSearchForm::VALUE_FORM_FIELD]);
$search_value_empty = isset($input[AdvancedSearchForm::VALUE_FORM_FIELD]) && empty($input[AdvancedSearchForm::VALUE_FORM_FIELD]);
if (!$has_required_inputs || $search_value_empty) {
return NULL;
}
$field = $input[AdvancedSearchForm::SEARCH_FORM_FIELD];
$value = $input[AdvancedSearchForm::VALUE_FORM_FIELD];
$include = self::DEFAULT_INCLUDE;
$conjunction = self::DEFAULT_CONJUNCTION;
if (isset($input[AdvancedSearchForm::CONJUNCTION_FORM_FIELD])) {
switch ($input[AdvancedSearchForm::CONJUNCTION_FORM_FIELD]) {
case AdvancedSearchForm::AND_OP:
$conjunction = self::CONJUNCTION_AND;
break;
case AdvancedSearchForm::OR_OP:
$conjunction = self::CONJUNCTION_OR;
break;
}
}
// Only allow users to specify include when using 'AND' conjunction.
if (
$conjunction == self::CONJUNCTION_AND
&& isset($input[AdvancedSearchForm::INCLUDE_FORM_FIELD])
) {
switch ($input[AdvancedSearchForm::INCLUDE_FORM_FIELD]) {
case AdvancedSearchForm::IS_OP:
$include = TRUE;
break;
case AdvancedSearchForm::NOT_OP:
$include = FALSE;
break;
}
}
return new self($field, $value, $include, $conjunction);
}
/**
* Get query parameter representation of this search term.
*
* @return array
* Representation of this search term which can be serialized to a query
* parameter.
*/
public function toQueryParams() {
$params = [
self::FIELD_QUERY_PARAMETER => $this->field,
self::VALUE_QUERY_PARAMETER => $this->value,
];
// No need to specify conjunction if it is equivalent to the default.
if ($this->conjunction != self::DEFAULT_CONJUNCTION) {
$params[self::CONJUNCTION_QUERY_PARAMETER] = $this->conjunction;
}
if ($this->include != self::DEFAULT_CONJUNCTION) {
$params[self::INCLUDE_QUERY_PARAMETER] = $this->include ? '1' : '0';
}
return $params;
}
/**
* Get user input of search form representation of this search term.
*
* @return array
* Representation of this search term which can be used as input to the
* advanced search form.
*/
public function toUserInput() {
return [
AdvancedSearchForm::SEARCH_FORM_FIELD => $this->field,
AdvancedSearchForm::VALUE_FORM_FIELD => $this->value,
AdvancedSearchForm::INCLUDE_FORM_FIELD => $this->include ? AdvancedSearchForm::IS_OP : AdvancedSearchForm::NOT_OP,
AdvancedSearchForm::CONJUNCTION_FORM_FIELD => $this->conjunction == self::CONJUNCTION_AND ? AdvancedSearchForm::AND_OP : AdvancedSearchForm::OR_OP,
];
}
/**
* Gets if this term should be included / excluded from results.
*
* @return bool
* TRUE if the term should be include in results, FALSE otherwise.
*/
public function getInclude() {
return $this->include;
}
/**
* Gets the conjunction for this term.
*
* @return string
* The conjunction to use for this term.
*/
public function getConjunction() {
return $this->conjunction;
}
/**
* Using the provided field mapping create a Solr Query string.
*
* @param array $solr_field_mapping
* An array that maps search api fields to one or more solr fields.
*
* @return string
* The conjunction to use for this term conjunction.
*/
public function toSolrQuery(array $solr_field_mapping) {
$terms = [];
$query_helper = \Drupal::service('solarium.query_helper');
$value = $query_helper->escapePhrase(trim($this->value));
foreach ($solr_field_mapping[$this->field] as $field) {
$terms[] = "$field:$value";
}
$terms = implode(' ', $terms);
return $this->include ? "($terms)" : "-($terms)";
}
}

165
modules/islandora_advanced_search/src/Controller/AjaxBlocksController.php

@ -1,165 +0,0 @@
<?php
namespace Drupal\islandora_advanced_search\Controller;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Path\CurrentPathStack;
use Drupal\Core\PathProcessor\PathProcessorManager;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Routing\CurrentRouteMatch;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\RouterInterface;
/**
* Defines a controller to load a facet via AJAX.
*/
class AjaxBlocksController extends ControllerBase {
/**
* The entity storage for block.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $storage;
/**
* The renderer.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* The current path.
*
* @var \Drupal\Core\Path\CurrentPathStack
*/
protected $currentPath;
/**
* The dynamic router service.
*
* @var \Symfony\Component\Routing\Matcher\RequestMatcherInterface
*/
protected $router;
/**
* The path processor service.
*
* @var \Drupal\Core\PathProcessor\InboundPathProcessorInterface
*/
protected $pathProcessor;
/**
* The current route match service.
*
* @var \Drupal\Core\Routing\CurrentRouteMatch
*/
protected $currentRouteMatch;
/**
* The service container this instance should use.
*
* @var \Symfony\Component\DependencyInjection\ContainerInterface
*/
protected $container;
/**
* Constructs a FacetBlockAjaxController object.
*
* @param \Drupal\Core\Render\RendererInterface $renderer
* The renderer service.
* @param \Drupal\Core\Path\CurrentPathStack $currentPath
* The current path service.
* @param \Symfony\Component\Routing\RouterInterface $router
* The router service.
* @param \Drupal\Core\PathProcessor\PathProcessorManager $pathProcessor
* The path processor manager.
* @param \Drupal\Core\Routing\CurrentRouteMatch $currentRouteMatch
* The current route match service.
* @param \Symfony\Component\DependencyInjection\ContainerInterface $container
* The drupal container.
*/
public function __construct(RendererInterface $renderer, CurrentPathStack $currentPath, RouterInterface $router, PathProcessorManager $pathProcessor, CurrentRouteMatch $currentRouteMatch, ContainerInterface $container) {
$this->storage = $this->entityTypeManager()->getStorage('block');
$this->renderer = $renderer;
$this->currentPath = $currentPath;
$this->router = $router;
$this->pathProcessor = $pathProcessor;
$this->currentRouteMatch = $currentRouteMatch;
$this->container = $container;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('renderer'),
$container->get('path.current'),
$container->get('router'),
$container->get('path_processor_manager'),
$container->get('current_route_match'),
$container
);
}
/**
* Loads and renders the facet blocks via AJAX.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The current request object.
*
* @return \Drupal\Core\Ajax\AjaxResponse
* The ajax response.
*
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
* Thrown when the view was not found.
*/
public function respond(Request $request) {
$response = new AjaxResponse();
// Rebuild the request and the current path, needed for facets.
$path = $request->request->get('link');
$blocks = $request->request->get('blocks');
// Make sure we are not updating blocks multiple times.
$blocks = array_unique($blocks);
if (empty($path) || empty($blocks)) {
throw new NotFoundHttpException('No facet link or facet blocks found.');
}
$new_request = Request::create($path);
$request_stack = new RequestStack();
$processed = $this->pathProcessor->processInbound($new_request->getPathInfo(), $new_request);
$this->currentPath->setPath($processed);
$request->attributes->add($this->router->matchRequest($new_request));
$this->currentRouteMatch->resetRouteMatch();
$request_stack->push($new_request);
$this->container->set('request_stack', $request_stack);
// Build the facets blocks found for the current request and update.
foreach ($blocks as $block_id => $block_selector) {
$block_entity = $this->storage->load($block_id);
if ($block_entity) {
// Render a block, then add it to the response as a replace command.
$block_view = $this->entityTypeManager
->getViewBuilder('block')
->view($block_entity);
$block_view = (string) $this->renderer->renderPlain($block_view);
$response->addCommand(new ReplaceCommand($block_selector, $block_view));
}
}
return $response;
}
}

423
modules/islandora_advanced_search/src/Form/AdvancedSearchForm.php

@ -1,423 +0,0 @@
<?php
namespace Drupal\islandora_advanced_search\Form;
use Drupal\Component\Utility\Html;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\islandora_advanced_search\AdvancedSearchQuery;
use Drupal\islandora_advanced_search\AdvancedSearchQueryTerm;
use Drupal\islandora_advanced_search\GetConfigTrait;
use Drupal\views\DisplayPluginCollection;
use Drupal\views\Entity\View;
use Drupal\views\Plugin\views\display\PathPluginBase;
use Drupal\views\Views;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Form for building and Advanced Search Query.
*/
class AdvancedSearchForm extends FormBase {
use GetConfigTrait;
// Users can customize the operator to use font-awesome or some other icons.
// Its a limitation in the use of `input type=submit` rather than buttons in
// Drupal that we couldn't just rely on CSS.
// This is exposed in the module settings.
// @see https://www.drupal.org/project/drupal/issues/1671190
const DEFAULT_ADD_OP = '+';
const DEFAULT_REMOVE_OP = '-';
const AND_OP = 'AND';
const IS_OP = 'IS';
const NOT_OP = 'NOT';
const OR_OP = 'OR';
// These are also hard-coded in islandora_advanced_search.form.js.
const CONJUNCTION_FORM_FIELD = 'conjunction';
const SEARCH_FORM_FIELD = 'search';
const INCLUDE_FORM_FIELD = 'include';
const VALUE_FORM_FIELD = 'value';
const AJAX_WRAPPER = 'advanced-search-ajax';
/**
* The current request.
*
* @var \Symfony\Component\HttpFoundation\Request
*/
protected $request;
/**
* The current route match.
*
* @var \Drupal\Core\Routing\RouteMatchInterface
*/
protected $currentRouteMatch;
/**
* Class constructor.
*/
public function __construct(Request $request, RouteMatchInterface $current_route_match) {
$this->request = $request;
$this->currentRouteMatch = $current_route_match;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('request_stack')->getMainRequest(),
$container->get('current_route_match')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'islandora_advanced_search_form';
}
/**
* Get the character to use for adding a facet to the query.
*
* @return string
* The character to use for adding an facet to the query.
*/
public static function getAddOperator() {
return self::getConfig(SettingsForm::SEARCH_ADD_OPERATOR, self::DEFAULT_ADD_OP);
}
/**
* Get the character to use for removing a facet from the query.
*
* @return string
* The character to use for removing an facet to the query.
*/
public static function getRemoveOperator() {
return self::getConfig(SettingsForm::SEARCH_REMOVE_OPERATOR, self::DEFAULT_REMOVE_OP);
}
/**
* Convert the list of fields to select options.
*
* @param \Drupal\search_api\Item\FieldInterface[] $fields
* The fields to convert to select options.
*
* @return array
* Array of fields which can be searched where the key is the search field
* identifier and the value is its human readable label.
*/
protected function fieldOptions(array $fields) {
$options = [];
foreach ($fields as $field) {
$id = $field->getFieldIdentifier();
$options[$id] = $field->getLabel();
}
return $options;
}
/**
* Gets possible include options for the given conjunction.
*/
protected function includeOptions(string $conjunction) {
switch ($conjunction) {
case self::AND_OP:
return;
case self::OR_OP:
return [
self::IS_OP => $this->t('is'),
];
}
}
/**
* Default values to for a term.
*/
protected function defaultTermValues(array $options) {
return [
self::CONJUNCTION_FORM_FIELD => self::AND_OP,
// First item in list is default.
self::SEARCH_FORM_FIELD => key($options),
self::INCLUDE_FORM_FIELD => self::IS_OP,
self::VALUE_FORM_FIELD => NULL,
];
}
/**
* Process input to the from either URL parameters or from the form input.
*/
protected function processInput(FormStateInterface $form_state, array $term_default_values) {
$input = $form_state->getUserInput();
$recursive = isset($input['recursive']) ? $input['recursive'] : NULL;
$term_values = isset($input['terms']) && is_array($input['terms']) ? $input['terms'] : [];
// Form was not submitted see if we can rebuild from query parameters.
$advanced_search_query = new AdvancedSearchQuery();
if (empty($term_values)) {
$terms = $advanced_search_query->getTerms($this->request);
foreach ($terms as $term) {
$term_values[] = $term->toUserInput();
}
}
if (!isset($input['recursive'])) {
$recursive = $advanced_search_query->shouldRecurse($this->request);
}
// Form was submitted via +/- operators.
$trigger = $form_state->getTriggeringElement();
if ($trigger != NULL) {
$term_index = $trigger['#term_index'] ?? 0;
$value = $trigger['#value'] instanceof TranslatableMarkup ?
$trigger['#value']->getUntranslatedString() :
$trigger['#value'];
switch ($value) {
case $this->getAddOperator():
// Insert after the term listed.
array_splice($term_values, $term_index + 1, 0, [$term_default_values]);
break;
case $this->getRemoveOperator():
array_splice($term_values, $term_index, 1);
break;
case "Reset":
$recursive = FALSE;
$term_values = [];
break;
// Ignore unknown value for trigger.
}
// Place user input with updated values.
$input['terms'] = $term_values;
$input['recursive'] = $recursive;
$form_state->setUserInput($input);
}
return [$recursive, $term_values];
}
/**
* Gets the route name for the view display used to derive this forms block.
*
* @return string|null
* The route name for the view display that was used to create this
* forms block.
*/
protected function getRouteName(FormStateInterface $form_state) {
$view = $form_state->get('view');
$display = $form_state->get('display');
$display_handlers = new DisplayPluginCollection($view->getExecutable(), Views::pluginManager('display'));
$display_handler = $display_handlers->get($display['id']);
if ($display_handler instanceof PathPluginBase) {
return $display_handler->getRouteName();
}
return NULL;
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, View $view = NULL, array $display = [], array $fields = [], string $context_filter = NULL) {
// Keep reference to view and display as the submit handler may use them
// to redirect the user to the search page.
$form_state->set('view', $view);
$form_state->set('display', $display);
$route_name = $this->getRouteName($form_state);
$requires_redirect = $route_name ? $this->currentRouteMatch->getRouteName() !== $route_name : FALSE;
$form['#attached']['library'][] = 'islandora_advanced_search/advanced.search.form';
$form['#attached']['drupalSettings']['islandora_advanced_search_form'] = [
'id' => Html::getId($this->getFormId()),
'redirect' => $requires_redirect,
'query_parameter' => AdvancedSearchQuery::getQueryParameter(),
'recurse_parameter' => AdvancedSearchQuery::getRecurseParameter(),
'mapping' => [
self::CONJUNCTION_FORM_FIELD => AdvancedSearchQueryTerm::CONJUNCTION_QUERY_PARAMETER,
self::SEARCH_FORM_FIELD => AdvancedSearchQueryTerm::FIELD_QUERY_PARAMETER,
self::INCLUDE_FORM_FIELD => AdvancedSearchQueryTerm::INCLUDE_QUERY_PARAMETER,
self::VALUE_FORM_FIELD => AdvancedSearchQueryTerm::VALUE_QUERY_PARAMETER,
],
];
$options = $this->fieldOptions($fields);
$term_default_values = $this->defaultTermValues($options);
list($recursive, $term_values) = $this->processInput($form_state, $term_default_values);
$i = 0;
$term_elements = [];
$total_terms = count($term_values);
$block_class_prefix = str_replace('_', '-', $this->getFormId());
do {
// Either specified by the user in the request or use the default.
$first = $i == 0;
$term_value = !empty($term_values) ? array_shift($term_values) : $term_default_values;
$conjunction = isset($term_value[self::CONJUNCTION_FORM_FIELD]) ? $term_value[self::CONJUNCTION_FORM_FIELD] : $term_default_values[self::CONJUNCTION_FORM_FIELD];
$term_elements[] = [
// Only show on terms after the first.
self::CONJUNCTION_FORM_FIELD => $first ? NULL : [
'#type' => 'select',
'#options' => [
self::AND_OP => $this->t('and'),
self::OR_OP => $this->t('or'),
],
'#default_value' => $conjunction,
],
self::SEARCH_FORM_FIELD => [
'#type' => 'select',
'#options' => $options,
'#default_value' => $term_value[self::SEARCH_FORM_FIELD],
],
self::INCLUDE_FORM_FIELD => [
'#type' => 'select',
'#options' => [
self::IS_OP => $this->t('is'),
self::NOT_OP => $this->t('is not'),
],
'#default_value' => $term_value[self::INCLUDE_FORM_FIELD],
// Show only when conjunction is 'AND' as 'OR NOT' is not supported
// by solr and will be converted to 'AND NOT'.
'#states' => [
'visible' => [
':input[name="terms[' . $i . '][' . self::CONJUNCTION_FORM_FIELD . ']"]' => ['value' => self::AND_OP],
],
],
],
// Just markup to show when 'include' is not alterable due to the
// selected 'conjunction'. Hide for the first term.
'is' => $first ? NULL : [
'#type' => 'container',
'#attributes' => ['style' => 'display:inline;'],
'#states' => [
'visible' => [
':input[name="terms[' . $i . '][' . self::CONJUNCTION_FORM_FIELD . ']"]' => ['value' => self::OR_OP],
],
],
'content' => [
'#markup' => $this->t('is'),
],
],
self::VALUE_FORM_FIELD => [
'#type' => 'textfield',
'#default_value' => $term_value[self::VALUE_FORM_FIELD],
],
'actions' => [
'#type' => 'container',
'add' => [
'#type' => 'button',
'#value' => $this->getAddOperator(),
'#name' => 'add-term-' . $i,
'#term_index' => $i,
'#attributes' => [
'class' => [$block_class_prefix . '__add', 'fa'],
],
'#ajax' => [
'callback' => [$this, 'ajaxCallback'],
'wrapper' => self::AJAX_WRAPPER,
'progress' => [
'type' => 'none',
],
],
],
'remove' => $total_terms <= 1 ? NULL : [
'#type' => 'button',
'#value' => $this->getRemoveOperator(),
'#name' => 'remove-term-' . $i,
'#term_index' => $i,
'#attributes' => [
'class' => [$block_class_prefix . '__remove', 'fa'],
],
'#ajax' => [
'callback' => [$this, 'ajaxCallback'],
'wrapper' => self::AJAX_WRAPPER,
'progress' => [
'type' => 'none',
],
],
],
],
];
$i++;
} while (!empty($term_values));
$form['ajax'] = [
'#type' => 'container',
'#attributes' => ['id' => self::AJAX_WRAPPER],
'terms' => array_merge([
'#tree' => TRUE,
'#type' => 'container',
], $term_elements),
];
if ($context_filter != NULL) {
$form['ajax']['recursive'] = [
'#type' => 'checkbox',
'#title' => $this->t('Include Sub-Collections'),
'#default_value' => $recursive,
];
}
$form['reset'] = [
'#type' => 'button',
'#value' => $this->t('Reset'),
'#attributes' => [
'class' => [$block_class_prefix . '__reset'],
],
'#ajax' => [
'callback' => [$this, 'ajaxCallback'],
'wrapper' => self::AJAX_WRAPPER,
'progress' => [
'type' => 'none',
],
],
];
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Search'),
'#attributes' => [
'class' => [$block_class_prefix . '__search'],
],
];
return $form;
}
/**
* Builds an Advanced Search Query Url from the submitted form values.
*/
protected function buildUrl(FormStateInterface $form_state) {
$terms = [];
$values = $form_state->getValues();
foreach ($values['terms'] as $term) {
$terms[] = AdvancedSearchQueryTerm::fromUserInput($term);
}
$terms = array_filter($terms);
$recurse = filter_var(isset($values['recursive']) ? $values['recursive'] : FALSE, FILTER_VALIDATE_BOOLEAN);
$route = $this->getRouteName($form_state);
$advanced_search_query = new AdvancedSearchQuery();
return $advanced_search_query->toUrl($this->request, $terms, $recurse, $route);
}
/**
* Callback for adding / removing terms from the search.
*/
public function ajaxCallback(array &$form, FormStateInterface $form_state) {
return $form['ajax'];
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$trigger = (string) $form_state->getTriggeringElement()['#value'];
switch ($trigger) {
case $this->t('Search'):
$form_state->setRedirectUrl($this->buildUrl($form_state));
break;
default:
$form_state->setRebuild();
}
}
}

122
modules/islandora_advanced_search/src/Form/SettingsForm.php

@ -1,122 +0,0 @@
<?php
namespace Drupal\islandora_advanced_search\Form;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\islandora_advanced_search\AdvancedSearchQuery;
use Drupal\islandora_advanced_search\GetConfigTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Config form for Islandora Advanced Search settings.
*/
class SettingsForm extends ConfigFormBase {
use GetConfigTrait;
const CONFIG_NAME = 'islandora_advanced_search.settings';
const SEARCH_QUERY_PARAMETER = 'search_query_parameter';
const SEARCH_RECURSIVE_PARAMETER = 'search_recursive_parameter';
const SEARCH_ADD_OPERATOR = 'search_add_operator';
const SEARCH_REMOVE_OPERATOR = 'search_remove_operator';
const FACET_TRUNCATE = 'facet_truncate';
/**
* Constructs a \Drupal\system\ConfigFormBase object.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The factory for configuration objects.
*/
public function __construct(ConfigFactoryInterface $config_factory) {
$this->setConfigFactory($config_factory);
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container->get('config.factory'));
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'islandora_advanced_search_settings_form';
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return [
self::CONFIG_NAME,
];
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form += [
'search' => [
'#type' => 'fieldset',
'#title' => $this->t('Advanced Search'),
self::SEARCH_QUERY_PARAMETER => [
'#type' => 'textfield',
'#title' => $this->t('Search Query Parameter'),
'#description' => $this->t('The url parameter in which the advanced search query is stored.'),
'#default_value' => AdvancedSearchQuery::getQueryParameter(),
],
self::SEARCH_RECURSIVE_PARAMETER => [
'#type' => 'textfield',
'#title' => $this->t('Recurse Query Parameter'),
'#description' => $this->t('The url parameter which can toggle recursive search.'),
'#default_value' => AdvancedSearchQuery::getRecurseParameter(),
],
self::SEARCH_ADD_OPERATOR => [
'#type' => 'textfield',
'#title' => $this->t('Facet Add Operator'),
'#description' => $this->t('Users can customize the operator for adding facets to use font-awesome or some other icon, etc.'),
'#default_value' => AdvancedSearchForm::getAddOperator(),
],
self::SEARCH_REMOVE_OPERATOR => [
'#type' => 'textfield',
'#title' => $this->t('Facet Remove Operator'),
'#description' => $this->t('Users can customize the operator for removing facets to use font-awesome or some other icon, etc.'),
'#default_value' => AdvancedSearchForm::getRemoveOperator(),
],
],
'facets' => [
'#type' => 'fieldset',
'#title' => $this->t('Facets'),
self::FACET_TRUNCATE => [
'#type' => 'number',
'#title' => $this->t('Truncate Facet'),
'#description' => $this->t('Optionally truncate the length of facets titles in the display. If unspecified they will not be truncated.'),
'#default_value' => self::getConfig(self::FACET_TRUNCATE, 32),
'#min' => 1,
],
],
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$config = $this->configFactory->getEditable(self::CONFIG_NAME);
$config
->set(self::SEARCH_QUERY_PARAMETER, $form_state->getValue(self::SEARCH_QUERY_PARAMETER))
->set(self::SEARCH_RECURSIVE_PARAMETER, $form_state->getValue(self::SEARCH_RECURSIVE_PARAMETER))
->set(self::SEARCH_ADD_OPERATOR, $form_state->getValue(self::SEARCH_ADD_OPERATOR))
->set(self::SEARCH_REMOVE_OPERATOR, $form_state->getValue(self::SEARCH_REMOVE_OPERATOR))
->set(self::FACET_TRUNCATE, $form_state->getValue(self::FACET_TRUNCATE))
->save();
parent::submitForm($form, $form_state);
}
}

24
modules/islandora_advanced_search/src/GetConfigTrait.php

@ -1,24 +0,0 @@
<?php
namespace Drupal\islandora_advanced_search;
use Drupal\islandora_advanced_search\Form\SettingsForm;
/**
* Simple trait for accessing this modules configuration.
*/
trait GetConfigTrait {
/**
* Get a config setting or returns a default.
*
* @return string
* The config setting or default value.
*/
protected static function getConfig($config, $default) {
$settings = \Drupal::config(SettingsForm::CONFIG_NAME);
$value = $settings->get($config);
return !empty($value) ? $value : $default;
}
}

394
modules/islandora_advanced_search/src/Plugin/Block/AdvancedSearchBlock.php

@ -1,394 +0,0 @@
<?php
namespace Drupal\islandora_advanced_search\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\search_api\Display\DisplayPluginManager;
use Drupal\views\Entity\View;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Provides an Islandora Advanced Search block.
*
* @Block(
* id = "islandora_advanced_search_block",
* deriver = "Drupal\islandora_advanced_search\Plugin\Block\AdvancedSearchBlockDeriver",
* admin_label = @Translation("Islandora Advanced Search"),
* category = @Translation("Islandora"),
* )
*/
class AdvancedSearchBlock extends BlockBase implements ContainerFactoryPluginInterface {
use ViewAndDisplayIdentifiersTrait;
// CSS classes used to bind table-drag behavior to.
const WEIGHT_FIELD_CLASS = 'field-weight';
const DISPLAY_FIELD_CLASS = 'field-display';
// Regions in the table which denote if a given field
// is visible in the Advanced Search Form or not.
const REGION_VISIBLE = 'visible';
const REGION_HIDDEN = 'hidden';
// Keys for settings.
const SETTING_FIELDS = 'fields';
const SETTING_CONTEXTUAL_FILTER = 'context_filter';
/**
* The display plugin manager.
*
* @var \Drupal\search_api\Display\DisplayPluginManager
*/
protected $displayPluginManager;
/**
* The clone of the current request object.
*
* @var \Symfony\Component\HttpFoundation\Request
*/
protected $request;
/**
* The view this block affects.
*
* @var \Drupal\views\Entity\View
*/
protected $view;
/**
* The view display this block affects.
*
* @var array
*/
protected $display;
/**
* Form Builder.
*
* @var \Drupal\Core\Form\FormBuilderInterface
*/
protected $formBuilder;
/**
* Construct a AdvancedSearchBlock instance.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param string $plugin_definition
* The plugin implementation definition.
* @param \Drupal\search_api\Display\DisplayPluginManager $display_plugin_manager
* The display plugin manager.
* @param \Drupal\Core\Form\FormBuilderInterface $form_builder
* The form builder service used to build the search form.
* @param \Symfony\Component\HttpFoundation\Request $request
* A request object for the current request.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, DisplayPluginManager $display_plugin_manager, FormBuilderInterface $form_builder, Request $request) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->displayPluginManager = $display_plugin_manager;
list($view_id, $display_id) = preg_split('/__/', $this->getDerivativeId(), 2);
$this->view = View::Load($view_id);
$this->display = $this->view->getDisplay($display_id);
$this->formBuilder = $form_builder;
$this->request = clone $request;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('plugin.manager.search_api.display'),
$container->get('form_builder'),
$container->get('request_stack')->getMainRequest()
);
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
self::SETTING_FIELDS => [],
self::SETTING_CONTEXTUAL_FILTER => NULL,
];
}
/**
* Fields which can be enabled / disabled for display in the search form.
*
* @return \Drupal\search_api\Item\FieldInterface[]
* The $fields sorted by label.
*/
protected function getFields() {
$fields = $this->getIndex()->getFields();
// First pass sort on label, secondary sort will be used
// when looking at existing configuration for this block.
uasort($fields, function ($a, $b) {
return strcmp($a->getLabel(), $b->getLabel());
});
return $fields;
}
/**
* Get regions of table to display.
*
* @return array
* The properties of each region used for building the table of fields.
*/
protected function getRegions() {
// Classes for select fields like 'weight' and 'display' are hard-coded
// and used in js/islandora-advanced-search.admin.js.
return [
'visible' => [
'title' => $this->t('Visible'),
'invisible' => TRUE,
'message' => $this->t('No search field is visible.'),
'weight' => self::WEIGHT_FIELD_CLASS . '-visible',
'display' => self::DISPLAY_FIELD_CLASS . '-visible',
],
'hidden' => [
'title' => $this->t('Hidden'),
'invisible' => FALSE,
'message' => $this->t('No search field is hidden.'),
'weight' => self::WEIGHT_FIELD_CLASS . '-hidden',
'display' => self::DISPLAY_FIELD_CLASS . '-hidden',
],
];
}
/**
* Options for field display derived from the available regions.
*
* @return array
* Display select field options.
*/
protected function getDisplayOptions() {
$options = [];
foreach ($this->getRegions() as $region => $settings) {
$options[$region] = $settings['title'];
}
return $options;
}
/**
* {@inheritdoc}
*/
public function blockForm($form, FormStateInterface $form_state) {
// At most we will have one row per field.
$fields = $this->getFields();
$weight_delta = round(count($fields) / 2);
// Group each field into a region given our current configuration.
$visible_fields = $this->configuration[self::SETTING_FIELDS];
$regions = $this->getRegions();
$display_options = $this->getDisplayOptions();
// Field rows are grouped by the region in which they are displayed.
$field_rows = array_fill_keys(array_keys($regions), []);
foreach ($fields as $field) {
// If a field exists in the blocks configuration than it is 'visible' and
// its weight is equivalent to its order in the configuration,
// i.e. its index.
$identifier = $field->getFieldIdentifier();
$weight = array_search($identifier, $visible_fields);
$visible = $weight !== FALSE;
$region = $visible ? self::REGION_VISIBLE : self::REGION_HIDDEN;
$field_rows[$region][$identifier] = [
'#attributes' => [
'class' => ['draggable'],
],
'label' => ['#plain_text' => $field->getLabel()],
'identifier' => ['#plain_text' => $identifier],
'weight' => [
'#type' => 'weight',
'#title' => $this->t('Weight'),
'#title_display' => 'invisible',
'#default_value' => $visible ? $weight : 0,
'#delta' => $weight_delta,
'#attributes' => [
'class' => [self::WEIGHT_FIELD_CLASS, $regions[$region]['weight']],
],
],
'display' => [
'#type' => 'select',
'#title' => $this->t('Display'),
'#title_display' => 'invisible',
'#options' => $display_options,
'#default_value' => $region,
'#attributes' => [
'class' => [self::DISPLAY_FIELD_CLASS, $regions[$region]['display']],
],
],
];
}
// Sort the visible rows by their weight.
uasort($field_rows[self::REGION_VISIBLE], function ($a, $b) {
$a = $a['weight']['#default_value'];
$b = $b['weight']['#default_value'];
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
});
// Build Rows.
$rows = [];
$table_drag = [];
foreach ($regions as $region => $properties) {
$rows += [
// Conditionally display region title as a row.
"region-$region" => $properties['invisible'] ? NULL : [
'#attributes' => [
'class' => ['region-title', "region-title-$region"],
],
'label' => [
'#plain_text' => $properties['title'],
'#wrapper_attributes' => [
'colspan' => 4,
],
],
],
// Will dynamically display if the region has fields or not controlled
// by Drupal behaviors in js/islandora-advanced-search.admin.js.
"region-$region-message" => [
'#attributes' => [
'class' => [
'region-message',
"region-$region-message",
empty($field_rows[$region]) ? 'region-empty' : 'region-populated',
],
],
'message' => [
'#markup' => '<em>' . $properties['message'] . '</em>',
'#wrapper_attributes' => [
'colspan' => 4,
],
],
],
];
// Include field rows in this region.
$rows += $field_rows[$region];
// Configure order by weight field in region.
$table_drag[] = [
'action' => 'order',
'relationship' => 'sibling',
'group' => self::WEIGHT_FIELD_CLASS,
'subgroup' => $properties['weight'],
'source' => self::WEIGHT_FIELD_CLASS,
];
// Configure drag action for display field in region.
$table_drag[] = [
'action' => 'match',
'relationship' => 'sibling',
'group' => self::DISPLAY_FIELD_CLASS,
'subgroup' => $properties['display'],
'source' => self::DISPLAY_FIELD_CLASS,
];
}
$form[self::SETTING_FIELDS] = [
'#type' => 'table',
'#attributes' => [
// Identifier is hard-coded and used in
// js/islandora-advanced-search.admin.js.
'id' => 'advanced-search-fields',
],
'#header' => [
$this->t('Label'),
$this->t('Field'),
$this->t('Weight'),
$this->t('Display'),
],
'#empty' => $this->t('No search fields, please check search index configuration.'),
'#tabledrag' => $table_drag,
] + $rows;
// If there is contextual filters associated with the display that means
// we can filter on collection / sub-collection. Allow the user to choose
// which filters collections.
$id = NULL;
$field = NULL;
$options = [];
if (isset($this->display['display_options']['arguments'])) {
foreach ($this->display['display_options']['arguments'] as $context_filter) {
$id = $context_filter['id'];
$field = $context_filter['field'];
if (isset($fields[$field])) {
$options[$id] = $fields[$field]->getLabel() . ':' . $id;
}
}
}
if (count($options) > 1) {
$form[self::SETTING_CONTEXTUAL_FILTER] = [
'#type' => 'select',
'#title' => $this->t('Context Filter'),
'#description' => $this->t('If more than one <strong>Context Filter</strong> is defined, specify which is used to <strong>include</strong> only <strong>direct children</strong> of the Collection as it will disabled to allow recursive searching.'),
'#options' => $options,
'#default_value' => $this->configuration[self::SETTING_CONTEXTUAL_FILTER],
'#multiple' => FALSE,
'#required' => TRUE,
'#size' => count($options) + 1,
];
}
$form['#attributes']['class'][] = 'clearfix';
$form['#attached']['library'][] = 'islandora_advanced_search/advanced.search.admin';
return $form;
}
/**
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state) {
$values = $form_state->getValues();
$fields = array_filter($values[self::SETTING_FIELDS], function ($field) {
return $field['display'] == 'visible';
});
uasort($fields, '\Drupal\Component\Utility\SortArray::sortByWeightElement');
$this->configuration[self::SETTING_FIELDS] = array_keys($fields);
if (isset($values[self::SETTING_CONTEXTUAL_FILTER])) {
$this->configuration[self::SETTING_CONTEXTUAL_FILTER] = $values[self::SETTING_CONTEXTUAL_FILTER];
}
}
/**
* {@inheritdoc}
*/
public function build() {
$fields = $this->getIndex()->getFields();
$configured_fields = [];
foreach ($this->configuration[self::SETTING_FIELDS] as $identifier) {
$configured_fields[$identifier] = $fields[$identifier];
}
return $this->formBuilder->getForm('Drupal\islandora_advanced_search\Form\AdvancedSearchForm', $this->view, $this->display, $configured_fields, $this->configuration[self::SETTING_CONTEXTUAL_FILTER]);
}
/**
* {@inheritdoc}
*/
public function getCacheMaxAge() {
// The block cannot be cached, because it must always match the current
// search results.
return 0;
}
/**
* Get Search Index.
*/
protected function getIndex() {
$id = $this->getDerivativeId();
return $this->displayPluginManager->createInstance("views_{$this->display['display_plugin']}:{$id}")->getIndex();
}
}

17
modules/islandora_advanced_search/src/Plugin/Block/AdvancedSearchBlockDeriver.php

@ -1,17 +0,0 @@
<?php
namespace Drupal\islandora_advanced_search\Plugin\Block;
/**
* Deriver for AdvancedSearchBlock.
*/
class AdvancedSearchBlockDeriver extends SearchApiDisplayBlockDeriver {
/**
* {@inheritdoc}
*/
protected function label() {
return $this->t('Advanced Search');
}
}

97
modules/islandora_advanced_search/src/Plugin/Block/SearchApiDisplayBlockDeriver.php

@ -1,97 +0,0 @@
<?php
namespace Drupal\islandora_advanced_search\Plugin\Block;
use Drupal\Component\Plugin\PluginBase;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* This deriver creates a block for every search_api.display.
*/
abstract class SearchApiDisplayBlockDeriver implements ContainerDeriverInterface {
use StringTranslationTrait;
/**
* List of derivative definitions.
*
* @var array
*/
protected $derivatives = [];
/**
* The entity storage for the view.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $storage;
/**
* The display manager for the search_api.
*
* @var \Drupal\search_api\Display\DisplayPluginManager
*/
protected $displayPluginManager;
/**
* Label for the SearchApiDisplayBlockDriver.
*/
abstract protected function label();
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, $base_plugin_id) {
$deriver = new static($container, $base_plugin_id);
$deriver->storage = $container->get('entity_type.manager')->getStorage('view');
$deriver->displayPluginManager = $container->get('plugin.manager.search_api.display');
return $deriver;
}
/**
* {@inheritdoc}
*/
public function getDerivativeDefinition($derivative_id, $base_plugin_definition) {
$derivatives = $this->getDerivativeDefinitions($base_plugin_definition);
return isset($derivatives[$derivative_id]) ? $derivatives[$derivative_id] : NULL;
}
/**
* {@inheritdoc}
*/
public function getDerivativeDefinitions($base_plugin_definition) {
$base_plugin_id = $base_plugin_definition['id'];
if (!isset($this->derivatives[$base_plugin_id])) {
$plugin_derivatives = [];
foreach ($this->displayPluginManager->getDefinitions() as $display_definition) {
$view_id = $display_definition['view_id'];
$view_display = $display_definition['view_display'];
// The derived block needs both the view / display identifiers to
// construct the pager.
$machine_name = "${view_id}__${view_display}";
/** @var \Drupal\views\ViewEntityInterface $view */
$view = $this->storage->load($view_id);
$display = $view->getDisplay($view_display);
$plugin_derivatives[$machine_name] = [
'id' => $base_plugin_id . PluginBase::DERIVATIVE_SEPARATOR . $machine_name,
'label' => $this->label(),
'admin_label' => $this->t(':view: :label for :display', [
':view' => $view->label(),
':label' => $this->label(),
':display' => $display['display_title'],
]),
] + $base_plugin_definition;
}
$this->derivatives[$base_plugin_id] = $plugin_derivatives;
}
return $this->derivatives[$base_plugin_id];
}
}

314
modules/islandora_advanced_search/src/Plugin/Block/SearchResultsPagerBlock.php

@ -1,314 +0,0 @@
<?php
namespace Drupal\islandora_advanced_search\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Render\Markup;
use Drupal\Core\Url;
use Drupal\islandora_advanced_search\AdvancedSearchQuery;
use Drupal\views\Entity\View;
use Drupal\views\Plugin\views\pager\SqlBase;
use Drupal\views\ViewExecutable;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Provides a 'AjaxViewBlock' block.
*
* @Block(
* id = "islandora_advanced_search_result_pager",
* deriver = "Drupal\islandora_advanced_search\Plugin\Block\SearchResultsPagerBlockDeriver",
* admin_label = @Translation("Search Results Pager"),
* category = @Translation("Islandora"),
* )
*/
class SearchResultsPagerBlock extends BlockBase implements ContainerFactoryPluginInterface {
use ViewAndDisplayIdentifiersTrait;
/**
* The clone of the current request object.
*
* @var \Symfony\Component\HttpFoundation\Request
*/
protected $request;
/**
* Construct a FacetBlock instance.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param string $plugin_definition
* The plugin implementation definition.
* @param \Symfony\Component\HttpFoundation\Request $request
* A request object for the current request.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, Request $request) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->request = clone $request;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('request_stack')->getMainRequest()
);
}
/**
* {@inheritdoc}
*/
public function build() {
$id = $this->getDerivativeId();
list($view_id, $display_id) = $this->getViewAndDisplayIdentifiers();
$view = View::Load($view_id);
$view_executable = $view->getExecutable();
$view_executable->setDisplay($display_id);
// Allow advanced search to alter the query.
$advanced_search_query = new AdvancedSearchQuery();
$advanced_search_query->alterView($this->request, $view_executable, $display_id);
$view_executable->execute();
$pager = $view_executable->getPager();
$exposed_input = $view_executable->getExposedInput();
$query_parameters = $this->request->query->all();
$build = [
'#attached' => [
'drupalSettings' => [
'islandora_advanced_search_pager_views_ajax' => [
$id => [
'view_id' => $view_id,
'current_display_id' => $display_id,
'ajax_path' => '/views/ajax',
],
],
],
],
'#attributes' => [
'class' => ['islandora_advanced_search_result_pager'],
'data-drupal-pager-id' => $id,
],
'result_summary' => $this->buildResultsSummary($view_executable),
'container' => [
'#prefix' => '<div class="pager__group">',
'#suffix' => '</div>',
'results_per_page_links' => $this->buildResultsPerPageLinks($pager, $query_parameters),
'display_links' => $this->buildDisplayLinks($query_parameters),
'sort_by' => $this->buildSortByForm($view_executable->sort, $query_parameters),
'pager' => array_merge($pager->render($exposed_input), ['#wrapper_attributes' => ['class' => ['container']]]),
],
];
return $build;
}
/**
* Build the results summary portion of the pager.
*
* @param Drupal\views\ViewExecutable $view_executable
* The view to build the summary for.
*
* @return array
* A renderable array that represents the current page, and number of
* results in the view.
*/
protected function buildResultsSummary(ViewExecutable $view_executable) {
$current_page = (int) $view_executable->getCurrentPage() + 1;
$per_page = (int) $view_executable->getItemsPerPage();
$total = isset($view_executable->total_rows) ? $view_executable->total_rows : count($view_executable->result);
// If there is no result the "start" and "current_record_count" should be
// equal to 0. To have the same calculation logic, we use a "start offset"
// to handle all the cases.
$start_offset = empty($total) ? 0 : 1;
if ($per_page === 0) {
$start = $start_offset;
$end = $total;
}
else {
$total_count = $current_page * $per_page;
if ($total_count > $total) {
$total_count = $total;
}
$start = ($current_page - 1) * $per_page + $start_offset;
$end = $total_count;
}
if (!empty($total)) {
// Return as render array.
return [
'#prefix' => '<div class="pager__summary">',
'#suffix' => '</div>',
'#markup' => $this->t('Displaying @start - @end of @total', [
'@start' => $start,
'@end' => $end,
'@total' => $total,
]),
];
}
return [];
}
/**
* Build the results per page portion of the pager.
*
* @param Drupal\views\Plugin\views\pager\SqlBase $pager
* The pager for the view.
* @param array $query_parameters
* The query parameters used to change the number of results per page.
*
* @return array
* A renderable array representing the results per page portion of pager.
*/
protected function buildResultsPerPageLinks(SqlBase $pager, array $query_parameters) {
$active_items_per_page = $query_parameters['items_per_page'] ?? $pager->options['items_per_page'];
$items_per_page_options = array_map(function ($value) {
return trim($value);
}, explode(',', $pager->options['expose']['items_per_page_options']));
$items = [];
foreach ($items_per_page_options as $items_per_page) {
$url = Url::fromRoute('<current>', [], [
// When changing the number of items displayed always return the user
// to the first page.
'query' => array_merge($query_parameters, [
'items_per_page' => $items_per_page,
'page' => 0,
]),
'absolute' => TRUE,
]);
$active = $items_per_page == $active_items_per_page;
$items[] = [
'#type' => 'link',
'#url' => $url,
'#title' => $items_per_page,
'#attributes' => [
'class' => $active ? ['pager__link', 'pager__link--is-active'] : ['pager__link'],
],
'#wrapper_attributes' => [
'class' => $active ? ['pager__item', 'is-active'] : ['pager__item'],
],
];
}
return [
'#theme' => 'item_list',
'#title' => $this->t('Results per page'),
'#list_type' => 'ul',
'#items' => $items,
'#attributes' => [],
'#wrapper_attributes' => ['class' => ['pager__results', 'container']],
];
}
/**
* Build the display links portion of the pager (list/grid).
*
* @param array $query_parameters
* The query parameters used to change the display format.
*
* @return array
* A renderable array representing the display links portion of pager.
*/
protected function buildDisplayLinks(array $query_parameters) {
$active_display = $query_parameters['display'] ?? 'list';
$display_options = [
'list' => [
'icon' => 'fa-list',
'title' => $this->t('List'),
],
'grid' => [
'icon' => 'fa-th',
'title' => $this->t('Grid'),
],
];
$items = [];
foreach ($display_options as $display => $options) {
$url = Url::fromRoute('<current>', [], [
'query' => array_merge($query_parameters, ['display' => $display]),
'absolute' => TRUE,
]);
$text = "<i class='fa {$options['icon']}' aria-hidden='true'>&nbsp;</i>{$options['title']}";
$active = $active_display == $display;
$items[] = [
'#type' => 'link',
'#url' => $url,
'#title' => Markup::create($text),
'#attributes' => [
'class' => $active ? ['pager__link', 'pager__link--is-active'] : ['pager__link'],
],
'#wrapper_attributes' => [
'class' => $active ? ['pager__item', 'is-active'] : ['pager__item'],
],
];
}
return [
'#theme' => 'item_list',
'#list_type' => 'ul',
'#items' => $items,
'#attributes' => [],
'#wrapper_attributes' => ['class' => ['pager__display', 'container']],
];
}
/**
* Build the sort by portion of the pager.
*
* @param array $sort_criteria
* The search fields which can be sorted.
* @param array $query_parameters
* The query parameters used to change the display format.
*
* @return array
* A renderable array representing the sort by portion of pager.
*/
protected function buildSortByForm(array $sort_criteria, array $query_parameters) {
$default_order = $query_parameters['sort_order'] ?? 'ASC';
$default_sort_by = $query_parameters['sort_by'] ?? 'search_api_relevance';
$default_value = $default_sort_by . '_' . strtolower($default_order);
$options = [];
$options_attributes = [];
// Not sure if this will work without defining a sort per direction.
foreach ($sort_criteria as $sort) {
if ($sort->options['exposed'] == TRUE) {
$id = $sort->options['id'];
// Label should be translated via views already.
$label = $sort->options['expose']['label'];
$asc = "{$id}_asc";
$desc = "{$id}_desc";
$options[$asc] = "{$label} ↑";
$options[$desc] = "{$label} ↓";
$options_attributes[$asc] = [
'data-sort_by' => $id,
'data-sort_order' => 'ASC',
];
$options_attributes[$desc] = [
'data-sort_by' => $id,
'data-sort_order' => 'DESC',
];
}
}
return [
'#type' => 'select',
'#title' => 'Sort',
'#title_display' => 'invisible',
'#options' => $options,
'#options_attributes' => $options_attributes,
'#attributes' => ['autocomplete' => 'off'],
'#wrapper_attributes' => ['class' => ['pager__sort', 'container']],
'#name' => 'order',
'#value' => $default_value,
];
}
/**
* {@inheritdoc}
*/
public function getCacheMaxAge() {
// The block cannot be cached, because it must always match the current
// search results.
return 0;
}
}

17
modules/islandora_advanced_search/src/Plugin/Block/SearchResultsPagerBlockDeriver.php

@ -1,17 +0,0 @@
<?php
namespace Drupal\islandora_advanced_search\Plugin\Block;
/**
* This deriver creates a block for every search_api.display.
*/
class SearchResultsPagerBlockDeriver extends SearchApiDisplayBlockDeriver {
/**
* {@inheritdoc}
*/
protected function label() {
return $this->t('Search Results Pager');
}
}

30
modules/islandora_advanced_search/src/Plugin/Block/ViewAndDisplayIdentifiersTrait.php

@ -1,30 +0,0 @@
<?php
namespace Drupal\islandora_advanced_search\Plugin\Block;
/**
* Gets the view and display identifiers used to create this block.
*
* @see Drupal\Component\Plugin\Discovery\DiscoveryInterface
*/
trait ViewAndDisplayIdentifiersTrait {
/**
* {@inheritdoc}
*/
abstract public function getDerivativeId();
/**
* Gets the View and View Display identifiers used to derive this block.
*
* @return string[]
* Returns an array of two strings where the first is the View identifier
* and the second is the View Display identifier associated with the view
* used to derive this block.
*/
public function getViewAndDisplayIdentifiers() {
$id = $this->getDerivativeId();
return preg_split('/__/', $id, 2);
}
}

63
modules/islandora_advanced_search/src/Plugin/Field/FieldFormatter/EntityReferenceCountFormatter.php

@ -1,63 +0,0 @@
<?php
namespace Drupal\islandora_advanced_search\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Plugin implementation of the 'entity reference ID' formatter.
*
* @FieldFormatter(
* id = "entity_reference_url_title",
* label = @Translation("Children Entity Count, Label."),
* description = @Translation("Children Entity Count, Label."),
* field_types = {
* "entity_reference"
* }
* )
*/
class EntityReferenceCountFormatter extends EntityReferenceFormatterBase {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'label' => 'Items in Collection',
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements['separator'] = [
'#title' => $this->t("Text to appear next to the children's count"),
'#type' => 'textfield',
'#default_value' => $this->getSetting('label'),
];
return $elements;
}
/**
* {@inheritdoc}
*/
public function settingsSummary(): array {
$summary = [];
$summary[] = $this->getSetting('label') ? 'Label : ' . $this->getSetting('label') : $this->t('No label');
return $summary;
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode): array {
$element = [];
$total_items = count($this->getEntitiesToView($items, $langcode));
$element[] = ['#markup' => "<span class='collection_children__total_count'>{$total_items}<span>" . ' ' . $this->formatPlural($total_items, '1 Item in Collection', '@count Items in Collection')];
return $element;
}
}

84
modules/islandora_advanced_search/src/Plugin/facets/widget/IncludeExcludeLinksWidget.php

@ -1,84 +0,0 @@
<?php
namespace Drupal\islandora_advanced_search\Plugin\facets\widget;
use Drupal\facets\Plugin\facets\widget\LinksWidget;
use Drupal\Core\Link;
use Drupal\facets\Result\ResultInterface;
/**
* The links widget.
*
* @FacetsWidget(
* id = "include_exclude_links",
* label = @Translation("List of links that allow the user to include / exclude facets."),
* description = @Translation("A simple widget that shows a list of +/- links."),
* )
*/
class IncludeExcludeLinksWidget extends LinksWidget {
/**
* {@inheritdoc}
*/
protected function prepareLink(ResultInterface $result) {
$facet = $result->getFacet();
$facet_source_id = $facet->getFacetSourceId();
$facet_manager = \Drupal::service('facets.manager');
$facets = $facet_manager->getFacetsByFacetSourceId($facet_source_id);
$raw_value = $result->getRawValue();
$count = $result->getCount();
$url = $result->getUrl();
$exclude_facet = $this->getExcludeFacet($facet, $facets);
$exclude_result = $this->getExcludeResult($exclude_facet, $raw_value);
$exclude_url = $exclude_result ? $exclude_result->getUrl() : NULL;
return [
'#theme' => 'facets_result_item',
'#is_active' => $result->isActive(),
'#value' => [
'text' => (new Link($result->getDisplayValue(), $url))->toRenderable(),
'include' => (new Link(' ', $url))->toRenderable() + [
'#attributes' => [
'class' => ['facet-item__include', 'fa', 'fa-plus'],
],
],
'exclude' => $exclude_url ? (new Link(' ', $exclude_url))->toRenderable() + [
'#attributes' => [
'class' => ['facet-item__exclude', 'fa', 'fa-minus'],
],
] : NULL,
],
'#show_count' => $this->getConfiguration()['show_numbers'] && ($count !== NULL),
'#count' => $count,
'#facet' => $facet,
'#raw_value' => $raw_value,
];
}
/**
* Looks for the excluded facet version of the included facet.
*/
protected function getExcludeResult($facet, $raw_value) {
if ($facet) {
foreach ($facet->getResults() as $result) {
if ($result->getRawValue() === $raw_value) {
return $result;
}
}
}
return NULL;
}
/**
* Looks for the excluded facet version of the included facet.
*/
protected function getExcludeFacet($include, $facets) {
$field_identifier = $include->getFieldIdentifier();
foreach ($facets as $facet) {
if ($field_identifier === $facet->getFieldIdentifier() && $facet->getExclude()) {
return $facet;
}
}
return NULL;
}
}

42
modules/islandora_advanced_search/src/Plugin/facets_summary/processor/ResetRemovePage.php

@ -1,42 +0,0 @@
<?php
namespace Drupal\islandora_advanced_search\Plugin\facets_summary\processor;
use Drupal\facets_summary\FacetsSummaryInterface;
use Drupal\facets_summary\Processor\BuildProcessorInterface;
/**
* Reset should also remove the page query attribute.
*
* @SummaryProcessor(
* id = "reset_remove_page",
* label = @Translation("Remove page from query when resetting facets/query."),
* description = @Translation("Remove page from query when resetting facets/query."),
* stages = {
* "build" = 45
* }
* )
*/
class ResetRemovePage extends ShowSearchQueryProcessor implements BuildProcessorInterface {
/**
* {@inheritdoc}
*/
public function build(FacetsSummaryInterface $facets_summary, array $build, array $facets) {
// This processor is weighted to occur after the reset facets link.
// Which leaves two cases:
// - No facets selected so no reset link (we must add one).
// - Reset link exists at the top of the list (we must remove the
// search term from the link as well).
$reset_index = $this->getResetLinkIndex($build);
if ($reset_index !== NULL) {
$reset = &$build['#items'][$reset_index];
// Remove query from reset url as well.
$query_params = $reset['#url']->getOption('query');
unset($query_params['page']);
$reset['#url']->setOption('query', $query_params);
}
return $build;
}
}

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

Loading…
Cancel
Save