/**
  * Main function of the script.
  *
  * @access	public
  *
  * @return	void
  */
 public function main()
 {
     switch ((string) $this->cli_args['_DEFAULT'][1]) {
         case 'index':
             // Add command line arguments.
             $this->cli_options[] = array('-doc UID/URL', 'UID or URL of the document.');
             $this->cli_options[] = array('-pid UID', 'UID of the page the document should be added to.');
             $this->cli_options[] = array('-core UID', 'UID of the Solr core the document should be added to.');
             // Check the command line arguments.
             $this->cli_validateArgs();
             // Get the document...
             $doc =& tx_dlf_document::getInstance($this->cli_args['-doc'][0], $this->cli_args['-pid'][0], TRUE);
             if ($doc->ready) {
                 // ...and save it to the database...
                 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);
                     exit(1);
                 }
             } else {
                 $this->cli_echo('ERROR: Document ' . $this->cli_args['-doc'][0] . ' could not be loaded.' . LF, TRUE);
                 exit(1);
             }
             break;
         default:
             $this->cli_help();
             break;
     }
     exit(0);
 }
 /**
  * Main function of the script.
  *
  * @access	public
  *
  * @return	void
  */
 public function main()
 {
     switch ((string) $this->cli_args['_DEFAULT'][1]) {
         // (Re-)Index a single document.
         case 'index':
             // Add command line arguments.
             $this->cli_options[] = array('-doc UID/URL', 'UID or URL of the document.');
             $this->cli_options[] = array('-pid UID', 'UID of the page the document should be added to.');
             $this->cli_options[] = array('-core UID', 'UID of the Solr core the document should be added to.');
             // Check the command line arguments.
             $this->cli_validateArgs();
             // Get the document...
             $doc =& tx_dlf_document::getInstance($this->cli_args['-doc'][0], $this->cli_args['-pid'][0], TRUE);
             if ($doc->ready) {
                 // ...and save it to the database...
                 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);
                     exit(1);
                 }
             } else {
                 $this->cli_echo('ERROR: Document ' . $this->cli_args['-doc'][0] . ' could not be loaded.' . LF, TRUE);
                 exit(1);
             }
             break;
             // Re-index all documents of a collection.
         // Re-index all documents of a collection.
         case 'reindex':
             // Add command line arguments.
             $this->cli_options[] = array('-coll UID', 'UID of the collection.');
             $this->cli_options[] = array('-pid UID', 'UID of the page the document should be added to.');
             $this->cli_options[] = array('-core UID', 'UID of the Solr core the document should be added to.');
             // Check the command line arguments.
             $this->cli_validateArgs();
             // Get the collection.
             $result = $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_collections.uid=' . intval($this->cli_args['-coll'][0]) . ' AND tx_dlf_collections.pid=' . intval($this->cli_args['-pid'][0]) . ' AND tx_dlf_relations.ident=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('docs_colls', 'tx_dlf_relations') . tx_dlf_helper::whereClause('tx_dlf_documents') . tx_dlf_helper::whereClause('tx_dlf_collections'), '', '', '');
             while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
                 // Get the document...
                 $doc =& tx_dlf_document::getInstance($resArray['uid'], $this->cli_args['-pid'][0], TRUE);
                 if ($doc->ready) {
                     // ...and save it to the database...
                     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);
                         exit(1);
                     }
                 } else {
                     $this->cli_echo('ERROR: Document ' . $resArray['uid'] . ' could not be loaded.' . LF, TRUE);
                     exit(1);
                 }
             }
             break;
         default:
             $this->cli_help();
             break;
     }
     exit(0);
 }
 /**
  * Loads the current document into $this->doc
  *
  * @access	protected
  *
  * @return	void
  */
 protected function loadDocument()
 {
     // Check for required variable.
     if (!empty($this->piVars['id']) && !empty($this->conf['pages'])) {
         // Should we exclude documents from other pages than $this->conf['pages']?
         $pid = !empty($this->conf['excludeOther']) ? intval($this->conf['pages']) : 0;
         // Get instance of tx_dlf_document.
         $this->doc =& tx_dlf_document::getInstance($this->piVars['id'], $pid);
         if (!$this->doc->ready) {
             // Destroy the incomplete object.
             if (TYPO3_DLOG) {
                 t3lib_div::devLog('[tx_dlf_plugin->loadDocument()] Failed to load document with UID "' . $this->piVars['id'] . '"', $this->extKey, SYSLOG_SEVERITY_ERROR);
             }
             $this->doc = NULL;
         } else {
             // Set configuration PID.
             $this->doc->cPid = $this->conf['pages'];
         }
     } elseif (!empty($this->piVars['recordId'])) {
         // Get UID of document with given record identifier.
         $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery('tx_dlf_documents.uid', 'tx_dlf_documents', 'tx_dlf_documents.record_id=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->piVars['recordId'], 'tx_dlf_documents') . tx_dlf_helper::whereClause('tx_dlf_documents'), '', '', '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'];
             // Unset variable to avoid infinite looping.
             unset($this->piVars['recordId'], $_GET[$this->prefixId]['recordId']);
             // Try to load document.
             $this->loadDocument();
         } else {
             if (TYPO3_DLOG) {
                 t3lib_div::devLog('[tx_dlf_plugin->loadDocument()] Failed to load document with record ID "' . $this->piVars['recordId'] . '"', $this->extKey, SYSLOG_SEVERITY_ERROR);
             }
         }
     } else {
         if (TYPO3_DLOG) {
             t3lib_div::devLog('[tx_dlf_plugin->loadDocument()] Invalid UID "' . $this->piVars['id'] . '" or PID "' . $this->conf['pages'] . '" for document loading', $this->extKey, SYSLOG_SEVERITY_ERROR);
         }
     }
 }
 /**
  * Processes a physical unit for the Solr index
  *
  * @access	protected
  *
  * @param	tx_dlf_document		&$doc: The METS document
  * @param	integer		$page: The page number
  * @param	array		$physicalUnit: Array of the physical unit to process
  *
  * @return	integer		0 on success or 1 on failure
  */
 protected static function processPhysical(tx_dlf_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']])) {
         $file = $doc->getFileLocation($physicalUnit['files'][$extConf['fileGrpFulltext']]);
         // Load XML file.
         if (\TYPO3\CMS\Core\Utility\GeneralUtility::isValidUrl($file) || version_compare(phpversion(), '5.3.3', '<')) {
             // Set user-agent to identify self when fetching XML data.
             if (!empty($extConf['useragent'])) {
                 @ini_set('user_agent', $extConf['useragent']);
             }
             // Turn off libxml's error logging.
             $libxmlErrors = libxml_use_internal_errors(TRUE);
             // disable entity loading
             $previousValueOfEntityLoader = libxml_disable_entity_loader(TRUE);
             // Load XML from file.
             $xml = simplexml_load_string(file_get_contents($file));
             // reset entity loader setting
             libxml_disable_entity_loader($previousValueOfEntityLoader);
             // Reset libxml's error logging.
             libxml_use_internal_errors($libxmlErrors);
             if ($xml === FALSE) {
                 return 1;
             }
         } else {
             return 1;
         }
         // Load class.
         if (!class_exists('Apache_Solr_Document')) {
             require_once \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName('EXT:' . self::$extKey . '/lib/SolrPhpClient/Apache/Solr/Document.php');
         }
         // Create new Solr document.
         $solrDoc = new Apache_Solr_Document();
         // Create unique identifier from document's UID and unit's XML ID.
         $solrDoc->setField('id', $doc->uid . $physicalUnit['id']);
         $solrDoc->setField('uid', $doc->uid);
         $solrDoc->setField('pid', $doc->pid);
         $solrDoc->setField('page', $page);
         if (!empty($physicalUnit['files'][$extConf['fileGrpThumbs']])) {
             $solrDoc->setField('thumbnail', $doc->getFileLocation($physicalUnit['files'][$extConf['fileGrpThumbs']]));
         }
         $solrDoc->setField('partof', $doc->parentId);
         $solrDoc->setField('root', $doc->rootId);
         $solrDoc->setField('sid', $physicalUnit['id']);
         $solrDoc->setField('toplevel', FALSE);
         $solrDoc->setField('type', $physicalUnit['type'], self::$fields['fieldboost']['type']);
         $solrDoc->setField('fulltext', tx_dlf_alto::getRawText($xml));
         try {
             self::$solr->service->addDocument($solrDoc);
         } catch (Exception $e) {
             if (!defined('TYPO3_cliMode')) {
                 $message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Messaging\\FlashMessage', tx_dlf_helper::getLL('flash.solrException', TRUE) . '<br />' . htmlspecialchars($e->getMessage()), tx_dlf_helper::getLL('flash.error', TRUE), \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR, TRUE);
                 tx_dlf_helper::addMessage($message);
             }
             return 1;
         }
     }
     return $errors;
 }
 /**
  * Post-processing hook for the process_cmdmap() method.
  *
  * @access	public
  *
  * @param	string		$command: 'move', 'copy', 'localize', 'inlineLocalizeSynchronize', 'delete' or 'undelete'
  * @param	string		$table: The destination table
  * @param	integer		$id: The uid of the record
  * @param	mixed		$value: The value for the command
  * @param	\TYPO3\CMS\Core\DataHandling\DataHandler $pObj: The parent object
  *
  * @return	void
  */
 public function processCmdmap_postProcess($command, $table, $id, $value, $pObj)
 {
     if (in_array($command, array('move', 'delete', 'undelete')) && $table == 'tx_dlf_documents') {
         // Get Solr core.
         $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery('tx_dlf_solrcores.uid', 'tx_dlf_solrcores,tx_dlf_documents', 'tx_dlf_solrcores.uid=tx_dlf_documents.solrcore AND tx_dlf_documents.uid=' . intval($id) . tx_dlf_helper::whereClause('tx_dlf_solrcores'), '', '', '1');
         if ($GLOBALS['TYPO3_DB']->sql_num_rows($result)) {
             list($core) = $GLOBALS['TYPO3_DB']->sql_fetch_row($result);
             switch ($command) {
                 case 'move':
                 case 'delete':
                     // Establish Solr connection.
                     if ($solr = tx_dlf_solr::getInstance($core)) {
                         // Delete Solr document.
                         $solr->service->deleteByQuery('uid:' . $id);
                         $solr->service->commit();
                         if ($command == 'delete') {
                             break;
                         }
                     }
                 case 'undelete':
                     // Reindex document.
                     $doc =& tx_dlf_document::getInstance($id);
                     if ($doc->ready) {
                         $doc->save($doc->pid, $core);
                     } else {
                         if (TYPO3_DLOG) {
                             \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_tcemain->processCmdmap_postProcess(' . $command . ', ' . $table . ', ' . $id . ', ' . $value . ', [' . get_class($pObj) . '])] Failed to re-index document with UID "' . $id . '"', $this->extKey, SYSLOG_SEVERITY_ERROR);
                         }
                     }
                     break;
             }
         }
     }
 }
 /**
  * The main method of the PlugIn
  *
  * @access	public
  *
  * @param	string		$content: The PlugIn content
  * @param	array		$conf: The PlugIn configuration
  *
  * @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('[tx_dlf_search->main(' . $content . ', [data])] Incomplete plugin configuration', $this->extKey, SYSLOG_SEVERITY_WARNING, $conf);
         }
         return $content;
     }
     if (!isset($this->piVars['query']) && empty($this->piVars['extQuery'])) {
         // Add javascript for search suggestions if enabled and jQuery autocompletion is available.
         if (!empty($this->conf['suggest'])) {
             $this->addAutocompleteJS();
         }
         // Load template file.
         if (!empty($this->conf['templateFile'])) {
             $this->template = $this->cObj->getSubpart($this->cObj->fileResource($this->conf['templateFile']), '###TEMPLATE###');
         } else {
             $this->template = $this->cObj->getSubpart($this->cObj->fileResource('EXT:dlf/plugins/search/template.tmpl'), '###TEMPLATE###');
         }
         // Configure @action URL for form.
         $linkConf = array('parameter' => $GLOBALS['TSFE']->id, 'forceAbsoluteUrl' => 1);
         // Fill markers.
         $markerArray = array('###ACTION_URL###' => $this->cObj->typoLink_URL($linkConf), '###LABEL_QUERY###' => $this->pi_getLL('label.query'), '###LABEL_SUBMIT###' => $this->pi_getLL('label.submit'), '###FIELD_QUERY###' => $this->prefixId . '[query]', '###QUERY###' => '', '###FULLTEXTSWITCH###' => $this->addFulltextSwitch(), '###FIELD_DOC###' => $this->conf['searchIn'] == 'document' || $this->conf['searchIn'] == 'all' ? $this->addCurrentDocument() : '', '###FIELD_COLL###' => $this->conf['searchIn'] == 'collection' || $this->conf['searchIn'] == 'all' ? $this->addCurrentCollection() : '', '###ADDITIONAL_INPUTS###' => $this->addEncryptedCoreName(), '###FACETS_MENU###' => $this->addFacetsMenu());
         // 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 = tx_dlf_solr::getInstance($this->conf['solrcore']);
         if (!$solr->ready) {
             if (TYPO3_DLOG) {
                 \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_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 = array();
         // Set search query.
         if (!empty($this->conf['fulltext']) && !empty($this->piVars['fulltext'])) {
             // Search in fulltext field if applicable.
             $query = 'fulltext:(' . tx_dlf_solr::escapeQuery($this->piVars['query']) . ')';
             // Add highlighting for fulltext.
             $params['hl'] = 'true';
             $params['hl.fl'] = 'fulltext';
         } else {
             // Retain given search field if valid.
             $query = tx_dlf_solr::escapeQueryKeepField($this->piVars['query'], $this->conf['pages']);
         }
         // Add extended search query.
         if (!empty($this->piVars['extQuery']) && is_array($this->piVars['extQuery'])) {
             $allowedOperators = array('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 (!empty($query)) {
                             $query .= ' ' . $this->piVars['extOperator'][$i] . ' ';
                         }
                         $query .= tx_dlf_indexing::getIndexFieldName($this->piVars['extField'][$i], $this->conf['pages']) . ':(' . tx_dlf_solr::escapeQuery($this->piVars['extQuery'][$i]) . ')';
                     }
                 }
             }
         }
         // Add filter query for faceting.
         if (!empty($this->piVars['fq'])) {
             $params['fq'] = $this->piVars['fq'];
         }
         // 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'])) {
                 $params['fq'][] = 'uid:(' . $this->piVars['id'] . ') OR partof:(' . $this->piVars['id'] . ')';
                 $label .= htmlspecialchars(sprintf($this->pi_getLL('in', ''), tx_dlf_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'])) {
                 $index_name = tx_dlf_helper::getIndexName($this->piVars['collection'], 'tx_dlf_collections', $this->conf['pages']);
                 $params['fq'][] = 'collection_faceting:("' . tx_dlf_solr::escapeQuery($index_name) . '")';
                 $label .= sprintf($this->pi_getLL('in', '', TRUE), tx_dlf_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 = array();
             foreach ($collIds as $collId) {
                 $collIndexNames[] = tx_dlf_solr::escapeQuery(tx_dlf_helper::getIndexName(intval($collId), 'tx_dlf_collections', $this->conf['pages']));
             }
             // Last value is fake and used for distinction in $this->addCurrentCollection()
             $params['fq'][] = 'collection_faceting:("' . implode('" OR "', $collIndexNames) . '" OR "FakeValueForDistinction")';
         }
         // Set search parameters.
         $solr->limit = max(intval($this->conf['limit']), 1);
         $solr->cPid = $this->conf['pages'];
         $solr->params = $params;
         // Perform search.
         $results = $solr->search($query);
         $results->metadata = array('label' => $label, 'description' => '<p class="tx-dlf-search-numHits">' . htmlspecialchars(sprintf($this->pi_getLL('hits', ''), $solr->numberOfHits, count($results))) . '</p>', 'thumbnail' => '', 'options' => $results->metadata['options']);
         $results->save();
         // Clean output buffer.
         \TYPO3\CMS\Core\Utility\GeneralUtility::cleanOutputBuffers();
         // Keep some plugin variables.
         $linkConf['parameter'] = $this->conf['targetPid'];
         if (!empty($this->piVars['order'])) {
             $linkConf['additionalParams'] = \TYPO3\CMS\Core\Utility\GeneralUtility::implodeArrayForUrl($this->prefixId, array('order' => $this->piVars['order'], 'asc' => !empty($this->piVars['asc']) ? '1' : '0'), '', 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;
     }
 }
 /**
  * This saves the document to the database and index
  *
  * @access	public
  *
  * @param	integer		$pid: The PID of the saved record
  * @param	integer		$core: The UID of the Solr core for indexing
  *
  * @return	boolean		TRUE on success or FALSE on failure
  */
 public function save($pid = 0, $core = 0)
 {
     // Save parameters for logging purposes.
     $_pid = $pid;
     $_core = $core;
     if (TYPO3_MODE !== 'BE') {
         if (TYPO3_DLOG) {
             t3lib_div::devLog('[tx_dlf_document->save(' . $_pid . ', ' . $_core . ')] Saving a document is only allowed in the backend', self::$extKey, SYSLOG_SEVERITY_ERROR);
         }
         return FALSE;
     }
     // Make sure $pid is a non-negative integer.
     $pid = max(intval($pid), 0);
     // Make sure $core is a non-negative integer.
     $core = max(intval($core), 0);
     // If $pid is not given, try to get it elsewhere.
     if (!$pid && $this->pid) {
         // Retain current PID.
         $pid = $this->pid;
     } elseif (!$pid) {
         if (TYPO3_DLOG) {
             t3lib_div::devLog('[tx_dlf_document->save(' . $_pid . ', ' . $_core . ')] Invalid PID "' . $pid . '" for document saving', self::$extKey, SYSLOG_SEVERITY_ERROR);
         }
         return FALSE;
     }
     // Set PID for metadata definitions.
     $this->cPid = $pid;
     // Set UID placeholder if not updating existing record.
     if ($pid != $this->pid) {
         $this->uid = uniqid('NEW');
     }
     // Get metadata array.
     $metadata = $this->getTitledata($pid);
     // Check for record identifier.
     if (empty($metadata['record_id'][0])) {
         if (TYPO3_DLOG) {
             t3lib_div::devLog('[tx_dlf_document->save(' . $_pid . ', ' . $_core . ')] No record identifier found to avoid duplication', self::$extKey, SYSLOG_SEVERITY_ERROR);
         }
         return FALSE;
     }
     // Load plugin configuration.
     $conf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][self::$extKey]);
     // Get UID for user "_cli_dlf".
     $be_user = 0;
     $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery('be_users.uid AS uid', 'be_users', 'username='******'TYPO3_DB']->fullQuoteStr('_cli_dlf', 'be_users') . t3lib_BEfunc::BEenableFields('be_users') . t3lib_BEfunc::deleteClause('be_users'), '', '', '1');
     if ($GLOBALS['TYPO3_DB']->sql_num_rows($result)) {
         list($be_user) = $GLOBALS['TYPO3_DB']->sql_fetch_row($result);
     } else {
         if (TYPO3_DLOG) {
             t3lib_div::devLog('[tx_dlf_document->save(' . $_pid . ', ' . $_core . ')] Backend user "_cli_dlf" not found or disabled', self::$extKey, SYSLOG_SEVERITY_ERROR);
         }
         return FALSE;
     }
     // Get UID for structure type.
     $structure = 0;
     $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery('tx_dlf_structures.uid AS uid', 'tx_dlf_structures', 'tx_dlf_structures.pid=' . intval($pid) . ' AND tx_dlf_structures.index_name=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($metadata['type'][0], 'tx_dlf_structures') . tx_dlf_helper::whereClause('tx_dlf_structures'), '', '', '1');
     if ($GLOBALS['TYPO3_DB']->sql_num_rows($result)) {
         list($structure) = $GLOBALS['TYPO3_DB']->sql_fetch_row($result);
     } else {
         if (TYPO3_DLOG) {
             t3lib_div::devLog('[tx_dlf_document->save(' . $_pid . ', ' . $_core . ')] Could not identify document/structure type', self::$extKey, SYSLOG_SEVERITY_ERROR);
         }
         return FALSE;
     }
     $metadata['type'][0] = $structure;
     // Get UIDs for collections.
     $collections = array();
     $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery('tx_dlf_collections.index_name AS index_name,tx_dlf_collections.uid AS uid', 'tx_dlf_collections', 'tx_dlf_collections.pid=' . intval($pid) . ' AND tx_dlf_collections.cruser_id=' . intval($be_user) . ' AND tx_dlf_collections.fe_cruser_id=0' . tx_dlf_helper::whereClause('tx_dlf_collections'), '', '', '');
     for ($i = 0, $j = $GLOBALS['TYPO3_DB']->sql_num_rows($result); $i < $j; $i++) {
         $resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result);
         $collUid[$resArray['index_name']] = $resArray['uid'];
     }
     foreach ($metadata['collection'] as $collection) {
         if (!empty($collUid[$collection])) {
             // Add existing collection's UID.
             $collections[] = $collUid[$collection];
         } else {
             // Insert new collection.
             $collNewUid = uniqid('NEW');
             $collData['tx_dlf_collections'][$collNewUid] = array('pid' => $pid, 'label' => $collection, 'index_name' => $collection, 'oai_name' => !empty($conf['publishNewCollections']) ? $collection : '', 'description' => '', 'documents' => 0, 'owner' => 0, 'status' => 0);
             $substUid = tx_dlf_helper::processDB($collData);
             // Prevent double insertion.
             unset($collData);
             // Add new collection's UID.
             $collections[] = $substUid[$collNewUid];
             if (!defined('TYPO3_cliMode')) {
                 $message = t3lib_div::makeInstance('t3lib_FlashMessage', htmlspecialchars(sprintf(tx_dlf_helper::getLL('flash.newCollection'), $collection, $substUid[$collNewUid])), tx_dlf_helper::getLL('flash.attention', TRUE), t3lib_FlashMessage::INFO, TRUE);
                 t3lib_FlashMessageQueue::addMessage($message);
             }
         }
     }
     // Preserve user-defined collections.
     $result = $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query('tx_dlf_collections.uid AS uid', 'tx_dlf_documents', 'tx_dlf_relations', 'tx_dlf_collections', 'AND tx_dlf_documents.pid=' . intval($pid) . ' AND tx_dlf_collections.pid=' . intval($pid) . ' AND tx_dlf_documents.uid=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->uid, 'tx_dlf_documents') . ' AND NOT (tx_dlf_collections.cruser_id=' . intval($be_user) . ' AND tx_dlf_collections.fe_cruser_id=0) AND tx_dlf_relations.ident=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('docs_colls', 'tx_dlf_relations'), '', '', '');
     for ($i = 0, $j = $GLOBALS['TYPO3_DB']->sql_num_rows($result); $i < $j; $i++) {
         list($collections[]) = $GLOBALS['TYPO3_DB']->sql_fetch_row($result);
     }
     $metadata['collection'] = $collections;
     // Get UID for owner.
     $owner = 0;
     $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery('tx_dlf_libraries.uid AS uid', 'tx_dlf_libraries', 'tx_dlf_libraries.pid=' . intval($pid) . ' AND tx_dlf_libraries.index_name=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($metadata['owner'][0], 'tx_dlf_libraries') . tx_dlf_helper::whereClause('tx_dlf_libraries'), '', '', '1');
     if ($GLOBALS['TYPO3_DB']->sql_num_rows($result)) {
         list($owner) = $GLOBALS['TYPO3_DB']->sql_fetch_row($result);
     } else {
         // Insert new library.
         $libNewUid = uniqid('NEW');
         $libData['tx_dlf_libraries'][$libNewUid] = array('pid' => $pid, 'label' => $metadata['owner'][0], 'index_name' => $metadata['owner'][0], 'website' => '', 'contact' => '', 'image' => '', 'oai_label' => '', 'oai_base' => '', 'opac_label' => '', 'opac_base' => '', 'union_label' => '', 'union_base' => '');
         $substUid = tx_dlf_helper::processDB($libData);
         // Add new library's UID.
         $owner = $substUid[$libNewUid];
         if (!defined('TYPO3_cliMode')) {
             $message = t3lib_div::makeInstance('t3lib_FlashMessage', htmlspecialchars(sprintf(tx_dlf_helper::getLL('flash.newLibrary'), $metadata['owner'][0], $owner)), tx_dlf_helper::getLL('flash.attention', TRUE), t3lib_FlashMessage::INFO, TRUE);
             t3lib_FlashMessageQueue::addMessage($message);
         }
     }
     $metadata['owner'][0] = $owner;
     // Load table of contents.
     $this->_getTableOfContents();
     // Get UID of superior document.
     $partof = 0;
     if (!empty($this->tableOfContents[0]['points']) && $this->tableOfContents[0]['points'] != $this->location && !tx_dlf_helper::testInt($this->tableOfContents[0]['points'])) {
         $superior =& tx_dlf_document::getInstance($this->tableOfContents[0]['points'], $pid);
         if ($superior->ready) {
             if ($superior->pid != $pid) {
                 $superior->save($pid, $core);
             }
             $partof = $superior->uid;
         }
     }
     // Use the date of publication as alternative sorting metric for parts of multi-part works.
     if (!empty($partof)) {
         if (empty($metadata['volume'][0]) && !empty($metadata['year'][0])) {
             $metadata['volume'] = $metadata['year'];
         }
         if (empty($metadata['volume_sorting'][0])) {
             if (!empty($metadata['year_sorting'][0])) {
                 $metadata['volume_sorting'][0] = $metadata['year_sorting'][0];
             } elseif (!empty($metadata['year'][0])) {
                 $metadata['volume_sorting'][0] = $metadata['year'][0];
             }
         }
     }
     // Get metadata for lists and sorting.
     $listed = array();
     $sortable = array();
     $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.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($pid) . tx_dlf_helper::whereClause('tx_dlf_metadata'), '', '', '');
     while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
         if (!empty($metadata[$resArray['index_name']])) {
             if ($resArray['is_listed']) {
                 $listed[$resArray['index_name']] = $metadata[$resArray['index_name']];
             }
             if ($resArray['is_sortable']) {
                 $sortable[$resArray['index_name']] = $metadata[$resArray['index_name']][0];
             }
         }
     }
     // Fill data array.
     $data['tx_dlf_documents'][$this->uid] = array('pid' => $pid, $GLOBALS['TCA']['tx_dlf_documents']['ctrl']['enablecolumns']['starttime'] => 0, $GLOBALS['TCA']['tx_dlf_documents']['ctrl']['enablecolumns']['endtime'] => 0, 'prod_id' => $metadata['prod_id'][0], 'location' => $this->location, 'record_id' => $metadata['record_id'][0], 'opac_id' => $metadata['opac_id'][0], 'union_id' => $metadata['union_id'][0], 'urn' => $metadata['urn'][0], 'purl' => $metadata['purl'][0], 'title' => $metadata['title'][0], 'title_sorting' => $metadata['title_sorting'][0], 'author' => implode('; ', $metadata['author']), 'year' => implode('; ', $metadata['year']), 'place' => implode('; ', $metadata['place']), 'thumbnail' => $this->_getThumbnail(TRUE), 'metadata' => serialize($listed), 'metadata_sorting' => serialize($sortable), 'structure' => $metadata['type'][0], 'partof' => $partof, 'volume' => $metadata['volume'][0], 'volume_sorting' => $metadata['volume_sorting'][0], 'collections' => $metadata['collection'], 'owner' => $metadata['owner'][0], 'solrcore' => $core, 'status' => 0);
     // Unhide hidden documents.
     if (!empty($conf['unhideOnIndex'])) {
         $data['tx_dlf_documents'][$this->uid][$GLOBALS['TCA']['tx_dlf_documents']['ctrl']['enablecolumns']['disabled']] = 0;
     }
     // Process data.
     $newIds = tx_dlf_helper::processDB($data);
     // Replace placeholder with actual UID.
     if (strpos($this->uid, 'NEW') === 0) {
         $this->uid = $newIds[$this->uid];
         $this->pid = $pid;
         $this->parentId = $partof;
     }
     if (!defined('TYPO3_cliMode')) {
         $message = t3lib_div::makeInstance('t3lib_FlashMessage', htmlspecialchars(sprintf(tx_dlf_helper::getLL('flash.documentSaved'), $metadata['title'][0], $this->uid)), tx_dlf_helper::getLL('flash.done', TRUE), t3lib_FlashMessage::OK, TRUE);
         t3lib_FlashMessageQueue::addMessage($message);
     }
     // Add document to index.
     if ($core) {
         tx_dlf_indexing::add($this, $core);
     } else {
         if (TYPO3_DLOG) {
             t3lib_div::devLog('[tx_dlf_document->save(' . $_pid . ', ' . $_core . ')] Invalid UID "' . $core . '" for Solr core', self::$extKey, SYSLOG_SEVERITY_NOTICE);
         }
     }
     return TRUE;
 }
Example #8
0
 /**
  * Main function of the module
  *
  * @access	public
  *
  * @return	void
  */
 public function main()
 {
     // Is the user allowed to access this page?
     $access = is_array($this->pageInfo) || $GLOBALS['BE_USER']->isAdmin();
     if ($this->id && $access) {
         // Increase max_execution_time and max_input_time for large documents.
         if (!ini_get('safe_mode')) {
             ini_set('max_execution_time', '0');
             ini_set('max_input_time', '-1');
         }
         switch ($this->CMD) {
             case 'indexFile':
                 if (!empty($this->data['id']) && isset($this->data['core'])) {
                     // Save document to database and index.
                     $doc =& tx_dlf_document::getInstance($this->data['id'], $this->id, TRUE);
                     if ($doc->ready) {
                         $doc->save($this->id, $this->data['core']);
                     } else {
                         $_message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Messaging\\FlashMessage', htmlspecialchars(sprintf(tx_dlf_helper::getLL('flash.fileNotLoaded'), $this->data['id'])), tx_dlf_helper::getLL('flash.error', TRUE), \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR, TRUE);
                         tx_dlf_helper::addMessage($_message);
                     }
                 }
                 break;
             case 'reindexDocs':
                 if (isset($this->data['core'])) {
                     if (!empty($this->data['collection'])) {
                         // Get all documents in this collection.
                         $_result = $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query('tx_dlf_documents.title AS title,tx_dlf_documents.uid AS uid', 'tx_dlf_documents', 'tx_dlf_relations', 'tx_dlf_collections', 'AND tx_dlf_documents.pid=' . intval($this->id) . ' AND tx_dlf_collections.uid=' . intval($this->data['collection']) . ' AND tx_dlf_relations.ident=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('docs_colls', 'tx_dlf_relations') . tx_dlf_helper::whereClause('tx_dlf_documents') . tx_dlf_helper::whereClause('tx_dlf_collections'), 'tx_dlf_documents.uid', '', '');
                     } else {
                         // Get all documents.
                         $_result = $GLOBALS['TYPO3_DB']->exec_SELECTquery('tx_dlf_documents.title AS title,tx_dlf_documents.uid AS uid', 'tx_dlf_documents', 'tx_dlf_documents.pid=' . intval($this->id) . tx_dlf_helper::whereClause('tx_dlf_documents'), '', '', '');
                     }
                     // Save them as a list object in user's session.
                     $elements = array();
                     while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($_result)) {
                         $elements[] = array($resArray['uid'], $resArray['title']);
                     }
                     $this->list = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('tx_dlf_list', $elements);
                     // Start index looping.
                     if (count($this->list) > 0) {
                         $this->indexLoop();
                     }
                 }
                 break;
             case 'indexLoop':
                 // Refresh user's session to prevent session timeout.
                 $GLOBALS['BE_USER']->fetchUserSession();
                 // Get document list from user's session.
                 $this->list = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('tx_dlf_list');
                 // Continue index looping.
                 if (count($this->list) > 0 && isset($this->data['core'])) {
                     $this->indexLoop();
                 } else {
                     $_message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Messaging\\FlashMessage', tx_dlf_helper::getLL('flash.seeLog', TRUE), tx_dlf_helper::getLL('flash.done', TRUE), \TYPO3\CMS\Core\Messaging\FlashMessage::OK, TRUE);
                     tx_dlf_helper::addMessage($_message);
                 }
                 break;
         }
         $this->markerArray['CONTENT'] .= tx_dlf_helper::renderFlashMessages();
         switch ($this->MOD_SETTINGS['function']) {
             case 'indexFile':
                 $this->markerArray['CONTENT'] .= $this->getFileForm();
                 break;
             case 'reindexDoc':
                 $this->markerArray['CONTENT'] .= $this->getDocList();
                 break;
             case 'reindexDocs':
                 $this->markerArray['CONTENT'] .= $this->getCollList();
                 break;
         }
     } else {
         // TODO: Ă„ndern!
         $this->markerArray['CONTENT'] .= 'You are not allowed to access this page or have not selected a page, yet.';
     }
     $this->printContent();
 }
 /**
  * Renders all sub-entries of one entry
  *
  * @access	protected
  *
  * @param	integer		$number: The number of the entry
  * @param	string		$template: Parsed template subpart
  *
  * @return	string		The rendered entries ready for output
  */
 protected function getSubEntries($number, $template)
 {
     $content = '';
     foreach ($this->list[$number]['subparts'] as $subpart) {
         $markerArray['###SUBMETADATA###'] = '';
         $markerArray['###SUBTHUMBNAIL###'] = '';
         $markerArray['###SUBPREVIEW###'] = '';
         $imgAlt = '';
         foreach ($this->metadata as $index_name => $metaConf) {
             $parsedValue = '';
             $fieldwrap = $this->parseTS($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 = tx_dlf_document::getTitle($subpart['uid'], TRUE);
                         if (!empty($superiorTitle)) {
                             $value = '[' . $superiorTitle . ']';
                         }
                     }
                     // Set fake title if still not present.
                     if (empty($value)) {
                         $value = $this->pi_getLL('noTitle');
                     }
                     $imgAlt = htmlspecialchars($value);
                     $additionalParams = array('id' => $subpart['uid'], 'page' => $subpart['page']);
                     $conf = array('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)) {
                     $value = htmlspecialchars(tx_dlf_helper::translate($value, 'tx_dlf_libraries', $this->conf['pages']));
                     // Translate document type.
                 } elseif ($index_name == 'type' && !empty($value)) {
                     $_value = $value;
                     $value = htmlspecialchars(tx_dlf_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)) {
                     $value = htmlspecialchars(tx_dlf_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'];
         }
         $content .= $this->cObj->substituteMarkerArray($template['subentry'], $markerArray);
     }
     return $this->cObj->substituteSubpart($this->cObj->getSubpart($this->template, '###SUBTEMPLATE###'), '###SUBENTRY###', $content, TRUE);
 }
 /**
  * The main method of the PlugIn
  *
  * @access	public
  *
  * @param	string		$content: The PlugIn content
  * @param	array		$conf: The PlugIn configuration
  *
  * @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(t3lib_div::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']) . tx_dlf_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']) || t3lib_div::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 . tx_dlf_helper::whereClause('tx_dlf_documents') . tx_dlf_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'])) {
                     $superiorTitle = tx_dlf_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 = array('parameter' => $this->conf['targetPid'], 'forceAbsoluteUrl' => 1, 'additionalParams' => t3lib_div::implodeArrayForUrl($this->prefixId, array('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.
     t3lib_div::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;
 }
 /**
  * Prepares the metadata array for output
  *
  * @access	protected
  *
  * @param	array		$metadataArray: The metadata array
  *
  * @return	string		The metadata array ready for output
  */
 protected function printMetadata(array $metadataArray)
 {
     // Load template file.
     if (!empty($this->conf['templateFile'])) {
         $this->template = $this->cObj->getSubpart($this->cObj->fileResource($this->conf['templateFile']), '###TEMPLATE###');
     } else {
         $this->template = $this->cObj->getSubpart($this->cObj->fileResource('EXT:dlf/plugins/metadata/template.tmpl'), '###TEMPLATE###');
     }
     $output = '';
     $subpart['block'] = $this->cObj->getSubpart($this->template, '###BLOCK###');
     // Get list of metadata to show.
     $metaList = array();
     $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']) . tx_dlf_helper::whereClause('tx_dlf_metadata'), '', 'tx_dlf_metadata.sorting', '');
     while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
         if ($this->conf['showFull'] || $resArray['is_listed']) {
             $metaList[$resArray['index_name']] = array('wrap' => $resArray['wrap'], 'label' => tx_dlf_helper::translate($resArray['index_name'], 'tx_dlf_metadata', $this->conf['pages']));
         }
     }
     // 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 = tx_dlf_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, array($this->prefixId => array('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(tx_dlf_helper::translate($value, 'tx_dlf_libraries', $this->conf['pages']));
                 } elseif ($index_name == 'type' && !empty($value)) {
                     // Translate document type.
                     $value = htmlspecialchars(tx_dlf_helper::translate($value, 'tx_dlf_structures', $this->conf['pages']));
                 } elseif ($index_name == 'collection' && !empty($value)) {
                     // Translate collection.
                     $value = htmlspecialchars(tx_dlf_helper::translate($value, 'tx_dlf_collections', $this->conf['pages']));
                 } elseif ($index_name == 'language' && !empty($value)) {
                     // Translate ISO 639 language code.
                     $value = htmlspecialchars(tx_dlf_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);
 }
 /**
  * Loads the current document into $this->doc
  *
  * @access	protected
  *
  * @return	void
  */
 protected function loadDocument()
 {
     // Check for required variable.
     if (!empty($this->piVars['id'])) {
         // Get instance of tx_dlf_document.
         $this->doc =& tx_dlf_document::getInstance($this->piVars['id']);
         if (!$this->doc->ready) {
             // Destroy the incomplete object.
             $this->doc = NULL;
             if (TYPO3_DLOG) {
                 \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_doctype->loadDocument()] Failed to load document with UID "' . $this->piVars['id'] . '"', $this->extKey, SYSLOG_SEVERITY_WARNING);
             }
         }
     } elseif (!empty($this->piVars['recordId'])) {
         // Get UID of document with given record identifier.
         $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery('tx_dlf_documents.uid', 'tx_dlf_documents', 'tx_dlf_documents.record_id=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->piVars['recordId'], 'tx_dlf_documents') . tx_dlf_helper::whereClause('tx_dlf_documents'), '', '', '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'];
             // Unset variable to avoid infinite looping.
             unset($this->piVars['recordId'], $_GET[$this->prefixId]['recordId']);
             // Try to load document.
             $this->loadDocument();
         } else {
             if (TYPO3_DLOG) {
                 \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_doctype->loadDocument()] Failed to load document with record ID "' . $this->piVars['recordId'] . '"', $this->extKey, SYSLOG_SEVERITY_WARNING);
             }
         }
     }
 }
 /**
  * Processes a logical unit (and its children) for the Solr index
  *
  * @access	protected
  *
  * @param	tx_dlf_document		&$doc: The METS document
  * @param	array		$logicalUnit: Array of the logical unit to process
  *
  * @return	integer		0 on success or 1 on failure
  */
 protected static function process(tx_dlf_document &$doc, array $logicalUnit)
 {
     $errors = 0;
     // Get metadata for logical unit.
     $metadata = $doc->metadataArray[$logicalUnit['id']];
     if (!empty($metadata)) {
         // Load class.
         if (!class_exists('Apache_Solr_Document')) {
             require_once t3lib_div::getFileAbsFileName('EXT:' . self::$extKey . '/lib/SolrPhpClient/Apache/Solr/Document.php');
         }
         // Create new Solr document.
         $solrDoc = new Apache_Solr_Document();
         // Create unique identifier from document's UID and unit's XML ID.
         $solrDoc->setField('id', $doc->uid . $logicalUnit['id']);
         $solrDoc->setField('uid', $doc->uid);
         $solrDoc->setField('pid', $doc->pid);
         if (tx_dlf_helper::testInt($logicalUnit['points'])) {
             $solrDoc->setField('page', $logicalUnit['points']);
         }
         if ($logicalUnit['id'] == $doc->toplevelId) {
             $solrDoc->setField('thumbnail', $doc->thumbnail);
         } elseif (!empty($logicalUnit['thumbnailId'])) {
             $solrDoc->setField('thumbnail', $doc->getFileLocation($logicalUnit['thumbnailId']));
         }
         $solrDoc->setField('partof', $doc->parentId);
         $solrDoc->setField('sid', $logicalUnit['id']);
         $solrDoc->setField('toplevel', in_array($logicalUnit['type'], self::$toplevel));
         $solrDoc->setField('type', $logicalUnit['type'], self::$fields['fieldboost']['type']);
         $solrDoc->setField('title', $metadata['title'][0], self::$fields['fieldboost']['title']);
         $solrDoc->setField('volume', $metadata['volume'][0], self::$fields['fieldboost']['volume']);
         $autocomplete = array();
         foreach ($metadata as $index_name => $data) {
             if (!empty($data) && 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'])) {
                     // Add sortable fields to index.
                     $solrDoc->setField($index_name . '_sorting', $metadata[$index_name . '_sorting'][0]);
                 }
                 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['autocompleted'])) {
                     $autocomplete = array_merge($autocomplete, $data);
                 }
             }
         }
         // Add autocomplete values to index.
         if (!empty($autocomplete)) {
             $solrDoc->setField('autocomplete', $autocomplete);
         }
         try {
             self::$solr->service->addDocument($solrDoc);
         } catch (Exception $e) {
             if (!defined('TYPO3_cliMode')) {
                 $message = t3lib_div::makeInstance('t3lib_FlashMessage', tx_dlf_helper::getLL('flash.solrException', TRUE) . '<br />' . htmlspecialchars($e->getMessage()), tx_dlf_helper::getLL('flash.error', TRUE), t3lib_FlashMessage::ERROR, TRUE);
                 t3lib_FlashMessageQueue::addMessage($message);
             }
             return 1;
         }
     }
     // Check for child elements...
     if (!empty($logicalUnit['children'])) {
         foreach ($logicalUnit['children'] as $child) {
             if (!$errors) {
                 // ...and process them, too.
                 $errors = self::process($doc, $child);
             } else {
                 break;
             }
         }
     }
     return $errors;
 }