/** * Process incoming parameters and display the page. * * @return void * @access public */ public function launch() { global $interface; global $configArray; // Set Up Collection $this->assignCollection(); $this->assignCollectionFacets(); // Assign interface variables $summary = $this->searchObject->getResultSummary(); $interface->assign('recordCount', $summary['resultTotal']); $interface->assign('recordStart', $summary['startRecord']); $interface->assign('recordEnd', $summary['endRecord']); $interface->assign('sortList', $this->searchObject->getSortList()); $interface->assign('viewList', $this->searchObject->getViewList()); $interface->assign('rssLink', $this->searchObject->getRSSUrl()); $interface->assign('limitList', $this->searchObject->getLimitList()); $interface->assign('page', isset($_REQUEST['page']) ? $_REQUEST['page'] : 1); // Process Paging $link = $this->searchObject->renderLinkPageTemplate(); $options = array('totalItems' => $summary['resultTotal'], 'fileName' => $link, 'perPage' => $summary['perPage']); $pager = new VuFindPager($options); $pageLinks = $pager->getLinks(); $interface->assign('pageLinks', $pageLinks); // Set templates etc. $currentView = $this->searchObject->getView(); $interface->assign('searchPage', 'Search/list-' . $currentView . '.tpl'); $interface->assign('subpage', 'Collection/list.tpl'); // This is because if loaded from an link, the tab will // not automatically be selected $interface->assign('tab', 'list'); // Display Page $interface->display('layout.tpl'); }
function launch() { global $interface; $interface->caching = false; // Retrieve User Search History $interface->assign('lastsearch', isset($_SESSION['lastSearchURL']) ? $_SESSION['lastSearchURL'] : false); // Initialise from the current search globals $searchObject = SearchObjectFactory::initSearchObject(); $searchObject->init(); // TODO : Stats $result = $searchObject->processSearch(); if (PEAR_Singleton::isError($result)) { PEAR_Singleton::raiseError($result->getMessage()); } $interface->assign('sortList', $searchObject->getSortList()); $interface->assign('lookfor', $searchObject->displayQuery()); $interface->assign('searchType', $searchObject->getSearchType()); $interface->assign('searchIndex', $searchObject->getSearchIndex()); $interface->assign('qtime', round($searchObject->getQuerySpeed(), 2)); $summary = $searchObject->getResultSummary(); // Post processing, remember that the REAL results here with regards to // numbers and pagination are the author facet, not the document // results from the solr index. So access '$summary' with care. $page = $summary['page']; $limit = $summary['perPage']; // The search object will have returned an array of author facets that // is offset to display the current page of results but which has more // than a single page worth of content. This allows a user to dig deeper // and deeper into the result set even though we have no way of finding // out the exact count of results without risking a memory overflow or // long delay. We need to use the current page information to adjust the // known total count accordingly, and we need to use the page size to // crop off extra results when displaying the list to the user. // See VUFIND-127 in JIRA for more details. $authors = $result['facet_counts']['facet_fields']['authorStr']; $cnt = ($page - 1) * $limit + count($authors); $interface->assign('recordSet', array_slice($authors, 0, $limit)); $interface->assign('recordCount', $cnt); $interface->assign('recordStart', ($page - 1) * $limit + 1); if ($cnt < $limit || $page * $limit > $cnt) { $interface->assign('recordEnd', $cnt); } else { $interface->assign('recordEnd', $page * $limit); } $link = $searchObject->renderLinkPageTemplate(); $options = array('totalItems' => $cnt, 'fileName' => $link); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); $interface->setPageTitle('Author Browse'); $interface->setTemplate('list.tpl'); $interface->display('layout.tpl'); }
function launch() { global $interface; global $configArray; $results = array(); $editorialReview = new EditorialReview(); $currentPage = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1; $recordsPerPage = 20; $searchUrl = $configArray['Site']['path'] . '/EditorialReview/Search'; $searchParams = array(); foreach ($_REQUEST as $key => $value) { if (!in_array($key, array('module', 'action', 'page'))) { $searchParams[] = "{$key}={$value}"; } } $searchUrl = $searchUrl . '?page=%d&' . implode('&', $searchParams); $interface->assign('page', $currentPage); $editorialReview = new EditorialReview(); if (isset($_REQUEST['sortOptions'])) { $editorialReview->orderBy($_REQUEST['sortOptions']); $interface->assign('sort', $_REQUEST['sortOptions']); } $numTotalFiles = $editorialReview->count(); $editorialReview->limit(($currentPage - 1) * $recordsPerPage, 20); $editorialReview->find(); if ($editorialReview->N > 0) { while ($editorialReview->fetch()) { $results[] = clone $editorialReview; } } $interface->assign('results', $results); $options = array('totalItems' => $numTotalFiles, 'fileName' => $searchUrl, 'perPage' => $recordsPerPage); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); $interface->assign('sidebar', 'MyAccount/account-sidebar.tpl'); $interface->setTemplate('search.tpl'); $interface->display('layout.tpl'); }
/** * Process MetaLib search * * @return void */ function doMetaLib() { global $interface; global $configArray; // Initialise SearchObject. $searchObject = SearchObjectFactory::initSearchObject('MetaLib'); $searchObject->init(); if (isset($_GET['page'])) { $searchObject->setPage($_GET['page']); } $displayQuery = $searchObject->displayQuery(); $interface->assign('lookfor', $displayQuery); $interface->assign('searchType', $searchObject->getSearchType()); // Search MetaLib $template = null; if (!empty($displayQuery)) { $result = $searchObject->processSearch(true, true); // Whether RSI is enabled if (isset($configArray['OpenURL']['use_rsi']) && $configArray['OpenURL']['use_rsi']) { $interface->assign('rsi', true); } // Whether embedded openurl autocheck is enabled if (isset($configArray['OpenURL']['autocheck']) && $configArray['OpenURL']['autocheck']) { $interface->assign('openUrlAutoCheck', true); } // We'll need recommendations no matter how many results we found: $interface->assign('qtime', round($searchObject->getQuerySpeed(), 2)); $interface->assign('spellingSuggestions', $searchObject->getSpellingSuggestions()); $interface->assign('topRecommendations', $searchObject->getRecommendationsTemplates('top')); $interface->assign('sideRecommendations', $searchObject->getRecommendationsTemplates('side')); $interface->assign('disallowedDatabases', $result['disallowedDatabases']); $interface->assign('failedDatabases', $result['failedDatabases']); $interface->assign('successDatabases', $result['successDatabases']); $methodsAvailable = Login::getActiveAuthorizationMethods(); $userAuthorized = UserAccount::isAuthorized(); $setNotification = array(); // We want to guide the user to login for access to licensed material if (!$userAuthorized && $methodsAvailable) { $setNotification[] = '<p>' . translate('authorize_user_notification') . '</p>'; } if ($result['recordCount'] > 0) { $summary = $searchObject->getResultSummary(); $page = $summary['page']; $interface->assign('recordCount', $summary['resultTotal']); $interface->assign('recordStart', $summary['startRecord']); $interface->assign('recordEnd', $summary['endRecord']); $interface->assign('recordSet', $result['documents']); $interface->assign('sortList', $searchObject->getSortList()); // If our result set is larger than the number of records that // MetaLib will let us page through (10000 records per database), // we should cut off the number before passing it to our paging // mechanism: $config = getExtraConfigArray('MetaLib'); $pageLimit = isset($config['General']['result_limit']) ? $config['General']['result_limit'] : 2000; $totalPagerItems = $summary['resultTotal'] < $pageLimit ? $summary['resultTotal'] : $pageLimit; // Process Paging $link = $searchObject->renderLinkPageTemplate(); $options = array('totalItems' => $totalPagerItems, 'fileName' => $link, 'perPage' => $summary['perPage']); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); $interface->assign('pagesTotal', $totalPagerItems); // Display Listing of Results $template = 'list-list.tpl'; } else { $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, 'user.entered.query.is.malformed') || stristr($error, 'unknown.field')) { $interface->assign('parseError', true); } else { // Unexpected error -- let's treat this as a fatal condition. PEAR::raiseError(new PEAR_Error('Unable to process query<br />MetaLib Returned: ' . $error)); } } // Show notification if all databases were disallowed. if (count($result['successDatabases']) === 0 && count($result['failedDatabases']) === 0 && count($result['disallowedDatabases']) > 0) { array_unshift($setNotification, '<p>' . translate('metalib_not_authorized_all') . '</p>'); $interface->assign('noSearch', true); } $template = 'list-none.tpl'; } $interface->assign('setNotification', implode('', $setNotification)); } else { $result = false; $interface->assign('noQuery', true); $template = 'list-none.tpl'; } // '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()); // Save the URL of this search to the session so we can return to it easily: $_SESSION['lastSearchURL'] = $searchObject->renderSearchUrl(); return $interface->fetch("MetaLib/{$template}"); }
/** * Process parameters and display the page. * * @return void * @access public */ public function launch() { global $interface; global $configArray; $config = getExtraConfigArray("PCI"); // Initialise SearchObject. $this->searchObject->init(); $displayQuery = $this->searchObject->displayQuery(); $interface->setPageTitle(translate('Search Results') . (empty($displayQuery) ? '' : ' - ' . htmlspecialchars($displayQuery))); $interface->assign('lookfor', $displayQuery); $interface->assign('searchIndex', $this->searchObject->getSearchIndex()); $interface->assign('searchType', $this->searchObject->getSearchType()); $interface->assign('searchWithoutFilters', $this->searchObject->renderSearchUrlWithoutFilters()); $interface->assign('searchWithFilters', $this->searchObject->renderSearchUrl()); if ($spatialDateRangeType = $this->searchObject->getSpatialDateRangeFilterType()) { $interface->assign('spatialDateRangeType', $spatialDateRangeType); } // Search PCI $result = $this->searchObject->processSearch(false, true); // We'll need recommendations no matter how many results we found: $interface->assign('qtime', round($this->searchObject->getQuerySpeed(), 2)); $interface->assign('spellingSuggestions', $this->searchObject->getSpellingSuggestions()); $interface->assign('topRecommendations', $this->searchObject->getRecommendationsTemplates('top')); $interface->assign('sideRecommendations', $this->searchObject->getRecommendationsTemplates('side')); // Whether embedded openurl autocheck is enabled if (isset($configArray['OpenURL']['autocheck']) && $configArray['OpenURL']['autocheck']) { $interface->assign('openUrlAutoCheck', true); } // We'll need to assign search parameters for removal link $interface->assign('searchParams', $this->searchObject->renderSearchUrlParams()); // We want to guide the user to login for access to licensed material $interface->assign('methodsAvailable', Login::getActiveAuthorizationMethods()); $interface->assign('userAuthorized', UserAccount::isAuthorized()); if ($showGlobalFiltersNote = $interface->getGlobalFiltersNotification('Primo Central')) { $interface->assign('showGlobalFiltersNote', $showGlobalFiltersNote); } if ($result['recordCount'] > 0) { // If the "jumpto" parameter is set, jump to the specified result index: $this->_processJumpto($result); $summary = $this->searchObject->getResultSummary(); $page = $summary['page']; $interface->assign('recordCount', $summary['resultTotal']); $interface->assign('recordStart', $summary['startRecord']); $interface->assign('recordEnd', $summary['endRecord']); $interface->assign('recordSet', $result['response']['docs']); $interface->assign('sortList', $this->searchObject->getSortList()); $pageLimit = isset($config['General']['result_limit']) ? $config['General']['result_limit'] : 2000; $totalPagerItems = $summary['resultTotal'] < $pageLimit ? $summary['resultTotal'] : $pageLimit; // Process Paging $link = $this->searchObject->renderLinkPageTemplate(); $options = array('totalItems' => $totalPagerItems, 'fileName' => $link, 'perPage' => $summary['perPage']); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); // Display Listing of Results $interface->setTemplate('list.tpl'); $interface->assign('subpage', 'PCI/list-list.tpl'); } else { // Don't let bots crawl "no results" pages $this->disallowBots(); $interface->assign('recordCount', 0); // Was the empty result set due to an error? $error = $this->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, 'user.entered.query.is.malformed') || stristr($error, 'unknown.field')) { $interface->assign('parseError', true); } else { // Unexpected error -- let's treat this as a fatal condition. PEAR::raiseError(new PEAR_Error('Unable to process query<br />PCI Returned: ' . $error)); } } if (empty($displayQuery)) { $interface->assign('noQuery', true); } $interface->assign('removeAllFilters', $this->searchObject->renderSearchUrlWithoutFilters(array('prefiltered'))); $interface->setTemplate('list-none.tpl'); } // 'Finish' the search... complete timers and log search history. $this->searchObject->close(); $interface->assign('time', round($this->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', $this->searchObject->isSavedSearch()); $interface->assign('searchId', $this->searchObject->getSearchId()); // Save the URL of this search to the session so we can return to it easily: $_SESSION['lastSearchURL'] = $this->searchObject->renderSearchUrl(); // Save the display query too, so we can use it e.g. in the breadcrumbs $_SESSION['lastSearchDisplayQuery'] = $displayQuery; // Initialize visFacets for PCI Published Timeline $visFacets = array('search_sdaterange_mv' => array(0 => "", 1 => "", 'label' => "Other")); $interface->assign('visFacets', $visFacets); $interface->display('layout.tpl'); }
/** * Process parameters and display the page. * * @return void * @access public */ public function launch() { global $interface; global $configArray; // Initialise SearchObject. $this->searchObject->init(); $displayQuery = $this->searchObject->displayQuery(); $interface->setPageTitle(translate('Search Results') . (empty($displayQuery) ? '' : ' - ' . htmlspecialchars($displayQuery))); $interface->assign('lookfor', $displayQuery); $interface->assign('searchIndex', $this->searchObject->getSearchIndex()); $interface->assign('searchType', $this->searchObject->getSearchType()); // Search: $result = $this->searchObject->processSearch(true, true); // We'll need recommendations no matter how many results we found: $interface->assign('qtime', round($this->searchObject->getQuerySpeed(), 2)); $interface->assign('spellingSuggestions', $this->searchObject->getSpellingSuggestions()); $interface->assign('topRecommendations', $this->searchObject->getRecommendationsTemplates('top')); $interface->assign('sideRecommendations', $this->searchObject->getRecommendationsTemplates('side')); if ($this->searchObject->getResultTotal() > 0) { // If the "jumpto" parameter is set, jump to the specified result index: $this->_processJumpto($result); $summary = $this->searchObject->getResultSummary(); $page = $summary['page']; $interface->assign('recordCount', $summary['resultTotal']); $interface->assign('recordStart', $summary['startRecord']); $interface->assign('recordEnd', $summary['endRecord']); $interface->assign('recordSet', $result['response']['docs']); $interface->assign('sortList', $this->searchObject->getSortList()); // Process Paging $link = $this->searchObject->renderLinkPageTemplate(); $options = array('totalItems' => $summary['resultTotal'], 'fileName' => $link, 'perPage' => $summary['perPage']); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); // Display Listing of Results $interface->setTemplate('list.tpl'); $interface->assign('subpage', 'Authority/list-list.tpl'); } else { $interface->assign('recordCount', 0); // Was the empty result set due to an error? $error = $this->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); } else { // Unexpected error -- let's treat this as a fatal condition. PEAR::raiseError(new PEAR_Error('Unable to process query<br />Solr Returned: ' . $error)); } } $interface->setTemplate('list-none.tpl'); } // 'Finish' the search... complete timers and log search history. $this->searchObject->close(); $interface->assign('time', round($this->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', $this->searchObject->isSavedSearch()); $interface->assign('searchId', $this->searchObject->getSearchId()); // Save the URL of this search to the session so we can return to it easily: $_SESSION['lastSearchURL'] = $this->searchObject->renderSearchUrl(); $interface->display('layout.tpl'); }
/** * Assign all necessary values to the interface. * * @access public */ public function assign() { global $interface; $recordsPerPage = isset($_REQUEST['pagesize']) && is_numeric($_REQUEST['pagesize']) ? $_REQUEST['pagesize'] : 20; $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1; $startRecord = ($page - 1) * $recordsPerPage + 1; if ($startRecord < 0) { $startRecord = 0; } $endRecord = $page * $recordsPerPage; if ($endRecord > count($this->favorites)) { $endRecord = count($this->favorites); } $pageInfo = array('resultTotal' => count($this->favorites), 'startRecord' => $startRecord, 'endRecord' => $endRecord, 'perPage' => $recordsPerPage); // Initialise from the current search globals /** @var SearchObject_Solr $searchObject */ $searchObject = SearchObjectFactory::initSearchObject(); $searchObject->init(); $searchObject->disableScoping(); $searchObject->setLimit($recordsPerPage); //MDN 3/30 this was set to 200, but should be based off the page size $searchObject->setPage($page); if (!$this->isUserListSort) { // is a solr sort $searchObject->setSort($this->sort); // set solr sort. (have to set before retrieving solr sort options below) } $SolrSortList = $searchObject->getSortList(); // get all the search sort options (retrieve after setting solr sort option) $sortOptions = $defaultSortOptions = array(); foreach ($this->solrSortOptions as $option) { // extract just the ones we want if (isset($SolrSortList[$option])) { $sortOptions[$option] = $SolrSortList[$option]; $defaultSortOptions[$option] = $SolrSortList[$option]['desc']; } } foreach ($this->userListSortOptions as $option => $value_ignored) { // Non-Solr options $sortOptions[$option] = array('sortUrl' => $searchObject->renderLinkWithSort($option), 'desc' => "sort_{$option}_userlist", 'selected' => $option == $this->sort); $defaultSortOptions[$option] = "sort_{$option}_userlist"; } $interface->assign('sortList', $sortOptions); $interface->assign('defaultSortList', $defaultSortOptions); $interface->assign('defaultSort', $this->defaultSort); $interface->assign('userSort', $this->getSort() == 'custom'); // switch for when users can sort their list // Retrieve records from index (currently, only Solr IDs supported): if (count($this->favorites) > 0) { if ($this->isUserListSort) { $this->favorites = array_slice($this->favorites, $startRecord - 1, $recordsPerPage); $searchObject->setPage(1); // set to the first page for the search only } $searchObject->setQueryIDs($this->favorites); // do solr search by Ids $result = $searchObject->processSearch(); if (!$this->isUserListSort) { // adjust paging based on search $pageInfo['resultTotal'] = $result['response']['numFound']; if ($endRecord > $pageInfo['resultTotal']) { $endRecord = $pageInfo['resultTotal']; $pageInfo['endRecord'] = $endRecord; } $resourceList = $searchObject->getResultListHTML($this->user, $this->listId, $this->allowEdit); } else { $searchObject->setPage($page); // restore the actual sort page $resourceList = $searchObject->getResultListHTML($this->user, $this->listId, $this->allowEdit, $this->favorites); // puts html in order of favorites } } else { $resourceList = array(); } $interface->assign('resourceList', $resourceList); // Set up paging of list contents: $interface->assign('recordCount', $pageInfo['resultTotal']); $interface->assign('recordStart', $pageInfo['startRecord']); $interface->assign('recordEnd', $pageInfo['endRecord']); $interface->assign('recordsPerPage', $pageInfo['perPage']); $link = $_SERVER['REQUEST_URI']; if (preg_match('/[&?]page=/', $link)) { $link = preg_replace("/page=\\d+/", "page=%d", $link); } else { if (strpos($link, "?") > 0) { $link .= "&page=%d"; } else { $link .= "?page=%d"; } } $options = array('totalItems' => $pageInfo['resultTotal'], 'perPage' => $pageInfo['perPage'], 'fileName' => $link, 'append' => false); require_once ROOT_DIR . '/sys/Pager.php'; $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); }
/** * Do a basic search and return results as a JSON array */ function search() { global $interface; global $configArray; global $timer; // Include Search Engine Class require_once ROOT_DIR . '/sys/' . $configArray['Index']['engine'] . '.php'; $timer->logTime('Include search engine'); //setup the results array. $jsonResults = array(); // Initialise from the current search globals $searchObject = SearchObjectFactory::initSearchObject(); $searchObject->init(); // 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()); $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'); // 'Finish' the search... complete timers and log search history. $searchObject->close(); if ($searchObject->getResultTotal() < 1) { // No record found $interface->setTemplate('list-none.tpl'); $jsonResults['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)) { $jsonResults['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)); } } $timer->logTime('no hits processing'); } else { $timer->logTime('save search'); // Assign interface variables $summary = $searchObject->getResultSummary(); $jsonResults['recordCount'] = $summary['resultTotal']; $jsonResults['recordStart'] = $summary['startRecord']; $jsonResults['recordEnd'] = $summary['endRecord']; // Big one - our results $recordSet = $searchObject->getResultRecordSet(); //Remove fields as needed to improve the display. foreach ($recordSet as $recordKey => $record) { unset($record['auth_author']); unset($record['auth_authorStr']); unset($record['callnumber-first-code']); unset($record['spelling']); unset($record['callnumber-first']); unset($record['title_auth']); unset($record['callnumber-subject']); unset($record['author-letter']); unset($record['marc_error']); unset($record['title_fullStr']); unset($record['shortId']); $recordSet[$recordKey] = $record; } $jsonResults['recordSet'] = $recordSet; $timer->logTime('load result records'); $facetSet = $searchObject->getFacetList(); $jsonResults['facetSet'] = $facetSet; //Check to see if a format category is already set $categorySelected = false; if (isset($facetSet['top'])) { foreach ($facetSet['top'] as $title => $cluster) { if ($cluster['label'] == 'Category') { foreach ($cluster['list'] as $thisFacet) { if ($thisFacet['isApplied']) { $categorySelected = true; } } } } } $jsonResults['categorySelected'] = $categorySelected; $timer->logTime('finish checking to see if a format category has been loaded already'); // Process Paging $link = $searchObject->renderLinkPageTemplate(); $options = array('totalItems' => $summary['resultTotal'], 'fileName' => $link, 'perPage' => $summary['perPage']); $pager = new VuFindPager($options); $jsonResults['paging'] = array('currentPage' => $pager->pager->_currentPage, 'totalPages' => $pager->pager->_totalPages, 'totalItems' => $pager->pager->_totalItems, 'itemsPerPage' => $pager->pager->_perPage); $interface->assign('pageLinks', $pager->getLinks()); $timer->logTime('finish hits processing'); } // Report additional information after the results $jsonResults['query_time'] = round($searchObject->getQuerySpeed(), 2); $jsonResults['spellingSuggestions'] = $searchObject->getSpellingSuggestions(); $jsonResults['lookfor'] = $searchObject->displayQuery(); $jsonResults['searchType'] = $searchObject->getSearchType(); // Will assign null for an advanced search $jsonResults['searchIndex'] = $searchObject->getSearchIndex(); $jsonResults['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 $jsonResults['showSaved'] = true; $jsonResults['savedSearch'] = $searchObject->isSavedSearch(); $jsonResults['searchId'] = $searchObject->getSearchId(); $currentPage = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1; $jsonResults['page'] = $currentPage; if ($configArray['Statistics']['enabled'] && isset($_GET['lookfor'])) { require_once ROOT_DIR . '/Drivers/marmot_inc/SearchStatNew.php'; $searchStat = new SearchStatNew(); $searchStat->saveSearch(strip_tags($_GET['lookfor']), strip_tags($_GET['type']), $searchObject->getResultTotal()); } // 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(); // Return the results for display to the user. return $jsonResults; }
/** * Assign all necessary values to the interface. * * @access public */ public function assign() { global $interface; $recordsPerPage = isset($_REQUEST['pagesize']) && is_numeric($_REQUEST['pagesize']) ? $_REQUEST['pagesize'] : 25; $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1; $startRecord = ($page - 1) * $recordsPerPage + 1; if ($startRecord < 0) { $startRecord = 0; } $endRecord = $page * $recordsPerPage; if ($endRecord > count($this->favorites)) { $endRecord = count($this->favorites); } $pageInfo = array('resultTotal' => count($this->favorites), 'startRecord' => $startRecord, 'endRecord' => $endRecord, 'perPage' => $recordsPerPage); $this->favorites = array_slice($this->favorites, $startRecord - 1, $recordsPerPage); // Initialise from the current search globals $searchObject = SearchObjectFactory::initSearchObject(); $searchObject->init(); $interface->assign('sortList', $searchObject->getSortList()); $resourceList = array(); if (is_array($this->favorites)) { foreach ($this->favorites as $currentResource) { $interface->assign('resource', $currentResource); $resourceEntry = $interface->fetch('RecordDrivers/Resource/listentry.tpl'); $resourceList[] = $resourceEntry; } } $interface->assign('resourceList', $resourceList); // Initialise from the current search globals $searchObject = SearchObjectFactory::initSearchObject(); /*$searchObject->init(); $interface->assign('sortList', $searchObject->getSortList()); // Retrieve records from index (currently, only Solr IDs supported): $vuFindList = array(); if (array_key_exists('vufind', $this->ids) && count($this->ids['vufind']) > 0) { $searchObject->setQueryIDs($this->ids['vufind']); $result = $searchObject->processSearch(); $vuFindList = $searchObject->getResultListHTML($this->user, $this->listId, $this->allowEdit); } $eContentList = array(); if (array_key_exists('econtent', $this->ids) && count($this->ids['econtent']) > 0) { $eContentIds = array(); foreach ($this->ids['econtent'] as $eContentId){ $eContentIds[] = 'econtentRecord' . $eContentId; } $searchObject->setQueryIDs($eContentIds); $result = $searchObject->processSearch(); $eContentList = $searchObject->getResultListHTML($this->user, $this->listId, $this->allowEdit); } $resourceList = array_merge($vuFindList, $eContentList); $interface->assign('resourceList', $resourceList);*/ // Set up paging of list contents: $interface->assign('recordCount', $pageInfo['resultTotal']); $interface->assign('recordStart', $pageInfo['startRecord']); $interface->assign('recordEnd', $pageInfo['endRecord']); $link = $_SERVER['REQUEST_URI']; if (preg_match('/[&?]page=/', $link)) { $link = preg_replace("/page=\\d+/", "page=%d", $link); } else { if (strpos($link, "?") > 0) { $link .= "&page=%d"; } else { $link .= "?page=%d"; } } $options = array('totalItems' => $pageInfo['resultTotal'], 'perPage' => $pageInfo['perPage'], 'fileName' => $link, 'append' => false); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); }
function launch() { global $configArray; global $interface; global $user; global $timer; // Get My Transactions $oneOrMoreRenewableItems = false; if ($this->catalog->status) { if ($user->cat_username) { $patron = $this->catalog->patronLogin($user->cat_username, $user->cat_password); $timer->logTime("Logged in patron to get checked out items."); if (PEAR_Singleton::isError($patron)) { PEAR_Singleton::raiseError($patron); } $patronResult = $this->catalog->getMyProfile($patron); if (!PEAR_Singleton::isError($patronResult)) { $interface->assign('profile', $patronResult); } $timer->logTime("Got patron profile to get checked out items."); $libraryHoursMessage = Location::getLibraryHoursMessage($patronResult['homeLocationId']); $interface->assign('libraryHoursMessage', $libraryHoursMessage); // Define sorting options $sortOptions = array('title' => 'Title', 'author' => 'Author', 'dueDate' => 'Due Date', 'format' => 'Format', 'renewed' => 'Times Renewed', 'holdQueueLength' => 'Wish List'); $interface->assign('sortOptions', $sortOptions); $selectedSortOption = isset($_REQUEST['accountSort']) ? $_REQUEST['accountSort'] : 'dueDate'; $interface->assign('defaultSortOption', $selectedSortOption); $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1; $recordsPerPage = isset($_REQUEST['pagesize']) && is_numeric($_REQUEST['pagesize']) ? $_REQUEST['pagesize'] : 25; $interface->assign('recordsPerPage', $recordsPerPage); if (isset($_GET['exportToExcel'])) { $recordsPerPage = -1; $page = 1; } $result = $this->catalog->getMyTransactions($page, $recordsPerPage, $selectedSortOption); $timer->logTime("Loaded transactions from catalog."); if (!PEAR_Singleton::isError($result)) { $link = $_SERVER['REQUEST_URI']; if (preg_match('/[&?]page=/', $link)) { $link = preg_replace("/page=\\d+/", "page=%d", $link); } else { if (strpos($link, "?") > 0) { $link .= "&page=%d"; } else { $link .= "?page=%d"; } } if ($recordsPerPage != '-1') { $options = array('totalItems' => $result['numTransactions'], 'fileName' => $link, 'perPage' => $recordsPerPage, 'append' => false); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); } $interface->assign('showNotInterested', false); foreach ($result['transactions'] as $i => $data) { //Get Rating $resource = new Resource(); $resource->source = 'VuFind'; $resource->record_id = $data['id']; $resource->find(true); $data['ratingData'] = $resource->getRatingData($user); $result['transactions'][$i] = $data; $itemBarcode = isset($data['barcode']) ? $data['barcode'] : null; $itemId = isset($data['itemid']) ? $data['itemid'] : null; if ($itemBarcode != null && isset($_SESSION['renew_message'][$itemBarcode])) { $renewMessage = $_SESSION['renew_message'][$itemBarcode]['message']; $renewResult = $_SESSION['renew_message'][$itemBarcode]['result']; $data['renewMessage'] = $renewMessage; $data['renewResult'] = $renewResult; $result['transactions'][$i] = $data; unset($_SESSION['renew_message'][$itemBarcode]); //$logger->log("Found renewal message in session for $itemBarcode", PEAR_LOG_INFO); } else { if ($itemId != null && isset($_SESSION['renew_message'][$itemId])) { $renewMessage = $_SESSION['renew_message'][$itemId]['message']; $renewResult = $_SESSION['renew_message'][$itemId]['result']; $data['renewMessage'] = $renewMessage; $data['renewResult'] = $renewResult; $result['transactions'][$i] = $data; unset($_SESSION['renew_message'][$itemId]); //$logger->log("Found renewal message in session for $itemBarcode", PEAR_LOG_INFO); } else { $renewMessage = null; $renewResult = null; } } } $interface->assign('transList', $result['transactions']); unset($_SESSION['renew_message']); } } } //Determine which columns to show $ils = $configArray['Catalog']['ils']; $showOut = $ils == 'Horizon'; $showRenewed = $ils == 'Horizon' || $ils == 'Millennium'; $showWaitList = $ils == 'Horizon'; $interface->assign('showOut', $showOut); $interface->assign('showRenewed', $showRenewed); $interface->assign('showWaitList', $showWaitList); if (isset($_GET['exportToExcel'])) { $this->exportToExcel($result['transactions'], $showOut, $showRenewed, $showWaitList); } $interface->setTemplate('checkedout.tpl'); $interface->setPageTitle('Checked Out Items'); $interface->display('layout.tpl'); }
/** * Search course reserves index and display a list of matches. * * @return void * @access protected */ protected function searchReservesIndex() { global $interface; $searchObject = SearchObjectFactory::initSearchObject('SolrReserves'); $searchObject->init(); // Process Search $result = $searchObject->processSearch(true, true); if (PEAR::isError($result)) { PEAR::raiseError($result->getMessage()); } $interface->assign('qtime', round($searchObject->getQuerySpeed(), 2)); $interface->assign('spellingSuggestions', $searchObject->getSpellingSuggestions()); $interface->assign('sideRecommendations', $searchObject->getRecommendationsTemplates('side')); $interface->assign('reservesLookfor', $searchObject->displayQuery()); $interface->assign('searchType', $searchObject->getSearchType()); $interface->assign('sortList', $searchObject->getSortList()); if ($searchObject->getResultTotal() < 1) { // 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, 'org.apache.lucene.queryParser.ParseException') || preg_match('/^undefined field/', $error)) { $interface->assign('parseError', true); } else { // Unexpected error -- let's treat this as a fatal condition. PEAR::raiseError(new PEAR_Error('Unable to process query<br />Solr Returned: ' . $error)); } } } else { $interface->assign('recordSet', $result['response']['docs']); $summary = $searchObject->getResultSummary(); $interface->assign('recordCount', $summary['resultTotal']); $interface->assign('recordStart', $summary['startRecord']); $interface->assign('recordEnd', $summary['endRecord']); // Process Paging $link = $searchObject->renderLinkPageTemplate(); $options = array('totalItems' => $summary['resultTotal'], 'fileName' => $link, 'perPage' => $summary['perPage']); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); } }
function launch() { global $configArray; global $interface; //////////Populate the Date Filter Start //Grab the Selected Date Start if (isset($_REQUEST['dateFilterStart'])) { if (preg_match('/\\d{1,2}\\/\\d{1,2}\\/\\d{4}/', $_REQUEST['dateFilterStart'])) { $selectedDateStart = DateTime::createFromFormat('m/d/Y', $_REQUEST['dateFilterStart']); $selectedDateStart = $selectedDateStart->getTimestamp(); } else { $selectedDateStart = strtotime($_REQUEST['dateFilterStart']); } } else { $selectedDateStart = strtotime('-30 days'); } $selectedDateStart = date('Y-m-d', $selectedDateStart); $interface->assign('selectedDateStart', $selectedDateStart); //Populate the Date Filter End //Grab the Selected End Date if (isset($_REQUEST['dateFilterEnd'])) { if (preg_match('/\\d{1,2}\\/\\d{1,2}\\/\\d{4}/', $_REQUEST['dateFilterEnd'])) { $selectedDateEnd = DateTime::createFromFormat('m/d/Y', $_REQUEST['dateFilterEnd']); $selectedDateEnd = $selectedDateEnd->getTimestamp(); } else { $selectedDateEnd = strtotime($_REQUEST['dateFilterEnd']); } } else { $selectedDateEnd = strtotime('today'); } $selectedDateEnd = date('Y-m-d', $selectedDateEnd); $interface->assign('selectedDateEnd', $selectedDateEnd); //////////Populate the Stores Filter $queryHostsFilter = "SELECT DISTINCT linkHost AS linkHost FROM external_link_tracking ORDER BY linkHost ASC"; $externalLinkTracking = new ExternalLinkTracking(); $externalLinkTracking->query($queryHostsFilter); $allHosts = array(); while ($externalLinkTracking->fetch()) { $allHosts[] = $externalLinkTracking->linkHost; } $interface->assign('hostFilter', $allHosts); //////////Grab the Selected Hosts Filter Value if (isset($_REQUEST['hostFilter'])) { $selectedHosts = $_REQUEST['hostFilter']; } else { $selectedHosts = $allHosts; } $interface->assign('selectedHosts', $selectedHosts); $baseQueryLinks = "SELECT COUNT(externalLinkId) AS timesFollowed, recordId, linkUrl, linkHost " . "FROM external_link_tracking " . "WHERE (DATE_FORMAT(trackingDate, '%Y-%m-%d')) BETWEEN '" . $selectedDateStart . "' AND '" . $selectedDateEnd . "' "; if (count($selectedHosts) > 0) { $hosts = join("','", $selectedHosts); $baseQueryLinks .= "AND linkHost IN ('" . $hosts . "') "; } $baseQueryLinks .= "GROUP BY recordId, linkUrl "; //////////Get a count of the page view data $queryPurchasesCount = "SELECT COUNT(*) AS RowCount from ( " . $baseQueryLinks . ") As ResultCount"; $resPurchasesCount = mysql_query($queryPurchasesCount); if ($resPurchasesCount > 0) { $rowCount = mysql_fetch_object($resPurchasesCount); $totalResultCount = $rowCount->RowCount; } else { $totalResultCount = 0; } //////////Create the items per page array $itemsPerPageList = $this->getItemsPerPageList(); ///////////////////PAGING $currentPage = 1; $resultTotal = $totalResultCount; $startRecord = 1; if (isset($_GET['itemsPerPage'])) { switch ($_GET['itemsPerPage']) { case "20": $itemsPerPage = 20; $itemsPerPageList["20"]["selected"] = true; break; case "100": $itemsPerPage = 100; $itemsPerPageList["100"]["selected"] = true; break; default: $itemsPerPage = 50; $itemsPerPageList["50"]["selected"] = true; } } else { $itemsPerPage = 50; $itemsPerPageList["50"]["selected"] = true; } $endRecord = $itemsPerPage; $interface->assign('itemsPerPageList', $itemsPerPageList); if (isset($_GET['page'])) { $currentPage = $_GET['page']; // 1st record is easy, work out the start of this page $startRecord = ($currentPage - 1) * $itemsPerPage + 1; // Last record needs more care if ($resultTotal < $itemsPerPage) { // There are less records returned then one page, use total results $endRecord = $resultTotal; } else { if ($currentPage * $itemsPerPage > $resultTotal) { // The end of the current page runs past the last record, use total results $endRecord = $resultTotal; } else { // Otherwise use the last record on this page $endRecord = $currentPage * $itemsPerPage; } } } //////////Get the Page View Data with paging and sorting if (isset($_GET['reportSort'])) { $sortValue = $_GET['reportSort']; } //Create values for how to sort the table. $sortList = $this->getSortList(); if (!isset($sortValue)) { $sortValue = 'UrlASC'; } $sortList[$sortValue]["selected"] = true; $baseQueryLinks .= $sortList[$sortValue]['sql']; //append on a limit to return a result if (!isset($_REQUEST['exportToExcel'])) { $baseQueryLinks .= "LIMIT " . ($startRecord - 1) . ", " . $itemsPerPage . " "; } $resPurchases = mysql_query($baseQueryLinks); $resultsPurchases = array(); if ($resPurchases > 0) { //Build an array based on the data to dump out to the grid $i = 0; while ($r = mysql_fetch_array($resPurchases)) { $recordId = $r['recordId']; $fullId = $r['recordId']; if (preg_match('/econtentRecord(\\d+)/', $recordId, $matches)) { require_once ROOT_DIR . '/sys/eContent/EContentRecord.php'; $econtentRecord = new EContentRecord(); $econtentRecord->id = $matches[1]; $econtentRecord->find(true); $recordId = $econtentRecord->ilsId; $title = $econtentRecord->title; } else { $resource = new Resource(); $resource->record_id = $recordId; $resource->source = 'VuFind'; $resource->find(true); $title = $resource->title; } $tmp = array('recordId' => $recordId, 'recordUrl' => '/Record/' . $fullId, 'title' => $title, 'timesFollowed' => $r['timesFollowed'], 'linkHost' => $r['linkHost'], 'linkUrl' => $r['linkUrl']); $resultsPurchases[$i++] = $tmp; } } $interface->assign('resultLinks', $resultsPurchases); //////////Paging Array $summary = array('page' => $currentPage, 'perPage' => $itemsPerPage, 'resultTotal' => $totalResultCount, 'startRecord' => $startRecord, 'endRecord' => $endRecord); $interface->assign('recordCount', $summary['resultTotal']); $interface->assign('recordStart', $summary['startRecord']); $interface->assign('recordEnd', $summary['endRecord']); // Process Paging using VuFind Pager object if (strrpos($_SERVER["REQUEST_URI"], "page=")) { //replace the page variable with a new one $link = str_replace("page=" . $currentPage, "page=%d", $_SERVER["REQUEST_URI"]); } else { if (strrpos($_SERVER["REQUEST_URI"], "?")) { $link = $_SERVER["REQUEST_URI"] . "&page=%d"; } else { $link = $_SERVER["REQUEST_URI"] . "?page=%d"; } } $options = array('totalItems' => $summary['resultTotal'], 'fileName' => $link, 'perPage' => $summary['perPage']); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); ///////////////////END PAGING //////////Sorting $sortUrl = $_SERVER["REQUEST_URI"]; if (isset($sortValue)) { //Set the URL for sorting if (strrpos($_SERVER["REQUEST_URI"], "reportSort=")) { //replace the page variable with a new one $sortUrl = str_replace("sort=" . $currentPage, "reportSort=" . $sortValue, $_SERVER["REQUEST_URI"]); } else { if (strrpos($_SERVER["REQUEST_URI"], "?")) { $sortUrl = $_SERVER["REQUEST_URI"] . "&reportSort=" . $sortValue; } else { $sortUrl = $_SERVER["REQUEST_URI"] . "?reportSort=" . $sortValue; } } } $interface->assign('sortUrl', $sortUrl); $interface->assign('sortList', $sortList); //////////CHART //Create the chart and load data into the results. $queryDailyPurchases = "SELECT DATE_FORMAT(trackingDate, '%Y-%m-%d') as date, COUNT(externalLinkId) AS timesFollowed, linkHost FROM external_link_tracking " . "WHERE (DATE_FORMAT(trackingDate, '%Y-%m-%d')) BETWEEN '" . $selectedDateStart . "' AND '" . $selectedDateEnd . "' "; if (count($selectedHosts) > 0) { $hosts = join("','", $selectedHosts); $queryDailyPurchases .= "AND linkHost IN ('" . $hosts . "') "; } $queryDailyPurchases .= "GROUP BY DATE_FORMAT(trackingDate, '%Y-%m-%d'), linkHost ORDER BY trackingDate ASC"; $dailyUsage = mysql_query($queryDailyPurchases); //Initialize data by loading all of the dates that we are looking at so we can show the correct counts or each series on the right day. $check_date = $selectedDateStart; $datesInReport = array(); $linkUsageByHostByDay = array(); foreach ($allHosts as $hostName) { $linkUsageByHostByDay[$hostName] = array(); } while ($check_date != $selectedDateEnd) { $check_date = date("Y-m-d", strtotime("+1 day", strtotime($check_date))); $datesInReport[] = $check_date; //Default number of link usage for the day to 0 foreach ($allHosts as $host) { $linkUsageByHostByDay[$host][$check_date] = 0; } } //Chart section $reportData = new pData(); while ($r = mysql_fetch_array($dailyUsage)) { $linkHost = $r['linkHost']; $linkUsageByHostByDay[$linkHost][$r['date']] = $r['timesFollowed']; } foreach ($linkUsageByHostByDay as $hostName => $dailyResults) { $reportData->addPoints($dailyResults, $hostName); } $reportData->setAxisName(0, "Usage"); $reportData->addPoints($datesInReport, "Dates"); $reportData->setAbscissa("Dates"); /* Create the pChart object */ $myPicture = new pImage(700, 290, $reportData); /* Draw the background */ $Settings = array("R" => 225, "G" => 225, "B" => 225); $myPicture->drawFilledRectangle(0, 0, 700, 290, $Settings); /* Add a border to the picture */ $myPicture->drawRectangle(0, 0, 699, 289, array("R" => 0, "G" => 0, "B" => 0)); $myPicture->setFontProperties(array("FontName" => "sys/pChart/Fonts/verdana.ttf", "FontSize" => 9)); $myPicture->setGraphArea(50, 30, 670, 190); //$myPicture->drawFilledRectangle(30,30,670,150,array("R"=>255,"G"=>255,"B"=>255,"Surrounding"=>-200,"Alpha"=>10)); $myPicture->drawScale(array("DrawSubTicks" => TRUE, "LabelRotation" => 90)); $myPicture->setFontProperties(array("FontName" => "sys/pChart/Fonts/verdana.ttf", "FontSize" => 9)); $myPicture->drawLineChart(array("DisplayValues" => TRUE, "DisplayColor" => DISPLAY_AUTO)); /* Write the chart legend */ $myPicture->drawLegend(80, 20, array("Style" => LEGEND_NOBORDER, "Mode" => LEGEND_HORIZONTAL)); /* Render the picture (choose the best way) */ $time = time(); $chartHref = "/images/charts/dailyPurchases{$time}.png"; $chartPath = $configArray['Site']['local'] . $chartHref; $myPicture->render($chartPath); $interface->assign('chartPath', $chartHref); //////////EXPORT To EXCEL if (isset($_REQUEST['exportToExcel'])) { //PHPEXCEL // Create new PHPExcel object $objPHPExcel = new PHPExcel(); // Set properties $objPHPExcel->getProperties()->setTitle("External Link Usage Report")->setCategory("External Link Usage Report"); // Add some data $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', 'External Link Usage Report')->setCellValue('A3', 'Record Id')->setCellValue('B3', 'Url')->setCellValue('C3', 'Host')->setCellValue('D3', 'Usage'); $a = 4; //Loop Through The Report Data foreach ($resultsPurchases as $resultsPurchase) { $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . $a, $resultsPurchase['recordId'])->setCellValue('B' . $a, $resultsPurchase['linkUrl'])->setCellValue('C' . $a, $resultsPurchase['linkHost'])->setCellValue('D' . $a, $resultsPurchase['timesFollowed']); $a++; } $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true); $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true); $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true); // Rename sheet $objPHPExcel->getActiveSheet()->setTitle('Simple'); // Set active sheet index to the first sheet, so Excel opens this as the first sheet $objPHPExcel->setActiveSheetIndex(0); // Redirect output to a client's web browser (Excel5) header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="ExternalLinkReport.xls"'); header('Cache-Control: max-age=0'); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save('php://output'); exit; } $interface->setPageTitle('Report - External Link Tracking'); $interface->setTemplate('reportExternalLinks.tpl'); $interface->display('layout.tpl'); }
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('/&/', '&', $unscopedSearchUrl); $unscopedSearchUrl = str_replace('&', '&', $unscopedSearchUrl); // faster than preg_replace for simple substitutions } else { $unscopedSearchUrl .= "&searchSource=marmot"; } $unscopedSearchUrl .= "&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'); }
/** * Process parameters and display the page. * * @return void * @access public */ public function launch() { global $interface; global $configArray; global $action; $this->disallowBots(); $enabledActions = array(); // Check if requested action is enabled and configured $searchSettings = getExtraConfigArray('searches'); if (isset($searchSettings['BrowseExtended'])) { foreach ($searchSettings['BrowseExtended'] as $key => $val) { if ((bool) $val) { $enabledActions[] = $key; } } } if (!in_array($action, $enabledActions)) { PEAR::raiseError("Browse action {$action} not enabled"); } if (!isset($searchSettings["BrowseExtended:{$action}"])) { PEAR::raiseError("Browse action {$action} not configured"); } $settings = $searchSettings["BrowseExtended:{$action}"]; $searchObject = SearchObjectFactory::initSearchObject('SolrBrowseExtended'); $searchObject->init($action); $result = $searchObject->processSearch(true, true); if (PEAR::isError($result)) { PEAR::raiseError($result->getMessage()); } $interface->assign('sideRecommendations', $searchObject->getRecommendationsTemplates('side')); $displayQuery = $searchObject->displayQuery(); $interface->assign('lookfor', $displayQuery); $interface->assign('paginateTitle', translate("browse_extended_{$action}")); $interface->setPageTitle(translate("browse_extended_{$action}")); $interface->assign('snippet', 'RecordDrivers/Index/result-browse-snippet-' . strtolower($action) . '.tpl'); $interface->assign('more', 'RecordDrivers/Index/result-browse-more-' . strtolower($action) . '.tpl'); $interface->assign('homeAction', $action); // If no record found if ($searchObject->getResultTotal() < 1) { $interface->setTemplate('../BrowseExtended/list-none.tpl'); } else { $summary = $searchObject->getResultSummary(); $interface->assign('recordCount', $summary['resultTotal']); $interface->assign('recordStart', $summary['startRecord']); $interface->assign('recordEnd', $summary['endRecord']); $interface->assign('recordSet', $searchObject->getResultRecordHTML()); $interface->setTemplate('../BrowseExtended/browse.tpl'); // Process Paging $link = $searchObject->renderLinkPageTemplate(); $options = array('totalItems' => $summary['resultTotal'], 'fileName' => $link, 'perPage' => $summary['perPage']); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); } $_SESSION['lastSearchURL'] = $searchObject->renderSearchUrl(); $searchObject->close(); $scroller = new ResultScroller(); $scroller->init($searchObject, $result); $interface->assign('formAction', "Browse/{$action}"); // Done, display the page $interface->display('layout.tpl'); }
/** * Process incoming parameters and display the page. * * @return void * @access public */ public function launch() { global $configArray; global $interface; $catalog = ConnectionManager::connectToCatalog(); if (!$catalog || !$catalog->status) { PEAR::raiseError(new PEAR_Error('Cannot Load Catalog Driver')); } // Read in search-specific configurations: $searchSettings = getExtraConfigArray('searches'); if (isset($_GET['range'])) { // Initialise from the current search globals $searchObject = SearchObjectFactory::initSearchObject(); $searchObject->init(); // Are there "new item" filter queries specified in the config file? // If so, we should apply them as hidden filters so they do not show // up in the user-selected facet list. if (isset($searchSettings['NewItem']['filter'])) { $filter = is_array($searchSettings['NewItem']['filter']) ? $searchSettings['NewItem']['filter'] : array($searchSettings['NewItem']['filter']); foreach ($filter as $current) { $searchObject->addHiddenFilter($current); } } // Must have atleast Action and Module set to continue $interface->setPageTitle('New Item Search Results'); $interface->setTemplate('newitem-list.tpl'); //Get view & load template $currentView = $searchObject->getView(); $interface->assign('subpage', 'Search/list-' . $currentView . '.tpl'); $interface->assign('viewList', $searchObject->getViewList()); $interface->assign('sortList', $searchObject->getSortList()); $interface->assign('limitList', $searchObject->getLimitList()); $interface->assign('rssLink', $searchObject->getRSSUrl()); $interface->assign('range', $_GET['range']); // This code was originally designed to page through the results // retrieved from the catalog in parallel with paging through the // Solr results. The logical flaw in this approach is that if // we only retrieve one page of results from the catalog, we never // know the full extent of available results there! // // The code has now been changed to always pull in enough catalog // results to get a fixed number of pages worth of Solr results. Note // that if the Solr index is out of sync with the ILS, we may see fewer // results than expected. $tmp = $searchObject->getResultSummary(); $limit = $tmp['perPage']; if (isset($searchSettings['NewItem']['result_pages'])) { $resultPages = intval($searchSettings['NewItem']['result_pages']); if ($resultPages < 1) { $resultPages = 10; } } else { $resultPages = 10; } if (isset($configArray['Site']['indexBasedNewItems']) && $configArray['Site']['indexBasedNewItems']) { // Build RSS Feed for Results (if requested) if ($searchObject->getView() == 'rss') { // Throw the XML to screen echo $searchObject->buildRSS(); // And we're done exit; } // Process Search $result = $searchObject->processSearch(false, true); if (PEAR::isError($result)) { PEAR::raiseError($result->getMessage()); } // Store recommendations (facets, etc.) $interface->assign('topRecommendations', $searchObject->getRecommendationsTemplates('top')); $interface->assign('sideRecommendations', $searchObject->getRecommendationsTemplates('side')); } else { $newItems = $catalog->getNewItems(1, $limit * $resultPages, $_GET['range'], isset($_GET['department']) ? $_GET['department'] : null); // Special case -- if no new items were found, don't bother hitting // the index engine: if ($newItems['count'] > 0) { // Query Index for BIB Data $bibIDs = array(); for ($i = 0; $i < count($newItems['results']); $i++) { $bibIDs[] = $newItems['results'][$i]['id']; } if (!$searchObject->setQueryIDs($bibIDs)) { $interface->assign('infoMsg', 'too_many_new_items'); } // Build RSS Feed for Results (if requested) if ($searchObject->getView() == 'rss') { // Throw the XML to screen echo $searchObject->buildRSS(); // And we're done exit; } // Process Search $result = $searchObject->processSearch(false, true); if (PEAR::isError($result)) { PEAR::raiseError($result->getMessage()); } // Store recommendations (facets, etc.) $interface->assign('topRecommendations', $searchObject->getRecommendationsTemplates('top')); $interface->assign('sideRecommendations', $searchObject->getRecommendationsTemplates('side')); } else { if ($searchObject->getView() == 'rss') { // Special case -- empty RSS feed: // Throw the XML to screen echo $searchObject->buildRSS(array('response' => array('numFound' => 0), 'responseHeader' => array('params' => array('rows' => 0)))); // And we're done exit; } } } // Send the new items to the template $interface->assign('recordSet', $searchObject->getResultRecordHTML()); // Setup Record Count Display $summary = $searchObject->getResultSummary(); $interface->assign('recordCount', $summary['resultTotal']); $interface->assign('recordStart', $summary['startRecord']); $interface->assign('recordEnd', $summary['endRecord']); // Setup Paging $link = $searchObject->renderLinkPageTemplate(); $total = isset($result['response']['numFound']) ? $result['response']['numFound'] : 0; $options = array('totalItems' => $total, 'perPage' => $limit, 'fileName' => $link); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); // Save the URL of this search to the session so we can return to it // easily: $_SESSION['lastSearchURL'] = $searchObject->renderSearchUrl(); // Use 'New Items' as the display query e.g. in the breadcrumbs $_SESSION['lastSearchDisplayQuery'] = translate('New Items'); } else { $interface->setPageTitle('New Item Search'); $interface->setTemplate('newitem.tpl'); if (!isset($configArray['Site']['indexBasedNewItems']) || !$configArray['Site']['indexBasedNewItems']) { $list = $catalog->getFunds(); $interface->assign('fundList', $list); } // Find out if there are user configured range options; if not, // default to the standard 1/5/30 days: $ranges = array(); if (isset($searchSettings['NewItem']['ranges'])) { $tmp = explode(',', $searchSettings['NewItem']['ranges']); foreach ($tmp as $range) { $range = intval($range); if ($range > 0) { $ranges[] = $range; } } } if (empty($ranges)) { $ranges = array(1, 5, 30); } $interface->assign('ranges', $ranges); } $interface->display('layout.tpl'); }
function launch() { global $configArray; global $interface; global $user; // Publisher Filter $allPublishers = $this->getAllPublishers(); $interface->assign('publisherFilter', $allPublishers); $selectedPublisherFilter = null; if (isset($_REQUEST['publisherFilter'])) { $selectedPublisherFilter = $_REQUEST['publisherFilter']; } else { $selectedPublisherFilter = array(); } $interface->assign('selectedPublisherFilter', $selectedPublisherFilter); $publishers = empty($selectedPublisherFilter) ? $allPublishers : $selectedPublisherFilter; $interface->assign('publishers', $publishers); // Status Filter $allStatuses = $this->getStatuses(); $interface->assign('statusFilter', $allStatuses); $selectedStatusFilter = null; if (isset($_REQUEST['statusFilter'])) { $selectedStatusFilter = $_REQUEST['statusFilter']; } else { $selectedStatusFilter = array(); } $interface->assign('selectedStatusFilter', $selectedStatusFilter); $statuses = empty($selectedStatusFilter) ? $allStatuses : $selectedStatusFilter; $interface->assign('statuses', $statuses); // Date range filter (default to 1 hour ago) $startDate = new DateTime(); $startDate->modify("-1 hour"); if (isset($_REQUEST['startDate']) && strlen($_REQUEST['startDate']) > 0) { $startDate = DateTime::createFromFormat('m/d/Y', $_REQUEST['startDate']); $startDate->setTime(0, 0, 0); } $interface->assign('startDate', $startDate->format('m/d/Y')); $endDate = isset($_REQUEST['endDate']) && strlen($_REQUEST['endDate']) > 0 ? DateTime::createFromFormat('m/d/Y', $_REQUEST['endDate']) : new DateTime(); $interface->assign('endDate', $endDate->format('m/d/Y')); //Set the end date to the end of the day $endDate->setTime(24, 0, 0); // create a SQL clause to filter by selected publishers $publisherRestriction = null; if (isset($_REQUEST['publisherFilter'])) { $publishersToShow = array(); foreach ($_REQUEST['publisherFilter'] as $item) { $publishersToShow[] = "'" . mysql_escape_string(strip_tags($item)) . "'"; } if (!empty($publishersToShow)) { $publisherRestriction = "publisher IN (" . implode(",", $publishersToShow) . ") "; } } // create a SQL clause to filter by selected statuses $statusRestriction = null; if (isset($_REQUEST['statusFilter'])) { $statusesToShow = array(); foreach ($_REQUEST['statusFilter'] as $item) { $statusesToShow[] = "'" . mysql_escape_string(strip_tags($item)) . "'"; } if (!empty($statusesToShow)) { $statusRestriction = "status IN (" . implode(",", $statusesToShow) . ") "; } } // Packaging ID filter $packagingIdsToShow = array(); $packagingIdsRestriction = null; if (isset($_REQUEST['packagingIds'])) { $packagingIds = explode(',', $_REQUEST['packagingIds']); foreach ($packagingIds as $id) { if (is_numeric($id)) { $packagingIdsToShow[] = mysql_escape_string(strip_tags($id)); } } if (!empty($packagingIdsToShow)) { $packagingIdsRestriction = "packagingId IN (" . implode(",", $packagingIdsToShow) . ") "; } $interface->assign('packagingIds', implode(",", $packagingIdsToShow)); } $importDetails = new EContentImportDetailsEntry(); $importDetails->whereAdd('dateFound >= ' . $startDate->getTimestamp() . ' AND dateFound < ' . $endDate->getTimestamp()); if ($publisherRestriction) { $importDetails->whereAdd($publisherRestriction); } if ($statusRestriction) { $importDetails->whereAdd($statusRestriction); } if ($packagingIdsRestriction) { $importDetails->whereAdd($packagingIdsRestriction); } //Check to see if we are exporting to Excel if (isset($_REQUEST['exportToExcel'])) { $importDetails->find(); $records = array(); while ($importDetails->fetch()) { $records[] = clone $importDetails; } $this->exportToExcel($records); } // Number of row per page $perPage = 20; $datagrid =& new Structures_DataGrid($perPage); $datagrid->setDefaultSort(array('filename' => 'ASC')); $datagrid->bind($importDetails); $datagrid->addColumn(new Structures_DataGrid_Column('File Name', 'filename', 'filename', null, null, array($this, 'printFileNameAsLinkToDetails'))); $datagrid->addColumn(new Structures_DataGrid_Column('Publisher', 'publisher', 'publisher')); $datagrid->addColumn(new Structures_DataGrid_Column('Date Found', 'dateFound', 'dateFound', null, null, array($this, 'printDateFound'))); $datagrid->addColumn(new Structures_DataGrid_Column('Packaging ID', 'packagingId', 'packagingId')); $datagrid->addColumn(new Structures_DataGrid_Column('Status', 'status', 'status')); $datagrid->addColumn(new Structures_DataGrid_Column('Details', 'details', 'details', null, null, array($this, 'printLinkToDetails'))); $interface->assign('importDetailsTable', $datagrid->getOutput()); // create pager $params = array(); if (isset($_REQUEST['startDate']) && strlen($_REQUEST['startDate']) > 0) { $params['startDate'] = $startDate->format('m/d/Y'); } if (isset($_REQUEST['endDate']) && strlen($_REQUEST['endDate']) > 0) { $params['endDate'] = $endDate->format('m/d/Y'); } if (!empty($selectedPublisherFilter)) { $params['publisherFilter'] = $selectedPublisherFilter; } if (!empty($selectedStatusFilter)) { $params['statusFilter'] = $selectedStatusFilter; } if (!empty($packagingIdsToShow)) { $params['packagingIds'] = implode(',', $packagingIdsToShow); } $options = array('totalItems' => $datagrid->getRecordCount(), 'fileName' => $configArray['Site']['path'] . '/EContent/EContentImportDetails?' . http_build_query($params) . '&page=%d', 'perPage' => $perPage); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); $interface->setTemplate('eContentImportDetails.tpl'); $interface->setPageTitle('eContent Import Details'); $interface->display('layout.tpl'); }
function launch() { global $configArray; global $interface; global $user; global $timer; if (isset($_REQUEST['multiAction'])) { $multiAction = $_REQUEST['multiAction']; $locationId = isset($_REQUEST['location']) ? $_REQUEST['location'] : null; $cancelId = array(); $freeze = ''; $type = 'update'; if ($multiAction == 'cancelSelected') { $type = 'cancel'; $freeze = ''; } elseif ($multiAction == 'freezeSelected') { $type = 'update'; $freeze = 'on'; } elseif ($multiAction == 'thawSelected') { $type = 'update'; $freeze = 'off'; } elseif ($multiAction == 'updateSelected') { $type = 'update'; $freeze = ''; } $result = $this->catalog->driver->updateHoldDetailed($user->password, $type, '', null, $cancelId, $locationId, $freeze); $interface->assign('holdResult', $result); //Redirect back here without the extra parameters. $redirectUrl = $configArray['Site']['path'] . '/MyResearch/Holds?accountSort=' . ($selectedSortOption = isset($_REQUEST['accountSort']) ? $_REQUEST['accountSort'] : 'title'); if (isset($_REQUEST['section'])) { $redirectUrl .= "§ion=" . $_REQUEST['section']; } header("Location: " . $redirectUrl); die; } $interface->assign('allowFreezeHolds', true); $ils = $configArray['Catalog']['ils']; $showPosition = $ils == 'Horizon'; $showExpireTime = $ils == 'Horizon'; // Define sorting options $sortOptions = array('title' => 'Title', 'author' => 'Author', 'format' => 'Format', 'placed' => 'Date Placed', 'location' => 'Pickup Location', 'status' => 'Status'); if ($showPosition) { $sortOptions['position'] = 'Position'; } $interface->assign('sortOptions', $sortOptions); $selectedSortOption = isset($_REQUEST['accountSort']) ? $_REQUEST['accountSort'] : 'title'; $interface->assign('defaultSortOption', $selectedSortOption); $profile = $this->catalog->getMyProfile($user); $libraryHoursMessage = Location::getLibraryHoursMessage($profile['homeLocationId']); $interface->assign('libraryHoursMessage', $libraryHoursMessage); $allowChangeLocation = $ils == 'Millennium'; $interface->assign('allowChangeLocation', $allowChangeLocation); $showPlacedColumn = $ils == 'Horizon'; $interface->assign('showPlacedColumn', $showPlacedColumn); $showDateWhenSuspending = $ils == 'Horizon'; $interface->assign('showDateWhenSuspending', $showDateWhenSuspending); $interface->assign('showPosition', $showPosition); $interface->assign('showNotInterested', false); // Get My Transactions $patron = null; if ($this->catalog->status) { if ($user->cat_username) { $patron = $this->catalog->patronLogin($user->cat_username, $user->cat_password); $patronResult = $this->catalog->getMyProfile($patron); if (!PEAR_Singleton::isError($patronResult)) { $interface->assign('profile', $patronResult); } $interface->assign('sortOptions', $sortOptions); $selectedSortOption = isset($_REQUEST['accountSort']) ? $_REQUEST['accountSort'] : 'dueDate'; $interface->assign('defaultSortOption', $selectedSortOption); $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1; $recordsPerPage = isset($_REQUEST['pagesize']) && is_numeric($_REQUEST['pagesize']) ? $_REQUEST['pagesize'] : 25; $interface->assign('recordsPerPage', $recordsPerPage); if (isset($_GET['exportToExcel'])) { $recordsPerPage = -1; $page = 1; } $result = $this->catalog->getMyHolds($patron, $page, $recordsPerPage, $selectedSortOption); if (!PEAR_Singleton::isError($result)) { if (count($result) > 0) { $location = new Location(); $pickupBranches = $location->getPickupBranches($patronResult, null); $locationList = array(); foreach ($pickupBranches as $curLocation) { $locationList[$curLocation->locationId] = $curLocation->displayName; } $interface->assign('pickupLocations', $locationList); foreach ($result['holds'] as $sectionKey => $sectionData) { if ($sectionKey == 'unavailable') { $link = $_SERVER['REQUEST_URI']; if (preg_match('/[&?]page=/', $link)) { $link = preg_replace("/page=\\d+/", "page=%d", $link); } else { if (strpos($link, "?") > 0) { $link .= "&page=%d"; } else { $link .= "?page=%d"; } } if ($recordsPerPage != '-1') { $options = array('totalItems' => $result['numUnavailableHolds'], 'fileName' => $link, 'perPage' => $recordsPerPage, 'append' => false); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); } } //Processing of freeze messages? $timer->logTime("Got recordList of holds to display"); } //Make sure available holds come before unavailable $interface->assign('recordList', $result['holds']); //make call to export function if (isset($_GET['exportToExcelAvailable']) || isset($_GET['exportToExcelUnavailable'])) { if (isset($_GET['exportToExcelAvailable'])) { $exportType = "available"; } else { $exportType = "unavailable"; } $this->exportToExcel($result['holds'], $exportType, $showDateWhenSuspending, $showPosition, $showExpireTime); } } else { $interface->assign('recordList', 'You do not have any holds'); } } } } $interface->assign('patron', $patron); $hasSeparateTemplates = $interface->template_exists('MyResearch/availableHolds.tpl'); if ($hasSeparateTemplates) { $section = isset($_REQUEST['section']) ? $_REQUEST['section'] : 'available'; $interface->assign('section', $section); if ($section == 'available') { $interface->setPageTitle('Available Holds'); $interface->setTemplate('availableHolds.tpl'); } else { $interface->setPageTitle('On Hold'); $interface->setTemplate('unavailableHolds.tpl'); } } else { $interface->setPageTitle('My Holds'); $interface->setTemplate('holds.tpl'); } //print_r($patron); $interface->display('layout.tpl'); }
/** * Process parameters and display the page. * * @return void * @access public */ function launch() { global $configArray; global $interface; // Initialise from the current search globals $searchObject = SearchObjectFactory::initSearchObject(); $searchObject->init(); // Build RSS Feed for Results (if requested) if ($searchObject->getView() == 'rss') { // Throw the XML to screen echo $searchObject->buildRSS(); // And we're done exit; } // Determine whether to display book previews if (isset($configArray['Content']['previews'])) { $interface->assignPreviews(); } // TODO : Stats $interface->caching = false; // If no author is specified, display a blank search form: if (!isset($_GET['author'])) { $interface->setPageTitle('Author'); $interface->setTemplate('search.tpl'); $interface->display('layout.tpl'); return; } // If we made it this far, we have an author name to display: $interface->assign('author', $_GET['author']); // What language should we use? $this->_lang = $configArray['Site']['language']; // Retrieve User Search History -- note that we only want to offer a // "back to search" link if the saved URL is not for the current action; // when users first reach this page from search results, the "last URL" // will be their original search, which we want to link to. However, // since this module will later set the "last URL" value in order to // allow the user to return from a record view to this page, after they // return here, we will no longer have access to the last non-author // search, and it is better to display nothing than to provide an infinite // loop of links. Perhaps this can be solved more elegantly with a stack // or with multiple session variables, but for now this seems okay. $interface->assign('lastsearch', isset($_SESSION['lastSearchURL']) && !strstr($_SESSION['lastSearchURL'], 'Author/Home') ? $_SESSION['lastSearchURL'] : false); if (!$interface->is_cached('layout.tpl|Author' . $_GET['author'])) { // Clean up author string $author = str_replace('"', '', $_GET['author']); if (substr($author, strlen($author) - 1, 1) == ",") { $author = substr($author, 0, strlen($author) - 1); } $author = explode(',', $author); $interface->assign('author', $author); // Create First Name $fname = ''; if (isset($author[1])) { $fname = $author[1]; if (isset($author[2])) { // Remove punctuation if (strlen($author[2]) > 2 && substr($author[2], -1) == '.') { $author[2] = substr($author[2], 0, -1); } $fname = $author[2] . ' ' . $fname; } } // Remove dates $fname = preg_replace('/[0-9]+-[0-9]*/', '', $fname); // Build Author name to display. if (substr($fname, -3, 1) == ' ') { // Keep period after initial $authorName = $fname . ' '; } else { // No initial so strip any punctuation from the end if (substr(trim($fname), -1) == ',' || substr(trim($fname), -1) == '.') { $authorName = substr(trim($fname), 0, -1) . ' '; } else { $authorName = $fname . ' '; } } $authorName .= $author[0]; $interface->assign('authorName', trim($authorName)); // Pull External Author Content if ($searchObject->getPage() == 1) { // Only load Wikipedia info if turned on in config file: if (isset($configArray['Content']['authors']) && stristr($configArray['Content']['authors'], 'wikipedia')) { // Only use first two characters of language string; Wikipedia // uses language domains but doesn't break them up into regional // variations like pt-br or en-gb. $wiki_lang = substr($interface->getLanguage(), 0, 2); $authorInfo = $this->getWikipedia($authorName, $wiki_lang); $interface->assign('wiki_lang', $wiki_lang); if (!PEAR::isError($authorInfo)) { $interface->assign('info', $authorInfo); } } } } // Set Interface Variables // Those we can construct BEFORE the search is executed $interface->setPageTitle('Author Search Results'); $interface->assign('sortList', $searchObject->getSortList()); $interface->assign('limitList', $searchObject->getLimitList()); $interface->assign('viewList', $searchObject->getViewList()); $interface->assign('rssLink', $searchObject->getRSSUrl()); // Process Search $result = $searchObject->processSearch(false, true); if (PEAR::isError($result)) { PEAR::raiseError($result->getMessage()); } // 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)); // Assign interface variables $summary = $searchObject->getResultSummary(); $interface->assign('recordCount', $summary['resultTotal']); $interface->assign('recordStart', $summary['startRecord']); $interface->assign('recordEnd', $summary['endRecord']); $interface->assign('topRecommendations', $searchObject->getRecommendationsTemplates('top')); $interface->assign('sideRecommendations', $searchObject->getRecommendationsTemplates('side')); // Big one - our results $interface->assign('recordSet', $searchObject->getResultRecordHTML()); // Process Paging $link = $searchObject->renderLinkPageTemplate(); $options = array('totalItems' => $summary['resultTotal'], 'fileName' => $link, 'perPage' => $summary['perPage']); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); // Save the URL of this search to the session so we can return to it easily: $_SESSION['lastSearchURL'] = $searchObject->renderSearchUrl(); //Get view & load template $currentView = $searchObject->getView(); $interface->assign('subpage', 'Search/list-' . $currentView . '.tpl'); $interface->setTemplate('home.tpl'); $interface->display('layout.tpl', 'Author' . $_GET['author']); }
function launch() { global $configArray; global $interface; global $user; global $library; if (isset($library)) { $interface->assign('showRatings', $library->showRatings); } else { $interface->assign('showRatings', 1); } // Get My Transactions if ($this->catalog->status) { if ($user->cat_username) { $patron = $this->catalog->patronLogin($user->cat_username, $user->cat_password); if (PEAR_Singleton::isError($patron)) { PEAR_Singleton::raiseError($patron); } $patronResult = $this->catalog->getMyProfile($patron); if (!PEAR_Singleton::isError($patronResult)) { $interface->assign('profile', $patronResult); } //Check to see if there is an action to perform. if (isset($_REQUEST['readingHistoryAction']) && strlen($_REQUEST['readingHistoryAction']) > 0 && $_REQUEST['readingHistoryAction'] != 'exportToExcel') { //Perform the requested action $selectedTitles = isset($_REQUEST['selected']) ? $_REQUEST['selected'] : array(); $readingHistoryAction = $_REQUEST['readingHistoryAction']; $this->catalog->doReadingHistoryAction($readingHistoryAction, $selectedTitles); //redirect back to ourself without the action. header("Location: {$configArray['Site']['path']}/MyResearch/ReadingHistory"); die; } // Define sorting options if (strcasecmp($configArray['Catalog']['ils'], 'Millennium') == 0) { $sortOptions = array('title' => 'Title', 'author' => 'Author', 'checkedOut' => 'Checkout Date', 'format' => 'Format'); $selectedSortOption = isset($_REQUEST['accountSort']) ? $_REQUEST['accountSort'] : 'checkedOut'; } else { $sortOptions = array('title' => 'Title', 'author' => 'Author', 'checkedOut' => 'Checkout Date', 'returned' => 'Return Date', 'format' => 'Format'); $selectedSortOption = isset($_REQUEST['accountSort']) ? $_REQUEST['accountSort'] : 'returned'; } $interface->assign('sortOptions', $sortOptions); $interface->assign('defaultSortOption', $selectedSortOption); $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1; $recordsPerPage = isset($_REQUEST['pagesize']) && is_numeric($_REQUEST['pagesize']) ? $_REQUEST['pagesize'] : 25; $interface->assign('recordsPerPage', $recordsPerPage); if (isset($_REQUEST['readingHistoryAction']) && $_REQUEST['readingHistoryAction'] == 'exportToExcel') { $recordsPerPage = -1; $page = 1; } $result = $this->catalog->getReadingHistory($patron, $page, $recordsPerPage, $selectedSortOption); $link = $_SERVER['REQUEST_URI']; if (preg_match('/[&?]page=/', $link)) { $link = preg_replace("/page=\\d+/", "page=%d", $link); } else { if (strpos($link, "?") > 0) { $link .= "&page=%d"; } else { $link .= "?page=%d"; } } if ($recordsPerPage != '-1') { $options = array('totalItems' => $result['numTitles'], 'fileName' => $link, 'perPage' => $recordsPerPage, 'append' => false); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); } if (!PEAR_Singleton::isError($result)) { $interface->assign('historyActive', $result['historyActive']); $interface->assign('transList', $result['titles']); if (isset($_REQUEST['readingHistoryAction']) && $_REQUEST['readingHistoryAction'] == 'exportToExcel') { $this->exportToExcel($result['titles']); } } } } $interface->setTemplate('readingHistory.tpl'); $interface->setPageTitle('Reading History'); $interface->display('layout.tpl'); }
/** * Process parameters and display the page. * * @return void * @access public */ public function launch() { global $interface; global $configArray; // Initialise SearchObject. $this->searchObject->init(); $displayQuery = $this->searchObject->displayQuery(); $interface->setPageTitle(translate('Search Results') . (empty($displayQuery) ? '' : ' - ' . htmlspecialchars($displayQuery))); $interface->assign('lookfor', $displayQuery); $interface->assign('searchIndex', $this->searchObject->getSearchIndex()); $interface->assign('searchType', $this->searchObject->getSearchType()); // Search Summon $result = $this->searchObject->processSearch(true, true); // We'll need recommendations no matter how many results we found: $interface->assign('qtime', round($this->searchObject->getQuerySpeed(), 2)); $interface->assign('spellingSuggestions', $this->searchObject->getSpellingSuggestions()); $interface->assign('topRecommendations', $this->searchObject->getRecommendationsTemplates('top')); $interface->assign('sideRecommendations', $this->searchObject->getRecommendationsTemplates('side')); if ($result['recordCount'] > 0) { // If the "jumpto" parameter is set, jump to the specified result index: $this->_processJumpto($result); $summary = $this->searchObject->getResultSummary(); $page = $summary['page']; $interface->assign('recordCount', $summary['resultTotal']); $interface->assign('recordStart', $summary['startRecord']); $interface->assign('recordEnd', $summary['endRecord']); $interface->assign('recordSet', $result['documents']); $interface->assign('sortList', $this->searchObject->getSortList()); // If our result set is larger than the number of records that // Summon will let us page through, we should cut off the number // before passing it to our paging mechanism: $config = getExtraConfigArray('Summon'); $pageLimit = isset($config['General']['result_limit']) ? $config['General']['result_limit'] : 2000; $totalPagerItems = $summary['resultTotal'] < $pageLimit ? $summary['resultTotal'] : $pageLimit; // Process Paging $link = $this->searchObject->renderLinkPageTemplate(); $options = array('totalItems' => $totalPagerItems, 'fileName' => $link, 'perPage' => $summary['perPage']); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); // Display Listing of Results $interface->setTemplate('list.tpl'); $interface->assign('subpage', 'Summon/list-list.tpl'); } else { $interface->assign('recordCount', 0); // Set up special "no results" recommendations: $interface->assign('noResultsRecommendations', $this->searchObject->getRecommendationsTemplates('noresults')); // Was the empty result set due to an error? $error = $this->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, 'user.entered.query.is.malformed') || stristr($error, 'unknown.field')) { $interface->assign('parseError', true); } else { // Unexpected error -- let's treat this as a fatal condition. PEAR::raiseError(new PEAR_Error('Unable to process query<br />Summon Returned: ' . $error)); } } $interface->setTemplate('list-none.tpl'); } // 'Finish' the search... complete timers and log search history. $this->searchObject->close(); $interface->assign('time', round($this->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', $this->searchObject->isSavedSearch()); $interface->assign('searchId', $this->searchObject->getSearchId()); // Save the URL of this search to the session so we can return to it easily: $_SESSION['lastSearchURL'] = $this->searchObject->renderSearchUrl(); $interface->display('layout.tpl'); }
function loadUsageSummary($selectedDateStart, $selectedDateEnd, $selectedSourceFilter, $selectedAccessTypeFilter, $minFilter, $maxFilter, $interface) { $usageSummary = array(); $columns = array('title' => 'Title', 'source' => 'Source', 'readOnline' => 'Read Online', 'download' => 'Downloaded', 'numViews' => 'Total Usage', 'placeHold' => 'Hold Placed', 'checkedOut' => 'Checked Out', 'checkedIn' => 'Returned Early', 'numUsers' => 'Total Users'); $usageSummary['columns'] = $columns; $epubHistory = new EContentHistoryEntry(); //Setup paging for use in the query $currentPage = 1; $startRecord = 1; $itemsPerPage = isset($_REQUEST['itemsPerPage']) && is_numeric($_REQUEST['itemsPerPage']) ? $_REQUEST['itemsPerPage'] : 50; if (isset($_GET['page']) && is_numeric($_GET['page'])) { $currentPage = $_GET['page']; // 1st record is easy, work out the start of this page $startRecord = ($currentPage - 1) * $itemsPerPage + 1; } $startDateSqlFormatted = date('Y-m-d', strtotime($selectedDateStart)); $endDateSqlFormatted = date('Y-m-d', strtotime($selectedDateEnd)); //Create the base query $baseQuery = "SELECT econtent_record.id, " . "econtent_record.title, " . "econtent_record.source, " . "COUNT(DISTINCT userId) as numUsers, " . "COUNT(DISTINCT IF (action = 'Checked Out', userid, NULL)) as checkedOut, " . "COUNT(DISTINCT IF (action = 'Checked In', userid, NULL)) as checkedIn, " . "COUNT(DISTINCT IF (action = 'Read Online', userid, NULL)) as readOnline, " . "COUNT(DISTINCT IF (action = 'Place Hold', userid, NULL)) as placeHold, " . "COUNT(DISTINCT IF (action = 'Download', userid, NULL)) as download, " . "COUNT(DISTINCT IF (action = 'Read Online' OR action = 'Download', userid, NULL)) as numViews " . "FROM `econtent_history` " . "INNER join econtent_record on econtent_record.id = econtent_history.recordId "; $baseQuery .= "WHERE (DATE_FORMAT(econtent_history.openDate, '%Y-%m-%d')) BETWEEN '" . $startDateSqlFormatted . "' AND '" . $endDateSqlFormatted . "' "; if (count($selectedSourceFilter) > 0) { $sourceEntries = ""; foreach ($selectedSourceFilter as $curSource) { if (strlen($sourceEntries) > 0) { $sourceEntries .= ', '; } $sourceEntries .= "'" . mysql_escape_string($curSource) . "'"; } $baseQuery .= "AND econtent_record.source IN (" . $sourceEntries . ") "; } if (count($selectedAccessTypeFilter) > 0) { $accessTypes = join("','", $selectedAccessTypeFilter); $accessTypes = ""; foreach ($selectedAccessTypeFilter as $curAccessType) { if (strlen($accessTypes) > 0) { $accessTypes .= ', '; } $accessTypes .= "'" . mysql_escape_string($curAccessType) . "'"; } $baseQuery .= "AND econtent_record.accessType IN (" . $accessTypes . ") "; } $baseQuery .= "GROUP BY econtent_record.id " . "ORDER BY title, econtent_record.id ASC "; $countQuery = "SELECT COUNT(id) as totalResults FROM (" . $baseQuery . ") baseQuery "; $usageQuery = "SELECT * FROM (" . $baseQuery . ") baseQuery "; //Add max / min filters as needed since they depend on the base query if ($minFilter != "" && $maxFilter != "") { $countQuery .= "WHERE numViews >= " . $minFilter . " AND numViews <= " . $maxFilter . " "; $usageQuery .= "WHERE numViews >= " . $minFilter . " AND numViews <= " . $maxFilter . " "; } elseif ($minFilter != "") { $countQuery .= "WHERE numViews >= " . $minFilter . " "; $usageQuery .= "WHERE numViews >= " . $minFilter . " "; } elseif ($maxFilter != "") { $countQuery .= "WHERE numViews <= " . $maxFilter . " "; $usageQuery .= "WHERE numViews <= " . $maxFilter . " "; } if (!isset($_REQUEST['exportToExcel'])) { $usageQuery .= "LIMIT " . ($startRecord - 1) . ", " . $itemsPerPage . " "; } $epubHistory->query($usageQuery); $usageSummary['data'] = array(); while ($epubHistory->fetch()) { $resourceInfo = array(); $resourceInfo['title'] = $epubHistory->title; $resourceInfo['source'] = $epubHistory->source; $resourceInfo['record_id'] = $epubHistory->recordId; $resourceInfo['checkedOut'] = $epubHistory->checkedOut; $resourceInfo['checkedIn'] = $epubHistory->checkedIn; $resourceInfo['readOnline'] = $epubHistory->readOnline; $resourceInfo['placeHold'] = $epubHistory->placeHold; $resourceInfo['download'] = $epubHistory->download; $resourceInfo['numViews'] = $epubHistory->numViews; $resourceInfo['numUsers'] = $epubHistory->numUsers; $usageSummary['data'][] = $resourceInfo; } //Load total number of results $epubHistory->query($countQuery); if ($epubHistory->fetch()) { $totalResultCount = $epubHistory->totalResults; } else { $totalResultCount = 0; } //////////Paging Array $summary = array('page' => $currentPage, 'perPage' => $itemsPerPage, 'resultTotal' => $totalResultCount, 'startRecord' => $startRecord, 'endRecord' => $startRecord + count($usageSummary['data']) - 1); $interface->assign('recordCount', $summary['resultTotal']); $interface->assign('recordStart', $summary['startRecord']); $interface->assign('recordEnd', $summary['endRecord']); // Process Paging using VuFind Pager object if (strrpos($_SERVER["REQUEST_URI"], "page=")) { //replace the page variable with a new one $link = str_replace("page=" . $currentPage, "page=%d", $_SERVER["REQUEST_URI"]); } else { if (strrpos($_SERVER["REQUEST_URI"], "?")) { $link = $_SERVER["REQUEST_URI"] . "&page=%d"; } else { $link = $_SERVER["REQUEST_URI"] . "?page=%d"; } } $options = array('totalItems' => $summary['resultTotal'], 'fileName' => $link, 'perPage' => $summary['perPage']); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); return $usageSummary; }
/** * Display search results * * @param object $searchObject Search Object * * @return void */ public function showResults($searchObject) { global $interface; global $configArray; // Set Proxy URL if (isset($configArray['EZproxy']['host'])) { $interface->assign('proxy', $configArray['EZproxy']['host']); } // Handle hierarchical facets (request level 0 only for initial display) $facetConfig = getExtraConfigArray('facets'); if (isset($facetConfig['SpecialFacets']['hierarchical'])) { foreach ($facetConfig['SpecialFacets']['hierarchical'] as $facet) { $searchObject->addFacetPrefix(array($facet => '0/')); } } // Build RSS Feed for Results (if requested) if ($searchObject->getView() == 'rss') { // Throw the XML to screen echo $searchObject->buildRSS(); // And we're done exit; } $accept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : ''; // Build JSON for Results (if requested) if ($searchObject->getView() == 'json' || stristr($accept, 'application/json')) { // Allow cross-origin requests header('Access-Control-Allow-Origin: *'); // Throw the JSON to screen echo $searchObject->buildJSON(); // And we're done exit; } // Build XML for Results (if requested) if ($searchObject->getView() == 'xml' || stristr($accept, 'text/xml')) { // Allow cross-origin requests header('Access-Control-Allow-Origin: *'); // Throw the XML to screen echo $searchObject->buildXML(); // And we're done exit; } // Determine whether to display book previews if (isset($configArray['Content']['previews'])) { $interface->assignPreviews(); } $interface->assign('showContext', isset($configArray['Content']['showHierarchyTree']) ? $configArray['Content']['showHierarchyTree'] : false); // TODO : Stats, move inside the search object // Setup Statistics Index Connection if ($configArray['Statistics']['enabled']) { $this->_solrStats = ConnectionManager::connectToIndex('SolrStats'); } // Set Interface Variables // Those we can construct BEFORE the search is executed $displayQuery = $searchObject->displayQuery(); $interface->setPageTitle(translate('Search Results') . (empty($displayQuery) ? '' : ' - ' . htmlspecialchars($displayQuery))); // Process Search $result = $searchObject->processSearch(true, true); if (PEAR::isError($result)) { PEAR::raiseError($result->getMessage()); } // 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('isEmptySearch', $searchObject->isEmptySearch()); $interface->assign('lookfor', $displayQuery); $interface->assign('searchType', $searchObject->getSearchType()); // Will assign null for an advanced search $interface->assign('searchIndex', $searchObject->getSearchIndex()); $interface->assign('sortList', $searchObject->getSortList()); $interface->assign('viewList', $searchObject->getViewList()); $interface->assign('rssLink', $searchObject->getRSSUrl()); $interface->assign('limitList', $searchObject->getLimitList()); $interface->assign('searchWithoutFilters', $searchObject->renderSearchUrlWithoutFilters()); $interface->assign('searchWithFilters', $searchObject->renderSearchUrl()); if ($spatialDateRangeType = $searchObject->getSpatialDateRangeFilterType()) { $interface->assign('spatialDateRangeType', $spatialDateRangeType); } // We'll need recommendations no matter how many results we found: $interface->assign('topRecommendations', $searchObject->getRecommendationsTemplates('top')); $interface->assign('sideRecommendations', $searchObject->getRecommendationsTemplates('side')); $interface->assign('orFilters', $searchObject->getOrFilters()); // Whether RSI is enabled if (isset($configArray['OpenURL']['use_rsi']) && $configArray['OpenURL']['use_rsi']) { $interface->assign('rsi', true); } // Whether embedded openurl autocheck is enabled if (isset($configArray['OpenURL']['autocheck']) && $configArray['OpenURL']['autocheck']) { $interface->assign('openUrlAutoCheck', true); } // If no record found if ($searchObject->getResultTotal() < 1) { // Don't let bots crawl "no results" pages $this->disallowBots(); $interface->setTemplate('list-none.tpl'); $interface->assign('recordCount', 0); $interface->assign('removeAllFilters', $searchObject->renderSearchUrlWithoutFilters(array('prefiltered'))); // Set up special "no results" recommendations: $interface->assign('noResultsRecommendations', $searchObject->getRecommendationsTemplates('noresults')); // Was the empty result set due to an error? $error = $searchObject->getIndexError(); if ($error !== false) { // Solr 4 returns error as an array if (is_array($error)) { $error = $error['msg']; } // 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') || stristr($error, 'org.apache.solr.search.SyntaxError') || preg_match('/^undefined field/', $error)) { $interface->assign('parseError', true); } else { // Unexpected error -- let's treat this as a fatal condition. PEAR::raiseError(new PEAR_Error('Unable to process query<br />Solr Returned: ' . $error)); } } // TODO : Stats, move inside the search object // Save no records found stat if ($this->_solrStats) { $this->_solrStats->saveNoHits($_GET['lookfor'], $_GET['type']); } } else { // TODO : Stats, move inside the search object // Save search stat if ($this->_solrStats) { $this->_solrStats->saveSearch($_GET['lookfor'], $_GET['type']); } // If the "jumpto" parameter is set, jump to the specified result index: $this->_processJumpto($result); // Assign interface variables $summary = $searchObject->getResultSummary(); $interface->assign('recordCount', $summary['resultTotal']); $interface->assign('recordStart', $summary['startRecord']); $interface->assign('recordEnd', $summary['endRecord']); // Big one - our results $interface->assign('recordSet', $searchObject->getResultRecordHTML()); // Setup Display //Get view & load template $currentView = $searchObject->getView(); $interface->assign('subpage', 'Search/list-' . $currentView . '.tpl'); $interface->setTemplate('list.tpl'); // Process Paging $link = $searchObject->renderLinkPageTemplate(); $options = array('totalItems' => $summary['resultTotal'], 'fileName' => $link, 'perPage' => $summary['perPage']); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); } // '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()); // Save the URL of this search to the session so we can return to it easily: $_SESSION['lastSearchURL'] = $searchObject->renderSearchUrl(); // Save the display query too, so we can use it e.g. in the breadcrumbs $_SESSION['lastSearchDisplayQuery'] = $displayQuery; // Also save the search ID and type so user can edit the advanced search $_SESSION['lastSearchID'] = $searchObject->getSearchID(); $_SESSION['searchType'] = $searchObject->getSearchType(); // initialize the search result scroller for this search $scroller = new ResultScroller(); $scroller->init($searchObject, $result); // Done, display the page $interface->display('layout.tpl'); }
function launch() { global $interface; global $configArray; global $timer; global $user; global $analytics; //Check to see if a user is logged in with admin permissions if ($user && $user->hasRole('genealogyContributor')) { $interface->assign('userIsAdmin', true); } else { $interface->assign('userIsAdmin', false); } $searchSource = isset($_REQUEST['searchSource']) ? $_REQUEST['searchSource'] : 'local'; //Check to see if the year has been set and if so, convert to a filter and resend. $dateFilters = array('birthYear', 'deathYear'); 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']); $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']}/Genealogy/Results?{$queryParamString}"); exit; } } // Include Search Engine Class require_once ROOT_DIR . '/sys/' . $configArray['Genealogy']['engine'] . '.php'; $timer->logTime('Include search engine'); // Initialise from the current search globals $searchObject = SearchObjectFactory::initSearchObject($configArray['Genealogy']['searchObject']); $searchObject->init($searchSource); // 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); $allSearchSources = SearchSources::getSearchSources(); $translatedScope = $allSearchSources[$searchSource]['name']; $analytics->addSearch($translatedScope, $searchObject->displayQuery(), $searchObject->isAdvanced(), $searchObject->getFullSearchType(), $searchObject->hasAppliedFacets(), $searchObject->getResultTotal()); if ($searchObject->getResultTotal() < 1) { // No record found $interface->assign('sitepath', $configArray['Site']['path']); $interface->assign('subpage', 'Genealogy/list-none.tpl'); $interface->setTemplate('list.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)); } } $timer->logTime('no hits processing'); } 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 $title => $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', 'Genealogy/list-list.tpl'); $interface->setTemplate('list.tpl'); // Process Paging $link = $searchObject->renderLinkPageTemplate(); $options = array('totalItems' => $summary['resultTotal'], 'fileName' => $link, 'perPage' => $summary['perPage']); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); $timer->logTime('finish hits processing'); } /*if ($configArray['Statistics']['enabled'] && isset( $_GET['lookfor'])) { require_once(ROOT_DIR . '/Drivers/marmot_inc/SearchStat.php'); $searchStat = new SearchStat(); $searchStat->saveSearch( $_GET['lookfor'], $_GET['type'], $searchObject->getResultTotal()); }*/ // 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(); // Done, display the page $interface->display('layout.tpl'); }
function launch() { global $interface; $interface->setTemplate('econtentCollection.tpl'); $interface->setPageTitle('eContent Collection Report'); $endDate = isset($_REQUEST['endDate']) && strlen($_REQUEST['endDate']) > 0 ? DateTime::createFromFormat('m/d/Y', $_REQUEST['endDate']) : new DateTime(); $interface->assign('endDate', $endDate->format('m/d/Y')); if (isset($_REQUEST['startDate']) && strlen($_REQUEST['startDate']) > 0) { $startDate = DateTime::createFromFormat('m/d/Y', $_REQUEST['startDate']); } else { $startDate = new DateTime($endDate->format('m/d/Y') . " - 1 years"); } $interface->assign('startDate', $startDate->format('m/d/Y')); //Load source filter $sourceFilter = array(); $sources = $this->loadEContentSources(); $interface->assign('sourceFilter', $sources); $selectedSource = isset($_REQUEST['source']) ? $_REQUEST['source'] : $sources[0]; $interface->assign('source', $selectedSource); $interface->assign('showNumItems', strcasecmp($selectedSource, 'OverDrive') != 0); //Set the end date to the end of the day $endDate->setTime(24, 0, 0); $startDate->setTime(0, 0, 0); //Setup paging for use in the query $currentPage = 1; $startRecord = 1; $itemsPerPage = isset($_REQUEST['itemsPerPage']) && is_numeric($_REQUEST['itemsPerPage']) ? $_REQUEST['itemsPerPage'] : 50; if (isset($_GET['page']) && is_numeric($_GET['page'])) { $currentPage = $_GET['page']; // 1st record is easy, work out the start of this page $startRecord = ($currentPage - 1) * $itemsPerPage + 1; } if (isset($_REQUEST['exportToExcel'])) { $itemsPerPage = -1; } $collectionDetails = $this->loadCollectionDetails($selectedSource, $startDate, $endDate, $itemsPerPage, $startRecord); $interface->assign('collectionDetails', $collectionDetails['records']); //////////Paging Array $summary = array('page' => $currentPage, 'perPage' => $itemsPerPage, 'resultTotal' => $collectionDetails['resultTotal'], 'startRecord' => $startRecord, 'endRecord' => $startRecord + count($collectionDetails['records']) - 1); $interface->assign('recordCount', $collectionDetails['resultTotal']); $interface->assign('recordStart', $summary['startRecord']); $interface->assign('recordEnd', $summary['endRecord']); // Process Paging using VuFind Pager object if (strrpos($_SERVER["REQUEST_URI"], "page=")) { //replace the page variable with a new one $link = str_replace("page=" . $currentPage, "page=%d", $_SERVER["REQUEST_URI"]); } else { if (strrpos($_SERVER["REQUEST_URI"], "?")) { $link = $_SERVER["REQUEST_URI"] . "&page=%d"; } else { $link = $_SERVER["REQUEST_URI"] . "?page=%d"; } } $options = array('totalItems' => $summary['resultTotal'], 'fileName' => $link, 'perPage' => $summary['perPage']); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); //Export to Excel if (isset($_REQUEST['exportToExcel'])) { $this->exportToExcel($selectedSource, $collectionDetails['records']); } else { $this->getItemsPerPageList(); } $interface->assign('sidebar', 'MyAccount/account-sidebar.tpl'); $interface->display('layout.tpl'); }
function launch() { global $configArray; global $interface; global $library; // Initialise from the current search globals $searchObject = SearchObjectFactory::initSearchObject(); $searchObject->init(); // Build RSS Feed for Results (if requested) if ($searchObject->getView() == 'rss') { // Throw the XML to screen echo $searchObject->buildRSS(); // And we're done exit; } $interface->caching = false; if (!isset($_GET['author'])) { PEAR_Singleton::raiseError(new PEAR_Error('Unknown Author')); } else { $interface->assign('author', $_GET['author']); } // What language should we use? $this->lang = $configArray['Site']['language']; // Retrieve User Search History -- note that we only want to offer a // "back to search" link if the saved URL is not for the current action; // when users first reach this page from search results, the "last URL" // will be their original search, which we want to link to. However, // since this module will later set the "last URL" value in order to // allow the user to return from a record view to this page, after they // return here, we will no longer have access to the last non-author // search, and it is better to display nothing than to provide an infinite // loop of links. Perhaps this can be solved more elegantly with a stack // or with multiple session variables, but for now this seems okay. $interface->assign('lastsearch', isset($_SESSION['lastSearchURL']) && !strstr($_SESSION['lastSearchURL'], 'Author/Home') ? $_SESSION['lastSearchURL'] : false); $interface->assign('lookfor', $_GET['author']); $interface->assign('basicSearchIndex', 'Author'); $interface->assign('searchIndex', 'Author'); if (!$interface->is_cached('layout.tpl|Author' . $_GET['author'])) { // Clean up author string $author = $_GET['author']; if (substr($author, strlen($author) - 1, 1) == ",") { $author = substr($author, 0, strlen($author) - 1); } $author = explode(',', $author); $interface->assign('author', $author); // Create First Name $fname = ''; if (isset($author[1])) { $fname = $author[1]; if (isset($author[2])) { // Remove punctuation if (strlen($author[2]) > 2 && substr($author[2], -1) == '.') { $author[2] = substr($author[2], 0, -1); } $fname = $author[2] . ' ' . $fname; } } // Remove dates $fname = preg_replace('/[0-9]+-[0-9]*/', '', $fname); // Build Author name to display. if (substr($fname, -3, 1) == ' ') { // Keep period after initial $authorName = $fname . ' '; } else { // No initial so strip any punctuation from the end if (substr(trim($fname), -1) == ',' || substr(trim($fname), -1) == '.') { $authorName = substr(trim($fname), 0, -1) . ' '; } else { $authorName = $fname . ' '; } } $authorName .= $author[0]; $interface->assign('authorName', trim($authorName)); // Pull External Author Content if ($searchObject->getPage() == 1) { // Only load Wikipedia info if turned on in config file: if (isset($configArray['Content']['authors']) && stristr($configArray['Content']['authors'], 'wikipedia') && (!$library || $library->showWikipediaContent == 1)) { // Only use first two characters of language string; Wikipedia // uses language domains but doesn't break them up into regional // variations like pt-br or en-gb. $wiki_lang = substr($configArray['Site']['language'], 0, 2); $authorInfo = $this->getWikipedia($authorName, $wiki_lang); $interface->assign('wiki_lang', $wiki_lang); if (!PEAR_Singleton::isError($authorInfo)) { $interface->assign('info', $authorInfo); } } } } // Set Interface Variables // Those we can construct BEFORE the search is executed $interface->setPageTitle('Author Search Results'); $interface->assign('sortList', $searchObject->getSortList()); $interface->assign('limitList', $searchObject->getLimitList()); $interface->assign('viewList', $searchObject->getViewList()); $interface->assign('rssLink', $searchObject->getRSSUrl()); $interface->assign('filterList', $searchObject->getFilterList()); // Process Search /** @var PEAR_Error|null $result */ $result = $searchObject->processSearch(false, true); if (PEAR_Singleton::isError($result)) { PEAR_Singleton::raiseError($result->getMessage()); } // 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)); // Assign interface variables $summary = $searchObject->getResultSummary(); $interface->assign('recordCount', $summary['resultTotal']); $interface->assign('recordStart', $summary['startRecord']); $interface->assign('recordEnd', $summary['endRecord']); $interface->assign('sideRecommendations', $searchObject->getRecommendationsTemplates('side')); //Enable and disable functionality based on library settings global $library; global $locationSingleton; $location = $locationSingleton->getActiveLocation(); if (isset($library) && $location != null) { $interface->assign('showFavorites', $library->showFavorites); $interface->assign('showHoldButton', $location->showHoldButton == 1 && $library->showHoldButton == 1 ? 1 : 0); } else { if ($location != null) { $interface->assign('showFavorites', 1); $interface->assign('showHoldButton', $location->showHoldButton); } else { if (isset($library)) { $interface->assign('showFavorites', $library->showFavorites); $interface->assign('showHoldButton', $library->showHoldButton); } else { $interface->assign('showFavorites', 1); $interface->assign('showHoldButton', 1); } } } // Big one - our results $authorTitles = $searchObject->getResultRecordHTML(); $interface->assign('recordSet', $authorTitles); //Load similar author information. $authorIsbn = null; foreach ($authorTitles as $title) { if (isset($title['isbn'])) { if (is_array($title['isbn'])) { $authorIsbn = $title['isbn'][0]; } else { $authorIsbn = $title['isbn']; } break; } } if (!is_null($authorIsbn)) { //Make sure to trim off any format information from the ISBN $isbnParts = explode(' ', $authorIsbn); $authorIsbn = $isbnParts[0]; $novelist = NovelistFactory::getNovelist(); $enrichment['novelist'] = $novelist->loadEnrichment($authorIsbn, false, false, true); if ($enrichment) { $interface->assign('enrichment', $enrichment); } } // Setup Display $interface->assign('sitepath', $configArray['Site']['path']); // Process Paging $link = $searchObject->renderLinkPageTemplate(); $options = array('totalItems' => $summary['resultTotal'], 'fileName' => $link, 'perPage' => $summary['perPage']); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); // 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(); //Get view & load template $currentView = $searchObject->getView(); $interface->assign('subpage', 'Search/list-' . $currentView . '.tpl'); $interface->setTemplate('home.tpl'); $interface->display('layout.tpl', 'Author' . $_GET['author']); }
function launch() { global $configArray; global $interface; global $user; //////////Populate the Date Filter Start $today = getdate(); //Grab the Selected Date Start if (isset($_REQUEST['dateFilterStart'])) { if (preg_match('/\\d{1,2}\\/\\d{1,2}\\/\\d{4}/', $_REQUEST['dateFilterStart'])) { $selectedDateStart = DateTime::createFromFormat('m/d/Y', $_REQUEST['dateFilterStart']); $selectedDateStart = $selectedDateStart->getTimestamp(); } else { $selectedDateStart = strtotime($_REQUEST['dateFilterStart']); } } else { $selectedDateStart = strtotime('-30 days'); } $selectedDateStart = date('Y-m-d', $selectedDateStart); $interface->assign('selectedDateStart', $selectedDateStart); //Populate the Date Filter End //Grab the Selected End Date if (isset($_REQUEST['dateFilterEnd'])) { if (preg_match('/\\d{1,2}\\/\\d{1,2}\\/\\d{4}/', $_REQUEST['dateFilterEnd'])) { $selectedDateEnd = DateTime::createFromFormat('m/d/Y', $_REQUEST['dateFilterEnd']); $selectedDateEnd = $selectedDateEnd->getTimestamp(); } else { $selectedDateEnd = strtotime($_REQUEST['dateFilterEnd']); } } else { $selectedDateEnd = strtotime('today'); } $selectedDateEnd = date('Y-m-d', $selectedDateEnd); $interface->assign('selectedDateEnd', $selectedDateEnd); //////////Populate the Stores Filter $queryStoresFilter = "SELECT DISTINCT store AS Store FROM purchase_link_tracking ORDER BY Store ASC"; $resStoresFilter = mysql_query($queryStoresFilter); $allStores = array(); $i = 0; while ($r = mysql_fetch_array($resStoresFilter)) { $allStores[] = $r['Store']; } $interface->assign('resultsStoresFilter', $allStores); //////////Grab the Selected Stores Filter Value $selectedStoresFilter = array(); if (isset($_REQUEST['storesFilter'])) { $selectedStoresFilter = $_REQUEST['storesFilter']; } else { //Pre-Populate the Stores Filter MultiSelect list $queryStoresPreSelect = "SELECT DISTINCT store AS Store FROM purchase_link_tracking\n\t\t\t\tORDER BY Store ASC"; $resStoresPreSelect = mysql_query($queryStoresPreSelect); $i = 0; while ($r = mysql_fetch_array($resStoresPreSelect)) { $selectedStoresFilter[$i++] = $r['Store']; } } $interface->assign('selectedStoresFilter', $selectedStoresFilter); $baseQueryPurchases = "SELECT COUNT(purchaseLinkId) AS Purchases, store AS Store " . "FROM purchase_link_tracking " . "WHERE (DATE_FORMAT(trackingDate, '%Y-%m-%d')) BETWEEN '" . $selectedDateStart . "' AND '" . $selectedDateEnd . "' "; if (count($selectedStoresFilter) > 0) { $stores = join("','", $selectedStoresFilter); $baseQueryPurchases .= "AND store IN ('" . $stores . "') "; } $baseQueryPurchases .= "GROUP BY store "; //////////Get a count of the page view data $queryPurchasesCount = "SELECT COUNT(*) AS RowCount from ( " . $baseQueryPurchases . ") As ResultCount"; $resPurchasesCount = mysql_query($queryPurchasesCount); $rowCount = mysql_fetch_object($resPurchasesCount); $totalResultCount = $rowCount->RowCount; //////////Create the items per page array $itemsPerPageList = array(); $itemsPerPageList = $this->getItemsPerPageList(); ///////////////////PAGING $currentPage = 1; $resultTotal = $totalResultCount; $startRecord = 1; if (isset($_GET['itemsPerPage'])) { switch ($_GET['itemsPerPage']) { case "20": $itemsPerPage = 20; $itemsPerPageList["20"]["selected"] = true; break; case "100": $itemsPerPage = 100; $itemsPerPageList["100"]["selected"] = true; break; default: $itemsPerPage = 50; $itemsPerPageList["50"]["selected"] = true; } } else { $itemsPerPage = 50; $itemsPerPageList["50"]["selected"] = true; } $endRecord = $itemsPerPage; $interface->assign('itemsPerPageList', $itemsPerPageList); if (isset($_GET['page'])) { $currentPage = $_GET['page']; // 1st record is easy, work out the start of this page $startRecord = ($currentPage - 1) * $itemsPerPage + 1; // Last record needs more care if ($resultTotal < $itemsPerPage) { // There are less records returned then one page, use total results $endRecord = $resultTotal; } else { if ($currentPage * $itemsPerPage > $resultTotal) { // The end of the curent page runs past the last record, use total results $endRecord = $resultTotal; } else { // Otherwise use the last record on this page $endRecord = $currentPage * $itemsPerPage; } } } //////////Get the Page View Data with paging and sorting if (isset($_GET['reportSort'])) { $sortValue = $_GET['reportSort']; } //////////Create a sort array $sortList = $this->getSortList(); if (isset($sortValue)) { switch ($sortValue) { case "PurchasesDESC": $baseQueryPurchases .= "ORDER BY purchases DESC "; $sortList["PurchasesDESC"]["selected"] = true; break; case "PurchasesASC": $baseQueryPurchases .= "ORDER BY purchases ASC "; $sortList["PurchasesASC"]["selected"] = true; break; case "StoreASC": $baseQueryPurchases .= "ORDER BY store ASC "; $sortList["StoreASC"]["selected"] = true; break; case "StoreDESC": $baseQueryPurchases .= "ORDER BY store DESC "; $sortList["StoreDESC"]["selected"] = true; break; default: $baseQueryPurchases .= "ORDER BY store ASC "; $sortList["StoreASC"]["selected"] = true; } } else { $baseQueryPurchases .= "ORDER BY store ASC "; } //append on a limit to return a result if (!isset($_REQUEST['exportToExcel'])) { $baseQueryPurchases .= "LIMIT " . ($startRecord - 1) . ", " . $itemsPerPage . " "; } $resPurchases = mysql_query($baseQueryPurchases); //Build an array based on the data to dump out to the grid $resultsPurchases = array(); $i = 0; while ($r = mysql_fetch_array($resPurchases)) { $tmp = array('Purchases' => $r['Purchases'], 'Store' => $r['Store']); $resultsPurchases[$i++] = $tmp; } $interface->assign('resultsPurchases', $resultsPurchases); //////////Paging Array $summary = array('page' => $currentPage, 'perPage' => $itemsPerPage, 'resultTotal' => $totalResultCount, 'startRecord' => $startRecord, 'endRecord' => $endRecord); $interface->assign('recordCount', $summary['resultTotal']); $interface->assign('recordStart', $summary['startRecord']); $interface->assign('recordEnd', $summary['endRecord']); // Process Paging using VuFind Pager object if (strrpos($_SERVER["REQUEST_URI"], "page=")) { //replace the page variable with a new one $link = str_replace("page=" . $currentPage, "page=%d", $_SERVER["REQUEST_URI"]); } else { if (strrpos($_SERVER["REQUEST_URI"], "?")) { $link = $_SERVER["REQUEST_URI"] . "&page=%d"; } else { $link = $_SERVER["REQUEST_URI"] . "?page=%d"; } } $options = array('totalItems' => $summary['resultTotal'], 'fileName' => $link, 'perPage' => $summary['perPage']); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); ///////////////////END PAGING //////////Sorting $sortUrl = $_SERVER["REQUEST_URI"]; if (isset($sortValue)) { //Set the URL for sorting if (strrpos($_SERVER["REQUEST_URI"], "reportSort=")) { //replace the page variable with a new one $sortUrl = str_replace("sort=" . $currentPage, "reportSort=" . $sortValue, $_SERVER["REQUEST_URI"]); } else { if (strrpos($_SERVER["REQUEST_URI"], "?")) { $sortUrl = $_SERVER["REQUEST_URI"] . "&reportSort=" . $sortValue; } else { $sortUrl = $_SERVER["REQUEST_URI"] . "?reportSort=" . $sortValue; } } } $interface->assign('sortUrl', $sortUrl); $interface->assign('sortList', $sortList); //////////CHART //Create the chart and load data into the results. $queryDailyPurchases = "SELECT DATE_FORMAT(trackingDate, '%Y-%m-%d') as date, COUNT(recordId) AS Purchases, store AS Store FROM purchase_link_tracking " . "WHERE (DATE_FORMAT(trackingDate, '%Y-%m-%d')) BETWEEN '" . $selectedDateStart . "' AND '" . $selectedDateEnd . "' "; if (count($selectedStoresFilter) > 0) { $stores = join("','", $selectedStoresFilter); $queryDailyPurchases .= "AND store IN ('" . $stores . "') "; } $queryDailyPurchases .= "GROUP BY DATE_FORMAT(trackingDate, '%Y-%m-%d'), store ORDER BY trackingDate ASC"; $dailyPurchases = mysql_query($queryDailyPurchases); //Initialize data by loading all of the dates that we are looking at so we can show the correct counts or each series on the right day. $check_date = $selectedDateStart; $datesInReport = array(); $purchasesByStoreByDay = array(); foreach ($allStores as $storeName) { $purchasesByStoreByDay[$storeName] = array(); } $numDatesChecked = 0; //Prevent infinite loops while ($check_date != $selectedDateEnd && $numDatesChecked < 3000) { $check_date = date("Y-m-d", strtotime("+1 day", strtotime($check_date))); $datesInReport[] = $check_date; //Default number of purchases for the day to 0 foreach ($allStores as $storeName) { $purchasesByStoreByDay[$storeName][$check_date] = 0; } $numDatesChecked++; } //Chart section $reportData = new pData(); while ($r = mysql_fetch_array($dailyPurchases)) { $store = $r['Store']; $purchasesByStoreByDay[$store][$r['date']] = $r['Purchases']; } foreach ($purchasesByStoreByDay as $storeName => $dailyResults) { $reportData->addPoints($dailyResults, $storeName); } $reportData->setAxisName(0, "Purchases"); $reportData->addPoints($datesInReport, "Dates"); $reportData->setAbscissa("Dates"); /* Create the pChart object */ $myPicture = new pImage(700, 290, $reportData); /* Draw the background */ $Settings = array("R" => 225, "G" => 225, "B" => 225); $myPicture->drawFilledRectangle(0, 0, 700, 290, $Settings); /* Add a border to the picture */ $myPicture->drawRectangle(0, 0, 699, 289, array("R" => 0, "G" => 0, "B" => 0)); $myPicture->setFontProperties(array("FontName" => "sys/pChart/Fonts/verdana.ttf", "FontSize" => 9)); $myPicture->setGraphArea(50, 30, 670, 190); //$myPicture->drawFilledRectangle(30,30,670,150,array("R"=>255,"G"=>255,"B"=>255,"Surrounding"=>-200,"Alpha"=>10)); $myPicture->drawScale(array("DrawSubTicks" => TRUE, "LabelRotation" => 90)); $myPicture->setFontProperties(array("FontName" => "sys/pChart/Fonts/verdana.ttf", "FontSize" => 9)); $myPicture->drawLineChart(array("DisplayValues" => TRUE, "DisplayColor" => DISPLAY_AUTO)); /* Write the chart legend */ $myPicture->drawLegend(80, 20, array("Style" => LEGEND_NOBORDER, "Mode" => LEGEND_HORIZONTAL)); /* Render the picture (choose the best way) */ $time = time(); $chartHref = "/images/charts/dailyPurchases{$time}.png"; $chartPath = $configArray['Site']['local'] . $chartHref; $myPicture->render($chartPath); $interface->assign('chartPath', $chartHref); //EXPORT To EXCEL if (isset($_REQUEST['exportToExcel'])) { //PHPEXCEL // Create new PHPExcel object $objPHPExcel = new PHPExcel(); // Set properties $objPHPExcel->getProperties()->setCreator("DCL")->setLastModifiedBy("DCL")->setTitle("Office 2007 XLSX Document")->setSubject("Office 2007 XLSX Document")->setDescription("Office 2007 XLSX, generated using PHP.")->setKeywords("office 2007 openxml php")->setCategory("Purchases Report"); // Add some data $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', 'Purchases Report')->setCellValue('A3', 'STORE')->setCellValue('B3', 'PURCHASES'); $a = 4; //Loop Through The Report Data foreach ($resultsPurchases as $resultsPurchases) { $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . $a, $resultsPurchases['Store'])->setCellValue('B' . $a, $resultsPurchases['Purchases']); $a++; } $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true); $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true); // Rename sheet $objPHPExcel->getActiveSheet()->setTitle('Purchases'); // Set active sheet index to the first sheet, so Excel opens this as the first sheet $objPHPExcel->setActiveSheetIndex(0); // Redirect output to a client's web browser (Excel5) header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="PurchaseLinkReport.xls"'); header('Cache-Control: max-age=0'); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save('php://output'); exit; } $interface->setPageTitle('Report - Purchase Tracking'); $interface->setTemplate('reportPurchase.tpl'); $interface->display('layout.tpl'); }
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('/&/', '&', $unscopedSearchUrl); } else { $unscopedSearchUrl .= "&searchSource=marmot"; } $unscopedSearchUrl .= "&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'); }
/** * Assign all necessary values to the interface. * * @return void * @access public */ public function assign() { global $interface; $currentSort = isset($_REQUEST['sort']) ? $_REQUEST['sort'] : 'saved'; if (!isset($this->sortOptions[$currentSort])) { $currentSort = 'saved'; } $interface->assign('listEditAllowed', $this->_allowEdit); // Get html for the records $resourceList = array(); $searchObjects = array(); $searchObject = SearchObjectFactory::initSearchObject(); foreach ($this->_favorites as $favorite) { $source = $favorite->source; $data = $favorite->data; if (!empty($data)) { $data = unserialize($data); } $sortKey = $favorite->saved; if ($this->_publicList) { $interface->assign('listNotes', $favorite->notes); } if ($source == 'VuFind') { if (empty($data)) { // Fetch data from index for backwards compatibility and store it in the resource $data = $searchObject->getIndexEngine()->getRecord($favorite->record_id); if ($data) { $resource = new Resource(); $resource->id = $favorite->id; $resource->source = $favorite->source; if ($resource->find(true)) { $resource->data = serialize($data); $resource->update(); } } } $record = RecordDriverFactory::initRecordDriver($data); $tpl = $this->_publicList ? $record->getSearchResult($this->_viewType) : $record->getListEntry($this->_user, $this->_listId, $this->_allowEdit); $html = $interface->fetch($tpl); switch ($currentSort) { case 'title': $sortKey = isset($data['title_sort']) ? $data['title_sort'] : ''; break; case 'author': $sortKey = isset($data['author']) ? $data['author'] : ''; break; case 'date': $sortKey = isset($data['main_date_str']) ? $data['main_date_str'] : isset($data['publishDate'][0]) ? $data['publishDate'][0] : ''; break; case 'format': $sortKey = isset($data['format'][0]) ? translate($data['format'][0]) : ''; break; } } else { if (!isset($searchObjects[$source])) { $searchObjects[$source] = SearchObjectFactory::initSearchObject($source); if ($searchObjects[$source] === false) { error_log("Could not create search object for source '{$source}'"); continue; } } $html = $this->_publicList ? $searchObjects[$source]->getPublicListHTML($data, $this->_viewType) : $searchObjects[$source]->getResultHTML($data, $this->_user, $this->_listId, $this->_allowEdit); if ($source == 'MetaLib') { switch ($currentSort) { case 'title': $sortKey = isset($data['Title'][0]) ? $data['Title'][0] : ' '; break; case 'author': $sortKey = isset($data['Author'][0]) ? $data['Author'][0] : ' '; break; case 'date': $sortKey = isset($data['main_date_str']) ? $data['main_date_str'] : isset($data['publicationDate'][0]) ? $data['publicationDate'][0] : ' '; break; case 'format': $sortKey = isset($data['format'][0]) ? translate($data['format'][0]) : ' '; break; } } else { switch ($currentSort) { case 'title': $sortKey = isset($data['title']) ? $data['title'] : ' '; break; case 'author': $sortKey = isset($data['author'][0]) ? $data['author'][0] : ' '; break; case 'date': $sortKey = isset($data['main_date_str']) ? $data['main_date_str'] : isset($data['publicationDate']) ? $data['publicationDate'] : ' '; break; case 'format': $sortKey = isset($data['format']) ? translate($data['format']) : ' '; break; } } } $sortKey = mb_strtolower($sortKey, 'UTF-8'); $sortKey .= '_' . $favorite->record_id; $resourceList[$sortKey] = $html; } // Setup paging variables if (isset($_REQUEST['page'])) { $page = $_REQUEST['page']; $page = intval($page); if ($page < 1) { $page = 1; } } else { $page = 1; } $searchObject->init(); $perPage = $searchObject->getLimit(); $recordCount = count($this->_favorites); $startRecord = ($page - 1) * $perPage; // Sort and slice the array ksort($resourceList); $resourceList = array_slice($resourceList, $startRecord, $perPage, true); $html = array(); $interface->assign('resourceList', $resourceList); // Set up paging of list contents: $endRecord = $startRecord + $perPage; if ($endRecord > $recordCount) { $endRecord = $recordCount; } $interface->assign('recordCount', $recordCount); $interface->assign('recordStart', $startRecord + 1); $interface->assign('recordEnd', $endRecord); $options = array('totalItems' => $recordCount, 'perPage' => $perPage, 'fileName' => $searchObject->renderLinkPageTemplate()); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); // Sorting options $sortList = array(); foreach ($this->sortOptions as $sort => $desc) { $sortList[$sort] = array('sortUrl' => $searchObject->renderLinkWithSort($sort), 'desc' => $desc, 'selected' => $sort == $currentSort); } $interface->assign('sortList', $sortList); $interface->assign('limitList', $searchObject->getLimitList()); }