/**
  * 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;
     }
 }
 /**
  * Connects to Solr server.
  *
  * @access	protected
  *
  * @param	integer		$core: UID of the Solr core
  * @param	integer		$pid: UID of the configuration page
  *
  * @return	boolean		TRUE on success or FALSE on failure
  */
 protected static function solrConnect($core, $pid = 0)
 {
     // Get Solr instance.
     if (!self::$solr) {
         // Connect to Solr server.
         if (self::$solr = tx_dlf_solr::getInstance($core)) {
             // Load indexing configuration if needed.
             if ($pid) {
                 self::loadIndexConf($pid);
             }
         } else {
             return FALSE;
         }
     }
     return TRUE;
 }
 /**
  * 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;
 }