function isValidForUser($locationCode, $eContentFieldData)
 {
     $sharing = $this->getSharing($locationCode, $eContentFieldData);
     if ($sharing == 'shared') {
         $searchLibrary = Library::getSearchLibrary();
         if ($searchLibrary == null || $searchLibrary->econtentLocationsToInclude == 'all' || strlen($searchLibrary->econtentLocationsToInclude) == 0 || strpos($searchLibrary->econtentLocationsToInclude, $locationCode) !== FALSE) {
             return true;
         } else {
             return false;
         }
     } else {
         if ($sharing == 'library') {
             $searchLibrary = Library::getSearchLibrary();
             if ($searchLibrary == null || $searchLibrary->includeOutOfSystemExternalLinks || strlen($searchLibrary->ilsCode) > 0 && strpos($locationCode, $searchLibrary->ilsCode) === 0) {
                 return true;
             } else {
                 return false;
             }
         } else {
             $searchLibrary = Library::getSearchLibrary();
             $searchLocation = Location::getSearchLocation();
             if ($searchLibrary->includeOutOfSystemExternalLinks || strpos($locationCode, $searchLocation->code) === 0) {
                 return true;
             } else {
                 return false;
             }
         }
     }
 }
 function isValidForUser($locationCode, $eContentFieldData)
 {
     $sharing = $this->getSharing($locationCode, $eContentFieldData);
     if ($sharing == 'shared') {
         return true;
     } else {
         if ($sharing == 'library') {
             $searchLibrary = Library::getSearchLibrary();
             if ($searchLibrary == null || strlen($searchLibrary->ilsCode) > 0 && strpos($locationCode, $searchLibrary->ilsCode) === 0) {
                 global $user;
                 if ($user) {
                     $patronHomeLibrary = Library::getPatronHomeLibrary();
                     return $patronHomeLibrary == null || strlen($patronHomeLibrary->ilsCode) > 0 && strpos($locationCode, $patronHomeLibrary->ilsCode) === 0;
                 } else {
                     return true;
                 }
             } else {
                 return false;
             }
         } else {
             //Just share with the specific location
             $searchLocation = Location::getSearchLocation();
             if (!$searchLocation) {
                 return true;
             } elseif (strpos($locationCode, $searchLocation->code) === 0) {
                 return true;
             } else {
                 return false;
             }
         }
     }
 }
Esempio n. 3
0
 public function getBrowseResults($browseType, $lookFor, $relativePage = 0, $resultsPerPage = 20)
 {
     global $configArray;
     global $timer;
     //Normalize the search term
     $lookFor = strtolower($lookFor);
     $results = array();
     //Query to find the first record that matches the
     if (!in_array($browseType, array('title', 'author', 'callnumber', 'subject'))) {
         return array('success' => false, 'message' => "The browse type {$browseType} is not a valid browse type.");
     }
     $browseTable = $browseType . '_browse';
     $browseField = 'sortValue';
     mysql_select_db($configArray['Database']['database_vufind_dbname']);
     global $librarySingleton;
     global $locationSingleton;
     $searchLibrary = Library::getSearchLibrary();
     $libaryToBrowse = -1;
     $scope = 0;
     $scopeId = '';
     if (isset($searchLibrary) && $searchLibrary->restrictSearchByLibrary) {
         $libaryToBrowse = $searchLibrary->libraryId;
         $scope = 1;
         $scopeId = $searchLibrary->subdomain;
     }
     //Get the count of the rows in the database
     if ($scope == 0) {
         $scopingFilter = "scope = {$scope} and scopeId= -1";
     } elseif ($scope = 1) {
         $scopingFilter = "scope = 1 and scopeId={$libaryToBrowse}";
     }
     $query = "SELECT * FROM {$browseTable}_metadata WHERE {$scopingFilter}";
     $result = mysql_query($query);
     // @codeCoverageIgnoreStart
     if ($result == FALSE) {
         return array('success' => false, 'message' => "Sorry, unable to browse {$browseType} right now, please try again later.");
     }
     // @codeCoverageIgnoreEnd
     $timer->logTime("Loaded metadata");
     $metaData = mysql_fetch_assoc($result);
     //echo("NumRows = {$metaData['numResults']}");
     //Cleanup our look for value
     $lookFor = strtolower($lookFor);
     $lookFor = preg_replace('/\\W/', ' ', $lookFor);
     $lookFor = preg_replace("/^(a|an|the|el|la)\\s/", '', $lookFor);
     $lookFor = preg_replace('/\\s{2,}/', ' ', $lookFor);
     return $this->loadBrowseItems($lookFor, $browseType, $browseTable, $scopingFilter, $scope, $scopeId, $relativePage, $resultsPerPage, $metaData);
 }
Esempio n. 4
0
 function launch()
 {
     global $interface;
     global $configArray;
     global $timer;
     global $analytics;
     /** @var string|LibrarySearchSource|LocationSearchSource $searchSource */
     $searchSource = isset($_REQUEST['searchSource']) ? $_REQUEST['searchSource'] : 'local';
     if (preg_match('/library\\d+/', $searchSource)) {
         $trimmedId = str_replace('library', '', $searchSource);
         $searchSourceObj = new LibrarySearchSource();
         $searchSourceObj->id = $trimmedId;
         if ($searchSourceObj->find(true)) {
             $searchSource = $searchSourceObj;
         }
     }
     if (isset($_REQUEST['replacementTerm'])) {
         $replacementTerm = $_REQUEST['replacementTerm'];
         $interface->assign('replacementTerm', $replacementTerm);
         $oldTerm = $_REQUEST['lookfor'];
         $interface->assign('oldTerm', $oldTerm);
         $_REQUEST['lookfor'] = $replacementTerm;
         $_GET['lookfor'] = $replacementTerm;
         $oldSearchUrl = $_SERVER['REQUEST_URI'];
         $oldSearchUrl = str_replace('replacementTerm=' . urlencode($replacementTerm), 'disallowReplacements', $oldSearchUrl);
         $interface->assign('oldSearchUrl', $oldSearchUrl);
     }
     // Include Search Engine Class
     require_once ROOT_DIR . '/sys/Solr.php';
     $timer->logTime('Include search engine');
     //Check to see if the year has been set and if so, convert to a filter and resend.
     $dateFilters = array('publishDate');
     foreach ($dateFilters as $dateFilter) {
         if (isset($_REQUEST[$dateFilter . 'yearfrom']) || isset($_REQUEST[$dateFilter . 'yearto'])) {
             $queryParams = $_GET;
             $yearFrom = preg_match('/^\\d{2,4}$/', $_REQUEST[$dateFilter . 'yearfrom']) ? $_REQUEST[$dateFilter . 'yearfrom'] : '*';
             $yearTo = preg_match('/^\\d{2,4}$/', $_REQUEST[$dateFilter . 'yearto']) ? $_REQUEST[$dateFilter . 'yearto'] : '*';
             if (strlen($yearFrom) == 2) {
                 $yearFrom = '19' . $yearFrom;
             } else {
                 if (strlen($yearFrom) == 3) {
                     $yearFrom = '0' . $yearFrom;
                 }
             }
             if (strlen($yearTo) == 2) {
                 $yearTo = '19' . $yearTo;
             } else {
                 if (strlen($yearFrom) == 3) {
                     $yearTo = '0' . $yearTo;
                 }
             }
             if ($yearTo != '*' && $yearFrom != '*' && $yearTo < $yearFrom) {
                 $tmpYear = $yearTo;
                 $yearTo = $yearFrom;
                 $yearFrom = $tmpYear;
             }
             unset($queryParams['module']);
             unset($queryParams['action']);
             unset($queryParams[$dateFilter . 'yearfrom']);
             unset($queryParams[$dateFilter . 'yearto']);
             if (!isset($queryParams['sort'])) {
                 $queryParams['sort'] = 'year';
             }
             $queryParamStrings = array();
             foreach ($queryParams as $paramName => $queryValue) {
                 if (is_array($queryValue)) {
                     foreach ($queryValue as $arrayValue) {
                         if (strlen($arrayValue) > 0) {
                             $queryParamStrings[] = $paramName . '[]=' . $arrayValue;
                         }
                     }
                 } else {
                     if (strlen($queryValue)) {
                         $queryParamStrings[] = $paramName . '=' . $queryValue;
                     }
                 }
             }
             if ($yearFrom != '*' || $yearTo != '*') {
                 $queryParamStrings[] = "&filter[]={$dateFilter}:[{$yearFrom}+TO+{$yearTo}]";
             }
             $queryParamString = join('&', $queryParamStrings);
             header("Location: {$configArray['Site']['path']}/Search/Results?{$queryParamString}");
             exit;
         }
     }
     $rangeFilters = array('lexile_score', 'accelerated_reader_reading_level', 'accelerated_reader_point_value');
     foreach ($rangeFilters as $filter) {
         if (isset($_REQUEST[$filter . 'from']) && strlen($_REQUEST[$filter . 'from']) > 0 || isset($_REQUEST[$filter . 'to']) && strlen($_REQUEST[$filter . 'to']) > 0) {
             $queryParams = $_GET;
             $from = isset($_REQUEST[$filter . 'from']) && preg_match('/^\\d*(\\.\\d*)?$/', $_REQUEST[$filter . 'from']) ? $_REQUEST[$filter . 'from'] : '*';
             $to = isset($_REQUEST[$filter . 'to']) && preg_match('/^\\d*(\\.\\d*)?$/', $_REQUEST[$filter . 'to']) ? $_REQUEST[$filter . 'to'] : '*';
             if ($to != '*' && $from != '*' && $to < $from) {
                 $tmpFilter = $to;
                 $to = $from;
                 $from = $tmpFilter;
             }
             unset($queryParams['module']);
             unset($queryParams['action']);
             unset($queryParams[$filter . 'from']);
             unset($queryParams[$filter . 'to']);
             $queryParamStrings = array();
             foreach ($queryParams as $paramName => $queryValue) {
                 if (is_array($queryValue)) {
                     foreach ($queryValue as $arrayValue) {
                         if (strlen($arrayValue) > 0) {
                             $queryParamStrings[] = $paramName . '[]=' . $arrayValue;
                         }
                     }
                 } else {
                     if (strlen($queryValue)) {
                         $queryParamStrings[] = $paramName . '=' . $queryValue;
                     }
                 }
             }
             if ($from != '*' || $to != '*') {
                 $queryParamStrings[] = "&filter[]={$filter}:[{$from}+TO+{$to}]";
             }
             $queryParamString = join('&', $queryParamStrings);
             header("Location: {$configArray['Site']['path']}/Search/Results?{$queryParamString}");
             exit;
         }
     }
     // Initialise from the current search globals
     /** @var SearchObject_Solr $searchObject */
     $searchObject = SearchObjectFactory::initSearchObject();
     $searchObject->init($searchSource);
     $timer->logTime("Init Search Object");
     // Build RSS Feed for Results (if requested)
     if ($searchObject->getView() == 'rss') {
         // Throw the XML to screen
         echo $searchObject->buildRSS();
         // And we're done
         exit;
     } else {
         if ($searchObject->getView() == 'excel') {
             // Throw the Excel spreadsheet to screen for download
             echo $searchObject->buildExcel();
             // And we're done
             exit;
         }
     }
     // TODO : Investigate this... do we still need
     // If user wants to print record show directly print-dialog box
     if (isset($_GET['print'])) {
         $interface->assign('print', true);
     }
     // Set Interface Variables
     //   Those we can construct BEFORE the search is executed
     $interface->setPageTitle('Search Results');
     $interface->assign('sortList', $searchObject->getSortList());
     $interface->assign('rssLink', $searchObject->getRSSUrl());
     $interface->assign('excelLink', $searchObject->getExcelUrl());
     $timer->logTime('Setup Search');
     // Process Search
     $result = $searchObject->processSearch(true, true);
     if (PEAR_Singleton::isError($result)) {
         PEAR_Singleton::raiseError($result->getMessage());
     }
     $timer->logTime('Process Search');
     // Some more variables
     //   Those we can construct AFTER the search is executed, but we need
     //   no matter whether there were any results
     $interface->assign('qtime', round($searchObject->getQuerySpeed(), 2));
     $interface->assign('spellingSuggestions', $searchObject->getSpellingSuggestions());
     $interface->assign('lookfor', $searchObject->displayQuery());
     $interface->assign('searchType', $searchObject->getSearchType());
     // Will assign null for an advanced search
     $interface->assign('searchIndex', $searchObject->getSearchIndex());
     // We'll need recommendations no matter how many results we found:
     $interface->assign('topRecommendations', $searchObject->getRecommendationsTemplates('top'));
     $interface->assign('sideRecommendations', $searchObject->getRecommendationsTemplates('side'));
     // 'Finish' the search... complete timers and log search history.
     $searchObject->close();
     $interface->assign('time', round($searchObject->getTotalSpeed(), 2));
     // Show the save/unsave code on screen
     // The ID won't exist until after the search has been put in the search history
     //    so this needs to occur after the close() on the searchObject
     $interface->assign('showSaved', true);
     $interface->assign('savedSearch', $searchObject->isSavedSearch());
     $interface->assign('searchId', $searchObject->getSearchId());
     $currentPage = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1;
     $interface->assign('page', $currentPage);
     //Enable and disable functionality based on library settings
     //This must be done before we process each result
     global $library;
     /** @var Location $locationSingleton */
     global $locationSingleton;
     $location = $locationSingleton->getActiveLocation();
     $showHoldButton = 1;
     $showHoldButtonInSearchResults = 1;
     $interface->assign('showNotInterested', false);
     if (isset($library) && $location != null) {
         $interface->assign('showFavorites', $library->showFavorites);
         $interface->assign('showComments', $library->showComments);
         $showHoldButton = $location->showHoldButton == 1 && $library->showHoldButton == 1 ? 1 : 0;
         $showHoldButtonInSearchResults = $location->showHoldButton == 1 && $library->showHoldButtonInSearchResults == 1 ? 1 : 0;
     } else {
         if ($location != null) {
             $interface->assign('showFavorites', 1);
             $showHoldButton = $location->showHoldButton;
         } else {
             if (isset($library)) {
                 $interface->assign('showFavorites', $library->showFavorites);
                 $showHoldButton = $library->showHoldButton;
                 $showHoldButtonInSearchResults = $library->showHoldButtonInSearchResults;
                 $interface->assign('showComments', $library->showComments);
             } else {
                 $interface->assign('showFavorites', 1);
                 $interface->assign('showComments', 1);
             }
         }
     }
     if ($showHoldButton == 0) {
         $showHoldButtonInSearchResults = 0;
     }
     $interface->assign('showHoldButton', $showHoldButtonInSearchResults);
     $interface->assign('page_body_style', 'sidebar_left');
     $interface->assign('overDriveVersion', isset($configArray['OverDrive']['interfaceVersion']) ? $configArray['OverDrive']['interfaceVersion'] : 1);
     //Check to see if we should show unscoped results
     $enableUnscopedSearch = false;
     $searchLibrary = Library::getSearchLibrary();
     if ($searchLibrary != null && $searchLibrary->showMarmotResultsAtEndOfSearch) {
         if (is_object($searchSource)) {
             $enableUnscopedSearch = $searchSource->catalogScoping != 'unscoped';
             $unscopedSearch = clone $searchObject;
         } else {
             $searchSources = new SearchSources();
             $searchOptions = $searchSources->getSearchSources();
             if (isset($searchOptions['marmot'])) {
                 $unscopedSearch = clone $searchObject;
                 $enableUnscopedSearch = true;
             }
         }
     }
     $enableProspectorIntegration = isset($configArray['Content']['Prospector']) ? $configArray['Content']['Prospector'] : false;
     $showRatings = 1;
     $showProspectorResultsAtEndOfSearch = true;
     if (isset($library)) {
         $enableProspectorIntegration = $library->enablePospectorIntegration == 1;
         $showRatings = $library->showRatings;
         $showProspectorResultsAtEndOfSearch = $library->showProspectorResultsAtEndOfSearch == 1;
     }
     $interface->assign('showRatings', $showRatings);
     $numProspectorTitlesToLoad = 0;
     $numUnscopedTitlesToLoad = 0;
     // Save the ID of this search to the session so we can return to it easily:
     $_SESSION['lastSearchId'] = $searchObject->getSearchId();
     // Save the URL of this search to the session so we can return to it easily:
     $_SESSION['lastSearchURL'] = $searchObject->renderSearchUrl();
     if (is_object($searchSource)) {
         $translatedSearch = $searchSource->label;
     } else {
         $allSearchSources = SearchSources::getSearchSources();
         if (!isset($allSearchSources[$searchSource]) && $searchSource == 'marmot') {
             $searchSource = 'local';
         }
         $translatedSearch = $allSearchSources[$searchSource]['name'];
     }
     $analytics->addSearch($translatedSearch, $searchObject->displayQuery(), $searchObject->isAdvanced(), $searchObject->getFullSearchType(), $searchObject->hasAppliedFacets(), $searchObject->getResultTotal());
     if ($searchObject->getResultTotal() < 1) {
         //We didn't find anything.  Look for search Suggestions
         //Don't try to find suggestions if facets were applied
         $autoSwitchSearch = false;
         $disallowReplacements = isset($_REQUEST['disallowReplacements']) || isset($_REQUEST['replacementTerm']);
         if (!$disallowReplacements && (!isset($facetSet) || count($facetSet) == 0)) {
             require_once ROOT_DIR . '/services/Search/lib/SearchSuggestions.php';
             $searchSuggestions = new SearchSuggestions();
             $commonSearches = $searchSuggestions->getCommonSearchesMySql($searchObject->displayQuery(), $searchObject->getSearchIndex());
             //If the first search in the list is used 10 times more than the next, just show results for that
             $numSuggestions = count($commonSearches);
             if ($numSuggestions == 1) {
                 $autoSwitchSearch = true;
             } elseif ($numSuggestions >= 2) {
                 $firstTimesSearched = $commonSearches[0]['numSearches'];
                 $secondTimesSearched = $commonSearches[1]['numSearches'];
                 if ($firstTimesSearched / $secondTimesSearched > 10) {
                     $autoSwitchSearch = true;
                 }
             }
             $interface->assign('autoSwitchSearch', $autoSwitchSearch);
             if ($autoSwitchSearch) {
                 //Get search results for the new search
                 $interface->assign('oldTerm', $searchObject->displayQuery());
                 $interface->assign('newTerm', $commonSearches[0]['phrase']);
                 $thisUrl = $_SERVER['REQUEST_URI'];
                 $thisUrl = $thisUrl . "&replacementTerm=" . urlencode($commonSearches[0]['phrase']);
                 header("Location: " . $thisUrl);
                 exit;
             }
             $interface->assign('searchSuggestions', $commonSearches);
         }
         //Var for the IDCLREADER TEMPLATE
         $interface->assign('ButtonBack', true);
         $interface->assign('ButtonHome', true);
         $interface->assign('MobileTitle', 'No Results Found');
         // No record found
         $interface->setTemplate('list-none.tpl');
         $interface->assign('recordCount', 0);
         // Was the empty result set due to an error?
         $error = $searchObject->getIndexError();
         if ($error !== false) {
             // If it's a parse error or the user specified an invalid field, we
             // should display an appropriate message:
             if (stristr($error, 'org.apache.lucene.queryParser.ParseException') || preg_match('/^undefined field/', $error)) {
                 $interface->assign('parseError', true);
                 // Unexpected error -- let's treat this as a fatal condition.
             } else {
                 PEAR_Singleton::raiseError(new PEAR_Error('Unable to process query<br />' . 'Solr Returned: ' . $error));
             }
         }
         $numProspectorTitlesToLoad = 10;
         $numUnscopedTitlesToLoad = 10;
         $timer->logTime('no hits processing');
     } else {
         if ($searchObject->getResultTotal() == 1 && (strpos($searchObject->displayQuery(), 'id') === 0 || $searchObject->getSearchType() == 'id')) {
             //Redirect to the home page for the record
             $recordSet = $searchObject->getResultRecordSet();
             $record = reset($recordSet);
             $_SESSION['searchId'] = $searchObject->getSearchId();
             if ($record['recordtype'] == 'list') {
                 $listId = substr($record['id'], 4);
                 header("Location: " . $configArray['Site']['path'] . "/MyResearch/MyList/{$listId}");
                 exit;
             } elseif ($record['recordtype'] == 'econtentRecord') {
                 $shortId = str_replace('econtentRecord', '', $record['id']);
                 header("Location: " . $configArray['Site']['path'] . "/EcontentRecord/{$shortId}/Home");
                 exit;
             } else {
                 header("Location: " . $configArray['Site']['path'] . "/Record/{$record['id']}/Home");
                 exit;
             }
         } else {
             $timer->logTime('save search');
             // Assign interface variables
             $summary = $searchObject->getResultSummary();
             $interface->assign('recordCount', $summary['resultTotal']);
             $interface->assign('recordStart', $summary['startRecord']);
             $interface->assign('recordEnd', $summary['endRecord']);
             $facetSet = $searchObject->getFacetList();
             $interface->assign('facetSet', $facetSet);
             //Check to see if a format category is already set
             $categorySelected = false;
             if (isset($facetSet['top'])) {
                 foreach ($facetSet['top'] as $cluster) {
                     if ($cluster['label'] == 'Category') {
                         foreach ($cluster['list'] as $thisFacet) {
                             if ($thisFacet['isApplied']) {
                                 $categorySelected = true;
                             }
                         }
                     }
                 }
             }
             $interface->assign('categorySelected', $categorySelected);
             $timer->logTime('load selected category');
             // Big one - our results
             $recordSet = $searchObject->getResultRecordHTML();
             $interface->assign('recordSet', $recordSet);
             $timer->logTime('load result records');
             // Setup Display
             $interface->assign('sitepath', $configArray['Site']['path']);
             $interface->assign('subpage', 'Search/list-list.tpl');
             $interface->setTemplate('list.tpl');
             //Var for the IDCLREADER TEMPLATE
             $interface->assign('ButtonBack', true);
             $interface->assign('ButtonHome', true);
             $interface->assign('MobileTitle', 'Search Results');
             // Process Paging
             $link = $searchObject->renderLinkPageTemplate();
             $options = array('totalItems' => $summary['resultTotal'], 'fileName' => $link, 'perPage' => $summary['perPage']);
             $pager = new VuFindPager($options);
             $interface->assign('pageLinks', $pager->getLinks());
             if ($pager->isLastPage()) {
                 $numProspectorTitlesToLoad = 5;
                 $numUnscopedTitlesToLoad = 5;
             }
             $timer->logTime('finish hits processing');
         }
     }
     if ($numProspectorTitlesToLoad > 0 && $enableProspectorIntegration && $showProspectorResultsAtEndOfSearch) {
         $interface->assign('prospectorNumTitlesToLoad', $numProspectorTitlesToLoad);
         $interface->assign('prospectorSavedSearchId', $searchObject->getSearchId());
     } else {
         $interface->assign('prospectorNumTitlesToLoad', 0);
     }
     if ($enableUnscopedSearch && isset($unscopedSearch)) {
         $unscopedSearch->setLimit($numUnscopedTitlesToLoad * 4);
         $unscopedSearch->disableScoping();
         $unscopedSearch->processSearch(false, false);
         $numUnscopedResults = $unscopedSearch->getResultTotal();
         $interface->assign('numUnscopedResults', $numUnscopedResults);
         $unscopedSearchUrl = $unscopedSearch->renderSearchUrl();
         if (preg_match('/searchSource=(.*?)(?:&|$)/', $unscopedSearchUrl)) {
             $unscopedSearchUrl = preg_replace('/(.*searchSource=)(.*?)(&|$)(.*)/', '$1marmot$3$4', $unscopedSearchUrl);
             $unscopedSearchUrl = preg_replace('/&/', '&amp;', $unscopedSearchUrl);
         } else {
             $unscopedSearchUrl .= "&amp;searchSource=marmot";
         }
         $unscopedSearchUrl .= "&amp;shard=";
         $interface->assign('unscopedSearchUrl', $unscopedSearchUrl);
         if ($numUnscopedTitlesToLoad > 0) {
             $unscopedResults = $unscopedSearch->getSupplementalResultRecordHTML($searchObject->getResultRecordSet(), $numUnscopedTitlesToLoad, $searchObject->getResultTotal());
             $interface->assign('unscopedResults', $unscopedResults);
         }
     }
     //Determine whether or not materials request functionality should be enabled
     $interface->assign('enableMaterialsRequest', MaterialsRequest::enableMaterialsRequest());
     if ($configArray['Statistics']['enabled'] && isset($_GET['lookfor'])) {
         require_once ROOT_DIR . '/Drivers/marmot_inc/SearchStat.php';
         $searchStat = new SearchStat();
         $searchStat->saveSearch(strip_tags($_GET['lookfor']), strip_tags(isset($_GET['type']) ? $_GET['type'] : (isset($_GET['basicType']) ? $_GET['basicType'] : 'Keyword')), $searchObject->getResultTotal());
     }
     // Done, display the page
     $interface->display('layout.tpl');
 }
Esempio n. 5
0
 public function getLibraryScopingId()
 {
     //For econtent, we need to be more specific when restricting copies
     //since patrons can't use copies that are only available to other libraries.
     $searchLibrary = Library::getSearchLibrary();
     $searchLocation = Location::getSearchLocation();
     $activeLibrary = Library::getActiveLibrary();
     $activeLocation = Location::getActiveLocation();
     $homeLibrary = Library::getPatronHomeLibrary();
     //Load the holding label for the branch where the user is physically.
     if (!is_null($homeLibrary)) {
         return $homeLibrary->includeOutOfSystemExternalLinks ? -1 : $homeLibrary->libraryId;
     } else {
         if (!is_null($activeLocation)) {
             $activeLibrary = Library::getLibraryForLocation($activeLocation->locationId);
             return $activeLibrary->includeOutOfSystemExternalLinks ? -1 : $activeLibrary->libraryId;
         } else {
             if (isset($activeLibrary)) {
                 return $activeLibrary->includeOutOfSystemExternalLinks ? -1 : $activeLibrary->libraryId;
             } else {
                 if (!is_null($searchLocation)) {
                     $searchLibrary = Library::getLibraryForLocation($searchLibrary->locationId);
                     return $searchLibrary->includeOutOfSystemExternalLinks ? -1 : $searchLocation->libraryId;
                 } else {
                     if (isset($searchLibrary)) {
                         return $searchLibrary->includeOutOfSystemExternalLinks ? -1 : $searchLibrary->libraryId;
                     } else {
                         return -1;
                     }
                 }
             }
         }
     }
 }
 public function getItemsFast()
 {
     global $configArray;
     if ($this->fastItems == null) {
         $searchLibrary = Library::getSearchLibrary();
         if ($searchLibrary) {
             $libraryLocationCode = $searchLibrary->ilsCode;
         }
         $searchLocation = Location::getSearchLocation();
         if ($searchLocation) {
             $homeLocationCode = $searchLocation->code;
         } else {
             $homeLocation = Location::getUserHomeLocation();
             if ($homeLocation) {
                 $homeLocationCode = $homeLocation->code;
             }
         }
         $this->fastItems = array();
         if ($this->itemsFromIndex) {
             $this->fastItems = array();
             foreach ($this->itemsFromIndex as $itemData) {
                 $isLocalItem = false;
                 $isLibraryItem = false;
                 if (array_key_exists('item', $itemData)) {
                     $itemId = $itemData['item'][0];
                     $locationCode = $itemData['item'][1];
                     $shelfLocation = mapValue('shelf_location', $locationCode);
                     $sharing = $itemData['item'][3];
                     $source = $itemData['item'][4];
                     $fileOrUrl = '';
                     if (count($itemData['item']) > 5) {
                         $fileOrUrl = $itemData['item'][5];
                     }
                     if (array_key_exists('scope', $itemData)) {
                         $isLocalItem = $itemData['scope'][1] == 'true';
                         $isLibraryItem = $itemData['scope'][2] == 'true';
                     }
                 } else {
                     $itemId = $itemData[1];
                     $locationCode = $itemData[2];
                     $shelfLocation = mapValue('shelf_location', $itemData[2]);
                     $sharing = $itemData[4];
                     $source = $itemData[5];
                     $fileOrUrl = '';
                     if (count($itemData) > 6) {
                         $fileOrUrl = $itemData[6];
                     }
                     $isLocalItem = isset($libraryLocationCode) && strlen($libraryLocationCode) > 0 && strpos($locationCode, $libraryLocationCode) === 0;
                     $isLibraryItem = isset($homeLocationCode) && strlen($homeLocationCode) > 0 && strpos($locationCode, $homeLocationCode) === 0;
                 }
                 $actions = $this->getActionsForItem($itemId, $fileOrUrl, null);
                 $libraryLabelObj = new Library();
                 $libraryLabelObj->whereAdd("'{$locationCode}' LIKE CONCAT(ilsCode, '%') and ilsCode <> ''");
                 $libraryLabelObj->selectAdd();
                 $libraryLabelObj->selectAdd('displayName');
                 if ($libraryLabelObj->find(true)) {
                     $libraryLabel = $libraryLabelObj->displayName;
                 } else {
                     $libraryLabel = $locationCode . ' Online';
                 }
                 //TODO: Get the correct number of available copies
                 $totalCopies = 1;
                 $this->fastItems[] = array('itemId' => $itemId, 'location' => $locationCode, 'callnumber' => '', 'availability' => $this->isItemAvailable($itemId, $totalCopies), 'holdable' => $this->isEContentHoldable($locationCode, $itemData), 'inLibraryUseOnly' => false, 'isLocalItem' => $isLocalItem, 'isLibraryItem' => $isLibraryItem, 'locationLabel' => 'Online', 'libraryLabel' => $libraryLabel, 'shelfLocation' => $shelfLocation, 'source' => 'Online ' . $source, 'sharing' => $sharing, 'actions' => $actions);
             }
         } else {
             /** @var File_MARC_Data_Field[] $itemFields */
             $itemFields = $this->getMarcRecord()->getFields('989');
             foreach ($itemFields as $itemField) {
                 $locationCode = trim($itemField->getSubfield('d') != null ? $itemField->getSubfield('d')->getData() : '');
                 //Each item can have multiple item fields
                 /** @var File_MARC_Subfield[] $eContentFields */
                 $eContentFields = $itemField->getSubfields('w');
                 $itemId = $itemField->getSubfield('1')->getData();
                 $iType = $itemField->getSubfield($configArray['Reindex']['iTypeSubfield'])->getData();
                 foreach ($eContentFields as $eContentField) {
                     $eContentData = trim($eContentField->getData() != null ? $eContentField->getData() : '');
                     if ($eContentData && strpos($eContentData, ':') > 0) {
                         $eContentFieldData = explode(':', $eContentData);
                         $source = trim($eContentFieldData[0]);
                         $protectionType = strtolower(trim($eContentFieldData[1]));
                         $totalCopies = 1;
                         if ($this->isValidProtectionType($protectionType)) {
                             if ($this->isValidForUser($locationCode, $eContentFieldData)) {
                                 $libraryLabelObj = new Library();
                                 $libraryLabelObj->whereAdd("'{$locationCode}' LIKE CONCAT(ilsCode, '%') and ilsCode <> ''");
                                 $libraryLabelObj->selectAdd();
                                 $libraryLabelObj->selectAdd('displayName');
                                 if ($libraryLabelObj->find(true)) {
                                     $libraryLabel = $libraryLabelObj->displayName;
                                 } else {
                                     $libraryLabel = $locationCode . ' Online';
                                 }
                                 $locationLabelObj = new Location();
                                 $locationLabelObj->whereAdd("'{$locationCode}' LIKE CONCAT(code, '%') and code <> ''");
                                 if ($locationLabelObj->find(true)) {
                                     $locationLabel = $locationLabelObj->displayName;
                                 } else {
                                     $locationLabel = $locationCode . ' Online';
                                 }
                                 //Get the file or url that is related to this item.
                                 $fileOrUrl = '';
                                 $acsId = null;
                                 if ($protectionType == 'external') {
                                     $urlSubfield = $itemField->getSubfield('u');
                                     if ($urlSubfield != null) {
                                         $fileOrUrl = $urlSubfield->getData();
                                     } else {
                                         //Get from the 856 field
                                         /** @var File_MARC_Data_Field[] $linkFields */
                                         $linkFields = $this->getMarcRecord()->getFields('856');
                                         foreach ($linkFields as $link) {
                                             $urlSubfield = $link->getSubfield('u');
                                             if ($urlSubfield != null) {
                                                 $fileOrUrl = $urlSubfield->getData();
                                             }
                                         }
                                     }
                                 } else {
                                     if (count($eContentFieldData) > 3) {
                                         $fileOrUrl = trim($eContentFieldData[3]);
                                     }
                                     if (count($eContentFieldData) > 4) {
                                         $acsId = trim($eContentFieldData[4]);
                                     }
                                     if (count($eContentFieldData) > 5) {
                                         $totalCopies = trim($eContentFieldData[5]);
                                     }
                                 }
                                 $fileOrUrl = trim($fileOrUrl);
                                 $actions = $this->getActionsForItem($itemId, $fileOrUrl, $acsId);
                                 $format = $this->getEContentFormat($fileOrUrl, $iType);
                                 $sharing = $this->getSharing($locationCode, $eContentFieldData);
                                 //Add an item
                                 $item = array('itemId' => $itemId, 'location' => $locationCode, 'locationLabel' => $locationLabel, 'libraryLabel' => $libraryLabel, 'callnumber' => '', 'availability' => $this->isItemAvailable($itemId, $totalCopies), 'holdable' => $this->isEContentHoldable($locationCode, $eContentFieldData), 'isLocalItem' => $this->isLocalItem($locationCode, $eContentFieldData), 'isLibraryItem' => $this->isLibraryItem($locationCode, $eContentFieldData), 'shelfLocation' => 'Online ' . $source, 'source' => $source, 'sharing' => $sharing, 'fileOrUrl' => $fileOrUrl, 'format' => $format, 'helpText' => $this->getHelpText($fileOrUrl), 'usageNotes' => $this->getUsageRestrictions($sharing, $libraryLabel, $locationLabel), 'formatNotes' => $this->getFormatNotes($fileOrUrl), 'size' => $this->getFileSize($fileOrUrl), 'actions' => $actions);
                                 $this->fastItems[] = $item;
                             }
                         }
                     }
                 }
             }
         }
     }
     return $this->fastItems;
 }
Esempio n. 7
0
 public function process()
 {
     global $interface;
     //Get Facet settings for processing display
     $interface->assign('checkboxFilters', $this->searchObject->getCheckboxFacets());
     //Get applied facets
     $filterList = $this->searchObject->getFilterList(true);
     foreach ($filterList as $facetKey => $facet) {
         //Remove any top facets since the removal links are displayed above results
         if (strpos($facet[0]['field'], 'availability_toggle') === 0) {
             unset($filterList[$facetKey]);
         }
     }
     $interface->assign('filterList', $filterList);
     //Process the side facet set to handle the Added In Last facet which we only want to be
     //visible if there is not a value selected for the facet (makes it single select
     $sideFacets = $this->searchObject->getFacetList($this->mainFacets);
     $searchLibrary = Library::getSearchLibrary();
     //Do additional processing of facets for non-genealogy searches
     if ($this->searchObject->getSearchType() != 'genealogy') {
         foreach ($sideFacets as $facetKey => $facet) {
             $facetSetting = $this->facetSettings[$facetKey];
             //Do special processing of facets
             if (preg_match('/time_since_added/i', $facetKey)) {
                 $timeSinceAddedFacet = $this->updateTimeSinceAddedFacet($facet);
                 $sideFacets[$facetKey] = $timeSinceAddedFacet;
             } elseif ($facetKey == 'rating_facet') {
                 $userRatingFacet = $this->updateUserRatingsFacet($facet);
                 $sideFacets[$facetKey] = $userRatingFacet;
             } elseif ($facetKey == 'available_at') {
                 //Mangle the availability facets
                 $oldFacetValues = $sideFacets['available_at']['list'];
                 ksort($oldFacetValues);
                 $filters = $this->searchObject->getFilterList();
                 //print_r($filters);
                 $appliedAvailability = array();
                 foreach ($filters as $appliedFilters) {
                     foreach ($appliedFilters as $filter) {
                         if ($filter['field'] == 'available_at') {
                             $appliedAvailability[$filter['value']] = $filter['removalUrl'];
                         }
                     }
                 }
                 $availableAtFacets = array();
                 foreach ($oldFacetValues as $facetKey2 => $facetInfo) {
                     if (strlen($facetKey2) > 1) {
                         $sortIndicator = substr($facetKey2, 0, 1);
                         if ($sortIndicator >= '1' && $sortIndicator <= '4') {
                             $availableAtFacets[$facetKey2] = $facetInfo;
                         }
                     }
                 }
                 $includeAnyLocationFacet = $this->searchObject->getFacetSetting("Availability", "includeAnyLocationFacet");
                 $includeAnyLocationFacet = $includeAnyLocationFacet == '' || $includeAnyLocationFacet == 'true';
                 if ($searchLibrary) {
                     $includeAnyLocationFacet = $searchLibrary->showAvailableAtAnyLocation;
                 }
                 //print_r ("includeAnyLocationFacet = $includeAnyLocationFacet");
                 if ($includeAnyLocationFacet) {
                     $anyLocationLabel = $this->searchObject->getFacetSetting("Availability", "anyLocationLabel");
                     //print_r ("anyLocationLabel = $anyLocationLabel");
                     $availableAtFacets['*'] = array('value' => '*', 'display' => $anyLocationLabel == '' ? "Any Marmot Location" : $anyLocationLabel, 'count' => $this->searchObject->getResultTotal() - (isset($oldFacetValues['']['count']) ? $oldFacetValues['']['count'] : 0), 'url' => $this->searchObject->renderLinkWithFilter('available_at:*'), 'isApplied' => array_key_exists('*', $appliedAvailability), 'removalUrl' => array_key_exists('*', $appliedAvailability) ? $appliedAvailability['*'] : null);
                 }
                 $sideFacets['available_at']['list'] = $availableAtFacets;
             } else {
                 //Do other handling of the display
                 if ($facetSetting->sortMode == 'alphabetically') {
                     asort($sideFacets[$facetKey]['list']);
                 }
                 if ($facetSetting->numEntriesToShowByDefault > 0) {
                     $sideFacets[$facetKey]['valuesToShow'] = $facetSetting->numEntriesToShowByDefault;
                 }
                 if ($facetSetting->showAsDropDown) {
                     $sideFacets[$facetKey]['showAsDropDown'] = $facetSetting->showAsDropDown;
                 }
                 if ($facetSetting->useMoreFacetPopup && count($sideFacets[$facetKey]['list']) > 12) {
                     $sideFacets[$facetKey]['showMoreFacetPopup'] = true;
                     $facetsList = $sideFacets[$facetKey]['list'];
                     $sideFacets[$facetKey]['list'] = array_slice($facetsList, 0, 5);
                     $sortedList = array();
                     foreach ($facetsList as $key => $value) {
                         $sortedList[strtolower($key)] = $value;
                     }
                     ksort($sortedList);
                     $sideFacets[$facetKey]['sortedList'] = $sortedList;
                 } else {
                     $sideFacets[$facetKey]['showMoreFacetPopup'] = false;
                 }
             }
             $sideFacets[$facetKey]['collapseByDefault'] = $facetSetting->collapseByDefault;
         }
     }
     $interface->assign('sideFacetSet', $sideFacets);
 }
Esempio n. 8
0
function loadSearchInformation()
{
    //Determine the Search Source, need to do this always.
    global $searchSource;
    global $library;
    global $interface;
    $module = isset($_GET['module']) ? $_GET['module'] : null;
    $module = preg_replace('/[^\\w]/', '', $module);
    $searchSource = 'global';
    if (isset($_GET['searchSource'])) {
        $searchSource = $_GET['searchSource'];
        $_REQUEST['searchSource'] = $searchSource;
        //Update request since other check for it here
        $_SESSION['searchSource'] = $searchSource;
        //Update the session so we can remember what the user was doing last.
    } else {
        if (isset($_SESSION['searchSource'])) {
            //Didn't get a source, use what the user was doing last
            $searchSource = $_SESSION['searchSource'];
            $_REQUEST['searchSource'] = $searchSource;
        } else {
            //Use a default search source
            if ($module == 'Person') {
                $searchSource = 'genealogy';
            } else {
                $searchSource = 'local';
            }
            $_REQUEST['searchSource'] = $searchSource;
        }
    }
    $searchLibrary = Library::getSearchLibrary(null);
    $searchLocation = Location::getSearchLocation(null);
    //Based on the search source, determine the search scope and set a global variable
    global $solrScope;
    global $scopeType;
    $solrScope = false;
    $scopeType = '';
    if ($searchSource == 'local' || $searchSource == 'econtent') {
        $locationIsScoped = $searchLocation != null && ($searchLocation->restrictSearchByLocation || $searchLocation->econtentLocationsToInclude != 'all' || $searchLocation->useScope || !$searchLocation->enableOverdriveCollection || strlen($searchLocation->extraLocationCodesToInclude) > 0);
        $libraryIsScoped = $searchLibrary != null && ($searchLibrary->restrictSearchByLibrary || $searchLibrary->econtentLocationsToInclude != 'all' || strlen($searchLibrary->pTypes) > 0 && $searchLibrary->pTypes != -1 || $searchLibrary->useScope || !$searchLibrary->enableOverdriveCollection);
        if ($locationIsScoped && ($searchLocation->econtentLocationsToInclude != $searchLibrary->econtentLocationsToInclude && strlen($searchLocation->econtentLocationsToInclude) > 0 && $searchLocation->econtentLocationsToInclude != 'all' || $searchLocation->useScope && $searchLibrary->scope != $searchLocation->scope)) {
            $solrScope = $searchLocation->code;
            $scopeType = 'Location';
        } else {
            $solrScope = $searchLibrary->subdomain;
            $scopeType = 'Library';
        }
    } elseif ($searchSource != 'marmot' && $searchSource != 'global') {
        $solrScope = $searchSource;
        $scopeType = 'Search Source';
    }
    $solrScope = trim($solrScope);
    if (strlen($solrScope) == 0) {
        $solrScope = false;
        $scopeType = 'Unscoped';
    }
    $searchLibrary = Library::getSearchLibrary($searchSource);
    $searchLocation = Location::getSearchLocation($searchSource);
    global $millenniumScope;
    if ($library) {
        if ($searchLibrary) {
            $millenniumScope = $searchLibrary->scope;
        } elseif (isset($searchLocation)) {
            MillenniumDriver::$scopingLocationCode = $searchLocation->code;
        } else {
            $millenniumScope = isset($configArray['OPAC']['defaultScope']) ? $configArray['OPAC']['defaultScope'] : '93';
        }
    } else {
        $millenniumScope = isset($configArray['OPAC']['defaultScope']) ? $configArray['OPAC']['defaultScope'] : '93';
    }
}
Esempio n. 9
0
 function launch()
 {
     global $interface;
     global $configArray;
     global $timer;
     global $analytics;
     global $library;
     /** @var string|LibrarySearchSource|LocationSearchSource $searchSource */
     $searchSource = isset($_REQUEST['searchSource']) ? $_REQUEST['searchSource'] : 'local';
     if (preg_match('/library\\d+/', $searchSource)) {
         $trimmedId = str_replace('library', '', $searchSource);
         $searchSourceObj = new LibrarySearchSource();
         $searchSourceObj->id = $trimmedId;
         if ($searchSourceObj->find(true)) {
             $searchSource = $searchSourceObj;
         }
     }
     if (isset($_REQUEST['replacementTerm'])) {
         $replacementTerm = $_REQUEST['replacementTerm'];
         $interface->assign('replacementTerm', $replacementTerm);
         $oldTerm = $_REQUEST['lookfor'];
         $interface->assign('oldTerm', $oldTerm);
         $_REQUEST['lookfor'] = $replacementTerm;
         $_GET['lookfor'] = $replacementTerm;
         $oldSearchUrl = $_SERVER['REQUEST_URI'];
         $oldSearchUrl = str_replace('replacementTerm=' . urlencode($replacementTerm), 'disallowReplacements', $oldSearchUrl);
         $interface->assign('oldSearchUrl', $oldSearchUrl);
     }
     $interface->assign('showDplaLink', false);
     if ($configArray['DPLA']['enabled']) {
         if ($library->includeDplaResults) {
             $interface->assign('showDplaLink', true);
         }
     }
     // Include Search Engine Class
     require_once ROOT_DIR . '/sys/Solr.php';
     $timer->logTime('Include search engine');
     //Check to see if the year has been set and if so, convert to a filter and resend.
     $dateFilters = array('publishDate');
     foreach ($dateFilters as $dateFilter) {
         if (isset($_REQUEST[$dateFilter . 'yearfrom']) && !empty($_REQUEST[$dateFilter . 'yearfrom']) || isset($_REQUEST[$dateFilter . 'yearto']) && !empty($_REQUEST[$dateFilter . 'yearto'])) {
             $queryParams = $_GET;
             $yearFrom = preg_match('/^\\d{2,4}$/', $_REQUEST[$dateFilter . 'yearfrom']) ? $_REQUEST[$dateFilter . 'yearfrom'] : '*';
             $yearTo = preg_match('/^\\d{2,4}$/', $_REQUEST[$dateFilter . 'yearto']) ? $_REQUEST[$dateFilter . 'yearto'] : '*';
             if (strlen($yearFrom) == 2) {
                 $yearFrom = '19' . $yearFrom;
             } else {
                 if (strlen($yearFrom) == 3) {
                     $yearFrom = '0' . $yearFrom;
                 }
             }
             if (strlen($yearTo) == 2) {
                 $yearTo = '19' . $yearTo;
             } else {
                 if (strlen($yearFrom) == 3) {
                     $yearTo = '0' . $yearTo;
                 }
             }
             if ($yearTo != '*' && $yearFrom != '*' && $yearTo < $yearFrom) {
                 $tmpYear = $yearTo;
                 $yearTo = $yearFrom;
                 $yearFrom = $tmpYear;
             }
             unset($queryParams['module']);
             unset($queryParams['action']);
             unset($queryParams[$dateFilter . 'yearfrom']);
             unset($queryParams[$dateFilter . 'yearto']);
             if (!isset($queryParams['sort'])) {
                 $queryParams['sort'] = 'year';
             }
             $queryParamStrings = array();
             foreach ($queryParams as $paramName => $queryValue) {
                 if (is_array($queryValue)) {
                     foreach ($queryValue as $arrayValue) {
                         if (strlen($arrayValue) > 0) {
                             $queryParamStrings[] = $paramName . '[]=' . $arrayValue;
                         }
                     }
                 } else {
                     if (strlen($queryValue)) {
                         $queryParamStrings[] = $paramName . '=' . $queryValue;
                     }
                 }
             }
             if ($yearFrom != '*' || $yearTo != '*') {
                 $queryParamStrings[] = "&filter[]={$dateFilter}:[{$yearFrom}+TO+{$yearTo}]";
             }
             $queryParamString = join('&', $queryParamStrings);
             header("Location: {$configArray['Site']['path']}/Search/Results?{$queryParamString}");
             exit;
         }
     }
     $rangeFilters = array('lexile_score', 'accelerated_reader_reading_level', 'accelerated_reader_point_value');
     foreach ($rangeFilters as $filter) {
         if (isset($_REQUEST[$filter . 'from']) && strlen($_REQUEST[$filter . 'from']) > 0 || isset($_REQUEST[$filter . 'to']) && strlen($_REQUEST[$filter . 'to']) > 0) {
             $queryParams = $_GET;
             $from = isset($_REQUEST[$filter . 'from']) && preg_match('/^\\d*(\\.\\d*)?$/', $_REQUEST[$filter . 'from']) ? $_REQUEST[$filter . 'from'] : '*';
             $to = isset($_REQUEST[$filter . 'to']) && preg_match('/^\\d*(\\.\\d*)?$/', $_REQUEST[$filter . 'to']) ? $_REQUEST[$filter . 'to'] : '*';
             if ($to != '*' && $from != '*' && $to < $from) {
                 $tmpFilter = $to;
                 $to = $from;
                 $from = $tmpFilter;
             }
             unset($queryParams['module']);
             unset($queryParams['action']);
             unset($queryParams[$filter . 'from']);
             unset($queryParams[$filter . 'to']);
             $queryParamStrings = array();
             foreach ($queryParams as $paramName => $queryValue) {
                 if (is_array($queryValue)) {
                     foreach ($queryValue as $arrayValue) {
                         if (strlen($arrayValue) > 0) {
                             $queryParamStrings[] = $paramName . '[]=' . $arrayValue;
                         }
                     }
                 } else {
                     if (strlen($queryValue)) {
                         $queryParamStrings[] = $paramName . '=' . $queryValue;
                     }
                 }
             }
             if ($from != '*' || $to != '*') {
                 $queryParamStrings[] = "&filter[]={$filter}:[{$from}+TO+{$to}]";
             }
             $queryParamString = join('&', $queryParamStrings);
             header("Location: {$configArray['Site']['path']}/Search/Results?{$queryParamString}");
             exit;
         }
     }
     // Initialise from the current search globals
     /** @var SearchObject_Solr $searchObject */
     $searchObject = SearchObjectFactory::initSearchObject();
     //		$searchObject->viewOptions = $this->viewOptions; // set valid view options for the search object
     $searchObject->init($searchSource);
     $timer->logTime("Init Search Object");
     // Build RSS Feed for Results (if requested)
     if ($searchObject->getView() == 'rss') {
         // Throw the XML to screen
         echo $searchObject->buildRSS();
         // And we're done
         exit;
     } else {
         if ($searchObject->getView() == 'excel') {
             // Throw the Excel spreadsheet to screen for download
             echo $searchObject->buildExcel();
             // And we're done
             exit;
         }
     }
     $displayMode = $searchObject->getView();
     if ($displayMode == 'covers') {
         $searchObject->setLimit(24);
         // a set of 24 covers looks better in display
     }
     // Set Interface Variables
     //   Those we can construct BEFORE the search is executed
     $displayQuery = $searchObject->displayQuery();
     $pageTitle = $displayQuery;
     if (strlen($pageTitle) > 20) {
         $pageTitle = substr($pageTitle, 0, 20) . '...';
     }
     $pageTitle .= ' | Search Results';
     $interface->setPageTitle($pageTitle);
     $interface->assign('sortList', $searchObject->getSortList());
     $interface->assign('rssLink', $searchObject->getRSSUrl());
     $interface->assign('excelLink', $searchObject->getExcelUrl());
     $timer->logTime('Setup Search');
     // Process Search
     $result = $searchObject->processSearch(true, true);
     if (PEAR_Singleton::isError($result)) {
         PEAR_Singleton::raiseError($result->getMessage());
     }
     $timer->logTime('Process Search');
     // Some more variables
     //   Those we can construct AFTER the search is executed, but we need
     //   no matter whether there were any results
     $interface->assign('qtime', round($searchObject->getQuerySpeed(), 2));
     $interface->assign('spellingSuggestions', $searchObject->getSpellingSuggestions());
     $interface->assign('lookfor', $displayQuery);
     $interface->assign('searchType', $searchObject->getSearchType());
     // Will assign null for an advanced search
     $interface->assign('searchIndex', $searchObject->getSearchIndex());
     // We'll need recommendations no matter how many results we found:
     $interface->assign('topRecommendations', $searchObject->getRecommendationsTemplates('top'));
     $interface->assign('sideRecommendations', $searchObject->getRecommendationsTemplates('side'));
     // 'Finish' the search... complete timers and log search history.
     $searchObject->close();
     $interface->assign('time', round($searchObject->getTotalSpeed(), 2));
     // Show the save/unsave code on screen
     // The ID won't exist until after the search has been put in the search history
     //    so this needs to occur after the close() on the searchObject
     $interface->assign('showSaved', true);
     $interface->assign('savedSearch', $searchObject->isSavedSearch());
     $interface->assign('searchId', $searchObject->getSearchId());
     $currentPage = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1;
     $interface->assign('page', $currentPage);
     //Enable and disable functionality based on library settings
     //This must be done before we process each result
     $interface->assign('showNotInterested', false);
     $interface->assign('page_body_style', 'sidebar_left');
     $interface->assign('overDriveVersion', isset($configArray['OverDrive']['interfaceVersion']) ? $configArray['OverDrive']['interfaceVersion'] : 1);
     //Check to see if we should show unscoped results
     global $solrScope;
     $enableUnscopedSearch = false;
     // fallback setting
     if ($solrScope) {
         $searchLibrary = Library::getSearchLibrary();
         if ($searchLibrary != null && $searchLibrary->showMarmotResultsAtEndOfSearch) {
             if (is_object($searchSource)) {
                 $enableUnscopedSearch = $searchSource->catalogScoping != 'unscoped';
                 $unscopedSearch = clone $searchObject;
             } else {
                 $searchSources = new SearchSources();
                 $searchOptions = $searchSources->getSearchSources();
                 if (isset($searchOptions['marmot'])) {
                     //TODO: change name of search option to 'consortium'
                     $unscopedSearch = clone $searchObject;
                     $enableUnscopedSearch = true;
                 }
             }
         }
     }
     $showRatings = 1;
     $enableProspectorIntegration = isset($configArray['Content']['Prospector']) ? $configArray['Content']['Prospector'] : false;
     if (isset($library)) {
         $enableProspectorIntegration = $library->enablePospectorIntegration == 1;
         $showRatings = $library->showRatings;
     }
     if ($enableProspectorIntegration) {
         $interface->assign('showProspectorLink', true);
         $interface->assign('prospectorSavedSearchId', $searchObject->getSearchId());
     } else {
         $interface->assign('showProspectorLink', false);
     }
     $interface->assign('showRatings', $showRatings);
     $numUnscopedTitlesToLoad = 0;
     // Save the ID of this search to the session so we can return to it easily:
     $_SESSION['lastSearchId'] = $searchObject->getSearchId();
     // Save the URL of this search to the session so we can return to it easily:
     $_SESSION['lastSearchURL'] = $searchObject->renderSearchUrl();
     if (is_object($searchSource)) {
         $translatedSearch = $searchSource->label;
     } else {
         $allSearchSources = SearchSources::getSearchSources();
         if (!isset($allSearchSources[$searchSource]) && $searchSource == 'marmot') {
             $searchSource = 'local';
         }
         $translatedSearch = $allSearchSources[$searchSource]['name'];
     }
     // Save the search for statistics
     $analytics->addSearch($translatedSearch, $searchObject->displayQuery(), $searchObject->isAdvanced(), $searchObject->getFullSearchType(), $searchObject->hasAppliedFacets(), $searchObject->getResultTotal());
     // No Results Actions //
     if ($searchObject->getResultTotal() < 1) {
         //We didn't find anything.  Look for search Suggestions
         //Don't try to find suggestions if facets were applied
         $autoSwitchSearch = false;
         $disallowReplacements = isset($_REQUEST['disallowReplacements']) || isset($_REQUEST['replacementTerm']);
         if (!$disallowReplacements && (!isset($facetSet) || count($facetSet) == 0)) {
             require_once ROOT_DIR . '/services/Search/lib/SearchSuggestions.php';
             $searchSuggestions = new SearchSuggestions();
             $commonSearches = $searchSuggestions->getAllSuggestions($searchObject->displayQuery(), $searchObject->getSearchIndex());
             //assign here before we start popping stuff off
             $interface->assign('searchSuggestions', $commonSearches);
             //If the first search in the list is used 10 times more than the next, just show results for that
             $numSuggestions = count($commonSearches);
             if ($numSuggestions == 1) {
                 $firstSearch = array_pop($commonSearches);
                 $autoSwitchSearch = true;
             } elseif ($numSuggestions >= 2) {
                 $firstSearch = array_shift($commonSearches);
                 $secondSearch = array_shift($commonSearches);
                 $firstTimesSearched = $firstSearch['numSearches'];
                 $secondTimesSearched = $secondSearch['numSearches'];
                 if ($secondTimesSearched > 0 && $firstTimesSearched / $secondTimesSearched > 10) {
                     // avoids division by zero
                     $autoSwitchSearch = true;
                 }
             }
             // Switch to search with a better search term //
             //				$interface->assign('autoSwitchSearch', $autoSwitchSearch);
             if ($autoSwitchSearch) {
                 //Get search results for the new search
                 //					$interface->assign('oldTerm', $searchObject->displayQuery());
                 //					$interface->assign('newTerm', $commonSearches[0]['phrase']);
                 // The above assignments probably do nothing when there is a redirect below
                 $thisUrl = $_SERVER['REQUEST_URI'] . "&replacementTerm=" . urlencode($firstSearch['phrase']);
                 header("Location: " . $thisUrl);
                 exit;
             }
         }
         // No record found
         $interface->assign('recordCount', 0);
         // Was the empty result set due to an error?
         $error = $searchObject->getIndexError();
         if ($error !== false) {
             // If it's a parse error or the user specified an invalid field, we
             // should display an appropriate message:
             if (stristr($error['msg'], 'org.apache.lucene.queryParser.ParseException') || preg_match('/^undefined field/', $error['msg'])) {
                 $interface->assign('parseError', $error['msg']);
                 if (preg_match('/^undefined field/', $error['msg'])) {
                     // Setup to try as a possible subtitle search
                     $fieldName = trim(str_replace('undefined field', '', $error['msg'], $replaced));
                     // strip out the phrase 'undefined field' to get just the fieldname
                     $original = urlencode("{$fieldName}:");
                     if ($replaced === 1 && !empty($fieldName) && strpos($_SERVER['REQUEST_URI'], $original)) {
                         // ensure only 1 replacement was done, that the fieldname isn't an empty string, and the label is in fact in the Search URL
                         $new = urlencode("{$fieldName} :");
                         // include space in between the field name & colon to avoid the parse error
                         $thisUrl = str_replace($original, $new, $_SERVER['REQUEST_URI'], $replaced);
                         if ($replaced === 1) {
                             // ensure only one modification was made
                             header("Location: " . $thisUrl);
                             exit;
                         }
                     }
                 }
                 // Unexpected error -- let's treat this as a fatal condition.
             } else {
                 PEAR_Singleton::raiseError(new PEAR_Error('Unable to process query<br />' . 'Solr Returned: ' . $error));
             }
         }
         // Set up to try an Unscoped Search //
         $numUnscopedTitlesToLoad = 10;
         $timer->logTime('no hits processing');
     } elseif ($searchObject->getResultTotal() == 1 && (strpos($searchObject->displayQuery(), 'id') === 0 || $searchObject->getSearchType() == 'id')) {
         //Redirect to the home page for the record
         $recordSet = $searchObject->getResultRecordSet();
         $record = reset($recordSet);
         $_SESSION['searchId'] = $searchObject->getSearchId();
         if ($record['recordtype'] == 'list') {
             $listId = substr($record['id'], 4);
             header("Location: " . $configArray['Site']['path'] . "/MyResearch/MyList/{$listId}");
             exit;
         } elseif ($record['recordtype'] == 'econtentRecord') {
             $shortId = str_replace('econtentRecord', '', $record['id']);
             header("Location: " . $configArray['Site']['path'] . "/EcontentRecord/{$shortId}/Home");
             exit;
         } else {
             header("Location: " . $configArray['Site']['path'] . "/Record/{$record['id']}/Home");
             exit;
         }
     } else {
         $timer->logTime('save search');
         // Assign interface variables
         $summary = $searchObject->getResultSummary();
         $interface->assign('recordCount', $summary['resultTotal']);
         $interface->assign('recordStart', $summary['startRecord']);
         $interface->assign('recordEnd', $summary['endRecord']);
         $facetSet = $searchObject->getFacetList();
         $interface->assign('facetSet', $facetSet);
         //Check to see if a format category is already set
         $categorySelected = false;
         if (isset($facetSet['top'])) {
             foreach ($facetSet['top'] as $cluster) {
                 if ($cluster['label'] == 'Category') {
                     foreach ($cluster['list'] as $thisFacet) {
                         if ($thisFacet['isApplied']) {
                             $categorySelected = true;
                             break;
                         }
                     }
                 }
                 if ($categorySelected) {
                     break;
                 }
             }
         }
         $interface->assign('categorySelected', $categorySelected);
         $timer->logTime('load selected category');
     }
     // What Mode will search results be Displayed In //
     if ($displayMode == 'covers') {
         $displayTemplate = 'Search/covers-list.tpl';
         // structure for bookcover tiles
     } else {
         // default
         $displayTemplate = 'Search/list-list.tpl';
         // structure for regular results
         $displayMode = 'list';
         // In case the view is not explicitly set, do so now for display & clients-side functions
         // Process Paging (only in list mode)
         if ($searchObject->getResultTotal() > 1) {
             $link = $searchObject->renderLinkPageTemplate();
             $options = array('totalItems' => $summary['resultTotal'], 'fileName' => $link, 'perPage' => $summary['perPage']);
             $pager = new VuFindPager($options);
             $interface->assign('pageLinks', $pager->getLinks());
             if ($pager->isLastPage()) {
                 $numUnscopedTitlesToLoad = 5;
             }
         }
     }
     $timer->logTime('finish hits processing');
     $interface->assign('subpage', $displayTemplate);
     $interface->assign('displayMode', $displayMode);
     // For user toggle switches
     // Suplementary Unscoped Search //
     if ($enableUnscopedSearch && isset($unscopedSearch)) {
         // Total & Link will be shown in result header even if none of these results will be shown on this page
         $unscopedSearch->setLimit($numUnscopedTitlesToLoad * 4);
         $unscopedSearch->disableScoping();
         $unscopedSearch->processSearch(false, false);
         $numUnscopedResults = $unscopedSearch->getResultTotal();
         $interface->assign('numUnscopedResults', $numUnscopedResults);
         $unscopedSearchUrl = $unscopedSearch->renderSearchUrl();
         if (preg_match('/searchSource=(.*?)(?:&|$)/', $unscopedSearchUrl)) {
             $unscopedSearchUrl = preg_replace('/(.*searchSource=)(.*?)(&|$)(.*)/', '$1marmot$3$4', $unscopedSearchUrl);
             //				$unscopedSearchUrl = preg_replace('/&/', '&amp;', $unscopedSearchUrl);
             $unscopedSearchUrl = str_replace('&', '&amp;', $unscopedSearchUrl);
             // faster than preg_replace for simple substitutions
         } else {
             $unscopedSearchUrl .= "&amp;searchSource=marmot";
         }
         $unscopedSearchUrl .= "&amp;shard=";
         $interface->assign('unscopedSearchUrl', $unscopedSearchUrl);
         if ($numUnscopedTitlesToLoad > 0) {
             $unscopedResults = $unscopedSearch->getSupplementalResultRecordHTML($searchObject->getResultRecordSet(), $numUnscopedTitlesToLoad, $searchObject->getResultTotal());
             $interface->assign('recordSet', $unscopedResults);
             $unscopedResults = $interface->fetch($displayTemplate);
             $interface->assign('unscopedResults', $unscopedResults);
         }
     }
     // Big one - our results //
     $recordSet = $searchObject->getResultRecordHTML($displayMode);
     $interface->assign('recordSet', $recordSet);
     $timer->logTime('load result records');
     if ($configArray['Statistics']['enabled'] && isset($_GET['lookfor']) && !is_array($_GET['lookfor'])) {
         require_once ROOT_DIR . '/Drivers/marmot_inc/SearchStatNew.php';
         $searchStat = new SearchStatNew();
         $searchStat->saveSearch(strip_tags($_GET['lookfor']), strip_tags(isset($_GET['type']) ? $_GET['type'] : (isset($_GET['basicType']) ? $_GET['basicType'] : 'Keyword')), $searchObject->getResultTotal());
     }
     // Done, display the page
     $interface->setTemplate($searchObject->getResultTotal() ? 'list.tpl' : 'list-none.tpl');
     // main search results content
     $interface->assign('sidebar', 'Search/results-sidebar.tpl');
     $interface->display('layout.tpl');
 }
Esempio n. 10
0
 /**
  * returns the patron type identifier if a patron is logged in or if the patron
  * is not logged in, it will return the default PType for the library domain.
  * If a domain is not in use it will return -1.
  *
  * @return int
  */
 public function getPType()
 {
     if ($this->pType == null) {
         /** @var $user User */
         global $user;
         /** @var $locationSingleton Location */
         global $locationSingleton;
         $searchLocation = $locationSingleton->getSearchLocation();
         $searchLibrary = Library::getSearchLibrary();
         if (isset($user) && $user != false) {
             $patronDump = $this->_getPatronDump($this->_getBarcode());
             $this->pType = $patronDump['P_TYPE'];
         } else {
             if (isset($searchLocation) && $searchLocation->defaultPType > 0) {
                 $this->pType = $searchLocation->defaultPType;
             } else {
                 if (isset($searchLibrary) && $searchLibrary->defaultPType > 0) {
                     $this->pType = $searchLibrary->defaultPType;
                 } else {
                     $this->pType = -1;
                 }
             }
         }
     }
     return $this->pType;
 }
Esempio n. 11
0
 /**
  * Execute a search.
  *
  * @param	 string	$query			The XQuery script in binary encoding.
  * @param	 string	$handler		The Query Handler to use (null for default)
  * @param	 array	$filter		 The fields and values to filter results on
  * @param	 int	  $start			The record to start with
  * @param	 int	  $limit			The amount of records to return
  * @param	 array	$facet			An array of faceting options
  * @param	 string	$spell			Phrase to spell check
  * @param	 string	$dictionary Spell check dictionary to use
  * @param	 string	$sort			 Field name to use for sorting
  * @param	 string	$fields		 A list of fields to be returned
  * @param	 string	$method		 Method to use for sending request (GET/POST)
  * @param	 bool		$returnSolrError		If Solr reports a syntax error,
  *																			should we fail outright (false) or
  *																			treat it as an empty result set with
  *																			an error key set (true)?
  * @access	public
  * @throws	object							PEAR Error
  * @return	array							 An array of query results
  */
 function search($query, $handler = null, $filter = null, $start = 0, $limit = 20, $facet = null, $spell = '', $dictionary = null, $sort = null, $fields = null, $method = HTTP_REQUEST_METHOD_POST, $returnSolrError = false)
 {
     global $timer;
     // Query String Parameters
     $options = array('q' => $query, 'rows' => $limit, 'start' => $start, 'indent' => 'yes');
     //For FRBR, enable this and then update display
     //$options['group'] = 'true';
     //$options['group.field'] = 'grouping_term';
     // Add Sorting
     if ($sort && !empty($sort)) {
         // There may be multiple sort options (ranked, with tie-breakers);
         // process each individually, then assemble them back together again:
         $sortParts = explode(',', $sort);
         for ($x = 0; $x < count($sortParts); $x++) {
             $sortParts[$x] = $this->_normalizeSort($sortParts[$x]);
         }
         $options['sort'] = implode(',', $sortParts);
     }
     //Check to see if we need to automatically convert to a proper case only (no stemming search)
     //We will do this whenever all or part of a string is surrounded by quotes.
     if (preg_match('/\\".+?\\"/', $query)) {
         if ($handler == 'Keyword') {
             $handler = 'KeywordProper';
         } else {
             if ($handler == 'Subject') {
                 $handler = 'SubjectProper';
             } else {
                 if ($handler == 'AllFields') {
                     $handler = 'AllFieldsProper';
                 } else {
                     if ($handler == 'Title') {
                         $handler = 'TitleProper';
                     }
                 }
             }
         }
     }
     // Determine which handler to use
     if (!$this->isAdvanced($query)) {
         //Escape : to make sure that the query isn't treated as a field spec.
         $query = str_replace(':', '\\:', $query);
         $ss = is_null($handler) ? null : $this->_getSearchSpecs($handler);
         // Is this a Dismax search?
         if (isset($ss['DismaxFields'])) {
             // Specify the fields to do a Dismax search on:
             $options['qf'] = implode(' ', $ss['DismaxFields']);
             // Specify the default dismax search handler so we can use any
             // global settings defined by the user:
             $options['qt'] = 'dismax';
             // Load any custom Dismax parameters from the YAML search spec file:
             if (isset($ss['DismaxParams']) && is_array($ss['DismaxParams'])) {
                 foreach ($ss['DismaxParams'] as $current) {
                     $options[$current[0]] = $current[1];
                 }
             }
             // Apply search-specific filters if necessary:
             if (isset($ss['FilterQuery'])) {
                 if (is_array($filter)) {
                     $filter[] = $ss['FilterQuery'];
                 } else {
                     $filter = array($ss['FilterQuery']);
                 }
             }
         } else {
             // Not DisMax... but do we need to format the query based on
             // a setting in the YAML search specs?	If $ss is an array
             // at this point, it indicates that we found YAML details.
             if (is_array($ss)) {
                 $options['q'] = $this->_buildQueryComponent($handler, $query);
             } else {
                 if (!empty($handler)) {
                     $options['q'] = "({$handler}:{$query})";
                 }
             }
         }
     } else {
         // Force boolean operators to uppercase if we are in a case-insensitive
         // mode:
         if (!$this->caseSensitiveBooleans) {
             $query = SolrUtils::capitalizeBooleans($query);
         }
         // Process advanced search -- if a handler was specified, let's see
         // if we can adapt the search to work with the appropriate fields.
         if (!empty($handler)) {
             $options['q'] = $this->_buildAdvancedQuery($handler, $query);
         }
     }
     $timer->logTime("build query");
     // Limit Fields
     if ($fields) {
         $options['fl'] = $fields;
     } else {
         // This should be an explicit list
         $options['fl'] = '*,score';
     }
     if (is_object($this->searchSource)) {
         $defaultFilters = preg_split('/\\r\\n/', $this->searchSource->defaultFilter);
         foreach ($defaultFilters as $tmpFilter) {
             $filter[] = $tmpFilter;
         }
     }
     //Apply automatic boosting (only to biblio and econtent queries)
     if (preg_match('/.*(biblio|econtent).*/i', $this->host)) {
         //unset($options['qt']); //Force the query to never use dismax handling
         $searchLibrary = Library::getSearchLibrary($this->searchSource);
         //Boost items owned at our location
         $searchLocation = Location::getSearchLocation($this->searchSource);
         $boostFactors = $this->getBoostFactors($searchLibrary, $searchLocation);
         if (isset($options['qt']) && $options['qt'] == 'dismax') {
             //Boost by number of holdings
             if (count($boostFactors) > 0) {
                 $options['bf'] = "sum(" . implode(',', $boostFactors) . ")";
             }
             //print ($options['bq']);
         } else {
             $baseQuery = $options['q'];
             //Boost items in our system
             if (count($boostFactors) > 0) {
                 $boost = "sum(" . implode(',', $boostFactors) . ")";
             } else {
                 $boost = '';
             }
             $options['q'] = "{!boost b={$boost}} {$baseQuery}";
             //echo ("Advanced Query " . $options['q']);
         }
         $timer->logTime("apply boosting");
         $scopingFilters = $this->getScopingFilters($searchLibrary, $searchLocation);
         $timer->logTime("apply filters based on location");
     } else {
         //Non book search (genealogy)
         $scopingFilters = array();
     }
     if ($filter != null && $scopingFilters != null) {
         if (!is_array($filter)) {
             $filter = array($filter);
         }
         $filters = array_merge($filter, $scopingFilters);
     } else {
         if ($filter == null) {
             $filters = $scopingFilters;
         } else {
             $filters = $filter;
         }
     }
     // Build Facet Options
     if ($facet && !empty($facet['field'])) {
         $options['facet'] = 'true';
         $options['facet.mincount'] = 1;
         $options['facet.limit'] = isset($facet['limit']) ? $facet['limit'] : null;
         unset($facet['limit']);
         if (isset($facet['field']) && is_array($facet['field']) && in_array('date_added', $facet['field'])) {
             $options['facet.date'] = 'date_added';
             $options['facet.date.end'] = 'NOW';
             $options['facet.date.start'] = 'NOW-1YEAR';
             $options['facet.date.gap'] = '+1WEEK';
             foreach ($facet['field'] as $key => $value) {
                 if ($value == 'date_added') {
                     unset($facet['field'][$key]);
                     break;
                 }
             }
         }
         if (isset($facet['field'])) {
             $options['facet.field'] = $facet['field'];
             if ($options['facet.field'] && is_array($options['facet.field'])) {
                 foreach ($options['facet.field'] as $key => $facetName) {
                     if (strpos($facetName, 'availability_toggle') === 0) {
                         $options['facet.field'][$key] = '{!ex=avail}' . $facetName;
                     }
                 }
             }
         } else {
             $options['facet.field'] = null;
         }
         unset($facet['field']);
         $options['facet.prefix'] = isset($facet['prefix']) ? $facet['prefix'] : null;
         unset($facet['prefix']);
         $options['facet.sort'] = isset($facet['sort']) ? $facet['sort'] : null;
         unset($facet['sort']);
         if (isset($facet['offset'])) {
             $options['facet.offset'] = $facet['offset'];
             unset($facet['offset']);
         }
         if ($searchLibrary && $searchLibrary->showAvailableAtAnyLocation) {
             $options['f.available_at.facet.missing'] = 'true';
         }
         foreach ($facet as $param => $value) {
             $options[$param] = $value;
         }
     }
     $timer->logTime("build facet options");
     //Check to see if there are filters we want to show all values for
     if (isset($filters) && is_array($filters)) {
         foreach ($filters as $key => $value) {
             if (strpos($value, 'availability_toggle') === 0) {
                 $filters[$key] = '{!tag=avail}' . $value;
             }
         }
     }
     // Build Filter Query
     if (is_array($filters) && count($filters)) {
         $options['fq'] = $filters;
     }
     // Enable Spell Checking
     if ($spell != '') {
         $options['spellcheck'] = 'true';
         $options['spellcheck.q'] = $spell;
         if ($dictionary != null) {
             $options['spellcheck.dictionary'] = $dictionary;
         }
     }
     // Enable highlighting
     if ($this->_highlight) {
         $options['hl'] = 'true';
         $options['hl.fl'] = '*';
         $options['hl.simple.pre'] = '{{{{START_HILITE}}}}';
         $options['hl.simple.post'] = '{{{{END_HILITE}}}}';
     }
     if ($this->debug) {
         echo '<pre>Search options: ' . print_r($options, true) . "\n";
         if ($filters) {
             echo "\nFilterQuery: ";
             foreach ($filters as $filterItem) {
                 echo " {$filterItem}";
             }
         }
         if ($sort) {
             echo "\nSort: " . $options['sort'];
         }
         echo "</pre>\n";
         $options['debugQuery'] = 'on';
     }
     $timer->logTime("end solr setup");
     $result = $this->_select($method, $options, $returnSolrError);
     $timer->logTime("run select");
     if (PEAR_Singleton::isError($result)) {
         PEAR_Singleton::raiseError($result);
     }
     return $result;
 }
Esempio n. 12
0
 public function getItemsFast()
 {
     global $timer;
     if ($this->fastItems == null || isset($_REQUEST['reload'])) {
         $searchLibrary = Library::getSearchLibrary();
         $extraLocations = '';
         if ($searchLibrary) {
             $libraryLocationCode = $searchLibrary->ilsCode;
         }
         $searchLocation = Location::getSearchLocation();
         if ($searchLocation) {
             $homeLocationCode = $searchLocation->code;
             $extraLocations = $searchLocation->extraLocationCodesToInclude;
         }
         if ($this->itemsFromIndex) {
             $this->fastItems = array();
             foreach ($this->itemsFromIndex as $itemData) {
                 $isOrderItem = false;
                 $onOrderCopies = 0;
                 $status = null;
                 $groupedStatus = null;
                 $inLibraryUseOnly = false;
                 $isHoldable = true;
                 $isLocalItem = false;
                 $isLibraryItem = false;
                 if (array_key_exists('item', $itemData)) {
                     //New style with item, record, and scope information separated
                     $shelfLocation = $itemData['item'][7];
                     $locationCode = $itemData['item'][1];
                     $callNumber = $itemData['item'][2];
                     if (substr($itemData['item'][0], 0, 2) == '.o') {
                         $isOrderItem = true;
                         $onOrderCopies = $itemData['item'][7];
                         $available = false;
                         $shelfLocation = mapValue('shelf_location', $itemData['item'][1]);
                     } else {
                         $status = mapValue('item_status', $itemData['item'][6]);
                         $groupedStatus = mapValue('item_grouped_status', $itemData['item'][6]);
                         $available = $itemData['item'][3] == 'true';
                         $inLibraryUseOnly = $itemData['item'][4] == 'true';
                     }
                     //Don't use scoping section yet because it isn't ready for prime time.
                     /*if (array_key_exists('scope', $itemData) && count($itemData['scope']) > 0){
                     			$isHoldable = $itemData['scope'][0] == 'true';
                     			$isLocalItem = $itemData['scope'][1] == 'true';
                     			$isLibraryItem = $itemData['scope'][2] == 'true';
                     		}*/
                     if (!isset($libraryLocationCode) || $libraryLocationCode == '') {
                         $isLibraryItem = true;
                     } else {
                         $isLibraryItem = strpos($locationCode, $libraryLocationCode) === 0;
                     }
                     $isLocalItem = isset($homeLocationCode) && strlen($homeLocationCode) > 0 && strpos($locationCode, $homeLocationCode) === 0 || $extraLocations != '' && preg_match("/^{$extraLocations}\$/i", $locationCode);
                 } else {
                     //Old style where record and item information are combined
                     $shelfLocation = $itemData[2];
                     $locationCode = $itemData[2];
                     if (strpos($shelfLocation, ':') === false) {
                         $shelfLocation = mapValue('shelf_location', $itemData[2]);
                     } else {
                         $shelfLocationParts = explode(":", $shelfLocation);
                         $locationCode = $shelfLocationParts[0];
                         $branch = mapValue('shelf_location', $locationCode);
                         $shelfLocationTmp = mapValue('collection', $shelfLocationParts[1]);
                         $shelfLocation = $branch . ' ' . $shelfLocationTmp;
                     }
                     $callNumber = $itemData[3];
                     if (substr($itemData[1], 0, 2) == '.o') {
                         $isOrderItem = true;
                         $onOrderCopies = $itemData[8];
                         $available = false;
                     } else {
                         $status = mapValue('item_status', $itemData[7]);
                         $groupedStatus = mapValue('item_grouped_status', $itemData[7]);
                         $available = $itemData[4] == 'true';
                         $inLibraryUseOnly = $itemData[5] == 'true';
                     }
                     if (!isset($libraryLocationCode) || $libraryLocationCode == '') {
                         $isLibraryItem = true;
                     } else {
                         $isLibraryItem = strpos($locationCode, $libraryLocationCode) === 0;
                     }
                     $isLocalItem = isset($homeLocationCode) && strlen($homeLocationCode) > 0 && strpos($locationCode, $homeLocationCode) === 0 || $extraLocations != '' && preg_match("/^{$extraLocations}\$/i", $locationCode);
                 }
                 //Try to trim the courier code if any
                 if (preg_match('/(.*?)\\sC\\d{3}\\w{0,2}$/', $shelfLocation, $locationParts)) {
                     $shelfLocation = $locationParts[1];
                 }
                 //Determine the structure of the item data based on if it's an order record or not.
                 //TODO: This needs a better way of handling things because .o will only work for Sierra/Millennium systems
                 if ($isOrderItem) {
                     $groupedStatus = "On Order";
                     $callNumber = "ON ORDER";
                     $status = "On Order";
                 } else {
                     //This is a regular (physical) item
                     if ($status != null) {
                         if ($status == 'On Shelf' && $available != true) {
                             $status = 'Checked Out';
                             $groupedStatus = "Checked Out";
                         }
                     } else {
                         if ($available) {
                             $status = "On Shelf";
                             $groupedStatus = "On Shelf";
                         } else {
                             $status = "Checked Out";
                             $groupedStatus = "Checked Out";
                         }
                     }
                 }
                 $this->fastItems[] = array('location' => $locationCode, 'callnumber' => $callNumber, 'availability' => $available, 'holdable' => $isHoldable, 'inLibraryUseOnly' => $inLibraryUseOnly, 'isLibraryItem' => $isLibraryItem, 'isLocalItem' => $isLocalItem, 'locationLabel' => true, 'shelfLocation' => $shelfLocation, 'onOrderCopies' => $onOrderCopies, 'status' => $status, 'groupedStatus' => $groupedStatus);
             }
             $timer->logTime("Finished getItemsFast for marc record based on data in index");
         } else {
             $driver = MarcRecord::getCatalogDriver();
             $this->fastItems = $driver->getItemsFast($this->getUniqueID(), $this->scopingEnabled, $this->getMarcRecord());
             $timer->logTime("Finished getItemsFast for marc record based on data in driver");
         }
     }
     return $this->fastItems;
 }
Esempio n. 13
0
 public function process()
 {
     global $interface;
     // Grab the facet set -- note that we need to take advantage of the third
     // parameter to getFacetList in order to pass down row and column
     // information for inclusion in the final list.
     $facetList = $this->searchObject->getFacetList($this->facets, false);
     foreach ($facetList as $facetSetkey => $facetSet) {
         if ($facetSet['label'] == 'Category' || $facetSet['label'] == 'Format Category') {
             $validCategories = array('Books', 'eBook', 'Audio Books', 'eAudio', 'Music', 'Movies');
             //add an image name for display in the template
             foreach ($facetSet['list'] as $facetKey => $facet) {
                 if (in_array($facetKey, $validCategories)) {
                     $facet['imageName'] = strtolower(str_replace(' ', '', $facet['value'])) . ".png";
                     $facet['imageNameSelected'] = strtolower(str_replace(' ', '', $facet['value'])) . "_selected.png";
                     $facetSet['list'][$facetKey] = $facet;
                 } else {
                     unset($facetSet['list'][$facetKey]);
                 }
             }
             uksort($facetSet['list'], "format_category_comparator");
             $facetList[$facetSetkey] = $facetSet;
         } elseif (preg_match('/available/i', $facetSet['label'])) {
             $numSelected = 0;
             foreach ($facetSet['list'] as $facetKey => $facet) {
                 if ($facet['isApplied']) {
                     $numSelected++;
                 }
             }
             //If nothing is selected, select entire collection by default
             $sortedFacetList = array();
             $numTitlesWithNoValue = 0;
             $numTitlesWithEntireCollection = 0;
             $searchLibrary = Library::getSearchLibrary(null);
             $searchLocation = Location::getSearchLocation(null);
             if ($searchLocation) {
                 $superScopeLabel = $searchLocation->availabilityToggleLabelSuperScope;
                 $localLabel = $searchLocation->availabilityToggleLabelLocal;
                 $localLabel = str_ireplace('{display name}', $searchLocation->displayName, $localLabel);
                 $availableLabel = $searchLocation->availabilityToggleLabelAvailable;
                 $availableLabel = str_ireplace('{display name}', $searchLocation->displayName, $availableLabel);
             } else {
                 $superScopeLabel = $searchLibrary->availabilityToggleLabelSuperScope;
                 $localLabel = $searchLibrary->availabilityToggleLabelLocal;
                 $localLabel = str_ireplace('{display name}', $searchLibrary->displayName, $localLabel);
                 $availableLabel = $searchLibrary->availabilityToggleLabelAvailable;
                 $availableLabel = str_ireplace('{display name}', $searchLibrary->displayName, $availableLabel);
             }
             foreach ($facetSet['list'] as $facet) {
                 if ($facet['value'] == 'Entire Collection') {
                     $includeButton = true;
                     $facet['value'] = $localLabel;
                     if (trim($localLabel) == '') {
                         $includeButton = false;
                     } else {
                         if ($searchLocation) {
                             $includeButton = !$searchLocation->restrictSearchByLocation;
                         } elseif ($searchLibrary) {
                             $includeButton = !$searchLibrary->restrictSearchByLibrary;
                         }
                     }
                     $numTitlesWithEntireCollection = $facet['count'];
                     if ($includeButton) {
                         $sortedFacetList[1] = $facet;
                     }
                 } elseif ($facet['value'] == '') {
                     $facet['isApplied'] = $facet['isApplied'] || $numSelected == 0;
                     $facet['value'] = $superScopeLabel;
                     $sortedFacetList[0] = $facet;
                     $numTitlesWithNoValue = $facet['count'];
                     break;
                 } else {
                     $facet['value'] = $availableLabel;
                     $sortedFacetList[2] = $facet;
                 }
             }
             if (isset($sortedFacetList[0])) {
                 $sortedFacetList[0]['count'] = $numTitlesWithEntireCollection + $numTitlesWithNoValue;
             }
             ksort($sortedFacetList);
             $facetSet['list'] = $sortedFacetList;
             $facetList[$facetSetkey] = $facetSet;
         }
     }
     $interface->assign('topFacetSet', $facetList);
     $interface->assign('topFacetSettings', $this->baseSettings);
 }
Esempio n. 14
0
 /**
  * Return a list of valid sort options -- overrides the base class with
  * custom behavior for Author/Search screen.
  *
  * @access  public
  * @return  array    Sort value => description array.
  */
 protected function getSortOptions()
 {
     // Author/Search screen
     if ($this->searchType == 'author' && $this->searchSubType == 'search') {
         // It's important to remember here we are talking about on-screen
         //   sort values, not what is sent to Solr, since this screen
         //   is really using facet sorting.
         return array('relevance' => 'sort_author_relevance', 'author' => 'sort_author_author');
     }
     // Everywhere else -- use normal default behavior
     $sortOptions = parent::getSortOptions();
     $searchLibrary = Library::getSearchLibrary($this->searchSource);
     if ($searchLibrary == null) {
         unset($sortOptions['callnumber_sort']);
     }
     return $sortOptions;
 }