public function launch() { global $interface; if (isset($_REQUEST['startDate'])) { $startDate = new DateTime($_REQUEST['startDate']); } else { $startDate = new DateTime(); date_sub($startDate, new DateInterval('P1M')); } if (isset($_REQUEST['endDate'])) { $endDate = new DateTime($_REQUEST['endDate']); } else { $endDate = new DateTime(); } $interface->assign('startDate', $startDate->getTimestamp()); $interface->assign('endDate', $endDate->getTimestamp()); $offlineHolds = array(); $offlineHoldsObj = new OfflineHold(); $offlineHoldsObj->whereAdd("timeEntered >= " . $startDate->getTimestamp() . " AND timeEntered <= " . $endDate->getTimestamp()); $offlineHoldsObj->find(); while ($offlineHoldsObj->fetch()) { $offlineHold = array(); require_once ROOT_DIR . '/RecordDrivers/MarcRecord.php'; $recordDriver = new MarcRecord($offlineHoldsObj->bibId); if ($recordDriver->isValid()) { $offlineHold['title'] = $recordDriver->getTitle(); } $offlineHold['patronBarcode'] = $offlineHoldsObj->patronBarcode; $offlineHold['bibId'] = $offlineHoldsObj->bibId; $offlineHold['timeEntered'] = $offlineHoldsObj->timeEntered; $offlineHold['status'] = $offlineHoldsObj->status; $offlineHold['notes'] = $offlineHoldsObj->notes; $offlineHolds[] = $offlineHold; } $interface->setPageTitle('Offline Holds Report'); $interface->assign('sidebar', 'MyAccount/account-sidebar.tpl'); $interface->assign('offlineHolds', $offlineHolds); $interface->setTemplate('offlineHoldsReport.tpl'); $interface->display('layout.tpl'); }
/** * Constructor. We build the object using data from the Hoopla records stored on disk. * Will be similar to a MarcRecord with slightly different functionality * * @param array|File_MARC_Record|string $record * @access public */ public function __construct($record) { if ($record instanceof File_MARC_Record) { $this->marcRecord = $record; } elseif (is_string($record)) { require_once ROOT_DIR . '/sys/MarcLoader.php'; $this->id = $record; $this->valid = MarcLoader::marcExistsForHooplaId($record); } else { // Call the parent's constructor... parent::__construct($record); // Also process the MARC record: require_once ROOT_DIR . '/sys/MarcLoader.php'; $this->marcRecord = MarcLoader::loadMarcRecordFromRecord($record); if (!$this->marcRecord) { $this->valid = false; } } parent::loadGroupedWork(); }
public function getReadingHistory($patron, $page = 1, $recordsPerPage = -1, $sortOption = "checkedOut") { global $timer; $patronDump = $this->driver->_getPatronDump($this->driver->_getBarcode()); //Load the information from millennium using CURL $pageContents = $this->driver->_fetchPatronInfoPage($patronDump, 'readinghistory'); //Check to see if there are multiple pages of reading history $hasPagination = preg_match('/<td[^>]*class="browsePager"/', $pageContents); if ($hasPagination) { //Load a list of extra pages to load. The pagination links display multiple times, so load into an associative array to make them unique preg_match_all('/<a href="readinghistory&page=(\\d+)">/', $pageContents, $additionalPageMatches); $maxPageNum = 0; foreach ($additionalPageMatches[1] as $additionalPageMatch) { if ($additionalPageMatch > $maxPageNum) { $maxPageNum = $additionalPageMatch; } } } $recordsRead = 0; $readingHistoryTitles = $this->parseReadingHistoryPage($pageContents, $patron, $sortOption, $recordsRead); $recordsRead += count($readingHistoryTitles); if (isset($maxPageNum)) { for ($pageNum = 2; $pageNum <= $maxPageNum; $pageNum++) { $pageContents = $this->driver->_fetchPatronInfoPage($patronDump, 'readinghistory&page=' . $pageNum); $additionalTitles = $this->parseReadingHistoryPage($pageContents, $patron, $sortOption, $recordsRead); $recordsRead += count($additionalTitles); $readingHistoryTitles = array_merge($readingHistoryTitles, $additionalTitles); } } if ($sortOption == "checkedOut" || $sortOption == "returned") { krsort($readingHistoryTitles); } else { ksort($readingHistoryTitles); } $numTitles = count($readingHistoryTitles); //process pagination if ($recordsPerPage != -1) { $startRecord = ($page - 1) * $recordsPerPage; $readingHistoryTitles = array_slice($readingHistoryTitles, $startRecord, $recordsPerPage); } set_time_limit(20 * count($readingHistoryTitles)); foreach ($readingHistoryTitles as $key => $historyEntry) { //Get additional information from resources table $historyEntry['ratingData'] = null; $historyEntry['permanentId'] = null; $historyEntry['linkUrl'] = null; $historyEntry['coverUrl'] = null; $historyEntry['format'] = array(); if (isset($historyEntry['shortId']) && strlen($historyEntry['shortId']) > 0) { $historyEntry['recordId'] = "." . $historyEntry['shortId'] . $this->driver->getCheckDigit($historyEntry['shortId']); require_once ROOT_DIR . '/RecordDrivers/MarcRecord.php'; $recordDriver = new MarcRecord($historyEntry['recordId']); if ($recordDriver->isValid()) { $historyEntry['ratingData'] = $recordDriver->getRatingData(); $historyEntry['permanentId'] = $recordDriver->getPermanentId(); $historyEntry['linkUrl'] = $recordDriver->getLinkUrl(); $historyEntry['coverUrl'] = $recordDriver->getBookcoverUrl('medium'); $historyEntry['format'] = $recordDriver->getFormats(); } $recordDriver = null; } $readingHistoryTitles[$key] = $historyEntry; } //The history is active if there is an opt out link. $historyActive = strpos($pageContents, 'OptOut') > 0; $timer->logTime("Loaded Reading history for patron"); global $user; if ($historyActive && !$user->trackReadingHistory) { //The user does have reading history even though we hadn't detected it before. $user->trackReadingHistory = true; $user->update(); $_SESSION['userinfo'] = serialize($user); } if (!$historyActive && $user->trackReadingHistory) { //The user does have reading history even though we hadn't detected it before. $user->trackReadingHistory = false; $user->update(); $_SESSION['userinfo'] = serialize($user); } return array('historyActive' => $historyActive, 'titles' => $readingHistoryTitles, 'numTitles' => $numTitles); }
function getRelatedRecords($realTimeStatusNeeded) { $parentRecords = parent::getRelatedRecords($realTimeStatusNeeded); $relatedRecords = array(); $sources = $this->getSources(); //Add a record per source foreach ($sources as $source) { foreach ($parentRecords as $relatedRecord) { $relatedRecord['source'] = $source; if ($relatedRecord['available']) { $relatedRecord['availableOnline'] = true; } //$relatedRecord['usageRestrictions'] = $this->getUsageRestrictions(); $relatedRecords[] = $relatedRecord; } } return $relatedRecords; }
public function getMyHolds($patron = null, $page = 1, $recordsPerPage = -1, $sortOption = 'title') { global $timer; $patronDump = $this->driver->_getPatronDump($this->driver->_getBarcode()); //Load the information from millennium using CURL $sResult = $this->driver->_fetchPatronInfoPage($patronDump, 'holds'); $timer->logTime("Got holds page from Millennium"); $holds = $this->parseHoldsPage($sResult); $timer->logTime("Parsed Holds page"); require_once ROOT_DIR . '/RecordDrivers/MarcRecord.php'; foreach ($holds as $section => $holdSections) { foreach ($holdSections as $key => $hold) { disableErrorHandler(); $recordDriver = new MarcRecord($hold['recordId']); if ($recordDriver->isValid()) { $hold['id'] = $recordDriver->getUniqueID(); $hold['shortId'] = $recordDriver->getShortId(); //Load title, author, and format information about the title $hold['title'] = $recordDriver->getTitle(); $hold['sortTitle'] = $recordDriver->getSortableTitle(); $hold['author'] = $recordDriver->getAuthor(); $hold['format'] = $recordDriver->getFormat(); $hold['isbn'] = $recordDriver->getCleanISBN(); $hold['upc'] = $recordDriver->getCleanUPC(); $hold['format_category'] = $recordDriver->getFormatCategory(); //Load rating information $hold['ratingData'] = $recordDriver->getRatingData(); $holds[$section][$key] = $hold; } enableErrorHandler(); } } //Process sorting //echo ("<br/>\r\nSorting by $sortOption"); foreach ($holds as $sectionName => $section) { $sortKeys = array(); $i = 0; foreach ($section as $key => $hold) { $sortTitle = isset($hold['sortTitle']) ? $hold['sortTitle'] : (isset($hold['title']) ? $hold['title'] : "Unknown"); if ($sectionName == 'available') { $sortKeys[$key] = $sortTitle; } else { if ($sortOption == 'title') { $sortKeys[$key] = $sortTitle; } elseif ($sortOption == 'author') { $sortKeys[$key] = (isset($hold['author']) ? $hold['author'] : "Unknown") . '-' . $sortTitle; } elseif ($sortOption == 'placed') { $sortKeys[$key] = $hold['createTime'] . '-' . $sortTitle; } elseif ($sortOption == 'format') { $sortKeys[$key] = (isset($hold['format']) ? $hold['format'] : "Unknown") . '-' . $sortTitle; } elseif ($sortOption == 'location') { $sortKeys[$key] = (isset($hold['location']) ? $hold['location'] : "Unknown") . '-' . $sortTitle; } elseif ($sortOption == 'holdQueueLength') { $sortKeys[$key] = (isset($hold['holdQueueLength']) ? $hold['holdQueueLength'] : 0) . '-' . $sortTitle; } elseif ($sortOption == 'position') { $sortKeys[$key] = str_pad(isset($hold['position']) ? $hold['position'] : 1, 3, "0", STR_PAD_LEFT) . '-' . $sortTitle; } elseif ($sortOption == 'status') { $sortKeys[$key] = (isset($hold['status']) ? $hold['status'] : "Unknown") . '-' . (isset($hold['reactivateTime']) ? $hold['reactivateTime'] : "0") . '-' . $sortTitle; } else { $sortKeys[$key] = $sortTitle; } //echo ("<br/>\r\nSort Key for $key = {$sortKeys[$key]}"); } $sortKeys[$key] = strtolower($sortKeys[$key] . '-' . $i++); } array_multisort($sortKeys, $section); $holds[$sectionName] = $section; } //Limit to a specific number of records if (isset($holds['unavailable'])) { $numUnavailableHolds = count($holds['unavailable']); if ($recordsPerPage != -1) { $startRecord = ($page - 1) * $recordsPerPage; $holds['unavailable'] = array_slice($holds['unavailable'], $startRecord, $recordsPerPage); } } else { $numUnavailableHolds = 0; } if (!isset($holds['available'])) { $holds['available'] = array(); } if (!isset($holds['unavailable'])) { $holds['unavailable'] = array(); } //Sort the hold sections so available holds are first. ksort($holds); $patronId = isset($patron) ? $patron['id'] : $this->driver->_getBarcode(); $this->holds[$patronId] = $holds; $timer->logTime("Processed hold pagination and sorting"); return array('holds' => $holds, 'numUnavailableHolds' => $numUnavailableHolds); }
function launch() { global $configArray; global $interface; global $user; //these actions are being moved to MyAccount/AJAX.php if (isset($_REQUEST['multiAction'])) { $multiAction = $_REQUEST['multiAction']; $locationId = isset($_REQUEST['location']) ? $_REQUEST['location'] : null; $cancelId = array(); $type = 'update'; $freeze = ''; if ($multiAction == 'cancelSelected') { $type = 'cancel'; // $freeze = ''; // same as default setting. } elseif ($multiAction == 'freezeSelected') { // $type = 'update'; // same as default setting. $freeze = 'on'; } elseif ($multiAction == 'thawSelected') { // $type = 'update'; // same as default setting. $freeze = 'off'; } // elseif ($multiAction == 'updateSelected'){ // same as default settings. // $type = 'update'; // $freeze = ''; // } $result = $this->catalog->driver->updateHoldDetailed($user->password, $type, '', null, $cancelId, $locationId, $freeze); // $interface->assign('holdResult', $result); //Redirect back here without the extra parameters. $redirectUrl = $configArray['Site']['path'] . '/MyAccount/Holds?accountSort=' . ($selectedSortOption = isset($_REQUEST['accountSort']) ? $_REQUEST['accountSort'] : 'title'); header("Location: " . $redirectUrl); die; } $interface->assign('allowFreezeHolds', true); $ils = $configArray['Catalog']['ils']; $showPosition = $ils == 'Horizon' || ($ils = 'Koha'); $showExpireTime = $ils == 'Horizon'; $suspendRequiresReactivationDate = $ils == 'Horizon'; $interface->assign('suspendRequiresReactivationDate', $suspendRequiresReactivationDate); $canChangePickupLocation = $ils != 'Koha'; $interface->assign('canChangePickupLocation', $canChangePickupLocation); // Define sorting options $sortOptions = array('title' => 'Title', 'author' => 'Author', 'format' => 'Format', 'placed' => 'Date Placed', 'location' => 'Pickup Location', 'status' => 'Status'); if ($showPosition) { $sortOptions['position'] = 'Position'; } $interface->assign('sortOptions', $sortOptions); $selectedSortOption = isset($_REQUEST['accountSort']) ? $_REQUEST['accountSort'] : 'title'; $interface->assign('defaultSortOption', $selectedSortOption); $profile = $this->catalog->getMyProfile($user); // TODO: getMyProfile called for second time. First time on index.php $libraryHoursMessage = Location::getLibraryHoursMessage($profile['homeLocationId']); $interface->assign('libraryHoursMessage', $libraryHoursMessage); $allowChangeLocation = $ils == 'Millennium' || $ils == 'Sierra'; $interface->assign('allowChangeLocation', $allowChangeLocation); //$showPlacedColumn = ($ils == 'Horizon'); //Horizon Web Services does not include data placed anymore $showPlacedColumn = false; $interface->assign('showPlacedColumn', $showPlacedColumn); $showDateWhenSuspending = $ils == 'Horizon'; $interface->assign('showDateWhenSuspending', $showDateWhenSuspending); $interface->assign('showPosition', $showPosition); $interface->assign('showNotInterested', false); // Get My Transactions if ($configArray['Catalog']['offline']) { $interface->assign('offline', true); } else { $patron = null; if ($this->catalog->status) { if ($user->cat_username) { $patron = $this->catalog->patronLogin($user->cat_username, $user->cat_password); $patronResult = $this->catalog->getMyProfile($patron); // TODO: getMyProfile called above already. Is this call necessary? if (!PEAR_Singleton::isError($patronResult)) { $interface->assign('profile', $patronResult); } $interface->assign('sortOptions', $sortOptions); $selectedSortOption = isset($_REQUEST['accountSort']) ? $_REQUEST['accountSort'] : 'dueDate'; $interface->assign('defaultSortOption', $selectedSortOption); $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1; $recordsPerPage = isset($_REQUEST['pagesize']) && is_numeric($_REQUEST['pagesize']) ? $_REQUEST['pagesize'] : 25; $interface->assign('recordsPerPage', $recordsPerPage); if (isset($_GET['exportToExcel'])) { $recordsPerPage = -1; $page = 1; } //Get Holds from the ILS $ilsHolds = $this->catalog->getMyHolds($patron, 1, -1, $selectedSortOption); if (PEAR_Singleton::isError($ilsHolds)) { $ilsHolds = array(); } //Get holds from OverDrive require_once ROOT_DIR . '/Drivers/OverDriveDriverFactory.php'; $overDriveDriver = OverDriveDriverFactory::getDriver(); $overDriveHolds = $overDriveDriver->getOverDriveHolds($user); //Get a list of eContent that has been checked out require_once ROOT_DIR . '/Drivers/EContentDriver.php'; $driver = new EContentDriver(); $eContentHolds = $driver->getMyHolds($user); $allHolds = array_merge_recursive($ilsHolds, $overDriveHolds, $eContentHolds); /* pickUpLocations doesn't seem to be used by the Holds summary page. plb 1-26-2015 $location = new Location(); $pickupBranches = $location->getPickupBranches($patronResult, null); $locationList = array(); foreach ($pickupBranches as $curLocation) { $locationList[$curLocation->locationId] = $curLocation->displayName; } $interface->assign('pickupLocations', $locationList); */ //Make sure available holds come before unavailable $interface->assign('recordList', $allHolds['holds']); //make call to export function if (isset($_GET['exportToExcelAvailable']) || isset($_GET['exportToExcelUnavailable'])) { if (isset($_GET['exportToExcelAvailable'])) { $exportType = "available"; } else { $exportType = "unavailable"; } $this->exportToExcel($allHolds['holds'], $exportType, $showDateWhenSuspending, $showPosition, $showExpireTime); } } } $interface->assign('patron', $patron); } //Load holds that have been entered offline if ($user) { require_once ROOT_DIR . '/sys/OfflineHold.php'; $twoDaysAgo = time() - 48 * 60 * 60; $twoWeeksAgo = time() - 14 * 24 * 60 * 60; $offlineHoldsObj = new OfflineHold(); $offlineHoldsObj->patronId = $user->id; $offlineHoldsObj->whereAdd("status = 'Not Processed' OR (status = 'Hold Placed' AND timeEntered >= {$twoDaysAgo}) OR (status = 'Hold Failed' AND timeEntered >= {$twoWeeksAgo})"); // mysql has these functions as well: "status = 'Not Processed' OR (status = 'Hold Placed' AND timeEntered >= DATE_SUB(NOW(), INTERVAL 2 DAYS)) OR (status = 'Hold Failed' AND timeEntered >= DATE_SUB(NOW(), INTERVAL 2 WEEKS))"); $offlineHolds = array(); if ($offlineHoldsObj->find()) { while ($offlineHoldsObj->fetch()) { //Load the title $offlineHold = array(); require_once ROOT_DIR . '/RecordDrivers/MarcRecord.php'; $recordDriver = new MarcRecord($offlineHoldsObj->bibId); if ($recordDriver->isValid()) { $offlineHold['title'] = $recordDriver->getTitle(); } $offlineHold['bibId'] = $offlineHoldsObj->bibId; $offlineHold['timeEntered'] = $offlineHoldsObj->timeEntered; $offlineHold['status'] = $offlineHoldsObj->status; $offlineHold['notes'] = $offlineHoldsObj->notes; $offlineHolds[] = $offlineHold; } } $interface->assign('offlineHolds', $offlineHolds); } $interface->setPageTitle('My Holds'); $interface->assign('sidebar', 'MyAccount/account-sidebar.tpl'); global $library; if (!$library->showDetailedHoldNoticeInformation) { $notification_method = ''; } else { $notification_method = $profile['noticePreferenceLabel'] != 'Unknown' ? $profile['noticePreferenceLabel'] : ''; if ($notification_method == 'Mail' && $library->treatPrintNoticesAsPhoneNotices) { $notification_method = 'Telephone'; } } $interface->assign('notification_method', strtolower($notification_method)); $interface->setTemplate('holds.tpl'); //print_r($patron); $interface->display('layout.tpl'); }
/** * Get Patron Holds * * This is responsible for retrieving all holds by a specific patron. * * @param array|User $patron The patron array from patronLogin * @param integer $page The current page of holds * @param integer $recordsPerPage The number of records to show per page * @param string $sortOption How the records should be sorted * @param string $summaryPage If the summary page has already been loaded, it can be passed in for performance reasons. * * @return mixed Array of the patron's holds on success, PEAR_Error * otherwise. * @access public */ public function getMyHoldsFromDB($patron, $page = 1, $recordsPerPage = -1, $sortOption = 'title') { global $user; $availableHolds = array(); $unavailableHolds = array(); $holds = array('available' => $availableHolds, 'unavailable' => $unavailableHolds); $this->initDatabaseConnection(); $sql = "SELECT *, title, author FROM reserves inner join biblio on biblio.biblionumber = reserves.biblionumber where borrowernumber = ?"; $holdsStmt = mysqli_prepare($this->dbConnection, $sql); $holdsStmt->bind_param('i', $user->username); $holdsStmt->execute(); $results = $holdsStmt->get_result(); while ($curRow = $results->fetch_assoc()) { //Each row in the table represents a hold $curHold = array(); $curHold['holdSource'] = 'ILS'; $bibId = $curRow['biblionumber']; $curHold['id'] = $curRow['biblionumber']; $curHold['shortId'] = $curRow['biblionumber']; $curHold['recordId'] = $curRow['biblionumber']; $curHold['title'] = $curRow['title']; $curHold['create'] = date_parse_from_format('Y-M-d H:m:s', $curRow['reservedate']); $curHold['expire'] = date_parse_from_format('Y-M-d', $curRow['expirationdate']); $curHold['location'] = $curRow['branchcode']; $curHold['locationUpdateable'] = false; $curHold['currentPickupName'] = $curHold['location']; $curHold['position'] = $curRow['priority']; $curHold['frozen'] = false; $curHold['freezeable'] = false; $curHold['cancelable'] = true; if ($curRow['found'] == 'S') { $curHold['frozen'] = true; $curHold['status'] = "Suspended"; $curHold['cancelable'] = false; } elseif ($curRow['found'] == 'W') { $curHold['status'] = "Ready to Pickup"; } elseif ($curRow['found'] == 'T') { $curHold['status'] = "In Transit"; } else { $curHold['status'] = "Pending"; $curHold['freezeable'] = true; } $curHold['freezeable'] = true; $curHold['cancelId'] = $curRow['reservenumber']; if ($bibId) { require_once ROOT_DIR . '/RecordDrivers/MarcRecord.php'; $recordDriver = new MarcRecord($bibId); if ($recordDriver->isValid()) { $curHold['sortTitle'] = $recordDriver->getSortableTitle(); $curHold['format'] = $recordDriver->getFormat(); $curHold['isbn'] = $recordDriver->getCleanISBN(); $curHold['upc'] = $recordDriver->getCleanUPC(); $curHold['format_category'] = $recordDriver->getFormatCategory(); //Load rating information $curHold['ratingData'] = $recordDriver->getRatingData(); } } if (!isset($curHold['status']) || !preg_match('/^Item waiting.*/i', $curHold['status'])) { $holds['unavailable'][] = $curHold; } else { $holds['available'][] = $curHold; } } return array('holds' => $holds, 'numUnavailableHolds' => count($holds['unavailable'])); }
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); // Retrieve Full Marc Record disableErrorHandler(); $record = $this->db->getRecord($this->id); enableErrorHandler(); if ($record == false) { $marcRecord = new MarcRecord($this->id); if ($marcRecord->isValid()) { $itemData['holdings'] = Record_Holdings::loadHoldings($this->id); $timer->logTime('Loaded Holdings'); } else { $itemData['error'] = 'Cannot load Record for id ' . $record['id']; } } else { $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; }
/** * @return MillenniumDriver|Sierra|Marmot|DriverInterface|HorizonAPI */ protected static function getCatalogDriver() { if (MarcRecord::$catalogDriver == null) { global $configArray; try { require_once ROOT_DIR . '/CatalogFactory.php'; MarcRecord::$catalogDriver = CatalogFactory::getCatalogConnectionInstance(); } catch (PDOException $e) { // What should we do with this error? if ($configArray['System']['debug']) { echo '<pre>'; echo 'DEBUG: ' . $e->getMessage(); echo '</pre>'; } return null; } } return MarcRecord::$catalogDriver; }
public function getMyTransactions($page = 1, $recordsPerPage = -1, $sortOption = 'dueDate') { global $timer; $patronDump = $this->driver->_getPatronDump($this->driver->_getBarcode()); $timer->logTime("Ready to load checked out titles from Millennium"); //Load the information from millennium using CURL $sResult = $this->driver->_fetchPatronInfoPage($patronDump, 'items'); $timer->logTime("Loaded checked out titles from Millennium"); $sResult = preg_replace("/<[^<]+?>\\W<[^<]+?>\\W\\d* ITEM.? CHECKED OUT<[^<]+?>\\W<[^<]+?>/i", "", $sResult); $s = substr($sResult, stripos($sResult, 'patFunc')); $s = substr($s, strpos($s, ">") + 1); $s = substr($s, 0, stripos($s, "</table")); $s = preg_replace("/<br \\/>/", "", $s); $sRows = preg_split("/<tr([^>]*)>/", $s); $sCount = 0; $sKeys = array_pad(array(), 10, ""); $checkedOutTitles = array(); //Get patron's location to determine if renewals are allowed. global $locationSingleton; /** @var Location $patronLocation */ $patronLocation = $locationSingleton->getUserHomeLocation(); if (isset($patronLocation)) { $patronPType = $this->driver->getPType(); $patronCanRenew = false; if ($patronLocation->ptypesToAllowRenewals == '*') { $patronCanRenew = true; } else { if (preg_match("/^({$patronLocation->ptypesToAllowRenewals})\$/", $patronPType)) { $patronCanRenew = true; } } } else { $patronCanRenew = true; } $timer->logTime("Determined if patron can renew"); foreach ($sRows as $srow) { $scols = preg_split("/<t(h|d)([^>]*)>/", $srow); $curTitle = array(); for ($i = 0; $i < sizeof($scols); $i++) { $scols[$i] = str_replace(" ", " ", $scols[$i]); $scols[$i] = preg_replace("/<br+?>/", " ", $scols[$i]); $scols[$i] = html_entity_decode(trim(substr($scols[$i], 0, stripos($scols[$i], "</t")))); //print_r($scols[$i]); if ($sCount == 1) { $sKeys[$i] = $scols[$i]; } else { if ($sCount > 1) { if (stripos($sKeys[$i], "TITLE") > -1) { if (preg_match('/.*?<a href=\\"\\/record=(.*?)(?:~S\\d{1,2})\\">(.*?)<\\/a>.*/', $scols[$i], $matches)) { //Standard Millennium WebPAC $shortId = $matches[1]; $bibid = '.' . $matches[1]; //Technically, this isn't correct since the check digit is missing $title = strip_tags($matches[2]); } elseif (preg_match('/.*<a href=".*?\\/record\\/C__R(.*?)\\?.*?">(.*?)<\\/a>.*/si', $scols[$i], $matches)) { //Encore $shortId = $matches[1]; $bibid = '.' . $matches[1]; //Technically, this isn't correct since the check digit is missing $title = strip_tags($matches[2]); } else { $title = strip_tags($scols[$i]); $shortId = ''; $bibid = ''; } $curTitle['checkoutSource'] = 'ILS'; $curTitle['shortId'] = $shortId; $curTitle['id'] = $bibid; $curTitle['title'] = utf8_encode($title); } if (stripos($sKeys[$i], "STATUS") > -1) { // $sret[$scount-2]['duedate'] = strip_tags($scols[$i]); $due = trim(str_replace("DUE", "", strip_tags($scols[$i]))); $renewCount = 0; if (preg_match('/FINE\\(up to now\\) (\\$\\d+\\.\\d+)/i', $due, $matches)) { $curTitle['fine'] = trim($matches[1]); } if (preg_match('/(.*)Renewed (\\d+) time(?:s)?/i', $due, $matches)) { $due = trim($matches[1]); $renewCount = $matches[2]; } else { if (preg_match('/(.*)\\+\\d+ HOLD.*/i', $due, $matches)) { $due = trim($matches[1]); } } if (preg_match('/(\\d{2}-\\d{2}-\\d{2})/', $due, $dueMatches)) { $dateDue = DateTime::createFromFormat('m-d-y', $dueMatches[1]); if ($dateDue) { $dueTime = $dateDue->getTimestamp(); } else { $dueTime = null; } } else { $dueTime = strtotime($due); } if ($dueTime != null) { $daysUntilDue = ceil(($dueTime - time()) / (24 * 60 * 60)); $overdue = $daysUntilDue < 0; $curTitle['duedate'] = $dueTime; $curTitle['overdue'] = $overdue; $curTitle['daysUntilDue'] = $daysUntilDue; } $curTitle['renewCount'] = $renewCount; } if (stripos($sKeys[$i], "BARCODE") > -1) { $curTitle['barcode'] = strip_tags($scols[$i]); } if (stripos($sKeys[$i], "RENEW") > -1) { $matches = array(); if (preg_match('/<input\\s*type="checkbox"\\s*name="renew(\\d+)"\\s*id="renew(\\d+)"\\s*value="(.*?)"\\s*\\/>/', $scols[$i], $matches)) { $curTitle['canrenew'] = $patronCanRenew; $curTitle['itemindex'] = $matches[1]; $curTitle['itemid'] = $matches[3]; $curTitle['renewIndicator'] = $curTitle['itemid'] . '|' . $curTitle['itemindex']; $curTitle['renewMessage'] = ''; } else { $curTitle['canrenew'] = false; } } if (stripos($sKeys[$i], "CALL NUMBER") > -1) { $curTitle['request'] = "null"; } } } } if ($sCount > 1) { //Get additional information from resources table if ($curTitle['shortId'] && strlen($curTitle['shortId']) > 0) { $checkDigit = $this->driver->getCheckDigit($curTitle['shortId']); $curTitle['recordId'] = '.' . $curTitle['shortId'] . $checkDigit; $curTitle['id'] = '.' . $curTitle['shortId'] . $checkDigit; require_once ROOT_DIR . '/RecordDrivers/MarcRecord.php'; $recordDriver = new MarcRecord($curTitle['recordId']); if ($recordDriver->isValid()) { $curTitle['coverUrl'] = $recordDriver->getBookcoverUrl('medium'); $curTitle['groupedWorkId'] = $recordDriver->getGroupedWorkId(); $formats = $recordDriver->getFormats(); $curTitle['format'] = reset($formats); $curTitle['author'] = $recordDriver->getPrimaryAuthor(); if (!isset($curTitle['title']) || empty($curTitle['title'])) { $curTitle['title'] = $recordDriver->getTitle(); } } else { $curTitle['coverUrl'] = ""; $curTitle['groupedWorkId'] = ""; $curTitle['format'] = "Unknown"; $curTitle['author'] = ""; } } $sortTitle = isset($curTitle['title_sort']) ? $curTitle['title_sort'] : $curTitle['title']; $sortKey = $sortTitle; if ($sortOption == 'title') { $sortKey = $sortTitle; } elseif ($sortOption == 'author') { $sortKey = (isset($curTitle['author']) ? $curTitle['author'] : "Unknown") . '-' . $sortTitle; } elseif ($sortOption == 'dueDate') { if (isset($curTitle['duedate'])) { if (preg_match('/.*?(\\d{1,2})[-\\/](\\d{1,2})[-\\/](\\d{2,4}).*/', $curTitle['duedate'], $matches)) { $sortKey = $matches[3] . '-' . $matches[1] . '-' . $matches[2] . '-' . $sortTitle; } else { $sortKey = $curTitle['duedate'] . '-' . $sortTitle; } } } elseif ($sortOption == 'format') { $sortKey = (isset($curTitle['format']) ? $curTitle['format'] : "Unknown") . '-' . $sortTitle; } elseif ($sortOption == 'renewed') { $sortKey = (isset($curTitle['renewCount']) ? $curTitle['renewCount'] : 0) . '-' . $sortTitle; } elseif ($sortOption == 'holdQueueLength') { $sortKey = (isset($curTitle['holdQueueLength']) ? $curTitle['holdQueueLength'] : 0) . '-' . $sortTitle; } $sortKey .= "_{$sCount}"; $checkedOutTitles[utf8_encode($sortKey)] = $curTitle; } $sCount++; } ksort($checkedOutTitles); $timer->logTime("Parsed checkout information"); $numTransactions = count($checkedOutTitles); //Process pagination if ($recordsPerPage != -1) { $startRecord = ($page - 1) * $recordsPerPage; if ($startRecord > $numTransactions) { $startRecord = 0; } $checkedOutTitles = array_slice($checkedOutTitles, $startRecord, $recordsPerPage); } return array('transactions' => $checkedOutTitles, 'numTransactions' => $numTransactions); }
function launch() { global $configArray; global $interface; //////////Populate the Date Filter Start //Grab the Selected Date Start if (isset($_REQUEST['dateFilterStart'])) { if (preg_match('/\\d{1,2}\\/\\d{1,2}\\/\\d{4}/', $_REQUEST['dateFilterStart'])) { $selectedDateStart = DateTime::createFromFormat('m/d/Y', $_REQUEST['dateFilterStart']); $selectedDateStart = $selectedDateStart->getTimestamp(); } else { $selectedDateStart = strtotime($_REQUEST['dateFilterStart']); } } else { $selectedDateStart = strtotime('-30 days'); } $selectedDateStart = date('Y-m-d', $selectedDateStart); $interface->assign('selectedDateStart', $selectedDateStart); //Populate the Date Filter End //Grab the Selected End Date if (isset($_REQUEST['dateFilterEnd'])) { if (preg_match('/\\d{1,2}\\/\\d{1,2}\\/\\d{4}/', $_REQUEST['dateFilterEnd'])) { $selectedDateEnd = DateTime::createFromFormat('m/d/Y', $_REQUEST['dateFilterEnd']); $selectedDateEnd = $selectedDateEnd->getTimestamp(); } else { $selectedDateEnd = strtotime($_REQUEST['dateFilterEnd']); } } else { $selectedDateEnd = strtotime('today'); } $selectedDateEnd = date('Y-m-d', $selectedDateEnd); $interface->assign('selectedDateEnd', $selectedDateEnd); //////////Populate the Stores Filter $queryHostsFilter = "SELECT DISTINCT linkHost AS linkHost FROM external_link_tracking ORDER BY linkHost ASC"; $externalLinkTracking = new ExternalLinkTracking(); $externalLinkTracking->query($queryHostsFilter); $allHosts = array(); while ($externalLinkTracking->fetch()) { $allHosts[] = $externalLinkTracking->linkHost; } $interface->assign('hostFilter', $allHosts); //////////Grab the Selected Hosts Filter Value if (isset($_REQUEST['hostFilter'])) { $selectedHosts = $_REQUEST['hostFilter']; } else { $selectedHosts = $allHosts; } $interface->assign('selectedHosts', $selectedHosts); $baseQueryLinks = "SELECT COUNT(externalLinkId) AS timesFollowed, recordId, linkUrl, linkHost " . "FROM external_link_tracking " . "WHERE (DATE_FORMAT(trackingDate, '%Y-%m-%d')) BETWEEN '" . $selectedDateStart . "' AND '" . $selectedDateEnd . "' "; if (count($selectedHosts) > 0) { $hosts = join("','", $selectedHosts); $baseQueryLinks .= "AND linkHost IN ('" . $hosts . "') "; } $baseQueryLinks .= "GROUP BY recordId, linkUrl "; //////////Get a count of the page view data $queryPurchasesCount = "SELECT COUNT(*) AS RowCount from ( " . $baseQueryLinks . ") As ResultCount"; $resPurchasesCount = mysql_query($queryPurchasesCount); if ($resPurchasesCount > 0) { $rowCount = mysql_fetch_object($resPurchasesCount); $totalResultCount = $rowCount->RowCount; } else { $totalResultCount = 0; } //////////Create the items per page array $itemsPerPageList = $this->getItemsPerPageList(); ///////////////////PAGING $currentPage = 1; $resultTotal = $totalResultCount; $startRecord = 1; if (isset($_GET['itemsPerPage'])) { switch ($_GET['itemsPerPage']) { case "20": $itemsPerPage = 20; $itemsPerPageList["20"]["selected"] = true; break; case "100": $itemsPerPage = 100; $itemsPerPageList["100"]["selected"] = true; break; default: $itemsPerPage = 50; $itemsPerPageList["50"]["selected"] = true; } } else { $itemsPerPage = 50; $itemsPerPageList["50"]["selected"] = true; } $endRecord = $itemsPerPage; $interface->assign('itemsPerPageList', $itemsPerPageList); if (isset($_GET['page'])) { $currentPage = $_GET['page']; // 1st record is easy, work out the start of this page $startRecord = ($currentPage - 1) * $itemsPerPage + 1; // Last record needs more care if ($resultTotal < $itemsPerPage) { // There are less records returned then one page, use total results $endRecord = $resultTotal; } else { if ($currentPage * $itemsPerPage > $resultTotal) { // The end of the current page runs past the last record, use total results $endRecord = $resultTotal; } else { // Otherwise use the last record on this page $endRecord = $currentPage * $itemsPerPage; } } } //////////Get the Page View Data with paging and sorting if (isset($_GET['reportSort'])) { $sortValue = $_GET['reportSort']; } //Create values for how to sort the table. $sortList = $this->getSortList(); if (!isset($sortValue)) { $sortValue = 'UrlASC'; } $sortList[$sortValue]["selected"] = true; $baseQueryLinks .= $sortList[$sortValue]['sql']; //append on a limit to return a result if (!isset($_REQUEST['exportToExcel'])) { $baseQueryLinks .= "LIMIT " . ($startRecord - 1) . ", " . $itemsPerPage . " "; } $resPurchases = mysql_query($baseQueryLinks); $resultsPurchases = array(); if ($resPurchases > 0) { //Build an array based on the data to dump out to the grid $i = 0; while ($r = mysql_fetch_array($resPurchases)) { $recordId = $r['recordId']; $fullId = $r['recordId']; if (preg_match('/econtentRecord(\\d+)/', $recordId, $matches)) { require_once ROOT_DIR . '/sys/eContent/EContentRecord.php'; $econtentRecord = new EContentRecord(); $econtentRecord->id = $matches[1]; $econtentRecord->find(true); $recordId = $econtentRecord->ilsId; $title = $econtentRecord->title; } else { require_once ROOT_DIR . '/RecordDrivers/MarcRecord.php'; $recordDriver = new MarcRecord($recordId); $title = $recordDriver->getTitle(); } $tmp = array('recordId' => $recordId, 'recordUrl' => '/Record/' . $fullId, 'title' => $title, 'timesFollowed' => $r['timesFollowed'], 'linkHost' => $r['linkHost'], 'linkUrl' => $r['linkUrl']); $resultsPurchases[$i++] = $tmp; } } $interface->assign('resultLinks', $resultsPurchases); //////////Paging Array $summary = array('page' => $currentPage, 'perPage' => $itemsPerPage, 'resultTotal' => $totalResultCount, 'startRecord' => $startRecord, 'endRecord' => $endRecord); $interface->assign('recordCount', $summary['resultTotal']); $interface->assign('recordStart', $summary['startRecord']); $interface->assign('recordEnd', $summary['endRecord']); // Process Paging using VuFind Pager object if (strrpos($_SERVER["REQUEST_URI"], "page=")) { //replace the page variable with a new one $link = str_replace("page=" . $currentPage, "page=%d", $_SERVER["REQUEST_URI"]); } else { if (strrpos($_SERVER["REQUEST_URI"], "?")) { $link = $_SERVER["REQUEST_URI"] . "&page=%d"; } else { $link = $_SERVER["REQUEST_URI"] . "?page=%d"; } } $options = array('totalItems' => $summary['resultTotal'], 'fileName' => $link, 'perPage' => $summary['perPage']); $pager = new VuFindPager($options); $interface->assign('pageLinks', $pager->getLinks()); ///////////////////END PAGING //////////Sorting $sortUrl = $_SERVER["REQUEST_URI"]; if (isset($sortValue)) { //Set the URL for sorting if (strrpos($_SERVER["REQUEST_URI"], "reportSort=")) { //replace the page variable with a new one $sortUrl = str_replace("sort=" . $currentPage, "reportSort=" . $sortValue, $_SERVER["REQUEST_URI"]); } else { if (strrpos($_SERVER["REQUEST_URI"], "?")) { $sortUrl = $_SERVER["REQUEST_URI"] . "&reportSort=" . $sortValue; } else { $sortUrl = $_SERVER["REQUEST_URI"] . "?reportSort=" . $sortValue; } } } $interface->assign('sortUrl', $sortUrl); $interface->assign('sortList', $sortList); //////////CHART //Create the chart and load data into the results. $queryDailyPurchases = "SELECT DATE_FORMAT(trackingDate, '%Y-%m-%d') as date, COUNT(externalLinkId) AS timesFollowed, linkHost FROM external_link_tracking " . "WHERE (DATE_FORMAT(trackingDate, '%Y-%m-%d')) BETWEEN '" . $selectedDateStart . "' AND '" . $selectedDateEnd . "' "; if (count($selectedHosts) > 0) { $hosts = join("','", $selectedHosts); $queryDailyPurchases .= "AND linkHost IN ('" . $hosts . "') "; } $queryDailyPurchases .= "GROUP BY DATE_FORMAT(trackingDate, '%Y-%m-%d'), linkHost ORDER BY trackingDate ASC"; $dailyUsage = mysql_query($queryDailyPurchases); //Initialize data by loading all of the dates that we are looking at so we can show the correct counts or each series on the right day. $check_date = $selectedDateStart; $datesInReport = array(); $linkUsageByHostByDay = array(); foreach ($allHosts as $hostName) { $linkUsageByHostByDay[$hostName] = array(); } while ($check_date != $selectedDateEnd) { $check_date = date("Y-m-d", strtotime("+1 day", strtotime($check_date))); $datesInReport[] = $check_date; //Default number of link usage for the day to 0 foreach ($allHosts as $host) { $linkUsageByHostByDay[$host][$check_date] = 0; } } //Chart section $reportData = new pData(); while ($r = mysql_fetch_array($dailyUsage)) { $linkHost = $r['linkHost']; $linkUsageByHostByDay[$linkHost][$r['date']] = $r['timesFollowed']; } foreach ($linkUsageByHostByDay as $hostName => $dailyResults) { $reportData->addPoints($dailyResults, $hostName); } $reportData->setAxisName(0, "Usage"); $reportData->addPoints($datesInReport, "Dates"); $reportData->setAbscissa("Dates"); /* Create the pChart object */ $myPicture = new pImage(700, 290, $reportData); /* Draw the background */ $Settings = array("R" => 225, "G" => 225, "B" => 225); $myPicture->drawFilledRectangle(0, 0, 700, 290, $Settings); /* Add a border to the picture */ $myPicture->drawRectangle(0, 0, 699, 289, array("R" => 0, "G" => 0, "B" => 0)); $myPicture->setFontProperties(array("FontName" => "sys/pChart/Fonts/verdana.ttf", "FontSize" => 9)); $myPicture->setGraphArea(50, 30, 670, 190); //$myPicture->drawFilledRectangle(30,30,670,150,array("R"=>255,"G"=>255,"B"=>255,"Surrounding"=>-200,"Alpha"=>10)); $myPicture->drawScale(array("DrawSubTicks" => TRUE, "LabelRotation" => 90)); $myPicture->setFontProperties(array("FontName" => "sys/pChart/Fonts/verdana.ttf", "FontSize" => 9)); $myPicture->drawLineChart(array("DisplayValues" => TRUE, "DisplayColor" => DISPLAY_AUTO)); /* Write the chart legend */ $myPicture->drawLegend(80, 20, array("Style" => LEGEND_NOBORDER, "Mode" => LEGEND_HORIZONTAL)); /* Render the picture (choose the best way) */ $time = time(); $chartHref = "/images/charts/dailyPurchases{$time}.png"; $chartPath = $configArray['Site']['local'] . $chartHref; $myPicture->render($chartPath); $interface->assign('chartPath', $chartHref); //////////EXPORT To EXCEL if (isset($_REQUEST['exportToExcel'])) { //PHPEXCEL // Create new PHPExcel object $objPHPExcel = new PHPExcel(); // Set properties $objPHPExcel->getProperties()->setTitle("External Link Usage Report")->setCategory("External Link Usage Report"); // Add some data $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', 'External Link Usage Report')->setCellValue('A3', 'Record Id')->setCellValue('B3', 'Url')->setCellValue('C3', 'Host')->setCellValue('D3', 'Usage'); $a = 4; //Loop Through The Report Data foreach ($resultsPurchases as $resultsPurchase) { $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . $a, $resultsPurchase['recordId'])->setCellValue('B' . $a, $resultsPurchase['linkUrl'])->setCellValue('C' . $a, $resultsPurchase['linkHost'])->setCellValue('D' . $a, $resultsPurchase['timesFollowed']); $a++; } $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true); $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true); $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true); // Rename sheet $objPHPExcel->getActiveSheet()->setTitle('Simple'); // Set active sheet index to the first sheet, so Excel opens this as the first sheet $objPHPExcel->setActiveSheetIndex(0); // Redirect output to a client's web browser (Excel5) header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="ExternalLinkReport.xls"'); header('Cache-Control: max-age=0'); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save('php://output'); exit; } $interface->setPageTitle('Report - External Link Tracking'); $interface->assign('sidebar', 'MyAccount/account-sidebar.tpl'); $interface->setTemplate('reportExternalLinks.tpl'); $interface->display('layout.tpl'); }
/** * Display a "cover unavailable" graphic and terminate execution. */ function getDefaultCover() { $useDefaultNoCover = true; //Get the resource for the cover so we can load the title and author $title = ''; $author = ''; if ($this->type == 'grouped_work') { $this->loadGroupedWork(); require_once ROOT_DIR . '/sys/Grouping/GroupedWork.php'; if ($this->groupedWork) { $title = ucwords($this->groupedWork->getTitle()); $author = ucwords($this->groupedWork->getPrimaryAuthor()); $this->category = 'blank'; } } elseif ($this->isEContent) { require_once ROOT_DIR . '/sys/eContent/EContentRecord.php'; $econtentRecord = new EContentRecord(); $econtentRecord->id = $this->id; if ($econtentRecord->find(true)) { $title = $econtentRecord->title; $author = $econtentRecord->author; } } else { require_once ROOT_DIR . '/RecordDrivers/MarcRecord.php'; $recordDriver = new MarcRecord($this->id); if ($recordDriver->isValid()) { $title = $recordDriver->getTitle(); $author = $recordDriver->getAuthor(); } } require_once ROOT_DIR . '/sys/DefaultCoverImageBuilder.php'; $coverBuilder = new DefaultCoverImageBuilder(); if (strlen($title) > 0 && $coverBuilder->blankCoverExists($this->format, $this->category)) { $this->log("Looking for default cover, format is {$this->format} category is {$this->category}", PEAR_LOG_DEBUG); $coverBuilder->getCover($title, $author, $this->format, $this->category, $this->cacheFile); return $this->processImageURL($this->cacheFile); } else { $themeName = $this->configArray['Site']['theme']; $noCoverUrl = "interface/themes/default/images/noCover2.png"; if (isset($this->format) && strlen($this->format) > 0) { if (is_readable("interface/themes/{$themeName}/images/{$this->format}_{$this->size}.png")) { $this->log("Found format image {$this->format}_{$this->size} .", PEAR_LOG_INFO); $noCoverUrl = "interface/themes/{$themeName}/images/{$this->format}_{$this->size}.png"; $useDefaultNoCover = false; } elseif (is_readable("interface/themes/{$themeName}/images/{$this->format}.png")) { $noCoverUrl = "interface/themes/{$themeName}/images/{$this->format}.png"; header('Content-type: image/png'); $useDefaultNoCover = false; } elseif (is_readable("interface/themes/default/images/{$this->format}_{$this->size}.png")) { $this->log("Found format image {$this->format}_{$this->size} .", PEAR_LOG_INFO); $noCoverUrl = "interface/themes/default/images/{$this->format}_{$this->size}.png"; header('Content-type: image/png'); $useDefaultNoCover = false; } elseif (is_readable("interface/themes/default/images/{$this->format}.png")) { $noCoverUrl = "interface/themes/default/images/{$this->format}.png"; header('Content-type: image/png'); $useDefaultNoCover = false; } } if ($useDefaultNoCover && isset($this->category) && strlen($this->category) > 0) { if (is_readable("interface/themes/{$themeName}/images/{$this->category}_{$this->size}.png")) { $this->log("Found category image {$this->category}_{$this->size} .", PEAR_LOG_INFO); $noCoverUrl = "interface/themes/{$themeName}/images/{$this->category}_{$this->size}.png"; $useDefaultNoCover = false; } elseif (is_readable("interface/themes/{$themeName}/images/{$this->category}.png")) { $noCoverUrl = "interface/themes/{$themeName}/images/{$this->category}.png"; header('Content-type: image/png'); $useDefaultNoCover = false; } elseif (is_readable("interface/themes/default/images/{$this->category}_{$this->size}.png")) { $this->log("Found category image {$this->category}_{$this->size} .", PEAR_LOG_INFO); $noCoverUrl = "interface/themes/default/images/{$this->category}_{$this->size}.png"; header('Content-type: image/png'); $useDefaultNoCover = false; } elseif (is_readable("interface/themes/default/images/{$this->category}.png")) { $noCoverUrl = "interface/themes/default/images/{$this->category}.png"; header('Content-type: image/png'); $useDefaultNoCover = false; } } if ($useDefaultNoCover) { header('Content-type: image/png'); } $ret = $this->processImageURL($noCoverUrl, true); //$ret = copy($nocoverurl, $this->cacheFile); if (!$ret) { $this->error = "Unable to copy file {$noCoverUrl} to {$this->cacheFile}"; return false; } else { return true; } } }
function reloadCover() { require_once ROOT_DIR . '/RecordDrivers/MarcRecord.php'; $id = $_REQUEST['id']; $recordDriver = new MarcRecord($id); //Reload small cover $smallCoverUrl = str_replace('&', '&', $recordDriver->getBookcoverUrl('small')) . '&reload'; file_get_contents($smallCoverUrl); //Reload medium cover $mediumCoverUrl = str_replace('&', '&', $recordDriver->getBookcoverUrl('medium')) . '&reload'; file_get_contents($mediumCoverUrl); //Reload large cover $largeCoverUrl = str_replace('&', '&', $recordDriver->getBookcoverUrl('large')) . '&reload'; file_get_contents($largeCoverUrl); //Also reload covers for the grouped work require_once ROOT_DIR . '/RecordDrivers/GroupedWorkDriver.php'; $groupedWorkDriver = new GroupedWorkDriver($recordDriver->getGroupedWorkId()); global $configArray; //Reload small cover $smallCoverUrl = $configArray['Site']['coverUrl'] . str_replace('&', '&', $groupedWorkDriver->getBookcoverUrl('small')) . '&reload'; file_get_contents($smallCoverUrl); //Reload medium cover $mediumCoverUrl = $configArray['Site']['coverUrl'] . str_replace('&', '&', $groupedWorkDriver->getBookcoverUrl('medium')) . '&reload'; file_get_contents($mediumCoverUrl); //Reload large cover $largeCoverUrl = $configArray['Site']['coverUrl'] . str_replace('&', '&', $groupedWorkDriver->getBookcoverUrl('large')) . '&reload'; file_get_contents($largeCoverUrl); return $this->json_utf8_encode(array('success' => true, 'message' => 'Covers have been reloaded. You may need to refresh the page to clear your local cache.')); }
/** * Dedup: Return format from predefined values * * @return string */ public function getFormat() { // Custom predefined type in 977a $field977a = $this->getFieldSubfields('977', ['a' => 1]); if ($field977a) { return $field977a; } // Dissertations and Thesis if (isset($this->fields['502'])) { return 'Dissertation'; } if (isset($this->fields['509'])) { $field509a = MetadataUtils::stripTrailingPunctuation($this->getFieldSubfields('509', ['a' => 1])); switch (strtolower($field509a)) { case 'kandidaatintyö': case 'kandidatarbete': return 'BachelorsThesis'; case 'pro gradu -työ': case 'pro gradu': return 'ProGradu'; case 'laudaturtyö': case 'laudaturavh': return 'LaudaturThesis'; case 'lisensiaatintyö': case 'lic.avh.': return 'LicentiateThesis'; case 'diplomityö': case 'diplomarbete': return 'MastersThesis'; case 'erikoistyö': case 'vicenot.ex.': return 'Thesis'; case 'lopputyö': case 'rättsnot.ex.': return 'Thesis'; case 'amk-opinnäytetyö': case 'yh-examensarbete': return 'BachelorsThesisPolytechnic'; case 'ylempi amk-opinnäytetyö': case 'högre yh-examensarbete': return 'MastersThesisPolytechnic'; } return 'Thesis'; } $format = parent::getFormat(); // Separate non-musical sound from other sound types. This is not quite // perfect since there's already e.g. MusicRecording, but we need to keep // e.g. CD intact for backwards-compatibility. if (in_array($format, ['CD', 'SoundCassette', 'SoundDisc', 'SoundRecording'])) { $leader = $this->getField('000'); $type = substr($leader, 6, 1); if ($type == 'i') { switch ($format) { case 'CD': $format = 'NonmusicalCD'; break; case 'SoundCassette': $format = 'NonmusicalCassette'; break; case 'SoundDisc': $format = 'NonmusicalDisc'; break; case 'SoundRecording': $format = 'NonmusicalRecording'; break; } } elseif ($type == 'j' && $format == 'SoundRecording') { $format = 'MusicRecording'; } } return $format; }
public function getMyTransactions($page = 1, $recordsPerPage = -1, $sortOption = 'dueDate') { global $configArray; global $user; $userId = $user->id; $checkedOutTitles = array(); //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) { echo "No session id found for user"; return $checkedOutTitles; } } //Now that we have the session token, get checkouts information $lookupMyAccountInfoResponse = $this->getWebServiceResponse($configArray['Catalog']['webServiceUrl'] . '/standard/lookupMyAccountInfo?clientID=' . $configArray['Catalog']['clientId'] . '&sessionToken=' . $sessionToken . '&includeItemsOutInfo=true'); if (isset($lookupMyAccountInfoResponse->ItemsOutInfo)) { $sCount = 0; foreach ($lookupMyAccountInfoResponse->ItemsOutInfo as $itemOut) { $sCount++; $bibId = (string) $itemOut->titleKey; $curTitle['checkoutSource'] = 'ILS'; $curTitle['recordId'] = $bibId; $curTitle['shortId'] = $bibId; $curTitle['id'] = $bibId; $curTitle['title'] = (string) $itemOut->title; $curTitle['author'] = (string) $itemOut->author; $curTitle['duedate'] = (string) $itemOut->dueDate; $curTitle['checkoutdate'] = (string) $itemOut->ckoDate; $dueTime = strtotime($curTitle['duedate']); $daysUntilDue = ceil(($dueTime - time()) / (24 * 60 * 60)); $overdue = $daysUntilDue < 0; $curTitle['overdue'] = $overdue; $curTitle['daysUntilDue'] = $daysUntilDue; $curTitle['renewCount'] = (string) $itemOut->renewals; $curTitle['canrenew'] = true; //TODO: Figure out if the user can renew the title or not $curTitle['renewIndicator'] = (string) $itemOut->itemBarcode; $curTitle['barcode'] = (string) $itemOut->itemBarcode; $curTitle['holdQueueLength'] = $this->getNumHolds($bibId); $curTitle['format'] = 'Unknown'; if ($curTitle['id'] && strlen($curTitle['id']) > 0) { require_once ROOT_DIR . '/RecordDrivers/MarcRecord.php'; $recordDriver = new MarcRecord($curTitle['id']); if ($recordDriver->isValid()) { $curTitle['coverUrl'] = $recordDriver->getBookcoverUrl('medium'); $curTitle['groupedWorkId'] = $recordDriver->getGroupedWorkId(); $formats = $recordDriver->getFormats(); $curTitle['format'] = reset($formats); } else { $curTitle['coverUrl'] = ""; } } $sortTitle = isset($curTitle['title_sort']) ? $curTitle['title_sort'] : $curTitle['title']; $sortKey = $sortTitle; if ($sortOption == 'title') { $sortKey = $sortTitle; } elseif ($sortOption == 'author') { $sortKey = (isset($curTitle['author']) ? $curTitle['author'] : "Unknown") . '-' . $sortTitle; } elseif ($sortOption == 'dueDate') { if (isset($curTitle['duedate'])) { if (preg_match('/.*?(\\d{1,2})[-\\/](\\d{1,2})[-\\/](\\d{2,4}).*/', $curTitle['duedate'], $matches)) { $sortKey = $matches[3] . '-' . $matches[1] . '-' . $matches[2] . '-' . $sortTitle; } else { $sortKey = $curTitle['duedate'] . '-' . $sortTitle; } } } elseif ($sortOption == 'format') { $sortKey = (isset($curTitle['format']) ? $curTitle['format'] : "Unknown") . '-' . $sortTitle; } elseif ($sortOption == 'renewed') { $sortKey = (isset($curTitle['renewCount']) ? $curTitle['renewCount'] : 0) . '-' . $sortTitle; } elseif ($sortOption == 'holdQueueLength') { $sortKey = (isset($curTitle['holdQueueLength']) ? $curTitle['holdQueueLength'] : 0) . '-' . $sortTitle; } $sortKey .= "_{$sCount}"; $checkedOutTitles[$sortKey] = $curTitle; } } return array('transactions' => $checkedOutTitles, 'numTransactions' => count($checkedOutTitles)); }
function _parseRecord($rec) { $r = new MarcRecord(); $this->_recnum += 1; $err = $r->setLeader(substr($rec, 0, 24), $this->lenient); if ($err) { return $this->_error("Invalid Leader: " . $err); } $base = $r->baseAddr; $entries = $this->_parseDirectory(substr($rec, 24, $base - 24)); if (is_a($entries, 'MarcParseError')) { return $entries; } foreach ($entries as $e) { $f = substr($rec, $base + $e['start'], $e['length']); $field = $this->_parseField($e['tag'], $f); if (is_a($field, 'MarcParseError')) { return $field; } array_push($r->fields, $field); } return $r; }
/** * @param $id * @return ExternalEContentDriver|MarcRecord|null|OverDriveRecordDriver|PublicEContentDriver|RestrictedEContentDriver */ static function initRecordDriverById($id) { if (isset(RecordDriverFactory::$recordDrivers[$id])) { return RecordDriverFactory::$recordDrivers[$id]; } $recordInfo = explode(':', $id); $recordType = $recordInfo[0]; $recordId = $recordInfo[1]; disableErrorHandler(); if ($recordType == 'overdrive') { require_once ROOT_DIR . '/RecordDrivers/OverDriveRecordDriver.php'; $recordDriver = new OverDriveRecordDriver($recordId); } elseif ($recordType == 'public_domain_econtent') { require_once ROOT_DIR . '/RecordDrivers/PublicEContentDriver.php'; $recordDriver = new PublicEContentDriver($recordId); } elseif ($recordType == 'external_econtent') { require_once ROOT_DIR . '/RecordDrivers/ExternalEContentDriver.php'; $recordDriver = new ExternalEContentDriver($recordId); } elseif ($recordType == 'restricted_econtent') { require_once ROOT_DIR . '/RecordDrivers/RestrictedEContentDriver.php'; $recordDriver = new RestrictedEContentDriver($recordId); } elseif ($recordType == 'hoopla') { require_once ROOT_DIR . '/RecordDrivers/HooplaDriver.php'; $recordDriver = new HooplaRecordDriver($recordId); if (!$recordDriver->isValid()) { global $logger; $logger->log("Unable to load record driver for hoopla record {$recordId}", PEAR_LOG_WARNING); $recordDriver = null; } } elseif ($recordType == 'ils') { require_once ROOT_DIR . '/RecordDrivers/MarcRecord.php'; $recordDriver = new MarcRecord($recordId); if (!$recordDriver->isValid()) { global $logger; $logger->log("Unable to load record driver for {$recordId}", PEAR_LOG_WARNING); $recordDriver = null; } } else { global $logger; $logger->log("Unknown record type " . $recordType, PEAR_LOG_ERR); $recordDriver = null; } enableErrorHandler(); RecordDriverFactory::$recordDrivers[$id] = $recordDriver; return $recordDriver; }
/** * Get an array of all the languages associated with the record. * * @return array * @access protected */ protected function getLanguages() { $codedLanguages = parent::getLanguages(); $freetextLanguages = $this->getFieldArray('546', array('a')); return array_merge($codedLanguages, $freetextLanguages); }