Browse Source

Use PSR-12 code styling

pull/415/head
Sebastian Meyer 2 years ago
parent
commit
6f48dcb9a5
  1. 37
      Classes/Command/IndexCommand.php
  2. 83
      Classes/Command/ReindexCommand.php
  3. 18
      Classes/Common/AbstractModule.php
  4. 48
      Classes/Common/AbstractPlugin.php
  5. 229
      Classes/Common/Document.php
  6. 203
      Classes/Common/DocumentList.php
  7. 43
      Classes/Common/DocumentTypeCheck.php
  8. 4
      Classes/Common/FulltextInterface.php
  9. 220
      Classes/Common/Helper.php
  10. 177
      Classes/Common/IiifManifest.php
  11. 10
      Classes/Common/IiifUrlReader.php
  12. 112
      Classes/Common/Indexer.php
  13. 4
      Classes/Common/MetadataInterface.php
  14. 279
      Classes/Common/MetsDocument.php
  15. 115
      Classes/Common/Solr.php
  16. 7
      Classes/Format/Alto.php
  17. 39
      Classes/Format/Mods.php
  18. 7
      Classes/Format/TeiHeader.php
  19. 29
      Classes/Hooks/ConfigurationForm.php
  20. 123
      Classes/Hooks/DataHandler.php
  21. 15
      Classes/Hooks/ExtensionManagementUtility.php
  22. 38
      Classes/Hooks/FormEngine.php
  23. 9
      Classes/Hooks/KitodoProductionHacks.php
  24. 26
      Classes/Module/NewTenant.php
  25. 36
      Classes/Plugin/AudioPlayer.php
  26. 132
      Classes/Plugin/Basket.php
  27. 49
      Classes/Plugin/Calendar.php
  28. 45
      Classes/Plugin/Collection.php
  29. 13
      Classes/Plugin/Eid/PageViewProxy.php
  30. 19
      Classes/Plugin/Eid/SearchInDocument.php
  31. 15
      Classes/Plugin/Eid/SearchSuggest.php
  32. 48
      Classes/Plugin/Feeds.php
  33. 88
      Classes/Plugin/ListView.php
  34. 28
      Classes/Plugin/Metadata.php
  35. 50
      Classes/Plugin/Navigation.php
  36. 147
      Classes/Plugin/OaiPmh.php
  37. 47
      Classes/Plugin/PageGrid.php
  38. 98
      Classes/Plugin/PageView.php
  39. 164
      Classes/Plugin/Search.php
  40. 45
      Classes/Plugin/Statistics.php
  41. 75
      Classes/Plugin/TableOfContents.php
  42. 9
      Classes/Plugin/Toolbox.php
  43. 17
      Classes/Plugin/Tools/AnnotationTool.php
  44. 23
      Classes/Plugin/Tools/FulltextTool.php
  45. 28
      Classes/Plugin/Tools/ImageDownloadTool.php
  46. 9
      Classes/Plugin/Tools/ImageManipulationTool.php
  47. 43
      Classes/Plugin/Tools/PdfDownloadTool.php
  48. 21
      Classes/Plugin/Tools/SearchInDocumentTool.php
  49. 7
      Classes/Plugin/Validator.php
  50. 1
      Configuration/TCA/Overrides/sys_template.php
  51. 33
      Configuration/TCA/Overrides/tt_content.php
  52. 1
      Configuration/TCA/tx_dlf_actionlog.php
  53. 1
      Configuration/TCA/tx_dlf_basket.php
  54. 1
      Configuration/TCA/tx_dlf_collections.php
  55. 3
      Configuration/TCA/tx_dlf_documents.php
  56. 1
      Configuration/TCA/tx_dlf_formats.php
  57. 1
      Configuration/TCA/tx_dlf_libraries.php
  58. 1
      Configuration/TCA/tx_dlf_mail.php
  59. 1
      Configuration/TCA/tx_dlf_metadata.php
  60. 1
      Configuration/TCA/tx_dlf_metadataformat.php
  61. 1
      Configuration/TCA/tx_dlf_printer.php
  62. 1
      Configuration/TCA/tx_dlf_solrcores.php
  63. 1
      Configuration/TCA/tx_dlf_structures.php
  64. 1
      Resources/Private/Data/MetadataDefaults.php
  65. 1
      Resources/Private/Data/StructureDefaults.php
  66. 104
      class.ext_update.php
  67. 1
      ext_emconf.php
  68. 50
      ext_localconf.php
  69. 3
      ext_tables.php

37
Classes/Command/IndexCommand.php

@ -1,4 +1,5 @@
<?php
namespace Kitodo\Dlf\Command;
/**
@ -10,6 +11,7 @@ namespace Kitodo\Dlf\Command;
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*/
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
@ -20,11 +22,9 @@ use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
use TYPO3\CMS\Core\Database\ConnectionPool;
use Kitodo\Dlf\Common\Document;
use Kitodo\Dlf\Common\Helper;
/**
* Index single document into database and solr.
* Index single document into database and Solr.
*/
class IndexCommand extends Command
{
@ -34,7 +34,7 @@ class IndexCommand extends Command
public function configure()
{
$this
->setDescription('Index single document into database and solr.')
->setDescription('Index single document into database and Solr.')
->setHelp('')
->addOption(
'dry-run',
@ -58,7 +58,7 @@ class IndexCommand extends Command
'solr',
's',
InputOption::VALUE_REQUIRED,
'[UID|index name] of the Solr core the document should be added to.'
'[UID|index_name] of the Solr core the document should be added to.'
);
}
@ -80,7 +80,7 @@ class IndexCommand extends Command
$startingPoint = 0;
if (MathUtility::canBeInterpretedAsInteger($input->getOption('pid'))) {
$startingPoint = MathUtility::forceIntegerInRange((int)$input->getOption('pid'), 0);
$startingPoint = MathUtility::forceIntegerInRange((int) $input->getOption('pid'), 0);
}
if ($startingPoint == 0) {
$io->error('ERROR: No valid PID (' . $startingPoint . ') given.');
@ -90,21 +90,22 @@ class IndexCommand extends Command
if ($input->getOption('solr')) {
$allSolrCores = $this->getSolrCores($startingPoint);
if (MathUtility::canBeInterpretedAsInteger($input->getOption('solr'))) {
$solrCoreUid = MathUtility::forceIntegerInRange((int)$input->getOption('solr'), 0);
$solrCoreUid = MathUtility::forceIntegerInRange((int) $input->getOption('solr'), 0);
} else {
$solrCoreName = $input->getOption('solr');
$solrCoreUid = $allSolrCores[$solrCoreName];
}
// Abort if solrCoreUid is empty or not in the array of allowed solr cores.
if (empty($solrCoreUid) || !in_array($solrCoreUid, $allSolrCores)) {
$output_solrCores = [];
foreach ($allSolrCores as $index_name => $uid) {
$output_solrCores .= ' ' . $uid . ' : ' . $index_name ."\n";
$output_solrCores[] = $uid . ' : ' . $index_name;
}
if (empty($output_solrCores)) {
$io->error('ERROR: No valid solr core ("'. $input->getOption('solr') . '") given. ' . "No valid cores found on PID " . $startingPoint .".\n" . $output_solrCores);
$io->error('ERROR: No valid Solr core ("' . $input->getOption('solr') . '") given. No valid cores found on PID ' . $startingPoint . ".\n");
exit(1);
} else {
$io->error('ERROR: No valid solr core ("'. $input->getOption('solr') . '") given. ' . "Valid cores are (<uid>:<index_name>):\n" . $output_solrCores);
$io->error('ERROR: No valid Solr core ("' . $input->getOption('solr') . '") given. ' . "Valid cores are (<uid>:<index_name>):\n" . implode("\n", $output_solrCores) . "\n");
exit(1);
}
}
@ -113,8 +114,10 @@ class IndexCommand extends Command
exit(1);
}
if (!MathUtility::canBeInterpretedAsInteger($input->getOption('doc'))
&& !GeneralUtility::isValidUrl($input->getOption('doc'))) {
if (
!MathUtility::canBeInterpretedAsInteger($input->getOption('doc'))
&& !GeneralUtility::isValidUrl($input->getOption('doc'))
) {
$io->error('ERROR: "' . $input->getOption('doc') . '" is not a valid document UID or URL for --doc|-d.');
exit(1);
}
@ -123,19 +126,19 @@ class IndexCommand extends Command
$doc = Document::getInstance($input->getOption('doc'), $startingPoint, TRUE);
if ($doc->ready) {
if ($dryRun) {
$io->section('DRY RUN: Would index ' . $doc->uid . ' '. $doc->location . ' on UID ' . $startingPoint . ' and solr core ' . $solrCoreUid .'.');
$io->section('DRY RUN: Would index ' . $doc->uid . ' ("' . $doc->location . '") on UID ' . $startingPoint . ' and Solr core ' . $solrCoreUid . '.');
} else {
if ($io->isVerbose()) {
$io->section('Will index ' . $doc->uid . ' ' . $doc->location . ' on UID ' . $startingPoint . ' and solr core ' . $solrCoreUid .'.');
$io->section('Indexing ' . $doc->uid . ' ("' . $doc->location . '") on UID ' . $startingPoint . ' and Solr core ' . $solrCoreUid . '.');
}
// ...and save it to the database...
if (!$doc->save($startingPoint, $solrCoreUid)) {
$io->error('ERROR: Document "'.$input->getOption('doc').'" not saved and indexed.');
$io->error('ERROR: Document "' . $input->getOption('doc') . '" not saved and indexed.');
exit(1);
}
}
} else {
$io->error('ERROR: Document "'.$input->getOption('doc').'" could not be loaded.');
$io->error('ERROR: Document "' . $input->getOption('doc') . '" could not be loaded.');
exit(1);
}
@ -157,7 +160,7 @@ class IndexCommand extends Command
->getQueryBuilderForTable('tx_dlf_solrcores');
$solrCores = [];
$pageId = (int)$pageId;
$pageId = (int) $pageId;
$result = $queryBuilder
->select('uid', 'index_name')
->from('tx_dlf_solrcores')

83
Classes/Command/ReindexCommand.php

@ -1,4 +1,5 @@
<?php
namespace Kitodo\Dlf\Command;
/**
@ -10,6 +11,7 @@ namespace Kitodo\Dlf\Command;
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*/
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
@ -21,11 +23,9 @@ use TYPO3\CMS\Core\Utility\MathUtility;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Connection;
use Kitodo\Dlf\Common\Document;
use Kitodo\Dlf\Common\Helper;
/**
* Reindex a collection into database and solr.
* Reindex a collection into database and Solr.
*/
class ReindexCommand extends Command
{
@ -35,7 +35,7 @@ class ReindexCommand extends Command
public function configure()
{
$this
->setDescription('Reindex a collection into database and solr.')
->setDescription('Reindex a collection into database and Solr.')
->setHelp('')
->addOption(
'dry-run',
@ -53,13 +53,13 @@ class ReindexCommand extends Command
'pid',
'p',
InputOption::VALUE_REQUIRED,
'UID of the page the document should be added to.'
'UID of the page the documents should be added to.'
)
->addOption(
'solr',
's',
InputOption::VALUE_REQUIRED,
'[UID|index name] of the Solr core the document should be added to.'
'[UID|index_name] of the Solr core the document should be added to.'
)
->addOption(
'all',
@ -87,7 +87,7 @@ class ReindexCommand extends Command
$startingPoint = 0;
if (MathUtility::canBeInterpretedAsInteger($input->getOption('pid'))) {
$startingPoint = MathUtility::forceIntegerInRange((int)$input->getOption('pid'), 0);
$startingPoint = MathUtility::forceIntegerInRange((int) $input->getOption('pid'), 0);
}
if ($startingPoint == 0) {
$io->error('ERROR: No valid PID (' . $startingPoint . ') given.');
@ -97,21 +97,22 @@ class ReindexCommand extends Command
if ($input->getOption('solr')) {
$allSolrCores = $this->getSolrCores($startingPoint);
if (MathUtility::canBeInterpretedAsInteger($input->getOption('solr'))) {
$solrCoreUid = MathUtility::forceIntegerInRange((int)$input->getOption('solr'), 0);
$solrCoreUid = MathUtility::forceIntegerInRange((int) $input->getOption('solr'), 0);
} else {
$solrCoreName = $input->getOption('solr');
$solrCoreUid = $allSolrCores[$solrCoreName];
}
// Abort if solrCoreUid is empty or not in the array of allowed solr cores.
if (empty($solrCoreUid) || !in_array($solrCoreUid, $allSolrCores)) {
$output_solrCores = [];
foreach ($allSolrCores as $index_name => $uid) {
$output_solrCores .= ' ' . $uid . ' : ' . $index_name ."\n";
$output_solrCores[] = $uid . ' : ' . $index_name;
}
if (empty($output_solrCores)) {
$io->error('ERROR: No valid solr core ("'. $input->getOption('solr') . '") given. ' . "No valid cores found on PID " . $startingPoint .".\n" . $output_solrCores);
$io->error('ERROR: No valid Solr core ("' . $input->getOption('solr') . '") given. No valid cores found on PID ' . $startingPoint . ".\n");
exit(1);
} else {
$io->error('ERROR: No valid solr core ("'. $input->getOption('solr') . '") given. ' . "Valid cores are (<uid>:<index_name>):\n" . $output_solrCores);
$io->error('ERROR: No valid Solr core ("' . $input->getOption('solr') . '") given. ' . "Valid cores are (<uid>:<index_name>):\n" . implode("\n", $output_solrCores) . "\n");
exit(1);
}
}
@ -136,18 +137,18 @@ class ReindexCommand extends Command
$doc = Document::getInstance($document, $startingPoint, TRUE);
if ($doc->ready) {
if ($dryRun) {
$io->writeln('DRY RUN: Would index ' . $id . '/' . count($documents) . ' ' . $doc->uid . ' ' . $doc->location . ' on UID ' . $startingPoint . ' and solr core ' . $solrCoreUid .'.');
$io->writeln('DRY RUN: Would index ' . $id . '/' . count($documents) . ' ' . $doc->uid . ' ("' . $doc->location . '") on UID ' . $startingPoint . ' and Solr core ' . $solrCoreUid . '.');
} else {
if ($io->isVerbose()) {
$io->writeln(date('Y-m-d H:i:s') . ' ' . $id . '/' . count($documents) . ' ' . $doc->uid . ' ' . $doc->location . ' on UID ' . $startingPoint . ' and solr core ' . $solrCoreUid .'.');
$io->writeln(date('Y-m-d H:i:s') . ' Indexing ' . $id . '/' . count($documents) . ' ' . $doc->uid . ' ("' . $doc->location . '") on UID ' . $startingPoint . ' and Solr core ' . $solrCoreUid . '.');
}
// ...and save it to the database...
if (!$doc->save($startingPoint, $solrCoreUid)) {
$io->error('ERROR: Document "'.$id.'" not saved and indexed.');
$io->error('ERROR: Document "' . $id . '" not saved and indexed.');
}
}
} else {
$io->error('ERROR: Document "'.$id.'" could not be loaded.');
$io->error('ERROR: Document "' . $id . '" could not be loaded.');
}
// Clear document registry to prevent memory exhaustion.
Document::clearRegistry();
@ -171,7 +172,7 @@ class ReindexCommand extends Command
->getQueryBuilderForTable('tx_dlf_solrcores');
$solrCores = [];
$pageId = (int)$pageId;
$pageId = (int) $pageId;
$result = $queryBuilder
->select('uid', 'index_name')
->from('tx_dlf_solrcores')
@ -205,7 +206,7 @@ class ReindexCommand extends Command
->getQueryBuilderForTable('tx_dlf_documents');
$documents = [];
$pageId = (int)$pageId;
$pageId = (int) $pageId;
$result = $queryBuilder
->select('tx_dlf_documents.uid')
->from('tx_dlf_documents')
@ -227,24 +228,24 @@ class ReindexCommand extends Command
'tx_dlf_collections_join.uid'
)
)
-> where(
$queryBuilder->expr()->andX(
$queryBuilder->expr()->in(
'tx_dlf_collections_join.uid',
$queryBuilder->createNamedParameter(
GeneralUtility::intExplode(',', $collIds, true),
Connection::PARAM_INT_ARRAY
)
),
$queryBuilder->expr()->eq(
'tx_dlf_collections_join.pid',
$queryBuilder->createNamedParameter($pageId, Connection::PARAM_INT)
),
$queryBuilder->expr()->eq(
'tx_dlf_relations_joins.ident',
$queryBuilder->createNamedParameter('docs_colls')
)
)
->where(
$queryBuilder->expr()->andX(
$queryBuilder->expr()->in(
'tx_dlf_collections_join.uid',
$queryBuilder->createNamedParameter(
GeneralUtility::intExplode(',', $collIds, true),
Connection::PARAM_INT_ARRAY
)
),
$queryBuilder->expr()->eq(
'tx_dlf_collections_join.pid',
$queryBuilder->createNamedParameter($pageId, Connection::PARAM_INT)
),
$queryBuilder->expr()->eq(
'tx_dlf_relations_joins.ident',
$queryBuilder->createNamedParameter('docs_colls')
)
)
)
->groupBy('tx_dlf_documents.uid')
->orderBy('tx_dlf_documents.uid', 'ASC')
@ -271,15 +272,15 @@ class ReindexCommand extends Command
->getQueryBuilderForTable('tx_dlf_documents');
$documents = [];
$pageId = (int)$pageId;
$pageId = (int) $pageId;
$result = $queryBuilder
->select('uid')
->from('tx_dlf_documents')
-> where(
$queryBuilder->expr()->eq(
'tx_dlf_documents.pid',
$queryBuilder->createNamedParameter($pageId, Connection::PARAM_INT)
)
->where(
$queryBuilder->expr()->eq(
'tx_dlf_documents.pid',
$queryBuilder->createNamedParameter($pageId, Connection::PARAM_INT)
)
)
->orderBy('tx_dlf_documents.uid', 'ASC')
->execute();

18
Classes/Common/AbstractModule.php

@ -1,4 +1,5 @@
<?php
namespace Kitodo\Dlf\Common;
/**
@ -20,7 +21,8 @@ namespace Kitodo\Dlf\Common;
* @access public
* @abstract
*/
abstract class AbstractModule extends \TYPO3\CMS\Backend\Module\BaseScriptClass {
abstract class AbstractModule extends \TYPO3\CMS\Backend\Module\BaseScriptClass
{
public $extKey = 'dlf';
public $prefixId = 'tx_dlf';
@ -93,11 +95,12 @@ abstract class AbstractModule extends \TYPO3\CMS\Backend\Module\BaseScriptClass
*
* @return void
*/
protected function printContent() {
protected function printContent()
{
$this->doc = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Template\DocumentTemplate::class);
$this->doc->setModuleTemplate('EXT:'.$this->extKey.'/Resources/Private/Templates/'.Helper::getUnqualifiedClassName(get_class($this)).'.tmpl');
$this->doc->setModuleTemplate('EXT:' . $this->extKey . '/Resources/Private/Templates/' . Helper::getUnqualifiedClassName(get_class($this)) . '.tmpl');
$this->doc->backPath = $GLOBALS['BACK_PATH'];
$this->doc->bodyTagAdditions = 'class="ext-'.$this->extKey.'-modules"';
$this->doc->bodyTagAdditions = 'class="ext-' . $this->extKey . '-modules"';
$this->doc->form = '<form action="" method="post" enctype="multipart/form-data">';
// Add Javascript for function menu.
$this->doc->JScode .= '<script type="text/javascript">script_ended = 0;function jumpToUrl(URL) { document.location = URL; }</script>';
@ -107,7 +110,7 @@ abstract class AbstractModule extends \TYPO3\CMS\Backend\Module\BaseScriptClass
$this->content .= $this->doc->startPage($GLOBALS['LANG']->getLL('title'));
// Set defaults for menu.
if (empty($this->markerArray['CSH'])) {
$this->markerArray['CSH'] = \TYPO3\CMS\Backend\Utility\BackendUtility::cshItem('_MOD_'.$GLOBALS['MCONF']['name'], 'csh', $GLOBALS['BACK_PATH'], '', TRUE);
$this->markerArray['CSH'] = \TYPO3\CMS\Backend\Utility\BackendUtility::cshItem('_MOD_' . $GLOBALS['MCONF']['name'], 'csh', $GLOBALS['BACK_PATH'], '', TRUE);
}
if (empty($this->markerArray['MOD_MENU'])) {
$this->markerArray['MOD_MENU'] = \TYPO3\CMS\Backend\Utility\BackendUtility::getFuncMenu($this->id, 'SET[function]', $this->MOD_SETTINGS['function'], $this->MOD_MENU['function']);
@ -124,8 +127,9 @@ abstract class AbstractModule extends \TYPO3\CMS\Backend\Module\BaseScriptClass
*
* @return void
*/
public function __construct() {
$GLOBALS['LANG']->includeLLFile('EXT:'.$this->extKey.'/Resources/Private/Language/'.Helper::getUnqualifiedClassName(get_class($this)).'.xml');
public function __construct()
{
$GLOBALS['LANG']->includeLLFile('EXT:' . $this->extKey . '/Resources/Private/Language/' . Helper::getUnqualifiedClassName(get_class($this)) . '.xml');
$this->conf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][$this->extKey]);
$this->data = \TYPO3\CMS\Core\Utility\GeneralUtility::_GPmerged($this->prefixId);
}

48
Classes/Common/AbstractPlugin.php

@ -1,4 +1,5 @@
<?php
namespace Kitodo\Dlf\Common;
/**
@ -25,7 +26,8 @@ use TYPO3\CMS\Core\Utility\GeneralUtility;
* @access public
* @abstract
*/
abstract class AbstractPlugin extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin {
abstract class AbstractPlugin extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
{
public $extKey = 'dlf';
public $prefixId = 'tx_dlf';
public $scriptRelPath = 'Classes/Common/AbstractPlugin.php';
@ -66,14 +68,15 @@ abstract class AbstractPlugin extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
*
* @return void
*/
protected function getTemplate($part = '###TEMPLATE###') {
protected function getTemplate($part = '###TEMPLATE###')
{
$this->templateService = GeneralUtility::makeInstance(MarkerBasedTemplateService::class);
if (!empty($this->conf['templateFile'])) {
// Load template file from configuration.
$templateFile = $this->conf['templateFile'];
} else {
// Load default template from extension.
$templateFile = 'EXT:'.$this->extKey.'/Resources/Private/Templates/' . Helper::getUnqualifiedClassName(get_class($this)) . '.tmpl';
$templateFile = 'EXT:' . $this->extKey . '/Resources/Private/Templates/' . Helper::getUnqualifiedClassName(get_class($this)) . '.tmpl';
}
$this->template = $this->templateService->getSubpart($this->cObj->fileResource($templateFile), $part);
}
@ -88,7 +91,8 @@ abstract class AbstractPlugin extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
*
* @return void
*/
protected function init(array $conf) {
protected function init(array $conf)
{
// Read FlexForm configuration.
$flexFormConf = [];
$this->cObj->readFlexformIntoConf($this->cObj->data['pi_flexform'], $flexFormConf);
@ -96,12 +100,12 @@ abstract class AbstractPlugin extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
$conf = Helper::mergeRecursiveWithOverrule($flexFormConf, $conf);
}
// Read plugin TS configuration.
$pluginConf = $GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_dlf_'.strtolower(Helper::getUnqualifiedClassName(get_class($this))).'.'];
$pluginConf = $GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_dlf_' . strtolower(Helper::getUnqualifiedClassName(get_class($this))) . '.'];
if (is_array($pluginConf)) {
$conf = Helper::mergeRecursiveWithOverrule($pluginConf, $conf);
}
// Read general TS configuration.
$generalConf = $GLOBALS['TSFE']->tmpl->setup['plugin.'][$this->prefixId.'.'];
$generalConf = $GLOBALS['TSFE']->tmpl->setup['plugin.'][$this->prefixId . '.'];
if (is_array($generalConf)) {
$conf = Helper::mergeRecursiveWithOverrule($generalConf, $conf);
}
@ -119,7 +123,7 @@ abstract class AbstractPlugin extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
// Set default plugin variables.
$this->pi_setPiVarDefaults();
// Load translation files.
$this->pi_loadLL('EXT:'.$this->extKey.'/Resources/Private/Language/'.Helper::getUnqualifiedClassName(get_class($this)).'.xml');
$this->pi_loadLL('EXT:' . $this->extKey . '/Resources/Private/Language/' . Helper::getUnqualifiedClassName(get_class($this)) . '.xml');
}
/**
@ -129,10 +133,13 @@ abstract class AbstractPlugin extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
*
* @return void
*/
protected function loadDocument() {
protected function loadDocument()
{
// Check for required variable.
if (!empty($this->piVars['id'])
&& !empty($this->conf['pages'])) {
if (
!empty($this->piVars['id'])
&& !empty($this->conf['pages'])
) {
// Should we exclude documents from other pages than $this->conf['pages']?
$pid = (!empty($this->conf['excludeOther']) ? intval($this->conf['pages']) : 0);
// Get instance of \Kitodo\Dlf\Common\Document.
@ -140,7 +147,7 @@ abstract class AbstractPlugin extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
if (!$this->doc->ready) {
// Destroy the incomplete object.
$this->doc = NULL;
Helper::devLog('Failed to load document with UID '.$this->piVars['id'], DEVLOG_SEVERITY_ERROR);
Helper::devLog('Failed to load document with UID ' . $this->piVars['id'], DEVLOG_SEVERITY_ERROR);
} else {
// Set configuration PID.
$this->doc->cPid = $this->conf['pages'];
@ -165,14 +172,14 @@ abstract class AbstractPlugin extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
$this->piVars['id'] = $resArray['uid'];
// Set superglobal $_GET array and unset variables to avoid infinite looping.
$_GET[$this->prefixId]['id'] = $this->piVars['id'];
unset ($this->piVars['recordId'], $_GET[$this->prefixId]['recordId']);
unset($this->piVars['recordId'], $_GET[$this->prefixId]['recordId']);
// Try to load document.
$this->loadDocument();
} else {
Helper::devLog('Failed to load document with record ID "'.$this->piVars['recordId'].'"', DEVLOG_SEVERITY_ERROR);
Helper::devLog('Failed to load document with record ID "' . $this->piVars['recordId'] . '"', DEVLOG_SEVERITY_ERROR);
}
} else {
Helper::devLog('Invalid UID '.$this->piVars['id'].' or PID '.$this->conf['pages'].' for document loading', DEVLOG_SEVERITY_ERROR);
Helper::devLog('Invalid UID ' . $this->piVars['id'] . ' or PID ' . $this->conf['pages'] . ' for document loading', DEVLOG_SEVERITY_ERROR);
}
}
@ -199,12 +206,13 @@ abstract class AbstractPlugin extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
*
* @return string HTML content wrapped, ready to return to the parent object.
*/
public function pi_wrapInBaseClass($content) {
public function pi_wrapInBaseClass($content)
{
if (!$GLOBALS['TSFE']->config['config']['disableWrapInBaseClass']) {
// Use class name instead of $this->prefixId for content wrapping because $this->prefixId is the same for all plugins.
$content = '<div class="tx-dlf-'.Helper::getUnqualifiedClassName(get_class($this)).'">'.$content.'</div>';
$content = '<div class="tx-dlf-' . Helper::getUnqualifiedClassName(get_class($this)) . '">' . $content . '</div>';
if (!$GLOBALS['TSFE']->config['config']['disablePrefixComment']) {
$content = "\n\n<!-- BEGIN: Content of extension '".$this->extKey."', plugin '".Helper::getUnqualifiedClassName(get_class($this))."' -->\n\n".$content."\n\n<!-- END: Content of extension '".$this->extKey."', plugin '".Helper::getUnqualifiedClassName(get_class($this))."' -->\n\n";
$content = "\n\n<!-- BEGIN: Content of extension '" . $this->extKey . "', plugin '" . Helper::getUnqualifiedClassName(get_class($this)) . "' -->\n\n" . $content . "\n\n<!-- END: Content of extension '" . $this->extKey . "', plugin '" . Helper::getUnqualifiedClassName(get_class($this)) . "' -->\n\n";
}
}
return $content;
@ -219,7 +227,8 @@ abstract class AbstractPlugin extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
*
* @return array The resulting typoscript array
*/
protected function parseTS($string = '') {
protected function parseTS($string = '')
{
$parser = GeneralUtility::makeInstance(\TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::class);
$parser->parse($string);
return $parser->setup;
@ -234,7 +243,8 @@ abstract class AbstractPlugin extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
*
* @return void
*/
protected function setCache($cache = TRUE) {
protected function setCache($cache = TRUE)
{
if ($cache) {
// Set cObject type to "USER" (default).
$this->pi_USER_INT_obj = FALSE;

229
Classes/Common/Document.php

@ -1,4 +1,5 @@
<?php
namespace Kitodo\Dlf\Common;
/**
@ -28,7 +29,8 @@ use Ubl\Iiif\Tools\IiifHelper;
* @access public
* @abstract
*/
abstract class Document {
abstract class Document
{
/**
* This holds the PID for the configuration
*
@ -303,7 +305,8 @@ abstract class Document {
*
* @return void
*/
public static function clearRegistry() {
public static function clearRegistry()
{
// Reset registry array.
self::$registry = [];
}
@ -384,29 +387,38 @@ abstract class Document {
*
* @return \Kitodo\Dlf\Common\Document Instance of this class, either MetsDocument or IiifManifest
*/
public static function &getInstance($uid, $pid = 0, $forceReload = FALSE) {
public static function &getInstance($uid, $pid = 0, $forceReload = FALSE)
{
// Sanitize input.
$pid = max(intval($pid), 0);
if (!$forceReload) {
$regObj = md5($uid);
if (is_object(self::$registry[$regObj])
&& self::$registry[$regObj] instanceof self) {
if (
is_object(self::$registry[$regObj])
&& self::$registry[$regObj] instanceof self
) {
// Check if instance has given PID.
if (!$pid
if (
!$pid
|| !self::$registry[$regObj]->pid
|| $pid == self::$registry[$regObj]->pid) {
|| $pid == self::$registry[$regObj]->pid
) {
// Return singleton instance if available.
return self::$registry[$regObj];
}
} else {
// Check the user's session...
$sessionData = Helper::loadFromSession(get_called_class());
if (is_object($sessionData[$regObj])
&& $sessionData[$regObj] instanceof self) {
if (
is_object($sessionData[$regObj])
&& $sessionData[$regObj] instanceof self
) {
// Check if instance has given PID.
if (!$pid
if (
!$pid
|| !$sessionData[$regObj]->pid
|| $pid == $sessionData[$regObj]->pid) {
|| $pid == $sessionData[$regObj]->pid
) {
// ...and restore registry.
self::$registry[$regObj] = $sessionData[$regObj];
return self::$registry[$regObj];
@ -482,7 +494,7 @@ abstract class Document {
/* @var $xml \SimpleXMLElement */
$xml->registerXPathNamespace('mets', 'http://www.loc.gov/METS/');
$xpathResult = $xml->xpath('//mets:mets');
$documentFormat = ($xpathResult !== false && count($xpathResult)>0) ? 'METS' : null;
$documentFormat = ($xpathResult !== false && count($xpathResult) > 0) ? 'METS' : null;
} else {
// Try to load file as IIIF resource instead.
$contentAsJsonArray = json_decode($content, true);
@ -564,9 +576,12 @@ abstract class Document {
*
* @return integer The physical page number
*/
public function getPhysicalPage($logicalPage) {
if (!empty($this->lastSearchedPhysicalPage['logicalPage'])
&& $this->lastSearchedPhysicalPage['logicalPage'] == $logicalPage) {
public function getPhysicalPage($logicalPage)
{
if (
!empty($this->lastSearchedPhysicalPage['logicalPage'])
&& $this->lastSearchedPhysicalPage['logicalPage'] == $logicalPage
) {
return $this->lastSearchedPhysicalPage['physicalPage'];
} else {
$physicalPage = 0;
@ -609,7 +624,8 @@ abstract class Document {
*
* @return string The physical structure node's / IIIF resource's raw text from XML
*/
protected function getRawTextFromXml($id) {
protected function getRawTextFromXml($id)
{
$rawText = '';
// Load available text formats, ...
$this->loadFormats();
@ -633,7 +649,7 @@ abstract class Document {
// Get the root element's name as text format.
$textFormat = strtoupper($rawTextXml->getName());
} else {
Helper::devLog('Invalid structure node @ID "'.$id.'"', DEVLOG_SEVERITY_WARNING);
Helper::devLog('Invalid structure node @ID "' . $id . '"', DEVLOG_SEVERITY_WARNING);
return $rawText;
}
// Is this text format supported?
@ -641,16 +657,18 @@ abstract class Document {
if (!empty($this->formats[$textFormat]['class'])) {
$class = $this->formats[$textFormat]['class'];
// Get the raw text from class.
if (class_exists($class)
&& ($obj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance($class)) instanceof FulltextInterface) {
if (
class_exists($class)
&& ($obj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance($class)) instanceof FulltextInterface
) {
$rawText = $obj->getRawText($rawTextXml);
$this->rawTextArray[$id] = $rawText;
} else {
Helper::devLog('Invalid class/method "'.$class.'->getRawText()" for text format "'.$textFormat.'"', DEVLOG_SEVERITY_WARNING);
Helper::devLog('Invalid class/method "' . $class . '->getRawText()" for text format "' . $textFormat . '"', DEVLOG_SEVERITY_WARNING);
}
}
} else {
Helper::devLog('Unsupported text format "'.$textFormat.'" in physical node with @ID "'.$id.'"', DEVLOG_SEVERITY_WARNING);
Helper::devLog('Unsupported text format "' . $textFormat . '" in physical node with @ID "' . $id . '"', DEVLOG_SEVERITY_WARNING);
}
return $rawText;
}
@ -667,7 +685,8 @@ abstract class Document {
*
* @return string The title of the document itself or a parent document
*/
public static function getTitle($uid, $recursive = FALSE) {
public static function getTitle($uid, $recursive = FALSE)
{
$title = '';
// Sanitize input.
$uid = max(intval($uid), 0);
@ -694,17 +713,19 @@ abstract class Document {
$title = $resArray['title'];
$partof = $resArray['partof'];
// Search parent documents recursively for a title?
if ($recursive
if (
$recursive
&& empty($title)
&& intval($partof)
&& $partof != $uid) {
&& $partof != $uid
) {
$title = self::getTitle($partof, TRUE);
}
} else {
Helper::devLog('No document with UID '.$uid.' found or document not accessible', DEVLOG_SEVERITY_WARNING);
Helper::devLog('No document with UID ' . $uid . ' found or document not accessible', DEVLOG_SEVERITY_WARNING);
}
} else {
Helper::devLog('Invalid UID '.$uid.' for document', DEVLOG_SEVERITY_ERROR);
Helper::devLog('Invalid UID ' . $uid . ' for document', DEVLOG_SEVERITY_ERROR);
}
return $title;
}
@ -718,13 +739,18 @@ abstract class Document {
*
* @return array The logical structure node's / resource's parsed metadata array
*/
public function getTitledata($cPid = 0) {
public function getTitledata($cPid = 0)
{
$titledata = $this->getMetadata($this->_getToplevelId(), $cPid);
// Set record identifier for METS file / IIIF manifest if not present.
if (is_array($titledata)
&& array_key_exists('record_id', $titledata)) {
if (!empty($this->recordId)
&& !in_array($this->recordId, $titledata['record_id'])) {
if (
is_array($titledata)
&& array_key_exists('record_id', $titledata)
) {
if (
!empty($this->recordId)
&& !in_array($this->recordId, $titledata['record_id'])
) {
array_unshift($titledata['record_id'], $this->recordId);
}
}
@ -743,13 +769,14 @@ abstract class Document {
* @return integer|boolean: false if structure with $logId is not a child of this substructure,
* or the actual depth.
*/
protected function getTreeDepth($structure, $depth, $logId) {
protected function getTreeDepth($structure, $depth, $logId)
{
foreach ($structure as $element) {
if ($element['id'] == $logId) {
return $depth;
} elseif (array_key_exists('children', $element)) {
$foundInChildren = $this->getTreeDepth($element['children'], $depth + 1, $logId);
if ($foundInChildren!==false) {
if ($foundInChildren !== false) {
return $foundInChildren;
}
}
@ -765,7 +792,8 @@ abstract class Document {
* @param string $logId: The id of the logical structure element whose depth is requested
* @return number|boolean tree depth as integer or FALSE if no element with $logId exists within the TOC.
*/
public function getStructureDepth($logId) {
public function getStructureDepth($logId)
{
return $this->getTreeDepth($this->_getTableOfContents(), 1, $logId);
}
@ -813,7 +841,8 @@ abstract class Document {
*
* @return boolean TRUE on success or FALSE on failure
*/
protected function load($location) {
protected function load($location)
{
// Load XML / JSON-LD file.
if (\TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl($location)) {
// Load extension configuration
@ -825,7 +854,7 @@ abstract class Document {
// the actual loading is format specific
return $this->loadLocation($location);
} else {
Helper::devLog('Invalid file location "'.$location.'" for document loading', DEVLOG_SEVERITY_ERROR);
Helper::devLog('Invalid file location "' . $location . '" for document loading', DEVLOG_SEVERITY_ERROR);
}
return FALSE;
}
@ -846,7 +875,8 @@ abstract class Document {
*
* @return void
*/
protected function loadFormats() {
protected function loadFormats()
{
if (!$this->formatsLoaded) {
/** @var QueryBuilder $queryBuilder */
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
@ -888,7 +918,8 @@ abstract class Document {
*
* @return void
*/
public function registerNamespaces(&$obj) {
public function registerNamespaces(&$obj)
{
// TODO Check usage. XML specific method does not seem to be used anywhere outside this class within the project, but it is public and may be used by extensions.
$this->loadFormats();
// Do we have a \SimpleXMLElement or \DOMXPath object?
@ -916,7 +947,8 @@ abstract class Document {
*
* @return boolean TRUE on success or FALSE on failure
*/
public function save($pid = 0, $core = 0) {
public function save($pid = 0, $core = 0)
{
if (TYPO3_MODE !== 'BE') {
Helper::devLog('Saving a document is only allowed in the backend', DEVLOG_SEVERITY_ERROR);
return FALSE;
@ -926,12 +958,14 @@ abstract class Document {
// Make sure $core is a non-negative integer.
$core = max(intval($core), 0);
// If $pid is not given, try to get it elsewhere.
if (!$pid
&& $this->pid) {
if (
!$pid
&& $this->pid
) {
// Retain current PID.
$pid = $this->pid;
} elseif (!$pid) {
Helper::devLog('Invalid PID '.$pid.' for document saving', DEVLOG_SEVERITY_ERROR);
Helper::devLog('Invalid PID ' . $pid . ' for document saving', DEVLOG_SEVERITY_ERROR);
return FALSE;
}
// Set PID for metadata definitions.
@ -969,7 +1003,7 @@ abstract class Document {
if ($resArray = $result->fetch()) {
$structure = $resArray['uid'];
} else {
Helper::devLog('Could not identify document/structure type "'.$queryBuilder->expr()->literal($metadata['type'][0]).'"', DEVLOG_SEVERITY_ERROR);
Helper::devLog('Could not identify document/structure type "' . $queryBuilder->expr()->literal($metadata['type'][0]) . '"', DEVLOG_SEVERITY_ERROR);
return FALSE;
}
$metadata['type'][0] = $structure;
@ -1022,7 +1056,7 @@ abstract class Document {
];
$substUid = Helper::processDBasAdmin($collData);
// Prevent double insertion.
unset ($collData);
unset($collData);
// Add new collection's UID.
$collections[] = $substUid[$collNewUid];
if ((TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_CLI) == FALSE) {
@ -1090,8 +1124,10 @@ abstract class Document {
$partof = $this->getParentDocumentUidForSaving($pid, $core);
// Use the date of publication or title as alternative sorting metric for parts of multi-part works.
if (!empty($partof)) {
if (empty($metadata['volume'][0])
&& !empty($metadata['year'][0])) {
if (
empty($metadata['volume'][0])
&& !empty($metadata['year'][0])
) {
$metadata['volume'] = $metadata['year'];
}
if (empty($metadata['volume_sorting'][0])) {
@ -1123,7 +1159,8 @@ abstract class Document {
->where(
$queryBuilder->expr()->orX(
$queryBuilder->expr()->eq('tx_dlf_metadata.is_listed', 1),
$queryBuilder->expr()->eq('tx_dlf_metadata.is_sortable', 1)),
$queryBuilder->expr()->eq('tx_dlf_metadata.is_sortable', 1)
),
$queryBuilder->expr()->eq('tx_dlf_metadata.pid', intval($pid)),
Helper::whereExpression('tx_dlf_metadata')
)
@ -1201,7 +1238,7 @@ abstract class Document {
if ($core) {
Indexer::add($this, $core);
} else {
Helper::devLog('Invalid UID "'.$core.'" for Solr core', DEVLOG_SEVERITY_NOTICE);
Helper::devLog('Invalid UID "' . $core . '" for Solr core', DEVLOG_SEVERITY_NOTICE);
}
return TRUE;
}
@ -1226,7 +1263,8 @@ abstract class Document {
*
* @return boolean Are there any fulltext files available?
*/
protected function _getHasFulltext() {
protected function _getHasFulltext()
{
$this->ensureHasFulltextIsSet();
return $this->hasFulltext;
}
@ -1238,7 +1276,8 @@ abstract class Document {
*
* @return string The location of the document
*/
protected function _getLocation() {
protected function _getLocation()
{
return $this->location;
}
@ -1260,15 +1299,18 @@ abstract class Document {
*
* @return array Array of metadata with their corresponding logical structure node ID as key
*/
protected function _getMetadataArray() {
protected function _getMetadataArray()
{
// Set metadata definitions' PID.
$cPid = ($this->cPid ? $this->cPid : $this->pid);
if (!$cPid) {
Helper::devLog('Invalid PID '.$cPid.' for metadata definitions', DEVLOG_SEVERITY_ERROR);
Helper::devLog('Invalid PID ' . $cPid . ' for metadata definitions', DEVLOG_SEVERITY_ERROR);
return [];
}
if (!$this->metadataArrayLoaded
|| $this->metadataArray[0] != $cPid) {
if (
!$this->metadataArrayLoaded
|| $this->metadataArray[0] != $cPid
) {
$this->prepareMetadataArray($cPid);
$this->metadataArray[0] = $cPid;
$this->metadataArrayLoaded = TRUE;
@ -1283,7 +1325,8 @@ abstract class Document {
*
* @return integer The total number of pages and/or tracks
*/
protected function _getNumPages() {
protected function _getNumPages()
{
$this->_getPhysicalStructure();
return $this->numPages;
}
@ -1295,7 +1338,8 @@ abstract class Document {
*
* @return integer The UID of the parent document or zero if not applicable
*/
protected function _getParentId() {
protected function _getParentId()
{
return $this->parentId;
}
@ -1318,7 +1362,8 @@ abstract class Document {
*
* @return array Array of elements' type, label and file representations ordered by @ID attribute / Canvas order
*/
protected function _getPhysicalStructureInfo() {
protected function _getPhysicalStructureInfo()
{
// Is there no physical structure array yet?
if (!$this->physicalStructureLoaded) {
// Build physical structure array.
@ -1334,7 +1379,8 @@ abstract class Document {
*
* @return integer The PID of the document or zero if not in database
*/
protected function _getPid() {
protected function _getPid()
{
return $this->pid;
}
@ -1345,7 +1391,8 @@ abstract class Document {
*
* @return boolean Is the document instantiated successfully?
*/
protected function _getReady() {
protected function _getReady()
{
return $this->ready;
}
@ -1356,7 +1403,8 @@ abstract class Document {
*
* @return mixed The METS file's / IIIF manifest's record identifier
*/
protected function _getRecordId() {
protected function _getRecordId()
{
return $this->recordId;
}
@ -1367,7 +1415,8 @@ abstract class Document {
*
* @return integer The UID of the root document or zero if not applicable
*/
protected function _getRootId() {
protected function _getRootId()
{
if (!$this->rootIdLoaded) {
if ($this->parentId) {
$parent = self::getInstance($this->parentId, $this->pid);
@ -1397,7 +1446,8 @@ abstract class Document {
*
* @return array Array of structure nodes' id, label, type and physical page indexes/mptr / Canvas link with original hierarchy preserved
*/
protected function _getTableOfContents() {
protected function _getTableOfContents()
{
// Is there no logical structure array yet?
if (!$this->tableOfContentsLoaded) {
// Get all logical structures.
@ -1438,7 +1488,8 @@ abstract class Document {
*
* @return mixed The UID or the URL of the document
*/
protected function _getUid() {
protected function _getUid()
{
return $this->uid;
}
@ -1451,7 +1502,8 @@ abstract class Document {
*
* @return void
*/
protected function _setCPid($value) {
protected function _setCPid($value)
{
$this->cPid = max(intval($value), 0);
}
@ -1463,7 +1515,8 @@ abstract class Document {
*
* @return void
*/
protected function __clone() {}
protected function __clone()
{ }
/**
* This is a singleton class, thus the constructor should be private/protected
@ -1478,7 +1531,8 @@ abstract class Document {
*
* @return void
*/
protected function __construct($uid, $pid, $preloadedDocument) {
protected function __construct($uid, $pid, $preloadedDocument)
{
/** @var QueryBuilder $queryBuilder */
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('tx_dlf_documents');
@ -1507,8 +1561,10 @@ abstract class Document {
// Loading failed.
return;
}
if (!empty($location)
&& !empty($this->recordId)) {
if (
!empty($location)
&& !empty($this->recordId)
) {
// Try to match record identifier or location (both should be unique).
$whereClause = $queryBuilder->expr()->andX(
$queryBuilder->expr()->orX(
@ -1537,7 +1593,8 @@ abstract class Document {
'tx_dlf_documents.record_id AS record_id',
'tx_dlf_documents.partof AS partof',
'tx_dlf_documents.thumbnail AS thumbnail',
'tx_dlf_documents.location AS location')
'tx_dlf_documents.location AS location'
)
->from('tx_dlf_documents')
->where($whereClause)
->setMaxResults(1)
@ -1552,8 +1609,10 @@ abstract class Document {
$this->location = $resArray['location'];
$this->thumbnailLoaded = TRUE;
// Load XML file if necessary...
if ($this->getDocument() === NULL
&& $this->load($this->location)) {
if (
$this->getDocument() === NULL
&& $this->load($this->location)
) {
// ...and set some basic properties.
$this->init();
}
@ -1573,7 +1632,7 @@ abstract class Document {
// Document ready!
$this->ready = TRUE;
} else {
Helper::devLog('No document with UID '.$uid.' found or document not accessible', DEVLOG_SEVERITY_ERROR);
Helper::devLog('No document with UID ' . $uid . ' found or document not accessible', DEVLOG_SEVERITY_ERROR);
}
}
@ -1586,11 +1645,14 @@ abstract class Document {
*
* @return mixed Value of $this->$var
*/
public function __get($var) {
$method = '_get'.ucfirst($var);
if (!property_exists($this, $var)
|| !method_exists($this, $method)) {
Helper::devLog('There is no getter function for property "'.$var.'"', DEVLOG_SEVERITY_WARNING);
public function __get($var)
{
$method = '_get' . ucfirst($var);
if (
!property_exists($this, $var)
|| !method_exists($this, $method)
) {
Helper::devLog('There is no getter function for property "' . $var . '"', DEVLOG_SEVERITY_WARNING);
return;
} else {
return $this->$method();
@ -1607,11 +1669,14 @@ abstract class Document {
*
* @return void
*/
public function __set($var, $value) {
$method = '_set'.ucfirst($var);
if (!property_exists($this, $var)
|| !method_exists($this, $method)) {
Helper::devLog('There is no setter function for property "'.$var.'"', DEVLOG_SEVERITY_WARNING);
public function __set($var, $value)
{
$method = '_set' . ucfirst($var);
if (
!property_exists($this, $var)
|| !method_exists($this, $method)
) {
Helper::devLog('There is no setter function for property "' . $var . '"', DEVLOG_SEVERITY_WARNING);
} else {
$this->$method($value);
}

203
Classes/Common/DocumentList.php

@ -1,4 +1,5 @@
<?php
namespace Kitodo\Dlf\Common;
/**
@ -25,7 +26,8 @@ use TYPO3\CMS\Core\Utility\MathUtility;
* @subpackage dlf
* @access public
*/
class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Core\SingletonInterface {
class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Core\SingletonInterface
{
/**
* This holds the number of documents in the list
* @see \Countable
@ -95,7 +97,8 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function add(array $elements, $position = -1) {
public function add(array $elements, $position = -1)
{
$position = MathUtility::forceIntegerInRange($position, 0, $this->count, $this->count);
if (!empty($elements)) {
array_splice($this->elements, $position, 0, $elements);
@ -111,7 +114,8 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return integer The number of elements in the list
*/
public function count() {
public function count()
{
return $this->count;
}
@ -123,11 +127,12 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return array The current element
*/
public function current() {
public function current()
{
if ($this->valid()) {
return $this->getRecord($this->elements[$this->position]);
} else {
Helper::devLog('Invalid position "'.$this->position.'" for list element', DEVLOG_SEVERITY_NOTICE);
Helper::devLog('Invalid position "' . $this->position . '" for list element', DEVLOG_SEVERITY_NOTICE);
return;
}
}
@ -141,9 +146,12 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return mixed The element's full record
*/
protected function getRecord($element) {
if (is_array($element)
&& array_keys($element) == ['u', 'h', 's', 'p']) {
protected function getRecord($element)
{
if (
is_array($element)
&& array_keys($element) == ['u', 'h', 's', 'p']
) {
// Return already processed record if possible.
if (!empty($this->records[$element['u']])) {
return $this->records[$element['u']];
@ -155,8 +163,10 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
'subparts' => $element['p']
];
// Check if it's a list of database records or Solr documents.
if (!empty($this->metadata['options']['source'])
&& $this->metadata['options']['source'] == 'collection') {
if (
!empty($this->metadata['options']['source'])
&& $this->metadata['options']['source'] == 'collection'
) {
/** @var QueryBuilder $queryBuilder */
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('tx_dlf_documents');
@ -172,7 +182,8 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
->where(
$queryBuilder->expr()->orX(
$queryBuilder->expr()->eq('tx_dlf_documents.uid', intval($record['uid'])),
$queryBuilder->expr()->eq('tx_dlf_documents.partof', intval($record['uid']))),
$queryBuilder->expr()->eq('tx_dlf_documents.partof', intval($record['uid']))
),
Helper::whereExpression('tx_dlf_documents')
)
->execute();
@ -181,16 +192,22 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
while ($resArray = $result->fetch()) {
// Prepare document's metadata.
$metadata = unserialize($resArray['metadata']);
if (!empty($metadata['type'][0])
&& MathUtility::canBeInterpretedAsInteger($metadata['type'][0])) {
if (
!empty($metadata['type'][0])
&& MathUtility::canBeInterpretedAsInteger($metadata['type'][0])
) {
$metadata['type'][0] = Helper::getIndexNameFromUid($metadata['type'][0], 'tx_dlf_structures', $this->metadata['options']['pid']);
}
if (!empty($metadata['owner'][0])
&& MathUtility::canBeInterpretedAsInteger($metadata['owner'][0])) {
if (
!empty($metadata['owner'][0])
&& MathUtility::canBeInterpretedAsInteger($metadata['owner'][0])
) {
$metadata['owner'][0] = Helper::getIndexNameFromUid($metadata['owner'][0], 'tx_dlf_libraries', $this->metadata['options']['pid']);
}
if (!empty($metadata['collection'])
&& is_array($metadata['collection'])) {
if (
!empty($metadata['collection'])
&& is_array($metadata['collection'])
) {
foreach ($metadata['collection'] as $i => $collection) {
if (MathUtility::canBeInterpretedAsInteger($collection)) {
$metadata['collection'][$i] = Helper::getIndexNameFromUid($metadata['collection'][$i], 'tx_dlf_collections', $this->metadata['options']['pid']);
@ -211,14 +228,16 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
];
}
}
} elseif (!empty($this->metadata['options']['source'])
&& $this->metadata['options']['source'] == 'search') {
} elseif (
!empty($this->metadata['options']['source'])
&& $this->metadata['options']['source'] == 'search'
) {
if ($this->solrConnect()) {
$params = [];
// Restrict the fields to the required ones
$params['fields'] = 'uid,id,toplevel,thumbnail,page';
foreach ($this->solrConfig as $solr_name) {
$params['fields'] .= ','.$solr_name;
$params['fields'] .= ',' . $solr_name;
}
// If it is a fulltext search, enable highlighting.
if ($this->metadata['fulltextSearch']) {
@ -240,15 +259,15 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
// Extend filter query to get all documents with the same UID.
foreach ($params['filterquery'] as $key => $value) {
if (isset($value['query'])) {
$params['filterquery'][$key]['query'] = $value['query'].' OR toplevel:true';
$params['filterquery'][$key]['query'] = $value['query'] . ' OR toplevel:true';
}
}
// Add filter query to get all documents with the required uid.
$params['filterquery'][] = ['query' => 'uid:'.Solr::escapeQuery($record['uid'])];
$params['filterquery'][] = ['query' => 'uid:' . Solr::escapeQuery($record['uid'])];
// Add sorting.
$params['sort'] = $this->metadata['options']['params']['sort'];
// Set query.
$params['query'] = $this->metadata['options']['select'].' OR toplevel:true';
$params['query'] = $this->metadata['options']['select'] . ' OR toplevel:true';
// Perform search for all documents with the same uid that either fit to the search or marked as toplevel.
$selectQuery = $this->solr->service->createSelect($params);
$result = $this->solr->service->select($selectQuery);
@ -300,7 +319,8 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return integer The current position
*/
public function key() {
public function key()
{
return $this->position;
}
@ -314,19 +334,23 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function move($position, $steps) {
public function move($position, $steps)
{
$position = intval($position);
// Check if list position is valid.
if ($position < 0
|| $position >= $this->count) {
Helper::devLog('Invalid position "'.$position.'" for element moving', DEVLOG_SEVERITY_WARNING);
if (
$position < 0
|| $position >= $this->count
) {
Helper::devLog('Invalid position "' . $position . '" for element moving', DEVLOG_SEVERITY_WARNING);
return;
}
$steps = intval($steps);
// Check if moving given amount of steps is possible.
if (($position + $steps) < 0
|| ($position + $steps) >= $this->count) {
Helper::devLog('Invalid steps "'.$steps.'" for moving element at position "'.$position.'"', DEVLOG_SEVERITY_WARNING);
|| ($position + $steps) >= $this->count
) {
Helper::devLog('Invalid steps "' . $steps . '" for moving element at position "' . $position . '"', DEVLOG_SEVERITY_WARNING);
return;
}
$element = $this->remove($position);
@ -342,7 +366,8 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function moveUp($position) {
public function moveUp($position)
{
$this->move($position, -1);
}
@ -355,7 +380,8 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function moveDown($position) {
public function moveDown($position)
{
$this->move($position, 1);
}
@ -367,7 +393,8 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function next() {
public function next()
{
$this->position++;
}
@ -381,7 +408,8 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return boolean Does the given offset exist?
*/
public function offsetExists($offset) {
public function offsetExists($offset)
{
return isset($this->elements[$offset]);
}
@ -395,11 +423,12 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return array The element at the given offset
*/
public function offsetGet($offset) {
public function offsetGet($offset)
{
if ($this->offsetExists($offset)) {
return $this->getRecord($this->elements[$offset]);
} else {
Helper::devLog('Invalid offset "'.$offset.'" for list element', DEVLOG_SEVERITY_NOTICE);
Helper::devLog('Invalid offset "' . $offset . '" for list element', DEVLOG_SEVERITY_NOTICE);
return;
}
}
@ -415,7 +444,8 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function offsetSet($offset, $value) {
public function offsetSet($offset, $value)
{
if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($offset)) {
$this->elements[$offset] = $value;
} else {
@ -435,11 +465,14 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return array The removed element
*/
public function remove($position) {
public function remove($position)
{
$position = intval($position);
if ($position < 0
|| $position >= $this->count) {
Helper::devLog('Invalid position "'.$position.'" for element removing', DEVLOG_SEVERITY_WARNING);
if (
$position < 0
|| $position >= $this->count
) {
Helper::devLog('Invalid position "' . $position . '" for element removing', DEVLOG_SEVERITY_WARNING);
return;
}
$removed = array_splice($this->elements, $position, 1);
@ -457,11 +490,14 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return array The indizes of the removed elements
*/
public function removeRange($position, $length) {
public function removeRange($position, $length)
{
$position = intval($position);
if ($position < 0
|| $position >= $this->count) {
Helper::devLog('Invalid position "'.$position.'" for element removing', DEVLOG_SEVERITY_WARNING);
if (
$position < 0
|| $position >= $this->count
) {
Helper::devLog('Invalid position "' . $position . '" for element removing', DEVLOG_SEVERITY_WARNING);
return;
}
$removed = array_splice($this->elements, $position, $length);
@ -476,7 +512,8 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function reset() {
public function reset()
{
$this->elements = [];
$this->records = [];
$this->metadata = [];
@ -492,7 +529,8 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function rewind() {
public function rewind()
{
$this->position = 0;
}
@ -505,7 +543,8 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function save($pid = 0) {
public function save($pid = 0)
{
$pid = max(intval($pid), 0);
// If no PID is given, save to the user's session instead
if ($pid > 0) {
@ -522,7 +561,8 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return boolean TRUE on success or FALSE on failure
*/
protected function solrConnect() {
protected function solrConnect()
{
// Get Solr instance.
if (!$this->solr) {
// Connect to Solr server.
@ -548,7 +588,7 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
->execute();
while ($resArray = $result->fetch()) {
$this->solrConfig[$resArray['index_name']] = $resArray['index_name'].'_'.($resArray['index_tokenized'] ? 't' : 'u').'s'.($resArray['index_indexed'] ? 'i' : 'u');
$this->solrConfig[$resArray['index_name']] = $resArray['index_name'] . '_' . ($resArray['index_tokenized'] ? 't' : 'u') . 's' . ($resArray['index_indexed'] ? 'i' : 'u');
}
// Add static fields.
$this->solrConfig['type'] = 'type';
@ -569,13 +609,14 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function sort($by, $asc = TRUE) {
public function sort($by, $asc = TRUE)
{
$newOrder = [];
$nonSortable = [];
foreach ($this->elements as $num => $element) {
// Is this element sortable?
if (!empty($element['s'][$by])) {
$newOrder[$element['s'][$by].str_pad($num, 6, '0', STR_PAD_LEFT)] = $element;
$newOrder[$element['s'][$by] . str_pad($num, 6, '0', STR_PAD_LEFT)] = $element;
} else {
$nonSortable[] = $element;
}
@ -606,8 +647,9 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function offsetUnset($offset) {
unset ($this->elements[$offset]);
public function offsetUnset($offset)
{
unset($this->elements[$offset]);
// Re-number the elements.
$this->elements = array_values($this->elements);
$this->count = count($this->elements);
@ -621,7 +663,8 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co