function launch() { global $interface; global $user; global $configArray; $suggestions = Suggestions::getSuggestions(); // Setup Search Engine Connection $class = $configArray['Index']['engine']; $url = $configArray['Index']['url']; /** @var SearchObject_Solr $solrDb */ $solrDb = new $class($url); $resourceList = array(); $curIndex = 0; if (is_array($suggestions)) { foreach ($suggestions as $suggestion) { $interface->assign('resultIndex', ++$curIndex); $record = $solrDb->getRecord($suggestion['titleInfo']['id']); /** @var IndexRecord $recordDriver */ $recordDriver = RecordDriverFactory::initRecordDriver($record); $resourceEntry = $interface->fetch($recordDriver->getSearchResult()); $resourceList[] = $resourceEntry; } } $interface->assign('resourceList', $resourceList); //Check to see if the user has rated any titles $interface->assign('hasRatings', $user->hasRatings()); $interface->setPageTitle('Recommended for you'); $interface->assign('sidebar', 'MyAccount/account-sidebar.tpl'); $interface->setTemplate('suggestedTitles.tpl'); $interface->display('layout.tpl'); }
/** * Constructor * * @access public */ public function __construct() { global $interface; global $configArray; // Call parent constructor parent::__construct(); // Fetch Record $config = getExtraConfigArray('MetaLib'); $metalib = new MetaLib(); $this->record = $metalib->getRecord($_REQUEST['id']); if (PEAR::isError($this->record)) { PEAR::raiseError($this->record); } // Get record driver $this->recordDriver = RecordDriverFactory::initRecordDriver($this->record); // Set Proxy URL $interface->assign('proxy', isset($configArray['EZproxy']['host']) ? $configArray['EZproxy']['host'] : false); // 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); } // Send record ID to template $interface->assign('id', $_REQUEST['id']); // Send down legal export formats (if any): $interface->assign('exportFormats', array('RefWorks', 'EndNote')); // Set AddThis User $interface->assign('addThis', isset($configArray['AddThis']['key']) ? $configArray['AddThis']['key'] : false); // Get core metadata $interface->assign('coreMetadata', $this->recordDriver->getCoreMetadata()); }
/** * Process incoming parameters and display the page. * * @return void * @access public */ public function launch() { global $configArray, $interface; // Execute Default Tab $defaultTab = isset($configArray['Site']['defaultRecordTab']) ? $configArray['Site']['defaultRecordTab'] : 'Holdings'; // Don't let bots crawl holdings if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|crawl|slurp|spider/i', $_SERVER['HTTP_USER_AGENT'])) { $defaultTab = 'Description'; } else { // We need to do a whole bunch of extra work to determine the default // tab if we have the hideHoldingsTabWhenEmpty setting turned on; only // do this work if we absolutely have to! if (isset($configArray['Site']['hideHoldingsTabWhenEmpty']) && $configArray['Site']['hideHoldingsTabWhenEmpty'] && $defaultTab == "Holdings") { $db = ConnectionManager::connectToIndex(); if (!($record = $db->getRecord($_REQUEST['id']))) { PEAR::raiseError(new PEAR_Error('Record Does Not Exist')); } $recordDriver = RecordDriverFactory::initRecordDriver($record); $showHoldingsTab = $recordDriver->hasHoldings(); $defaultTab = $showHoldingsTab ? 'Holdings' : 'Description'; } } include_once $defaultTab . '.php'; $service = new $defaultTab(); $service->recordHit(); $service->launch(); }
/** * Process parameters and display the page. * * @return void * @access public */ public function launch() { global $interface; // Get My Transactions if ($patron = UserAccount::catalogLogin()) { if (PEAR::isError($patron)) { $this->handleCatalogError($patron); } else { // Renew Items if (isset($_POST['renewAll']) || isset($_POST['renewSelected'])) { $renewResult = $this->_renewItems($patron); } $result = $this->catalog->getMyTransactions($patron); if (PEAR::isError($result)) { PEAR::raiseError($result); } $transList = array(); foreach ($result as $data) { $current = array('ils_details' => $data); if ($record = $this->db->getRecord($data['id'])) { $formats = isset($record['format']) ? $record['format'] : ''; if (!is_array($formats)) { $formats = array($formats); } foreach ($formats as &$format) { $format = preg_replace('/^\\d\\//', '', $format); $format = rtrim($format, "/"); } $driver = RecordDriverFactory::initRecordDriver($record); if (!empty($data['title'])) { $title = $data['title']; } else { $title = isset($record['title']) ? $record['title'] : null; } $current += array('id' => $record['id'], 'isbn' => isset($record['isbn']) ? $record['isbn'] : null, 'author' => isset($record['author']) ? $record['author'] : null, 'title' => $title, 'format' => $formats, 'summImages' => $driver ? $driver->getAllImages() : null, 'summThumb' => $driver ? $driver->getThumbnail() : null); } $transList[] = $current; } if ($this->checkRenew) { $transList = $this->_addRenewDetails($transList); } $interface->assign('transList', $transList); $profile = $this->catalog->getMyProfile($patron); if (!PEAR::isError($profile)) { $interface->assign('profile', $profile); } } } Login::setupLoginFormVars(); $interface->setTemplate('checkedout.tpl'); $interface->setPageTitle('Checked Out Items'); $interface->display('layout.tpl'); }
/** * Get similar items and return html snippet * * @return void */ public function launch() { global $interface; if (!isset($_REQUEST['id'])) { return; } $this->db = ConnectionManager::connectToIndex(); // Retrieve the record from the index if (!($record = $this->db->getRecord($_REQUEST['id']))) { PEAR::raiseError(new PEAR_Error('Record Does Not Exist')); } $this->recordDriver = RecordDriverFactory::initRecordDriver($record); $interface->display($this->recordDriver->getSimilarItems()); }
function launch() { global $configArray; global $interface; global $user; //Build the actual view $interface->setTemplate('../Record/view-series.tpl'); $eContentRecord = new EContentRecord(); $id = strip_tags($_REQUEST['id']); $eContentRecord->id = $id; $eContentRecord->find(true); require_once 'Enrichment.php'; $enrichment = new EcontentRecord_Enrichment(); $enrichmentData = $enrichment->loadEnrichment($eContentRecord->getIsbn()); $seriesTitle = ''; $seriesAuthors = array(); $seriesTitles = array(); $resourceList = array(); if (isset($enrichmentData['novelist']) && isset($enrichmentData['novelist']['series'])) { $seriesTitles = $enrichmentData['novelist']['series']; //Loading the series title is not reliable. Do not try to load it. if (isset($seriesTitles) && is_array($seriesTitles)) { foreach ($seriesTitles as $title) { if (isset($title['series']) && strlen($title['series']) > 0 && !isset($seriesTitle)) { $seriesTitle = $title['series']; $interface->assign('seriesTitle', $seriesTitle); } if (isset($title['author'])) { $seriesAuthors[$title['author']] = $title['author']; } if ($title['libraryOwned']) { $record = RecordDriverFactory::initRecordDriver($title); $resourceList[] = $interface->fetch($record->getSearchResult($user, null, false)); } else { $interface->assign('record', $title); $resourceList[] = $interface->fetch('RecordDrivers/Index/nonowned_result.tpl'); } } } } $interface->assign('seriesAuthors', $seriesAuthors); $interface->assign('recordSet', $seriesTitles); $interface->assign('resourceList', $resourceList); $interface->assign('recordStart', 1); $interface->assign('recordEnd', count($seriesTitles)); $interface->assign('recordCount', count($seriesTitles)); $interface->setPageTitle($seriesTitle); // Display Page $interface->display('layout.tpl'); }
/** * Get description and return html snippet * * @return void */ public function launch() { global $configArray; if (!isset($_GET['id']) || !$_GET['id']) { return; } $id = $_GET['id']; $localFile = 'interface/cache/description_' . urlencode($id) . '.txt'; $maxAge = isset($configArray['Content']['summarycachetime']) ? $configArray['Content']['summarycachetime'] : 1440; if (is_readable($localFile) && time() - filemtime($localFile) < $maxAge * 60) { // Load local cache if available header('Content-type: text/plain'); echo file_get_contents($localFile); return; } else { // Get URL $db = ConnectionManager::connectToIndex(); if (!($record = $db->getRecord($id))) { return; } $recordDriver = RecordDriverFactory::initRecordDriver($record); $url = $recordDriver->getDescriptionURL(); // Get, manipulate, save and display content if available if ($url) { if ($content = @file_get_contents($url)) { $content = preg_replace('/.*<.B>(.*)/', '\\1', $content); $content = strip_tags($content); // Replace line breaks with <br> $content = preg_replace('/(\\r\\n|\\n|\\r){3,}/', "<br><br>", $content); $content = utf8_encode($content); file_put_contents($localFile, $content); echo $content; return; } } if ($summary = $recordDriver->getSummary()) { echo implode('<br><br>', $summary); } } }
/** * Support method for getItemStatuses() -- Get Axiell Full Item Status * * @param array $holdings Holdings for the record * @param object $catalog Catalog connection * @param array $patron Patron * * @return void * @access public * @author Erik Henriksson <*****@*****.**> * @author Ere Maijala <*****@*****.**> */ protected function getAxiellItemStatusFull($holdings, $catalog, $patron) { global $interface; global $configArray; $itemCount = 0; $requestCount = 0; $locationCount = 0; $branchCount = 0; $availableLocationCount = 0; $availableCount = 0; $itemStatusText = ''; $closestDueDate = ''; $closestDueDateStamp = 0; $journal = false; $itemStatusText = ''; $isHoldable = false; foreach ($holdings as &$location) { if (is_array($location)) { $journal = isset($location['journal']) && $location['journal']; if (is_array($location['holdings'])) { foreach ($location['holdings'] as $holding) { if (isset($holding['total'])) { $itemCount += $holding['total']; } if (isset($holding['status']) && trim($holding['status']) === JSON::REFERENCE_DESK_STATUS) { $location['status']['availableCount']++; } $branchCount++; } } if (isset($location['status'])) { if (isset($location['status']['reservations']) && $location['status']['reservations'] > $requestCount) { $requestCount = $location['status']['reservations']; } if (isset($location['status']['available']) && $location['status']['available']) { $availableLocationCount++; } if (isset($location['status']['availableCount']) && $location['status']['availableCount'] > 0) { $availableCount += $location['status']['availableCount']; } if (isset($location['status']['text']) && $location['status']['text'] != '' && $closestDueDate == '') { $itemStatusText = $location['status']['text']; } if (isset($location['status']['dueDateStamp']) && $location['status']['dueDateStamp'] != '' && isset($location['status']['closestDueDate']) && $location['status']['closestDueDate'] != '') { $dueDate = $location['status']['dueDateStamp']; if ($closestDueDateStamp < $dueDate) { $closestDueDate = $location['status']['closestDueDate']; if (isset($location['status']['text']) && $location['status']['text'] != '') { $itemStatusText = $location['status']['text']; } } } $locationCount++; } if (isset($location['is_holdable']) && $location['is_holdable']) { $isHoldable = true; } } } $id = $holdings[0]['id']; $interface->assign('id', $id); $interface->assign('holdings', $holdings); $locationThreshold = isset($configArray['Site']['locationThreshold']) ? $configArray['Site']['locationThreshold'] : 5; $branchThreshold = isset($configArray['Site']['branchThreshold']) ? $configArray['Site']['branchThreshold'] : 15; $interface->assign('itemCount', $itemCount); $interface->assign('requestCount', $requestCount); $interface->assign('branchCount', $branchCount); $interface->assign('locationCount', $locationCount); $interface->assign('availableLocationCount', $availableLocationCount); $interface->assign('availableCount', $availableCount); $interface->assign('closestDueDate', $closestDueDate); $interface->assign('itemStatusText', $itemStatusText); $interface->assign('isHoldable', $isHoldable); $interface->assign('locationThreshold', $locationThreshold); $interface->assign('branchThreshold', $branchThreshold); $interface->assign('journal', $journal); $interface->assign('referenceDeskStatus', JSON::REFERENCE_DESK_STATUS); $db = ConnectionManager::connectToIndex(); if (!($record = $db->getRecord($id))) { PEAR::raiseError(new PEAR_Error('Record Does Not Exist')); } $recordDriver = RecordDriverFactory::initRecordDriver($record); $interface->assign('patronFunctions', $recordDriver->hasPatronFunctions()); if ("driver" == CatalogConnection::getHoldsMode()) { $interface->assign('driverMode', true); } if ("driver" == CatalogConnection::getTitleHoldsMode()) { $interface->assign('titleDriverMode', true); } if (!PEAR::isError($patron)) { $holdLogic = new HoldLogicTitle($catalog); $holdingTitleHold = $holdLogic->getHold($id, $patron); $interface->assign('holdingTitleHold', $holdingTitleHold); } return $interface->fetch('AJAX/holdings-axiell.tpl'); }
function getItemAvailability() { global $timer; global $configArray; $itemData = array(); //Load basic information $this->id = $_GET['id']; $itemData['id'] = $this->id; // Setup Search Engine Connection $class = $configArray['Index']['engine']; $url = $configArray['Index']['url']; $this->db = new $class($url); if ($configArray['System']['debugSolr']) { $this->db->debug = true; } // Retrieve Full Marc Record if (!($record = $this->db->getRecord($this->id))) { PEAR_Singleton::raiseError(new PEAR_Error('Record Does Not Exist')); } $this->record = $record; if ($record['recordtype'] == 'econtentRecord') { require_once ROOT_DIR . '/sys/eContent/EContentRecord.php'; $eContentRecord = new EContentRecord(); $eContentRecord->id = substr($record['id'], strlen('econtentRecord')); if (!$eContentRecord->find(true)) { $itemData['error'] = 'Cannot load eContent Record for id ' . $record['id']; } else { require_once ROOT_DIR . '/Drivers/EContentDriver.php'; $driver = new EContentDriver(); $itemData['holdings'] = $driver->getHolding($eContentRecord->id); } } else { $this->recordDriver = RecordDriverFactory::initRecordDriver($record); $timer->logTime('Initialized the Record Driver'); //Load Holdings $itemData['holdings'] = Record_Holdings::loadHoldings($this->id); $timer->logTime('Loaded Holdings'); } return $itemData; }
function __construct($subAction = false, $record_id = null) { global $interface; global $configArray; global $library; global $timer; global $logger; $interface->assign('page_body_style', 'sidebar_left'); $interface->assign('libraryThingUrl', $configArray['LibraryThing']['url']); //Determine whether or not materials request functionality should be enabled $interface->assign('enableMaterialsRequest', MaterialsRequest::enableMaterialsRequest()); //Load basic information needed in subclasses if ($record_id == null || !isset($record_id)) { $this->id = $_GET['id']; } else { $this->id = $record_id; } //Check to see if the record exists within the resources table $resource = new Resource(); $resource->record_id = $this->id; $resource->source = 'VuFind'; $resource->deleted = 0; if (!$resource->find()) { //Check to see if the record has been converted to an eContent record require_once ROOT_DIR . '/sys/eContent/EContentRecord.php'; $econtentRecord = new EContentRecord(); $econtentRecord->ilsId = $this->id; $econtentRecord->status = 'active'; if ($econtentRecord->find(true)) { header("Location: /EcontentRecord/{$econtentRecord->id}/Home"); die; } $logger->log("Did not find a record for id {$this->id} in resources table.", PEAR_LOG_DEBUG); $interface->setTemplate('invalidRecord.tpl'); $interface->display('layout.tpl'); die; } if ($configArray['Catalog']['ils'] == 'Millennium') { $interface->assign('classicId', substr($this->id, 1, strlen($this->id) - 2)); $interface->assign('classicUrl', $configArray['Catalog']['linking_url']); } // Setup Search Engine Connection $class = $configArray['Index']['engine']; $url = $configArray['Index']['url']; $this->db = new $class($url); $this->db->disableScoping(); // Retrieve Full Marc Record if (!($record = $this->db->getRecord($this->id))) { $logger->log("Did not find a record for id {$this->id} in solr.", PEAR_LOG_DEBUG); $interface->setTemplate('invalidRecord.tpl'); $interface->display('layout.tpl'); die; } $this->db->enableScoping(); $this->record = $record; $interface->assign('record', $record); $this->recordDriver = RecordDriverFactory::initRecordDriver($record); $timer->logTime('Initialized the Record Driver'); $interface->assign('coreMetadata', $this->recordDriver->getCoreMetadata()); // Process MARC Data require_once ROOT_DIR . '/sys/MarcLoader.php'; $marcRecord = MarcLoader::loadMarcRecordFromRecord($record); if ($marcRecord) { $this->marcRecord = $marcRecord; $interface->assign('marc', $marcRecord); } else { $interface->assign('error', 'Cannot Process MARC Record'); } $timer->logTime('Processed the marc record'); //Load information for display in the template rather than processing specific fields in the template $marcField = $marcRecord->getField('245'); $recordTitle = $this->getSubfieldData($marcField, 'a'); $interface->assign('recordTitle', $recordTitle); $recordTitleSubtitle = trim($this->concatenateSubfieldData($marcField, array('a', 'b', 'h', 'n', 'p'))); $recordTitleSubtitle = preg_replace('~\\s+[\\/:]$~', '', $recordTitleSubtitle); $interface->assign('recordTitleSubtitle', $recordTitleSubtitle); $recordTitleWithAuth = trim($this->concatenateSubfieldData($marcField, array('a', 'b', 'h', 'n', 'p', 'c'))); $interface->assign('recordTitleWithAuth', $recordTitleWithAuth); $marcField = $marcRecord->getField('100'); if ($marcField) { $mainAuthor = $this->concatenateSubfieldData($marcField, array('a', 'b', 'c', 'd')); $interface->assign('mainAuthor', $mainAuthor); } $marcField = $marcRecord->getField('110'); if ($marcField) { $corporateAuthor = $this->getSubfieldData($marcField, 'a'); $interface->assign('corporateAuthor', $corporateAuthor); } $marcFields = $marcRecord->getFields('700'); if ($marcFields) { $contributors = array(); foreach ($marcFields as $marcField) { $contributors[] = $this->concatenateSubfieldData($marcField, array('a', 'b', 'c', 'd')); } $interface->assign('contributors', $contributors); } $published = $this->recordDriver->getPublicationDetails(); $interface->assign('published', $published); $marcFields = $marcRecord->getFields('250'); if ($marcFields) { $editionsThis = array(); foreach ($marcFields as $marcField) { $editionsThis[] = $this->getSubfieldData($marcField, 'a'); } $interface->assign('editionsThis', $editionsThis); } $marcFields = $marcRecord->getFields('300'); if ($marcFields) { $physicalDescriptions = array(); foreach ($marcFields as $marcField) { $description = $this->concatenateSubfieldData($marcField, array('a', 'b', 'c', 'e', 'f', 'g')); if ($description != 'p. cm.') { $description = preg_replace("/[\\/|;:]\$/", '', $description); $description = preg_replace("/p\\./", 'pages', $description); $physicalDescriptions[] = $description; } } $interface->assign('physicalDescriptions', $physicalDescriptions); } // Get ISBN for cover and review use $mainIsbnSet = false; /** @var File_MARC_Data_Field[] $isbnFields */ if ($isbnFields = $this->marcRecord->getFields('020')) { $isbns = array(); //Use the first good ISBN we find. foreach ($isbnFields as $isbnField) { /** @var File_MARC_Subfield $isbnSubfieldA */ if ($isbnSubfieldA = $isbnField->getSubfield('a')) { $tmpIsbn = trim($isbnSubfieldA->getData()); if (strlen($tmpIsbn) > 0) { $isbns[] = $isbnSubfieldA->getData(); $pos = strpos($tmpIsbn, ' '); if ($pos > 0) { $tmpIsbn = substr($tmpIsbn, 0, $pos); } $tmpIsbn = trim($tmpIsbn); if (strlen($tmpIsbn) > 0) { if (strlen($tmpIsbn) < 10) { $tmpIsbn = str_pad($tmpIsbn, 10, "0", STR_PAD_LEFT); } if (!$mainIsbnSet) { $this->isbn = $tmpIsbn; $interface->assign('isbn', $tmpIsbn); $mainIsbnSet = true; } } } } } if (isset($this->isbn)) { if (strlen($this->isbn) == 13) { require_once ROOT_DIR . '/Drivers/marmot_inc/ISBNConverter.php'; $this->isbn10 = ISBNConverter::convertISBN13to10($this->isbn); } else { $this->isbn10 = $this->isbn; } $interface->assign('isbn10', $this->isbn10); } $interface->assign('isbns', $isbns); } if ($upcField = $this->marcRecord->getField('024')) { /** @var File_MARC_Data_Field $upcField */ if ($upcSubField = $upcField->getSubfield('a')) { $this->upc = trim($upcSubField->getData()); $interface->assign('upc', $this->upc); } } if ($issnField = $this->marcRecord->getField('022')) { /** @var File_MARC_Data_Field $issnField */ if ($issnSubField = $issnField->getSubfield('a')) { $this->issn = trim($issnSubField->getData()); if ($pos = strpos($this->issn, ' ')) { $this->issn = substr($this->issn, 0, $pos); } $interface->assign('issn', $this->issn); //Also setup GoldRush link if (isset($library) && strlen($library->goldRushCode) > 0) { $interface->assign('goldRushLink', "http://goldrush.coalliance.org/index.cfm?fuseaction=Search&inst_code={$library->goldRushCode}&search_type=ISSN&search_term={$this->issn}"); } } } $timer->logTime("Got basic data from Marc Record subaction = {$subAction}, record_id = {$record_id}"); //stop if this is not the main action. if ($subAction == true) { return; } //Get street date if ($streetDateField = $this->marcRecord->getField('263')) { $streetDate = $this->getSubfieldData($streetDateField, 'a'); if ($streetDate != '') { $interface->assign('streetDate', $streetDate); } } /** @var File_MARC_Data_Field[] $marcField440 */ $marcField440 = $marcRecord->getFields('440'); /** @var File_MARC_Data_Field[] $marcField490 */ $marcField490 = $marcRecord->getFields('490'); /** @var File_MARC_Data_Field[] $marcField830 */ $marcField830 = $marcRecord->getFields('830'); if ($marcField440 || $marcField490 || $marcField830) { $series = array(); foreach ($marcField440 as $field) { $series[] = $this->getSubfieldData($field, 'a'); } foreach ($marcField490 as $field) { if ($field->getIndicator(1) == 0) { $series[] = $this->getSubfieldData($field, 'a'); } } foreach ($marcField830 as $field) { $series[] = $this->getSubfieldData($field, 'a'); } $interface->assign('series', $series); } //Load description from Syndetics $useMarcSummary = true; if ($this->isbn || $this->upc) { if ($library && $library->preferSyndeticsSummary == 1) { require_once ROOT_DIR . '/Drivers/marmot_inc/GoDeeperData.php'; $summaryInfo = GoDeeperData::getSummary($this->isbn, $this->upc); if (isset($summaryInfo['summary'])) { $interface->assign('summaryTeaser', $summaryInfo['summary']); $interface->assign('summary', $summaryInfo['summary']); $useMarcSummary = false; } } } if ($useMarcSummary) { if ($summaryField = $this->marcRecord->getField('520')) { $interface->assign('summary', $this->getSubfieldData($summaryField, 'a')); $interface->assign('summaryTeaser', $this->getSubfieldData($summaryField, 'a')); } elseif ($library && $library->preferSyndeticsSummary == 0) { require_once ROOT_DIR . '/Drivers/marmot_inc/GoDeeperData.php'; $summaryInfo = GoDeeperData::getSummary($this->isbn, $this->upc); if (isset($summaryInfo['summary'])) { $interface->assign('summaryTeaser', $summaryInfo['summary']); $interface->assign('summary', $summaryInfo['summary']); $useMarcSummary = false; } } } if ($mpaaField = $this->marcRecord->getField('521')) { $interface->assign('mpaaRating', $this->getSubfieldData($mpaaField, 'a')); } if (isset($configArray['Content']['subjectFieldsToShow'])) { $subjectFieldsToShow = $configArray['Content']['subjectFieldsToShow']; $subjectFields = explode(',', $subjectFieldsToShow); $subjects = array(); foreach ($subjectFields as $subjectField) { /** @var File_MARC_Data_Field[] $marcFields */ $marcFields = $marcRecord->getFields($subjectField); if ($marcFields) { foreach ($marcFields as $marcField) { $searchSubject = ""; $subject = array(); foreach ($marcField->getSubFields() as $subField) { /** @var File_MARC_Subfield $subField */ if ($subField->getCode() != 2) { $searchSubject .= " " . $subField->getData(); $subject[] = array('search' => trim($searchSubject), 'title' => $subField->getData()); } } $subjects[] = $subject; } } $interface->assign('subjects', $subjects); } } $format = $record['format']; $interface->assign('recordFormat', $record['format']); $format_category = isset($record['format_category'][0]) ? $record['format_category'][0] : ''; $interface->assign('format_category', $format_category); $interface->assign('recordLanguage', isset($record['language']) ? $record['language'] : null); $timer->logTime('Got detailed data from Marc Record'); $tableOfContents = array(); $marcFields505 = $marcRecord->getFields('505'); if ($marcFields505) { $tableOfContents = $this->processTableOfContentsFields($marcFields505); } $notes = array(); $marcFields500 = $marcRecord->getFields('500'); $marcFields504 = $marcRecord->getFields('504'); $marcFields511 = $marcRecord->getFields('511'); $marcFields518 = $marcRecord->getFields('518'); $marcFields520 = $marcRecord->getFields('520'); if ($marcFields500 || $marcFields504 || $marcFields505 || $marcFields511 || $marcFields518 || $marcFields520) { $allFields = array_merge($marcFields500, $marcFields504, $marcFields511, $marcFields518, $marcFields520); $notes = $this->processNoteFields($allFields); } if (isset($library) && $library->showTableOfContentsTab == 0 || count($tableOfContents) == 0) { $notes = array_merge($notes, $tableOfContents); } else { $interface->assign('tableOfContents', $tableOfContents); } if (isset($library) && strlen($library->notesTabName) > 0) { $interface->assign('notesTabName', $library->notesTabName); } else { $interface->assign('notesTabName', 'Notes'); } $additionalNotesFields = array('310' => 'Current Publication Frequency', '321' => 'Former Publication Frequency', '351' => 'Organization & arrangement of materials', '362' => 'Dates of publication and/or sequential designation', '501' => '"With"', '502' => 'Dissertation', '506' => 'Restrictions on Access', '507' => 'Scale for Graphic Material', '508' => 'Creation/Production Credits', '510' => 'Citation/References', '511' => 'Participant or Performer', '513' => 'Type of Report an Period Covered', '515' => 'Numbering Peculiarities', '518' => 'Date/Time and Place of Event', '521' => 'Target Audience', '522' => 'Geographic Coverage', '525' => 'Supplement', '526' => 'Study Program Information', '530' => 'Additional Physical Form', '533' => 'Reproduction', '534' => 'Original Version', '536' => 'Funding Information', '538' => 'System Details', '545' => 'Biographical or Historical Data', '546' => 'Language', '547' => 'Former Title Complexity', '550' => 'Issuing Body', '555' => 'Cumulative Index/Finding Aids', '556' => 'Information About Documentation', '561' => 'Ownership and Custodial History', '563' => 'Binding Information', '580' => 'Linking Entry Complexity', '581' => 'Publications About Described Materials', '586' => 'Awards', '590' => 'Local note', '599' => 'Differentiable Local note'); foreach ($additionalNotesFields as $tag => $label) { $marcFields = $marcRecord->getFields($tag); foreach ($marcFields as $marcField) { $noteText = array(); foreach ($marcField->getSubFields() as $subfield) { /** @var File_MARC_Subfield $subfield */ $noteText[] = $subfield->getData(); } $note = implode(',', $noteText); if (strlen($note) > 0) { $notes[] = "<b>{$label}</b>: " . $note; } } } if (count($notes) > 0) { $interface->assign('notes', $notes); } /** @var File_MARC_Data_Field[] $linkFields */ $linkFields = $marcRecord->getFields('856'); if ($linkFields) { $internetLinks = array(); $purchaseLinks = array(); $field856Index = 0; foreach ($linkFields as $marcField) { $field856Index++; //Get the link if ($marcField->getSubfield('u')) { $link = $marcField->getSubfield('u')->getData(); if ($marcField->getSubfield('3')) { $linkText = $marcField->getSubfield('3')->getData(); } elseif ($marcField->getSubfield('y')) { $linkText = $marcField->getSubfield('y')->getData(); } elseif ($marcField->getSubfield('z')) { $linkText = $marcField->getSubfield('z')->getData(); } else { $linkText = $link; } $showLink = true; //Process some links differently so we can either hide them //or show them in different areas of the catalog. if (preg_match('/purchase|buy/i', $linkText) || preg_match('/barnesandnoble|tatteredcover|amazon|smashwords\\.com/i', $link)) { $showLink = false; } $isBookLink = preg_match('/acs\\.dcl\\.lan|vufind\\.douglascountylibraries\\.org|catalog\\.douglascountylibraries\\.org/i', $link); if ($isBookLink == 1) { //e-book link, don't show $showLink = false; } if ($showLink) { //Rewrite the link so we can track usage $link = $configArray['Site']['path'] . '/Record/' . $this->id . '/Link?index=' . $field856Index; $internetLinks[] = array('link' => $link, 'linkText' => $linkText); } } } if (count($internetLinks) > 0) { $interface->assign('internetLinks', $internetLinks); } } if (isset($purchaseLinks) && count($purchaseLinks) > 0) { $interface->assign('purchaseLinks', $purchaseLinks); } //Determine the cover to use $bookCoverUrl = $configArray['Site']['coverUrl'] . "/bookcover.php?id={$this->id}&isn={$this->isbn}&issn={$this->issn}&size=large&upc={$this->upc}&category=" . urlencode($format_category) . "&format=" . urlencode(isset($format[0]) ? $format[0] : ''); $interface->assign('bookCoverUrl', $bookCoverUrl); //Load accelerated reader data if (isset($record['accelerated_reader_interest_level'])) { $arData = array('interestLevel' => $record['accelerated_reader_interest_level'], 'pointValue' => $record['accelerated_reader_point_value'], 'readingLevel' => $record['accelerated_reader_reading_level']); $interface->assign('arData', $arData); } if (isset($record['lexile_score']) && $record['lexile_score'] > -1) { $lexileScore = $record['lexile_score']; if (isset($record['lexile_code'])) { $lexileScore = $record['lexile_code'] . $lexileScore; } $interface->assign('lexileScore', $lexileScore . 'L'); } //Do actions needed if this is the main action. //$interface->caching = 1; $interface->assign('id', $this->id); if (substr($this->id, 0, 1) == '.') { $interface->assign('shortId', substr($this->id, 1)); } else { $interface->assign('shortId', $this->id); } $interface->assign('addHeader', '<link rel="alternate" type="application/rdf+xml" title="RDF Representation" href="' . $configArray['Site']['path'] . '/Record/' . urlencode($this->id) . '/RDF" />'); // Define Default Tab $tab = isset($_GET['action']) ? $_GET['action'] : 'Description'; $interface->assign('tab', $tab); if (isset($_REQUEST['detail'])) { $detail = strip_tags($_REQUEST['detail']); $interface->assign('defaultDetailsTab', $detail); } // Define External Content Provider if ($this->marcRecord->getField('020')) { if (isset($configArray['Content']['reviews'])) { $interface->assign('hasReviews', true); } if (isset($configArray['Content']['excerpts'])) { $interface->assign('hasExcerpt', true); } } // Retrieve User Search History $interface->assign('lastsearch', isset($_SESSION['lastSearchURL']) ? $_SESSION['lastSearchURL'] : false); // Retrieve tags associated with the record $limit = 5; $resource = new Resource(); $resource->record_id = $_GET['id']; $resource->source = 'VuFind'; $resource->find(true); $tags = $resource->getTags($limit); $interface->assign('tagList', $tags); $timer->logTime('Got tag list'); $this->cacheId = 'Record|' . $_GET['id'] . '|' . get_class($this); // Find Similar Records /** @var Memcache $memCache */ global $memCache; $similar = $memCache->get('similar_titles_' . $this->id); if ($similar == false) { $similar = $this->db->getMoreLikeThis($this->id); // Send the similar items to the template; if there is only one, we need // to force it to be an array or things will not display correctly. if (isset($similar) && count($similar['response']['docs']) > 0) { $similar = $similar['response']['docs']; } else { $similar = array(); $timer->logTime("Did not find any similar records"); } $memCache->set('similar_titles_' . $this->id, $similar, 0, $configArray['Caching']['similar_titles']); } $this->similarTitles = $similar; $interface->assign('similarRecords', $similar); $timer->logTime('Loaded similar titles'); // Find Other Editions if ($configArray['Content']['showOtherEditionsPopup'] == false) { $editions = OtherEditionHandler::getEditions($this->id, $this->isbn, isset($this->record['issn']) ? $this->record['issn'] : null); if (!PEAR_Singleton::isError($editions)) { $interface->assign('editions', $editions); } else { $timer->logTime("Did not find any other editions"); } $timer->logTime('Got Other editions'); } $interface->assign('showStrands', isset($configArray['Strands']['APID']) && strlen($configArray['Strands']['APID']) > 0); // Send down text for inclusion in breadcrumbs $interface->assign('breadcrumbText', $this->recordDriver->getBreadcrumb()); // Send down OpenURL for COinS use: $interface->assign('openURL', $this->recordDriver->getOpenURL()); // Send down legal export formats (if any): $interface->assign('exportFormats', $this->recordDriver->getExportFormats()); // Set AddThis User $interface->assign('addThis', isset($configArray['AddThis']['key']) ? $configArray['AddThis']['key'] : false); // Set Proxy URL if (isset($configArray['EZproxy']['host'])) { $interface->assign('proxy', $configArray['EZproxy']['host']); } //setup 5 star ratings global $user; $ratingData = $resource->getRatingData($user); $interface->assign('ratingData', $ratingData); $timer->logTime('Got 5 star data'); //Get Next/Previous Links $searchSource = isset($_REQUEST['searchSource']) ? $_REQUEST['searchSource'] : 'local'; $searchObject = SearchObjectFactory::initSearchObject(); $searchObject->init($searchSource); $searchObject->getNextPrevLinks(); //Load Staff Details $interface->assign('staffDetails', $this->recordDriver->getStaffView()); }
/** * Get record and export data * Display error message on terminal error or email details page on success * * @param string $format The desired export format * @param array $ids A list of bib IDs * * @return array Record data for each ID, plus an list of IDs without results * @access public */ public function exportAll($format, $ids) { global $interface; global $configArray; $exportDetails = array(); $errorMsgDetails = array(); // MARC-XML needs a container at the start: if ($format == 'MARCXML') { $exportDetails[] = '<?xml version="1.0" encoding="UTF-8"?>' . '<collection xmlns="http://www.loc.gov/MARC21/slim">'; } foreach ($ids as $id) { // Retrieve the record from the index list($index, $recId) = explode('.', $id, 2); $current = null; if ($index === 'pci' || $index === 'metalib') { $format = strtolower($format); if ($index === 'pci') { $db = new SearchObject_PCI(); if ($rec = $db->getRecord($id)) { $pci = new PCI(); $current = $interface->fetch($pci->export($rec, $format)); } } else { if ($index === 'metalib') { $db = new MetaLib(); if ($rec = $db->getRecord($id)) { $current = $interface->fetch($db->export($rec, $format)); } } } if ($current) { $exportDetails[] = $current; } else { $errorMsgDetails[] = $id; } } else { if (!($record = $this->db->getRecord($id))) { $errorMsgDetails[] = $id; } else { $recordDetails = RecordDriverFactory::initRecordDriver($record); // Assign core metadata to be sure export has all necessary values // available: $recordDetails->getCoreMetadata(); $result = $recordDetails->getExport($format); if (!empty($result)) { $interface->assign('id', $id); $current = $interface->fetch($result); // For MARC-XML, extract <record> from <collection>: if ($format == 'MARCXML') { $current = $this->extractXMLRecord($current); } if (!empty($current)) { $exportDetails[] = $current; } } else { $errorMsgDetails[] = $id; } } } } // MARC-XML needs a container close at the end: if ($format == 'MARCXML') { $exportDetails[] = '</collection>'; } $results = array('exportDetails' => $exportDetails, 'errorDetails' => $errorMsgDetails); return $results; }
* @author Lutz Biedinger <*****@*****.**> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://vufind.org/wiki Wiki */ require_once 'util.inc.php'; require_once 'sys/ConfigArray.php'; require_once 'sys/solr.php'; require_once 'sys/SearchObject/solr.php'; require_once 'sys/SearchObject/Factory.php'; require_once 'RecordDrivers/Factory.php'; require_once 'sys/hierarchy/HierarchyTreeGenerator_JSTree.php'; print "getting config\r\n"; $configArray = readConfig(); print "creating Search Object\r\n"; $solrSearchObject = new SearchObject_Solr(); if (!$solrSearchObject) { die("Error: No connection to solr index\n"); } print "Getting Full Field Facets\r\n"; $hierarchyTopFacets = $solrSearchObject->getFullFieldFacets(array("hierarchy_top_id")); $db = ConnectionManager::connectToIndex(); print "Iterate through Values\r\n"; foreach ($hierarchyTopFacets["hierarchy_top_id"]["data"] as $hierarchyTopFacet) { $topRecord = $db->getRecord($hierarchyTopFacet[0]); $RecDriver = RecordDriverFactory::initRecordDriver($topRecord); if ($RecDriver->getHierarchyType()) { //only do this if the record is actually a hierarchy type record $generator = new HierarchyTreeGenerator_JSTree($RecDriver); $generator->generateXMLfromSolr($hierarchyTopFacet[0]); } }
/** * Gets An individual Collection Record * * @param string $id The Collection Record ID * * @return mixed "unknown" if the record doesn't exist, the location of a * template file on success * @access protected */ public function getRecord($id) { global $interface; // Retrieve the record from the index if (!($record = $this->db->getRecord($id))) { return "unknown"; } else { $recordDriver = RecordDriverFactory::initRecordDriver($record); return $recordDriver->getCollectionRecord(); } }
/** * Use the record driver to build an array of HTML displays from the search * results. * * @access public * @return array Array of HTML chunks for individual records. */ public function getResultRecordHTML() { global $interface; $html = array(); for ($x = 0; $x < count($this->indexResult['response']['docs']); $x++) { $current =& $this->indexResult['response']['docs'][$x]; $interface->assign('recordIndex', $x + 1); $record = RecordDriverFactory::initRecordDriver($current); $html[] = $interface->fetch($record->getSearchResult()); } return $html; }
/** * Perform a bulk export operation. * * @param string $format Format to export (should be a valid value for the * getExport method of the record driver) * @param array $ids IDs to export * * @return array Exported documents * @access public */ public function exportAll($format, $ids) { global $interface; global $configArray; $exportDetails = array(); $errorMsgDetails = array(); foreach ($ids as $id) { // Retrieve the record from the index if (!($record = $this->db->getRecord($id))) { $errorMsgDetails[] = $id; } else { $recordDetails = RecordDriverFactory::initRecordDriver($record); // Assign core metadata to be sure export has all necessary values // available: $recordDetails->getCoreMetadata(); $result = $recordDetails->getExport($format); if (!empty($result)) { $exportDetails[] = $interface->fetch($result); } else { $errorMsgDetails[] = $id; } } } $results = array('exportDetails' => $exportDetails, 'errorDetails' => $errorMsgDetails); return $results; }
/** * Returns a record driver for handling the pseudo-record. * In a separate method so the static call can be mocked. * * @param array $record The index fields to read from * * @return Record driver instance */ protected function getDriver($record) { return RecordDriverFactory::initRecordDriver($record); }
/** * Process the "jumpto" parameter. * * @param array $result Solr result returned by SearchObject * * @return void * @access private */ private function _processJumpto($result) { if (isset($_REQUEST['jumpto']) && is_numeric($_REQUEST['jumpto'])) { $i = intval($_REQUEST['jumpto'] - 1); if (isset($result['response']['docs'][$i])) { $record = RecordDriverFactory::initRecordDriver($result['response']['docs'][$i]); $jumpUrl = '../Record/' . urlencode($record->getUniqueID()); header('Location: ' . $jumpUrl); die; } } }
/** * Initialize the record * * @param string $id Record ID * @param array $record Record data * * @return void */ protected function setRecord($id, $record) { global $interface; global $configArray; global $user; // Store ID of current record (this is needed to generate appropriate // links, and it is independent of which record driver gets used). $interface->assign('id', $_REQUEST['id']); $this->recordDriver = RecordDriverFactory::initRecordDriver($record); // Define Default Tab $defaultTab = isset($configArray['Site']['defaultRecordTab']) ? $configArray['Site']['defaultRecordTab'] : 'Holdings'; // Don't let bots crawl holdings if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|crawl|slurp|spider/i', $_SERVER['HTTP_USER_AGENT'])) { $this->hasHoldings = false; $interface->assign('hasHoldings', false); $defaultTab = 'Description'; } else { if (isset($configArray['Site']['hideHoldingsTabWhenEmpty']) && $configArray['Site']['hideHoldingsTabWhenEmpty']) { $showHoldingsTab = $this->recordDriver->hasHoldings(); $interface->assign('hasHoldings', $showHoldingsTab); $defaultTab = !$showHoldingsTab && $defaultTab == "Holdings" ? "Description" : $defaultTab; } else { $interface->assign('hasHoldings', true); } } $tab = isset($_GET['action']) ? $_GET['action'] : $defaultTab; $interface->assign('tab', $tab); // Check if ajax tabs are active if (isset($configArray['Site']['ajaxRecordTabs']) && $configArray['Site']['ajaxRecordTabs']) { $interface->assign('dynamicTabs', true); } if ($this->recordDriver->hasRDF()) { $interface->assign('addHeader', '<link rel="alternate" type="application/rdf+xml" ' . 'title="RDF Representation" href="' . $configArray['Site']['url'] . '/Record/' . urlencode($_REQUEST['id']) . '/RDF" />' . "\n"); } $interface->assign('coreMetadata', $this->recordDriver->getCoreMetadata()); // Determine whether to display book previews if (isset($configArray['Content']['previews'])) { $interface->assignPreviews(); } // Determine whether comments or reviews are enabled if (isset($configArray['Site']['userComments']) && $configArray['Site']['userComments']) { $interface->assign('userCommentsEnabled', true); } // Ratings for libraries, comments for museums and archives if ($this->recordDriver->getSector() == 'lib') { $interface->assign('ratings', true); } if (isset($configArray['Site']['userComments']) && $configArray['Site']['userComments']) { // Get number of comments for this record include_once 'services/MyResearch/lib/Comments.php'; $comments = new Comments(); $commentCount = $comments->getCommentCount($_REQUEST['id']); $interface->assign(compact('commentCount')); $recordRating = $comments->getAverageRating($_REQUEST['id']); $interface->assign(compact('recordRating')); } // Determine whether to include script tag for syndetics plus if (isset($configArray['Syndetics']['plus']) && $configArray['Syndetics']['plus'] && isset($configArray['Syndetics']['plus_id'])) { $interface->assign('syndetics_plus_js', "http://plus.syndetics.com/widget.php?id=" . $configArray['Syndetics']['plus_id']); } // Set flags that control which tabs are displayed: if (isset($configArray['Content']['reviews'])) { $interface->assign('hasReviews', $this->recordDriver->hasReviews()); } if (isset($configArray['Content']['excerpts'])) { $interface->assign('hasExcerpt', $this->recordDriver->hasExcerpt()); } //Hierarchy Tree $interface->assign('hasHierarchyTree', $this->recordDriver->hasHierarchyTree()); $interface->assign('hasTOC', $this->recordDriver->hasTOC()); $interface->assign('hasMap', $this->recordDriver->hasMap()); $this->recordDriver->getTOC(); $interface->assign('extendedMetadata', $this->recordDriver->getExtendedMetadata()); // Assign the next/previous record data: $scroller = new ResultScroller(); $scrollData = $scroller->getScrollData($_REQUEST['id']); $interface->assign('previousRecord', $scrollData['previousRecord']); $interface->assign('nextRecord', $scrollData['nextRecord']); $interface->assign('currentRecordPosition', $scrollData['currentPosition']); $interface->assign('resultTotal', $scrollData['resultTotal']); // Retrieve User Search History $lastsearch = isset($_SESSION['lastSearchURL']) ? $_SESSION['lastSearchURL'] : false; $interface->assign('lastsearch', $lastsearch); if ($lastsearch) { // Retrieve active filters and assign them to searchbox template. // Since SearchObjects use $_REQUEST to init filters, we stash the current $_REQUEST // and fill it temporarily with URL parameters from last search. $query = parse_url($lastsearch, PHP_URL_QUERY); parse_str($query, $vars); $oldReq = $_REQUEST; $_REQUEST = $vars; $searchObject = SearchObjectFactory::initSearchObject(); $searchObject->init(); // This is needed for facet labels $searchObject->initRecommendations(); $filterList = $searchObject->getFilterList(); $filterListOthers = $searchObject->getFilterListOthers(); $checkboxFilters = $searchObject->getCheckboxFacets(); $filterUrlParams = $searchObject->getfilterUrlParams(); if (isset($vars['lookfor'])) { $interface->assign('lookfor', $vars['lookfor']); } $interface->assign('filterUrlParam', $filterUrlParams[0]); $interface->assign(compact('filterList')); $interface->assign(compact('filterListOthers')); $interface->assign('checkboxFilters', $checkboxFilters); if (isset($_SERVER['HTTP_REFERER'])) { // Set followup module & action for next search $parts = parse_url($_SERVER['HTTP_REFERER']); $pathParts = explode('/', $parts['path']); $refAction = array_pop($pathParts); $refModule = array_pop($pathParts); $interface->assign('followupSearchModule', $refModule); $interface->assign('followupSearchAction', $refAction); } $_REQUEST = $oldReq; } $interface->assign('lastsearchdisplayquery', isset($_SESSION['lastSearchDisplayQuery']) ? $_SESSION['lastSearchDisplayQuery'] : false); $interface->assign('searchId', isset($_SESSION['lastSearchID']) ? $_SESSION['lastSearchID'] : false); $interface->assign('searchType', isset($_SESSION['searchType']) ? $_SESSION['searchType'] : false); unset($_SESSION['lastSearchID']); unset($_SESSION['searchType']); // Send down text for inclusion in breadcrumbs $interface->assign('breadcrumbText', $this->recordDriver->getBreadcrumb()); // Send down OpenURL for COinS use: $interface->assign('openURL', $this->recordDriver->getOpenURL()); // 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); } // Send down legal export formats (if any): $interface->assign('exportFormats', $this->recordDriver->getExportFormats()); if ($this->recordDriver->allowSocialMediaSharing()) { // Set AddThis User $interface->assign('addThis', isset($configArray['AddThis']['key']) ? $configArray['AddThis']['key'] : false); } // Set Proxy URL if (isset($configArray['EZproxy']['host'])) { $interface->assign('proxy', $configArray['EZproxy']['host']); } // Get Messages $this->infoMsg = isset($_GET['infoMsg']) ? $_GET['infoMsg'] : false; $this->errorMsg = isset($_GET['errorMsg']) ? $_GET['errorMsg'] : false; // Set bX flag $interface->assign('bXEnabled', isset($configArray['bX']['token']) ? true : false); // Get Record source driver $catalog = $this->catalog; $driver = is_callable(array($catalog, 'getSourceDriver')) ? $this->catalog->getSourceDriver($_REQUEST['id']) : ''; $interface->assign('driver', $driver); }
public function getSupplementalResultRecordHTML($mainResults, $maxResultsToShow, $startIndex = 0) { global $interface; $html = array(); $numResultsShown = 0; for ($x = 0; $x < count($this->indexResult['response']['docs']); $x++) { $current =& $this->indexResult['response']['docs'][$x]; //Check to make sure this id is not in the main results $supplementalInMainResults = false; foreach ($mainResults as $mainResult) { if ($mainResult['id'] == $current['id']) { $supplementalInMainResults = true; break; } } if ($supplementalInMainResults) { continue; } $interface->assign('recordIndex', $numResultsShown + 1); $interface->assign('resultIndex', $numResultsShown + 1 + ($this->page - 1) * $this->limit + $startIndex); /** @var IndexRecord|MarcRecord|EcontentRecordDriver $record */ $record = RecordDriverFactory::initRecordDriver($current); $numResultsShown++; $html[] = $interface->fetch($record->getSearchResult('list', true)); if ($numResultsShown >= $maxResultsToShow) { break; } } return $html; }
/** * Return Solr results in an extended array * * @param array $result Optional results to process * * @return array Results */ protected function createResultArray($result = null) { global $configArray; // First, get the search results if none were provided if (is_null($result)) { // Let's do at most 100 at a time... if ($this->limit > 100) { $this->limit = 100; } // Get the results: $result = $this->processSearch(false, true); } if ($this->searchType == 'newitem') { $lookfor = translate('New Items'); } else { if ($this->searchType == 'reserves') { $lookfor = translate('Course Reserves'); } else { $lookfor = $this->displayQuery(); } } $resultHeader = array('searchTerms' => $lookfor, 'searchUrl' => $this->renderSearchUrl()); unset($result['responseHeader']); $result = array_merge($resultHeader, $result); // The marc_error nodes can cause problems, so let's get rid // of them at the same time. // We add the record image to the array: for MARC records we // use bookcover.php, for everything else thumbnail.php. // Finally we remove an extra slash in format values. for ($i = 0; $i < count($result['response']['docs']); $i++) { if (isset($result['response']['docs'][$i]['marc_error'])) { unset($result['response']['docs'][$i]['marc_error']); } if (isset($result['response']['docs'][$i]['thumbnail'])) { unset($result['response']['docs'][$i]['thumbnail']); } $id = isset($result['response']['docs'][$i]['id']) ? $result['response']['docs'][$i]['id'] : false; $type = isset($result['response']['docs'][$i]['recordtype']) ? $result['response']['docs'][$i]['recordtype'] : false; if ($type === 'marc') { if (isset($result['response']['docs'][$i]['fullrecord'])) { $marc = preg_replace('/#31;/', "", $result['response']['docs'][$i]['fullrecord']); $marc = preg_replace('/#30;/', "", $marc); $marc = new File_MARC($marc, File_MARC::SOURCE_STRING); $record = $marc->next(); $result['response']['docs'][$i]['fullrecord'] = $record->toXML(); } } $result['response']['docs'][$i]['record_link'] = $this->serverUrl . '/Record/' . urlencode($id); // Fetch image links and information $record = RecordDriverFactory::initRecordDriver($result['response']['docs'][$i]); for ($img = 0; $img < count($record->getAllImages()); $img++) { $result['response']['docs'][$i]['image_links'][] = $this->serverUrl . '/thumbnail.php?id=' . urlencode($id) . "&index={$img}&size=large"; } $thumbnail = $record->getThumbnail(); if ($thumbnail) { $result['response']['docs'][$i]['thumbnail_link'] = $thumbnail; } $result['response']['docs'][$i]['parsed_title'] = $record->getTitle(); $links = $record->getAllRecordLinks(); if ($links) { $result['response']['docs'][$i]['parsed_record_links'] = $links; } $urls = $record->getOnlineURLs(); if ($urls) { $result['response']['docs'][$i]['parsed_online_urls'] = $urls; } } return $result; }
/** * Send scheduled alerts * * @return void */ public function send() { global $configArray; global $interface; global $translator; $iso8601 = 'Y-m-d\\TH:i:s\\Z'; ini_set('display_errors', true); $configArray = $mainConfig = readConfig(); $datasourceConfig = getExtraConfigArray('datasources'); $siteLocal = $configArray['Site']['local']; // Set up time zone. N.B. Don't use msg() or other functions requiring date before this. date_default_timezone_set($configArray['Site']['timezone']); $this->msg('Sending scheduled alerts'); // Setup Local Database Connection ConnectionManager::connectToDatabase(); // Initialize Mailer $mailer = new VuFindMailer(); // Find all scheduled alerts $sql = 'SELECT * FROM "search" WHERE "schedule" > 0 ORDER BY user_id'; $s = new SearchEntry(); $s->query($sql); $this->msg('Processing ' . $s->N . ' searches'); $user = false; $interface = false; $institution = false; $todayTime = new DateTime(); while ($s->fetch()) { $lastTime = new DateTime($s->last_executed); if ($s->schedule == 1) { // Daily if ($todayTime->format('Y-m-d') == $lastTime->format('Y-m-d')) { $this->msg('Bypassing search ' . $s->id . ': previous execution too recent (daily, ' . $lastTime->format($iso8601) . ')'); continue; } } elseif ($s->schedule == 2) { // Weekly $diff = $todayTime->diff($lastTime); if ($diff->days < 6) { $this->msg('Bypassing search ' . $s->id . ': previous execution too recent (weekly, ' . $lastTime->format($iso8601) . ')'); continue; } } else { $this->msg('Search ' . $s->id . ': unknown schedule: ' . $s->schedule); continue; } if ($user === false || $s->user_id != $user->id) { $user = User::staticGet($s->user_id); } if (!$user->email || trim($user->email) == '') { $this->msg('User ' . $user->username . ' does not have an email address, bypassing alert ' . $s->id); continue; } $userInstitution = reset(explode(':', $user->username, 2)); if (!$institution || $institution != $userInstitution) { $institution = $userInstitution; if (!isset($datasourceConfig[$institution])) { foreach ($datasourceConfig as $code => $values) { if (isset($values['institution']) && strcasecmp($values['institution'], $institution) == 0) { $institution = $code; break; } } } if (!($configArray = $this->readInstitutionConfig($institution))) { continue; } $configArray['Site']['url'] = $s->schedule_base_url; // Start Interface $interface = new UInterface($siteLocal); $validLanguages = array_keys($configArray['Languages']); $dateFormat = new VuFindDate(); } $language = $user->language; if (!in_array($user->language, $validLanguages)) { $language = $configArray['Site']['language']; } $translator = new I18N_Translator(array($configArray['Site']['local'] . '/lang', $configArray['Site']['local'] . '/lang_local'), $language, $configArray['System']['debug']); $interface->setLanguage($language); $minSO = unserialize($s->search_object); // Check minified search object type $searchObject = SearchObjectFactory::deminify($minSO); if (!$searchObject instanceof SearchObject_Solr) { $this->msg('Search ' . $s->id . ': search object type not supported'); continue; } // Create a new search object to avoid cached defaults for e.g. // hidden filters. $searchObject = SearchObjectFactory::initSearchObject(); $searchObject->deminify($minSO); $searchObject->setSort('first_indexed desc'); $searchTime = time(); $searchDate = gmdate($iso8601, time()); $searchObject->setLimit(50); $searchObject->disableLogging(); $results = $searchObject->processSearch(); if (PEAR::isError($results)) { $this->msg('Search ' . $s->id . ' failed: ' . $results->getMessage()); continue; } if ($searchObject->getResultTotal() < 1) { $this->msg('No results found for search ' . $s->id); continue; } $newestRecordDate = date($iso8601, strtotime($results['response']['docs'][0]['first_indexed'])); $lastExecutionDate = $lastTime->format($iso8601); if ($newestRecordDate < $lastExecutionDate) { $this->msg('No new results for search ' . $s->id . ": {$newestRecordDate} < {$lastExecutionDate}"); } else { $this->msg('New results for search ' . $s->id . ": {$newestRecordDate} >= {$lastExecutionDate}"); $interface->assign('summary', $searchObject->getResultSummary()); $interface->assign('searchDate', $dateFormat->convertToDisplayDate("U", floor($searchTime))); $interface->assign('lastSearchDate', $dateFormat->convertToDisplayDate("U", floor($lastTime->getTimestamp()))); $records = array(); foreach ($results['response']['docs'] as &$doc) { $docDate = date($iso8601, strtotime($doc['first_indexed'])); if ($docDate < $lastExecutionDate) { break; } $record = RecordDriverFactory::initRecordDriver($doc); $records[] = $interface->fetch($record->getSearchResult('email')); } $interface->assign('recordSet', $records); $key = $this->getSecret($user, $s->id); $params = array('id' => $s->id, 'type' => 'alert', 'key' => $key); $unsubscribeUrl = $configArray['Site']['url'] . '/MyResearch/Unsubscribe?' . http_build_query($params); $interface->assign('info', array('time' => $dateFormat->convertToDisplayDate("U", floor($searchObject->getStartTime())), 'url' => $searchObject->renderSearchUrl(), 'searchId' => $searchObject->getSearchId(), 'description' => $searchObject->displayQuery(), 'filters' => $searchObject->getFilterList(), 'hits' => $searchObject->getResultTotal(), 'speed' => round($searchObject->getQuerySpeed(), 2) . "s", 'schedule' => $s->schedule, 'last_executed' => $s->last_executed, 'recordCount' => count($records), 'unsubscribeUrl' => $unsubscribeUrl)); $searchObject->close(); // Load template $message = $interface->fetch('MyResearch/alert-email.tpl'); if (strstr($message, 'Warning: Smarty error:')) { $this->msg("Message template processing failed: {$message}"); continue; } $result = $mailer->send($user->email, $configArray['Site']['email'], translate('Scheduled Alert Results'), $message); if (PEAR::isError($result)) { $this->msg("Failed to send message to {$user->email}: " . $result->getMessage()); continue; } } // Update search date $s->changeLastExecuted($searchDate); } $this->reportErrors(); $this->msg('Scheduled alerts execution completed'); }
/** * Get data and output in JSON * * @return void * @access public */ public function getbXRecommendations() { global $configArray; if (!isset($configArray['bX']['token'])) { $this->output('bX support not enabled', JSON::STATUS_ERROR); return; } $id = $_REQUEST['id']; if (strncmp($id, 'metalib.', 8) == 0) { include_once 'sys/MetaLib.php'; $metalib = new MetaLib(); if (!($record = $metalib->getRecord($id))) { $this->output('Record does not exist', JSON::STATUS_ERROR); return; } $openUrl = $record['openUrl']; } elseif (strncmp($id, 'pci.', 4) == 0) { include_once 'sys/PCI.php'; $pci = new PCI(); if (!($record = $pci->getRecord($id))) { $this->output('Record does not exist', JSON::STATUS_ERROR); return; } $openUrl = $record['openUrl']; } else { $searchObject = SearchObjectFactory::initSearchObject(); if (!($record = $searchObject->getIndexEngine()->getRecord($id))) { $this->output('Record does not exist', JSON::STATUS_ERROR); return; } $recordDriver = RecordDriverFactory::initRecordDriver($record); $openUrl = $recordDriver->getOpenURL(); } $params = http_build_query(array('token' => $configArray['bX']['token'], 'format' => 'xml', 'source' => isset($configArray['bX']['source']) ? $configArray['bX']['source'] : 'global', 'maxRecords' => isset($configArray['bX']['maxRecords']) ? $configArray['bX']['maxRecords'] : '5', 'threshold' => isset($configArray['bX']['threshold']) ? $configArray['bX']['threshold'] : '50')); $openUrl .= '&res_dat=' . urlencode($params); $baseUrl = isset($configArray['bX']['baseUrl']) ? $configArray['bX']['baseUrl'] : 'http://recommender.service.exlibrisgroup.com/service/recommender/openurl'; $client = new HTTP_Request(); $client->setMethod(HTTP_REQUEST_METHOD_GET); $client->setURL($baseUrl . "?{$openUrl}"); $result = $client->sendRequest(); if (!PEAR::isError($result)) { // Even if we get a response, make sure it's a 'good' one. if ($client->getResponseCode() != 200) { $this->output('bX request failed, response code ' . $client->getResponseCode(), JSON::STATUS_ERROR); } } else { $this->_output('bX request failed: ' . $result, JSON::STATUS_ERROR); } $xml = simplexml_load_string($client->getResponseBody()); $data = array(); $jnl = 'info:ofi/fmt:xml:xsd:journal'; $xml->registerXPathNamespace('jnl', $jnl); foreach ($xml->xpath('//jnl:journal') as $journal) { $item = $this->convertToArray($journal, $jnl); if (!isset($item['authors']['author'][0])) { $item['authors']['author'] = array($item['authors']['author']); } $item['openurl'] = $this->createOpenUrl($item); $data[] = $item; } $this->output($data, JSON::STATUS_OK); }
function placeHold() { global $interface; global $configArray; global $user; global $logger; //TODO: Clean this up so there is only ever one id. if (isset($_REQUEST['recordId'])) { $recordId = $_REQUEST['recordId']; } else { $recordId = $_REQUEST['id']; } $interface->assign('id', $recordId); //Get title information for the record. $holding = $this->catalog->getHolding($recordId); if (PEAR_Singleton::isError($holding)) { PEAR_Singleton::raiseError($holding); } $interface->assign('holding', $holding); if (isset($_REQUEST['autologout'])) { $_SESSION['autologout'] = true; } $showMessage = false; $type = isset($_REQUEST['holdType']) ? $_REQUEST['holdType'] : ''; if (isset($_POST['submit']) || $type == 'recall' || $type == 'update' || $type == 'hold') { if (isset($_REQUEST['username']) && isset($_REQUEST['password'])) { //Log the user in $user = UserAccount::login(); } if ($user) { //The user is already logged in $barcodeProperty = $configArray['Catalog']['barcodeProperty']; $return = $this->catalog->placeHold($recordId, $user->{$barcodeProperty}, '', $type); $interface->assign('result', $return['result']); $message = $return['message']; $interface->assign('message', $message); $showMessage = true; } else { $message = 'Incorrect Patron Information'; $interface->assign('message', $message); $interface->assign('focusElementId', 'username'); $showMessage = true; } } else { //Get the referrer so we can go back there. if (isset($_SERVER['HTTP_REFERER'])) { $referer = $_SERVER['HTTP_REFERER']; $_SESSION['hold_referrer'] = $referer; } //Showing place hold form. if ($user) { $profile = $this->catalog->getMyProfile($user); $interface->assign('profile', $profile); //Get information to show a warning if the user does not have sufficient holds require_once ROOT_DIR . '/Drivers/marmot_inc/PType.php'; $maxHolds = -1; //Determine if we should show a warning $ptype = new PType(); $ptype->pType = $user->patronType; if ($ptype->find(true)) { $maxHolds = $ptype->maxHolds; } $currentHolds = $profile['numHolds']; if ($maxHolds != -1 && $currentHolds + 1 > $maxHolds) { $interface->assign('showOverHoldLimit', true); $interface->assign('maxHolds', $maxHolds); $interface->assign('currentHolds', $currentHolds); } global $locationSingleton; //Get the list of pickup branch locations for display in the user interface. $locations = $locationSingleton->getPickupBranches($profile, $profile['homeLocationId']); $interface->assign('pickupLocations', $locations); //set focus to the submit button if the user is logged in since the campus will be correct most of the time. $interface->assign('focusElementId', 'submit'); } else { //set focus to the username field by default. $interface->assign('focusElementId', 'username'); } global $library; $patronHomeBranch = Library::getPatronHomeLibrary(); if ($patronHomeBranch != null) { if ($patronHomeBranch->defaultNotNeededAfterDays > 0) { $interface->assign('defaultNotNeededAfterDays', date('m/d/Y', time() + $patronHomeBranch->defaultNotNeededAfterDays * 60 * 60 * 24)); } else { $interface->assign('defaultNotNeededAfterDays', ''); } $interface->assign('showHoldCancelDate', $patronHomeBranch->showHoldCancelDate); } else { if ($library) { //Show the hold cancellation date for now. It may be hidden later when the user logs in. if ($library->defaultNotNeededAfterDays > 0) { $interface->assign('defaultNotNeededAfterDays', date('m/d/Y', time() + $library->defaultNotNeededAfterDays * 60 * 60 * 24)); } else { $interface->assign('defaultNotNeededAfterDays', ''); } $interface->assign('showHoldCancelDate', $library->showHoldCancelDate); } else { //Show the hold cancellation date for now. It may be hidden later when the user logs in. $interface->assign('showHoldCancelDate', 1); $interface->assign('defaultNotNeededAfterDays', ''); } } $activeLibrary = Library::getActiveLibrary(); if ($activeLibrary != null) { $interface->assign('holdDisclaimer', $activeLibrary->holdDisclaimer); } else { //Show the hold cancellation date for now. It may be hidden later when the user logs in. $interface->assign('holdDisclaimer', ''); } } $record = RecordDriverFactory::initRecordDriverById('ils:' . $_GET['id']); if ($record) { $interface->assign('record', $record); } else { PEAR_Singleton::raiseError('Cannot find record ' . $_GET['id']); } $interface->assign('id', $_GET['id']); if ($showMessage && isset($return)) { $hold_message_data = array('successful' => $return['result'] == true ? 'all' : 'none', 'error' => isset($return['error']) ? $return['error'] : '', 'titles' => array($return), 'campus' => $_REQUEST['campus']); //Check to see if there are item level holds that need follow-up by the user if (isset($return['items']) && count($return['items']) > 0) { $hold_message_data['showItemForm'] = true; $hold_message_data['items'] = $return['items']; } $_SESSION['hold_message'] = $hold_message_data; if (isset($_SESSION['hold_referrer'])) { $logger->log('Hold Referrer is set, redirecting to there. location ' . $_SESSION['hold_referrer'], PEAR_LOG_INFO); if ($_REQUEST['type'] != 'recall' && $_REQUEST['type'] != 'cancel' && $_REQUEST['type'] != 'update') { header("Location: " . $_SESSION['hold_referrer']); } else { //Redirect for hold cancellation or update $section = isset($_REQUEST['section']) ? $_REQUEST['section'] : 'unavailable'; header("Location: " . '/MyResearch/Holds?section=' . $section); } if (!isset($hold_message_data['showItemForm']) || $hold_message_data['showItemForm'] == false) { unset($_SESSION['hold_referrer']); if (isset($_SESSION['autologout'])) { unset($_SESSION['autologout']); UserAccount::softLogout(); } } } else { $logger->log('No referrer set, but there is a message to show, go to the main holds page', PEAR_LOG_INFO); header("Location: " . '/MyResearch/Holds'); die; } } else { //$logger->log('placeHold finished, do not need to show a message', PEAR_LOG_INFO); $interface->setPageTitle('Request an Item'); $interface->assign('subTemplate', 'hold.tpl'); $interface->setTemplate('hold.tpl'); $interface->display('layout.tpl', 'RecordHold' . $_GET['id']); } }
public function placeItemHold($recordId, $itemId, $patronId, $comment, $type) { global $configArray; global $user; $userId = $user->id; //Get the session token for the user if (isset(HorizonAPI::$sessionIdsForUsers[$userId])) { $sessionToken = HorizonAPI::$sessionIdsForUsers[$userId]; } else { //Log the user in list($userValid, $sessionToken) = $this->loginViaWebService($user->cat_username, $user->cat_password); if (!$userValid) { return array('result' => false, 'message' => 'Sorry, it does not look like you are logged in currently. Please login and try again'); } } // Retrieve Full Marc Record require_once ROOT_DIR . '/RecordDrivers/Factory.php'; $record = RecordDriverFactory::initRecordDriverById('ils:' . $recordId); if (!$record) { $title = null; } else { $title = $record->getTitle(); } if ($configArray['Catalog']['offline']) { global $user; require_once ROOT_DIR . '/sys/OfflineHold.php'; $offlineHold = new OfflineHold(); $offlineHold->bibId = $recordId; $offlineHold->patronBarcode = $patronId; $offlineHold->patronId = $user->id; $offlineHold->timeEntered = time(); $offlineHold->status = 'Not Processed'; if ($offlineHold->insert()) { return array('title' => $title, 'bib' => $recordId, 'result' => true, 'message' => 'The circulation system is currently offline. This hold will be entered for you automatically when the circulation system is online.'); } else { return array('title' => $title, 'bib' => $recordId, 'result' => false, 'message' => 'The circulation system is currently offline and we could not place this hold. Please try again later.'); } } else { if ($type == 'cancel' || $type == 'recall' || $type == 'update') { $result = $this->updateHold($recordId, $patronId, $type, $title); $result['title'] = $title; $result['bid'] = $recordId; return $result; } else { if (isset($_REQUEST['campus'])) { $campus = trim($_REQUEST['campus']); } else { global $user; $campus = $user->homeLocationId; } //create the hold using the web service $createHoldUrl = $configArray['Catalog']['webServiceUrl'] . '/standard/createMyHold?clientID=' . $configArray['Catalog']['clientId'] . '&sessionToken=' . $sessionToken . '&pickupLocation=' . $campus . '&titleKey=' . $recordId; if ($itemId) { $createHoldUrl .= '&itemKey=' . $itemId; } $createHoldResponse = $this->getWebServiceResponse($createHoldUrl); $hold_result = array(); if ($createHoldResponse == true) { $hold_result['result'] = true; $hold_result['message'] = 'Your hold was placed successfully.'; } else { $hold_result['result'] = false; $hold_result['message'] = 'Your hold could not be placed. '; if (isset($createHoldResponse->message)) { $hold_result['message'] .= (string) $createHoldResponse->message; } else { if (isset($createHoldResponse->string)) { $hold_result['message'] .= (string) $createHoldResponse->string; } } } $hold_result['title'] = $title; $hold_result['bid'] = $recordId; global $analytics; if ($analytics) { if ($hold_result['result'] == true) { $analytics->addEvent('ILS Integration', 'Successful Hold', $title); } else { $analytics->addEvent('ILS Integration', 'Failed Hold', $hold_result['message'] . ' - ' . $title); } } //Clear the patron profile $this->clearPatronProfile(); return $hold_result; } } }
function __construct($subAction = false, $record_id = null) { global $interface; global $configArray; global $library; global $timer; global $user; //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'; //Load basic information needed in subclasses if ($record_id == null || !isset($record_id)) { $this->id = $_GET['id']; } else { $this->id = $record_id; } // Setup Search Engine Connection // Include Search Engine Class require_once ROOT_DIR . '/sys/' . $configArray['Genealogy']['engine'] . '.php'; $timer->logTime('Include search engine'); // Initialise from the current search globals $this->db = SearchObjectFactory::initSearchObject($configArray['Genealogy']['searchObject']); $this->db->init($searchSource); // Retrieve Full Marc Record if (!($record = $this->db->getRecord('person' . $this->id))) { PEAR_Singleton::raiseError(new PEAR_Error('Record Does Not Exist')); } $this->record = $record; //Load person from the database to get additional information $person = Person::staticGet('personId', $this->id); $record['picture'] = $person->picture; $interface->assign('record', $record); $interface->assign('person', $person); $this->recordDriver = RecordDriverFactory::initRecordDriver($record); $timer->logTime('Initialized the Record Driver'); $marriages = array(); $personMarriages = $person->marriages; if (isset($personMarriages)) { foreach ($personMarriages as $marriage) { $marriageArray = (array) $marriage; $marriageArray['formattedMarriageDate'] = $person->formatPartialDate($marriage->marriageDateDay, $marriage->marriageDateMonth, $marriage->marriageDateYear); $marriages[] = $marriageArray; } } $interface->assign('marriages', $marriages); $obituaries = array(); $personObituaries = $person->obituaries; if (isset($personObituaries)) { foreach ($personObituaries as $obit) { $obitArray = (array) $obit; $obitArray['formattedObitDate'] = $person->formatPartialDate($obit->dateDay, $obit->dateMonth, $obit->dateYear); $obituaries[] = $obitArray; } } $interface->assign('obituaries', $obituaries); //Do actions needed if this is the main action. $interface->assign('id', $this->id); // Retrieve User Search History $interface->assign('lastsearch', isset($_SESSION['lastSearchURL']) ? $_SESSION['lastSearchURL'] : false); $this->cacheId = 'Person|' . $_GET['id'] . '|' . get_class($this); // Send down text for inclusion in breadcrumbs $interface->assign('breadcrumbText', $this->recordDriver->getBreadcrumb()); $formattedBirthdate = $person->formatPartialDate($person->birthDateDay, $person->birthDateMonth, $person->birthDateYear); $interface->assign('birthDate', $formattedBirthdate); $formattedDeathdate = $person->formatPartialDate($person->deathDateDay, $person->deathDateMonth, $person->deathDateYear); $interface->assign('deathDate', $formattedDeathdate); //Setup next and previous links based on the search results. if (isset($_REQUEST['searchId'])) { //rerun the search $s = new SearchEntry(); $s->id = $_REQUEST['searchId']; $interface->assign('searchId', $_REQUEST['searchId']); $currentPage = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1; $interface->assign('page', $currentPage); $s->find(); if ($s->N > 0) { $s->fetch(); $minSO = unserialize($s->search_object); $searchObject = SearchObjectFactory::deminify($minSO); $searchObject->setPage($currentPage); //Run the search $result = $searchObject->processSearch(true, false, false); //Check to see if we need to run a search for the next or previous page $currentResultIndex = $_REQUEST['recordIndex'] - 1; $recordsPerPage = $searchObject->getLimit(); if ($currentResultIndex % $recordsPerPage == 0 && $currentResultIndex > 0) { //Need to run a search for the previous page $interface->assign('previousPage', $currentPage - 1); $previousSearchObject = clone $searchObject; $previousSearchObject->setPage($currentPage - 1); $previousSearchObject->processSearch(true, false, false); $previousResults = $previousSearchObject->getResultRecordSet(); } else { if (($currentResultIndex + 1) % $recordsPerPage == 0 && $currentResultIndex + 1 < $searchObject->getResultTotal()) { //Need to run a search for the next page $nextSearchObject = clone $searchObject; $interface->assign('nextPage', $currentPage + 1); $nextSearchObject->setPage($currentPage + 1); $nextSearchObject->processSearch(true, false, false); $nextResults = $nextSearchObject->getResultRecordSet(); } } if (PEAR_Singleton::isError($result)) { //If we get an error excuting the search, just eat it for now. } else { if ($searchObject->getResultTotal() < 1) { //No results found } else { $recordSet = $searchObject->getResultRecordSet(); //Record set is 0 based, but we are passed a 1 based index if ($currentResultIndex > 0) { if (isset($previousResults)) { $previousRecord = $previousResults[count($previousResults) - 1]; } else { $previousRecord = $recordSet[$currentResultIndex - 1 - ($currentPage - 1) * $recordsPerPage]; } $interface->assign('previousId', $previousRecord['id']); //Convert back to 1 based index $interface->assign('previousIndex', $currentResultIndex - 1 + 1); $interface->assign('previousTitle', $previousRecord['title']); } if ($currentResultIndex + 1 < $searchObject->getResultTotal()) { if (isset($nextResults)) { $nextRecord = $nextResults[0]; } else { $nextRecord = $recordSet[$currentResultIndex + 1 - ($currentPage - 1) * $recordsPerPage]; } $interface->assign('nextId', $nextRecord['id']); //Convert back to 1 based index $interface->assign('nextIndex', $currentResultIndex + 1 + 1); $interface->assign('nextTitle', $nextRecord['title']); } } } } $timer->logTime('Got next/previous links'); } }
/** * Respond to a ListMetadataFormats request. * * @return void * @access protected */ protected function listMetadataFormats() { global $interface; // If a specific ID was provided, try to load the related record; otherwise, // set $recordDriver to false so we know it is a generic request. if (isset($this->params['identifier'])) { if (!($record = $this->loadRecord($this->params['identifier']))) { return $this->showError('idDoesNotExist', 'Unknown Record'); } $recordDriver = RecordDriverFactory::initRecordDriver($record); } else { $recordDriver = false; } // Loop through all available metadata formats and see if they apply in // the current context (all apply if $recordDriver is false, since that // means that no specific record ID was requested; otherwise, they only // apply if the current record driver supports them): $supported = array(); foreach ($this->metadataFormats as $prefix => $details) { if ($recordDriver === false || $recordDriver->getXML($prefix) !== false) { $supported[$prefix] = $details; } } // Display the response: $interface->assign('supported', $supported); $this->showResponse('list-metadata.tpl'); }
/** * Get data and output in JSON * * @return void * @access public */ public function getRSIStatuses() { //<SFX server>:<port>/<sfx_instance>/cgi/core/rsi/rsi.cgi global $configArray; if (!isset($configArray['OpenURL']['url'])) { return $this->output(array(), JSON::STATUS_OK); } $sfxUrl = $configArray['OpenURL']['url'] . "/cgi/core/rsi/rsi.cgi"; $metalib = new MetaLib(); $indexEngine = SearchObjectFactory::initSearchObject()->getIndexEngine(); $dom = new DOMDocument('1.0', 'UTF-8'); // ID REQUEST $idReq = $dom->createElement('IDENTIFIER_REQUEST', ''); $idReq->setAttribute("VERSION", "1.0"); $idReq->setAttribute("xsi:noNamespaceSchemaLocation", "ISSNRequest.xsd"); $idReq->setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); $dom->appendChild($idReq); // Cache values and status in an array $rsiResults = array(); $validRequest = false; foreach ($_REQUEST['id'] as $id) { if (strncmp($id, 'metalib.', 8) == 0) { if (!($record = $metalib->getRecord($id))) { $this->output('Record does not exist', JSON::STATUS_ERROR); return; } $values = array('isbn' => !empty($record['ISBN']) ? $record['ISBN'][0] : '', 'issn' => !empty($record['ISSN']) ? $record['ISSN'][0] : '', 'year' => !empty($record['PublicationDate']) ? $record['PublicationDate'][0] : '', 'volume' => !empty($record['Volume']) ? $record['Volume'] : '', 'issue' => !empty($record['Issue']) ? $record['Issue'] : '', 'institute' => isset($configArray['OpenURL']['institute']) ? $configArray['OpenURL']['institute'] : ''); } else { if (!($record = $indexEngine->getRecord($id))) { $this->output('Record does not exist', JSON::STATUS_ERROR); return; } $recordDriver = RecordDriverFactory::initRecordDriver($record); $values = $recordDriver->getRSIValues($recordDriver); } $result = array('id' => $id, 'status' => 'noInformation'); // Ignore the record if mandatory elements are not available if (empty($values['issn']) && empty($values['isbn'])) { // Mark this result invalid so it can be skipped when processing results $result['invalid'] = true; $rsiResults[] = $result; continue; } $rsiResults[] = $result; $validRequest = true; // ID REQUEST ITEM $idReqItem = $dom->createElement('IDENTIFIER_REQUEST_ITEM', ''); $idReq->appendChild($idReqItem); // ID if (!empty($values['issn'])) { $identifier = $dom->createElement('IDENTIFIER', 'issn:' . $values['issn']); $idReqItem->appendChild($identifier); } if (!empty($values['isbn'])) { $identifier = $dom->createElement('IDENTIFIER', 'isbn:' . $values['isbn']); $idReqItem->appendChild($identifier); } // Optional elements if ($values['year']) { $year = $dom->createElement('YEAR', $values['year']); $idReqItem->appendChild($year); } if ($values['volume']) { $volume = $dom->createElement('VOLUME', $values['volume']); $idReqItem->appendChild($volume); } if ($values['issue']) { $issue = $dom->createElement('ISSUE', $values['issue']); $idReqItem->appendChild($issue); } if ($values['institute']) { $institute = $dom->createElement('INSTITUTE_NAME', $values['institute']); $idReqItem->appendChild($institute); } } if (!$validRequest) { return $this->output(array(), JSON::STATUS_OK); } $xml = $dom->saveXML(); $req = new Proxy_Request($sfxUrl, array('saveBody' => true)); $req->setMethod(HTTP_REQUEST_METHOD_POST); $req->addPostData('request_xml', $xml); $req->sendRequest(); $code = $req->getResponseCode(); if ($code != 200) { $this->output("SFX RSI request failed ({$code})", JSON::STATUS_ERROR); return; } $dom->loadXML($req->getResponseBody()); $items = $dom->getElementsByTagName('IDENTIFIER_RESPONSE_ITEM'); $position = -1; foreach ($items as $item) { $requests = $dom->getElementsByTagName('IDENTIFIER_REQUEST_ITEM'); $request = $requests->item(0); $position++; // Bypass invalid ID's and stop if at the end of list. while (isset($rsiResults[$position]['invalid'])) { ++$position; } if (!isset($rsiResults[$position])) { break; } $result = $item->getElementsByTagName('RESULT')->item(0)->nodeValue; if ($result == 'not found') { $rsiResults[$position]['status'] = 'noFullText'; } elseif ($result == 'maybe') { $rsiResults[$position]['status'] = 'maybeFullText'; } else { foreach ($item->getElementsByTagName('AVAILABLE_SERVICES') as $service) { if ($service->nodeValue == 'getFullTxt') { $peerReviewed = false; foreach ($item->getElementsByTagName('PEER_REVIEWED') as $peer) { if ($peer->nodeValue == 'YES') { $peerReviewed = true; break; } } $rsiResults[$position]['status'] = $peerReviewed ? 'peerReviewedFullText' : 'fullText'; break; } } } } $results = array(); foreach ($rsiResults as $result) { $results[] = array('id' => $result['id'], 'status' => $result['status']); } return $this->output($results, JSON::STATUS_OK); }
function launch() { global $configArray; global $interface; global $user; //Enable and disable functionality based on library settings global $library; global $locationSingleton; $location = $locationSingleton->getActiveLocation(); if (isset($library)) { if ($location != null) { $interface->assign('showHoldButton', $location->showHoldButton == 1 && $library->showHoldButton == 1 ? 1 : 0); } else { $interface->assign('showHoldButton', $library->showHoldButton); } $interface->assign('showTagging', $library->showTagging); $interface->assign('showRatings', $library->showRatings); $interface->assign('showComments', $library->showComments); $interface->assign('showFavorites', $library->showFavorites); } else { if ($location != null) { $interface->assign('showHoldButton', $location->showHoldButton); } else { $interface->assign('showHoldButton', 1); } $interface->assign('showTagging', 1); $interface->assign('showRatings', 1); $interface->assign('showComments', 1); $interface->assign('showFavorites', 1); } //Build the actual view $interface->setTemplate('../Record/view-series.tpl'); $eContentRecord = new EContentRecord(); $this->id = strip_tags($_REQUEST['id']); $eContentRecord->id = $this->id; $eContentRecord->find(true); require_once 'Enrichment.php'; $enrichment = new EcontentRecord_Enrichment(); $enrichmentData = $enrichment->loadEnrichment($eContentRecord->getIsbn()); $seriesTitle = ''; $seriesAuthors = array(); $seriesTitles = array(); $resourceList = array(); if (isset($enrichmentData['novelist'])) { $seriesTitles = $enrichmentData['novelist']['series']; //Loading the series title is not reliable. Do not try to load it. if (isset($seriesTitles) && is_array($seriesTitles)) { foreach ($seriesTitles as $key => $title) { if (isset($title['series']) && strlen($title['series']) > 0 && !isset($seriesTitle)) { $seriesTitle = $title['series']; $interface->assign('seriesTitle', $seriesTitle); } if (isset($title['author'])) { $seriesAuthors[$title['author']] = $title['author']; } if ($title['libraryOwned']) { $record = RecordDriverFactory::initRecordDriver($title); $resourceList[] = $interface->fetch($record->getSearchResult($user, null, false)); } else { $interface->assign('record', $title); $resourceList[] = $interface->fetch('RecordDrivers/Index/nonowned_result.tpl'); } } } } $interface->assign('seriesAuthors', $seriesAuthors); $interface->assign('recordSet', $seriesTitles); $interface->assign('resourceList', $resourceList); $interface->assign('recordStart', 1); $interface->assign('recordEnd', count($seriesTitles)); $interface->assign('recordCount', count($seriesTitles)); $interface->setPageTitle($seriesTitle); // Display Page $interface->display('layout.tpl'); }
/** * Assign comments for the current resource to the interface. * * @return void * @access public */ public static function assignComments() { global $interface, $user; $comments = new Comments(); $commentList = $comments->getComments($_GET['id']); $interface->assign('commentList', $commentList); $reported = isset($_SESSION['reportedComments']) ? $_SESSION['reportedComments'] : array(); $usersComments = array(); if (is_object($user)) { $commentInapp = new Comments_inappropriate(); $commentInapp->user_id = $user->id; $commentInapp->find(); while ($commentInapp->fetch()) { $usersComments[] = $commentInapp->comment_id; } $commentedByUser = false; foreach ($commentList as $comment) { if ($user->id == $comment->user_id) { $commentedByUser = true; break; } } } include_once 'RecordDrivers/Factory.php'; $db = ConnectionManager::connectToIndex(); $id = $_REQUEST['id']; if (!($record = $db->getRecord($id))) { PEAR::raiseError(new PEAR_Error('Record Does Not Exist')); } $recordDriver = RecordDriverFactory::initRecordDriver($record); if ($recordDriver->getSector() == 'lib') { $interface->assign('ratings', true); } $interface->assign(compact('commentedByUser')); $interface->assign('reported', array_merge($reported, $usersComments)); }
/** * Place Item Hold * * This is responsible for both placing item level holds. * * @param string $recordId The id of the bib record * @param string $itemId The id of the item to hold * @param string $patronId The id of the patron * @param string $comment Any comment regarding the hold or recall * @param string $type Whether to place a hold or recall * @param string $type The date when the hold should be cancelled if any * @return mixed True if successful, false if unsuccessful * If an error occurs, return a PEAR_Error * @access public */ public function placeItemHold($recordId, $itemId, $patronId, $comment, $type) { global $configArray; $bib1 = $recordId; if (substr($bib1, 0, 1) != '.') { $bib1 = '.' . $bib1; } $bib = substr(str_replace('.b', 'b', $bib1), 0, -1); if (strlen($bib) == 0) { return array('result' => false, 'message' => 'A valid record id was not provided. Please try again.'); } //Get the title of the book. $class = $configArray['Index']['engine']; $url = $configArray['Index']['url']; $this->driver->db = new $class($url); // Retrieve Full Marc Record require_once ROOT_DIR . '/RecordDrivers/Factory.php'; $record = RecordDriverFactory::initRecordDriverById('ils:' . $bib1); if (!$record) { $title = null; } else { $title = $record->getTitle(); } if ($configArray['Catalog']['offline']) { global $user; require_once ROOT_DIR . '/sys/OfflineHold.php'; $offlineHold = new OfflineHold(); $offlineHold->bibId = $bib1; $offlineHold->patronBarcode = $patronId; $offlineHold->patronId = $user->id; $offlineHold->timeEntered = time(); $offlineHold->status = 'Not Processed'; if ($offlineHold->insert()) { return array('title' => $title, 'bib' => $bib1, 'result' => true, 'message' => 'The circulation system is currently offline. This hold will be entered for you automatically when the circulation system is online.'); } else { return array('title' => $title, 'bib' => $bib1, 'result' => false, 'message' => 'The circulation system is currently offline and we could not place this hold. Please try again later.'); } } else { //Cancel a hold if ($type == 'cancel' || $type == 'recall' || $type == 'update') { $result = $this->updateHold($recordId, $patronId, $type, $title); $result['title'] = $title; $result['bid'] = $bib1; return $result; } else { if (isset($_REQUEST['canceldate']) && !is_null($_REQUEST['canceldate']) && $_REQUEST['canceldate'] != '') { $date = $_REQUEST['canceldate']; } else { //Default to a date 6 months (half a year) in the future. $sixMonthsFromNow = time() + 182.5 * 24 * 60 * 60; $date = date('m/d/Y', $sixMonthsFromNow); } if (isset($_REQUEST['campus'])) { $campus = trim($_REQUEST['campus']); } else { global $user; $campus = $user->homeLocationId; } if (is_numeric($campus)) { $location = new Location(); $location->locationId = $campus; if ($location->find(true)) { $campus = $location->code; } } list($Month, $Day, $Year) = explode("/", $date); //------------BEGIN CURL----------------------------------------------------------------- $header = array(); $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,"; $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"; $header[] = "Cache-Control: max-age=0"; $header[] = "Connection: keep-alive"; $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"; $header[] = "Accept-Language: en-us,en;q=0.5"; $cookie = tempnam("/tmp", "CURLCOOKIE"); $curl_connection = curl_init(); curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($curl_connection, CURLOPT_HTTPHEADER, $header); curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl_connection, CURLOPT_UNRESTRICTED_AUTH, true); curl_setopt($curl_connection, CURLOPT_COOKIEJAR, $cookie); curl_setopt($curl_connection, CURLOPT_COOKIESESSION, true); curl_setopt($curl_connection, CURLOPT_FORBID_REUSE, false); curl_setopt($curl_connection, CURLOPT_HEADER, false); curl_setopt($curl_connection, CURLOPT_POST, true); $lt = null; if (isset($configArray['Catalog']['loginPriorToPlacingHolds']) && ($configArray['Catalog']['loginPriorToPlacingHolds'] = true)) { //User must be logged in as a separate step to placing holds $curl_url = $configArray['Catalog']['url'] . "/patroninfo"; $post_data = $this->driver->_getLoginFormValues(); $post_data['submit.x'] = "35"; $post_data['submit.y'] = "21"; $post_data['submit'] = "submit"; curl_setopt($curl_connection, CURLOPT_REFERER, $curl_url); curl_setopt($curl_connection, CURLOPT_URL, $curl_url); $post_items = array(); foreach ($post_data as $key => $value) { $post_items[] = $key . '=' . $value; } $post_string = implode('&', $post_items); curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string); $loginResult = curl_exec($curl_connection); $curlInfo = curl_getinfo($curl_connection); //When a library uses Encore, the initial login does a redirect and requires additional parameters. if (preg_match('/<input type="hidden" name="lt" value="(.*?)" \\/>/si', $loginResult, $loginMatches)) { //Get the lt value $lt = $loginMatches[1]; //Login again $post_data['lt'] = $lt; $post_data['_eventId'] = 'submit'; $post_items = array(); foreach ($post_data as $key => $value) { $post_items[] = $key . '=' . $value; } $post_string = implode('&', $post_items); curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string); $loginResult = curl_exec($curl_connection); $curlInfo = curl_getinfo($curl_connection); } $post_data = array(); } else { $post_data = $this->driver->_getLoginFormValues(); } $scope = $this->driver->getLibraryScope(); $curl_url = $configArray['Catalog']['url'] . "/search/.{$bib}/.{$bib}/1,1,1,B/request~{$bib}"; //echo "$curl_url"; curl_setopt($curl_connection, CURLOPT_URL, $curl_url); /** @var Library $librarySingleton */ global $librarySingleton; $patronHomeBranch = $librarySingleton->getPatronHomeLibrary(); if ($patronHomeBranch->defaultNotNeededAfterDays != -1) { $post_data['needby_Month'] = $Month; $post_data['needby_Day'] = $Day; $post_data['needby_Year'] = $Year; } $post_data['submit.x'] = "35"; $post_data['submit.y'] = "21"; $post_data['submit'] = "submit"; $post_data['locx00'] = str_pad($campus, 5 - strlen($campus), '+'); if (!is_null($itemId) && $itemId != -1) { $post_data['radio'] = $itemId; } $post_data['x'] = "48"; $post_data['y'] = "15"; if ($lt != null) { $post_data['lt'] = $lt; $post_data['_eventId'] = 'submit'; } $post_items = array(); foreach ($post_data as $key => $value) { $post_items[] = $key . '=' . $value; } $post_string = implode('&', $post_items); curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string); $sResult = curl_exec($curl_connection); global $logger; $logger->log("Placing hold {$curl_url}?{$post_string}", PEAR_LOG_INFO); $sResult = preg_replace("/<!--([^(-->)]*)-->/", "", $sResult); curl_close($curl_connection); //Parse the response to get the status message $hold_result = $this->_getHoldResult($sResult); $hold_result['title'] = $title; $hold_result['bid'] = $bib1; global $analytics; if ($analytics) { if ($hold_result['result'] == true) { $analytics->addEvent('ILS Integration', 'Successful Hold', $title); } else { $analytics->addEvent('ILS Integration', 'Failed Hold', $hold_result['message'] . ' - ' . $title); } } //Clear the patron profile $this->driver->clearPatronProfile(); return $hold_result; } } }