Update code style

This commit is contained in:
Sebastian Meyer 2019-03-14 22:41:35 +01:00
parent 425aedde5a
commit b3887bdbad
43 changed files with 1456 additions and 4411 deletions

View File

@ -22,8 +22,7 @@ use Kitodo\Dlf\Common\Helper;
* @subpackage dlf
* @access public
*/
class CommandLineIndexer extends \TYPO3\CMS\Core\Controller\CommandLineController
{
class CommandLineIndexer extends \TYPO3\CMS\Core\Controller\CommandLineController {
/**
* This is the return code
*
@ -39,10 +38,8 @@ class CommandLineIndexer extends \TYPO3\CMS\Core\Controller\CommandLineControlle
*
* @return integer Return Code
*/
public function main()
{
switch ((string) $this->cli_args['_DEFAULT'][1])
{
public function main() {
switch ((string) $this->cli_args['_DEFAULT'][1]) {
// (Re-)Index a single document.
case 'index':
// Add command line arguments.
@ -52,32 +49,26 @@ class CommandLineIndexer extends \TYPO3\CMS\Core\Controller\CommandLineControlle
// Check the command line arguments.
$this->cli_validateArgs();
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->cli_args['-doc'][0])
&& !\TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl($this->cli_args['-doc'][0]))
{
&& !\TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl($this->cli_args['-doc'][0])) {
$this->cli_echo('ERROR: "'.$this->cli_args['-doc'][0].'" is not a valid document UID or URL.'.LF, TRUE);
$this->return = 1;
}
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->cli_args['-pid'][0]))
{
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->cli_args['-pid'][0])) {
$this->cli_echo('ERROR: "'.$this->cli_args['-pid'][0].'" is not a valid page UID.'.LF, TRUE);
$this->return = 1;
}
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->cli_args['-core'][0]))
{
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->cli_args['-core'][0])) {
$this->cli_echo('ERROR: "'.$this->cli_args['-core'][0].'" is not a valid core UID.'.LF, TRUE);
$this->return = 1;
}
if ($this->return > 0)
{
if ($this->return > 0) {
break;
}
// Get the document...
$doc = Document::getInstance($this->cli_args['-doc'][0], $this->cli_args['-pid'][0], TRUE);
if ($doc->ready)
{
if ($doc->ready) {
// ...and save it to the database...
if (!$doc->save(intval($this->cli_args['-pid'][0]), intval($this->cli_args['-core'][0])))
{
if (!$doc->save(intval($this->cli_args['-pid'][0]), intval($this->cli_args['-core'][0]))) {
$this->cli_echo('ERROR: Document "'.$this->cli_args['-doc'][0].'" not saved and indexed.'.LF, TRUE);
$this->return = 1;
}
@ -94,18 +85,15 @@ class CommandLineIndexer extends \TYPO3\CMS\Core\Controller\CommandLineControlle
$this->cli_options[] = ['-core UID', 'UID of the Solr core the document should be added to.'];
// Check the command line arguments.
$this->cli_validateArgs();
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->cli_args['-coll'][0]))
{
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->cli_args['-coll'][0])) {
$this->cli_echo('ERROR: "'.$this->cli_args['-coll'][0].'" is not a valid collection UID.'.LF, TRUE);
$this->return = 1;
}
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->cli_args['-pid'][0]))
{
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->cli_args['-pid'][0])) {
$this->cli_echo('ERROR: "'.$this->cli_args['-pid'][0].'" is not a valid page UID.'.LF, TRUE);
$this->return = 1;
}
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->cli_args['-core'][0]))
{
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->cli_args['-core'][0])) {
$this->cli_echo('ERROR: "'.$this->cli_args['-core'][0].'" is not a valid core UID.'.LF, TRUE);
$this->return = 1;
}
@ -127,15 +115,12 @@ class CommandLineIndexer extends \TYPO3\CMS\Core\Controller\CommandLineControlle
'',
''
);
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result))
{
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
// Get the document...
$doc = Document::getInstance($resArray['uid'], $this->cli_args['-pid'][0], TRUE);
if ($doc->ready)
{
if ($doc->ready) {
// ...and save it to the database...
if (!$doc->save(intval($this->cli_args['-pid'][0]), intval($this->cli_args['-core'][0])))
{
if (!$doc->save(intval($this->cli_args['-pid'][0]), intval($this->cli_args['-core'][0]))) {
$this->cli_echo('ERROR: Document "'.$resArray['uid'].'" not saved and indexed.'.LF, TRUE);
$this->return = 1;
}
@ -161,8 +146,7 @@ class CommandLineIndexer extends \TYPO3\CMS\Core\Controller\CommandLineControlle
*
* @return void
*/
public function __construct()
{
public function __construct() {
// Run parent constructor.
parent::__construct();
// Set basic information about the script.

View File

@ -20,8 +20,7 @@ namespace Kitodo\Dlf\Common;
* @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';
@ -54,10 +53,8 @@ abstract class AbstractPlugin extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
*
* @return void
*/
protected function getTemplate($part = '###TEMPLATE###')
{
if (!empty($this->conf['templateFile']))
{
protected function getTemplate($part = '###TEMPLATE###') {
if (!empty($this->conf['templateFile'])) {
// Load template file from configuration.
$this->template = $this->cObj->getSubpart($this->cObj->fileResource($this->conf['templateFile']), $part);
} else {
@ -76,43 +73,36 @@ 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);
if (!empty($flexFormConf))
{
if (!empty($flexFormConf)) {
$conf = \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($flexFormConf, $conf);
}
// Read plugin TS configuration.
$pluginConf = $GLOBALS['TSFE']->tmpl->setup['plugin.'][get_class($this).'.'];
if (is_array($pluginConf))
{
if (is_array($pluginConf)) {
$conf = \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($pluginConf, $conf);
}
// Read old plugin TS configuration.
$oldPluginConf = $GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_dlf_'.strtolower(get_class($this)).'.'];
if (is_array($oldPluginConf))
{
if (is_array($oldPluginConf)) {
$conf = \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($oldPluginConf, $conf);
}
// Read general TS configuration.
$generalConf = $GLOBALS['TSFE']->tmpl->setup['plugin.'][$this->prefixId.'.'];
if (is_array($generalConf))
{
if (is_array($generalConf)) {
$conf = \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($generalConf, $conf);
}
// Read extension configuration.
$extConf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][$this->extKey]);
if (is_array($extConf))
{
if (is_array($extConf)) {
$conf = \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($extConf, $conf);
}
// Read TYPO3_CONF_VARS configuration.
$varsConf = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF'][$this->extKey];
if (is_array($varsConf))
{
if (is_array($varsConf)) {
$conf = \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($varsConf, $conf);
}
$this->conf = $conf;
@ -129,12 +119,10 @@ 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']))
{
&& !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.
@ -142,16 +130,14 @@ abstract class AbstractPlugin extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
if (!$this->doc->ready) {
// Destroy the incomplete object.
$this->doc = NULL;
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\AbstractPlugin->loadDocument()] Failed to load document with UID "'.$this->piVars['id'].'"', $this->extKey, SYSLOG_SEVERITY_ERROR);
}
} else {
// Set configuration PID.
$this->doc->cPid = $this->conf['pages'];
}
} elseif (!empty($this->piVars['recordId']))
{
} elseif (!empty($this->piVars['recordId'])) {
// Get UID of document with given record identifier.
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'tx_dlf_documents.uid',
@ -162,8 +148,7 @@ abstract class AbstractPlugin extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
'',
'1'
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) == 1)
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) == 1) {
list ($this->piVars['id']) = $GLOBALS['TYPO3_DB']->sql_fetch_row($result);
// Set superglobal $_GET array and unset variables to avoid infinite looping.
$_GET[$this->prefixId]['id'] = $this->piVars['id'];
@ -171,14 +156,12 @@ abstract class AbstractPlugin extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
// Try to load document.
$this->loadDocument();
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\AbstractPlugin->loadDocument()] Failed to load document with record ID "'.$this->piVars['recordId'].'"', $this->extKey, SYSLOG_SEVERITY_ERROR);
}
}
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\AbstractPlugin->loadDocument()] Invalid UID "'.$this->piVars['id'].'" or PID "'.$this->conf['pages'].'" for document loading', $this->extKey, SYSLOG_SEVERITY_ERROR);
}
}
@ -207,14 +190,11 @@ 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)
{
if (!$GLOBALS['TSFE']->config['config']['disableWrapInBaseClass'])
{
public function pi_wrapInBaseClass($content) {
if (!$GLOBALS['TSFE']->config['config']['disableWrapInBaseClass']) {
// Use get_class($this) instead of $this->prefixId for content wrapping because $this->prefixId is the same for all plugins.
$content = '<div class="tx-dlf-'.get_class($this).'">'.$content.'</div>';
if (!$GLOBALS['TSFE']->config['config']['disablePrefixComment'])
{
if (!$GLOBALS['TSFE']->config['config']['disablePrefixComment']) {
$content = "\n\n<!-- BEGIN: Content of extension '".$this->extKey."', plugin '".get_class($this)."' -->\n\n".$content."\n\n<!-- END: Content of extension '".$this->extKey."', plugin '".get_class($this)."' -->\n\n";
}
}
@ -230,8 +210,7 @@ abstract class AbstractPlugin extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
*
* @return array The resulting typoscript array
*/
protected function parseTS($string = '')
{
protected function parseTS($string = '') {
$parser = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::class);
$parser->parse($string);
return $parser->setup;
@ -246,15 +225,12 @@ abstract class AbstractPlugin extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
*
* @return void
*/
protected function setCache($cache = TRUE)
{
if ($cache)
{
protected function setCache($cache = TRUE) {
if ($cache) {
// Set cObject type to "USER" (default).
$this->pi_USER_INT_obj = FALSE;
$this->pi_checkCHash = TRUE;
if (count($this->piVars))
{
if (count($this->piVars)) {
// Check cHash or disable caching.
$GLOBALS['TSFE']->reqCHash();
}

File diff suppressed because it is too large Load Diff

View File

@ -20,8 +20,7 @@ namespace Kitodo\Dlf\Common;
* @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
@ -91,11 +90,9 @@ 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 = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($position, 0, $this->count, $this->count);
if (!empty($elements))
{
if (!empty($elements)) {
array_splice($this->elements, $position, 0, $elements);
$this->count = count($this->elements);
}
@ -109,8 +106,7 @@ 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;
}
@ -122,14 +118,11 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return array The current element
*/
public function current()
{
if ($this->valid())
{
public function current() {
if ($this->valid()) {
return $this->getRecord($this->elements[$this->position]);
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\DocumentList->current()] Invalid position "'.$this->position.'" for list element', $this->extKey, SYSLOG_SEVERITY_NOTICE);
}
return;
@ -145,14 +138,11 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return mixed The element's full record
*/
protected function getRecord($element)
{
protected function getRecord($element) {
if (is_array($element)
&& array_keys($element) == ['u', 'h', 's', 'p'])
{
&& array_keys($element) == ['u', 'h', 's', 'p']) {
// Return already processed record if possible.
if (!empty($this->records[$element['u']]))
{
if (!empty($this->records[$element['u']])) {
return $this->records[$element['u']];
}
$record = [
@ -163,8 +153,7 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
];
// Check if it's a list of database records or Solr documents.
if (!empty($this->metadata['options']['source'])
&& $this->metadata['options']['source'] == 'collection')
{
&& $this->metadata['options']['source'] == 'collection') {
// Get document's thumbnail and metadata from database.
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'tx_dlf_documents.uid AS uid,tx_dlf_documents.thumbnail AS thumbnail,tx_dlf_documents.metadata AS metadata',
@ -176,38 +165,30 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
''
);
// Process results.
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result))
{
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
// Prepare document's metadata.
$metadata = unserialize($resArray['metadata']);
if (!empty($metadata['type'][0])
&& \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($metadata['type'][0]))
{
&& \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($metadata['type'][0])) {
$metadata['type'][0] = Helper::getIndexName($metadata['type'][0], 'tx_dlf_structures', $this->metadata['options']['pid']);
}
if (!empty($metadata['owner'][0])
&& \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($metadata['owner'][0]))
{
&& \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($metadata['owner'][0])) {
$metadata['owner'][0] = Helper::getIndexName($metadata['owner'][0], 'tx_dlf_libraries', $this->metadata['options']['pid']);
}
if (!empty($metadata['collection'])
&& is_array($metadata['collection']))
{
foreach ($metadata['collection'] as $i => $collection)
{
if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($collection))
{
&& is_array($metadata['collection'])) {
foreach ($metadata['collection'] as $i => $collection) {
if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($collection)) {
$metadata['collection'][$i] = Helper::getIndexName($metadata['collection'][$i], 'tx_dlf_collections', $this->metadata['options']['pid']);
}
}
}
// Add metadata to list element.
if ($resArray['uid'] == $record['uid'])
{
if ($resArray['uid'] == $record['uid']) {
$record['thumbnail'] = $resArray['thumbnail'];
$record['metadata'] = $metadata;
} elseif (($key = array_search(['u' => $resArray['uid']], $record['subparts'], TRUE)) !== FALSE)
{
} elseif (($key = array_search(['u' => $resArray['uid']], $record['subparts'], TRUE)) !== FALSE) {
$record['subparts'][$key] = [
'uid' => $resArray['uid'],
'page' => 1,
@ -218,20 +199,16 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
}
}
} elseif (!empty($this->metadata['options']['source'])
&& $this->metadata['options']['source'] == 'search')
{
if ($this->solrConnect())
{
&& $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)
{
foreach ($this->solrConfig as $solr_name) {
$params['fields'] .= ','.$solr_name;
}
// If it is a fulltext search, enable highlighting.
if ($this->metadata['fulltextSearch'])
{
if ($this->metadata['fulltextSearch']) {
$params['component'] = [
'highlighting' => [
'query' => Solr::escapeQuery($this->metadata['searchString']),
@ -248,10 +225,8 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
// Take over existing filter queries.
$params['filterquery'] = isset($this->metadata['options']['params']['filterquery']) ? $this->metadata['options']['params']['filterquery'] : [];
// Extend filter query to get all documents with the same UID.
foreach ($params['filterquery'] as $key => $value)
{
if (isset($value['query']))
{
foreach ($params['filterquery'] as $key => $value) {
if (isset($value['query'])) {
$params['filterquery'][$key]['query'] = $value['query'].' OR toplevel:true';
}
}
@ -265,25 +240,20 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
$selectQuery = $this->solr->service->createSelect($params);
$result = $this->solr->service->select($selectQuery);
// If it is a fulltext search, fetch the highlighting results.
if ($this->metadata['fulltextSearch'])
{
if ($this->metadata['fulltextSearch']) {
$highlighting = $result->getHighlighting();
}
// Process results.
foreach ($result as $resArray)
{
foreach ($result as $resArray) {
// Prepare document's metadata.
$metadata = [];
foreach ($this->solrConfig as $index_name => $solr_name)
{
if (!empty($resArray->$solr_name))
{
foreach ($this->solrConfig as $index_name => $solr_name) {
if (!empty($resArray->$solr_name)) {
$metadata[$index_name] = (is_array($resArray->$solr_name) ? $resArray->$solr_name : [$resArray->$solr_name]);
}
}
// Add metadata to list elements.
if ($resArray->toplevel)
{
if ($resArray->toplevel) {
$record['thumbnail'] = $resArray->thumbnail;
$record['metadata'] = $metadata;
} else {
@ -303,8 +273,7 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
// Save record for later usage.
$this->records[$element['u']] = $record;
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\DocumentList->getRecord([data])] No UID of list element to fetch full record', $this->extKey, SYSLOG_SEVERITY_NOTICE, $element);
}
$record = $element;
@ -320,8 +289,7 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return integer The current position
*/
public function key()
{
public function key() {
return $this->position;
}
@ -335,18 +303,15 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function move($position, $steps)
{
public function move($position, $steps) {
// Save parameters for logging purposes.
$_position = $position;
$_steps = $steps;
$position = intval($position);
// Check if list position is valid.
if ($position < 0
|| $position >= $this->count)
{
if (TYPO3_DLOG)
{
|| $position >= $this->count) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\DocumentList->move('.$_position.', '.$_steps.')] Invalid position "'.$position.'" for element moving', $this->extKey, SYSLOG_SEVERITY_WARNING);
}
return;
@ -354,10 +319,8 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
$steps = intval($steps);
// Check if moving given amount of steps is possible.
if (($position + $steps) < 0
|| ($position + $steps) >= $this->count)
{
if (TYPO3_DLOG)
{
|| ($position + $steps) >= $this->count) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\DocumentList->move('.$_position.', '.$_steps.')] Invalid steps "'.$steps.'" for moving element at position "'.$position.'"', $this->extKey, SYSLOG_SEVERITY_WARNING);
}
return;
@ -375,8 +338,7 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function moveUp($position)
{
public function moveUp($position) {
$this->move($position, -1);
}
@ -389,8 +351,7 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function moveDown($position)
{
public function moveDown($position) {
$this->move($position, 1);
}
@ -402,8 +363,7 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function next()
{
public function next() {
$this->position++;
}
@ -417,8 +377,7 @@ 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]);
}
@ -432,14 +391,11 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return array The element at the given offset
*/
public function offsetGet($offset)
{
if ($this->offsetExists($offset))
{
public function offsetGet($offset) {
if ($this->offsetExists($offset)) {
return $this->getRecord($this->elements[$offset]);
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\DocumentList->offsetGet('.$offset.')] Invalid offset "'.$offset.'" for list element', $this->extKey, SYSLOG_SEVERITY_NOTICE);
}
return;
@ -457,10 +413,8 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function offsetSet($offset, $value)
{
if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($offset))
{
public function offsetSet($offset, $value) {
if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($offset)) {
$this->elements[$offset] = $value;
} else {
$this->elements[] = $value;
@ -479,16 +433,13 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return array The removed element
*/
public function remove($position)
{
public function remove($position) {
// Save parameter for logging purposes.
$_position = $position;
$position = intval($position);
if ($position < 0
|| $position >= $this->count)
{
if (TYPO3_DLOG)
{
|| $position >= $this->count) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\DocumentList->remove('.$_position.')] Invalid position "'.$position.'" for element removing', $this->extKey, SYSLOG_SEVERITY_WARNING);
}
return;
@ -508,16 +459,13 @@ 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) {
// Save parameter for logging purposes.
$_position = $position;
$position = intval($position);
if ($position < 0
|| $position >= $this->count)
{
if (TYPO3_DLOG)
{
|| $position >= $this->count) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\DocumentList->remove('.$_position.')] Invalid position "'.$position.'" for element removing', $this->extKey, SYSLOG_SEVERITY_WARNING);
}
return;
@ -534,8 +482,7 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function reset()
{
public function reset() {
$this->elements = [];
$this->records = [];
$this->metadata = [];
@ -551,8 +498,7 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function rewind()
{
public function rewind() {
$this->position = 0;
}
@ -565,12 +511,10 @@ 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)
{
if ($pid > 0) {
// TODO: Liste in Datenbank speichern (inkl. Sichtbarkeit, Beschreibung, etc.)
} else {
Helper::saveToSession([$this->elements, $this->metadata], get_class($this));
@ -584,14 +528,11 @@ 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)
{
if (!$this->solr) {
// Connect to Solr server.
if ($this->solr = Solr::getInstance($this->metadata['options']['core']))
{
if ($this->solr = Solr::getInstance($this->metadata['options']['core'])) {
// Load index configuration.
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'tx_dlf_metadata.index_name AS index_name,tx_dlf_metadata.index_tokenized AS index_tokenized,tx_dlf_metadata.index_indexed AS index_indexed',
@ -603,8 +544,7 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
'tx_dlf_metadata.sorting ASC',
''
);
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result))
{
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
$this->solrConfig[$resArray['index_name']] = $resArray['index_name'].'_'.($resArray['index_tokenized'] ? 't' : 'u').'s'.($resArray['index_indexed'] ? 'i' : 'u');
}
// Add static fields.
@ -626,23 +566,19 @@ 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)
{
foreach ($this->elements as $num => $element) {
// Is this element sortable?
if (!empty($element['s'][$by]))
{
if (!empty($element['s'][$by])) {
$newOrder[$element['s'][$by].str_pad($num, 6, '0', STR_PAD_LEFT)] = $element;
} else {
$nonSortable[] = $element;
}
}
// Reorder elements.
if ($asc)
{
if ($asc) {
ksort($newOrder, SORT_LOCALE_STRING);
} else {
krsort($newOrder, SORT_LOCALE_STRING);
@ -650,12 +586,10 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
// Add non sortable elements to the end of the list.
$newOrder = array_merge(array_values($newOrder), $nonSortable);
// Check if something is missing.
if ($this->count == count($newOrder))
{
if ($this->count == count($newOrder)) {
$this->elements = $newOrder;
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\DocumentList->sort('.$by.', ['.($asc ? 'TRUE' : 'FALSE').'])] Sorted list elements do not match unsorted elements', $this->extKey, SYSLOG_SEVERITY_ERROR);
}
}
@ -671,8 +605,7 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function offsetUnset($offset)
{
public function offsetUnset($offset) {
unset ($this->elements[$offset]);
// Re-number the elements.
$this->elements = array_values($this->elements);
@ -687,8 +620,7 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return boolean Is the current list position valid?
*/
public function valid()
{
public function valid() {
return isset($this->elements[$this->position]);
}
@ -699,8 +631,7 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return array The list's metadata
*/
protected function _getMetadata()
{
protected function _getMetadata() {
return $this->metadata;
}
@ -713,8 +644,7 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
protected function _setMetadata(array $metadata = [])
{
protected function _setMetadata(array $metadata = []) {
$this->metadata = $metadata;
}
@ -728,22 +658,17 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function __construct(array $elements = [], array $metadata = [])
{
public function __construct(array $elements = [], array $metadata = []) {
if (empty($elements)
&& empty($metadata))
{
&& empty($metadata)) {
// Let's check the user's session.
$sessionData = Helper::loadFromSession(get_class($this));
// Restore list from session data.
if (is_array($sessionData))
{
if (is_array($sessionData[0]))
{
if (is_array($sessionData)) {
if (is_array($sessionData[0])) {
$this->elements = $sessionData[0];
}
if (is_array($sessionData[1]))
{
if (is_array($sessionData[1])) {
$this->metadata = $sessionData[1];
}
}
@ -776,14 +701,11 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return mixed Value of $this->$var
*/
public function __get($var)
{
public function __get($var) {
$method = '_get'.ucfirst($var);
if (!property_exists($this, $var)
|| !method_exists($this, $method))
{
if (TYPO3_DLOG)
{
|| !method_exists($this, $method)) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\DocumentList->__get('.$var.')] There is no getter function for property "'.$var.'"', $this->extKey, SYSLOG_SEVERITY_WARNING);
}
return;
@ -802,14 +724,11 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function __set($var, $value)
{
public function __set($var, $value) {
$method = '_set'.ucfirst($var);
if (!property_exists($this, $var)
|| !method_exists($this, $method))
{
if (TYPO3_DLOG)
{
|| !method_exists($this, $method)) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\DocumentList->__set('.$var.', [data])] There is no setter function for property "'.$var.'"', $this->extKey, SYSLOG_SEVERITY_WARNING, $value);
}
} else {
@ -825,8 +744,7 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return array Properties to be serialized
*/
public function __sleep()
{
public function __sleep() {
return ['elements', 'metadata'];
}
@ -838,8 +756,7 @@ class DocumentList implements \ArrayAccess, \Countable, \Iterator, \TYPO3\CMS\Co
*
* @return void
*/
public function __wakeup()
{
public function __wakeup() {
$this->count = count($this->elements);
}
}

View File

@ -20,8 +20,7 @@ namespace Kitodo\Dlf\Common;
* @subpackage dlf
* @access public
*/
class DocumentTypeCheck
{
class DocumentTypeCheck {
/**
* This holds the current document
*
@ -62,12 +61,10 @@ class DocumentTypeCheck
*
* @return string The type of the current document
*/
public function getDocType()
{
public function getDocType() {
// Load current document.
$this->loadDocument();
if ($this->doc === NULL)
{
if ($this->doc === NULL) {
// Quit without doing anything if document not available.
return '';
}
@ -86,12 +83,10 @@ class DocumentTypeCheck
* - children array ([0]) --> type = month
* - children array ([0], [1], [2], ...) --> type = day --> Issue
*/
switch ($toc[0]['type'])
{
switch ($toc[0]['type']) {
case 'newspaper':
$nodes_year = $this->doc->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]/mets:div[@TYPE="newspaper"]/mets:div[@TYPE="year"]');
if (count($nodes_year) > 1)
{
if (count($nodes_year) > 1) {
// Multiple years means this is a newspaper's anchor file.
return 'newspaper';
} else {
@ -100,26 +95,22 @@ class DocumentTypeCheck
$nodes_issue = $this->doc->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]/mets:div[@TYPE="newspaper"]/mets:div[@TYPE="year"]//mets:div[@TYPE="issue"]');
$nodes_issue_current = $this->doc->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]/mets:div[@TYPE="newspaper"]/mets:div[@TYPE="year"]//mets:div[@TYPE="issue"]/@DMDID');
if (count($nodes_year) == 1
&& count($nodes_issue) == 0)
{
&& count($nodes_issue) == 0) {
// It's possible to have only one year in the newspaper's anchor file.
return 'newspaper';
} elseif (count($nodes_year) == 1
&& count($nodes_month) > 1)
{
&& count($nodes_month) > 1) {
// One year, multiple months means this is a year's anchor file.
return 'year';
} elseif (count($nodes_year) == 1
&& count($nodes_month) == 1
&& count($nodes_day) > 1)
{
&& count($nodes_day) > 1) {
// One year, one month, one or more days means this is a year's anchor file.
return 'year';
} elseif (count($nodes_year) == 1
&& count($nodes_month) == 1
&& count($nodes_day) == 1
&& count($nodes_issue_current) == 0)
{
&& count($nodes_issue_current) == 0) {
// One year, one month, a single day, one or more issues (but not the current one) means this is a year's anchor file.
return 'year';
} else {
@ -140,24 +131,19 @@ class DocumentTypeCheck
*
* @return void
*/
protected function loadDocument()
{
protected function loadDocument() {
// Check for required variable.
if (!empty($this->piVars['id']))
{
if (!empty($this->piVars['id'])) {
// Get instance of \Kitodo\Dlf\Common\Document.
$this->doc = Document::getInstance($this->piVars['id']);
if (!$this->doc->ready)
{
if (!$this->doc->ready) {
// Destroy the incomplete object.
$this->doc = NULL;
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\DocumentTypeCheck->loadDocument()] Failed to load document with UID "'.$this->piVars['id'].'"', $this->extKey, SYSLOG_SEVERITY_WARNING);
}
}
} elseif (!empty($this->piVars['recordId']))
{
} elseif (!empty($this->piVars['recordId'])) {
// Get UID of document with given record identifier.
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'tx_dlf_documents.uid',
@ -168,8 +154,7 @@ class DocumentTypeCheck
'',
'1'
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) == 1)
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) == 1) {
list ($this->piVars['id']) = $GLOBALS['TYPO3_DB']->sql_fetch_row($result);
// Set superglobal $_GET array.
$_GET[$this->prefixId]['id'] = $this->piVars['id'];
@ -178,8 +163,7 @@ class DocumentTypeCheck
// Try to load document.
$this->loadDocument();
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\DocumentTypeCheck->loadDocument()] Failed to load document with record ID "'.$this->piVars['recordId'].'"', $this->extKey, SYSLOG_SEVERITY_WARNING);
}
}
@ -193,8 +177,7 @@ class DocumentTypeCheck
*
* @return void
*/
public function __construct()
{
public function __construct() {
// Load current plugin parameters.
$this->piVars = \TYPO3\CMS\Core\Utility\GeneralUtility::_GPmerged($this->prefixId);
}

View File

@ -20,8 +20,7 @@ namespace Kitodo\Dlf\Common;
* @access public
* @abstract
*/
interface FulltextInterface
{
interface FulltextInterface {
/**
* This extracts raw fulltext data from XML
*

View File

@ -20,8 +20,7 @@ namespace Kitodo\Dlf\Common;
* @subpackage dlf
* @access public
*/
class Helper
{
class Helper {
/**
* The extension key
*
@ -64,69 +63,54 @@ class Helper
*
* @return boolean Is $id a valid GNL identifier of the given $type?
*/
public static function checkIdentifier($id, $type)
{
public static function checkIdentifier($id, $type) {
$digits = substr($id, 0, 8);
$checksum = 0;
for ($i = 0, $j = strlen($digits); $i < $j; $i++)
{
for ($i = 0, $j = strlen($digits); $i < $j; $i++) {
$checksum += (9 - $i) * intval(substr($digits, $i, 1));
}
$checksum = (11 - ($checksum % 11)) % 11;
switch (strtoupper($type))
{
switch (strtoupper($type)) {
case 'PPN':
case 'IDN':
case 'PND':
if ($checksum == 10)
{
if ($checksum == 10) {
$checksum = 'X';
}
if (!preg_match('/[0-9]{8}[0-9X]{1}/i', $id))
{
if (!preg_match('/[0-9]{8}[0-9X]{1}/i', $id)) {
return FALSE;
} elseif (strtoupper(substr($id, -1, 1)) != $checksum)
{
} elseif (strtoupper(substr($id, -1, 1)) != $checksum) {
return FALSE;
}
break;
case 'ZDB':
if ($checksum == 10)
{
if ($checksum == 10) {
$checksum = 'X';
}
if (!preg_match('/[0-9]{8}-[0-9X]{1}/i', $id))
{
if (!preg_match('/[0-9]{8}-[0-9X]{1}/i', $id)) {
return FALSE;
} elseif (strtoupper(substr($id, -1, 1)) != $checksum)
{
} elseif (strtoupper(substr($id, -1, 1)) != $checksum) {
return FALSE;
}
break;
case 'SWD':
$checksum = 11 - $checksum;
if (!preg_match('/[0-9]{8}-[0-9]{1}/i', $id))
{
if (!preg_match('/[0-9]{8}-[0-9]{1}/i', $id)) {
return FALSE;
} elseif ($checksum == 10)
{
} elseif ($checksum == 10) {
return self::checkIdentifier(($digits + 1).substr($id, -2, 2), 'SWD');
} elseif (substr($id, -1, 1) != $checksum)
{
} elseif (substr($id, -1, 1) != $checksum) {
return FALSE;
}
break;
case 'GKD':
$checksum = 11 - $checksum;
if ($checksum == 10)
{
if ($checksum == 10) {
$checksum = 'X';
}
if (!preg_match('/[0-9]{8}-[0-9X]{1}/i', $id))
{
if (!preg_match('/[0-9]{8}-[0-9X]{1}/i', $id)) {
return FALSE;
} elseif (strtoupper(substr($id, -1, 1)) != $checksum)
{
} elseif (strtoupper(substr($id, -1, 1)) != $checksum) {
return FALSE;
}
break;
@ -145,31 +129,24 @@ class Helper
*
* @return mixed The decrypted value or NULL on error
*/
public static function decrypt($encrypted, $hash)
{
public static function decrypt($encrypted, $hash) {
$decrypted = NULL;
// Check for PHP extension "mcrypt".
if (!extension_loaded('mcrypt'))
{
if (TYPO3_DLOG)
{
if (!extension_loaded('mcrypt')) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->decrypt('.$encrypted.', '.$hash.')] PHP extension "mcrypt" not available', self::$extKey, SYSLOG_SEVERITY_WARNING);
}
return;
}
if (empty($encrypted)
|| empty($hash))
{
if (TYPO3_DLOG)
{
|| empty($hash)) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->decrypt('.$encrypted.', '.$hash.')] Invalid parameters given for decryption', self::$extKey, SYSLOG_SEVERITY_ERROR);
}
return;
}
if (empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']))
{
if (TYPO3_DLOG)
{
if (empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'])) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->decrypt('.$encrypted.', '.$hash.')] No encryption key set in TYPO3 configuration', self::$extKey, SYSLOG_SEVERITY_ERROR);
}
return;
@ -178,10 +155,8 @@ class Helper
$decrypted = mcrypt_decrypt(MCRYPT_BLOWFISH, substr($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'], 0, 56), base64_decode($encrypted), MCRYPT_MODE_CFB, $iv);
$salt = substr($hash, 0, 10);
$hashed = $salt.substr(sha1($salt.$decrypted), -10);
if ($hashed !== $hash)
{
if (TYPO3_DLOG)
{
if ($hashed !== $hash) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->decrypt('.$encrypted.', '.$hash.')] Invalid hash "'.$hash.'" given for decryption', self::$extKey, SYSLOG_SEVERITY_WARNING);
}
return;
@ -199,21 +174,16 @@ class Helper
*
* @return array Array with encrypted string and control hash
*/
public static function encrypt($string)
{
public static function encrypt($string) {
// Check for PHP extension "mcrypt".
if (!extension_loaded('mcrypt'))
{
if (TYPO3_DLOG)
{
if (!extension_loaded('mcrypt')) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->encrypt('.$string.')] PHP extension "mcrypt" not available', self::$extKey, SYSLOG_SEVERITY_WARNING);
}
return;
}
if (empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']))
{
if (TYPO3_DLOG)
{
if (empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'])) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->encrypt('.$string.')] No encryption key set in TYPO3 configuration', self::$extKey, SYSLOG_SEVERITY_ERROR);
}
return;
@ -234,8 +204,7 @@ class Helper
*/
public static function getBeUser() {
if (TYPO3_MODE === 'FE'
|| TYPO3_MODE === 'BE')
{
|| TYPO3_MODE === 'BE') {
// Initialize backend session with CLI user's rights.
$userObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Authentication\BackendUserAuthentication::class);
$userObj->dontSetCookie = TRUE;
@ -244,8 +213,7 @@ class Helper
$userObj->backendCheckLogin();
return $userObj;
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->getBeUser()] Unexpected TYPO3_MODE "'.TYPO3_MODE.'"', self::$extKey, SYSLOG_SEVERITY_ERROR);
}
return;
@ -261,8 +229,7 @@ class Helper
*
* @return string The cleaned up string
*/
public static function getCleanString($string)
{
public static function getCleanString($string) {
// Convert to lowercase.
$string = strtolower($string);
// Remove non-alphanumeric characters.
@ -281,21 +248,16 @@ class Helper
*
* @return \TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication Instance of \TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication or NULL on failure
*/
public static function getFeUser()
{
if (TYPO3_MODE === 'FE')
{
public static function getFeUser() {
if (TYPO3_MODE === 'FE') {
// Check if a user is currently logged in.
if (!empty($GLOBALS['TSFE']->loginUser))
{
if (!empty($GLOBALS['TSFE']->loginUser)) {
return $GLOBALS['TSFE']->fe_user;
} elseif (\TYPO3\CMS\Core\Utility\GeneralUtility::_GP('eID') !== NULL)
{
} elseif (\TYPO3\CMS\Core\Utility\GeneralUtility::_GP('eID') !== NULL) {
return \TYPO3\CMS\Frontend\Utility\EidUtility::initFeUser();
}
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->getFeUser()] Unexpected TYPO3_MODE "'.TYPO3_MODE.'"', self::$extKey, SYSLOG_SEVERITY_ERROR);
}
}
@ -311,13 +273,10 @@ class Helper
*
* @return array Array of hook objects for the class
*/
public static function getHookObjects($scriptRelPath)
{
public static function getHookObjects($scriptRelPath) {
$hookObjects = [];
if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::$extKey.'/'.$scriptRelPath]['hookClass']))
{
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::$extKey.'/'.$scriptRelPath]['hookClass'] as $classRef)
{
if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::$extKey.'/'.$scriptRelPath]['hookClass'])) {
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::$extKey.'/'.$scriptRelPath]['hookClass'] as $classRef) {
$hookObjects[] = &\TYPO3\CMS\Core\Utility\GeneralUtility::getUserObj($classRef);
}
}
@ -335,26 +294,22 @@ class Helper
*
* @return string "index_name" for the given UID
*/
public static function getIndexName($uid, $table, $pid = -1)
{
public static function getIndexName($uid, $table, $pid = -1) {
// Save parameters for logging purposes.
$_uid = $uid;
$_pid = $pid;
// Sanitize input.
$uid = max(intval($uid), 0);
if (!$uid
|| !in_array($table, ['tx_dlf_collections', 'tx_dlf_libraries', 'tx_dlf_metadata', 'tx_dlf_structures', 'tx_dlf_solrcores']))
{
if (TYPO3_DLOG)
{
|| !in_array($table, ['tx_dlf_collections', 'tx_dlf_libraries', 'tx_dlf_metadata', 'tx_dlf_structures', 'tx_dlf_solrcores'])) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->getIndexName('.$_uid.', '.$table.', '.$_pid.')] Invalid UID "'.$uid.'" or table "'.$table.'"', self::$extKey, SYSLOG_SEVERITY_ERROR);
}
return '';
}
$where = '';
// Should we check for a specific PID, too?
if ($pid !== -1)
{
if ($pid !== -1) {
$pid = max(intval($pid), 0);
$where = ' AND '.$table.'.pid='.$pid;
}
@ -369,13 +324,11 @@ class Helper
'',
'1'
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0)
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0) {
$resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result);
return $resArray['index_name'];
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->getIndexName('.$_uid.', '.$table.', '.$_pid.')] No "index_name" with UID "'.$uid.'" and PID "'.$pid.'" found in table "'.$table.'"', self::$extKey, SYSLOG_SEVERITY_WARNING);
}
return '';
@ -393,24 +346,20 @@ class Helper
*
* @return string "uid" for the given index_name
*/
public static function getIdFromIndexName($index_name, $table, $pid = -1)
{
public static function getIdFromIndexName($index_name, $table, $pid = -1) {
// Save parameters for logging purposes.
$_index_name = $index_name;
$_pid = $pid;
if (!$index_name
|| !in_array($table, ['tx_dlf_collections', 'tx_dlf_libraries', 'tx_dlf_metadata', 'tx_dlf_structures', 'tx_dlf_solrcores']))
{
if (TYPO3_DLOG)
{
|| !in_array($table, ['tx_dlf_collections', 'tx_dlf_libraries', 'tx_dlf_metadata', 'tx_dlf_structures', 'tx_dlf_solrcores'])) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->getIdFromIndexName('.$_index_name.', '.$table.', '.$_pid.')] Invalid UID "'.$index_name.'" or table "'.$table.'"', self::$extKey, SYSLOG_SEVERITY_ERROR);
}
return '';
}
$where = '';
// Should we check for a specific PID, too?
if ($pid !== -1)
{
if ($pid !== -1) {
$pid = max(intval($pid), 0);
$where = ' AND '.$table.'.pid='.$pid;
}
@ -425,13 +374,11 @@ class Helper
'',
'1'
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0)
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0) {
$resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result);
return $resArray['uid'];
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->getIdFromIndexName('.$_index_name.', '.$table.', '.$_pid.')] No UID for given "index_name" "'.$index_name.'" and PID "'.$pid.'" found in table "'.$table.'"', self::$extKey, SYSLOG_SEVERITY_WARNING);
}
return '';
@ -447,48 +394,38 @@ class Helper
*
* @return string Localized full name of language or unchanged input
*/
public static function getLanguageName($code)
{
public static function getLanguageName($code) {
// Analyze code and set appropriate ISO table.
$isoCode = strtolower(trim($code));
if (preg_match('/^[a-z]{3}$/', $isoCode))
{
if (preg_match('/^[a-z]{3}$/', $isoCode)) {
$file = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath(self::$extKey).'Resources/Private/ISO-639/iso-639-2b.xml';
} elseif (preg_match('/^[a-z]{2}$/', $isoCode))
{
} elseif (preg_match('/^[a-z]{2}$/', $isoCode)) {
$file = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath(self::$extKey).'Resources/Private/ISO-639/iso-639-1.xml';
} else {
// No ISO code, return unchanged.
return $code;
}
// Load ISO table and get localized full name of language.
if (TYPO3_MODE === 'FE')
{
if (TYPO3_MODE === 'FE') {
$iso639 = $GLOBALS['TSFE']->readLLfile($file);
if (!empty($iso639['default'][$isoCode]))
{
if (!empty($iso639['default'][$isoCode])) {
$lang = $GLOBALS['TSFE']->getLLL($isoCode, $iso639);
}
} elseif (TYPO3_MODE === 'BE')
{
} elseif (TYPO3_MODE === 'BE') {
$iso639 = $GLOBALS['LANG']->includeLLFile($file, FALSE, TRUE);
if (!empty($iso639['default'][$isoCode]))
{
if (!empty($iso639['default'][$isoCode])) {
$lang = $GLOBALS['LANG']->getLLL($isoCode, $iso639, FALSE);
}
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->getLanguageName('.$code.')] Unexpected TYPO3_MODE "'.TYPO3_MODE.'"', self::$extKey, SYSLOG_SEVERITY_ERROR);
}
return $code;
}
if (!empty($lang))
{
if (!empty($lang)) {
return $lang;
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->getLanguageName('.$code.')] Language code "'.$code.'" not found in ISO-639 table', self::$extKey, SYSLOG_SEVERITY_NOTICE);
}
return $code;
@ -506,42 +443,32 @@ class Helper
*
* @return string The translated string or the given key on failure
*/
public static function getMessage($key, $hsc = FALSE, $default = '')
{
public static function getMessage($key, $hsc = FALSE, $default = '') {
// Set initial output to default value.
$translated = (string) $default;
// Load common messages file.
if (empty(self::$messages))
{
if (empty(self::$messages)) {
$file = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath(self::$extKey, 'Resources/Private/Language/FlashMessages.xml');
if (TYPO3_MODE === 'FE')
{
if (TYPO3_MODE === 'FE') {
self::$messages = $GLOBALS['TSFE']->readLLfile($file);
} elseif (TYPO3_MODE === 'BE')
{
} elseif (TYPO3_MODE === 'BE') {
self::$messages = $GLOBALS['LANG']->includeLLFile($file, FALSE, TRUE);
} elseif (TYPO3_DLOG)
{
} elseif (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->getMessage('.$key.', '.$default.', ['.($hsc ? 'TRUE' : 'FALSE').'])] Unexpected TYPO3_MODE "'.TYPO3_MODE.'"', self::$extKey, SYSLOG_SEVERITY_ERROR);
}
}
// Get translation.
if (!empty(self::$messages['default'][$key]))
{
if (TYPO3_MODE === 'FE')
{
if (!empty(self::$messages['default'][$key])) {
if (TYPO3_MODE === 'FE') {
$translated = $GLOBALS['TSFE']->getLLL($key, self::$messages);
} elseif (TYPO3_MODE === 'BE')
{
} elseif (TYPO3_MODE === 'BE') {
$translated = $GLOBALS['LANG']->getLLL($key, self::$messages, FALSE);
} elseif (TYPO3_DLOG)
{
} elseif (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->getMessage('.$key.', '.$default.', ['.($hsc ? 'TRUE' : 'FALSE').'])] Unexpected TYPO3_MODE "'.TYPO3_MODE.'"', self::$extKey, SYSLOG_SEVERITY_ERROR);
}
}
// Escape HTML characters if applicable.
if ($hsc)
{
if ($hsc) {
$translated = htmlspecialchars($translated);
}
return $translated;
@ -558,8 +485,7 @@ class Helper
*
* @return string Uniform Resource Name as string
*/
public static function getURN($base, $id)
{
public static function getURN($base, $id) {
$concordance = [
'0' => 1,
'1' => 2,
@ -601,22 +527,18 @@ class Helper
':' => 17,
];
$urn = strtolower($base.$id);
if (preg_match('/[^a-z0-9:-]/', $urn))
{
if (TYPO3_DLOG)
{
if (preg_match('/[^a-z0-9:-]/', $urn)) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->getURN('.$base.', '.$id.')] Invalid chars in given parameters', self::$extKey, SYSLOG_SEVERITY_WARNING);
}
return '';
}
$digits = '';
for ($i = 0, $j = strlen($urn); $i < $j; $i++)
{
for ($i = 0, $j = strlen($urn); $i < $j; $i++) {
$digits .= $concordance[substr($urn, $i, 1)];
}
$checksum = 0;
for ($i = 0, $j = strlen($digits); $i < $j; $i++)
{
for ($i = 0, $j = strlen($digits); $i < $j; $i++) {
$checksum += ($i + 1) * intval(substr($digits, $i, 1));
}
$checksum = substr(intval($checksum / intval(substr($digits, -1, 1))), -1, 1);
@ -632,8 +554,7 @@ class Helper
*
* @return boolean Is $id a valid PPN?
*/
public static function isPPN($id)
{
public static function isPPN($id) {
return self::checkIdentifier($id, 'PPN');
}
@ -646,30 +567,24 @@ class Helper
*
* @return mixed Session value for given key or NULL on failure
*/
public static function loadFromSession($key)
{
public static function loadFromSession($key) {
// Save parameter for logging purposes.
$_key = $key;
// Cast to string for security reasons.
$key = (string) $key;
if (!$key)
{
if (TYPO3_DLOG)
{
if (!$key) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->loadFromSession('.$_key.')] Invalid key "'.$key.'" for session data retrieval', self::$extKey, SYSLOG_SEVERITY_WARNING);
}
return;
}
// Get the session data.
if (TYPO3_MODE === 'FE')
{
if (TYPO3_MODE === 'FE') {
return $GLOBALS['TSFE']->fe_user->getKey('ses', $key);
} elseif (TYPO3_MODE === 'BE')
{
} elseif (TYPO3_MODE === 'BE') {
return $GLOBALS['BE_USER']->getSessionData($key);
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->loadFromSession('.$_key.')] Unexpected TYPO3_MODE "'.TYPO3_MODE.'"', self::$extKey, SYSLOG_SEVERITY_ERROR);
}
return;
@ -688,16 +603,14 @@ class Helper
*
* @return array Array of substituted "NEW..." identifiers and their actual UIDs.
*/
public static function processDB(array $data = [], array $cmd = [], $reverseOrder = FALSE, $be_user = FALSE)
{
public static function processDB(array $data = [], array $cmd = [], $reverseOrder = FALSE, $be_user = FALSE) {
// Instantiate TYPO3 core engine.
$tce = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\DataHandling\DataHandler::class);
// Set some configuration variables.
$tce->stripslashes_values = FALSE;
// Get backend user for processing.
if ($be_user
&& isset($GLOBALS['BE_USER']))
{
&& isset($GLOBALS['BE_USER'])) {
$user = $GLOBALS['BE_USER'];
} else {
$user = self::getBeUser();
@ -706,19 +619,16 @@ class Helper
$tce->start($data, $cmd, $user);
// Process command map first if default order is reversed.
if ($cmd
&& $reverseOrder)
{
&& $reverseOrder) {
$tce->process_cmdmap();
}
// Process data map.
if ($data)
{
if ($data) {
$tce->process_datamap();
}
// Process command map if processing order is not reversed.
if ($cmd
&& !$reverseOrder)
{
&& !$reverseOrder) {
$tce->process_cmdmap();
}
return $tce->substNEWwithIDs;
@ -735,15 +645,12 @@ class Helper
*
* @return array Array of substituted "NEW..." identifiers and their actual UIDs.
*/
public static function processDBasAdmin(array $data = [], array $cmd = [], $reverseOrder = FALSE)
{
public static function processDBasAdmin(array $data = [], array $cmd = [], $reverseOrder = FALSE) {
if (TYPO3_MODE === 'BE'
&& $GLOBALS['BE_USER']->isAdmin())
{
&& $GLOBALS['BE_USER']->isAdmin()) {
return self::processDB($data, $cmd, $reverseOrder, TRUE);
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->processDBasAdmin([data->data], [data->cmd], ['.($reverseOrder ? 'TRUE' : 'FALSE').'])] Current backend user has no admin privileges', self::$extKey, SYSLOG_SEVERITY_ERROR, ['data' => $data, 'cmd' => $cmd]);
}
return [];
@ -757,24 +664,20 @@ class Helper
*
* @return string All flash messages in the queue rendered as HTML.
*/
public static function renderFlashMessages()
{
public static function renderFlashMessages() {
$flashMessageService = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessageService::class);
$content = '';
// Since TYPO3 7.4.0, \TYPO3\CMS\Core\Messaging\FlashMessageQueue::renderFlashMessages
// uses htmlspecialchars on all texts, but we have message text with HTML tags.
// Therefore we copy the implementation from 7.4.0, but remove the htmlspecialchars call.
$flashMessages = $flashMessageService->getMessageQueueByIdentifier()->getAllMessagesAndFlush();
if (!empty($flashMessages))
{
if (!empty($flashMessages)) {
$content .= '<ul class="typo3-messages">';
foreach ($flashMessages as $flashMessage)
{
foreach ($flashMessages as $flashMessage) {
$severityClass = sprintf('alert %s', $flashMessage->getClass());
//~ $messageContent = htmlspecialchars($flashMessage->getMessage());
$messageContent = $flashMessage->getMessage();
if ($flashMessage->getTitle() !== '')
{
if ($flashMessage->getTitle() !== '') {
$messageContent = sprintf('<h4>%s</h4>', htmlspecialchars($flashMessage->getTitle())).$messageContent;
}
$content .= sprintf('<li class="%s">%s</li>', htmlspecialchars($severityClass), $messageContent);
@ -794,33 +697,27 @@ class Helper
*
* @return boolean TRUE on success, FALSE on failure
*/
public static function saveToSession($value, $key)
{
public static function saveToSession($value, $key) {
// Save parameter for logging purposes.
$_key = $key;
// Cast to string for security reasons.
$key = (string) $key;
if (!$key)
{
if (TYPO3_DLOG)
{
if (!$key) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->saveToSession([data], '.$_key.')] Invalid key "'.$key.'" for session data saving', self::$extKey, SYSLOG_SEVERITY_WARNING, $value);
}
return FALSE;
}
// Save value in session data.
if (TYPO3_MODE === 'FE')
{
if (TYPO3_MODE === 'FE') {
$GLOBALS['TSFE']->fe_user->setKey('ses', $key, $value);
$GLOBALS['TSFE']->fe_user->storeSessionData();
return TRUE;
} elseif (TYPO3_MODE === 'BE')
{
} elseif (TYPO3_MODE === 'BE') {
$GLOBALS['BE_USER']->setAndSaveSessionData($key, $value);
return TRUE;
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->saveToSession([data], '.$_key.')] Unexpected TYPO3_MODE "'.TYPO3_MODE.'"', self::$extKey, SYSLOG_SEVERITY_ERROR, $value);
}
return FALSE;
@ -838,8 +735,7 @@ class Helper
*
* @return string Localized label for $index_name
*/
public static function translate($index_name, $table, $pid)
{
public static function translate($index_name, $table, $pid) {
// Save parameters for logging purposes.
$_index_name = $index_name;
$_pid = $pid;
@ -847,17 +743,14 @@ class Helper
static $labels = [];
// Sanitize input.
$pid = max(intval($pid), 0);
if (!$pid)
{
if (TYPO3_DLOG)
{
if (!$pid) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->translate('.$_index_name.', '.$table.', '.$_pid.')] Invalid PID "'.$pid.'" for translation', self::$extKey, SYSLOG_SEVERITY_WARNING);
}
return $index_name;
}
// Check if "index_name" is an UID.
if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($index_name))
{
if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($index_name)) {
$index_name = self::getIndexName($index_name, $table, $pid);
}
/* $labels already contains the translated content element, but with the index_name of the translated content element itself
@ -874,8 +767,7 @@ class Helper
'',
''
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0)
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0) {
// Now we use the uid of the l18_parent to fetch the index_name of the translated content element.
$resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result);
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
@ -889,22 +781,18 @@ class Helper
'',
''
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0)
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0) {
// If there is an translated content element, overwrite the received $index_name.
$resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result);
$index_name = $resArray['index_name'];
}
}
// Check if we already got a translation.
if (empty($labels[$table][$pid][$GLOBALS['TSFE']->sys_language_content][$index_name]))
{
if (empty($labels[$table][$pid][$GLOBALS['TSFE']->sys_language_content][$index_name])) {
// Check if this table is allowed for translation.
if (in_array($table, ['tx_dlf_collections', 'tx_dlf_libraries', 'tx_dlf_metadata', 'tx_dlf_structures']))
{
if (in_array($table, ['tx_dlf_collections', 'tx_dlf_libraries', 'tx_dlf_metadata', 'tx_dlf_structures'])) {
$additionalWhere = ' AND sys_language_uid IN (-1,0)';
if ($GLOBALS['TSFE']->sys_language_content > 0)
{
if ($GLOBALS['TSFE']->sys_language_content > 0) {
$additionalWhere = ' AND (sys_language_uid IN (-1,0) OR (sys_language_uid='.intval($GLOBALS['TSFE']->sys_language_content).' AND l18n_parent=0))';
}
// Get labels from database.
@ -918,35 +806,28 @@ class Helper
'',
''
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0)
{
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result))
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0) {
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
// Overlay localized labels if available.
if ($GLOBALS['TSFE']->sys_language_content > 0)
{
if ($GLOBALS['TSFE']->sys_language_content > 0) {
$resArray = $GLOBALS['TSFE']->sys_page->getRecordOverlay($table, $resArray, $GLOBALS['TSFE']->sys_language_content, $GLOBALS['TSFE']->sys_language_contentOL);
}
if ($resArray)
{
if ($resArray) {
$labels[$table][$pid][$GLOBALS['TSFE']->sys_language_content][$resArray['index_name']] = $resArray['label'];
}
}
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->translate('.$_index_name.', '.$table.', '.$_pid.')] No translation with PID "'.$pid.'" available in table "'.$table.'" or translation not accessible', self::extKey, SYSLOG_SEVERITY_NOTICE);
}
}
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->translate('.$_index_name.', '.$table.', '.$_pid.')] No translations available for table "'.$table.'"', self::$extKey, SYSLOG_SEVERITY_WARNING);
}
}
}
if (!empty($labels[$table][$pid][$GLOBALS['TSFE']->sys_language_content][$index_name]))
{
if (!empty($labels[$table][$pid][$GLOBALS['TSFE']->sys_language_content][$index_name])) {
return $labels[$table][$pid][$GLOBALS['TSFE']->sys_language_content][$index_name];
} else {
return $index_name;
@ -963,13 +844,10 @@ class Helper
*
* @return string Additional WHERE clause
*/
public static function whereClause($table, $showHidden = FALSE)
{
if (TYPO3_MODE === 'FE')
{
public static function whereClause($table, $showHidden = FALSE) {
if (TYPO3_MODE === 'FE') {
// Table "tx_dlf_formats" always has PID 0.
if ($table == 'tx_dlf_formats')
{
if ($table == 'tx_dlf_formats') {
return \TYPO3\CMS\Backend\Utility\BackendUtility::deleteClause($table);
}
// Should we ignore the record's hidden flag?
@ -978,20 +856,17 @@ class Helper
$ignoreHide = 1;
}
// $GLOBALS['TSFE']->sys_page is not always available in frontend.
if (is_object($GLOBALS['TSFE']->sys_page))
{
if (is_object($GLOBALS['TSFE']->sys_page)) {
return $GLOBALS['TSFE']->sys_page->enableFields($table, $ignoreHide);
} else {
$pageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\Page\PageRepository::class);
$GLOBALS['TSFE']->includeTCA();
return $pageRepository->enableFields($table, $ignoreHide);
}
} elseif (TYPO3_MODE === 'BE')
{
} elseif (TYPO3_MODE === 'BE') {
return \TYPO3\CMS\Backend\Utility\BackendUtility::deleteClause($table);
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Helper->whereClause('.$table.', ['.($showHidden ? 'TRUE' : 'FALSE').'])] Unexpected TYPO3_MODE "'.TYPO3_MODE.'"', self::$extKey, SYSLOG_SEVERITY_ERROR);
}
return ' AND 1=-1';

View File

@ -19,8 +19,7 @@ namespace Kitodo\Dlf\Common;
* @subpackage dlf
* @access public
*/
class Indexer
{
class Indexer {
/**
* The extension key
*
@ -81,24 +80,18 @@ class Indexer
*
* @return integer 0 on success or 1 on failure
*/
public static function add(Document &$doc, $core = 0)
{
if (in_array($doc->uid, self::$processedDocs))
{
public static function add(Document &$doc, $core = 0) {
if (in_array($doc->uid, self::$processedDocs)) {
return 0;
} elseif (self::solrConnect($core, $doc->pid))
{
} elseif (self::solrConnect($core, $doc->pid)) {
$errors = 0;
// Handle multi-volume documents.
if ($doc->parentId)
{
if ($doc->parentId) {
$parent = Document::getInstance($doc->parentId, 0, TRUE);
if ($parent->ready)
{
if ($parent->ready) {
$errors = self::add($parent, $core);
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Indexer->add(['.$doc->uid.'], '.$core.')] Could not load parent document with UID "'.$doc->parentId.'"', self::$extKey, SYSLOG_SEVERITY_ERROR);
}
return 1;
@ -112,22 +105,17 @@ class Indexer
$updateQuery->addDeleteQuery('uid:'.$doc->uid);
self::$solr->service->update($updateQuery);
// Index every logical unit as separate Solr document.
foreach ($doc->tableOfContents as $logicalUnit)
{
if (!$errors)
{
foreach ($doc->tableOfContents as $logicalUnit) {
if (!$errors) {
$errors = self::processLogical($doc, $logicalUnit);
} else {
break;
}
}
// Index fulltext files if available.
if ($doc->hasFulltext)
{
foreach ($doc->physicalStructure as $pageNumber => $xmlId)
{
if (!$errors)
{
if ($doc->hasFulltext) {
foreach ($doc->physicalStructure as $pageNumber => $xmlId) {
if (!$errors) {
$errors = self::processPhysical($doc, $pageNumber, $doc->physicalStructureInfo[$xmlId]);
} else {
break;
@ -149,10 +137,8 @@ class Indexer
'1'
);
$resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result);
if (!defined('TYPO3_cliMode'))
{
if (!$errors)
{
if (!defined('TYPO3_cliMode')) {
if (!$errors) {
$message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
\TYPO3\CMS\Core\Messaging\FlashMessage::class,
htmlspecialchars(sprintf(Helper::getMessage('flash.documentIndexed'), $resArray['title'], $doc->uid)),
@ -172,10 +158,8 @@ class Indexer
Helper::addMessage($message);
}
return $errors;
} catch (\Exception $e)
{
if (!defined('TYPO3_cliMode'))
{
} catch (\Exception $e) {
if (!defined('TYPO3_cliMode')) {
$message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
\TYPO3\CMS\Core\Messaging\FlashMessage::class,
Helper::getMessage('flash.solrException', TRUE).'<br />'.htmlspecialchars($e->getMessage()),
@ -185,15 +169,13 @@ class Indexer
);
Helper::addMessage($message);
}
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Indexer->add(['.$doc->uid.'], '.$core.')] Apache Solr threw exception: "'.$e->getMessage().'"', self::$extKey, SYSLOG_SEVERITY_ERROR);
}
return 1;
}
} else {
if (!defined('TYPO3_cliMode'))
{
if (!defined('TYPO3_cliMode')) {
$message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
\TYPO3\CMS\Core\Messaging\FlashMessage::class,
Helper::getMessage('flash.solrNoConnection', TRUE),
@ -203,8 +185,7 @@ class Indexer
);
Helper::addMessage($message);
}
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Indexer->add(['.$doc->uid.'], '.$core.')] Could not connect to Apache Solr server', self::$extKey, SYSLOG_SEVERITY_ERROR);
}
return 1;
@ -220,8 +201,7 @@ class Indexer
*
* @return integer 0 on success or 1 on failure
*/
public static function delete($uid)
{
public static function delete($uid) {
// Save parameter for logging purposes.
$_uid = $uid;
// Sanitize input.
@ -237,22 +217,18 @@ class Indexer
'',
'1'
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result))
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result)) {
list ($core, $title) = $GLOBALS['TYPO3_DB']->sql_fetch_row($result);
// Establish Solr connection.
if (self::solrConnect($core))
{
if (self::solrConnect($core)) {
try {
// Delete Solr document.
$updateQuery = self::$solr->service->createUpdate();
$updateQuery->addDeleteQuery('uid:'.$uid);
$updateQuery->addCommit();
self::$solr->service->update($updateQuery);
} catch (\Exception $e)
{
if (!defined('TYPO3_cliMode'))
{
} catch (\Exception $e) {
if (!defined('TYPO3_cliMode')) {
$message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
\TYPO3\CMS\Core\Messaging\FlashMessage::class,
Helper::getMessage('flash.solrException', TRUE).'<br />'.htmlspecialchars($e->getMessage()),
@ -262,15 +238,13 @@ class Indexer
);
Helper::addMessage($message);
}
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Indexer->delete('.$_uid.')] Apache Solr threw exception: "'.$e->getMessage().'"', self::$extKey, SYSLOG_SEVERITY_ERROR);
}
return 1;
}
} else {
if (!defined('TYPO3_cliMode'))
{
if (!defined('TYPO3_cliMode')) {
$message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
\TYPO3\CMS\Core\Messaging\FlashMessage::class,
Helper::getMessage('flash.solrNoConnection', TRUE),
@ -280,14 +254,12 @@ class Indexer
);
Helper::addMessage($message);
}
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Indexer->delete('.$_uid.')] Could not connect to Apache Solr server', self::$extKey, SYSLOG_SEVERITY_ERROR);
}
return 1;
}
if (!defined('TYPO3_cliMode'))
{
if (!defined('TYPO3_cliMode')) {
$message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
\TYPO3\CMS\Core\Messaging\FlashMessage::class,
htmlspecialchars(sprintf(Helper::getMessage('flash.documentDeleted'), $title, $uid)),
@ -299,8 +271,7 @@ class Indexer
}
return 0;
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Indexer->delete('.$_uid.')] Invalid UID "'.$uid.'" for document deletion', self::$extKey, SYSLOG_SEVERITY_ERROR);
}
return 1;
@ -317,16 +288,13 @@ class Indexer
*
* @return string The field's dynamic index name
*/
public static function getIndexFieldName($index_name, $pid = 0)
{
public static function getIndexFieldName($index_name, $pid = 0) {
// Save parameter for logging purposes.
$_pid = $pid;
// Sanitize input.
$pid = max(intval($pid), 0);
if (!$pid)
{
if (TYPO3_DLOG)
{
if (!$pid) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Indexer->getIndexFieldName('.$index_name.', '.$_pid.')] Invalid PID "'.$pid.'" for metadata configuration', self::$extKey, SYSLOG_SEVERITY_ERROR);
}
return '';
@ -350,10 +318,8 @@ class Indexer
*
* @return void
*/
protected static function loadIndexConf($pid)
{
if (!self::$fieldsLoaded)
{
protected static function loadIndexConf($pid) {
if (!self::$fieldsLoaded) {
// Get the metadata indexing options.
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'tx_dlf_metadata.index_name AS index_name,tx_dlf_metadata.index_tokenized AS index_tokenized,tx_dlf_metadata.index_stored AS index_stored,tx_dlf_metadata.index_indexed AS index_indexed,tx_dlf_metadata.is_sortable AS is_sortable,tx_dlf_metadata.is_facet AS is_facet,tx_dlf_metadata.is_listed AS is_listed,tx_dlf_metadata.index_autocomplete AS index_autocomplete,tx_dlf_metadata.index_boost AS index_boost',
@ -364,36 +330,28 @@ class Indexer
'',
''
);
while ($indexing = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result))
{
if ($indexing['index_tokenized'])
{
while ($indexing = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
if ($indexing['index_tokenized']) {
self::$fields['tokenized'][] = $indexing['index_name'];
}
if ($indexing['index_stored']
|| $indexing['is_listed'])
{
|| $indexing['is_listed']) {
self::$fields['stored'][] = $indexing['index_name'];
}
if ($indexing['index_indexed']
|| $indexing['index_autocomplete'])
{
|| $indexing['index_autocomplete']) {
self::$fields['indexed'][] = $indexing['index_name'];
}
if ($indexing['is_sortable'])
{
if ($indexing['is_sortable']) {
self::$fields['sortables'][] = $indexing['index_name'];
}
if ($indexing['is_facet'])
{
if ($indexing['is_facet']) {
self::$fields['facets'][] = $indexing['index_name'];
}
if ($indexing['index_autocomplete'])
{
if ($indexing['index_autocomplete']) {
self::$fields['autocomplete'][] = $indexing['index_name'];
}
if ($indexing['index_boost'] > 0.0)
{
if ($indexing['index_boost'] > 0.0) {
self::$fields['fieldboost'][$indexing['index_name']] = floatval($indexing['index_boost']);
} else {
self::$fields['fieldboost'][$indexing['index_name']] = FALSE;
@ -413,13 +371,11 @@ class Indexer
*
* @return integer 0 on success or 1 on failure
*/
protected static function processLogical(Document &$doc, array $logicalUnit)
{
protected static function processLogical(Document &$doc, array $logicalUnit) {
$errors = 0;
// Get metadata for logical unit.
$metadata = $doc->metadataArray[$logicalUnit['id']];
if (!empty($metadata))
{
if (!empty($metadata)) {
// Create new Solr document.
$updateQuery = self::$solr->service->createUpdate();
$solrDoc = $updateQuery->createDocument();
@ -427,15 +383,12 @@ class Indexer
$solrDoc->setField('id', $doc->uid.$logicalUnit['id']);
$solrDoc->setField('uid', $doc->uid);
$solrDoc->setField('pid', $doc->pid);
if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($logicalUnit['points']))
{
if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($logicalUnit['points'])) {
$solrDoc->setField('page', $logicalUnit['points']);
}
if ($logicalUnit['id'] == $doc->toplevelId)
{
if ($logicalUnit['id'] == $doc->toplevelId) {
$solrDoc->setField('thumbnail', $doc->thumbnail);
} elseif (!empty($logicalUnit['thumbnailId']))
{
} elseif (!empty($logicalUnit['thumbnailId'])) {
$solrDoc->setField('thumbnail', $doc->getFileLocation($logicalUnit['thumbnailId']));
}
$solrDoc->setField('partof', $doc->parentId);
@ -452,47 +405,38 @@ class Indexer
$solrDoc->setField('urn', $metadata['urn']);
$solrDoc->setField('collection', $doc->metadataArray[$doc->toplevelId]['collection']);
$autocomplete = [];
foreach ($metadata as $index_name => $data)
{
foreach ($metadata as $index_name => $data) {
if (!empty($data)
&& substr($index_name, -8) !== '_sorting')
{
&& substr($index_name, -8) !== '_sorting') {
$solrDoc->setField(self::getIndexFieldName($index_name, $doc->pid), $data, self::$fields['fieldboost'][$index_name]);
if (in_array($index_name, self::$fields['sortables']))
{
if (in_array($index_name, self::$fields['sortables'])) {
// Add sortable fields to index.
$solrDoc->setField($index_name.'_sorting', $metadata[$index_name.'_sorting'][0]);
}
if (in_array($index_name, self::$fields['facets']))
{
if (in_array($index_name, self::$fields['facets'])) {
// Add facets to index.
$solrDoc->setField($index_name.'_faceting', $data);
}
if (in_array($index_name, self::$fields['autocomplete']))
{
if (in_array($index_name, self::$fields['autocomplete'])) {
$autocomplete = array_merge($autocomplete, $data);
}
}
}
// Add autocomplete values to index.
if (!empty($autocomplete))
{
if (!empty($autocomplete)) {
$solrDoc->setField('autocomplete', $autocomplete);
}
// Add collection information to logical sub-elements if applicable.
if (in_array('collection', self::$fields['facets'])
&& empty($metadata['collection'])
&& !empty($doc->metadataArray[$doc->toplevelId]['collection']))
{
&& !empty($doc->metadataArray[$doc->toplevelId]['collection'])) {
$solrDoc->setField('collection_faceting', $doc->metadataArray[$doc->toplevelId]['collection']);
}
try {
$updateQuery->addDocument($solrDoc);
self::$solr->service->update($updateQuery);
} catch (\Exception $e)
{
if (!defined('TYPO3_cliMode'))
{
} catch (\Exception $e) {
if (!defined('TYPO3_cliMode')) {
$message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
\TYPO3\CMS\Core\Messaging\FlashMessage::class,
Helper::getMessage('flash.solrException', TRUE).'<br />'.htmlspecialchars($e->getMessage()),
@ -506,12 +450,9 @@ class Indexer
}
}
// Check for child elements...
if (!empty($logicalUnit['children']))
{
foreach ($logicalUnit['children'] as $child)
{
if (!$errors)
{
if (!empty($logicalUnit['children'])) {
foreach ($logicalUnit['children'] as $child) {
if (!$errors) {
// ...and process them, too.
$errors = self::processLogical($doc, $child);
} else {
@ -533,20 +474,16 @@ class Indexer
*
* @return integer 0 on success or 1 on failure
*/
protected static function processPhysical(Document &$doc, $page, array $physicalUnit)
{
protected static function processPhysical(Document &$doc, $page, array $physicalUnit) {
$errors = 0;
// Read extension configuration.
$extConf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][self::$extKey]);
if (!empty($physicalUnit['files'][$extConf['fileGrpFulltext']]))
{
if (!empty($physicalUnit['files'][$extConf['fileGrpFulltext']])) {
$file = $doc->getFileLocation($physicalUnit['files'][$extConf['fileGrpFulltext']]);
// Load XML file.
if (\TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl($file))
{
if (\TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl($file)) {
// Set user-agent to identify self when fetching XML data.
if (!empty($extConf['useragent']))
{
if (!empty($extConf['useragent'])) {
@ini_set('user_agent', $extConf['useragent']);
}
// Turn off libxml's error logging.
@ -559,8 +496,7 @@ class Indexer
libxml_disable_entity_loader($previousValueOfEntityLoader);
// Reset libxml's error logging.
libxml_use_internal_errors($libxmlErrors);
if ($xml === FALSE)
{
if ($xml === FALSE) {
return 1;
}
} else {
@ -574,8 +510,7 @@ class Indexer
$solrDoc->setField('uid', $doc->uid);
$solrDoc->setField('pid', $doc->pid);
$solrDoc->setField('page', $page);
if (!empty($physicalUnit['files'][$extConf['fileGrpThumbs']]))
{
if (!empty($physicalUnit['files'][$extConf['fileGrpThumbs']])) {
$solrDoc->setField('thumbnail', $doc->getFileLocation($physicalUnit['files'][$extConf['fileGrpThumbs']]));
}
$solrDoc->setField('partof', $doc->parentId);
@ -586,13 +521,10 @@ class Indexer
$solrDoc->setField('collection', $doc->metadataArray[$doc->toplevelId]['collection']);
$solrDoc->setField('fulltext', $doc->getRawText($physicalUnit['id']));
// Add faceting information to physical sub-elements if applicable.
foreach ($doc->metadataArray[$doc->toplevelId] as $index_name => $data)
{
foreach ($doc->metadataArray[$doc->toplevelId] as $index_name => $data) {
if (!empty($data)
&& substr($index_name, -8) !== '_sorting')
{
if (in_array($index_name, self::$fields['facets']))
{
&& substr($index_name, -8) !== '_sorting') {
if (in_array($index_name, self::$fields['facets'])) {
// Add facets to index.
$solrDoc->setField($index_name.'_faceting', $data);
}
@ -600,17 +532,14 @@ class Indexer
}
// Add collection information to physical sub-elements if applicable.
if (in_array('collection', self::$fields['facets'])
&& !empty($doc->metadataArray[$doc->toplevelId]['collection']))
{
&& !empty($doc->metadataArray[$doc->toplevelId]['collection'])) {
$solrDoc->setField('collection_faceting', $doc->metadataArray[$doc->toplevelId]['collection']);
}
try {
$updateQuery->addDocument($solrDoc);
self::$solr->service->update($updateQuery);
} catch (\Exception $e)
{
if (!defined('TYPO3_cliMode'))
{
} catch (\Exception $e) {
if (!defined('TYPO3_cliMode')) {
$message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
\TYPO3\CMS\Core\Messaging\FlashMessage::class,
Helper::getMessage('flash.solrException', TRUE).'<br />'.htmlspecialchars($e->getMessage()),
@ -636,17 +565,13 @@ class Indexer
*
* @return boolean TRUE on success or FALSE on failure
*/
protected static function solrConnect($core, $pid = 0)
{
protected static function solrConnect($core, $pid = 0) {
// Get Solr instance.
if (!self::$solr)
{
if (!self::$solr) {
// Connect to Solr server.
if (self::$solr = Solr::getInstance($core))
{
if (self::$solr = Solr::getInstance($core)) {
// Load indexing configuration if needed.
if ($pid)
{
if ($pid) {
self::loadIndexConf($pid);
}
} else {

View File

@ -20,8 +20,7 @@ namespace Kitodo\Dlf\Common;
* @access public
* @abstract
*/
interface MetadataInterface
{
interface MetadataInterface {
/**
* This extracts metadata from XML
*

View File

@ -20,8 +20,7 @@ namespace Kitodo\Dlf\Common;
* @subpackage dlf
* @access public
*/
class Solr
{
class Solr {
/**
* This holds the core name
*
@ -103,12 +102,10 @@ class Solr
*
* @return string The escaped query string
*/
public static function escapeQuery($query)
{
public static function escapeQuery($query) {
$helper = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\Solarium\Core\Query\Helper::class);
// Escape query phrase or term.
if (preg_match('/^".*"$/', $query))
{
if (preg_match('/^".*"$/', $query)) {
return '"'.$helper->escapePhrase(trim($query, '"')).'"';
} else {
return $helper->escapeTerm($query);
@ -125,11 +122,9 @@ class Solr
*
* @return string The escaped query string
*/
public static function escapeQueryKeepField($query, $pid)
{
public static function escapeQueryKeepField($query, $pid) {
// Is there a field query?
if (preg_match('/^[[:alnum:]]+_[tu][su]i:\(?.*\)?$/', $query))
{
if (preg_match('/^[[:alnum:]]+_[tu][su]i:\(?.*\)?$/', $query)) {
// Get all indexed fields.
$fields = [];
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
@ -143,24 +138,20 @@ class Solr
'',
''
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0)
{
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_row($result))
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0) {
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_row($result)) {
$fields[] = $resArray[0].'_'.($resArray[1] ? 't' : 'u').($resArray[2] ? 's' : 'u').'i';
}
}
// Check if queried field is valid.
$splitQuery = explode(':', $query, 2);
if (in_array($splitQuery[0], $fields))
{
if (in_array($splitQuery[0], $fields)) {
$query = $splitQuery[0].':('.self::escapeQuery(trim($splitQuery[1], '()')).')';
} else {
$query = self::escapeQuery($query);
}
} elseif (!empty($query)
&& $query !== '*')
{
&& $query !== '*') {
// Don't escape plain asterisk search.
$query = self::escapeQuery($query);
}
@ -176,42 +167,35 @@ class Solr
*
* @return \Kitodo\Dlf\Common\Solr Instance of this class
*/
public static function getInstance($core)
{
public static function getInstance($core) {
// Save parameter for logging purposes.
$_core = $core;
// Get core name if UID is given.
if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($core))
{
if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($core)) {
$core = Helper::getIndexName($core, 'tx_dlf_solrcores');
}
// Check if core is set.
if (empty($core))
{
if (TYPO3_DLOG)
{
if (empty($core)) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Solr->getInstance('.$_core.')] Invalid core name "'.$core.'" for Apache Solr', self::$extKey, SYSLOG_SEVERITY_ERROR);
}
return;
}
// Check if there is an instance in the registry already.
if (is_object(self::$registry[$core])
&& self::$registry[$core] instanceof self)
{
&& self::$registry[$core] instanceof self) {
// Return singleton instance if available.
return self::$registry[$core];
}
// Create new instance...
$instance = new self($core);
// ...and save it to registry.
if ($instance->ready)
{
if ($instance->ready) {
self::$registry[$core] = $instance;
// Return new instance.
return $instance;
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Solr->getInstance('.$_core.')] Could not connect to Apache Solr server', self::$extKey, SYSLOG_SEVERITY_ERROR);
}
return;
@ -225,8 +209,7 @@ class Solr
*
* @return string The connection parameters for a specific Solr core
*/
public static function getSolrConnectionInfo()
{
public static function getSolrConnectionInfo() {
$solrInfo = [];
// Extract extension configuration.
$conf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][self::$extKey]);
@ -255,13 +238,11 @@ class Solr
*
* @return string The request URL for a specific Solr core
*/
public static function getSolrUrl($core = '')
{
public static function getSolrUrl($core = '') {
// Get Solr connection information.
$solrInfo = self::getSolrConnectionInfo();
if ($solrInfo['username']
&& $solrInfo['password'])
{
&& $solrInfo['password']) {
$host = $solrInfo['username'].':'.$solrInfo['password'].'@'.$solrInfo['host'];
} else {
$host = $solrInfo['host'];
@ -279,12 +260,10 @@ class Solr
*
* @return integer First unused core number found
*/
public static function solrGetCoreNumber($start = 0)
{
public static function solrGetCoreNumber($start = 0) {
$start = max(intval($start), 0);
// Check if core already exists.
if (self::getInstance('dlfCore'.$start) === NULL)
{
if (self::getInstance('dlfCore'.$start) === NULL) {
return $start;
} else {
return self::solrGetCoreNumber($start + 1);
@ -298,8 +277,7 @@ class Solr
*
* @return \Kitodo\Dlf\Common\DocumentList The result list
*/
public function search()
{
public function search() {
$toplevel = [];
// Take over query parameters.
$params = $this->params;
@ -317,10 +295,8 @@ class Solr
// Restrict the fields to the required ones.
$params['fields'] = 'uid,id';
// Extend filter query to get all documents with the same uids.
foreach ($params['filterquery'] as $key => $value)
{
if (isset($value['query']))
{
foreach ($params['filterquery'] as $key => $value) {
if (isset($value['query'])) {
$params['filterquery'][$key]['query'] = '{!join from=uid to=uid}'.$value['query'];
}
}
@ -333,8 +309,7 @@ class Solr
$results = $this->service->select($selectQuery);
$numberOfToplevelHits = $results->getNumFound();
// Process results.
foreach ($results as $doc)
{
foreach ($results as $doc) {
$toplevel[$doc->id] = [
'u' => $doc->uid,
'h' => '',
@ -377,8 +352,7 @@ class Solr
*
* @return array The Apache Solr Documents that were fetched
*/
public function search_raw($query = '', $parameters = [])
{
public function search_raw($query = '', $parameters = []) {
// Set additional query parameters.
$parameters['start'] = 0;
$parameters['rows'] = $this->limit;
@ -388,8 +362,7 @@ class Solr
$selectQuery = $this->service->createSelect(array_merge($this->params, $parameters));
$result = $this->service->select($selectQuery);
$resultSet = [];
foreach ($result as $doc)
{
foreach ($result as $doc) {
$resultSet[] = $doc;
}
return $resultSet;
@ -402,8 +375,7 @@ class Solr
*
* @return integer The max number of results
*/
protected function _getLimit()
{
protected function _getLimit() {
return $this->limit;
}
@ -414,8 +386,7 @@ class Solr
*
* @return integer Total number of hits for last search
*/
protected function _getNumberOfHits()
{
protected function _getNumberOfHits() {
return $this->numberOfHits;
}
@ -426,8 +397,7 @@ class Solr
*
* @return boolean Is the search instantiated successfully?
*/
protected function _getReady()
{
protected function _getReady() {
return $this->ready;
}
@ -438,8 +408,7 @@ class Solr
*
* @return \Solarium\Client Apache Solr service object
*/
protected function _getService()
{
protected function _getService() {
return $this->service;
}
@ -452,8 +421,7 @@ class Solr
*
* @return void
*/
protected function _setCPid($value)
{
protected function _setCPid($value) {
$this->cPid = max(intval($value), 0);
}
@ -466,8 +434,7 @@ class Solr
*
* @return void
*/
protected function _setLimit($value)
{
protected function _setLimit($value) {
$this->limit = max(intval($value), 0);
}
@ -480,8 +447,7 @@ class Solr
*
* @return void
*/
protected function _setParams(array $value)
{
protected function _setParams(array $value) {
$this->params = $value;
}
@ -494,14 +460,11 @@ class Solr
*
* @return mixed Value of $this->$var
*/
public function __get($var)
{
public function __get($var) {
$method = '_get'.ucfirst($var);
if (!property_exists($this, $var)
|| !method_exists($this, $method))
{
if (TYPO3_DLOG)
{
|| !method_exists($this, $method)) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Solr->__get('.$var.')] There is no getter function for property "'.$var.'"', self::$extKey, SYSLOG_SEVERITY_WARNING);
}
return;
@ -520,14 +483,11 @@ class Solr
*
* @return void
*/
public function __set($var, $value)
{
public function __set($var, $value) {
$method = '_set'.ucfirst($var);
if (!property_exists($this, $var)
|| !method_exists($this, $method))
{
if (TYPO3_DLOG)
{
|| !method_exists($this, $method)) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Common\Solr->__set('.$var.', [data])] There is no setter function for property "'.$var.'"', self::$extKey, SYSLOG_SEVERITY_WARNING, $value);
}
} else {
@ -544,8 +504,7 @@ class Solr
*
* @return void
*/
protected function __construct($core)
{
protected function __construct($core) {
$solrInfo = self::getSolrConnectionInfo();
$config = [
'endpoint' => [
@ -571,8 +530,7 @@ class Solr
$this->core = $core;
// Instantiation successful!
$this->ready = TRUE;
} catch (\Exception $e)
{
} catch (\Exception $e) {
// Nothing to do here.
}
}

View File

@ -19,8 +19,7 @@ namespace Kitodo\Dlf\Formats;
* @subpackage dlf
* @access public
*/
class Alto implements \Kitodo\Dlf\Common\FulltextInterface
{
class Alto implements \Kitodo\Dlf\Common\FulltextInterface {
/**
* This extracts the fulltext data from ALTO XML
*
@ -30,8 +29,7 @@ class Alto implements \Kitodo\Dlf\Common\FulltextInterface
*
* @return string The raw unformatted fulltext
*/
public function getRawText(\SimpleXMLElement $xml)
{
public function getRawText(\SimpleXMLElement $xml) {
$xml->registerXPathNamespace('alto', 'http://www.loc.gov/standards/alto/ns-v2#');
// Get all (presumed) words of the text.
$words = $xml->xpath('./alto:Layout/alto:Page/alto:PrintSpace//alto:TextBlock/alto:TextLine/alto:String/@CONTENT');

View File

@ -19,8 +19,7 @@ namespace Kitodo\Dlf\Formats;
* @subpackage dlf
* @access public
*/
class Mods implements \Kitodo\Dlf\Common\MetadataInterface
{
class Mods implements \Kitodo\Dlf\Common\MetadataInterface {
/**
* This extracts the essential MODS metadata from XML
*
@ -31,47 +30,36 @@ class Mods implements \Kitodo\Dlf\Common\MetadataInterface
*
* @return void
*/
public function extractMetadata(\SimpleXMLElement $xml, array &$metadata)
{
public function extractMetadata(\SimpleXMLElement $xml, array &$metadata) {
$xml->registerXPathNamespace('mods', 'http://www.loc.gov/mods/v3');
// Get "author" and "author_sorting".
$authors = $xml->xpath('./mods:name[./mods:role/mods:roleTerm[@type="code" and @authority="marcrelator"]="aut"]');
// Get "author" and "author_sorting" again if that was to sophisticated.
if (!$authors)
{
if (!$authors) {
// Get all names which do not have any role term assigned and assume these are authors.
$authors = $xml->xpath('./mods:name[not(./mods:role)]');
}
if (is_array($authors))
{
for ($i = 0, $j = count($authors); $i < $j; $i++)
{
if (is_array($authors)) {
for ($i = 0, $j = count($authors); $i < $j; $i++) {
$authors[$i]->registerXPathNamespace('mods', 'http://www.loc.gov/mods/v3');
// Check if there is a display form.
if (($displayForm = $authors[$i]->xpath('./mods:displayForm')))
{
if (($displayForm = $authors[$i]->xpath('./mods:displayForm'))) {
$metadata['author'][$i] = (string) $displayForm[0];
} elseif (($nameParts = $authors[$i]->xpath('./mods:namePart')))
{
} elseif (($nameParts = $authors[$i]->xpath('./mods:namePart'))) {
$name = [];
$k = 4;
foreach ($nameParts as $namePart)
{
foreach ($nameParts as $namePart) {
if (isset($namePart['type'])
&& (string) $namePart['type'] == 'family')
{
&& (string) $namePart['type'] == 'family') {
$name[0] = (string) $namePart;
} elseif (isset($namePart['type'])
&& (string) $namePart['type'] == 'given')
{
&& (string) $namePart['type'] == 'given') {
$name[1] = (string) $namePart;
} elseif (isset($namePart['type'])
&& (string) $namePart['type'] == 'termsOfAddress')
{
&& (string) $namePart['type'] == 'termsOfAddress') {
$name[2] = (string) $namePart;
} elseif (isset($namePart['type'])
&& (string) $namePart['type'] == 'date')
{
&& (string) $namePart['type'] == 'date') {
$name[3] = (string) $namePart;
} else {
$name[$k] = (string) $namePart;
@ -86,49 +74,38 @@ class Mods implements \Kitodo\Dlf\Common\MetadataInterface
// Get "place" and "place_sorting".
$places = $xml->xpath('./mods:originInfo[not(./mods:edition="[Electronic ed.]")]/mods:place/mods:placeTerm');
// Get "place" and "place_sorting" again if that was to sophisticated.
if (!$places)
{
if (!$places) {
// Get all places and assume these are places of publication.
$places = $xml->xpath('./mods:originInfo/mods:place/mods:placeTerm');
}
if (is_array($places))
{
foreach ($places as $place)
{
if (is_array($places)) {
foreach ($places as $place) {
$metadata['place'][] = (string) $place;
if (!$metadata['place_sorting'][0])
{
if (!$metadata['place_sorting'][0]) {
$metadata['place_sorting'][0] = preg_replace('/[[:punct:]]/', '', (string) $place);
}
}
}
// Get "year_sorting".
if (($years_sorting = $xml->xpath('./mods:originInfo[not(./mods:edition="[Electronic ed.]")]/mods:dateOther[@type="order" and @encoding="w3cdtf"]')))
{
foreach ($years_sorting as $year_sorting)
{
if (($years_sorting = $xml->xpath('./mods:originInfo[not(./mods:edition="[Electronic ed.]")]/mods:dateOther[@type="order" and @encoding="w3cdtf"]'))) {
foreach ($years_sorting as $year_sorting) {
$metadata['year_sorting'][0] = intval($year_sorting);
}
}
// Get "year" and "year_sorting" if not specified separately.
$years = $xml->xpath('./mods:originInfo[not(./mods:edition="[Electronic ed.]")]/mods:dateIssued[@keyDate="yes"]');
// Get "year" and "year_sorting" again if that was to sophisticated.
if (!$years)
{
if (!$years) {
// Get all dates and assume these are dates of publication.
$years = $xml->xpath('./mods:originInfo/mods:dateIssued');
}
if (is_array($years))
{
foreach ($years as $year)
{
if (is_array($years)) {
foreach ($years as $year) {
$metadata['year'][] = (string) $year;
if (!$metadata['year_sorting'][0])
{
if (!$metadata['year_sorting'][0]) {
$year_sorting = str_ireplace('x', '5', preg_replace('/[^\d.x]/i', '', (string) $year));
if (strpos($year_sorting, '.')
|| strlen($year_sorting) < 3)
{
|| strlen($year_sorting) < 3) {
$year_sorting = ((intval(trim($year_sorting, '.')) - 1) * 100) + 50;
}
$metadata['year_sorting'][0] = intval($year_sorting);

View File

@ -19,8 +19,7 @@ namespace Kitodo\Dlf\Formats;
* @subpackage dlf
* @access public
*/
class TeiHeader implements \Kitodo\Dlf\Common\MetadataInterface
{
class TeiHeader implements \Kitodo\Dlf\Common\MetadataInterface {
/**
* This extracts the essential TEIHDR metadata from XML
*
@ -31,8 +30,7 @@ class TeiHeader implements \Kitodo\Dlf\Common\MetadataInterface
*
* @return void
*/
public function extractMetadata(\SimpleXMLElement $xml, array &$metadata)
{
public function extractMetadata(\SimpleXMLElement $xml, array &$metadata) {
$xml->registerXPathNamespace('teihdr', 'http://www.tei-c.org/ns/1.0');
}
}

View File

@ -22,8 +22,7 @@ use Kitodo\Dlf\Common\Solr;
* @subpackage dlf
* @access public
*/
class ConfigurationForm
{
class ConfigurationForm {
/**
* This holds the current configuration
*
@ -50,13 +49,11 @@ class ConfigurationForm
*
* @return string Message informing the user of success or failure
*/
public function checkSolrConnection(&$params, &$pObj)
{
public function checkSolrConnection(&$params, &$pObj) {
$solrInfo = Solr::getSolrConnectionInfo();
// Prepend username and password to hostname.
if (!empty($solrInfo['username'])
&& !empty($solrInfo['password']))
{
&& !empty($solrInfo['password'])) {
$host = $solrInfo['username'].':'.$solrInfo['password'].'@'.$solrInfo['host'];
} else {
$host = $solrInfo['host'];
@ -72,11 +69,9 @@ class ConfigurationForm
// Try to connect to Solr server.
$response = @simplexml_load_string(file_get_contents($url, FALSE, $context));
// Check status code.
if ($response)
{
if ($response) {
$status = $response->xpath('//lst[@name="responseHeader"]/int[@name="status"]');
if (is_array($status))
{
if (is_array($status)) {
$message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
\TYPO3\CMS\Core\Messaging\FlashMessage::class,
sprintf($GLOBALS['LANG']->getLL('solr.status'), (string) $status[0]),
@ -109,8 +104,7 @@ class ConfigurationForm
*
* @return integer UID of user or 0 if something is wrong
*/
protected function checkCliUser($checkOnly, $groupUid)
{
protected function checkCliUser($checkOnly, $groupUid) {
// Set default return value.
$usrUid = 0;
// Check if user "_cli_dlf" exists, is no admin and is not disabled.
@ -120,8 +114,7 @@ class ConfigurationForm
'username='.$GLOBALS['TYPO3_DB']->fullQuoteStr('_cli_dlf', 'be_users')
.\TYPO3\CMS\Backend\Utility\BackendUtility::deleteClause('be_users')
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0)
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0) {
$resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result);
// Explode comma-separated list.
$resArray['usergroup'] = explode(',', $resArray['usergroup']);
@ -135,8 +128,7 @@ class ConfigurationForm
// Check if user is configured properly.
if (count(array_diff([$groupUid], $resArray['usergroup'])) == 0
&& !$resArray['admin']
&& $GLOBALS['TYPO3_DB']->sql_num_rows($result2) > 0)
{
&& $GLOBALS['TYPO3_DB']->sql_num_rows($result2) > 0) {
$usrUid = $resArray['uid'];
$message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
\TYPO3\CMS\Core\Messaging\FlashMessage::class,
@ -147,8 +139,7 @@ class ConfigurationForm
);
} else {
if (!$checkOnly
&& $groupUid)
{
&& $groupUid) {
// Keep exisiting values and add the new ones.
$usergroup = array_unique(array_merge([$groupUid], $resArray['usergroup']));
// Try to configure user.
@ -162,8 +153,7 @@ class ConfigurationForm
];
Helper::processDBasAdmin($data);
// Check if configuration was successful.
if ($this->checkCliUser(TRUE, $groupUid))
{
if ($this->checkCliUser(TRUE, $groupUid)) {
$usrUid = $resArray['uid'];
$message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
\TYPO3\CMS\Core\Messaging\FlashMessage::class,
@ -193,8 +183,7 @@ class ConfigurationForm
}
} else {
if (!$checkOnly
&& $groupUid)
{
&& $groupUid) {
// Try to create user.
$tempUid = uniqid('NEW');
$data = [];
@ -207,8 +196,7 @@ class ConfigurationForm
];
$substUid = Helper::processDBasAdmin($data);
// Check if creation was successful.
if (!empty($substUid[$tempUid]))
{
if (!empty($substUid[$tempUid])) {
$usrUid = $substUid[$tempUid];
$message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
\TYPO3\CMS\Core\Messaging\FlashMessage::class,
@ -250,13 +238,11 @@ class ConfigurationForm
*
* @return integer UID of usergroup or 0 if something is wrong
*/
protected function checkCliGroup($checkOnly, $settings = [])
{
protected function checkCliGroup($checkOnly, $settings = []) {
// Set default return value.
$grpUid = 0;
// Set default configuration for usergroup.
if (empty($settings))
{
if (empty($settings)) {
$settings = [
'non_exclude_fields' => [],
'tables_select' => [
@ -276,12 +262,9 @@ class ConfigurationForm
]
];
// Set allowed exclude fields.
foreach ($settings['tables_modify'] as $table)
{
foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $fieldConf)
{
if (!empty($fieldConf['exclude']))
{
foreach ($settings['tables_modify'] as $table) {
foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $fieldConf) {
if (!empty($fieldConf['exclude'])) {
$settings['non_exclude_fields'][] = $table.':'.$field;
}
}
@ -294,8 +277,7 @@ class ConfigurationForm
'title='.$GLOBALS['TYPO3_DB']->fullQuoteStr('_cli_dlf', 'be_groups')
.\TYPO3\CMS\Backend\Utility\BackendUtility::deleteClause('be_groups')
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0)
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0) {
$resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result);
// Explode comma-separated lists.
$resArray['non_exclude_fields'] = explode(',', $resArray['non_exclude_fields']);
@ -305,8 +287,7 @@ class ConfigurationForm
if (count(array_diff($settings['non_exclude_fields'], $resArray['non_exclude_fields'])) == 0
&& count(array_diff($settings['tables_select'], $resArray['tables_select'])) == 0
&& count(array_diff($settings['tables_modify'], $resArray['tables_modify'])) == 0
&& $resArray[$GLOBALS['TCA']['be_groups']['ctrl']['enablecolumns']['disabled']] == 0)
{
&& $resArray[$GLOBALS['TCA']['be_groups']['ctrl']['enablecolumns']['disabled']] == 0) {
$grpUid = $resArray['uid'];
$message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
\TYPO3\CMS\Core\Messaging\FlashMessage::class,
@ -316,8 +297,7 @@ class ConfigurationForm
FALSE
);
} else {
if (!$checkOnly)
{
if (!$checkOnly) {
// Keep exisiting values and add the new ones.
$non_exclude_fields = array_unique(array_merge($settings['non_exclude_fields'], $resArray['non_exclude_fields']));
$tables_select = array_unique(array_merge($settings['tables_select'], $resArray['tables_select']));
@ -332,8 +312,7 @@ class ConfigurationForm
];
Helper::processDBasAdmin($data);
// Check if configuration was successful.
if ($this->checkCliGroup(TRUE, $settings))
{
if ($this->checkCliGroup(TRUE, $settings)) {
$grpUid = $resArray['uid'];
$message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
\TYPO3\CMS\Core\Messaging\FlashMessage::class,
@ -362,8 +341,7 @@ class ConfigurationForm
}
}
} else {
if (!$checkOnly)
{
if (!$checkOnly) {
// Try to create usergroup.
$tempUid = uniqid('NEW');
$data = [];
@ -377,8 +355,7 @@ class ConfigurationForm
];
$substUid = Helper::processDBasAdmin($data);
// Check if creation was successful.
if (!empty($substUid[$tempUid]))
{
if (!empty($substUid[$tempUid])) {
$grpUid = $substUid[$tempUid];
$message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
\TYPO3\CMS\Core\Messaging\FlashMessage::class,
@ -420,8 +397,7 @@ class ConfigurationForm
*
* @return string Message informing the user of success or failure
*/
public function checkCliUserGroup(&$params, &$pObj)
{
public function checkCliUserGroup(&$params, &$pObj) {
// Check if usergroup "_cli_dlf" exists and is configured properly.
$groupUid = $this->checkCliGroup(empty($this->conf['makeCliUserGroup']));
// Save output because it will be overwritten by the user check method.
@ -431,8 +407,7 @@ class ConfigurationForm
// Merge output from usergroup and user checks.
$this->content .= $content;
// Check if CLI dispatcher is executable.
if (is_executable(PATH_typo3.'cli_dispatch.phpsh'))
{
if (is_executable(PATH_typo3.'cli_dispatch.phpsh')) {
$message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
\TYPO3\CMS\Core\Messaging\FlashMessage::class,
$GLOBALS['LANG']->getLL('cliUserGroup.cliOkayMsg'),
@ -463,8 +438,7 @@ class ConfigurationForm
*
* @return string Message informing the user of success or failure
*/
public function checkMetadataFormats(&$params, &$pObj)
{
public function checkMetadataFormats(&$params, &$pObj) {
$nsDefined = [
'MODS' => FALSE,
'TEIHDR' => FALSE,
@ -477,15 +451,13 @@ class ConfigurationForm
'1=1'
.Helper::whereClause('tx_dlf_formats')
);
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result))
{
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
$nsDefined[$resArray['type']] = TRUE;
}
// Build data array.
$data = [];
// Add MODS namespace.
if (!$nsDefined['MODS'])
{
if (!$nsDefined['MODS']) {
$data['tx_dlf_formats'][uniqid('NEW')] = [
'pid' => 0,
'type' => 'MODS',
@ -495,8 +467,7 @@ class ConfigurationForm
];
}
// Add TEIHDR namespace.
if (!$nsDefined['TEIHDR'])
{
if (!$nsDefined['TEIHDR']) {
$data['tx_dlf_formats'][uniqid('NEW')] = [
'pid' => 0,
'type' => 'TEIHDR',
@ -506,8 +477,7 @@ class ConfigurationForm
];
}
// Add ALTO namespace.
if (!$nsDefined['ALTO'])
{
if (!$nsDefined['ALTO']) {
$data['tx_dlf_formats'][uniqid('NEW')] = [
'pid' => 0,
'type' => 'ALTO',
@ -516,12 +486,10 @@ class ConfigurationForm
'class' => 'Kitodo\\Dlf\\Formats\\Alto'
];
}
if (!empty($data))
{
if (!empty($data)) {
// Process changes.
$substUid = Helper::processDBasAdmin($data);
if (!empty($substUid))
{
if (!empty($substUid)) {
$message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
\TYPO3\CMS\Core\Messaging\FlashMessage::class,
$GLOBALS['LANG']->getLL('metadataFormats.nsCreatedMsg'),
@ -558,8 +526,7 @@ class ConfigurationForm
*
* @return void
*/
public function __construct()
{
public function __construct() {
// Load localization file.
$GLOBALS['LANG']->includeLLFile('EXT:dlf/Resources/Private/Language/FlashMessages.xml');
// Get current configuration.

View File

@ -23,8 +23,7 @@ use Kitodo\Dlf\Common\Solr;
* @subpackage dlf
* @access public
*/
class DataHandler
{
class DataHandler {
/**
* Field post-processing hook for the process_datamap() method.
*
@ -38,31 +37,25 @@ class DataHandler
*
* @return void
*/
public function processDatamap_postProcessFieldArray($status, $table, $id, &$fieldArray, $pObj)
{
if ($status == 'new')
{
switch ($table)
{
public function processDatamap_postProcessFieldArray($status, $table, $id, &$fieldArray, $pObj) {
if ($status == 'new') {
switch ($table) {
// Field post-processing for table "tx_dlf_documents".
case 'tx_dlf_documents':
// Set sorting field if empty.
if (empty($fieldArray['title_sorting'])
&& !empty($fieldArray['title']))
{
&& !empty($fieldArray['title'])) {
$fieldArray['title_sorting'] = $fieldArray['title'];
}
break;
// Field post-processing for table "tx_dlf_metadata".
case 'tx_dlf_metadata':
// Store field in index if it should appear in lists.
if (!empty($fieldArray['is_listed']))
{
if (!empty($fieldArray['is_listed'])) {
$fieldArray['index_stored'] = 1;
}
// Index field in index if it should be used for auto-completion.
if (!empty($fieldArray['index_autocomplete']))
{
if (!empty($fieldArray['index_autocomplete'])) {
$fieldArray['index_indexed'] = 1;
}
// Field post-processing for tables "tx_dlf_metadata", "tx_dlf_collections", "tx_dlf_libraries" and "tx_dlf_structures".
@ -71,19 +64,16 @@ class DataHandler
case 'tx_dlf_structures':
// Set label as index name if empty.
if (empty($fieldArray['index_name'])
&& !empty($fieldArray['label']))
{
&& !empty($fieldArray['label'])) {
$fieldArray['index_name'] = $fieldArray['label'];
}
// Set index name as label if empty.
if (empty($fieldArray['label'])
&& !empty($fieldArray['index_name']))
{
&& !empty($fieldArray['index_name'])) {
$fieldArray['label'] = $fieldArray['index_name'];
}
// Ensure that index names don't get mixed up with sorting values.
if (substr($fieldArray['index_name'], -8) == '_sorting')
{
if (substr($fieldArray['index_name'], -8) == '_sorting') {
$fieldArray['index_name'] .= '0';
}
break;
@ -105,8 +95,7 @@ class DataHandler
$solrInfo = Solr::getSolrConnectionInfo();
// Prepend username and password to hostname.
if ($solrInfo['username']
&& $solrInfo['password'])
{
&& $solrInfo['password']) {
$host = $solrInfo['username'].':'.$solrInfo['password'].'@'.$solrInfo['host'];
} else {
$host = $solrInfo['host'];
@ -122,39 +111,32 @@ class DataHandler
$url = $solrInfo['scheme'].'://'.$host.':'.$solrInfo['port'].'/'.$solrInfo['path'].'/admin/cores?wt=xml&action=CREATE&name=dlfCore'.$coreNumber.'&instanceDir=dlfCore'.$coreNumber.'&dataDir=data&configSet=dlf';
$response = @simplexml_load_string(file_get_contents($url, FALSE, $context));
// Process response.
if ($response)
{
if ($response) {
$status = $response->xpath('//lst[@name="responseHeader"]/int[@name="status"]');
if ($status
&& $status[0] == 0)
{
&& $status[0] == 0) {
$fieldArray['index_name'] = 'dlfCore'.$coreNumber;
return;
}
}
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Hooks\DataHandler->processDatamap_postProcessFieldArray('.$status.', '.$table.', '.$id.', [data], ['.get_class($pObj).'])] Could not create new Apache Solr core "dlfCore'.$coreNumber.'"', $this->extKey, SYSLOG_SEVERITY_ERROR, $fieldArray);
}
// Solr core could not be created, thus unset field array.
$fieldArray = [];
break;
}
} elseif ($status == 'update')
{
switch ($table)
{
} elseif ($status == 'update') {
switch ($table) {
// Field post-processing for table "tx_dlf_metadata".
case 'tx_dlf_metadata':
// Store field in index if it should appear in lists.
if (!empty($fieldArray['is_listed']))
{
if (!empty($fieldArray['is_listed'])) {
$fieldArray['index_stored'] = 1;
}
if (isset($fieldArray['index_stored'])
&& $fieldArray['index_stored'] == 0
&& !isset($fieldArray['is_listed']))
{
&& !isset($fieldArray['is_listed'])) {
// Get current configuration.
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
$table.'.is_listed AS is_listed',
@ -165,21 +147,18 @@ class DataHandler
'',
'1'
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result))
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result)) {
// Reset storing to current.
list ($fieldArray['index_stored']) = $GLOBALS['TYPO3_DB']->sql_fetch_row($result);
}
}
// Index field in index if it should be used for auto-completion.
if (!empty($fieldArray['index_autocomplete']))
{
if (!empty($fieldArray['index_autocomplete'])) {
$fieldArray['index_indexed'] = 1;
}
if (isset($fieldArray['index_indexed'])
&& $fieldArray['index_indexed'] == 0
&& !isset($fieldArray['index_autocomplete']))
{
&& !isset($fieldArray['index_autocomplete'])) {
// Get current configuration.
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
$table.'.index_autocomplete AS index_autocomplete',
@ -190,8 +169,7 @@ class DataHandler
'',
'1'
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result))
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result)) {
// Reset indexing to current.
list ($fieldArray['index_indexed']) = $GLOBALS['TYPO3_DB']->sql_fetch_row($result);
}
@ -199,10 +177,8 @@ class DataHandler
// Field post-processing for tables "tx_dlf_metadata" and "tx_dlf_structures".
case 'tx_dlf_structures':
// The index name should not be changed in production.
if (isset($fieldArray['index_name']))
{
if (count($fieldArray) < 2)
{
if (isset($fieldArray['index_name'])) {
if (count($fieldArray) < 2) {
// Unset the whole field array.
$fieldArray = [];
} else {
@ -216,14 +192,12 @@ class DataHandler
'',
'1'
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result))
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result)) {
// Reset index name to current.
list ($fieldArray['index_name']) = $GLOBALS['TYPO3_DB']->sql_fetch_row($result);
}
}
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Hooks\DataHandler->processDatamap_postProcessFieldArray('.$status.', '.$table.', '.$id.', [data], ['.get_class($pObj).'])] Prevented change of "index_name" for UID "'.$id.'" in table "'.$table.'"', $this->extKey, SYSLOG_SEVERITY_NOTICE, $fieldArray);
}
}
@ -245,18 +219,14 @@ class DataHandler
*
* @return void
*/
public function processDatamap_afterDatabaseOperations($status, $table, $id, &$fieldArray, $pObj)
{
if ($status == 'update')
{
switch ($table)
{
public function processDatamap_afterDatabaseOperations($status, $table, $id, &$fieldArray, $pObj) {
if ($status == 'update') {
switch ($table) {
// After database operations for table "tx_dlf_documents".
case 'tx_dlf_documents':
// Delete/reindex document in Solr if "hidden" status or collections have changed.
if (isset($fieldArray['hidden'])
|| isset($fieldArray['collections']))
{
|| isset($fieldArray['collections'])) {
// Get Solr core.
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'tx_dlf_solrcores.uid,tx_dlf_documents.hidden',
@ -268,14 +238,11 @@ class DataHandler
'',
'1'
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result))
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result)) {
list ($core, $hidden) = $GLOBALS['TYPO3_DB']->sql_fetch_row($result);
if ($hidden)
{
if ($hidden) {
// Establish Solr connection.
if ($solr = Solr::getInstance($core))
{
if ($solr = Solr::getInstance($core)) {
// Delete Solr document.
$updateQuery = $solr->service->createUpdate();
$updateQuery->addDeleteQuery('uid:'.$id);
@ -285,12 +252,10 @@ class DataHandler
} else {
// Reindex document.
$doc = Document::getInstance($id);
if ($doc->ready)
{
if ($doc->ready) {
$doc->save($doc->pid, $core);
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Hooks\DataHandler->processDatamap_afterDatabaseOperations('.$status.', '.$table.', '.$id.', [data], ['.get_class($pObj).'])] Failed to re-index document with UID "'.$id.'"', $this->extKey, SYSLOG_SEVERITY_ERROR, $fieldArray);
}
}
@ -315,11 +280,9 @@ class DataHandler
*
* @return void
*/
public function processCmdmap_postProcess($command, $table, $id, $value, $pObj)
{
public function processCmdmap_postProcess($command, $table, $id, $value, $pObj) {
if (in_array($command, ['move', 'delete', 'undelete'])
&& $table == 'tx_dlf_documents')
{
&& $table == 'tx_dlf_documents') {
// Get Solr core.
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'tx_dlf_solrcores.uid',
@ -331,35 +294,29 @@ class DataHandler
'',
'1'
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result))
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result)) {
list ($core) = $GLOBALS['TYPO3_DB']->sql_fetch_row($result);
switch ($command)
{
switch ($command) {
case 'move':
case 'delete':
// Establish Solr connection.
if ($solr = Solr::getInstance($core))
{
if ($solr = Solr::getInstance($core)) {
// Delete Solr document.
$updateQuery = $solr->service->createUpdate();
$updateQuery->addDeleteQuery('uid:'.$id);
$updateQuery->addCommit();
$solr->service->update($updateQuery);
if ($command == 'delete')
{
if ($command == 'delete') {
break;
}
}
case 'undelete':
// Reindex document.
$doc = Document::getInstance($id);
if ($doc->ready)
{
if ($doc->ready) {
$doc->save($doc->pid, $core);
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Hooks\DataHandler->processCmdmap_postProcess('.$command.', '.$table.', '.$id.', '.$value.', ['.get_class($pObj).'])] Failed to re-index document with UID "'.$id.'"', $this->extKey, SYSLOG_SEVERITY_ERROR);
}
}

View File

@ -21,8 +21,7 @@ use Kitodo\Dlf\Common\Helper;
* @subpackage dlf
* @access public
*/
class FormEngine
{
class FormEngine {
/**
* Helper to display document's thumbnail for table "tx_dlf_documents"
*
@ -33,13 +32,11 @@ class FormEngine
*
* @return string HTML <img> tag for thumbnail
*/
public function displayThumbnail(&$params, &$pObj)
{
public function displayThumbnail(&$params, &$pObj) {
$output = '<div style="padding:5px; background-color:#000000;">';
// Simulate TCA field type "passthrough".
$output .= '<input type="hidden" name="'.$params['itemFormElName'].'" value="'.$params['itemFormElValue'].'" />';
if (!empty($params['itemFormElValue']))
{
if (!empty($params['itemFormElValue'])) {
$output .= '<img alt="" src="'.$params['itemFormElValue'].'" />';
}
$output .= '</div>';
@ -56,20 +53,16 @@ class FormEngine
*
* @return void
*/
public function itemsProcFunc_collectionList(&$params, &$pObj)
{
public function itemsProcFunc_collectionList(&$params, &$pObj) {
$pages = $params['row']['pages'];
if (!empty($pages))
{
if (!empty($pages)) {
// There is a strange behavior where the uid from the flexform is prepended by the table's name and appended by its title.
// i.e. instead of "18" it reads "pages_18|Title"
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($pages))
{
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($pages)) {
$parts = explode('|', $pages);
$pages = array_pop(explode('_', $parts[0]));
}
if ($pages > 0)
{
if ($pages > 0) {
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'label,uid',
'tx_dlf_collections',
@ -80,10 +73,8 @@ class FormEngine
'label',
''
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0)
{
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_row($result))
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0) {
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_row($result)) {
$params['items'][] = $resArray;
}
}
@ -101,20 +92,16 @@ class FormEngine
*
* @return void
*/
public function itemsProcFunc_extendedSearchList(&$params, &$pObj)
{
public function itemsProcFunc_extendedSearchList(&$params, &$pObj) {
$pages = $params['row']['pages'];
if (!empty($pages))
{
if (!empty($pages)) {
// There is a strange behavior where the uid from the flexform is prepended by the table's name and appended by its title.
// i.e. instead of "18" it reads "pages_18|Title"
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($pages))
{
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($pages)) {
$_parts = explode('|', $pages);
$pages = array_pop(explode('_', $_parts[0]));
}
if ($pages > 0)
{
if ($pages > 0) {
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'label,index_name',
'tx_dlf_metadata',
@ -126,10 +113,8 @@ class FormEngine
'sorting',
''
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0)
{
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_row($result))
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0) {
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_row($result)) {
$params['items'][] = $resArray;
}
}
@ -147,20 +132,16 @@ class FormEngine
*
* @return void
*/
public function itemsProcFunc_facetsList(&$params, &$pObj)
{
public function itemsProcFunc_facetsList(&$params, &$pObj) {
$pages = $params['row']['pages'];
if (!empty($pages))
{
if (!empty($pages)) {
// There is a strange behavior where the uid from the flexform is prepended by the table's name and appended by its title.
// i.e. instead of "18" it reads "pages_18|Title"
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($pages))
{
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($pages)) {
$_parts = explode('|', $pages);
$pages = array_pop(explode('_', $_parts[0]));
}
if ($pages > 0)
{
if ($pages > 0) {
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'label,index_name',
'tx_dlf_metadata',
@ -172,10 +153,8 @@ class FormEngine
'sorting',
''
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0)
{
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_row($result))
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0) {
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_row($result)) {
$params['items'][] = $resArray;
}
}
@ -193,20 +172,16 @@ class FormEngine
*
* @return void
*/
public function itemsProcFunc_libraryList(&$params, &$pObj)
{
public function itemsProcFunc_libraryList(&$params, &$pObj) {
$pages = $params['row']['pages'];
if (!empty($pages))
{
if (!empty($pages)) {
// There is a strange behavior where the uid from the flexform is prepended by the table's name and appended by its title.
// i.e. instead of "18" it reads "pages_18|Title"
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($pages))
{
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($pages)) {
$parts = explode('|', $pages);
$pages = array_pop(explode('_', $parts[0]));
}
if ($pages > 0)
{
if ($pages > 0) {
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'label,uid',
'tx_dlf_libraries',
@ -217,10 +192,8 @@ class FormEngine
'label',
''
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0)
{
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_row($result))
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0) {
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_row($result)) {
$params['items'][] = $resArray;
}
}
@ -238,20 +211,16 @@ class FormEngine
*
* @return void
*/
public function itemsProcFunc_solrList(&$params, &$pObj)
{
public function itemsProcFunc_solrList(&$params, &$pObj) {
$pages = $params['row']['pages'];
if (!empty($pages))
{
if (!empty($pages)) {
// There is a strange behavior where the uid from the flexform is prepended by the table's name and appended by its title.
// i.e. instead of "18" it reads "pages_18|Title"
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($pages))
{
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($pages)) {
$parts = explode('|', $pages);
$pages = array_pop(explode('_', $parts[0]));
}
if ($pages > 0)
{
if ($pages > 0) {
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'label,uid',
'tx_dlf_solrcores',
@ -261,10 +230,8 @@ class FormEngine
'label',
''
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0)
{
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_row($result))
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0) {
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_row($result)) {
$params['items'][] = $resArray;
}
}
@ -282,10 +249,8 @@ class FormEngine
*
* @return void
*/
public function itemsProcFunc_toolList(&$params, &$pObj)
{
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['dlf/plugins/toolbox/tools'] as $class => $label)
{
public function itemsProcFunc_toolList(&$params, &$pObj) {
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['dlf/plugins/toolbox/tools'] as $class => $label) {
$params['items'][] = [$GLOBALS['LANG']->sL($label), $class];
}
}

View File

@ -19,8 +19,7 @@ namespace Kitodo\Dlf\Hooks;
* @subpackage dlf
* @access public
*/
class KitodoProductionHacks
{
class KitodoProductionHacks {
/**
* Hook for \Kitodo\Dlf\Common\Document::__construct()
* When using Kitodo.Production the record identifier is saved only in MODS, but not
@ -33,37 +32,28 @@ class KitodoProductionHacks
*
* @return void
*/
public function construct_postProcessRecordId(\SimpleXMLElement &$xml, &$record_id)
{
if (!$record_id)
{
public function construct_postProcessRecordId(\SimpleXMLElement &$xml, &$record_id) {
if (!$record_id) {
$xml->registerXPathNamespace('mods', 'http://www.loc.gov/mods/v3');
// Get all logical structure nodes with metadata, but without associated METS-Pointers.
if (($divs = $xml->xpath('//mets:structMap[@TYPE="LOGICAL"]//mets:div[@DMDID and not(./mets:mptr)]')))
{
if (($divs = $xml->xpath('//mets:structMap[@TYPE="LOGICAL"]//mets:div[@DMDID and not(./mets:mptr)]'))) {
$smLinks = $xml->xpath('//mets:structLink/mets:smLink');
if ($smLinks)
{
foreach ($smLinks as $smLink)
{
if ($smLinks) {
foreach ($smLinks as $smLink) {
$links[(string) $smLink->attributes('http://www.w3.org/1999/xlink')->from][] = (string) $smLink->attributes('http://www.w3.org/1999/xlink')->to;
}
foreach ($divs as $div)
{
if (!empty($links[(string) $div['ID']]))
{
foreach ($divs as $div) {
if (!empty($links[(string) $div['ID']])) {
$id = (string) $div['DMDID'];
break;
}
}
}
if (empty($id))
{
if (empty($id)) {
$id = (string) $divs[0]['DMDID'];
}
$recordIds = $xml->xpath('//mets:dmdSec[@ID="'.$id.'"]//mods:mods/mods:recordInfo/mods:recordIdentifier');
if (!empty($recordIds[0]))
{
if (!empty($recordIds[0])) {
$record_id = (string) $recordIds[0];
}
}

View File

@ -12,7 +12,7 @@ namespace Kitodo\Dlf\Plugins;
*/
/**
* Plugin AudioPlayer for the 'dlf' extension.
* Plugin AudioPlayer for the 'dlf' extension
*
* @author Sebastian Meyer <sebastian.meyer@slub-dresden.de>
* @package TYPO3
@ -20,7 +20,6 @@ namespace Kitodo\Dlf\Plugins;
* @access public
*/
class AudioPlayer extends \Kitodo\Dlf\Common\AbstractPlugin {
public $scriptRelPath = 'Classes/Plugins/AudioPlayer.php';
/**
@ -39,15 +38,10 @@ class AudioPlayer extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string Player script tags ready for output
*/
protected function addPlayerJS() {
$output = [];
$output[] = '<link type="text/css" rel="stylesheet" href="'.\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey).'Resources/Public/Javascript/jPlayer/blue.monday/css/jplayer.blue.monday.min.css">';
$output[] = '<script type="text/javascript" src="'.\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey).'Resources/Public/Javascript/jPlayer/jquery.jplayer.min.js"></script>';
$output[] = '<script type="text/javascript" src="'.\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey).'Resources/Public/Javascript/AudioPlayer/AudioPlayer.js"></script>';
// Add player configuration.
$output[] = '
<style>
@ -66,9 +60,7 @@ class AudioPlayer extends \Kitodo\Dlf\Common\AbstractPlugin {
});
});
</script>';
return implode("\n", $output);
}
/**
@ -82,64 +74,41 @@ class AudioPlayer extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The content that is displayed on the website
*/
public function main($content, $conf) {
$this->init($conf);
// Load current document.
$this->loadDocument();
if ($this->doc === NULL || $this->doc->numPages < 1) {
if ($this->doc === NULL
|| $this->doc->numPages < 1) {
// Quit without doing anything if required variables are not set.
return $content;
} else {
// Set default values if not set.
// $this->piVars['page'] may be integer or string (physical structure @ID)
if ((int) $this->piVars['page'] > 0 || empty($this->piVars['page'])) {
if ((int) $this->piVars['page'] > 0
|| empty($this->piVars['page'])) {
$this->piVars['page'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange((int) $this->piVars['page'], 1, $this->doc->numPages, 1);
} else {
$this->piVars['page'] = array_search($this->piVars['page'], $this->doc->physicalStructure);
}
$this->piVars['double'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($this->piVars['double'], 0, 1, 0);
}
// Check if there are any audio files available.
if (!empty($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$this->piVars['page']]]['files'][$this->conf['fileGrpAudio']])) {
// Get audio data.
$this->audio['url'] = $this->doc->getFileLocation($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$this->piVars['page']]]['files'][$this->conf['fileGrpAudio']]);
$this->audio['label'] = $this->doc->physicalStructureInfo[$this->doc->physicalStructure[$this->piVars['page']]]['label'];
$this->audio['mimetype'] = $this->doc->getFileMimeType($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$this->piVars['page']]]['files'][$this->conf['fileGrpAudio']]);
} else {
// Quit without doing anything if required variables are not set.
return $content;
}
// Load template file.
$this->getTemplate();
// Fill in the template markers.
$markerArray = [
'###PLAYER_JS###' => $this->addPlayerJS()
];
$content .= $this->cObj->substituteMarkerArray($this->template, $markerArray);
return $this->pi_wrapInBaseClass($content);
}
}

View File

@ -15,7 +15,7 @@ use Kitodo\Dlf\Common\Document;
use Kitodo\Dlf\Common\Helper;
/**
* Plugin 'Basket' for the 'dlf' extension.
* Plugin 'Basket' for the 'dlf' extension
*
* @author Christopher Timm <timm@effective-webwork.de>
* @package TYPO3
@ -23,7 +23,6 @@ use Kitodo\Dlf\Common\Helper;
* @access public
*/
class Basket extends \Kitodo\Dlf\Common\AbstractPlugin {
public $scriptRelPath = 'Classes/Plugins/Basket.php';
/**
@ -37,193 +36,123 @@ class Basket extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The content that is displayed on the website
*/
public function main($content, $conf) {
$this->init($conf);
// Don't cache the output.
$this->setCache(FALSE);
// Load template file.
$this->getTemplate();
$subpartArray['entry'] = $this->cObj->getSubpart($this->template, '###ENTRY###');
$markerArray['###JS###'] = '';
// get user session
$sessionId = $GLOBALS['TSFE']->fe_user->id;
if ($GLOBALS['TSFE']->loginUser) {
$insertArray['fe_user_id'] = $GLOBALS['TSFE']->fe_user->user['uid'];
$query = $GLOBALS['TYPO3_DB']->SELECTquery(
'*',
'tx_dlf_basket',
'tx_dlf_basket.fe_user_id='.intval($insertArray['fe_user_id']).Helper::whereClause('tx_dlf_basket'),
'tx_dlf_basket.fe_user_id='.intval($insertArray['fe_user_id'])
.Helper::whereClause('tx_dlf_basket'),
'',
'',
'1'
);
} else {
$GLOBALS['TSFE']->fe_user->setKey('ses', 'tx_dlf_basket', '');
$GLOBALS['TSFE']->fe_user->sesData_change = TRUE;
$GLOBALS['TSFE']->fe_user->storeSessionData();
$query = $GLOBALS['TYPO3_DB']->SELECTquery(
'*',
'tx_dlf_basket',
'tx_dlf_basket.session_id='.$GLOBALS['TYPO3_DB']->fullQuoteStr($sessionId, 'tx_dlf_basket').Helper::whereClause('tx_dlf_basket'),
'tx_dlf_basket.session_id='.$GLOBALS['TYPO3_DB']->fullQuoteStr($sessionId, 'tx_dlf_basket')
.Helper::whereClause('tx_dlf_basket'),
'',
'',
'1'
);
}
$result = $GLOBALS['TYPO3_DB']->sql_query($query);
// session already exists
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) == 0) {
// create new basket in db
$insertArray['session_id'] = $sessionId;
$insertArray['doc_ids'] = '';
$insertArray['label'] = '';
$insertArray['l18n_diffsource'] = '';
$GLOBALS['TYPO3_DB']->exec_INSERTquery('tx_dlf_basket', $insertArray);
$result = $GLOBALS['TYPO3_DB']->sql_query($query);
}
$basketData = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result);
$piVars = $this->piVars;
// action add to basket
if (!empty($this->piVars['id']) && $this->piVars['addToBasket']) {
if (!empty($this->piVars['id'])
&& $this->piVars['addToBasket']) {
$returnData = $this->addToBasket($this->piVars, $basketData);
$basketData = $returnData['basketData'];
$markerArray['###JS###'] = $returnData['jsOutput'];
} else {
$basketData['doc_ids'] = json_decode($basketData['doc_ids']);
}
// action remove from basket
if ($this->piVars['basket_action'] == 'remove') {
// remove entry from list
unset($piVars['basket_action']);
if (isset($this->piVars['selected'])) {
$basketData = $this->removeFromBasket($piVars, $basketData);
}
}
// action remove from basket
if ($this->piVars['basket_action'] == 'open') {
// open selected documents
unset($piVars['basket_action']);
if (isset($this->piVars['selected'])) {
$basketData = $this->openFromBasket($piVars, $basketData);
}
}
// action print from basket
if ($this->piVars['print_action']) {
// open selected documents
unset($piVars['print_action']);
if (isset($this->piVars['selected'])) {
$basketData = $this->printDocument($piVars, $basketData);
}
}
// action send mail
if ($this->piVars['mail_action']) {
if (isset($this->piVars['selected'])) {
$this->sendMail($this->piVars);
}
}
// set marker
$markerArray['###ACTION###'] = $this->pi_getPageLink($GLOBALS['TSFE']->id);
$markerArray['###LISTTITLE###'] = $this->pi_getLL('basket', '', TRUE);
if ($basketData['doc_ids']) {
if (is_object($basketData['doc_ids'])) {
$basketData['doc_ids'] = get_object_vars($basketData['doc_ids']);
}
$markerArray['###COUNT###'] = sprintf($this->pi_getLL('count'), count($basketData['doc_ids']));
} else {
$markerArray['###COUNT###'] = sprintf($this->pi_getLL('count'), 0);
}
// get mail addresses
$resultMail = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'*',
'tx_dlf_mail',
'1'.Helper::whereClause('tx_dlf_mail'),
'1=1'
.Helper::whereClause('tx_dlf_mail'),
'',
'tx_dlf_mail.sorting',
''
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($resultMail) > 0) {
$mailForm = '<select name="tx_dlf[mail_action]">';
$mailForm .= '<option value="">'.$this->pi_getLL('chooseMail', '', TRUE).'</option>';
while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($resultMail)) {
$mailForm .= '<option value="'.$row['uid'].'">'.$row['name'].' ('.$row['mail'].')</option>';
}
$mailForm .= '</select><input type="submit">';
}
// mail action form
$markerArray['###MAILACTION###'] = $mailForm;
// remove action form
$markerArray['###REMOVEACTION###'] = '
<select name="tx_dlf[basket_action]">
@ -233,178 +162,117 @@ class Basket extends \Kitodo\Dlf\Common\AbstractPlugin {
</select>
<input type="submit">
';
// get mail addresses
$resultPrinter = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'*',
'tx_dlf_printer',
'1'.Helper::whereClause('tx_dlf_printer'),
'1=1'
.Helper::whereClause('tx_dlf_printer'),
'',
'',
''
);
$printForm = '';
if ($GLOBALS['TYPO3_DB']->sql_num_rows($resultPrinter) > 0) {
$printForm = '<select name="tx_dlf[print_action]">';
$printForm .= '<option value="">'.$this->pi_getLL('choosePrinter', '', TRUE).'</option>';
while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($resultPrinter)) {
$printForm .= '<option value="'.$row['uid'].'">'.$row['label'].'</option>';
}
$printForm .= '</select><input type="submit" />';
}
// print action form
$markerArray['###PRINTACTION###'] = $printForm;
$entries = '';
if (isset($basketData['doc_ids'])) {
// get each entry
foreach ($basketData['doc_ids'] as $value) {
$entries .= $this->getEntry($value, $subpartArray);
}
} else {
$entries = '';
}
// basket go to
if ($this->conf['targetBasket'] && $this->conf['basketGoToButton'] && $this->piVars['id']) {
$label = $this->pi_getLL('goBasket', '', TRUE);
$basketConf = [
'parameter' => $this->conf['targetBasket'],
'title' => $label
];
$markerArray['###BASKET###'] = $this->cObj->typoLink($label, $basketConf);
} else {
$markerArray['###BASKET###'] = '';
}
$content = $this->cObj->substituteMarkerArray($this->cObj->substituteSubpart($this->template, '###ENTRY###', $entries, TRUE), $markerArray);
return $this->pi_wrapInBaseClass($content);
}
/**
* Return one basket entry
* @param array $data DocumentData
* @param array $template Template information
* @return string
*
* @access protected
*
* @param array $data: DocumentData
* @param array $template: Template information
*
* @return string One basket entry
*/
public function getEntry($data, $template) {
protected function getEntry($data, $template) {
if (is_object($data)) {
$data = get_object_vars($data);
}
$id = $data['id'];
$startpage = $data['startpage'];
$endpage = $data['endpage'];
$startX = $data['startX'];
$startY = $data['startY'];
$endX = $data['endX'];
$endY = $data['endY'];
$rotation = $data['rotation'];
$docData = $this->getDocumentData($id, $data);
$markerArray['###BASKETDATA###'] = $docData['downloadLink'];
$arrayKey = $id.'_'.$startpage;
if (isset($startX)) {
$arrayKey .= '_'.$startX;
}
if (isset($endX)) {
$arrayKey .= '_'.$endX;
}
$controlMark = '<input value="'.$id.'" name="tx_dlf[selected]['.$arrayKey.'][id]" type="checkbox">';
$controlMark .= '<input value="'.$startpage.'" name="tx_dlf[selected]['.$arrayKey.'][startpage]" type="hidden">';
$controlMark .= '<input value="'.$endpage.'" name="tx_dlf[selected]['.$arrayKey.'][endpage]" type="hidden">';
// add hidden fields for detail information
if ($startX) {
$controlMark .= '<input type="hidden" name="tx_dlf[selected]['.$arrayKey.'][startX]" value="'.$startX.'">';
$controlMark .= '<input type="hidden" name="tx_dlf[selected]['.$arrayKey.'][startY]" value="'.$startY.'">';
$controlMark .= '<input type="hidden" name="tx_dlf[selected]['.$arrayKey.'][endX]" value="'.$endX.'">';
$controlMark .= '<input type="hidden" name="tx_dlf[selected]['.$arrayKey.'][endY]" value="'.$endY.'">';
$controlMark .= '<input type="hidden" name="tx_dlf[selected]['.$arrayKey.'][rotation]" value="'.$rotation.'">';
}
// return one entry
$markerArray['###CONTROLS###'] = $controlMark;
$markerArray['###NUMBER###'] = $docData['record_id'];
return $this->cObj->substituteMarkerArray($this->cObj->substituteSubpart($template['entry'], '###ENTRY###', '', TRUE), $markerArray);
}
/**
* Adds documents to the basket
* @param array $_piVars piVars
* @param array $basketData basket data
*
* @access protected
*
* @param array $_piVars: piVars
* @param array $basketData: basket data
*
* @return array Basket data and Javascript output
*/
public function addToBasket($_piVars, $basketData) {
protected function addToBasket($_piVars, $basketData) {
$output = '';
if (!$_piVars['startpage']) {
$page = 0;
} else {
$page = intval($_piVars['startpage']);
}
if ($page != NULL || $_piVars['addToBasket'] == 'list') {
$documentItem = [
'id' => intval($_piVars['id']),
'startpage' => intval($_piVars['startpage']),
@ -415,90 +283,51 @@ class Basket extends \Kitodo\Dlf\Common\AbstractPlugin {
'endY' => !isset($_piVars['endY']) || $_piVars['endY'] === "" ? "" : intval($_piVars['endY']),
'rotation' => !isset($_piVars['rotation']) || $_piVars['rotation'] === "" ? "" : intval($_piVars['rotation'])
];
// update basket
if (!empty($basketData['doc_ids'])) {
$items = json_decode($basketData['doc_ids']);
$items = get_object_vars($items);
} else {
$items = [];
}
// get document instance to load further information
$document = Document::getInstance($documentItem['id'], 0);
// set endpage for toc and subentry based on logid
if (($_piVars['addToBasket'] == 'subentry') or ($_piVars['addToBasket'] == 'toc')) {
$smLinks = $document->smLinks;
$pageCounter = sizeof($smLinks['l2p'][$_piVars['logId']]);
$documentItem['endpage'] = ($documentItem['startpage'] + $pageCounter) - 1;
}
// add whole document
if ($_piVars['addToBasket'] == 'list') {
$documentItem['endpage'] = $document->numPages;
}
$arrayKey = $documentItem['id'].'_'.$page;
if (!empty($documentItem['startX'])) {
$arrayKey .= '_'.$documentItem['startX'];
}
if (!empty($documentItem['endX'])) {
$arrayKey .= '_'.$documentItem['endX'];
}
// do not add more than one identical object
if (!in_array($arrayKey, $items)) {
$items[$arrayKey] = $documentItem;
// replace url param placeholder
$pdfParams = str_replace("##startpage##", $documentItem['startpage'], $this->conf['pdfparams']);
$pdfParams = str_replace("##docId##", $document->recordId, $pdfParams);
$pdfParams = str_replace("##startx##", $documentItem['startX'], $pdfParams);
$pdfParams = str_replace("##starty##", $documentItem['startY'], $pdfParams);
$pdfParams = str_replace("##endx##", $documentItem['endX'], $pdfParams);
$pdfParams = str_replace("##endy##", $documentItem['endY'], $pdfParams);
$pdfParams = str_replace("##rotation##", $documentItem['rotation'], $pdfParams);
if ($documentItem['startpage'] != $documentItem['endpage']) {
$pdfParams = str_replace("##endpage##", $documentItem['endpage'], $pdfParams);
} else {
// remove parameter endpage
$pdfParams = str_replace(",##endpage##", '', $pdfParams);
}
$pdfGenerateUrl = $this->conf['pdfgenerate'].$pdfParams;
if ($this->conf['pregeneration']) {
// send ajax request to webapp
$output .= '
<script>
@ -509,198 +338,128 @@ class Basket extends \Kitodo\Dlf\Common\AbstractPlugin {
});
});
</script>';
}
}
$update = ['doc_ids' => json_encode($items)];
$GLOBALS['TYPO3_DB']->exec_UPDATEquery('tx_dlf_basket', 'uid='.intval($basketData['uid']), $update);
$basketData['doc_ids'] = $items;
}
return ['basketData' => $basketData, 'jsOutput' => $output];
}
/**
* Removes selected documents from basket
* @param array $_piVars plugin variables
* @param array $basketData array with document information
*
* @access protected
*
* @param array $_piVars: plugin variables
* @param array $basketData: array with document information
*
* @return array basket data
*/
public function removeFromBasket($_piVars, $basketData) {
protected function removeFromBasket($_piVars, $basketData) {
if (!empty($basketData['doc_ids'])) {
$items = $basketData['doc_ids'];
$items = get_object_vars($items);
}
foreach ($_piVars['selected'] as $value) {
if (isset($value['id'])) {
$arrayKey = $value['id'].'_'.$value['startpage'];
if (isset($value['startX'])) {
$arrayKey .= '_'.$value['startX'];
}
if (isset($value['endX'])) {
$arrayKey .= '_'.$value['endX'];
}
if (isset($items[$arrayKey])) {
unset($items[$arrayKey]);
}
}
}
if (empty($items)) {
$update = ['doc_ids' => ''];
} else {
$update = ['doc_ids' => json_encode($items)];
}
$GLOBALS['TYPO3_DB']->exec_UPDATEquery('tx_dlf_basket', 'uid='.intval($basketData['uid']), $update);
$basketData['doc_ids'] = $items;
return $basketData;
}
/**
* Open selected documents from basket
* @param array $_piVars plugin variables
* @param array $basketData array with document information
*
* @access protected
*
* @param array $_piVars: plugin variables
* @param array $basketData: array with document information
*
* @return array basket data
*/
public function openFromBasket($_piVars, $basketData) {
protected function openFromBasket($_piVars, $basketData) {
$pdfUrl = $this->conf['pdfgenerate'];
foreach ($this->piVars['selected'] as $docValue) {
if ($docValue['id']) {
$docData = $this->getDocumentData($docValue['id'], $docValue);
$pdfUrl .= $docData['urlParams'].$this->conf['pdfparamseparator'];
}
}
header('Location: '.$pdfUrl);
ob_end_flush();
exit;
}
/**
* Returns the downloadurl configured in the basket
* @param integer $id Document id
*
* @access protected
*
* @param integer $id: Document id
*
* @return mixed download url or false
*/
public function getDocumentData($id, $data) {
protected function getDocumentData($id, $data) {
// get document instance to load further information
$document = Document::getInstance($id, 0);
if ($document) {
// replace url param placeholder
$urlParams = str_replace("##page##", intval($data['page']), $this->conf['pdfparams']);
$urlParams = str_replace("##docId##", $document->recordId, $urlParams);
$urlParams = str_replace("##startpage##", intval($data['startpage']), $urlParams);
if ($data['startpage'] != $data['endpage']) {
$urlParams = str_replace("##endpage##", $data['endpage'] === "" ? "" : intval($data['endpage']), $urlParams);
} else {
// remove parameter endpage
$urlParams = str_replace(",##endpage##", '', $urlParams);
}
$urlParams = str_replace("##startx##", $data['startX'] === "" ? "" : intval($data['startX']), $urlParams);
$urlParams = str_replace("##starty##", $data['startY'] === "" ? "" : intval($data['startY']), $urlParams);
$urlParams = str_replace("##endx##", $data['endX'] === "" ? "" : intval($data['endX']), $urlParams);
$urlParams = str_replace("##endy##", $data['endY'] === "" ? "" : intval($data['endY']), $urlParams);
$urlParams = str_replace("##rotation##", $data['rotation'] === "" ? "" : intval($data['rotation']), $urlParams);
$downloadUrl = $this->conf['pdfgenerate'].$urlParams;
$title = $document->getTitle($id, TRUE);
if (empty($title)) {
$title = $this->pi_getLL('noTitle', '', TRUE);
}
// Set page and cutout information
$info = '';
if ($data['startX'] != '' && $data['endX'] != '') {
// cutout
$info .= $this->pi_getLL('cutout', '', TRUE).' ';
}
if ($data['startpage'] == $data['endpage']) {
// One page
$info .= $this->pi_getLL('page', '', TRUE).' '.$data['startpage'];
} else {
$info .= $this->pi_getLL('page', '', TRUE).' '.$data['startpage'].'-'.$data['endpage'];
}
$downloadLink = '<a href="'.$downloadUrl.'" target="_blank">'.$title.'</a> ('.$info.')';
if ($data['startpage'] == $data['endpage']) {
$pageNums = 1;
} else {
$pageNums = $data['endpage'] - $data['startpage'];
}
return [
'downloadUrl' => $downloadUrl,
'downloadLink' => $downloadLink,
@ -708,106 +467,72 @@ class Basket extends \Kitodo\Dlf\Common\AbstractPlugin {
'urlParams' => $urlParams,
'record_id' => $document->recordId,
];
}
return FALSE;
}
/**
* Send mail with pdf download url
*
* @access protected
*
* @return void
*/
public function sendMail() {
protected function sendMail() {
// send mail
$mailId = $this->piVars['mail_action'];
// get id from db and send selected doc downloadlink
$resultMail = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'*',
'tx_dlf_mail',
'tx_dlf_mail.uid="'.intval($mailId).'"'.Helper::whereClause('tx_dlf_mail'),
'tx_dlf_mail.uid='.intval($mailId)
.Helper::whereClause('tx_dlf_mail'),
'',
'',
'1'
);
$mailData = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($resultMail);
$mailText = $this->pi_getLL('mailBody', '', TRUE)."\n";
$numberOfPages = 0;
$pdfUrl = $this->conf['pdfdownload'];
// prepare links
foreach ($this->piVars['selected'] as $docValue) {
if ($docValue['id']) {
$explodeId = explode("_", $docValue['id']);
$docData = $this->getDocumentData($explodeId[0], $docValue);
$pdfUrl .= $docData['urlParams'].$this->conf['pdfparamseparator'];
$pages = (abs(intval($docValue['startpage']) - intval($docValue['endpage'])));
if ($pages === 0) {
$numberOfPages = $numberOfPages + 1;
} else {
$numberOfPages = $numberOfPages + $pages;
}
}
}
// Remove leading/tailing pdfparamseperator
$pdfUrl = trim($pdfUrl, $this->conf['pdfparamseparator']);
$mailBody = $mailText.$pdfUrl;
// Get hook objects.
$hookObjects = Helper::getHookObjects($this->scriptRelPath);
// Hook for getting a customized mail body.
foreach ($hookObjects as $hookObj) {
if (method_exists($hookObj, 'customizeMailBody')) {
$mailBody = $hookObj->customizeMailBody($mailText, $pdfUrl);
}
}
$from = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
// send mail
$mail = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
// Prepare and send the message
$mail
// subject
->setSubject($this->pi_getLL('mailSubject', '', TRUE))
// Set the From address with an associative array
->setFrom($from)
// Set the To addresses with an associative array
->setTo([$mailData['mail'] => $mailData['name']])
->setBody($mailBody, 'text/html')
->send()
;
->send();
// protocol
$insertArray = [
'pid' => $this->conf['pages'],
@ -815,97 +540,65 @@ class Basket extends \Kitodo\Dlf\Common\AbstractPlugin {
'count_pages' => $numberOfPages,
'crdate' => time(),
];
if ($GLOBALS["TSFE"]->loginUser) {
// internal user
$insertArray['user_id'] = $GLOBALS["TSFE"]->fe_user->user['uid'];
$insertArray['name'] = $GLOBALS["TSFE"]->fe_user->user['username'];
$insertArray['label'] = 'Mail: '.$mailData['mail'];
} else {
// external user
$insertArray['user_id'] = 0;
$insertArray['name'] = 'n/a';
$insertArray['label'] = 'Mail: '.$mailData['mail'];
}
// add action to protocol
$GLOBALS['TYPO3_DB']->exec_INSERTquery('tx_dlf_actionlog', $insertArray);
}
/**
* Sends document information to an external printer (url)
*
* @access protected
*
* @return void
*/
public function printDocument() {
protected function printDocument() {
$pdfUrl = $this->conf['pdfprint'];
$numberOfPages = 0;
foreach ($this->piVars['selected'] as $docId => $docValue) {
if ($docValue['id']) {
$docData = $this->getDocumentData($docValue['id'], $docValue);
$pdfUrl .= $docData['urlParams'].$this->conf['pdfparamseparator'];
$numberOfPages += $docData['pageNums'];
}
}
// get printer data
$printerId = $this->piVars['print_action'];
// get id from db and send selected doc downloadlink
$resultPrinter = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'*',
'tx_dlf_printer',
'tx_dlf_printer.uid="'.intval($printerId).'"'.Helper::whereClause('tx_dlf_basket'),
'tx_dlf_printer.uid='.intval($printerId)
.Helper::whereClause('tx_dlf_basket'),
'',
'',
'1'
);
$printerData = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($resultPrinter);
// printer is selected
if ($printerData) {
$pdfUrl = $printerData['print'];
$numberOfPages = 0;
foreach ($this->piVars['selected'] as $docId => $docValue) {
if ($docValue['id']) {
$explodeId = explode("_", $docId);
$docData = $this->getDocumentData($explodeId[0], $docValue);
$pdfUrl .= $docData['urlParams'].$this->conf['pdfparamseparator'];
$numberOfPages += $docData['pageNums'];
}
}
$pdfUrl = trim($pdfUrl, $this->conf['pdfparamseparator']);
}
// protocol
$insertArray = [
'pid' => $this->conf['pages'],
@ -913,36 +606,21 @@ class Basket extends \Kitodo\Dlf\Common\AbstractPlugin {
'count_pages' => $numberOfPages,
'crdate' => time(),
];
if ($GLOBALS["TSFE"]->loginUser) {
// internal user
$insertArray['user_id'] = $GLOBALS["TSFE"]->fe_user->user['uid'];
$insertArray['name'] = $GLOBALS["TSFE"]->fe_user->user['username'];
$insertArray['label'] = 'Print: '.$printerData['label'];
} else {
// external user
$insertArray['user_id'] = 0;
$insertArray['name'] = 'n/a';
$insertArray['label'] = 'Print: '.$printerData['label'];
}
// add action to protocol
$GLOBALS['TYPO3_DB']->exec_INSERTquery('tx_dlf_actionlog', $insertArray);
header('Location: '.$pdfUrl);
ob_end_flush();
exit;
}
}

View File

@ -14,7 +14,7 @@ namespace Kitodo\Dlf\Plugins;
use Kitodo\Dlf\Common\Helper;
/**
* Plugin 'Calendar' for the 'dlf' extension.
* Plugin 'Calendar' for the 'dlf' extension
*
* @author Alexander Bigga <alexander.bigga@slub-dresden.de>
* @package TYPO3
@ -22,9 +22,6 @@ use Kitodo\Dlf\Common\Helper;
* @access public
*/
class Calendar extends \Kitodo\Dlf\Common\AbstractPlugin {
public $extKey = 'dlf';
public $scriptRelPath = 'Classes/Plugins/Calendar.php';
/**
@ -38,10 +35,8 @@ class Calendar extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The content that is displayed on the website
*/
public function main($content, $conf) {
// Nothing to do here.
return $content;
}
/**
@ -55,70 +50,49 @@ class Calendar extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The content that is displayed on the website
*/
public function calendar($content, $conf) {
$this->init($conf);
// Load current document.
$this->loadDocument();
if ($this->doc === NULL) {
// Quit without doing anything if required variables are not set.
return $content;
}
// Load template file.
$this->getTemplate('###TEMPLATECALENDAR###');
// Get all children of year anchor.
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'tx_dlf_documents.uid AS uid, tx_dlf_documents.title AS title, tx_dlf_documents.year AS year',
'tx_dlf_documents',
'(tx_dlf_documents.structure='.Helper::getIdFromIndexName('issue', 'tx_dlf_structures', $this->doc->pid).' AND tx_dlf_documents.partof='.intval($this->doc->uid).')'.Helper::whereClause('tx_dlf_documents'),
'tx_dlf_documents.structure='.Helper::getIdFromIndexName('issue', 'tx_dlf_structures', $this->doc->pid)
.' AND tx_dlf_documents.partof='.intval($this->doc->uid)
.Helper::whereClause('tx_dlf_documents'),
'',
'title ASC',
''
);
// Process results.
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
$issues[] = [
'uid' => $resArray['uid'],
'title' => $resArray['title'],
'year' => $resArray['year']
];
}
// We need an array of issues with month number as key.
$calendarIssues = [];
foreach ($issues as $issue) {
$calendarIssues[date('n', strtotime($issue['year']))][date('j', strtotime($issue['year']))][] = $issue;
}
$allIssues = [];
// Get subpart templates.
$subparts['list'] = $this->cObj->getSubpart($this->template, '###ISSUELIST###');
$subparts['month'] = $this->cObj->getSubpart($this->template, '###CALMONTH###');
$subparts['week'] = $this->cObj->getSubpart($subparts['month'], '###CALWEEK###');
$subparts['singleday'] = $this->cObj->getSubpart($subparts['list'], '###SINGLEDAY###');
// Build calendar for given year.
$year = date('Y', strtotime($issues[0]['year']));
$subPartContent = '';
for ($i = 0; $i <= 11; $i++) {
$markerArray = [
'###DAYMON_NAME###' => strftime('%a', strtotime('last Monday')),
'###DAYTUE_NAME###' => strftime('%a', strtotime('last Tuesday')),
@ -129,19 +103,14 @@ class Calendar extends \Kitodo\Dlf\Common\AbstractPlugin {
'###DAYSUN_NAME###' => strftime('%a', strtotime('last Sunday')),
'###MONTHNAME###' => strftime('%B', strtotime($year.'-'.($i + 1).'-1'))
];
// Reset week content of new month.
$subWeekPartContent = '';
$firstOfMonth = strtotime($year.'-'.($i + 1).'-1');
$lastOfMonth = strtotime('last day of', ($firstOfMonth));
$firstOfMonthStart = strtotime('last Monday', $firstOfMonth);
// There are never more than 6 weeks in a month.
for ($j = 0; $j <= 5; $j++) {
$firstDayOfWeek = strtotime('+ '.$j.' Week', $firstOfMonthStart);
$weekArray = [
'###DAYMON###' => '&nbsp;',
'###DAYTUE###' => '&nbsp;',
@ -151,157 +120,105 @@ class Calendar extends \Kitodo\Dlf\Common\AbstractPlugin {
'###DAYSAT###' => '&nbsp;',
'###DAYSUN###' => '&nbsp;',
];
// Every week has seven days. ;-)
for ($k = 0; $k <= 6; $k++) {
$currentDayTime = strtotime('+ '.$k.' Day', $firstDayOfWeek);
if ($currentDayTime >= $firstOfMonth && $currentDayTime <= $lastOfMonth) {
if ($currentDayTime >= $firstOfMonth
&& $currentDayTime <= $lastOfMonth) {
$dayLinks = '';
$dayLinksText = [];
$dayLinksList = '';
$currentMonth = date('n', $currentDayTime);
if (is_array($calendarIssues[$currentMonth])) {
foreach ($calendarIssues[$currentMonth] as $id => $day) {
if ($id == date('j', $currentDayTime)) {
$dayLinks = $id;
foreach ($day as $issue) {
$dayLinkLabel = empty($issue['title']) ? strftime('%x', $currentDayTime) : $issue['title'];
$linkConf = [
'useCacheHash' => 1,
'parameter' => $this->conf['targetPid'],
'additionalParams' => '&'.$this->prefixId.'[id]='.urlencode($issue['uid']),
'ATagParams' => ' class="title"',
];
$dayLinksText[] = $this->cObj->typoLink($dayLinkLabel, $linkConf);
// Save issues for list view.
$allIssues[$currentDayTime][] = $this->cObj->typoLink($dayLinkLabel, $linkConf);
}
}
}
if (!empty($dayLinksText)) {
$dayLinksList = '<ul>';
foreach ($dayLinksText as $link) {
$dayLinksList .= '<li>'.$link.'</li>';
}
$dayLinksList .= '</ul>';
}
$dayLinkDiv = '<div class="issues"><h4>'.strftime('%d', $currentDayTime).'</h4><div>'.$dayLinksList.'</div></div>';
}
switch (strftime('%w', strtotime('+ '.$k.' Day', $firstDayOfWeek))) {
case '0': $weekArray['###DAYSUN###'] = ((int) $dayLinks === (int) date('j', $currentDayTime)) ? $dayLinkDiv : strftime('%d', $currentDayTime);
case '0':
$weekArray['###DAYSUN###'] = ((int) $dayLinks === (int) date('j', $currentDayTime)) ? $dayLinkDiv : strftime('%d', $currentDayTime);
break;
case '1': $weekArray['###DAYMON###'] = ((int) $dayLinks === (int) date('j', $currentDayTime)) ? $dayLinkDiv : strftime('%d', $currentDayTime);
case '1':
$weekArray['###DAYMON###'] = ((int) $dayLinks === (int) date('j', $currentDayTime)) ? $dayLinkDiv : strftime('%d', $currentDayTime);
break;
case '2': $weekArray['###DAYTUE###'] = ((int) $dayLinks === (int) date('j', $currentDayTime)) ? $dayLinkDiv : strftime('%d', $currentDayTime);
case '2':
$weekArray['###DAYTUE###'] = ((int) $dayLinks === (int) date('j', $currentDayTime)) ? $dayLinkDiv : strftime('%d', $currentDayTime);
break;
case '3': $weekArray['###DAYWED###'] = ((int) $dayLinks === (int) date('j', $currentDayTime)) ? $dayLinkDiv : strftime('%d', $currentDayTime);
case '3':
$weekArray['###DAYWED###'] = ((int) $dayLinks === (int) date('j', $currentDayTime)) ? $dayLinkDiv : strftime('%d', $currentDayTime);
break;
case '4': $weekArray['###DAYTHU###'] = ((int) $dayLinks === (int) date('j', $currentDayTime)) ? $dayLinkDiv : strftime('%d', $currentDayTime);
case '4':
$weekArray['###DAYTHU###'] = ((int) $dayLinks === (int) date('j', $currentDayTime)) ? $dayLinkDiv : strftime('%d', $currentDayTime);
break;
case '5': $weekArray['###DAYFRI###'] = ((int) $dayLinks === (int) date('j', $currentDayTime)) ? $dayLinkDiv : strftime('%d', $currentDayTime);
case '5':
$weekArray['###DAYFRI###'] = ((int) $dayLinks === (int) date('j', $currentDayTime)) ? $dayLinkDiv : strftime('%d', $currentDayTime);
break;
case '6': $weekArray['###DAYSAT###'] = ((int) $dayLinks === (int) date('j', $currentDayTime)) ? $dayLinkDiv : strftime('%d', $currentDayTime);
case '6':
$weekArray['###DAYSAT###'] = ((int) $dayLinks === (int) date('j', $currentDayTime)) ? $dayLinkDiv : strftime('%d', $currentDayTime);
break;
}
}
}
// Fill the weeks.
$subWeekPartContent .= $this->cObj->substituteMarkerArray($subparts['week'], $weekArray);
}
// Fill the month markers.
$subPartContent .= $this->cObj->substituteMarkerArray($subparts['month'], $markerArray);
// Fill the week markers with the week entries.
$subPartContent = $this->cObj->substituteSubpart($subPartContent, '###CALWEEK###', $subWeekPartContent);
}
// Link to years overview
$linkConf = [
'useCacheHash' => 1,
'parameter' => $this->conf['targetPid'],
'additionalParams' => '&'.$this->prefixId.'[id]='.urlencode($this->doc->parentId),
];
$allYearsLink = $this->cObj->typoLink($this->pi_getLL('allYears', '', TRUE).' '.$this->doc->getTitle($this->doc->parentId), $linkConf);
// Link to current year.
$linkConf = [
'useCacheHash' => 1,
'parameter' => $this->conf['targetPid'],
'additionalParams' => '&'.$this->prefixId.'[id]='.urlencode($this->doc->uid),
];
$yearLink = $this->cObj->typoLink($year, $linkConf);
$subPartContentList = '';
// Prepare list as alternative of the calendar view.
foreach ($allIssues as $dayTime => $issues) {
$markerArrayDay['###DATE_STRING###'] = strftime('%A, %x', $dayTime);
$markerArrayDay['###ITEMS###'] = '';
foreach ($issues as $issue) {
$markerArrayDay['###ITEMS###'] .= $issue;
}
$subPartContentList .= $this->cObj->substituteMarkerArray($subparts['singleday'], $markerArrayDay);
}
$this->template = $this->cObj->substituteSubpart($this->template, '###SINGLEDAY###', $subPartContentList);
if (count($allIssues) < 6) {
$listViewActive = TRUE;
} else {
$listViewActive = FALSE;
}
$markerArray = [
'###CALENDARVIEWACTIVE###' => $listViewActive ? '' : 'active',
'###LISTVIEWACTIVE###' => $listViewActive ? 'active' : '',
@ -310,11 +227,8 @@ class Calendar extends \Kitodo\Dlf\Common\AbstractPlugin {
'###LABEL_CALENDAR###' => $this->pi_getLL('label.view_calendar'),
'###LABEL_LIST_VIEW###' => $this->pi_getLL('label.view_list'),
];
$this->template = $this->cObj->substituteMarkerArray($this->template, $markerArray);
return $this->cObj->substituteSubpart($this->template, '###CALMONTH###', $subPartContent);
}
/**
@ -328,70 +242,52 @@ class Calendar extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The content that is displayed on the website
*/
public function years($content, $conf) {
$this->init($conf);
// Load current document.
$this->loadDocument();
if ($this->doc === NULL) {
// Quit without doing anything if required variables are not set.
return $content;
}
// Load template file.
$this->getTemplate('###TEMPLATEYEAR###');
// Get subpart templates
$subparts['year'] = $this->cObj->getSubpart($this->template, '###LISTYEAR###');
// get the title of the anchor file
// Get the title of the anchor file
$titleAnchor = $this->doc->getTitle($this->doc->uid);
// get all children of anchor. this should be the year anchor documents
// Get all children of anchor. This should be the year anchor documents
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'tx_dlf_documents.uid AS uid, tx_dlf_documents.title AS title',
'tx_dlf_documents',
'(tx_dlf_documents.structure='.Helper::getIdFromIndexName('year', 'tx_dlf_structures', $this->doc->pid).' AND tx_dlf_documents.partof='.intval($this->doc->uid).')'.Helper::whereClause('tx_dlf_documents'),
'tx_dlf_documents.structure='.Helper::getIdFromIndexName('year', 'tx_dlf_structures', $this->doc->pid)
.' AND tx_dlf_documents.partof='.intval($this->doc->uid)
.Helper::whereClause('tx_dlf_documents'),
'',
'title ASC',
''
);
// Process results.
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
$years[] = [
'title' => $resArray['title'],
'uid' => $resArray['uid']
];
}
$subYearPartContent = '';
if (count($years) > 0) {
foreach ($years as $id => $year) {
$linkConf = [
'useCacheHash' => 1,
'parameter' => $this->conf['targetPid'],
'additionalParams' => '&'.$this->prefixId.'[id]='.urlencode($year['uid']),
'title' => $titleAnchor.': '.$year['title']
];
$yearArray = [
'###YEARNAME###' => $this->cObj->typoLink($year['title'], $linkConf),
];
$subYearPartContent .= $this->cObj->substituteMarkerArray($subparts['year'], $yearArray);
}
}
// link to years overview (should be itself here)
$linkConf = [
'useCacheHash' => 1,
@ -399,18 +295,13 @@ class Calendar extends \Kitodo\Dlf\Common\AbstractPlugin {
'additionalParams' => '&'.$this->prefixId.'[id]='.$this->doc->uid,
];
$allYearsLink = $this->cObj->typoLink($this->pi_getLL('allYears', '', TRUE).' '.$this->doc->getTitle($this->doc->uid), $linkConf);
// Fill markers.
$markerArray = [
'###LABEL_CHOOSE_YEAR###' => $this->pi_getLL('label.please_choose_year'),
'###CALALLYEARS###' => $allYearsLink
];
$this->template = $this->cObj->substituteMarkerArray($this->template, $markerArray);
// fill the week markers
// Fill the week markers
return $this->cObj->substituteSubpart($this->template, '###LISTYEAR###', $subYearPartContent);
}
}

View File

@ -16,7 +16,7 @@ use Kitodo\Dlf\Common\Helper;
use Kitodo\Dlf\Common\Solr;
/**
* Plugin 'Collection' for the 'dlf' extension.
* Plugin 'Collection' for the 'dlf' extension
*
* @author Sebastian Meyer <sebastian.meyer@slub-dresden.de>
* @package TYPO3
@ -24,7 +24,6 @@ use Kitodo\Dlf\Common\Solr;
* @access public
*/
class Collection extends \Kitodo\Dlf\Common\AbstractPlugin {
public $scriptRelPath = 'Classes/Plugins/Collection.php';
/**
@ -46,43 +45,26 @@ class Collection extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The content that is displayed on the website
*/
public function main($content, $conf) {
$this->init($conf);
// Turn cache on.
$this->setCache(TRUE);
// Quit without doing anything if required configuration variables are not set.
if (empty($this->conf['pages'])) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Plugins\Collection->main('.$content.', [data])] Incomplete plugin configuration', $this->extKey, SYSLOG_SEVERITY_WARNING, $conf);
}
return $content;
}
// Load template file.
$this->getTemplate();
// Get hook objects.
$this->hookObjects = Helper::getHookObjects($this->scriptRelPath);
if (!empty($this->piVars['collection'])) {
$this->showSingleCollection(intval($this->piVars['collection']));
} else {
$content .= $this->showCollectionList();
}
return $this->pi_wrapInBaseClass($content);
}
/**
@ -93,234 +75,142 @@ class Collection extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The list of collections ready to output
*/
protected function showCollectionList() {
$selectedCollections = 'tx_dlf_collections.uid != 0';
$orderBy = 'tx_dlf_collections.label';
$showUserDefinedColls = '';
// Handle collections set by configuration.
if ($this->conf['collections']) {
if (count(explode(',', $this->conf['collections'])) == 1 && empty($this->conf['dont_show_single'])) {
if (count(explode(',', $this->conf['collections'])) == 1
&& empty($this->conf['dont_show_single'])) {
$this->showSingleCollection(intval(trim($this->conf['collections'], ' ,')));
}
$selectedCollections = 'tx_dlf_collections.uid IN ('.$GLOBALS['TYPO3_DB']->cleanIntList($this->conf['collections']).')';
$orderBy = 'FIELD(tx_dlf_collections.uid,'.$GLOBALS['TYPO3_DB']->cleanIntList($this->conf['collections']).')';
}
// Should user-defined collections be shown?
if (empty($this->conf['show_userdefined'])) {
$showUserDefinedColls = ' AND tx_dlf_collections.fe_cruser_id=0';
} elseif ($this->conf['show_userdefined'] > 0) {
if (!empty($GLOBALS['TSFE']->fe_user->user['uid'])) {
$showUserDefinedColls = ' AND tx_dlf_collections.fe_cruser_id='.intval($GLOBALS['TSFE']->fe_user->user['uid']);
} else {
$showUserDefinedColls = ' AND NOT tx_dlf_collections.fe_cruser_id=0';
}
}
// Get collections.
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'tx_dlf_collections.index_name AS index_name,tx_dlf_collections.index_search as index_query,tx_dlf_collections.uid AS uid,tx_dlf_collections.sys_language_uid AS sys_language_uid,tx_dlf_collections.label AS label,tx_dlf_collections.thumbnail AS thumbnail,tx_dlf_collections.description AS description,tx_dlf_collections.priority AS priority',
'tx_dlf_collections',
$selectedCollections.$showUserDefinedColls.' AND tx_dlf_collections.pid='.intval($this->conf['pages']).' AND (tx_dlf_collections.sys_language_uid IN (-1,0) OR (tx_dlf_collections.sys_language_uid = '.$GLOBALS['TSFE']->sys_language_uid.' AND tx_dlf_collections.l18n_parent = 0))'.Helper::whereClause('tx_dlf_collections'),
$selectedCollections
.$showUserDefinedColls
.' AND tx_dlf_collections.pid='.intval($this->conf['pages'])
.' AND (tx_dlf_collections.sys_language_uid IN (-1,0) OR (tx_dlf_collections.sys_language_uid = '.$GLOBALS['TSFE']->sys_language_uid.' AND tx_dlf_collections.l18n_parent = 0))'
.Helper::whereClause('tx_dlf_collections'),
'',
$orderBy,
''
);
$count = $GLOBALS['TYPO3_DB']->sql_num_rows($result);
$content = '';
if ($count == 1 && empty($this->conf['dont_show_single'])) {
if ($count == 1
&& empty($this->conf['dont_show_single'])) {
$resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result);
$this->showSingleCollection(intval($resArray['uid']));
}
$solr = Solr::getInstance($this->conf['solrcore']);
// We only care about the UID and partOf in the results and want them sorted
$params['fields'] = 'uid,partof';
$params['sort'] = ['uid' => 'asc'];
$collections = [];
while ($collectionData = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
if ($collectionData['sys_language_uid'] != $GLOBALS['TSFE']->sys_language_content && $GLOBALS['TSFE']->sys_language_contentOL) {
$collections[$collectionData['uid']] = $GLOBALS['TSFE']->sys_page->getRecordOverlay('tx_dlf_collections', $collectionData, $GLOBALS['TSFE']->sys_language_content, $GLOBALS['TSFE']->sys_language_contentOL);
} else {
$collections[$collectionData['uid']] = $collectionData;
}
}
$markerArray = [];
// Process results.
foreach ($collections as $collection) {
$solr_query = '';
if ($collection['index_query'] != '') {
$solr_query .= '('.$collection['index_query'].')';
} else {
$solr_query .= 'collection:("'.$collection['index_name'].'")';
}
$partOfNothing = $solr->search_raw($solr_query.' AND partof:0', $params);
$partOfSomething = $solr->search_raw($solr_query.' AND NOT partof:0', $params);
// Titles are all documents that are "root" elements i.e. partof == 0
$collection['titles'] = [];
foreach ($partOfNothing as $doc) {
$collection['titles'][$doc->uid] = $doc->uid;
}
// Volumes are documents that are both
// a) "leaf" elements i.e. partof != 0
// b) "root" elements that are not referenced by other documents ("root" elements that have no descendants)
$collection['volumes'] = $collection['titles'];
foreach ($partOfSomething as $doc) {
$collection['volumes'][$doc->uid] = $doc->uid;
// If a document is referenced via partof, its not a volume anymore.
unset($collection['volumes'][$doc->partof]);
}
// Generate random but unique array key taking priority into account.
do {
$_key = ($collection['priority'] * 1000) + mt_rand(0, 1000);
} while (!empty($markerArray[$_key]));
// Merge plugin variables with new set of values.
$additionalParams = ['collection' => $collection['uid']];
if (is_array($this->piVars)) {
$piVars = $this->piVars;
unset($piVars['DATA']);
$additionalParams = \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($piVars, $additionalParams);
}
// Build typolink configuration array.
$conf = [
'useCacheHash' => 1,
'parameter' => $GLOBALS['TSFE']->id,
'additionalParams' => \TYPO3\CMS\Core\Utility\GeneralUtility::implodeArrayForUrl($this->prefixId, $additionalParams, '', TRUE, FALSE)
];
// Link collection's title to list view.
$markerArray[$_key]['###TITLE###'] = $this->cObj->typoLink(htmlspecialchars($collection['label']), $conf);
// Add feed link if applicable.
if (!empty($this->conf['targetFeed'])) {
$img = '<img src="'.\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey).'Resources/Public/Icons/txdlffeeds.png" alt="'.$this->pi_getLL('feedAlt', '', TRUE).'" title="'.$this->pi_getLL('feedTitle', '', TRUE).'" />';
$markerArray[$_key]['###FEED###'] = $this->pi_linkTP($img, [$this->prefixId => ['collection' => $collection['uid']]], FALSE, $this->conf['targetFeed']);
} else {
$markerArray[$_key]['###FEED###'] = '';
}
// Add thumbnail.
if (!empty($collection['thumbnail'])) {
$markerArray[$_key]['###THUMBNAIL###'] = '<img alt="" title="'.htmlspecialchars($collection['label']).'" src="'.$collection['thumbnail'].'" />';
} else {
$markerArray[$_key]['###THUMBNAIL###'] = '';
}
// Add description.
$markerArray[$_key]['###DESCRIPTION###'] = $this->pi_RTEcssText($collection['description']);
// Build statistic's output.
$labelTitles = $this->pi_getLL((count($collection['titles']) > 1 ? 'titles' : 'title'), '', FALSE);
$markerArray[$_key]['###COUNT_TITLES###'] = htmlspecialchars(count($collection['titles']).$labelTitles);
$labelVolumes = $this->pi_getLL((count($collection['volumes']) > 1 ? 'volumes' : 'volume'), '', FALSE);
$markerArray[$_key]['###COUNT_VOLUMES###'] = htmlspecialchars(count($collection['volumes']).$labelVolumes);
}
// Randomize sorting?
if (!empty($this->conf['randomize'])) {
ksort($markerArray, SORT_NUMERIC);
// Don't cache the output.
$this->setCache(FALSE);
}
$entry = $this->cObj->getSubpart($this->template, '###ENTRY###');
foreach ($markerArray as $marker) {
$content .= $this->cObj->substituteMarkerArray($entry, $marker);
}
// Hook for getting custom collection hierarchies/subentries (requested by SBB).
foreach ($this->hookObjects as $hookObj) {
if (method_exists($hookObj, 'showCollectionList_getCustomCollectionList')) {
$hookObj->showCollectionList_getCustomCollectionList($this, $this->conf['templateFile'], $content, $markerArray);
}
}
return $this->cObj->substituteSubpart($this->template, '###ENTRY###', $content, TRUE);
}
/**
@ -333,102 +223,69 @@ class Collection extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return void
*/
protected function showSingleCollection($id) {
$additionalWhere = '';
// Should user-defined collections be shown?
if (empty($this->conf['show_userdefined'])) {
$additionalWhere = ' AND tx_dlf_collections.fe_cruser_id=0';
} elseif ($this->conf['show_userdefined'] > 0) {
$additionalWhere = ' AND NOT tx_dlf_collections.fe_cruser_id=0';
}
// Get collection information from DB
$collection = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'tx_dlf_collections.index_name AS index_name, tx_dlf_collections.index_search as index_query, tx_dlf_collections.label AS collLabel, tx_dlf_collections.description AS collDesc, tx_dlf_collections.thumbnail AS collThumb, tx_dlf_collections.fe_cruser_id',
'tx_dlf_collections',
'tx_dlf_collections.pid='.intval($this->conf['pages']).' AND tx_dlf_collections.uid='.intval($id).$additionalWhere.Helper::whereClause('tx_dlf_collections'),
'tx_dlf_collections.pid='.intval($this->conf['pages'])
.' AND tx_dlf_collections.uid='.intval($id)
.$additionalWhere
.Helper::whereClause('tx_dlf_collections'),
'',
'',
'1'
);
// Fetch corresponding document UIDs from Solr.
$solr_query = '';
$collectionData = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($collection);
if ($collectionData['index_query'] != '') {
$solr_query .= '('.$collectionData['index_query'].')';
} else {
$solr_query .= 'collection:("'.$collectionData['index_name'].'")';
}
$solr = Solr::getInstance($this->conf['solrcore']);
if (!$solr->ready) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Plugins\Collection->showSingleCollection('.intval($id).')] Apache Solr not available', $this->extKey, SYSLOG_SEVERITY_ERROR);
}
return;
}
$params['fields'] = 'uid';
$params['sort'] = ['uid' => 'asc'];
$solrResult = $solr->search_raw($solr_query, $params);
// initialize array
// Initialize array
$documentSet = [];
foreach ($solrResult as $doc) {
$documentSet[] = $doc->uid;
}
$documentSet = array_unique($documentSet);
//Fetch document info for UIDs in $documentSet from DB
// Fetch document info for UIDs in $documentSet from DB
$documents = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'tx_dlf_documents.uid AS uid, tx_dlf_documents.metadata_sorting AS metadata_sorting, tx_dlf_documents.volume_sorting AS volume_sorting, tx_dlf_documents.partof AS partof',
'tx_dlf_documents',
'tx_dlf_documents.pid='.intval($this->conf['pages']).' AND tx_dlf_documents.uid IN ('.implode(',', $documentSet).')'.Helper::whereClause('tx_dlf_documents'),
'tx_dlf_documents.pid='.intval($this->conf['pages'])
.' AND tx_dlf_documents.uid IN ('.implode(',', $documentSet).')'
.Helper::whereClause('tx_dlf_documents'),
'',
'',
''
);
$toplevel = [];
$subparts = [];
$listMetadata = [];
// Process results.
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($documents)) {
if (empty($l10nOverlay)) {
$l10nOverlay = $GLOBALS['TSFE']->sys_page->getRecordOverlay('tx_dlf_collections', $resArray, $GLOBALS['TSFE']->sys_language_content, $GLOBALS['TSFE']->sys_language_contentOL);
}
if (empty($listMetadata)) {
$listMetadata = [
'label' => !empty($l10nOverlay['label']) ? htmlspecialchars($l10nOverlay['label']) : htmlspecialchars($collectionData['collLabel']),
'description' => !empty($l10nOverlay['description']) ? $this->pi_RTEcssText($l10nOverlay['description']) : $this->pi_RTEcssText($collectionData['collDesc']),
@ -444,89 +301,52 @@ class Collection extends \Kitodo\Dlf\Common\AbstractPlugin {
'order.asc' => TRUE
]
];
}
// Split toplevel documents from volumes.
if ($resArray['partof'] == 0) {
// Prepare document's metadata for sorting.
$sorting = unserialize($resArray['metadata_sorting']);
if (!empty($sorting['type']) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($sorting['type'])) {
$sorting['type'] = Helper::getIndexName($sorting['type'], 'tx_dlf_structures', $this->conf['pages']);
}
if (!empty($sorting['owner']) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($sorting['owner'])) {
$sorting['owner'] = Helper::getIndexName($sorting['owner'], 'tx_dlf_libraries', $this->conf['pages']);
}
if (!empty($sorting['collection']) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($sorting['collection'])) {
$sorting['collection'] = Helper::getIndexName($sorting['collection'], 'tx_dlf_collections', $this->conf['pages']);
}
$toplevel[$resArray['uid']] = [
'u' => $resArray['uid'],
'h' => '',
's' => $sorting,
'p' => []
];
} else {
$subparts[$resArray['partof']][$resArray['volume_sorting']] = $resArray['uid'];
}
}
// Add volumes to the corresponding toplevel documents.
foreach ($subparts as $partof => $parts) {
if (!empty($toplevel[$partof])) {
ksort($parts);
foreach ($parts as $part) {
$toplevel[$partof]['p'][] = ['u' => $part];
}
}
}
// Save list of documents.
$list = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(DocumentList::class);
$list->reset();
$list->add(array_values($toplevel));
$listMetadata['options']['numberOfToplevelHits'] = count($list);
$list->metadata = $listMetadata;
$list->save();
// Clean output buffer.
\TYPO3\CMS\Core\Utility\GeneralUtility::cleanOutputBuffers();
// Send headers.
header('Location: '.\TYPO3\CMS\Core\Utility\GeneralUtility::locationHeaderUrl($this->cObj->typoLink_URL(['parameter' => $this->conf['targetPid']])));
// Flush output buffer and end script processing.
ob_end_flush();
exit;
}
}

View File

@ -19,8 +19,7 @@ namespace Kitodo\Dlf\Plugins\Eid;
* @subpackage dlf
* @access public
*/
class PageViewProxy extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
{
class PageViewProxy extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin {
public $scriptRelPath = 'Classes/Plugins/Eid/PageViewProxy.php';
/**
@ -33,8 +32,7 @@ class PageViewProxy extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
*
* @return string
*/
public function main($content = '', $conf = [])
{
public function main($content = '', $conf = []) {
$this->cObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::class);
$header = \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('header');
$url = \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('url');
@ -46,10 +44,8 @@ class PageViewProxy extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
header('Content-Type: '.finfo_buffer(finfo_open(FILEINFO_MIME), $fetchedData));
// Get last modified date from request header
$fetchedHeader = explode("\n", \TYPO3\CMS\Core\Utility\GeneralUtility::getUrl($url, 2));
foreach ($fetchedHeader as $headerline)
{
if (stripos($headerline, 'Last-Modified:') !== FALSE)
{
foreach ($fetchedHeader as $headerline) {
if (stripos($headerline, 'Last-Modified:') !== FALSE) {
header($headerline);
break;
}

View File

@ -23,8 +23,7 @@ use Kitodo\Dlf\Common\Solr;
* @subpackage dlf
* @access public
*/
class SearchSuggest extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
{
class SearchSuggest extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin {
public $scriptRelPath = 'Classes/Plugins/Eid/SearchSuggest.php';
/**
@ -37,18 +36,14 @@ class SearchSuggest extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
*
* @return string XML response of search suggestions
*/
public function main($content = '', $conf = [])
{
public function main($content = '', $conf = []) {
if (\TYPO3\CMS\Core\Utility\GeneralUtility::_GP('encrypted') != ''
&& \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('hashed') != '')
{
&& \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('hashed') != '') {
$core = Helper::decrypt(\TYPO3\CMS\Core\Utility\GeneralUtility::_GP('encrypted'), \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('hashed'));
}
if (!empty($core))
{
if (!empty($core)) {
$url = trim(Solr::getSolrUrl($core), '/').'/suggest/?wt=xml&q='.Solr::escapeQuery(\TYPO3\CMS\Core\Utility\GeneralUtility::_GP('q'));
if ($stream = fopen($url, 'r'))
{
if ($stream = fopen($url, 'r')) {
$content .= stream_get_contents($stream);
fclose($stream);
}

View File

@ -15,7 +15,7 @@ use Kitodo\Dlf\Common\Document;
use Kitodo\Dlf\Common\Helper;
/**
* Plugin 'Feeds' for the 'dlf' extension.
* Plugin 'Feeds' for the 'dlf' extension
*
* @author Sebastian Meyer <sebastian.meyer@slub-dresden.de>
* @package TYPO3
@ -23,7 +23,6 @@ use Kitodo\Dlf\Common\Helper;
* @access public
*/
class Feeds extends \Kitodo\Dlf\Common\AbstractPlugin {
public $scriptRelPath = 'Classes/Plugins/Feeds.php';
/**
@ -37,197 +36,130 @@ class Feeds extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return void
*/
public function main($content, $conf) {
$this->init($conf);
// Don't cache the output.
$this->setCache(FALSE);
// Create XML document.
$rss = new \DOMDocument('1.0', 'utf-8');
// Add mandatory root element.
$root = $rss->createElement('rss');
$root->setAttribute('version', '2.0');
// Add channel element.
$channel = $rss->createElement('channel');
$channel->appendChild($rss->createElement('title', htmlspecialchars($this->conf['title'], ENT_NOQUOTES, 'UTF-8')));
$channel->appendChild($rss->createElement('link', htmlspecialchars(\TYPO3\CMS\Core\Utility\GeneralUtility::locationHeaderUrl($this->pi_linkTP_keepPIvars_url()), ENT_NOQUOTES, 'UTF-8')));
if (!empty($this->conf['description'])) {
$channel->appendChild($rss->createElement('description', htmlspecialchars($this->conf['description'], ENT_QUOTES, 'UTF-8')));
}
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'tx_dlf_libraries.label AS label',
'tx_dlf_libraries',
'tx_dlf_libraries.pid='.intval($this->conf['pages']).' AND tx_dlf_libraries.uid='.intval($this->conf['library']).Helper::whereClause('tx_dlf_libraries'),
'tx_dlf_libraries.pid='.intval($this->conf['pages'])
.' AND tx_dlf_libraries.uid='.intval($this->conf['library'])
.Helper::whereClause('tx_dlf_libraries'),
'',
'',
'1'
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result)) {
$resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result);
$channel->appendChild($rss->createElement('copyright', htmlspecialchars($resArray['label'], ENT_NOQUOTES, 'UTF-8')));
}
$channel->appendChild($rss->createElement('pubDate', date('r', $GLOBALS['EXEC_TIME'])));
$channel->appendChild($rss->createElement('generator', htmlspecialchars($this->conf['useragent'], ENT_NOQUOTES, 'UTF-8')));
// Add item elements.
if (!$this->conf['excludeOther'] || empty($this->piVars['collection']) || \TYPO3\CMS\Core\Utility\GeneralUtility::inList($this->conf['collections'], $this->piVars['collection'])) {
if (!$this->conf['excludeOther']
|| empty($this->piVars['collection'])
|| \TYPO3\CMS\Core\Utility\GeneralUtility::inList($this->conf['collections'], $this->piVars['collection'])) {
$additionalWhere = '';
// Check for pre-selected collections.
if (!empty($this->piVars['collection'])) {
$additionalWhere = ' AND tx_dlf_collections.uid='.intval($this->piVars['collection']);
} elseif (!empty($this->conf['collections'])) {
$additionalWhere = ' AND tx_dlf_collections.uid IN ('.$GLOBALS['TYPO3_DB']->cleanIntList($this->conf['collections']).')';
}
$result = $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query(
'tx_dlf_documents.uid AS uid,tx_dlf_documents.partof AS partof,tx_dlf_documents.title AS title,tx_dlf_documents.volume AS volume,tx_dlf_documents.author AS author,tx_dlf_documents.record_id AS guid,tx_dlf_documents.tstamp AS tstamp,tx_dlf_documents.crdate AS crdate',
'tx_dlf_documents',
'tx_dlf_relations',
'tx_dlf_collections',
'AND tx_dlf_documents.pid='.intval($this->conf['pages']).' AND tx_dlf_relations.ident='.$GLOBALS['TYPO3_DB']->fullQuoteStr('docs_colls', 'tx_dlf_relations').' AND tx_dlf_collections.pid='.intval($this->conf['pages']).$additionalWhere.Helper::whereClause('tx_dlf_documents').Helper::whereClause('tx_dlf_collections'),
'AND tx_dlf_documents.pid='.intval($this->conf['pages'])
.' AND tx_dlf_relations.ident='.$GLOBALS['TYPO3_DB']->fullQuoteStr('docs_colls', 'tx_dlf_relations')
.' AND tx_dlf_collections.pid='.intval($this->conf['pages'])
.$additionalWhere
.Helper::whereClause('tx_dlf_documents')
.Helper::whereClause('tx_dlf_collections'),
'tx_dlf_documents.uid',
'tx_dlf_documents.tstamp DESC',
intval($this->conf['limit'])
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result)) {
// Add each record as item element.
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
$item = $rss->createElement('item');
$title = '';
// Get title of superior document.
if ((empty($resArray['title']) || !empty($this->conf['prependSuperiorTitle'])) && !empty($resArray['partof'])) {
if ((empty($resArray['title']) || !empty($this->conf['prependSuperiorTitle']))
&& !empty($resArray['partof'])) {
$superiorTitle = Document::getTitle($resArray['partof'], TRUE);
if (!empty($superiorTitle)) {
$title .= '['.$superiorTitle.']';
}
}
// Get title of document.
if (!empty($resArray['title'])) {
$title .= ' '.$resArray['title'];
}
// Set default title if empty.
if (empty($title)) {
$title = $this->pi_getLL('noTitle');
}
// Append volume information.
if (!empty($resArray['volume'])) {
$title .= ', '.$this->pi_getLL('volume').' '.$resArray['volume'];
}
// Is this document new or updated?
if ($resArray['crdate'] == $resArray['tstamp']) {
$title = $this->pi_getLL('new').' '.trim($title);
} else {
$title = $this->pi_getLL('update').' '.trim($title);
}
$item->appendChild($rss->createElement('title', htmlspecialchars($title, ENT_NOQUOTES, 'UTF-8')));
// Add link.
$linkConf = [
'parameter' => $this->conf['targetPid'],
'forceAbsoluteUrl' => 1,
'additionalParams' => \TYPO3\CMS\Core\Utility\GeneralUtility::implodeArrayForUrl($this->prefixId, ['id' => $resArray['uid']], '', TRUE, FALSE)
];
$item->appendChild($rss->createElement('link', htmlspecialchars($this->cObj->typoLink_URL($linkConf), ENT_NOQUOTES, 'UTF-8')));
// Add author if applicable.
if (!empty($resArray['author'])) {
$item->appendChild($rss->createElement('author', htmlspecialchars($resArray['author'], ENT_NOQUOTES, 'UTF-8')));
}
// Add online publication date.
$item->appendChild($rss->createElement('pubDate', date('r', $resArray['crdate'])));
// Add internal record identifier.
$item->appendChild($rss->createElement('guid', htmlspecialchars($resArray['guid'], ENT_NOQUOTES, 'UTF-8')));
$channel->appendChild($item);
}
}
}
$root->appendChild($channel);
// Build XML output.
$rss->appendChild($root);
$content = $rss->saveXML();
// Clean output buffer.
\TYPO3\CMS\Core\Utility\GeneralUtility::cleanOutputBuffers();
// Send headers.
header('HTTP/1.1 200 OK');
header('Cache-Control: no-cache');
header('Content-Length: '.strlen($content));
header('Content-Type: application/rss+xml; charset=utf-8');
header('Date: '.date('r', $GLOBALS['EXEC_TIME']));
header('Expires: '.date('r', $GLOBALS['EXEC_TIME']));
echo $content;
// Flush output buffer and end script processing.
ob_end_flush();
exit;
}
}

View File

@ -17,7 +17,7 @@ use Kitodo\Dlf\Common\Helper;
use Kitodo\Dlf\Common\Solr;
/**
* Plugin 'List View' for the 'dlf' extension.
* Plugin 'List View' for the 'dlf' extension
*
* @author Sebastian Meyer <sebastian.meyer@slub-dresden.de>
* @author Henrik Lochmann <dev@mentalmotive.com>
@ -27,7 +27,6 @@ use Kitodo\Dlf\Common\Solr;
* @access public
*/
class ListView extends \Kitodo\Dlf\Common\AbstractPlugin {
public $scriptRelPath = 'Classes/Plugins/ListView.php';
/**
@ -70,77 +69,44 @@ class ListView extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The rendered page browser ready for output
*/
protected function getPageBrowser() {
// Get overall number of pages.
$maxPages = intval(ceil($this->list->metadata['options']['numberOfToplevelHits'] / $this->conf['limit']));
// Return empty pagebrowser if there is just one page.
if ($maxPages < 2) {
return '';
}
// Get separator.
$separator = $this->pi_getLL('separator', ' - ', TRUE);
// Add link to previous page.
if ($this->piVars['pointer'] > 0) {
$output = $this->pi_linkTP_keepPIvars($this->pi_getLL('prevPage', '&lt;', TRUE), ['pointer' => $this->piVars['pointer'] - 1], TRUE).$separator;
} else {
$output = $this->pi_getLL('prevPage', '&lt;', TRUE).$separator;
}
$i = 0;
$skip = NULL;
// Add links to pages.
while ($i < $maxPages) {
if ($i < 3 || ($i > $this->piVars['pointer'] - 3 && $i < $this->piVars['pointer'] + 3) || $i > $maxPages - 4) {
if ($this->piVars['pointer'] != $i) {
$output .= $this->pi_linkTP_keepPIvars(sprintf($this->pi_getLL('page', '%d', TRUE), $i + 1), ['pointer' => $i], TRUE).$separator;
} else {
$output .= sprintf($this->pi_getLL('page', '%d', TRUE), $i + 1).$separator;
}
$skip = TRUE;
} elseif ($skip === TRUE) {
$output .= $this->pi_getLL('skip', '...', TRUE).$separator;
$skip = FALSE;
}
$i++;
}
// Add link to next page.
if ($this->piVars['pointer'] < $maxPages - 1) {
$output .= $this->pi_linkTP_keepPIvars($this->pi_getLL('nextPage', '&gt;', TRUE), ['pointer' => $this->piVars['pointer'] + 1], TRUE);
} else {
$output .= $this->pi_getLL('nextPage', '&gt;', TRUE);
}
return $output;
}
/**
@ -154,161 +120,90 @@ class ListView extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The rendered entry ready for output
*/
protected function getEntry($number, $template) {
$markerArray['###NUMBER###'] = $number + 1;
$markerArray['###METADATA###'] = '';
$markerArray['###THUMBNAIL###'] = '';
$markerArray['###PREVIEW###'] = '';
$subpart = '';
$imgAlt = '';
$noTitle = $this->pi_getLL('noTitle');
$metadata = $this->list[$number]['metadata'];
foreach ($this->metadata as $index_name => $metaConf) {
$parsedValue = '';
$fieldwrap = $this->getFieldWrap($index_name, $metaConf['wrap']);
do {
$value = @array_shift($metadata[$index_name]);
// Link title to pageview.
if ($index_name == 'title') {
// Get title of parent document if needed.
if (empty($value) && $this->conf['getTitle']) {
$superiorTitle = Document::getTitle($this->list[$number]['uid'], TRUE);
if (!empty($superiorTitle)) {
$value = '['.$superiorTitle.']';
}
}
// Set fake title if still not present.
if (empty($value)) {
$value = $noTitle;
}
$imgAlt = htmlspecialchars($value);
$additionalParams = [
'id' => $this->list[$number]['uid'],
'page' => $this->list[$number]['page']
];
if (!empty($this->piVars['logicalPage'])) {
$additionalParams['logicalPage'] = $this->piVars['logicalPage'];
}
$conf = [
'useCacheHash' => 1,
'parameter' => $this->conf['targetPid'],
'additionalParams' => \TYPO3\CMS\Core\Utility\GeneralUtility::implodeArrayForUrl($this->prefixId, $additionalParams, '', TRUE, FALSE)
];
$value = $this->cObj->typoLink(htmlspecialchars($value), $conf);
// Translate name of holding library.
} elseif ($index_name == 'owner' && !empty($value)) {
} elseif ($index_name == 'owner' && !empty($value)) { // Translate name of holding library.
$value = htmlspecialchars(Helper::translate($value, 'tx_dlf_libraries', $this->conf['pages']));
// Translate document type.
} elseif ($index_name == 'type' && !empty($value)) {
} elseif ($index_name == 'type' && !empty($value)) { // Translate document type.
$value = htmlspecialchars(Helper::translate($value, 'tx_dlf_structures', $this->conf['pages']));
// Translate ISO 639 language code.
} elseif ($index_name == 'language' && !empty($value)) {
} elseif ($index_name == 'language' && !empty($value)) { // Translate ISO 639 language code.
$value = htmlspecialchars(Helper::getLanguageName($value));
} elseif (!empty($value)) {
$value = htmlspecialchars($value);
}
$value = $this->cObj->stdWrap($value, $fieldwrap['value.']);
if (!empty($value)) {
$parsedValue .= $value;
}
} while (count($metadata[$index_name]));
if (!empty($parsedValue)) {
$field = $this->cObj->stdWrap(htmlspecialchars($metaConf['label']), $fieldwrap['key.']);
$field .= $parsedValue;
$markerArray['###METADATA###'] .= $this->cObj->stdWrap($field, $fieldwrap['all.']);
}
}
// Add thumbnail.
if (!empty($this->list[$number]['thumbnail'])) {
$markerArray['###THUMBNAIL###'] = '<img alt="'.$imgAlt.'" src="'.$this->list[$number]['thumbnail'].'" />';
}
// Add preview.
if (!empty($this->list[$number]['preview'])) {
$markerArray['###PREVIEW###'] = $this->list[$number]['preview'];
}
if (!empty($this->list[$number]['subparts'])) {
$subpart = $this->getSubEntries($number, $template);
}
// basket button
// Basket button.
$markerArray['###BASKETBUTTON###'] = '';
if (!empty($this->conf['basketButton']) && !empty($this->conf['targetBasket'])) {
$additionalParams = ['id' => $this->list[$number]['uid'], 'startpage' => $this->list[$number]['page'], 'addToBasket' => 'list'];
$conf = [
'useCacheHash' => 1,
'parameter' => $this->conf['targetBasket'],
'additionalParams' => \TYPO3\CMS\Core\Utility\GeneralUtility::implodeArrayForUrl($this->prefixId, $additionalParams, '', TRUE, FALSE)
];
$link = $this->cObj->typoLink($this->pi_getLL('addBasket', '', TRUE), $conf);
$markerArray['###BASKETBUTTON###'] = $link;
}
return $this->cObj->substituteMarkerArray($this->cObj->substituteSubpart($template['entry'], '###SUBTEMPLATE###', $subpart, TRUE), $markerArray);
}
/**
@ -322,17 +217,11 @@ class ListView extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return array The parsed fieldwrap
*/
private function getFieldWrap($index_name, $wrap) {
if (isset($this->fieldwrap[$index_name])) {
return $this->fieldwrap[$index_name];
} else {
return $this->fieldwrap[$index_name] = $this->parseTS($wrap);
}
}
/**
@ -343,74 +232,44 @@ class ListView extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The rendered sorting dialog ready for output
*/
protected function getSortingForm() {
// Return nothing if there are no sortable metadata fields.
if (!count($this->sortables)) {
return '';
}
// Set class prefix.
$prefix = str_replace('_', '-', get_class($this));
// Configure @action URL for form.
$linkConf = [
'parameter' => $GLOBALS['TSFE']->id
];
if (!empty($this->piVars['logicalPage'])) {
$linkConf['additionalParams'] = \TYPO3\CMS\Core\Utility\GeneralUtility::implodeArrayForUrl($this->prefixId, ['logicalPage' => $this->piVars['logicalPage']], '', TRUE, FALSE);
}
// Build HTML form.
$sorting = '<form action="'.$this->cObj->typoLink_URL($linkConf).'" method="get"><div><input type="hidden" name="id" value="'.$GLOBALS['TSFE']->id.'" />';
foreach ($this->piVars as $piVar => $value) {
if ($piVar != 'order' && $piVar != 'DATA' && !empty($value)) {
$sorting .= '<input type="hidden" name="'.$this->prefixId.'['.$piVar.']" value="'.$value.'" />';
}
}
// Select sort field.
$uniqId = uniqid($prefix.'-');
$sorting .= '<label for="'.$uniqId.'">'.$this->pi_getLL('orderBy', '', TRUE).'</label><select id="'.$uniqId.'" name="'.$this->prefixId.'[order]" onchange="javascript:this.form.submit();">';
// Add relevance sorting if this is a search result list.
if ($this->list->metadata['options']['source'] == 'search') {
$sorting .= '<option value="score"'.(($this->list->metadata['options']['order'] == 'score') ? ' selected="selected"' : '').'>'.$this->pi_getLL('relevance', '', TRUE).'</option>';
}
foreach ($this->sortables as $index_name => $label) {
$sorting .= '<option value="'.$index_name.'"'.(($this->list->metadata['options']['order'] == $index_name) ? ' selected="selected"' : '').'>'.htmlspecialchars($label).'</option>';
}
$sorting .= '</select>';
// Select sort direction.
$uniqId = uniqid($prefix.'-');
$sorting .= '<label for="'.$uniqId.'">'.$this->pi_getLL('direction', '', TRUE).'</label><select id="'.$uniqId.'" name="'.$this->prefixId.'[asc]" onchange="javascript:this.form.submit();">';
$sorting .= '<option value="1" '.($this->list->metadata['options']['order.asc'] ? ' selected="selected"' : '').'>'.$this->pi_getLL('direction.asc', '', TRUE).'</option>';
$sorting .= '<option value="0" '.(!$this->list->metadata['options']['order.asc'] ? ' selected="selected"' : '').'>'.$this->pi_getLL('direction.desc', '', TRUE).'</option>';
$sorting .= '</select></div></form>';
return $sorting;
}
/**
@ -424,170 +283,96 @@ class ListView extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The rendered entries ready for output
*/
protected function getSubEntries($number, $template) {
$content = '';
$noTitle = $this->pi_getLL('noTitle');
$highlight_word = preg_replace('/\s\s+/', ';', $this->list->metadata['searchString']);
foreach ($this->list[$number]['subparts'] as $subpart) {
$markerArray['###SUBMETADATA###'] = '';
$markerArray['###SUBTHUMBNAIL###'] = '';
$markerArray['###SUBPREVIEW###'] = '';
$imgAlt = '';
foreach ($this->metadata as $index_name => $metaConf) {
$parsedValue = '';
$fieldwrap = $this->getFieldWrap($index_name, $metaConf['wrap']);
do {
$value = @array_shift($subpart['metadata'][$index_name]);
// Link title to pageview.
if ($index_name == 'title') {
// Get title of parent document if needed.
if (empty($value) && $this->conf['getTitle']) {
$superiorTitle = Document::getTitle($subpart['uid'], TRUE);
if (!empty($superiorTitle)) {
$value = '['.$superiorTitle.']';
}
}
// Set fake title if still not present.
if (empty($value)) {
$value = $noTitle;
}
$imgAlt = htmlspecialchars($value);
$additionalParams = [
'id' => $subpart['uid'],
'page' => $subpart['page'],
'highlight_word' => $highlight_word
];
if (!empty($this->piVars['logicalPage'])) {
$additionalParams['logicalPage'] = $this->piVars['logicalPage'];
}
$conf = [
// we don't want cHash in case of search parameters
'useCacheHash' => empty($this->list->metadata['searchString']) ? 1 : 0,
'parameter' => $this->conf['targetPid'],
'additionalParams' => \TYPO3\CMS\Core\Utility\GeneralUtility::implodeArrayForUrl($this->prefixId, $additionalParams, '', TRUE, FALSE)
];
$value = $this->cObj->typoLink(htmlspecialchars($value), $conf);
// Translate name of holding library.
} elseif ($index_name == 'owner' && !empty($value)) {
} elseif ($index_name == 'owner' && !empty($value)) { // Translate name of holding library.
$value = htmlspecialchars(Helper::translate($value, 'tx_dlf_libraries', $this->conf['pages']));
// Translate document type.
} elseif ($index_name == 'type' && !empty($value)) {
} elseif ($index_name == 'type' && !empty($value)) { // Translate document type.
$_value = $value;
$value = htmlspecialchars(Helper::translate($value, 'tx_dlf_structures', $this->conf['pages']));
// Add page number for single pages.
if ($_value == 'page') {
$value .= ' '.intval($subpart['page']);
}
// Translate ISO 639 language code.
} elseif ($index_name == 'language' && !empty($value)) {
} elseif ($index_name == 'language' && !empty($value)) { // Translate ISO 639 language code.
$value = htmlspecialchars(Helper::getLanguageName($value));
} elseif (!empty($value)) {
$value = htmlspecialchars($value);
}
$value = $this->cObj->stdWrap($value, $fieldwrap['value.']);
if (!empty($value)) {
$parsedValue .= $value;
}
} while (count($subpart['metadata'][$index_name]));
if (!empty($parsedValue)) {
$field = $this->cObj->stdWrap(htmlspecialchars($metaConf['label']), $fieldwrap['key.']);
$field .= $parsedValue;
$markerArray['###SUBMETADATA###'] .= $this->cObj->stdWrap($field, $fieldwrap['all.']);
}
}
// Add thumbnail.
if (!empty($subpart['thumbnail'])) {
$markerArray['###SUBTHUMBNAIL###'] = '<img alt="'.$imgAlt.'" src="'.$subpart['thumbnail'].'" />';
}
// Add preview.
if (!empty($subpart['preview'])) {
$markerArray['###SUBPREVIEW###'] = $subpart['preview'];
}
// basket button
// Basket button
$markerArray['###SUBBASKETBUTTON###'] = '';
if (!empty($this->conf['basketButton']) && !empty($this->conf['targetBasket'])) {
$additionalParams = ['id' => $this->list[$number]['uid'], 'startpage' => $subpart['page'], 'endpage' => $subpart['page'], 'logId' => $subpart['sid'], 'addToBasket' => 'subentry'];
$conf = [
'useCacheHash' => 1,
'parameter' => $this->conf['targetBasket'],
'additionalParams' => \TYPO3\CMS\Core\Utility\GeneralUtility::implodeArrayForUrl($this->prefixId, $additionalParams, '', TRUE, FALSE)
];
$link = $this->cObj->typoLink($this->pi_getLL('addBasket', '', TRUE), $conf);
$markerArray['###SUBBASKETBUTTON###'] = $link;
}
$content .= $this->cObj->substituteMarkerArray($template['subentry'], $markerArray);
}
return $this->cObj->substituteSubpart($this->cObj->getSubpart($this->template, '###SUBTEMPLATE###'), '###SUBENTRY###', $content, TRUE);
}
/**
@ -598,35 +383,27 @@ class ListView extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return void
*/
protected function loadConfig() {
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'tx_dlf_metadata.index_name AS index_name,tx_dlf_metadata.wrap AS wrap,tx_dlf_metadata.is_listed AS is_listed,tx_dlf_metadata.is_sortable AS is_sortable',
'tx_dlf_metadata',
'(tx_dlf_metadata.is_listed=1 OR tx_dlf_metadata.is_sortable=1) AND tx_dlf_metadata.pid='.intval($this->conf['pages']).Helper::whereClause('tx_dlf_metadata'),
'(tx_dlf_metadata.is_listed=1 OR tx_dlf_metadata.is_sortable=1)'
.' AND tx_dlf_metadata.pid='.intval($this->conf['pages'])
.Helper::whereClause('tx_dlf_metadata'),
'',
'tx_dlf_metadata.sorting ASC',
''
);
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
if ($resArray['is_listed']) {
$this->metadata[$resArray['index_name']] = [
'wrap' => $resArray['wrap'],
'label' => Helper::translate($resArray['index_name'], 'tx_dlf_metadata', $this->conf['pages'])
];
}
if ($resArray['is_sortable']) {
$this->sortables[$resArray['index_name']] = Helper::translate($resArray['index_name'], 'tx_dlf_metadata', $this->conf['pages']);
}
}
}
/**
@ -640,174 +417,105 @@ class ListView extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The content that is displayed on the website
*/
public function main($content, $conf) {
$this->init($conf);
// Don't cache the output.
$this->setCache(FALSE);
// Load the list.
$this->list = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(DocumentList::class);
$currentEntry = $this->piVars['pointer'] * $this->conf['limit'];
$lastEntry = ($this->piVars['pointer'] + 1) * $this->conf['limit'];
// Check if it's a list of database records or Solr documents.
if ((!empty($this->list->metadata['options']['source']) && $this->list->metadata['options']['source'] == 'collection')
if (!empty($this->list->metadata['options']['source'])
&& $this->list->metadata['options']['source'] == 'collection'
&& ((!empty($this->piVars['order']) && $this->piVars['order'] != $this->list->metadata['options']['order'])
|| (isset($this->piVars['asc']) && $this->piVars['asc'] != $this->list->metadata['options']['order.asc']))) {
// Order list by given field.
$this->list->sort($this->piVars['order'], (boolean) $this->piVars['asc']);
// Update list's metadata.
$listMetadata = $this->list->metadata;
$listMetadata['options']['order'] = $this->piVars['order'];
$listMetadata['options']['order.asc'] = (boolean) $this->piVars['asc'];
$this->list->metadata = $listMetadata;
// Save updated list.
$this->list->save();
// Reset pointer.
$this->piVars['pointer'] = 0;
} elseif (!empty($this->list->metadata['options']['source']) && $this->list->metadata['options']['source'] == 'search') {
// Update list's metadata
$listMetadata = $this->list->metadata;
// Sort the list if applicable.
if ((!empty($this->piVars['order']) && $this->piVars['order'] != $listMetadata['options']['order'])
|| (isset($this->piVars['asc']) && $this->piVars['asc'] != $listMetadata['options']['order.asc'])) {
// Update list's metadata.
$listMetadata['options']['params']['sort'] = [$this->piVars['order']."_sorting" => (boolean) $this->piVars['asc']?'asc':'desc'];
$listMetadata['options']['order'] = $this->piVars['order'];
$listMetadata['options']['order.asc'] = (boolean) $this->piVars['asc'];
// Reset pointer.
$this->piVars['pointer'] = 0;
}
// Set some query parameters
$listMetadata['options']['params']['start'] = $currentEntry;
$listMetadata['options']['params']['rows'] = $this->conf['limit'];
// Search only if the query params have changed.
if ($listMetadata['options']['params'] != $this->list->metadata['options']['params']) {
// Instantiate search object.
$solr = Solr::getInstance($this->list->metadata['options']['core']);
if (!$solr->ready) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Plugins\ListView->main('.$content.', [data])] Apache Solr not available', $this->extKey, SYSLOG_SEVERITY_ERROR, $conf);
}
return $content;
}
// Set search parameters.
$solr->cPid = $listMetadata['options']['pid'];
$solr->params = $listMetadata['options']['params'];
// Perform search.
$this->list = $solr->search();
}
// Add list description
$listMetadata['description'] = '<p class="tx-dlf-search-numHits">'.htmlspecialchars(sprintf($this->pi_getLL('hits', ''), $this->list->metadata['options']['numberOfHits'], $this->list->metadata['options']['numberOfToplevelHits'])).'</p>';
$this->list->metadata = $listMetadata;
// Save updated list.
$this->list->save();
$currentEntry = 0;
$lastEntry = $this->conf['limit'];
}
// Load template file.
$this->getTemplate();
$subpartArray['entry'] = $this->cObj->getSubpart($this->template, '###ENTRY###');
$subpartArray['subentry'] = $this->cObj->getSubpart($this->template, '###SUBENTRY###');
// Set some variable defaults.
if (!empty($this->piVars['pointer']) && (($this->piVars['pointer'] * $this->conf['limit']) + 1) <= $this->list->metadata['options']['numberOfToplevelHits']) {
$this->piVars['pointer'] = max(intval($this->piVars['pointer']), 0);
} else {
$this->piVars['pointer'] = 0;
}
// Load metadata configuration.
$this->loadConfig();
for ($currentEntry, $lastEntry; $currentEntry < $lastEntry; $currentEntry++) {
if (empty($this->list[$currentEntry])) {
break;
} else {
$content .= $this->getEntry($currentEntry, $subpartArray);
}
}
$markerArray['###LISTTITLE###'] = $this->list->metadata['label'];
$markerArray['###LISTDESCRIPTION###'] = $this->list->metadata['description'];
if (!empty($this->list->metadata['thumbnail'])) {
$markerArray['###LISTTHUMBNAIL###'] = '<img alt="" src="'.$this->list->metadata['thumbnail'].'" />';
} else {
$markerArray['###LISTTHUMBNAIL###'] = '';
}
if ($currentEntry) {
$currentEntry = ($this->piVars['pointer'] * $this->conf['limit']) + 1;
$lastEntry = ($this->piVars['pointer'] * $this->conf['limit']) + $this->conf['limit'];
$markerArray['###COUNT###'] = htmlspecialchars(sprintf($this->pi_getLL('count'), $currentEntry, $lastEntry < $this->list->metadata['options']['numberOfToplevelHits'] ? $lastEntry : $this->list->metadata['options']['numberOfToplevelHits'], $this->list->metadata['options']['numberOfToplevelHits']));
} else {
$markerArray['###COUNT###'] = $this->pi_getLL('nohits', '', TRUE);
}
$markerArray['###PAGEBROWSER###'] = $this->getPageBrowser();
$markerArray['###SORTING###'] = $this->getSortingForm();
$content = $this->cObj->substituteMarkerArray($this->cObj->substituteSubpart($this->template, '###ENTRY###', $content, TRUE), $markerArray);
return $this->pi_wrapInBaseClass($content);
}
}

View File

@ -15,7 +15,7 @@ use Kitodo\Dlf\Common\Document;
use Kitodo\Dlf\Common\Helper;
/**
* Plugin 'Metadata' for the 'dlf' extension.
* Plugin 'Metadata' for the 'dlf' extension
*
* @author Sebastian Meyer <sebastian.meyer@slub-dresden.de>
* @author Siegfried Schweizer <siegfried.schweizer@sbb.spk-berlin.de>
@ -24,7 +24,6 @@ use Kitodo\Dlf\Common\Helper;
* @access public
*/
class Metadata extends \Kitodo\Dlf\Common\AbstractPlugin {
public $scriptRelPath = 'Classes/Plugins/Metadata.php';
/**
@ -46,144 +45,79 @@ class Metadata extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The content that is displayed on the website
*/
public function main($content, $conf) {
$this->init($conf);
// Turn cache on.
$this->setCache(TRUE);
// Load current document.
$this->loadDocument();
if ($this->doc === NULL) {
// Quit without doing anything if required variables are not set.
return $content;
} else {
// Set default values if not set.
if (!isset($this->conf['rootline'])) {
$this->conf['rootline'] = 0;
}
}
$metadata = [];
if ($this->conf['rootline'] < 2) {
// Get current structure's @ID.
$ids = [];
if (!empty($this->doc->physicalStructure[$this->piVars['page']]) && !empty($this->doc->smLinks['p2l'][$this->doc->physicalStructure[$this->piVars['page']]])) {
foreach ($this->doc->smLinks['p2l'][$this->doc->physicalStructure[$this->piVars['page']]] as $logId) {
$count = count($this->doc->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@ID="'.$logId.'"]/ancestor::*'));
$ids[$count][] = $logId;
}
}
ksort($ids);
reset($ids);
// Check if we should display all metadata up to the root.
if ($this->conf['rootline'] == 1) {
foreach ($ids as $id) {
foreach ($id as $sid) {
$data = $this->doc->getMetadata($sid, $this->conf['pages']);
if (!empty($data)) {
$data['_id'] = $sid;
$metadata[] = $data;
}
}
}
} else {
$id = array_pop($ids);
if (is_array($id)) {
foreach ($id as $sid) {
$data = $this->doc->getMetadata($sid, $this->conf['pages']);
if (!empty($data)) {
$data['_id'] = $sid;
$metadata[] = $data;
}
}
}
}
}
// Get titledata?
if (empty($metadata) || ($this->conf['rootline'] == 1 && $metadata[0]['_id'] != $this->doc->toplevelId)) {
$data = $this->doc->getTitleData($this->conf['pages']);
$data['_id'] = $this->doc->toplevelId;
array_unshift($metadata, $data);
}
if (empty($metadata)) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Plugins\Metadata->main('.$content.', [data])] No metadata found for document with UID "'.$this->doc->uid.'"', $this->extKey, SYSLOG_SEVERITY_WARNING, $conf);
}
return $content;
}
ksort($metadata);
// Get hook objects.
$this->hookObjects = Helper::getHookObjects($this->scriptRelPath);
// Hook for getting a customized title bar (requested by SBB).
foreach ($this->hookObjects as $hookObj) {
if (method_exists($hookObj, 'main_customizeTitleBarGetCustomTemplate')) {
$hookObj->main_customizeTitleBarGetCustomTemplate($this, $metadata);
}
}
$content .= $this->printMetadata($metadata);
return $this->pi_wrapInBaseClass($content);
}
/**
@ -196,212 +130,129 @@ class Metadata extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The metadata array ready for output
*/
protected function printMetadata(array $metadataArray) {
// Load template file.
$this->getTemplate();
$output = '';
$subpart['block'] = $this->cObj->getSubpart($this->template, '###BLOCK###');
// Get list of metadata to show.
$metaList = [];
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'tx_dlf_metadata.index_name AS index_name,tx_dlf_metadata.is_listed AS is_listed,tx_dlf_metadata.wrap AS wrap',
'tx_dlf_metadata',
'tx_dlf_metadata.pid='.intval($this->conf['pages']).Helper::whereClause('tx_dlf_metadata').' AND (sys_language_uid IN (-1,0) OR (sys_language_uid = '.$GLOBALS['TSFE']->sys_language_uid.' AND l18n_parent = 0))',
'tx_dlf_metadata.pid='.intval($this->conf['pages'])
.' AND (sys_language_uid IN (-1,0) OR (sys_language_uid = '.$GLOBALS['TSFE']->sys_language_uid.' AND l18n_parent = 0))'
.Helper::whereClause('tx_dlf_metadata'),
'',
'tx_dlf_metadata.sorting',
''
);
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
if (is_array($resArray) && $resArray['sys_language_uid'] != $GLOBALS['TSFE']->sys_language_content && $GLOBALS['TSFE']->sys_language_contentOL) {
$resArray = $GLOBALS['TSFE']->sys_page->getRecordOverlay('tx_dlf_metadata', $resArray, $GLOBALS['TSFE']->sys_language_content, $GLOBALS['TSFE']->sys_language_contentOL);
}
if ($resArray) {
// get correct language uid for translated realurl link
$link_uid = ($resArray['_LOCALIZED_UID']) ? $resArray['_LOCALIZED_UID'] : $resArray['uid'];
// do stuff with the row entry data like built HTML or prepare further usage
if ($this->conf['showFull'] || $resArray['is_listed']) {
$metaList[$resArray['index_name']] = [
'wrap' => $resArray['wrap'],
'label' => Helper::translate($resArray['index_name'], 'tx_dlf_metadata', $this->conf['pages'])
];
}
}
}
// Get list of collections to show.
$collList = [];
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'tx_dlf_collections.index_name AS index_name',
'tx_dlf_collections',
'tx_dlf_collections.pid='.intval($this->conf['pages']).Helper::whereClause('tx_dlf_collections'),
'tx_dlf_collections.pid='.intval($this->conf['pages'])
.Helper::whereClause('tx_dlf_collections'),
'',
'',
''
);
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
$collList[] = $resArray['index_name'];
}
// Save original data array.
$cObjData = $this->cObj->data;
// Parse the metadata arrays.
foreach ($metadataArray as $metadata) {
$markerArray['###METADATA###'] = '';
// Reset content object's data array.
$this->cObj->data = $cObjData;
// Load all the metadata values into the content object's data array.
foreach ($metadata as $index_name => $value) {
if (is_array($value)) {
$this->cObj->data[$index_name] = implode($this->conf['separator'], $value);
} else {
$this->cObj->data[$index_name] = $value;
}
}
// Process each metadate.
foreach ($metaList as $index_name => $metaConf) {
$parsedValue = '';
$fieldwrap = $this->parseTS($metaConf['wrap']);
do {
$value = @array_shift($metadata[$index_name]);
if ($index_name == 'title') {
// Get title of parent document if needed.
if (empty($value) && $this->conf['getTitle'] && $this->doc->parentId) {
$superiorTitle = Document::getTitle($this->doc->parentId, TRUE);
if (!empty($superiorTitle)) {
$value = '['.$superiorTitle.']';
}
}
if (!empty($value)) {
$value = htmlspecialchars($value);
// Link title to pageview.
if ($this->conf['linkTitle'] && $metadata['_id']) {
$details = $this->doc->getLogicalStructure($metadata['_id']);
$value = $this->pi_linkTP($value, [$this->prefixId => ['id' => $this->doc->uid, 'page' => (!empty($details['points']) ? intval($details['points']) : 1)]], TRUE, $this->conf['targetPid']);
}
}
} elseif ($index_name == 'owner' && !empty($value)) {
// Translate name of holding library.
$value = htmlspecialchars(Helper::translate($value, 'tx_dlf_libraries', $this->conf['pages']));
} elseif ($index_name == 'type' && !empty($value)) {
// Translate document type.
$value = htmlspecialchars(Helper::translate($value, 'tx_dlf_structures', $this->conf['pages']));
} elseif ($index_name == 'collection' && !empty($value)) {
// Check if collections isn't hidden.
if (in_array($value, $collList)) {
// Translate collection.
$value = htmlspecialchars(Helper::translate($value, 'tx_dlf_collections', $this->conf['pages']));
} else {
$value = '';
}
} elseif ($index_name == 'language' && !empty($value)) {
// Translate ISO 639 language code.
$value = htmlspecialchars(Helper::getLanguageName($value));
} elseif (!empty($value)) {
// Sanitize value for output.
$value = htmlspecialchars($value);
}
// Hook for getting a customized value (requested by SBB).
foreach ($this->hookObjects as $hookObj) {
if (method_exists($hookObj, 'printMetadata_customizeMetadata')) {
$hookObj->printMetadata_customizeMetadata($value);
}
}
$value = $this->cObj->stdWrap($value, $fieldwrap['value.']);
if (!empty($value)) {
$parsedValue .= $value;
}
} while (count($metadata[$index_name]));
if (!empty($parsedValue)) {
$field = $this->cObj->stdWrap(htmlspecialchars($metaConf['label']), $fieldwrap['key.']);
$field .= $parsedValue;
$markerArray['###METADATA###'] .= $this->cObj->stdWrap($field, $fieldwrap['all.']);
}
}
$output .= $this->cObj->substituteMarkerArray($subpart['block'], $markerArray);
}
return $this->cObj->substituteSubpart($this->template, '###BLOCK###', $output, TRUE);
}
}

View File

@ -15,7 +15,7 @@ use Kitodo\Dlf\Common\DocumentList;
use Kitodo\Dlf\Common\Helper;
/**
* Plugin 'Navigation' for the 'dlf' extension.
* Plugin 'Navigation' for the 'dlf' extension
*
* @author Sebastian Meyer <sebastian.meyer@slub-dresden.de>
* @package TYPO3
@ -23,7 +23,6 @@ use Kitodo\Dlf\Common\Helper;
* @access public
*/
class Navigation extends \Kitodo\Dlf\Common\AbstractPlugin {
public $scriptRelPath = 'Classes/Plugins/Navigation.php';
/**
@ -34,29 +33,20 @@ class Navigation extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string Link to the list view ready to output
*/
protected function getLinkToListview() {
if (!empty($this->conf['targetPid'])) {
// Load the list.
$list = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(DocumentList::class);
if (count($list) > 0) {
// Build typolink configuration array.
$conf = [
'useCacheHash' => 1,
'parameter' => $this->conf['targetPid'],
'title' => $this->pi_getLL('linkToList', '', TRUE)
];
return $this->cObj->typoLink($this->pi_getLL('linkToList', '', TRUE), $conf);
}
}
return '';
}
/**
@ -67,40 +57,25 @@ class Navigation extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string Page selector ready to output
*/
protected function getPageSelector() {
// Configure @action URL for form.
$linkConf = [
'parameter' => $GLOBALS['TSFE']->id
];
$output = '<form action="'.$this->cObj->typoLink_URL($linkConf).'" method="get"><div><input type="hidden" name="id" value="'.$GLOBALS['TSFE']->id.'" />';
// Add plugin variables.
foreach ($this->piVars as $piVar => $value) {
if ($piVar != 'page' && $piVar != 'DATA' && !empty($value)) {
$output .= '<input type="hidden" name="'.$this->prefixId.'['.$piVar.']" value="'.$value.'" />';
}
}
// Add page selector.
$uniqId = uniqid(str_replace('_', '-', get_class($this)).'-');
$output .= '<label for="'.$uniqId.'">'.$this->pi_getLL('selectPage', '', TRUE).'</label><select id="'.$uniqId.'" name="'.$this->prefixId.'[page]" onchange="javascript:this.form.submit();"'.($this->doc->numPages < 1 ? ' disabled="disabled"' : '').'>';
for ($i = 1; $i <= $this->doc->numPages; $i++) {
$output .= '<option value="'.$i.'"'.($this->piVars['page'] == $i ? ' selected="selected"' : '').'>['.$i.']'.($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$i]]['orderlabel'] ? ' - '.htmlspecialchars($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$i]]['orderlabel']) : '').'</option>';
}
$output .= '</select></div></form>';
return $output;
}
/**
@ -114,179 +89,105 @@ class Navigation extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The content that is displayed on the website
*/
public function main($content, $conf) {
$this->init($conf);
// Turn cache on.
$this->setCache(TRUE);
// Load current document.
$this->loadDocument();
if ($this->doc === NULL) {
// Quit without doing anything if required variables are not set.
return $content;
} else {
// Set default values if not set.
if ($this->doc->numPages > 0) {
if (!empty($this->piVars['logicalPage'])) {
$this->piVars['page'] = $this->doc->getPhysicalPage($this->piVars['logicalPage']);
// The logical page parameter should not appear
unset($this->piVars['logicalPage']);
}
// Set default values if not set.
// $this->piVars['page'] may be integer or string (physical structure @ID)
if ((int) $this->piVars['page'] > 0 || empty($this->piVars['page'])) {
if ((int) $this->piVars['page'] > 0
|| empty($this->piVars['page'])) {
$this->piVars['page'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange((int) $this->piVars['page'], 1, $this->doc->numPages, 1);
} else {
$this->piVars['page'] = array_search($this->piVars['page'], $this->doc->physicalStructure);
}
$this->piVars['double'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($this->piVars['double'], 0, 1, 0);
} else {
$this->piVars['page'] = 0;
$this->piVars['double'] = 0;
}
}
// Load template file.
$this->getTemplate();
// Steps for X pages backward / forward. Double page view uses double steps.
$pageSteps = $this->conf['pageStep'] * ($this->piVars['double'] + 1);
// Link to first page.
if ($this->piVars['page'] > 1) {
$markerArray['###FIRST###'] = $this->makeLink($this->pi_getLL('firstPage', '', TRUE), ['page' => 1]);
} else {
$markerArray['###FIRST###'] = '<span>'.$this->pi_getLL('firstPage', '', TRUE).'</span>';
}
// Link back X pages.
if ($this->piVars['page'] > $pageSteps) {
$markerArray['###BACK###'] = $this->makeLink(sprintf($this->pi_getLL('backXPages', '', TRUE), $pageSteps), ['page' => $this->piVars['page'] - $pageSteps]);
} else {
$markerArray['###BACK###'] = '<span>'.sprintf($this->pi_getLL('backXPages', '', TRUE), $pageSteps).'</span>';
}
// Link to previous page.
if ($this->piVars['page'] > (1 + $this->piVars['double'])) {
$markerArray['###PREVIOUS###'] = $this->makeLink($this->pi_getLL('prevPage', '', TRUE), ['page' => $this->piVars['page'] - (1 + $this->piVars['double'])]);
} else {
$markerArray['###PREVIOUS###'] = '<span>'.$this->pi_getLL('prevPage', '', TRUE).'</span>';
}
// Link to next page.
if ($this->piVars['page'] < ($this->doc->numPages - $this->piVars['double'])) {
$markerArray['###NEXT###'] = $this->makeLink($this->pi_getLL('nextPage', '', TRUE), ['page' => $this->piVars['page'] + (1 + $this->piVars['double'])]);
} else {
$markerArray['###NEXT###'] = '<span>'.$this->pi_getLL('nextPage', '', TRUE).'</span>';
}
// Link forward X pages.
if ($this->piVars['page'] <= ($this->doc->numPages - $pageSteps)) {
$markerArray['###FORWARD###'] = $this->makeLink(sprintf($this->pi_getLL('forwardXPages', '', TRUE), $pageSteps), ['page' => $this->piVars['page'] + $pageSteps]);
} else {
$markerArray['###FORWARD###'] = '<span>'.sprintf($this->pi_getLL('forwardXPages', '', TRUE), $pageSteps).'</span>';
}
// Link to last page.
if ($this->piVars['page'] < $this->doc->numPages) {
$markerArray['###LAST###'] = $this->makeLink($this->pi_getLL('lastPage', '', TRUE), ['page' => $this->doc->numPages]);
} else {
$markerArray['###LAST###'] = '<span>'.$this->pi_getLL('lastPage', '', TRUE).'</span>';
}
// Add double page switcher.
if ($this->doc->numPages > 0) {
if (!$this->piVars['double']) {
$markerArray['###DOUBLEPAGE###'] = $this->makeLink($this->pi_getLL('doublePageOn', '', TRUE), ['double' => 1], 'class="tx-dlf-navigation-doubleOn"');
} else {
$markerArray['###DOUBLEPAGE###'] = $this->makeLink($this->pi_getLL('doublePageOff', '', TRUE), ['double' => 0], 'class="tx-dlf-navigation-doubleOff"');
}
if ($this->piVars['double'] && $this->piVars['page'] < $this->doc->numPages) {
$markerArray['###DOUBLEPAGE+1###'] = $this->makeLink($this->pi_getLL('doublePage+1', '', TRUE), ['page' => $this->piVars['page'] + 1]);
} else {
$markerArray['###DOUBLEPAGE+1###'] = '<span>'.$this->pi_getLL('doublePage+1', '', TRUE).'</span>';
}
} else {
$markerArray['###DOUBLEPAGE###'] = '<span>'.$this->pi_getLL('doublePageOn', '', TRUE).'</span>';
$markerArray['###DOUBLEPAGE+1###'] = '<span>'.$this->pi_getLL('doublePage+1', '', TRUE).'</span>';
}
// Add page selector.
$markerArray['###PAGESELECT###'] = $this->getPageSelector();
// Add link to listview if applicable.
$markerArray['###LINKLISTVIEW###'] = $this->getLinkToListview();
// fill some language labels if available
// Fill some language labels if available.
$markerArray['###ZOOM_IN###'] = $this->pi_getLL('zoom-in', '', TRUE);
$markerArray['###ZOOM_OUT###'] = $this->pi_getLL('zoom-out', '', TRUE);
$markerArray['###ZOOM_FULLSCREEN###'] = $this->pi_getLL('zoom-fullscreen', '', TRUE);
$markerArray['###ROTATE_LEFT###'] = $this->pi_getLL('rotate-left', '', TRUE);
$markerArray['###ROTATE_RIGHT###'] = $this->pi_getLL('rotate-right', '', TRUE);
$markerArray['###ROTATE_RESET###'] = $this->pi_getLL('rotate-reset', '', TRUE);
$content .= $this->cObj->substituteMarkerArray($this->template, $markerArray);
return $this->pi_wrapInBaseClass($content);
}
/**
@ -296,23 +197,17 @@ class Navigation extends \Kitodo\Dlf\Common\AbstractPlugin {
*
* @param string $label: The link's text
* @param array $overrulePIvars: The new set of plugin variables
* @param string $aTagParams: Additional HTML attributes for link tag
* @paramstring $aTagParams: Additional HTML attributes for link tag
*
* @return string Typolink ready to output
*/
protected function makeLink($label, array $overrulePIvars = [], $aTagParams = '') {
// Merge plugin variables with new set of values.
if (is_array($this->piVars)) {
$piVars = $this->piVars;
unset($piVars['DATA']);
$overrulePIvars = \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($piVars, $overrulePIvars);
}
// Build typolink configuration array.
$conf = [
'useCacheHash' => 1,
@ -321,9 +216,6 @@ class Navigation extends \Kitodo\Dlf\Common\AbstractPlugin {
'additionalParams' => \TYPO3\CMS\Core\Utility\GeneralUtility::implodeArrayForUrl($this->prefixId, $overrulePIvars, '', TRUE, FALSE),
'title' => $label
];
return $this->cObj->typoLink($label, $conf);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -12,7 +12,7 @@ namespace Kitodo\Dlf\Plugins;
*/
/**
* Plugin 'Page Grid' for the 'dlf' extension.
* Plugin 'Page Grid' for the 'dlf' extension
*
* @author Henrik Lochmann <dev@mentalmotive.com>
* @author Sebastian Meyer <sebastian.meyer@slub-dresden.de>
@ -21,7 +21,6 @@ namespace Kitodo\Dlf\Plugins;
* @access public
*/
class PageGrid extends \Kitodo\Dlf\Common\AbstractPlugin {
public $scriptRelPath = 'Classes/Plugins/PageGrid.php';
/**
@ -35,61 +34,39 @@ class PageGrid extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The rendered entry ready for output
*/
protected function getEntry($number, $template) {
// Set current page if applicable.
if (!empty($this->piVars['page']) && $this->piVars['page'] == $number) {
$markerArray['###STATE###'] = 'cur';
} else {
$markerArray['###STATE###'] = 'no';
}
// Set page number.
$markerArray['###NUMBER###'] = $number;
// Set pagination.
$markerArray['###PAGINATION###'] = htmlspecialchars($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$number]]['orderlabel']);
// Get thumbnail or placeholder.
if (!empty($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$number]]['files'][$this->conf['fileGrpThumbs']])) {
$thumbnailFile = $this->doc->getFileLocation($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$number]]['files'][$this->conf['fileGrpThumbs']]);
} elseif (!empty($this->conf['placeholder'])) {
$thumbnailFile = $GLOBALS['TSFE']->tmpl->getFileName($this->conf['placeholder']);
} else {
$thumbnailFile = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey).'Resources/Public/Images/PageGridPlaceholder.jpg';
}
$thumbnail = '<img alt="'.$markerArray['###PAGINATION###'].'" src="'.$thumbnailFile.'" />';
// Get new plugin variables for typolink.
$piVars = $this->piVars;
// Unset no longer needed plugin variables.
// unset($piVars['pagegrid']) is for DFG Viewer compatibility!
unset($piVars['pointer'], $piVars['DATA'], $piVars['pagegrid']);
$piVars['page'] = $number;
$linkConf = [
'useCacheHash' => 1,
'parameter' => $this->conf['targetPid'],
'additionalParams' => \TYPO3\CMS\Core\Utility\GeneralUtility::implodeArrayForUrl($this->prefixId, $piVars, '', TRUE, FALSE),
'title' => $markerArray['###PAGINATION###']
];
$markerArray['###THUMBNAIL###'] = $this->cObj->typoLink($thumbnail, $linkConf);
return $this->cObj->substituteMarkerArray($template, $markerArray);
}
/**
@ -100,75 +77,43 @@ class PageGrid extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The rendered page browser ready for output
*/
protected function getPageBrowser() {
// Get overall number of pages.
$maxPages = intval(ceil($this->doc->numPages / $this->conf['limit']));
// Return empty pagebrowser if there is just one page.
if ($maxPages < 2) {
return '';
}
// Get separator.
$separator = $this->pi_getLL('separator', ' - ', TRUE);
// Add link to previous page.
if ($this->piVars['pointer'] > 0) {
$output = $this->pi_linkTP_keepPIvars($this->pi_getLL('prevPage', '&lt;', TRUE), ['pointer' => $this->piVars['pointer'] - 1, 'page' => (($this->piVars['pointer'] - 1) * $this->conf['limit']) + 1], TRUE).$separator;
} else {
$output = $this->pi_getLL('prevPage', '&lt;', TRUE).$separator;
}
$i = 0;
// Add links to pages.
while ($i < $maxPages) {
if ($i < 3 || ($i > $this->piVars['pointer'] - 3 && $i < $this->piVars['pointer'] + 3) || $i > $maxPages - 4) {
if ($this->piVars['pointer'] != $i) {
$output .= $this->pi_linkTP_keepPIvars(sprintf($this->pi_getLL('page', '%d', TRUE), $i + 1), ['pointer' => $i, 'page' => ($i * $this->conf['limit']) + 1], TRUE).$separator;
} else {
$output .= sprintf($this->pi_getLL('page', '%d', TRUE), $i + 1).$separator;
}
$skip = TRUE;
} elseif ($skip == TRUE) {
$output .= $this->pi_getLL('skip', '...', TRUE).$separator;
$skip = FALSE;
}
$i++;
}
// Add link to next page.
if ($this->piVars['pointer'] < $maxPages - 1) {
$output .= $this->pi_linkTP_keepPIvars($this->pi_getLL('nextPage', '&gt;', TRUE), ['pointer' => $this->piVars['pointer'] + 1, 'page' => ($this->piVars['pointer'] + 1) * $this->conf['limit'] + 1], TRUE);
} else {
$output .= $this->pi_getLL('nextPage', '&gt;', TRUE);
}
return $output;
}
/**
@ -182,103 +127,63 @@ class PageGrid extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The content that is displayed on the website
*/
public function main($content, $conf) {
$this->init($conf);
$this->loadDocument();
if ($this->doc === NULL || $this->doc->numPages < 1 || empty($this->conf['fileGrpThumbs'])) {
if ($this->doc === NULL
|| $this->doc->numPages < 1
|| empty($this->conf['fileGrpThumbs'])) {
// Quit without doing anything if required variables are not set.
return $content;
} else {
// Set default values for page if not set.
$this->piVars['pointer'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($this->piVars['pointer'], 0, $this->doc->numPages, 0);
}
// Load template file.
$this->getTemplate();
$entryTemplate = $this->cObj->getSubpart($this->template, '###ENTRY###');
if (empty($entryTemplate)) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Plugins\PageGrid->main('.$content.', [data])] No template subpart for list entry found', $this->extKey, SYSLOG_SEVERITY_WARNING, $conf);
}
// Quit without doing anything if required variables are not set.
return $content;
}
if (!empty($this->piVars['logicalPage'])) {
$this->piVars['page'] = $this->doc->getPhysicalPage($this->piVars['logicalPage']);
// The logical page parameter should not appear
unset($this->piVars['logicalPage']);
}
// Set some variable defaults.
// $this->piVars['page'] may be integer or string (physical structure @ID)
if ((int) $this->piVars['page'] > 0 || empty($this->piVars['page'])) {
if ((int) $this->piVars['page'] > 0
|| empty($this->piVars['page'])) {
$this->piVars['page'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange((int) $this->piVars['page'], 1, $this->doc->numPages, 1);
} else {
$this->piVars['page'] = array_search($this->piVars['page'], $this->doc->physicalStructure);
}
if (!empty($this->piVars['page'])) {
$this->piVars['pointer'] = intval(floor(($this->piVars['page'] - 1) / $this->conf['limit']));
}
if (!empty($this->piVars['pointer']) && (($this->piVars['pointer'] * $this->conf['limit']) + 1) <= $this->doc->numPages) {
if (!empty($this->piVars['pointer'])
&& (($this->piVars['pointer'] * $this->conf['limit']) + 1) <= $this->doc->numPages) {
$this->piVars['pointer'] = max(intval($this->piVars['pointer']), 0);
} else {
$this->piVars['pointer'] = 0;
}
// Iterate through visible page set and display thumbnails.
for ($i = $this->piVars['pointer'] * $this->conf['limit'], $j = ($this->piVars['pointer'] + 1) * $this->conf['limit']; $i < $j; $i++) {
// +1 because page counting starts at 1.
$number = $i + 1;
if ($number > $this->doc->numPages) {
break;
} else {
$content .= $this->getEntry($number, $entryTemplate);
}
}
// Render page browser.
$markerArray['###PAGEBROWSER###'] = $this->getPageBrowser();
// Merge everything with template.
$content = $this->cObj->substituteMarkerArray($this->cObj->substituteSubpart($this->template, '###ENTRY###', $content, TRUE), $markerArray);
return $this->pi_wrapInBaseClass($content);
}
}

View File

@ -12,7 +12,7 @@ namespace Kitodo\Dlf\Plugins;
*/
/**
* Plugin 'Page View' for the 'dlf' extension.
* Plugin 'Page View' for the 'dlf' extension
*
* @author Sebastian Meyer <sebastian.meyer@slub-dresden.de>
* @package TYPO3
@ -20,7 +20,6 @@ namespace Kitodo\Dlf\Plugins;
* @access public
*/
class PageView extends \Kitodo\Dlf\Common\AbstractPlugin {
public $scriptRelPath = 'Classes/Plugins/PageView.php';
/**
@ -55,33 +54,20 @@ class PageView extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string Viewer script tags ready for output
*/
protected function addViewerJS() {
$output = [];
// Add OpenLayers library.
$output[] = '<link type="text/css" rel="stylesheet" href="'.\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey).'Resources/Public/Javascript/OpenLayers/ol3.css">';
$output[] = '<script type="text/javascript" src="'.\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey).'Resources/Public/Javascript/OpenLayers/glif.min.js"></script>';
$output[] = '<script type="text/javascript" src="'.\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey).'Resources/Public/Javascript/OpenLayers/ol3-dlf.js"></script>';
// Add viewer library.
$output[] = '<script type="text/javascript" src="'.\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey).'Resources/Public/Javascript/PageView/Utility.js"></script>';
$output[] = '<script type="text/javascript" src="'.\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey).'Resources/Public/Javascript/PageView/OL3.js"></script>';
$output[] = '<script type="text/javascript" src="'.\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey).'Resources/Public/Javascript/PageView/OL3Styles.js"></script>';
$output[] = '<script type="text/javascript" src="'.\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey).'Resources/Public/Javascript/PageView/OL3Sources.js"></script>';
$output[] = '<script type="text/javascript" src="'.\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey).'Resources/Public/Javascript/PageView/AltoParser.js"></script>';
$output[] = '<script type="text/javascript" src="'.\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey).'Resources/Public/Javascript/PageView/ImageManipulationControl.js"></script>';
$output[] = '<script type="text/javascript" src="'.\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey).'Resources/Public/Javascript/PageView/FulltextControl.js"></script>';
$output[] = '<script type="text/javascript" src="'.\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey).'Resources/Public/Javascript/PageView/PageView.js"></script>';
// Add viewer configuration.
$output[] = '
<script id="tx-dlf-pageview-initViewer" type="text/javascript">
@ -97,9 +83,7 @@ class PageView extends \Kitodo\Dlf\Common\AbstractPlugin {
}
}
</script>';
return implode("\n", $output);
}
/**
@ -110,43 +94,24 @@ class PageView extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return array Marker array
*/
protected function addInteraction() {
$markerArray = [];
if ($this->piVars['id']) {
if (empty($this->piVars['page'])) {
$params['page'] = 1;
}
if ($this->conf['crop']) {
$markerArray['###EDITBUTTON###'] = '<a href="javascript: tx_dlf_viewer.activateSelection();">'.$this->pi_getLL('editMode', '', TRUE).'</a>';
$markerArray['###EDITREMOVE###'] = '<a href="javascript: tx_dlf_viewer.resetCropSelection();">'.$this->pi_getLL('editRemove', '', TRUE).'</a>';
} else {
$markerArray['###EDITBUTTON###'] = '';
$markerArray['###EDITREMOVE###'] = '';
}
if ($this->conf['magnifier']) {
$markerArray['###MAGNIFIER###'] = '<a href="javascript: tx_dlf_viewer.activateMagnifier();">'.$this->pi_getLL('magnifier', '', TRUE).'</a>';
} else {
$markerArray['###MAGNIFIER###'] = '';
}
}
return $markerArray;
}
@ -158,70 +123,44 @@ class PageView extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return array Marker array
*/
protected function addBasketForm() {
$markerArray = [];
// Add basket button
if ($this->conf['basketButton'] && $this->conf['targetBasket'] && $this->piVars['id']) {
$label = $this->pi_getLL('addBasket', '', TRUE);
$params = [
'id' => $this->piVars['id'],
'addToBasket' => TRUE
];
if (empty($this->piVars['page'])) {
$params['page'] = 1;
}
$basketConf = [
'parameter' => $this->conf['targetBasket'],
'additionalParams' => \TYPO3\CMS\Core\Utility\GeneralUtility::implodeArrayForUrl($this->prefixId, $params, '', TRUE, FALSE),
'title' => $label
];
$output = '<form id="addToBasketForm" action="'.$this->cObj->typoLink_URL($basketConf).'" method="post">';
$output .= '<input type="hidden" name="tx_dlf[startpage]" id="startpage" value="'.$this->piVars['page'].'">';
$output .= '<input type="hidden" name="tx_dlf[endpage]" id="endpage" value="'.$this->piVars['page'].'">';
$output .= '<input type="hidden" name="tx_dlf[startX]" id="startX">';
$output .= '<input type="hidden" name="tx_dlf[startY]" id="startY">';
$output .= '<input type="hidden" name="tx_dlf[endX]" id="endX">';
$output .= '<input type="hidden" name="tx_dlf[endY]" id="endY">';
$output .= '<input type="hidden" name="tx_dlf[rotation]" id="rotation">';
$output .= '<button id="submitBasketForm" onclick="this.form.submit()">'.$label.'</button>';
$output .= '</form>';
$output .= '<script>';
$output .= '
$(document).ready(function() {
$("#submitBasketForm").click(function() {
$("#addToBasketForm").submit();
});
});';
$output .= '</script>';
$markerArray['###BASKETBUTTON###'] = $output;
} else {
$markerArray['###BASKETBUTTON###'] = '';
}
return $markerArray;
}
@ -235,47 +174,30 @@ class PageView extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return array URL and MIME type of image file
*/
protected function getImage($page) {
$image = [];
// Get @USE value of METS fileGrp.
$fileGrps = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $this->conf['fileGrps']);
while ($fileGrp = @array_pop($fileGrps)) {
// Get image link.
if (!empty($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$page]]['files'][$fileGrp])) {
$image['url'] = $this->doc->getFileLocation($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$page]]['files'][$fileGrp]);
if ($this->conf['useInternalProxy']) {
// Configure @action URL for form.
$linkConf = [
'parameter' => $GLOBALS['TSFE']->id,
'additionalParams' => '&eID=tx_dlf_pageview_proxy&url='.urlencode($image['url']),
];
$image['url'] = $this->cObj->typoLink_URL($linkConf);
}
$image['mimetype'] = $this->doc->getFileMimeType($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$page]]['files'][$fileGrp]);
break;
} else {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Plugins\PageView->getImage('.$page.')] File not found in fileGrp "'.$fileGrp.'"', $this->extKey, SYSLOG_SEVERITY_WARNING);
}
}
}
return $image;
}
/**
@ -288,36 +210,23 @@ class PageView extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return array URL and MIME type of fulltext file
*/
protected function getFulltext($page) {
$fulltext = [];
// Get fulltext link.
if (!empty($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$page]]['files'][$this->conf['fileGrpFulltext']])) {
$fulltext['url'] = $this->doc->getFileLocation($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$page]]['files'][$this->conf['fileGrpFulltext']]);
// Configure @action URL for form.
$linkConf = [
'parameter' => $GLOBALS['TSFE']->id,
'additionalParams' => '&eID=tx_dlf_pageview_proxy&url='.urlencode($fulltext['url']),
];
$fulltext['url'] = $this->cObj->typoLink_URL($linkConf);
$fulltext['mimetype'] = $this->doc->getFileMimeType($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$page]]['files'][$this->conf['fileGrpFulltext']]);
} else {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Plugins\PageView->getFulltext('.$page.')] File not found in fileGrp "'.$this->conf['fileGrpFulltext'].'"', $this->extKey, SYSLOG_SEVERITY_WARNING);
}
}
return $fulltext;
}
/**
@ -331,71 +240,45 @@ class PageView extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The content that is displayed on the website
*/
public function main($content, $conf) {
$this->init($conf);
// Load current document.
$this->loadDocument();
if ($this->doc === NULL || $this->doc->numPages < 1) {
if ($this->doc === NULL
|| $this->doc->numPages < 1) {
// Quit without doing anything if required variables are not set.
return $content;
} else {
if (!empty($this->piVars['logicalPage'])) {
$this->piVars['page'] = $this->doc->getPhysicalPage($this->piVars['logicalPage']);
// The logical page parameter should not appear again
unset($this->piVars['logicalPage']);
}
// Set default values if not set.
// $this->piVars['page'] may be integer or string (physical structure @ID)
if ((int) $this->piVars['page'] > 0 || empty($this->piVars['page'])) {
$this->piVars['page'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange((int) $this->piVars['page'], 1, $this->doc->numPages, 1);
} else {
$this->piVars['page'] = array_search($this->piVars['page'], $this->doc->physicalStructure);
}
$this->piVars['double'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($this->piVars['double'], 0, 1, 0);
}
// Load template file.
$this->getTemplate();
// Get image data.
$this->images[0] = $this->getImage($this->piVars['page']);
$this->fulltexts[0] = $this->getFulltext($this->piVars['page']);
if ($this->piVars['double'] && $this->piVars['page'] < $this->doc->numPages) {
$this->images[1] = $this->getImage($this->piVars['page'] + 1);
$this->fulltexts[1] = $this->getFulltext($this->piVars['page'] + 1);
}
// Get the controls for the map.
$this->controls = explode(',', $this->conf['features']);
// Fill in the template markers.
$markerArray = [
'###VIEWER_JS###' => $this->addViewerJS()
];
$markerArray = array_merge($markerArray, $this->addInteraction(), $this->addBasketForm());
$content .= $this->cObj->substituteMarkerArray($this->template, $markerArray);
return $this->pi_wrapInBaseClass($content);
}
}

View File

@ -18,7 +18,7 @@ use Kitodo\Dlf\Common\Indexer;
use Kitodo\Dlf\Common\Solr;
/**
* Plugin 'Search' for the 'dlf' extension.
* Plugin 'Search' for the 'dlf' extension
*
* @author Sebastian Meyer <sebastian.meyer@slub-dresden.de>
* @author Henrik Lochmann <dev@mentalmotive.com>
@ -28,7 +28,6 @@ use Kitodo\Dlf\Common\Solr;
* @access public
*/
class Search extends \Kitodo\Dlf\Common\AbstractPlugin {
public $scriptRelPath = 'Classes/Plugins/Search.php';
/**
@ -39,31 +38,24 @@ class Search extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return void
*/
protected function addAutocompleteJS() {
// Check if there are any metadata to suggest.
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'tx_dlf_metadata.*',
'tx_dlf_metadata',
'tx_dlf_metadata.index_autocomplete=1 AND tx_dlf_metadata.pid='.intval($this->conf['pages']).Helper::whereClause('tx_dlf_metadata'),
'tx_dlf_metadata.index_autocomplete=1'
.' AND tx_dlf_metadata.pid='.intval($this->conf['pages'])
.Helper::whereClause('tx_dlf_metadata'),
'',
'',
'1'
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result)) {
$GLOBALS['TSFE']->additionalHeaderData[$this->prefixId.'_search_suggest'] = '<script type="text/javascript" src="'.\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey).'Resources/Public/Javascript/Search/Suggester.js"></script>';
} else {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Plugins\Search->addAutocompleteJS()] No metadata fields configured for search suggestions', $this->extKey, SYSLOG_SEVERITY_WARNING);
}
}
}
/**
@ -74,36 +66,24 @@ class Search extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string HTML input fields with current document's UID and parent ID
*/
protected function addCurrentCollection() {
// Load current collection.
$list = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(DocumentList::class);
if (!empty($list->metadata['options']['source']) && $list->metadata['options']['source'] == 'collection') {
if (!empty($list->metadata['options']['source'])
&& $list->metadata['options']['source'] == 'collection') {
// Get collection's UID.
return '<input type="hidden" name="'.$this->prefixId.'[collection]" value="'.$list->metadata['options']['select'].'" />';
} elseif (!empty($list->metadata['options']['params']['filterquery'])) {
// Get collection's UID from search metadata.
foreach ($list->metadata['options']['params']['filterquery'] as $facet) {
$facetKeyVal = explode(':', $facet['query'], 2);
if ($facetKeyVal[0] == 'collection_faceting' && !strpos($facetKeyVal[1], '" OR "')) {
if ($facetKeyVal[0] == 'collection_faceting'
&& !strpos($facetKeyVal[1], '" OR "')) {
$collectionId = Helper::getIdFromIndexName(trim($facetKeyVal[1], '(")'), 'tx_dlf_collections');
}
}
return '<input type="hidden" name="'.$this->prefixId.'[collection]" value="'.$collectionId.'" />';
}
return '';
}
/**
@ -114,43 +94,27 @@ class Search extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string HTML input fields with current document's UID and parent ID
*/
protected function addCurrentDocument() {
// Load current list object.
$list = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(DocumentList::class);
// Load current document.
if (!empty($this->piVars['id']) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->piVars['id'])) {
if (!empty($this->piVars['id'])
&& \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->piVars['id'])) {
$this->loadDocument();
// Get document's UID or parent ID.
if ($this->doc->ready) {
return '<input type="hidden" name="'.$this->prefixId.'[id]" value="'.($this->doc->parentId > 0 ? $this->doc->parentId : $this->doc->uid).'" />';
}
} elseif (!empty($list->metadata['options']['params']['filterquery'])) {
// Get document's UID from search metadata.
foreach ($list->metadata['options']['params']['filterquery'] as $facet) {
$facetKeyVal = explode(':', $facet['query']);
if ($facetKeyVal[0] == 'uid') {
$documentId = (int) substr($facetKeyVal[1], 1, strpos($facetKeyVal[1], ')'));
}
}
return '<input type="hidden" name="'.$this->prefixId.'[id]" value="'.$documentId.'" />';
}
return '';
}
/**
@ -161,28 +125,18 @@ class Search extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string HTML input fields with encrypted core name and hash
*/
protected function addEncryptedCoreName() {
// Get core name.
$name = Helper::getIndexName($this->conf['solrcore'], 'tx_dlf_solrcores');
// Encrypt core name.
if (!empty($name)) {
$name = Helper::encrypt($name);
}
// Add encrypted fields to search form.
if (is_array($name)) {
return '<input type="hidden" name="'.$this->prefixId.'[encrypted]" value="'.$name['encrypted'].'" /><input type="hidden" name="'.$this->prefixId.'[hashed]" value="'.$name['hash'].'" />';
} else {
return '';
}
}
/**
@ -193,50 +147,32 @@ class Search extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The extended search form or an empty string
*/
protected function addExtendedSearch() {
$extendedSearch = '';
// Quit without doing anything if no fields for extended search are selected.
if (empty($this->conf['extendedSlotCount']) || empty($this->conf['extendedFields'])) {
if (empty($this->conf['extendedSlotCount'])
|| empty($this->conf['extendedFields'])) {
return $extendedSearch;
}
// Get operator options.
$operatorOptions = '';
foreach (['AND', 'OR', 'NOT'] as $operator) {
$operatorOptions .= '<option class="tx-dlf-search-operator-option tx-dlf-search-operator-'.$operator.'" value="'.$operator.'">'.$this->pi_getLL($operator, '', TRUE).'</option>';
}
// Get field selector options.
$fieldSelectorOptions = '';
$searchFields = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $this->conf['extendedFields'], TRUE);
foreach ($searchFields as $searchField) {
$fieldSelectorOptions .= '<option class="tx-dlf-search-field-option tx-dlf-search-field-'.$searchField.'" value="'.$searchField.'">'.Helper::translate($searchField, 'tx_dlf_metadata', $this->conf['pages']).'</option>';
}
for ($i = 0; $i < $this->conf['extendedSlotCount']; $i++) {
$markerArray = [
'###EXT_SEARCH_OPERATOR###' => '<select class="tx-dlf-search-operator tx-dlf-search-operator-'.$i.'" name="'.$this->prefixId.'[extOperator]['.$i.']">'.$operatorOptions.'</select>',
'###EXT_SEARCH_FIELDSELECTOR###' => '<select class="tx-dlf-search-field tx-dlf-search-field-'.$i.'" name="'.$this->prefixId.'[extField]['.$i.']">'.$fieldSelectorOptions.'</select>',
'###EXT_SEARCH_FIELDQUERY###' => '<input class="tx-dlf-search-query tx-dlf-search-query-'.$i.'" type="text" name="'.$this->prefixId.'[extQuery]['.$i.']" />'
];
$extendedSearch .= $this->cObj->substituteMarkerArray($this->cObj->getSubpart($this->template, '###EXT_SEARCH_ENTRY###'), $markerArray);
}
return $extendedSearch;
}
/**
@ -247,51 +183,30 @@ class Search extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string HTML output of facets menu
*/
protected function addFacetsMenu() {
// Check for typoscript configuration to prevent fatal error.
if (empty($this->conf['facetsConf.'])) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Plugins\Search->addFacetsMenu()] Incomplete plugin configuration', $this->extKey, SYSLOG_SEVERITY_WARNING);
}
return '';
}
// Quit without doing anything if no facets are selected.
if (empty($this->conf['facets'])) {
return '';
}
// Get facets from plugin configuration.
$facets = [];
foreach (\TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $this->conf['facets'], TRUE) as $facet) {
$facets[$facet.'_faceting'] = Helper::translate($facet, 'tx_dlf_metadata', $this->conf['pages']);
}
// Render facets menu.
$TSconfig = [];
$TSconfig['special'] = 'userfunction';
$TSconfig['special.']['userFunc'] = 'Kitodo\\Dlf\\Plugins\\Search->makeFacetsMenuArray';
$TSconfig['special.']['facets'] = $facets;
$TSconfig['special.']['limit'] = max(intval($this->conf['limitFacets']), 1);
$TSconfig = \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($this->conf['facetsConf.'], $TSconfig);
return $this->cObj->HMENU($TSconfig);
}
/**
@ -299,29 +214,20 @@ class Search extends \Kitodo\Dlf\Common\AbstractPlugin {
*
* @access protected
*
* @param int $isFulltextSearch
* @param integer $isFulltextSearch: Is fulltext search activated?
*
* @return string HTML output of fulltext switch
*/
protected function addFulltextSwitch($isFulltextSearch = 0) {
$output = '';
// Check for plugin configuration.
if (!empty($this->conf['fulltext'])) {
$output .= ' <input class="tx-dlf-search-fulltext" id="tx-dlf-search-fulltext-no" type="radio" name="'.$this->prefixId.'[fulltext]" value="0" '.($isFulltextSearch == 0 ? 'checked="checked"' : '').' />';
$output .= ' <label for="tx-dlf-search-fulltext-no">'.$this->pi_getLL('label.inMetadata', '').'</label>';
$output .= ' <input class="tx-dlf-search-fulltext" id="tx-dlf-search-fulltext-yes" type="radio" name="'.$this->prefixId.'[fulltext]" value="1" '.($isFulltextSearch == 1 ? 'checked="checked"' : '').'/>';
$output .= ' <label for="tx-dlf-search-fulltext-yes">'.$this->pi_getLL('label.inFulltext', '').'</label>';
}
return $output;
}
/**
@ -332,25 +238,20 @@ class Search extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string HTML output of logical page field
*/
protected function addLogicalPage() {
$output = '';
// Check for plugin configuration.
if (!empty($this->conf['showLogicalPageField'])) {
$output .= ' <label for="tx-dlf-search-logical-page">'.$this->pi_getLL('label.logicalPage', '').': </label>';
$output .= ' <input class="tx-dlf-search-logical-page" id="tx-dlf-search-logical-page" type="text" name="'.$this->prefixId.'[logicalPage]" />';
}
return $output;
}
/**
* Creates an array for a HMENU entry of a facet value.
*
* @access protected
*
* @param string $field: The facet's index_name
* @param string $value: The facet's value
* @param integer $count: Number of hits for this facet
@ -360,55 +261,34 @@ class Search extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return array The array for the facet's menu entry
*/
protected function getFacetsMenuEntry($field, $value, $count, $search, &$state) {
$entryArray = [];
// Translate value.
if ($field == 'owner_faceting') {
// Translate name of holding library.
$entryArray['title'] = htmlspecialchars(Helper::translate($value, 'tx_dlf_libraries', $this->conf['pages']));
} elseif ($field == 'type_faceting') {
// Translate document type.
$entryArray['title'] = htmlspecialchars(Helper::translate($value, 'tx_dlf_structures', $this->conf['pages']));
} elseif ($field == 'collection_faceting') {
// Translate name of collection.
$entryArray['title'] = htmlspecialchars(Helper::translate($value, 'tx_dlf_collections', $this->conf['pages']));
} elseif ($field == 'language_faceting') {
// Translate ISO 639 language code.
$entryArray['title'] = htmlspecialchars(Helper::getLanguageName($value));
} else {
$entryArray['title'] = htmlspecialchars($value);
}
$entryArray['count'] = $count;
$entryArray['doNotLinkIt'] = 0;
// Check if facet is already selected.
$queryColumn = array_column($search['params']['filterquery'], 'query');
$index = array_search($field.':("'.Solr::escapeQuery($value).'")', $queryColumn);
if ($index !== FALSE) {
// Facet is selected, thus remove it from filter.
unset($queryColumn[$index]);
$queryColumn = array_values($queryColumn);
$entryArray['ITEM_STATE'] = 'CUR';
$state = 'ACTIFSUB';
//Reset facets
if ($this->conf['resetFacets']) {
//remove ($count) for selected facet in template
@ -417,20 +297,13 @@ class Search extends \Kitodo\Dlf\Common\AbstractPlugin {
$entryArray['_OVERRIDE_HREF'] = $this->pi_linkTP_keepPIvars_url(['query' => $search['query'], 'fq' => $queryColumn]);
$entryArray['title'] = sprintf($this->pi_getLL('resetFacet', ''), $entryArray['title']);
}
} else {
// Facet is not selected, thus add it to filter.
$queryColumn[] = $field.':("'.Solr::escapeQuery($value).'")';
$entryArray['ITEM_STATE'] = 'NO';
}
$entryArray['_OVERRIDE_HREF'] = $this->pi_linkTP_keepPIvars_url(['query' => $search['query'], 'fq' => $queryColumn]);
return $entryArray;
}
/**
@ -444,57 +317,36 @@ class Search extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The content that is displayed on the website
*/
public function main($content, $conf) {
$this->init($conf);
// Disable caching for this plugin.
$this->setCache(FALSE);
// Quit without doing anything if required variables are not set.
if (empty($this->conf['solrcore'])) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Plugins\Search->main('.$content.', [data])] Incomplete plugin configuration', $this->extKey, SYSLOG_SEVERITY_WARNING, $conf);
}
return $content;
}
if (!isset($this->piVars['query']) && empty($this->piVars['extQuery'])) {
if (!isset($this->piVars['query'])
&& empty($this->piVars['extQuery'])) {
// Extract query and filter from last search.
$list = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(DocumentList::class);
if (!empty($list->metadata['searchString'])) {
if ($list->metadata['options']['source'] == 'search') {
$search['query'] = $list->metadata['searchString'];
}
$search['params'] = $list->metadata['options']['params'];
}
// Add javascript for search suggestions if enabled and jQuery autocompletion is available.
if (!empty($this->conf['suggest'])) {
$this->addAutocompleteJS();
}
// Load template file.
$this->getTemplate();
// Configure @action URL for form.
$linkConf = [
'parameter' => $GLOBALS['TSFE']->id
];
// Fill markers.
$markerArray = [
'###ACTION_URL###' => $this->cObj->typoLink_URL($linkConf),
@ -509,179 +361,111 @@ class Search extends \Kitodo\Dlf\Common\AbstractPlugin {
'###FACETS_MENU###' => $this->addFacetsMenu(),
'###LOGICAL_PAGE###' => $this->addLogicalPage()
];
// Get additional fields for extended search.
$extendedSearch = $this->addExtendedSearch();
// Display search form.
$content .= $this->cObj->substituteSubpart($this->cObj->substituteMarkerArray($this->template, $markerArray), '###EXT_SEARCH_ENTRY###', $extendedSearch);
return $this->pi_wrapInBaseClass($content);
} else {
// Instantiate search object.
$solr = Solr::getInstance($this->conf['solrcore']);
if (!$solr->ready) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Plugins\Search->main('.$content.', [data])] Apache Solr not available', $this->extKey, SYSLOG_SEVERITY_ERROR, $conf);
}
return $content;
}
// Build label for result list.
$label = $this->pi_getLL('search', '', TRUE);
if (!empty($this->piVars['query'])) {
$label .= htmlspecialchars(sprintf($this->pi_getLL('for', ''), $this->piVars['query']));
}
// Prepare query parameters.
$params = [];
$matches = [];
// Set search query.
if ((!empty($this->conf['fulltext']) && !empty($this->piVars['fulltext'])) || preg_match('/fulltext:\((.*)\)/', $this->piVars['query'], $matches)) {
if ((!empty($this->conf['fulltext']) && !empty($this->piVars['fulltext']))
|| preg_match('/fulltext:\((.*)\)/', $this->piVars['query'], $matches)) {
// If the query already is a fulltext query e.g using the facets
$this->piVars['query'] = empty($matches[1]) ? $this->piVars['query'] : $matches[1];
// Search in fulltext field if applicable. query must not be empty!
if (!empty($this->piVars['query'])) {
$query = 'fulltext:('.Solr::escapeQuery($this->piVars['query']).')';
}
} else {
// Retain given search field if valid.
$query = Solr::escapeQueryKeepField($this->piVars['query'], $this->conf['pages']);
}
// Add extended search query.
if (!empty($this->piVars['extQuery']) && is_array($this->piVars['extQuery'])) {
if (!empty($this->piVars['extQuery'])
&& is_array($this->piVars['extQuery'])) {
$allowedOperators = ['AND', 'OR', 'NOT'];
$allowedFields = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $this->conf['extendedFields'], TRUE);
for ($i = 0; $i < count($this->piVars['extQuery']); $i++) {
if (!empty($this->piVars['extQuery'][$i])) {
if (in_array($this->piVars['extOperator'][$i], $allowedOperators) && in_array($this->piVars['extField'][$i], $allowedFields)) {
if (in_array($this->piVars['extOperator'][$i], $allowedOperators)
&& in_array($this->piVars['extField'][$i], $allowedFields)) {
if (!empty($query)) {
$query .= ' '.$this->piVars['extOperator'][$i].' ';
}
$query .= Indexer::getIndexFieldName($this->piVars['extField'][$i], $this->conf['pages']).':('.Solr::escapeQuery($this->piVars['extQuery'][$i]).')';
}
}
}
}
// Add filter query for faceting.
if (!empty($this->piVars['fq'])) {
foreach ($this->piVars['fq'] as $filterQuery) {
$params['filterquery'][]['query'] = $filterQuery;
}
}
// Add filter query for in-document searching.
if ($this->conf['searchIn'] == 'document' || $this->conf['searchIn'] == 'all') {
if (!empty($this->piVars['id']) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->piVars['id'])) {
if ($this->conf['searchIn'] == 'document'
|| $this->conf['searchIn'] == 'all') {
if (!empty($this->piVars['id'])
&& \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->piVars['id'])) {
$params['filterquery'][]['query'] = 'uid:('.$this->piVars['id'].') OR partof:('.$this->piVars['id'].')';
$label .= htmlspecialchars(sprintf($this->pi_getLL('in', ''), Document::getTitle($this->piVars['id'])));
}
}
// Add filter query for in-collection searching.
if ($this->conf['searchIn'] == 'collection' || $this->conf['searchIn'] == 'all') {
if (!empty($this->piVars['collection']) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->piVars['collection'])) {
if ($this->conf['searchIn'] == 'collection'
|| $this->conf['searchIn'] == 'all') {
if (!empty($this->piVars['collection'])
&& \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->piVars['collection'])) {
$index_name = Helper::getIndexName($this->piVars['collection'], 'tx_dlf_collections', $this->conf['pages']);
$params['filterquery'][]['query'] = 'collection_faceting:("'.Solr::escapeQuery($index_name).'")';
$label .= sprintf($this->pi_getLL('in', '', TRUE), Helper::translate($index_name, 'tx_dlf_collections', $this->conf['pages']));
}
}
// Add filter query for collection restrictions.
if ($this->conf['collections']) {
$collIds = explode(',', $this->conf['collections']);
$collIndexNames = [];
foreach ($collIds as $collId) {
$collIndexNames[] = Solr::escapeQuery(Helper::getIndexName(intval($collId), 'tx_dlf_collections', $this->conf['pages']));
}
// Last value is fake and used for distinction in $this->addCurrentCollection()
$params['filterquery'][]['query'] = 'collection_faceting:("'.implode('" OR "', $collIndexNames).'" OR "FakeValueForDistinction")';
}
// Set some query parameters.
$params['query'] = $query;
$params['start'] = 0;
$params['rows'] = 0;
$params['sort'] = ['score' => 'desc'];
// Instantiate search object.
$solr = Solr::getInstance($this->conf['solrcore']);
if (!$solr->ready) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Plugins\Search->main('.$content.', [data])] Apache Solr not available', $this->extKey, SYSLOG_SEVERITY_ERROR, $conf);
}
return $content;
}
// Set search parameters.
$solr->cPid = $this->conf['pages'];
$solr->params = $params;
// Perform search.
$list = $solr->search();
$list->metadata = [
'label' => $label,
'thumbnail' => '',
@ -689,55 +473,34 @@ class Search extends \Kitodo\Dlf\Common\AbstractPlugin {
'fulltextSearch' => (!empty($this->piVars['fulltext']) ? '1' : '0'),
'options' => $list->metadata['options']
];
$list->save();
// Clean output buffer.
\TYPO3\CMS\Core\Utility\GeneralUtility::cleanOutputBuffers();
$additionalParams = [];
if (!empty($this->piVars['logicalPage'])) {
$additionalParams['logicalPage'] = $this->piVars['logicalPage'];
}
// Jump directly to the page view, if there is only one result and it is configured
if ($list->metadata['options']['numberOfHits'] == 1 && !empty($this->conf['showSingleResult'])) {
$linkConf['parameter'] = $this->conf['targetPidPageView'];
$additionalParams['id'] = $list->current()['uid'];
$additionalParams['highlight_word'] = preg_replace('/\s\s+/', ';', $list->metadata['searchString']);
$additionalParams['page'] = count($list[0]['subparts']) == 1 ? $list[0]['subparts'][0]['page'] : 1;
} else {
// Keep some plugin variables.
$linkConf['parameter'] = $this->conf['targetPid'];
if (!empty($this->piVars['order'])) {
$additionalParams['order'] = $this->piVars['order'];
$additionalParams['asc'] = !empty($this->piVars['asc']) ? '1' : '0';
}
}
$linkConf['additionalParams'] = \TYPO3\CMS\Core\Utility\GeneralUtility::implodeArrayForUrl($this->prefixId, $additionalParams, '', TRUE, FALSE);
// Send headers.
header('Location: '.\TYPO3\CMS\Core\Utility\GeneralUtility::locationHeaderUrl($this->cObj->typoLink_URL($linkConf)));
// Flush output buffer and end script processing.
ob_end_flush();
exit;
}
}
/**
@ -751,11 +514,8 @@ class Search extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return array HMENU array
*/
public function makeFacetsMenuArray($content, $conf) {
$this->init($conf);
$menuArray = [];
// Set default value for facet search.
$search = [
'query' => '*',
@ -767,46 +527,27 @@ class Search extends \Kitodo\Dlf\Common\AbstractPlugin {
]
]
];
// Extract query and filter from last search.
$list = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(DocumentList::class);
if (!empty($list->metadata['options']['source'])) {
if ($list->metadata['options']['source'] == 'search') {
$search['query'] = $list->metadata['options']['select'];
}
$search['params'] = $list->metadata['options']['params'];
}
// Get applicable facets.
$solr = Solr::getInstance($this->conf['solrcore']);
if (!$solr->ready) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Plugins\Search->makeFacetsMenuArray('.$content.', [data])] Apache Solr not available', $this->extKey, SYSLOG_SEVERITY_ERROR, $conf);
}
return [];
}
// Set needed parameters for facet search.
if (empty($search['params']['filterquery'])) {
$search['params']['filterquery'] = [];
}
foreach ($this->conf['facets'] as $field => $name) {
$search['params']['component']['facetset']['facet'][] = [
'type' => 'field',
'key' => $field,
@ -814,73 +555,42 @@ class Search extends \Kitodo\Dlf\Common\AbstractPlugin {
'limit' => $this->conf['limitFacets'],
'sort' => isset($this->conf['sortingFacets']) ? $this->conf['sortingFacets'] : 'count'
];
}
// Set additional query parameters.
$search['params']['start'] = 0;
$search['params']['rows'] = 0;
// Set query.
$search['params']['query'] = $search['query'];
// Perform search.
$selectQuery = $solr->service->createSelect($search['params']);
$results = $solr->service->select($selectQuery);
$facet = $results->getFacetSet();
// Process results.
foreach ($facet as $field => $values) {
$entryArray = [];
$entryArray['title'] = htmlspecialchars($this->conf['facets'][$field]);
$entryArray['count'] = 0;
$entryArray['_OVERRIDE_HREF'] = '';
$entryArray['doNotLinkIt'] = 1;
$entryArray['ITEM_STATE'] = 'NO';
// Count number of facet values.
$i = 0;
foreach ($values as $value => $count) {
if ($count > 0) {
$entryArray['count']++;
if ($entryArray['ITEM_STATE'] == 'NO') {
$entryArray['ITEM_STATE'] = 'IFSUB';
}
$entryArray['_SUB_MENU'][] = $this->getFacetsMenuEntry($field, $value, $count, $search, $entryArray['ITEM_STATE']);
if (++$i == $this->conf['limit']) {
break;
}
} else {
break;
}
}
$menuArray[] = $entryArray;
}
return $menuArray;
}
}

View File

@ -14,7 +14,7 @@ namespace Kitodo\Dlf\Plugins;
use Kitodo\Dlf\Common\Helper;
/**
* Plugin 'Statistics' for the 'dlf' extension.
* Plugin 'Statistics' for the 'dlf' extension
*
* @author Sebastian Meyer <sebastian.meyer@slub-dresden.de>
* @package TYPO3
@ -22,7 +22,6 @@ use Kitodo\Dlf\Common\Helper;
* @access public
*/
class Statistics extends \Kitodo\Dlf\Common\AbstractPlugin {
public $scriptRelPath = 'Classes/Plugins/Statistics.php';
/**
@ -36,81 +35,78 @@ class Statistics extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The content that is displayed on the website
*/
public function main($content, $conf) {
$this->init($conf);
// Turn cache on.
$this->setCache(TRUE);
// Quit without doing anything if required configuration variables are not set.
if (empty($this->conf['pages'])) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Plugins\Statistics->main('.$content.', [data])] Incomplete plugin configuration', $this->extKey, SYSLOG_SEVERITY_WARNING, $conf);
}
return $content;
}
// Get description.
$content .= $this->pi_RTEcssText($this->conf['description']);
// Check for selected collections.
if ($this->conf['collections']) {
// Include only selected collections.
$resultTitles = $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query(
'tx_dlf_documents.uid AS uid',
'tx_dlf_documents',
'tx_dlf_relations',
'tx_dlf_collections',
'AND tx_dlf_documents.pid='.intval($this->conf['pages']).' AND tx_dlf_collections.pid='.intval($this->conf['pages']).' AND tx_dlf_documents.partof=0 AND tx_dlf_collections.uid IN ('.$GLOBALS['TYPO3_DB']->cleanIntList($this->conf['collections']).') AND tx_dlf_relations.ident='.$GLOBALS['TYPO3_DB']->fullQuoteStr('docs_colls', 'tx_dlf_relations').Helper::whereClause('tx_dlf_documents').Helper::whereClause('tx_dlf_collections'),
'AND tx_dlf_documents.pid='.intval($this->conf['pages'])
.' AND tx_dlf_collections.pid='.intval($this->conf['pages'])
.' AND tx_dlf_documents.partof=0'
.' AND tx_dlf_collections.uid IN ('.$GLOBALS['TYPO3_DB']->cleanIntList($this->conf['collections']).')'
.' AND tx_dlf_relations.ident='.$GLOBALS['TYPO3_DB']->fullQuoteStr('docs_colls', 'tx_dlf_relations')
.Helper::whereClause('tx_dlf_documents')
.Helper::whereClause('tx_dlf_collections'),
'tx_dlf_documents.uid',
'',
''
);
$resultVolumes = $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query(
'tx_dlf_documents.uid AS uid',
'tx_dlf_documents',
'tx_dlf_relations',
'tx_dlf_collections',
'AND tx_dlf_documents.pid='.intval($this->conf['pages']).' AND tx_dlf_collections.pid='.intval($this->conf['pages']).' AND NOT tx_dlf_documents.uid IN (SELECT DISTINCT tx_dlf_documents.partof FROM tx_dlf_documents WHERE NOT tx_dlf_documents.partof=0'.Helper::whereClause('tx_dlf_documents').') AND tx_dlf_collections.uid IN ('.$GLOBALS['TYPO3_DB']->cleanIntList($this->conf['collections']).') AND tx_dlf_relations.ident='.$GLOBALS['TYPO3_DB']->fullQuoteStr('docs_colls', 'tx_dlf_relations').Helper::whereClause('tx_dlf_documents').Helper::whereClause('tx_dlf_collections'),
'AND tx_dlf_documents.pid='.intval($this->conf['pages'])
.' AND tx_dlf_collections.pid='.intval($this->conf['pages'])
.' AND NOT tx_dlf_documents.uid IN (SELECT DISTINCT tx_dlf_documents.partof FROM tx_dlf_documents WHERE NOT tx_dlf_documents.partof=0'.Helper::whereClause('tx_dlf_documents').')'
.' AND tx_dlf_collections.uid IN ('.$GLOBALS['TYPO3_DB']->cleanIntList($this->conf['collections']).')'
.' AND tx_dlf_relations.ident='.$GLOBALS['TYPO3_DB']->fullQuoteStr('docs_colls', 'tx_dlf_relations')
.Helper::whereClause('tx_dlf_documents')
.Helper::whereClause('tx_dlf_collections'),
'tx_dlf_documents.uid',
'',
''
);
} else {
// Include all collections.
$resultTitles = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'tx_dlf_documents.uid AS uid',
'tx_dlf_documents',
'tx_dlf_documents.pid='.intval($this->conf['pages']).' AND tx_dlf_documents.partof=0'.Helper::whereClause('tx_dlf_documents'),
'tx_dlf_documents.pid='.intval($this->conf['pages'])
.' AND tx_dlf_documents.partof=0'
.Helper::whereClause('tx_dlf_documents'),
'',
'',
''
);
$resultVolumes = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'tx_dlf_documents.uid AS uid',
'tx_dlf_documents',
'tx_dlf_documents.pid='.intval($this->conf['pages']).' AND NOT tx_dlf_documents.uid IN (SELECT DISTINCT tx_dlf_documents.partof FROM tx_dlf_documents WHERE NOT tx_dlf_documents.partof=0'.Helper::whereClause('tx_dlf_documents').')'.Helper::whereClause('tx_dlf_documents'),
'tx_dlf_documents.pid='.intval($this->conf['pages'])
.' AND NOT tx_dlf_documents.uid IN (SELECT DISTINCT tx_dlf_documents.partof FROM tx_dlf_documents WHERE NOT tx_dlf_documents.partof=0'.Helper::whereClause('tx_dlf_documents').')'
.Helper::whereClause('tx_dlf_documents'),
'',
'',
''
);
}
$countTitles = $GLOBALS['TYPO3_DB']->sql_num_rows($resultTitles);
$countVolumes = $GLOBALS['TYPO3_DB']->sql_num_rows($resultVolumes);
// Set replacements.
$replace = [
'key' => [
@ -122,12 +118,8 @@ class Statistics extends \Kitodo\Dlf\Common\AbstractPlugin {
$countVolumes.($countVolumes > 1 ? $this->pi_getLL('volumes', '', TRUE) : $this->pi_getLL('volume', '', TRUE))
]
];
// Apply replacements.
$content = str_replace($replace['key'], $replace['value'], $content);
return $this->pi_wrapInBaseClass($content);
}
}

View File

@ -14,7 +14,7 @@ namespace Kitodo\Dlf\Plugins;
use Kitodo\Dlf\Common\Helper;
/**
* Plugin 'Table Of Contents' for the 'dlf' extension.
* Plugin 'Table Of Contents' for the 'dlf' extension
*
* @author Sebastian Meyer <sebastian.meyer@slub-dresden.de>
* @package TYPO3
@ -22,7 +22,6 @@ use Kitodo\Dlf\Common\Helper;
* @access public
*/
class TableOfContents extends \Kitodo\Dlf\Common\AbstractPlugin {
public $scriptRelPath = 'Classes/Plugins/TableOfContents.php';
/**
@ -44,106 +43,67 @@ class TableOfContents extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return array HMENU array for menu entry
*/
protected function getMenuEntry(array $entry, $recursive = FALSE) {
$entryArray = [];
// Set "title", "volume", "type" and "pagination" from $entry array.
$entryArray['title'] = $entry['label'];
$entryArray['volume'] = $entry['volume'];
$entryArray['orderlabel'] = $entry['orderlabel'];
$entryArray['type'] = Helper::translate($entry['type'], 'tx_dlf_structures', $this->conf['pages']);
$entryArray['pagination'] = htmlspecialchars($entry['pagination']);
$entryArray['_OVERRIDE_HREF'] = '';
$entryArray['doNotLinkIt'] = 1;
$entryArray['ITEM_STATE'] = 'NO';
// Build menu links based on the $entry['points'] array.
if (!empty($entry['points']) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($entry['points'])) {
if (!empty($entry['points'])
&& \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($entry['points'])) {
$entryArray['_OVERRIDE_HREF'] = $this->pi_linkTP_keepPIvars_url(['page' => $entry['points']], TRUE, FALSE, $this->conf['targetPid']);
$entryArray['doNotLinkIt'] = 0;
if ($this->conf['basketButton']) {
$entryArray['basketButtonHref'] = '<a href="'.$this->pi_linkTP_keepPIvars_url(['addToBasket' => 'toc', 'logId' => $entry['id'], 'startpage' => $entry['points']], TRUE, FALSE, $this->conf['targetBasket']).'">'.$this->pi_getLL('basketButton', '', TRUE).'</a>';
}
} elseif (!empty($entry['points']) && is_string($entry['points'])) {
} elseif (!empty($entry['points'])
&& is_string($entry['points'])) {
$entryArray['_OVERRIDE_HREF'] = $this->pi_linkTP_keepPIvars_url(['id' => $entry['points'], 'page' => 1], TRUE, FALSE, $this->conf['targetPid']);
$entryArray['doNotLinkIt'] = 0;
if ($this->conf['basketButton']) {
$entryArray['basketButtonHref'] = '<a href="'.$this->pi_linkTP_keepPIvars_url(['addToBasket' => 'toc', 'logId' => $entry['id'], 'startpage' => $entry['points']], TRUE, FALSE, $this->conf['targetBasket']).'">'.$this->pi_getLL('basketButton', '', TRUE).'</a>';
}
} elseif (!empty($entry['targetUid'])) {
$entryArray['_OVERRIDE_HREF'] = $this->pi_linkTP_keepPIvars_url(['id' => $entry['targetUid'], 'page' => 1], TRUE, FALSE, $this->conf['targetPid']);
$entryArray['doNotLinkIt'] = 0;
if ($this->conf['basketButton']) {
$entryArray['basketButtonHref'] = '<a href="'.$this->pi_linkTP_keepPIvars_url(['addToBasket' => 'toc', 'logId' => $entry['id'], 'startpage' => $entry['targetUid']], TRUE, FALSE, $this->conf['targetBasket']).'">'.$this->pi_getLL('basketButton', '', TRUE).'</a>';
}
}
// Set "ITEM_STATE" to "CUR" if this entry points to current page.
if (in_array($entry['id'], $this->activeEntries)) {
$entryArray['ITEM_STATE'] = 'CUR';
}
// Build sub-menu if available and called recursively.
if ($recursive == TRUE && !empty($entry['children'])) {
if ($recursive == TRUE
&& !empty($entry['children'])) {
// Build sub-menu only if one of the following conditions apply:
// 1. "expAll" is set for menu
// 2. Current menu node is in rootline
// 3. Current menu node points to another file
// 4. Current menu node has no corresponding images
if (!empty($this->conf['menuConf.']['expAll']) || $entryArray['ITEM_STATE'] == 'CUR' || is_string($entry['points']) || empty($this->doc->smLinks['l2p'][$entry['id']])) {
if (!empty($this->conf['menuConf.']['expAll'])
|| $entryArray['ITEM_STATE'] == 'CUR'
|| is_string($entry['points'])
|| empty($this->doc->smLinks['l2p'][$entry['id']])) {
$entryArray['_SUB_MENU'] = [];
foreach ($entry['children'] as $child) {
// Set "ITEM_STATE" to "ACT" if this entry points to current page and has sub-entries pointing to the same page.
if (in_array($child['id'], $this->activeEntries)) {
$entryArray['ITEM_STATE'] = 'ACT';
}
$entryArray['_SUB_MENU'][] = $this->getMenuEntry($child, TRUE);
}
}
// Append "IFSUB" to "ITEM_STATE" if this entry has sub-entries.
$entryArray['ITEM_STATE'] = ($entryArray['ITEM_STATE'] == 'NO' ? 'IFSUB' : $entryArray['ITEM_STATE'].'IFSUB');
}
return $entryArray;
}
/**
@ -157,39 +117,23 @@ class TableOfContents extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The content that is displayed on the website
*/
public function main($content, $conf) {
$this->init($conf);
// Check for typoscript configuration to prevent fatal error.
if (empty($this->conf['menuConf.'])) {
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Plugins\TableOfContents->main('.$content.', [data])] Incomplete plugin configuration', $this->extKey, SYSLOG_SEVERITY_WARNING, $conf);
}
return $content;
}
// Load template file.
$this->getTemplate();
$TSconfig = [];
$TSconfig['special'] = 'userfunction';
$TSconfig['special.']['userFunc'] = 'Kitodo\\Dlf\\Plugins\\TableOfContents->makeMenuArray';
$TSconfig = \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($this->conf['menuConf.'], $TSconfig);
$markerArray['###TOCMENU###'] = $this->cObj->HMENU($TSconfig);
$content .= $this->cObj->substituteMarkerArray($this->template, $markerArray);
return $this->pi_wrapInBaseClass($content);
}
/**
@ -203,86 +147,55 @@ class TableOfContents extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return array HMENU array
*/
public function makeMenuArray($content, $conf) {
$this->init($conf);
// Load current document.
$this->loadDocument();
if ($this->doc === NULL) {
// Quit without doing anything if required variables are not set.
return [];
} else {
if (!empty($this->piVars['logicalPage'])) {
$this->piVars['page'] = $this->doc->getPhysicalPage($this->piVars['logicalPage']);
// The logical page parameter should not appear again
unset($this->piVars['logicalPage']);
}
// Set default values for page if not set.
// $this->piVars['page'] may be integer or string (physical structure @ID)
if ((int) $this->piVars['page'] > 0 || empty($this->piVars['page'])) {
if ((int) $this->piVars['page'] > 0
|| empty($this->piVars['page'])) {
$this->piVars['page'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange((int) $this->piVars['page'], 1, $this->doc->numPages, 1);
} else {
$this->piVars['page'] = array_search($this->piVars['page'], $this->doc->physicalStructure);
}
$this->piVars['double'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($this->piVars['double'], 0, 1, 0);
}
$menuArray = [];
// Does the document have physical elements or is it an external file?
if ($this->doc->physicalStructure || !\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->doc->uid)) {
if ($this->doc->physicalStructure
|| !\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->doc->uid)) {
// Get all logical units the current page or track is a part of.
if (!empty($this->piVars['page']) && $this->doc->physicalStructure) {
if (!empty($this->piVars['page'])
&& $this->doc->physicalStructure) {
$this->activeEntries = array_merge((array) $this->doc->smLinks['p2l'][$this->doc->physicalStructure[0]], (array) $this->doc->smLinks['p2l'][$this->doc->physicalStructure[$this->piVars['page']]]);
if (!empty($this->piVars['double']) && $this->piVars['page'] < $this->doc->numPages) {
if (!empty($this->piVars['double'])
&& $this->piVars['page'] < $this->doc->numPages) {
$this->activeEntries = array_merge($this->activeEntries, (array) $this->doc->smLinks['p2l'][$this->doc->physicalStructure[$this->piVars['page'] + 1]]);
}
}
// Go through table of contents and create all menu entries.
foreach ($this->doc->tableOfContents as $entry) {
$menuArray[] = $this->getMenuEntry($entry, TRUE);
}
} else {
// Go through table of contents and create top-level menu entries.
foreach ($this->doc->tableOfContents as $entry) {
$menuArray[] = $this->getMenuEntry($entry, FALSE);
}
// Get all child documents from database.
$whereClause = 'tx_dlf_documents.partof='.intval($this->doc->uid).' AND tx_dlf_documents.structure=tx_dlf_structures.uid AND tx_dlf_structures.pid='.$this->doc->pid.Helper::whereClause('tx_dlf_documents').Helper::whereClause('tx_dlf_structures');
if ($this->conf['excludeOther']) {
$whereClause .= ' AND tx_dlf_documents.pid='.intval($this->conf['pages']);
}
// Build table of contents from database.
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'tx_dlf_documents.uid AS uid,tx_dlf_documents.title AS title,tx_dlf_documents.volume AS volume,tx_dlf_structures.index_name AS type',
@ -292,15 +205,10 @@ class TableOfContents extends \Kitodo\Dlf\Common\AbstractPlugin {
'tx_dlf_documents.volume_sorting',
''
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result)) {
$menuArray[0]['ITEM_STATE'] = 'CURIFSUB';
$menuArray[0]['_SUB_MENU'] = [];
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
$entry = [
'label' => $resArray['title'],
'type' => $resArray['type'],
@ -308,17 +216,10 @@ class TableOfContents extends \Kitodo\Dlf\Common\AbstractPlugin {
'pagination' => '',
'targetUid' => $resArray['uid']
];
$menuArray[0]['_SUB_MENU'][] = $this->getMenuEntry($entry, FALSE);
}
}
}
return $menuArray;
}
}

View File

@ -12,7 +12,7 @@ namespace Kitodo\Dlf\Plugins;
*/
/**
* Plugin 'Toolbox' for the 'dlf' extension.
* Plugin 'Toolbox' for the 'dlf' extension
*
* @author Sebastian Meyer <sebastian.meyer@slub-dresden.de>
* @package TYPO3
@ -20,7 +20,6 @@ namespace Kitodo\Dlf\Plugins;
* @access public
*/
class Toolbox extends \Kitodo\Dlf\Common\AbstractPlugin {
public $scriptRelPath = 'Classes/Plugins/Toolbox.php';
/**
@ -34,45 +33,28 @@ class Toolbox extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The content that is displayed on the website
*/
public function main($content, $conf) {
$this->init($conf);
// Quit without doing anything if required variable is not set.
if (empty($this->piVars['id'])) {
return $content;
}
// Load template file.
$this->getTemplate();
// Build data array.
$data = [
'conf' => $this->conf,
'piVars' => $this->piVars,
];
// Get template subpart for tools.
$subpart = $this->cObj->getSubpart($this->template, '###TOOLS###');
$tools = explode(',', $this->conf['tools']);
// Add the tools to the toolbox.
foreach ($tools as $tool) {
$tool = trim($tool);
$cObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::class);
$cObj->data = $data;
$content .= $this->cObj->substituteMarkerArray($subpart, ['###TOOL###' => $cObj->cObjGetSingle($GLOBALS['TSFE']->tmpl->setup['plugin.'][$tool], $GLOBALS['TSFE']->tmpl->setup['plugin.'][$tool.'.'])]);
}
return $this->pi_wrapInBaseClass($this->cObj->substituteSubpart($this->template, '###TOOLS###', $content, TRUE));
}
}

View File

@ -22,8 +22,7 @@ use Kitodo\Dlf\Common\Helper;
* @subpackage dlf
* @access public
*/
class FulltextTool extends \Kitodo\Dlf\Common\AbstractPlugin
{
class FulltextTool extends \Kitodo\Dlf\Common\AbstractPlugin {
public $scriptRelPath = 'Classes/Plugins/Tools/FulltextTool.php';
/**
@ -36,8 +35,7 @@ class FulltextTool extends \Kitodo\Dlf\Common\AbstractPlugin
*
* @return string The content that is displayed on the website
*/
public function main($content, $conf)
{
public function main($content, $conf) {
$this->init($conf);
// Merge configuration with conf array of toolbox.
$this->conf = \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($this->cObj->data['conf'], $this->conf);
@ -45,13 +43,11 @@ class FulltextTool extends \Kitodo\Dlf\Common\AbstractPlugin
$this->loadDocument();
if ($this->doc === NULL
|| $this->doc->numPages < 1
|| empty($this->conf['fileGrpFulltext']))
{
|| empty($this->conf['fileGrpFulltext'])) {
// Quit without doing anything if required variables are not set.
return $content;
} else {
if (!empty($this->piVars['logicalPage']))
{
if (!empty($this->piVars['logicalPage'])) {
$this->piVars['page'] = $this->doc->getPhysicalPage($this->piVars['logicalPage']);
// The logical page parameter should not appear again
unset($this->piVars['logicalPage']);
@ -59,8 +55,7 @@ class FulltextTool extends \Kitodo\Dlf\Common\AbstractPlugin
// Set default values if not set.
// $this->piVars['page'] may be integer or string (physical structure @ID)
if ((int) $this->piVars['page'] > 0
|| empty($this->piVars['page']))
{
|| empty($this->piVars['page'])) {
$this->piVars['page'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange((int) $this->piVars['page'], 1, $this->doc->numPages, 1);
} else {
$this->piVars['page'] = array_search($this->piVars['page'], $this->doc->physicalStructure);
@ -70,8 +65,7 @@ class FulltextTool extends \Kitodo\Dlf\Common\AbstractPlugin
// Load template file.
$this->getTemplate();
$fullTextFile = $this->doc->physicalStructureInfo[$this->doc->physicalStructure[$this->piVars['page']]]['files'][$this->conf['fileGrpFulltext']];
if (!empty($fullTextFile))
{
if (!empty($fullTextFile)) {
$markerArray['###FULLTEXT_SELECT###'] = '<a class="select switchoff" id="tx-dlf-tools-fulltext" title="" data-dic="fulltext-on:'.$this->pi_getLL('fulltext-on', '', TRUE).';fulltext-off:'.$this->pi_getLL('fulltext-off', '', TRUE).'">&nbsp;</a>';
} else {
$markerArray['###FULLTEXT_SELECT###'] = '<span class="no-fulltext">'.$this->pi_getLL('fulltext-not-available', '', TRUE).'</span>';

View File

@ -21,8 +21,7 @@ use Kitodo\Dlf\Common\Helper;
* @subpackage dlf
* @access public
*/
class ImageDownloadTool extends \Kitodo\Dlf\Common\AbstractPlugin
{
class ImageDownloadTool extends \Kitodo\Dlf\Common\AbstractPlugin {
public $scriptRelPath = 'Classes/Plugins/Tools/ImageDownloadTool.php';
/**
@ -35,8 +34,7 @@ class ImageDownloadTool extends \Kitodo\Dlf\Common\AbstractPlugin
*
* @return string The content that is displayed on the website
*/
public function main($content, $conf)
{
public function main($content, $conf) {
$this->init($conf);
// Merge configuration with conf array of toolbox.
$this->conf = \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($this->cObj->data['conf'], $this->conf);
@ -44,13 +42,11 @@ class ImageDownloadTool extends \Kitodo\Dlf\Common\AbstractPlugin
$this->loadDocument();
if ($this->doc === NULL
|| $this->doc->numPages < 1
|| empty($this->conf['fileGrpsImageDownload']))
{
|| empty($this->conf['fileGrpsImageDownload'])) {
// Quit without doing anything if required variables are not set.
return $content;
} else {
if (!empty($this->piVars['logicalPage']))
{
if (!empty($this->piVars['logicalPage'])) {
$this->piVars['page'] = $this->doc->getPhysicalPage($this->piVars['logicalPage']);
// The logical page parameter should not appear again
unset($this->piVars['logicalPage']);
@ -58,8 +54,7 @@ class ImageDownloadTool extends \Kitodo\Dlf\Common\AbstractPlugin
// Set default values if not set.
// $this->piVars['page'] may be integer or string (physical structure @ID)
if ((int) $this->piVars['page'] > 0
|| empty($this->piVars['page']))
{
|| empty($this->piVars['page'])) {
$this->piVars['page'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange((int) $this->piVars['page'], 1, $this->doc->numPages, 1);
} else {
$this->piVars['page'] = array_search($this->piVars['page'], $this->doc->physicalStructure);
@ -86,20 +81,16 @@ class ImageDownloadTool extends \Kitodo\Dlf\Common\AbstractPlugin
*
* @return string Link to image file with given label
*/
protected function getImage($page, $label)
{
protected function getImage($page, $label) {
$image = [];
// Get @USE value of METS fileGrp.
$fileGrps = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $this->conf['fileGrpsImageDownload']);
while ($fileGrp = @array_pop($fileGrps))
{
while ($fileGrp = @array_pop($fileGrps)) {
// Get image link.
if (!empty($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$page]]['files'][$fileGrp]))
{
if (!empty($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$page]]['files'][$fileGrp])) {
$image['url'] = $this->doc->getFileLocation($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$page]]['files'][$fileGrp]);
$image['mimetype'] = $this->doc->getFileMimeType($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$page]]['files'][$fileGrp]);
switch ($image['mimetype'])
{
switch ($image['mimetype']) {
case 'image/jpeg':
$mimetypeLabel = '(JPG)';
break;
@ -117,8 +108,7 @@ class ImageDownloadTool extends \Kitodo\Dlf\Common\AbstractPlugin
$imageLink = $this->cObj->typoLink($label.' '.$mimetypeLabel, $linkConf);
break;
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Plugins\Tools\ImageDownloadTool->getImage('.$page.')] File not found in fileGrp "'.$fileGrp.'"', $this->extKey, SYSLOG_SEVERITY_WARNING);
}
}

View File

@ -21,8 +21,7 @@ use Kitodo\Dlf\Common\Helper;
* @subpackage dlf
* @access public
*/
class ImageManipulationTool extends \Kitodo\Dlf\Common\AbstractPlugin
{
class ImageManipulationTool extends \Kitodo\Dlf\Common\AbstractPlugin {
public $scriptRelPath = 'Classes/Plugins/Tools/ImageManipulationTool.php';
/**
@ -35,8 +34,7 @@ class ImageManipulationTool extends \Kitodo\Dlf\Common\AbstractPlugin
*
* @return string The content that is displayed on the website
*/
public function main($content, $conf)
{
public function main($content, $conf) {
$this->init($conf);
// Merge configuration with conf array of toolbox.
$this->conf = \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($this->cObj->data['conf'], $this->conf);

View File

@ -22,8 +22,7 @@ use Kitodo\Dlf\Common\Helper;
* @subpackage dlf
* @access public
*/
class PdfDownloadTool extends \Kitodo\Dlf\Common\AbstractPlugin
{
class PdfDownloadTool extends \Kitodo\Dlf\Common\AbstractPlugin {
public $scriptRelPath = 'Classes/Plugins/Tools/PdfDownloadTool.php';
/**
@ -36,8 +35,7 @@ class PdfDownloadTool extends \Kitodo\Dlf\Common\AbstractPlugin
*
* @return string The content that is displayed on the website
*/
public function main($content, $conf)
{
public function main($content, $conf) {
$this->init($conf);
// Merge configuration with conf array of toolbox.
$this->conf = \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($this->cObj->data['conf'], $this->conf);
@ -45,13 +43,11 @@ class PdfDownloadTool extends \Kitodo\Dlf\Common\AbstractPlugin
$this->loadDocument();
if ($this->doc === NULL
|| $this->doc->numPages < 1
|| empty($this->conf['fileGrpDownload']))
{
|| empty($this->conf['fileGrpDownload'])) {
// Quit without doing anything if required variables are not set.
return $content;
} else {
if (!empty($this->piVars['logicalPage']))
{
if (!empty($this->piVars['logicalPage'])) {
$this->piVars['page'] = $this->doc->getPhysicalPage($this->piVars['logicalPage']);
// The logical page parameter should not appear again
unset($this->piVars['logicalPage']);
@ -59,8 +55,7 @@ class PdfDownloadTool extends \Kitodo\Dlf\Common\AbstractPlugin
// Set default values if not set.
// $this->piVars['page'] may be integer or string (physical structure @ID)
if ((int) $this->piVars['page'] > 0
|| empty($this->piVars['page']))
{
|| empty($this->piVars['page'])) {
$this->piVars['page'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange((int) $this->piVars['page'], 1, $this->doc->numPages, 1);
} else {
$this->piVars['page'] = array_search($this->piVars['page'], $this->doc->physicalStructure);
@ -84,47 +79,39 @@ class PdfDownloadTool extends \Kitodo\Dlf\Common\AbstractPlugin
*
* @return string Link to downloadable page
*/
protected function getPageLink()
{
protected function getPageLink() {
$page1Link = '';
$page2Link = '';
$pageNumber = $this->piVars['page'];
// Get image link.
$details = $this->doc->physicalStructureInfo[$this->doc->physicalStructure[$pageNumber]];
$file = $details['files'][$this->conf['fileGrpDownload']];
if (!empty($file))
{
if (!empty($file)) {
$page1Link = $this->doc->getFileLocation($file);
}
// Get second page, too, if double page view is activated.
if ($this->piVars['double']
&& $pageNumber < $this->doc->numPages)
{
&& $pageNumber < $this->doc->numPages) {
$details = $this->doc->physicalStructureInfo[$this->doc->physicalStructure[$pageNumber + 1]];
$file = $details['files'][$this->conf['fileGrpDownload']];
if (!empty($file))
{
if (!empty($file)) {
$page2Link = $this->doc->getFileLocation($file);
}
}
if (TYPO3_DLOG
&& empty($page1Link)
&& empty($page2Link))
{
&& empty($page2Link)) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Plugins\Tools\PdfDownloadTool->getPageLink()] File not found in fileGrp "'.$this->conf['fileGrpDownload'].'"', $this->extKey, SYSLOG_SEVERITY_WARNING);
}
// Wrap URLs with HTML.
if (!empty($page1Link))
{
if ($this->piVars['double'])
{
if (!empty($page1Link)) {
if ($this->piVars['double']) {
$page1Link = $this->cObj->typoLink($this->pi_getLL('leftPage', ''), ['parameter' => $page1Link, 'title' => $this->pi_getLL('leftPage', '')]);
} else {
$page1Link = $this->cObj->typoLink($this->pi_getLL('singlePage', ''), ['parameter' => $page1Link, 'title' => $this->pi_getLL('singlePage', '')]);
}
}
if (!empty($page2Link))
{
if (!empty($page2Link)) {
$page2Link = $this->cObj->typoLink($this->pi_getLL('rightPage', ''), ['parameter' => $page2Link, 'title' => $this->pi_getLL('rightPage', '')]);
}
return $page1Link.$page2Link;
@ -137,27 +124,22 @@ class PdfDownloadTool extends \Kitodo\Dlf\Common\AbstractPlugin
*
* @return string Link to downloadable work
*/
protected function getWorkLink()
{
protected function getWorkLink() {
$workLink = '';
// Get work link.
if (!empty($this->doc->physicalStructureInfo[$this->doc->physicalStructure[0]]['files'][$this->conf['fileGrpDownload']]))
{
if (!empty($this->doc->physicalStructureInfo[$this->doc->physicalStructure[0]]['files'][$this->conf['fileGrpDownload']])) {
$workLink = $this->doc->getFileLocation($this->doc->physicalStructureInfo[$this->doc->physicalStructure[0]]['files'][$this->conf['fileGrpDownload']]);
} else {
$details = $this->doc->getLogicalStructure($this->doc->toplevelId);
if (!empty($details['files'][$this->conf['fileGrpDownload']]))
{
if (!empty($details['files'][$this->conf['fileGrpDownload']])) {
$workLink = $this->doc->getFileLocation($details['files'][$this->conf['fileGrpDownload']]);
}
}
// Wrap URLs with HTML.
if (!empty($workLink))
{
if (!empty($workLink)) {
$workLink = $this->cObj->typoLink($this->pi_getLL('work', ''), ['parameter' => $workLink, 'title' => $this->pi_getLL('work', '')]);
} else {
if (TYPO3_DLOG)
{
if (TYPO3_DLOG) {
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[\Kitodo\Dlf\Plugins\Tools\PdfDownloadTool->getWorkLink()] File not found in fileGrp "'.$this->conf['fileGrpDownload'].'"', $this->extKey, SYSLOG_SEVERITY_WARNING);
}
}

View File

@ -12,7 +12,7 @@ namespace Kitodo\Dlf\Plugins;
*/
/**
* Plugin 'Validator' for the 'dlf' extension.
* Plugin 'Validator' for the 'dlf' extension
*
* @author Sebastian Meyer <sebastian.meyer@slub-dresden.de>
* @package TYPO3
@ -20,7 +20,6 @@ namespace Kitodo\Dlf\Plugins;
* @access public
*/
class Validator extends \Kitodo\Dlf\Common\AbstractPlugin {
public $scriptRelPath = 'Classes/Plugins/Validator.php';
/**
@ -34,40 +33,28 @@ class Validator extends \Kitodo\Dlf\Common\AbstractPlugin {
* @return string The content that is displayed on the website
*/
public function main($content, $conf) {
$this->init($conf);
// Disable caching for this plugin.
$this->setCache(FALSE);
// Load template file.
$this->getTemplate();
// Load current document.
$this->loadDocument();
if ($this->doc === NULL) {
// Document could not be loaded.
// Check:
// - if document location is valid URL
// - if document location is reachable
// - if document is well-formed XML
// - if document has METS node
} else {
// Document loaded.
// Check:
// - if document is valid METS document
// - if document contains supported metadata schema
// - if document's metadata are valid
// - if document provides configured mandatory fields
}
return $this->pi_wrapInBaseClass($content);
}
}

View File

@ -9,8 +9,7 @@
* LICENSE.txt file that was distributed with this source code.
*/
if (!defined('TYPO3_MODE'))
{
if (!defined('TYPO3_MODE')) {
die('Access denied.');
}
// Register static typoscript.

View File

@ -9,8 +9,7 @@
* LICENSE.txt file that was distributed with this source code.
*/
if (!defined('TYPO3_MODE'))
{
if (!defined('TYPO3_MODE')) {
die('Access denied.');
}
// Plugin "audioplayer".

View File

@ -20,8 +20,7 @@ use Kitodo\Dlf\Common\Solr;
* @subpackage dlf
* @access public
*/
class ext_update
{
class ext_update {
/**
* This holds the output ready to return
*
@ -37,19 +36,14 @@ class ext_update
*
* @return boolean Should the update option be shown?
*/
public function access()
{
if (count($this->getMetadataConfig()))
{
public function access() {
if (count($this->getMetadataConfig())) {
return TRUE;
} elseif ($this->oldIndexRelatedTableNames())
{
} elseif ($this->oldIndexRelatedTableNames()) {
return TRUE;
} elseif ($this->solariumSolrUpdateRequired())
{
} elseif ($this->solariumSolrUpdateRequired()) {
return TRUE;
} elseif (count($this->oldFormatClasses()))
{
} elseif (count($this->oldFormatClasses())) {
return TRUE;
}
return FALSE;
@ -62,13 +56,11 @@ class ext_update
*
* @return array Array of UIDs of outdated records
*/
protected function getMetadataConfig()
{
protected function getMetadataConfig() {
$uids = [];
// check if tx_dlf_metadata.xpath exists anyhow
$fieldsInDatabase = $GLOBALS['TYPO3_DB']->admin_get_fields('tx_dlf_metadata');
if (!in_array('xpath', array_keys($fieldsInDatabase)))
{
if (!in_array('xpath', array_keys($fieldsInDatabase))) {
return $uids;
}
// Get all records with outdated configuration.
@ -82,10 +74,8 @@ class ext_update
'',
''
);
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result))
{
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result))
{
if ($GLOBALS['TYPO3_DB']->sql_num_rows($result)) {
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
$uids[] = intval($resArray['uid']);
}
}
@ -99,25 +89,20 @@ class ext_update
*
* @return string The content that is displayed on the website
*/
public function main()
{
public function main() {
// Load localization file.
$GLOBALS['LANG']->includeLLFile('EXT:dlf/Resources/Private/Language/FlashMessages.xml');
// Update the metadata configuration.
if (count($this->getMetadataConfig()))
{
if (count($this->getMetadataConfig())) {
$this->updateMetadataConfig();
}
if ($this->oldIndexRelatedTableNames())
{
if ($this->oldIndexRelatedTableNames()) {
$this->renameIndexRelatedColumns();
}
if ($this->solariumSolrUpdateRequired())
{
if ($this->solariumSolrUpdateRequired()) {
$this->doSolariumSolrUpdate();
}
if (count($this->oldFormatClasses()))
{
if (count($this->oldFormatClasses())) {
$this->updateFormatClasses();
}
return $this->content;
@ -130,8 +115,7 @@ class ext_update
*
* @return boolean true if old format classes exist
*/
protected function oldFormatClasses()
{
protected function oldFormatClasses() {
$oldRecords = [];
// Get all records with outdated configuration.
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
@ -143,8 +127,7 @@ class ext_update
'',
''
);
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result))
{
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
$oldRecords[$resArray['uid']] = $resArray['type'];
}
return $oldRecords;
@ -157,8 +140,7 @@ class ext_update
*
* @return boolean TRUE if old index related columns exist
*/
protected function oldIndexRelatedTableNames()
{
protected function oldIndexRelatedTableNames() {
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'column_name',
'INFORMATION_SCHEMA.COLUMNS',
@ -167,14 +149,12 @@ class ext_update
'',
''
);
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result))
{
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
if ($resArray['column_name'] == 'tokenized'
|| $resArray['column_name'] == 'stored'
|| $resArray['column_name'] == 'indexed'
|| $resArray['column_name'] == 'boost'
|| $resArray['column_name'] == 'autocomplete')
{
|| $resArray['column_name'] == 'autocomplete') {
return TRUE;
}
}
@ -187,8 +167,7 @@ class ext_update
*
* @return void
*/
protected function renameIndexRelatedColumns()
{
protected function renameIndexRelatedColumns() {
$sqlQuery = 'UPDATE tx_dlf_metadata'
.' SET `index_tokenized` = `tokenized`'
.', `index_stored` = `stored`'
@ -197,8 +176,7 @@ class ext_update
.', `index_autocomplete` = `autocomplete`';
// Copy the content of the old tables to the new ones
$result = $GLOBALS['TYPO3_DB']->sql_query($sqlQuery);
if ($result)
{
if ($result) {
$message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
\TYPO3\CMS\Core\Messaging\FlashMessage::class,
$GLOBALS['LANG']->getLL('update.copyIndexRelatedColumnsOkay', TRUE),
@ -225,16 +203,14 @@ class ext_update
*
* @return void
*/
protected function updateFormatClasses()
{
protected function updateFormatClasses() {
$oldRecords = $this->oldFormatClasses();
$newValues = [
'ALTO' => 'Kitodo\\Dlf\\Formats\\Alto',
'MODS' => 'Kitodo\\Dlf\\Formats\\Mods',
'TEIHDR' => 'Kitodo\\Dlf\\Formats\\TeiHeader'
];
foreach ($oldRecords as $uid => $type)
{
foreach ($oldRecords as $uid => $type) {
$sqlQuery = 'UPDATE tx_dlf_formats SET class="'.$newValues[$type].'" WHERE uid='.$uid;
$GLOBALS['TYPO3_DB']->sql_query($sqlQuery);
}
@ -255,11 +231,9 @@ class ext_update
*
* @return void
*/
protected function updateMetadataConfig()
{
protected function updateMetadataConfig() {
$metadataUids = $this->getMetadataConfig();
if (!empty($metadataUids))
{
if (!empty($metadataUids)) {
$data = [];
// Get all old metadata configuration records.
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
@ -271,8 +245,7 @@ class ext_update
'',
''
);
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result))
{
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
$newId = uniqid('NEW');
// Copy record to new table.
$data['tx_dlf_metadataformat'][$newId] = [
@ -286,13 +259,11 @@ class ext_update
// Add reference to old table.
$data['tx_dlf_metadata'][$resArray['uid']]['format'] = $newId;
}
if (!empty($data))
{
if (!empty($data)) {
// Process datamap.
$substUids = Helper::processDBasAdmin($data);
unset ($data);
if (!empty($substUids))
{
if (!empty($substUids)) {
$message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
\TYPO3\CMS\Core\Messaging\FlashMessage::class,
$GLOBALS['LANG']->getLL('update.metadataConfigOkay', TRUE),
@ -321,8 +292,7 @@ class ext_update
*
* @return boolean
*/
protected function solariumSolrUpdateRequired()
{
protected function solariumSolrUpdateRequired() {
// Get all Solr cores that were not deleted.
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'index_name',
@ -332,12 +302,10 @@ class ext_update
'',
''
);
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result))
{
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
// Instantiate search object.
$solr = Solr::getInstance($resArray['index_name']);
if (!$solr->ready)
{
if (!$solr->ready) {
return TRUE;
}
}
@ -351,8 +319,7 @@ class ext_update
*
* @return void
*/
protected function doSolariumSolrUpdate()
{
protected function doSolariumSolrUpdate() {
// Get all Solr cores that were not deleted.
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'index_name',
@ -362,18 +329,15 @@ class ext_update
'',
''
);
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result))
{
while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
// Instantiate search object.
$solr = Solr::getInstance($resArray['index_name']);
if (!$solr->ready)
{
if (!$solr->ready) {
$conf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['dlf']);
$solrInfo = Solr::getSolrConnectionInfo();
// Prepend username and password to hostname.
if ($solrInfo['username']
&& $solrInfo['password'])
{
&& $solrInfo['password']) {
$host = $solrInfo['username'].':'.$solrInfo['password'].'@'.$solrInfo['host'];
} else {
$host = $solrInfo['host'];
@ -389,12 +353,10 @@ class ext_update
$url = $solrInfo['scheme'].'://'.$host.':'.$solrInfo['port'].'/'.$solrInfo['path'].'/admin/cores?wt=xml&action=CREATE&name='.$resArray['index_name'].'&instanceDir=dlfCore'.$resArray['index_name'].'&dataDir=data&configSet=dlf';
$response = @simplexml_load_string(file_get_contents($url, FALSE, $context));
// Process response.
if ($response)
{
if ($response) {
$status = $response->xpath('//lst[@name="responseHeader"]/int[@name="status"]');
if ($status
&& $status[0] == 0)
{
&& $status[0] == 0) {
continue;
}
}

View File

@ -9,8 +9,7 @@
* LICENSE.txt file that was distributed with this source code.
*/
if (!defined('TYPO3_MODE'))
{
if (!defined('TYPO3_MODE')) {
die ('Access denied.');
}
// Register plugins.
@ -45,8 +44,7 @@ $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['proc
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['dlf/Classes/Common/Document.php']['hookClass'][] = 'EXT:'.$_EXTKEY.'/Classes/Hooks/KitodoProductionHacks.php:KitodoProductionHacks';
// Register command line scripts.
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['cliKeys'][$_EXTKEY] = [
function ()
{
function () {
$SOBE = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\Kitodo\Dlf\Cli\CommandLineIndexer::class);
$SOBE->main();
},
@ -56,8 +54,7 @@ $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['cliKeys'][$_EXTKEY] = [
$GLOBALS['TYPO3_CONF_VARS']['FE']['eID_include']['tx_dlf_search_suggest'] = \Kitodo\Dlf\Plugins\Eid\SearchSuggest::class.'::main';
$GLOBALS['TYPO3_CONF_VARS']['FE']['eID_include']['tx_dlf_pageview_proxy'] = \Kitodo\Dlf\Plugins\Eid\PageViewProxy::class.'::main';
// Register Typoscript user function.
if (TYPO3_MODE === 'FE')
{
if (TYPO3_MODE === 'FE') {
/**
* docTypeCheck user function to use in Typoscript
* @example [userFunc = user_dlf_docTypeCheck($type)]
@ -68,8 +65,7 @@ if (TYPO3_MODE === 'FE')
*
* @return boolean TRUE if document type matches, FALSE if not
*/
function user_dlf_docTypeCheck($type)
{
function user_dlf_docTypeCheck($type) {
$hook = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\Kitodo\Dlf\Common\DocumentTypeCheck::class);
return ($hook->getDocType() === $type);
}