Example #1
0
 function launch()
 {
     global $configArray;
     global $interface;
     global $user;
     global $locationSingleton;
     if ($user) {
         $interface->assign('defaultPhone', $user->phone);
         $interface->assign('defaultEmail', $user->email);
         $locations = $locationSingleton->getPickupBranches($user, $user->homeLocationId);
     } else {
         $locations = $locationSingleton->getPickupBranches(false, -1);
     }
     $interface->assign('pickupLocations', $locations);
     //Get a list of formats to show
     $availableFormats = MaterialsRequest::getFormats();
     $interface->assign('availableFormats', $availableFormats);
     //Setup a default title based on the search term
     $interface->assign('new', true);
     if (isset($_REQUEST['lookfor']) && strlen($_REQUEST['lookfor']) > 0) {
         $request = new MaterialsRequest();
         $searchType = isset($_REQUEST['basicType']) ? $_REQUEST['basicType'] : (isset($_REQUEST['type']) ? $_REQUEST['type                                 '] : 'Keyword');
         if (strcasecmp($searchType, 'author') == 0) {
             $request->author = $_REQUEST['lookfor'];
         } else {
             $request->title = $_REQUEST['lookfor'];
         }
         $interface->assign('materialsRequest', $request);
     }
     $interface->assign('showPhoneField', $configArray['MaterialsRequest']['showPhoneField']);
     $interface->assign('showAgeField', $configArray['MaterialsRequest']['showAgeField']);
     $interface->assign('showBookTypeField', $configArray['MaterialsRequest']['showBookTypeField']);
     $interface->assign('showEbookFormatField', $configArray['MaterialsRequest']['showEbookFormatField']);
     $interface->assign('showEaudioFormatField', $configArray['MaterialsRequest']['showEaudioFormatField']);
     $interface->assign('showPlaceHoldField', $configArray['MaterialsRequest']['showPlaceHoldField']);
     $interface->assign('showIllField', $configArray['MaterialsRequest']['showIllField']);
     $interface->assign('requireAboutField', $configArray['MaterialsRequest']['requireAboutField']);
     $useWorldCat = false;
     if (isset($configArray['WorldCat']) && isset($configArray['WorldCat']['apiKey'])) {
         $useWorldCat = strlen($configArray['WorldCat']['apiKey']) > 0;
     }
     $interface->assign('useWorldCat', $useWorldCat);
     $interface->setTemplate('new.tpl');
     $interface->assign('sidebar', 'Search/home-sidebar.tpl');
     $interface->setPageTitle('Materials Request');
     $interface->display('layout.tpl');
 }
Example #2
0
 function launch()
 {
     global $configArray;
     global $interface;
     global $user;
     $showOpen = true;
     if (isset($_REQUEST['requestsToShow']) && $_REQUEST['requestsToShow'] == 'allRequests') {
         $showOpen = false;
     }
     $interface->assign('showOpen', $showOpen);
     $defaultStatus = new MaterialsRequestStatus();
     $defaultStatus->isDefault = 1;
     $defaultStatus->libraryId = Library::getPatronHomeLibrary()->libraryId;
     $defaultStatus->find(true);
     $interface->assign('defaultStatus', $defaultStatus->id);
     //Get a list of all materials requests for the user
     $allRequests = array();
     if ($user) {
         $materialsRequests = new MaterialsRequest();
         $materialsRequests->createdBy = $user->id;
         $materialsRequests->orderBy('title, dateCreated');
         $statusQuery = new MaterialsRequestStatus();
         if ($showOpen) {
             $homeLibrary = Library::getPatronHomeLibrary();
             $statusQuery->libraryId = $homeLibrary->libraryId;
             $statusQuery->isOpen = 1;
         }
         $materialsRequests->joinAdd($statusQuery);
         $materialsRequests->selectAdd();
         $materialsRequests->selectAdd('materials_request.*, description as statusLabel');
         $materialsRequests->find();
         while ($materialsRequests->fetch()) {
             $allRequests[] = clone $materialsRequests;
         }
     } else {
         header('Location: ' . $configArray['Site']['path'] . '/MyResearch/Home?followupModule=MaterialsRequest&followupAction=MyRequests');
         //$interface->assign('error', "You must be logged in to view your requests.");
     }
     $interface->assign('allRequests', $allRequests);
     $interface->assign('sidebar', 'MyAccount/account-sidebar.tpl');
     $interface->setTemplate('myMaterialRequests.tpl');
     $interface->setPageTitle('My Materials Requests');
     $interface->display('layout.tpl');
 }
Example #3
0
 function launch()
 {
     global $configArray;
     global $interface;
     global $user;
     //Load the materials request to determine if it can be edited
     $materialsRequest = new MaterialsRequest();
     $materialsRequest->id = $_REQUEST['id'];
     if (!$materialsRequest->find(true)) {
         $materialsRequest = null;
         $requestUser = false;
     } else {
         $requestUser = new User();
         $requestUser->id = $materialsRequest->createdBy;
         if ($requestUser->find(true)) {
             $interface->assign('requestUser', $requestUser);
         } else {
             $requestUser = false;
         }
     }
     //Make sure that the user is valid
     $processForm = true;
     if ($materialsRequest == null) {
         $interface->assign('success', false);
         $interface->assign('error', 'Sorry, we could not find a request with that id.');
         $processForm = false;
     } else {
         if (!$user) {
             $interface->assign('error', 'Sorry, you must be logged in to update a materials request.');
             $processForm = false;
         } else {
             if ($user->hasRole('cataloging')) {
                 //Ok to process the form even if it wasn't created by the current user
             } else {
                 if ($user->hasRole('library_material_requests') && $requestUser && Library::getLibraryForLocation($requestUser->homeLocationId)->libraryId == Library::getLibraryForLocation($user->homeLocationId)->libraryId) {
                     //Ok to process because they are an admin for the user's home library
                 } else {
                     if ($user->id != $materialsRequest->createdBy) {
                         $interface->assign('error', 'Sorry, you do not have permission to update this materials request.');
                         $processForm = false;
                     }
                 }
             }
         }
     }
     if ($processForm) {
         //Materials request can be submitted.
         $materialsRequest->title = strip_tags($_REQUEST['title']);
         $materialsRequest->season = isset($_REQUEST['season']) ? strip_tags($_REQUEST['season']) : '';
         $materialsRequest->magazineTitle = isset($_REQUEST['magazineTitle']) ? strip_tags($_REQUEST['magazineTitle']) : '';
         $materialsRequest->magazineDate = isset($_REQUEST['magazineDate']) ? strip_tags($_REQUEST['magazineDate']) : '';
         $materialsRequest->magazineVolume = isset($_REQUEST['magazineVolume']) ? strip_tags($_REQUEST['magazineVolume']) : '';
         $materialsRequest->magazineNumber = isset($_REQUEST['magazineNumber']) ? strip_tags($_REQUEST['magazineNumber']) : '';
         $materialsRequest->magazinePageNumbers = isset($_REQUEST['magazinePageNumbers']) ? strip_tags($_REQUEST['magazinePageNumbers']) : '';
         $materialsRequest->author = strip_tags($_REQUEST['author']);
         $materialsRequest->format = strip_tags($_REQUEST['format']);
         $materialsRequest->subFormat = isset($_REQUEST['subFormat']) ? strip_tags($_REQUEST['subFormat']) : '';
         $materialsRequest->ageLevel = strip_tags($_REQUEST['ageLevel']);
         $materialsRequest->bookType = isset($_REQUEST['bookType']) ? strip_tags($_REQUEST['bookType']) : '';
         $materialsRequest->isbn = isset($_REQUEST['isbn']) ? strip_tags($_REQUEST['isbn']) : '';
         $materialsRequest->upc = isset($_REQUEST['upc']) ? strip_tags($_REQUEST['upc']) : '';
         $materialsRequest->issn = isset($_REQUEST['issn']) ? strip_tags($_REQUEST['issn']) : '';
         $materialsRequest->oclcNumber = isset($_REQUEST['oclcNumber']) ? strip_tags($_REQUEST['oclcNumber']) : '';
         $materialsRequest->publisher = strip_tags($_REQUEST['publisher']);
         $materialsRequest->publicationYear = strip_tags($_REQUEST['publicationYear']);
         if (isset($_REQUEST['abridged'])) {
             if ($_REQUEST['abridged'] == 'abridged') {
                 $materialsRequest->abridged = 1;
             } elseif ($_REQUEST['abridged'] == 'unabridged') {
                 $materialsRequest->abridged = 0;
             } else {
                 $materialsRequest->abridged = 2;
                 //Not applicable
             }
         }
         $materialsRequest->comments = strip_tags($_REQUEST['comments']);
         $materialsRequest->dateUpdated = time();
         if ($materialsRequest->update()) {
             $interface->assign('success', true);
             $interface->assign('materialsRequest', $materialsRequest);
         } else {
             $interface->assign('success', false);
             $interface->assign('error', 'There was an error updating the materials request.');
         }
     } else {
         $interface->assign('success', false);
         $interface->assign('error', 'Sorry, we could not find a request with that id.');
     }
     //Get a list of formats to show
     $availableFormats = MaterialsRequest::getFormats();
     $interface->assign('availableFormats', $availableFormats);
     $interface->assign('showPhoneField', $configArray['MaterialsRequest']['showPhoneField']);
     $interface->assign('showAgeField', $configArray['MaterialsRequest']['showAgeField']);
     $interface->assign('showBookTypeField', $configArray['MaterialsRequest']['showBookTypeField']);
     $interface->assign('showEbookFormatField', $configArray['MaterialsRequest']['showEbookFormatField']);
     $interface->assign('showEaudioFormatField', $configArray['MaterialsRequest']['showEaudioFormatField']);
     $interface->assign('showPlaceHoldField', $configArray['MaterialsRequest']['showPlaceHoldField']);
     $interface->assign('showIllField', $configArray['MaterialsRequest']['showIllField']);
     $interface->setTemplate('update-result.tpl');
     $interface->setPageTitle('Update Result');
     $interface->display('layout.tpl');
 }
 function launch()
 {
     global $configArray;
     global $interface;
     global $user;
     //Load status information
     $materialsRequestStatus = new MaterialsRequestStatus();
     $materialsRequestStatus->orderBy('isDefault DESC, isOpen DESC, description ASC');
     if ($user->hasRole('library_material_requests')) {
         $homeLibrary = Library::getPatronHomeLibrary();
         $materialsRequestStatus->libraryId = $homeLibrary->libraryId;
     } else {
         $libraryList[-1] = 'Default';
     }
     $materialsRequestStatus->find();
     $allStatuses = array();
     $availableStatuses = array();
     $defaultStatusesToShow = array();
     while ($materialsRequestStatus->fetch()) {
         $availableStatuses[$materialsRequestStatus->id] = $materialsRequestStatus->description;
         $allStatuses[$materialsRequestStatus->id] = clone $materialsRequestStatus;
         if ($materialsRequestStatus->isOpen == 1 || $materialsRequestStatus->isDefault == 1) {
             $defaultStatusesToShow[] = $materialsRequestStatus->id;
         }
     }
     $interface->assign('availableStatuses', $availableStatuses);
     if (isset($_REQUEST['statusFilter'])) {
         $statusesToShow = $_REQUEST['statusFilter'];
         $_SESSION['materialsRequestStatusFilter'] = $statusesToShow;
     } elseif (isset($_SESSION['materialsRequestStatusFilter'])) {
         $statusesToShow = $_SESSION['materialsRequestStatusFilter'];
     } else {
         $statusesToShow = $defaultStatusesToShow;
     }
     $interface->assign('statusFilter', $statusesToShow);
     //Process status change if needed
     if (isset($_REQUEST['updateStatus']) && isset($_REQUEST['select'])) {
         //Look for which titles should be modified
         $selectedRequests = $_REQUEST['select'];
         $statusToSet = $_REQUEST['newStatus'];
         require_once ROOT_DIR . '/sys/Mailer.php';
         $mail = new VuFindMailer();
         foreach ($selectedRequests as $requestId => $selected) {
             $materialRequest = new MaterialsRequest();
             $materialRequest->id = $requestId;
             if ($materialRequest->find(true)) {
                 $materialRequest->status = $statusToSet;
                 $materialRequest->dateUpdated = time();
                 $materialRequest->update();
                 if ($allStatuses[$statusToSet]->sendEmailToPatron == 1 && $materialRequest->email) {
                     $body = '*****This is an auto-generated email response. Please do not reply.*****';
                     $body .= "\r\n" . $allStatuses[$statusToSet]->emailTemplate;
                     //Replace tags with appropriate values
                     $materialsRequestUser = new User();
                     $materialsRequestUser->id = $materialRequest->createdBy;
                     $materialsRequestUser->find(true);
                     foreach ($materialsRequestUser as $fieldName => $fieldValue) {
                         if (!is_array($fieldValue)) {
                             $body = str_replace('{' . $fieldName . '}', $fieldValue, $body);
                         }
                     }
                     foreach ($materialRequest as $fieldName => $fieldValue) {
                         if (!is_array($fieldValue)) {
                             $body = str_replace('{' . $fieldName . '}', $fieldValue, $body);
                         }
                     }
                     $materialsRequestUser->find(true);
                     $mail->send($materialRequest->email, $configArray['Site']['email'], "Your Materials Request Update", $body, $configArray['Site']['email']);
                 }
             }
         }
     }
     $availableFormats = MaterialsRequest::getFormats();
     $interface->assign('availableFormats', $availableFormats);
     $defaultFormatsToShow = array_keys($availableFormats);
     if (isset($_REQUEST['formatFilter'])) {
         $formatsToShow = $_REQUEST['formatFilter'];
         $_SESSION['materialsRequestFormatFilter'] = $formatsToShow;
     } elseif (isset($_SESSION['materialsRequestFormatFilter'])) {
         $formatsToShow = $_SESSION['materialsRequestFormatFilter'];
     } else {
         $formatsToShow = $defaultFormatsToShow;
     }
     $interface->assign('formatFilter', $formatsToShow);
     //Get a list of all materials requests for the user
     $allRequests = array();
     if ($user) {
         $materialsRequests = new MaterialsRequest();
         $materialsRequests->joinAdd(new Location(), "LEFT");
         $materialsRequests->joinAdd(new MaterialsRequestStatus());
         $materialsRequests->joinAdd(new User(), 'INNER', 'user');
         $materialsRequests->selectAdd();
         $materialsRequests->selectAdd('materials_request.*, description as statusLabel, location.displayName as location, firstname, lastname, ' . $configArray['Catalog']['barcodeProperty'] . ' as barcode');
         if ($user->hasRole('library_material_requests')) {
             //Need to limit to only requests submitted for the user's home location
             $userHomeLibrary = Library::getPatronHomeLibrary();
             $locations = new Location();
             $locations->libraryId = $userHomeLibrary->libraryId;
             $locations->find();
             $locationsForLibrary = array();
             while ($locations->fetch()) {
                 $locationsForLibrary[] = $locations->locationId;
             }
             $materialsRequests->whereAdd('user.homeLocationId IN (' . implode(', ', $locationsForLibrary) . ')');
         }
         if (count($availableStatuses) > count($statusesToShow)) {
             $statusSql = "";
             foreach ($statusesToShow as $status) {
                 if (strlen($statusSql) > 0) {
                     $statusSql .= ",";
                 }
                 $statusSql .= "'" . $materialsRequests->escape($status) . "'";
             }
             $materialsRequests->whereAdd("status in ({$statusSql})");
         }
         if (count($availableFormats) > count($formatsToShow)) {
             //At least one format is disabled
             $formatSql = "";
             foreach ($formatsToShow as $format) {
                 if (strlen($formatSql) > 0) {
                     $formatSql .= ",";
                 }
                 $formatSql .= "'" . $materialsRequests->escape($format) . "'";
             }
             $materialsRequests->whereAdd("format in ({$formatSql})");
         }
         //Add filtering by date as needed
         if (isset($_REQUEST['startDate']) && strlen($_REQUEST['startDate']) > 0) {
             $startDate = strtotime($_REQUEST['startDate']);
             $materialsRequests->whereAdd("dateCreated >= {$startDate}");
             $interface->assign('startDate', $_REQUEST['startDate']);
         }
         if (isset($_REQUEST['endDate']) && strlen($_REQUEST['endDate']) > 0) {
             $endDate = strtotime($_REQUEST['endDate']);
             $materialsRequests->whereAdd("dateCreated <= {$endDate}");
             $interface->assign('endDate', $_REQUEST['endDate']);
         }
         $materialsRequests->find();
         while ($materialsRequests->fetch()) {
             $allRequests[] = clone $materialsRequests;
         }
     } else {
         $interface->assign('error', "You must be logged in to manage requests.");
     }
     $interface->assign('allRequests', $allRequests);
     if (isset($_REQUEST['exportSelected'])) {
         $this->exportToExcel($_REQUEST['select'], $allRequests);
     } else {
         $interface->setTemplate('manageRequests.tpl');
         $interface->setPageTitle('Manage Materials Requests');
         $interface->display('layout.tpl');
     }
 }
Example #5
0
 /**
  * @param User $patron
  * @param bool $forceReload
  * @return array
  */
 public function getMyProfile($patron, $forceReload = false)
 {
     //Update to not use SIP, just screen scrape for performance (sigh)
     global $timer;
     /** @var Memcache $memCache */
     global $memCache;
     if (!is_object($patron)) {
         $tmpPatron = new User();
         $tmpPatron->username = $patron['username'];
         $tmpPatron->cat_username = $patron['cat_username'];
         $tmpPatron->cat_password = $patron['cat_password'];
         $tmpPatron->firstname = $patron['firstname'];
         $tmpPatron->lastname = $patron['lastname'];
         $tmpPatron->email = $patron['email'];
         $tmpPatron->patronType = $patron['patronType'];
         $patron = $tmpPatron;
     }
     if (!$forceReload && !isset($_REQUEST['reload'])) {
         // Check the Object for profile
         if (array_key_exists($patron->username, $this->patronProfiles)) {
             $timer->logTime('Retrieved Cached Profile for Patron');
             return $this->patronProfiles[$patron->username];
         }
     }
     // Determine memcache key
     global $serverName;
     $memCacheProfileKey = "patronProfile_{$serverName}_";
     if (is_object($patron) && !isset($tmpPatron)) {
         // exclude the new patron object $tmpPatron created above. It won't have an id or be stored in memcache
         //				$patron         = get_object_vars($patron);
         //			$memCacheProfileKey = $patron['username'];
         // $patron needs to remain an object for initial loading below
         $memCacheProfileKey .= $patron->username;
     } else {
         global $user;
         //				$memCacheProfileKey = $user->id;
         $memCacheProfileKey .= $user->username;
     }
     // Check MemCache for profile
     if (!$forceReload && !isset($_REQUEST['reload'])) {
         $patronProfile = $memCache->get($memCacheProfileKey);
         if ($patronProfile) {
             //echo("Using cached profile for patron " . $userId);
             $timer->logTime('Retrieved Cached Profile for Patron');
             return $patronProfile;
         }
     }
     $this->initDatabaseConnection();
     $this->getUserInfoStmt->bind_param('ss', $patron->cat_username, $patron->cat_username);
     if ($this->getUserInfoStmt->execute()) {
         if ($userFromDbResultSet = $this->getUserInfoStmt->get_result()) {
             $userFromDb = $userFromDbResultSet->fetch_assoc();
             $userFromDbResultSet->close();
             //				$city = $userFromDb['city'];
             //				$state = "";
             //				$commaPos = strpos($city, ',');
             //				if ($commaPos !== false){ // fix this
             //					$cityState = $city;
             //					$city = substr($cityState, 0, $commaPos);
             //					$state = substr($cityState, $commaPos);
             //				}
             $city = strtok($userFromDb['city'], ',');
             $state = strtok(',');
             $city = trim($city);
             $state = trim($state);
             //Get fines
             //Load fines from database
             $outstandingFines = $this->getOutstandingFineTotal();
             //Get number of items checked out
             $checkedOutItemsRS = mysqli_query($this->dbConnection, 'SELECT count(*) as numCheckouts FROM issues WHERE borrowernumber = ' . $patron->username);
             $numCheckouts = 0;
             if ($checkedOutItemsRS) {
                 $checkedOutItems = $checkedOutItemsRS->fetch_assoc();
                 $numCheckouts = $checkedOutItems['numCheckouts'];
                 $checkedOutItemsRS->close();
             }
             //Get number of available holds
             $availableHoldsRS = mysqli_query($this->dbConnection, 'SELECT count(*) as numHolds FROM reserves WHERE waitingdate is not null and borrowernumber = ' . $patron->username);
             $numAvailableHolds = 0;
             if ($availableHoldsRS) {
                 $availableHolds = $availableHoldsRS->fetch_assoc();
                 $numAvailableHolds = $availableHolds['numHolds'];
                 $availableHoldsRS->close();
             }
             //Get number of unavailable
             $waitingHoldsRS = mysqli_query($this->dbConnection, 'SELECT count(*) as numHolds FROM reserves WHERE waitingdate is null and borrowernumber = ' . $patron->username);
             $numWaitingHolds = 0;
             if ($waitingHoldsRS) {
                 $waitingHolds = $waitingHoldsRS->fetch_assoc();
                 $numWaitingHolds = $waitingHolds['numHolds'];
                 $waitingHoldsRS->close();
             }
             $homeBranchCode = $userFromDb['branchcode'];
             $location = new Location();
             $location->code = $homeBranchCode;
             $location->find(1);
             if ($location->N == 0) {
                 unset($location);
             }
             global $user;
             $profile = array('lastname' => $patron->lastname, 'firstname' => $patron->firstname, 'displayName' => isset($patron->displayName) ? $patron->displayName : '', 'fullname' => $user->lastname . ', ' . $user->firstname, 'address1' => trim($userFromDb['streetnumber'] . ' ' . $userFromDb['address'] . ' ' . $userFromDb['address2']), 'city' => $city, 'state' => $state, 'zip' => $userFromDb['zipcode'], 'phone' => $userFromDb['phone'], 'email' => $userFromDb['email'], 'homeLocationId' => isset($location) ? $location->locationId : -1, 'homeLocationName' => '', 'expires' => $userFromDb['dateexpiry'], 'fines' => sprintf('$%0.2f', $outstandingFines), 'finesval' => floatval($outstandingFines), 'numHolds' => $numWaitingHolds + $numAvailableHolds, 'numHoldsAvailable' => $numAvailableHolds, 'numHoldsRequested' => $numWaitingHolds, 'numCheckedOut' => $numCheckouts, 'bypassAutoLogout' => $user ? $user->bypassAutoLogout : false);
             $profile['noticePreferenceLabel'] = 'Unknown';
             //Get eContent info as well
             require_once ROOT_DIR . '/Drivers/EContentDriver.php';
             $eContentDriver = new EContentDriver();
             $eContentAccountSummary = $eContentDriver->getAccountSummary();
             $profile = array_merge($profile, $eContentAccountSummary);
             require_once ROOT_DIR . '/Drivers/OverDriveDriverFactory.php';
             $overDriveDriver = OverDriveDriverFactory::getDriver();
             if ($overDriveDriver->isUserValidForOverDrive($user)) {
                 $overDriveSummary = $overDriveDriver->getOverDriveSummary($user);
                 $profile['numOverDriveCheckedOut'] = $overDriveSummary['numCheckedOut'];
                 $profile['numOverDriveHoldsAvailable'] = $overDriveSummary['numAvailableHolds'];
                 $profile['numOverDriveHoldsRequested'] = $overDriveSummary['numUnavailableHolds'];
                 $profile['canUseOverDrive'] = true;
             } else {
                 $profile['numOverDriveCheckedOut'] = 0;
                 $profile['numOverDriveHoldsAvailable'] = 0;
                 $profile['numOverDriveHoldsRequested'] = 0;
                 $profile['canUseOverDrive'] = false;
             }
             $profile['numCheckedOutTotal'] = $profile['numCheckedOut'] + $profile['numOverDriveCheckedOut'] + $eContentAccountSummary['numEContentCheckedOut'];
             $profile['numHoldsAvailableTotal'] = $profile['numHoldsAvailable'] + $profile['numOverDriveHoldsAvailable'] + $eContentAccountSummary['numEContentAvailableHolds'];
             $profile['numHoldsRequestedTotal'] = $profile['numHoldsRequested'] + $profile['numOverDriveHoldsRequested'] + $eContentAccountSummary['numEContentUnavailableHolds'];
             $profile['numHoldsTotal'] = $profile['numHoldsAvailableTotal'] + $profile['numHoldsRequestedTotal'];
             //Get a count of the materials requests for the user
             if ($user) {
                 $homeLibrary = Library::getPatronHomeLibrary();
                 if ($homeLibrary) {
                     $materialsRequest = new MaterialsRequest();
                     $materialsRequest->createdBy = $user->id;
                     $statusQuery = new MaterialsRequestStatus();
                     $statusQuery->isOpen = 1;
                     $statusQuery->libraryId = $homeLibrary->libraryId;
                     $materialsRequest->joinAdd($statusQuery);
                     $materialsRequest->find();
                     $profile['numMaterialsRequests'] = $materialsRequest->N;
                 } else {
                     $profile['numMaterialsRequests'] = 0;
                 }
                 if ($user->homeLocationId == 0 && isset($location)) {
                     $user->homeLocationId = $location->locationId;
                     if ($location->nearbyLocation1 > 0) {
                         $user->myLocation1Id = $location->nearbyLocation1;
                     } else {
                         $user->myLocation1Id = $location->locationId;
                     }
                     if ($location->nearbyLocation2 > 0) {
                         $user->myLocation2Id = $location->nearbyLocation2;
                     } else {
                         $user->myLocation2Id = $location->locationId;
                     }
                     if ($user instanceof User) {
                         //Update the database
                         $user->update();
                         //Update the serialized instance stored in the session
                         $_SESSION['userinfo'] = serialize($user);
                     }
                 } else {
                     if (isset($location) && $location->locationId != $user->homeLocationId) {
                         $user->homeLocationId = $location->locationId;
                         //Update the database
                         $user->update();
                         //Update the serialized instance stored in the session
                         $_SESSION['userinfo'] = serialize($user);
                     }
                 }
             }
         } else {
             $profile = PEAR_Singleton::raiseError('patron_info_error_technical - could not load from database');
         }
     } else {
         $profile = PEAR_Singleton::raiseError('patron_info_error_technical - could not execute user info statement');
     }
     $this->patronProfiles[$patron->username] = $profile;
     $timer->logTime('Retrieved Profile for Patron from Database');
     global $configArray, $serverName;
     $memCache->set($memCacheProfileKey, $profile, 0, $configArray['Caching']['patron_profile']);
     // Looks like all drivers but aspencat use id rather than username.
     // plb 4-16-2014
     return $profile;
 }
Example #6
0
 function launch()
 {
     global $interface;
     global $user;
     $period = isset($_REQUEST['period']) ? $_REQUEST['period'] : 'week';
     if ($period == 'week') {
         $periodLength = new DateInterval("P1W");
     } elseif ($period == 'day') {
         $periodLength = new DateInterval("P1D");
     } elseif ($period == 'month') {
         $periodLength = new DateInterval("P1M");
     } else {
         //year
         $periodLength = new DateInterval("P1Y");
     }
     $interface->assign('period', $period);
     $endDate = isset($_REQUEST['endDate']) && strlen($_REQUEST['endDate']) > 0 ? DateTime::createFromFormat('m/d/Y', $_REQUEST['endDate']) : new DateTime();
     $interface->assign('endDate', $endDate->format('m/d/Y'));
     if (isset($_REQUEST['startDate']) && strlen($_REQUEST['startDate']) > 0) {
         $startDate = DateTime::createFromFormat('m/d/Y', $_REQUEST['startDate']);
     } else {
         if ($period == 'day') {
             $startDate = new DateTime($endDate->format('m/d/Y') . " - 7 days");
         } elseif ($period == 'week') {
             //Get the sunday after this
             $endDate->setISODate($endDate->format('Y'), $endDate->format("W"), 0);
             $endDate->modify("+7 days");
             $startDate = new DateTime($endDate->format('m/d/Y') . " - 28 days");
         } elseif ($period == 'month') {
             $endDate->modify("+1 month");
             $numDays = $endDate->format("d");
             $endDate->modify(" -{$numDays} days");
             $startDate = new DateTime($endDate->format('m/d/Y') . " - 6 months");
         } else {
             //year
             $endDate->modify("+1 year");
             $numDays = $endDate->format("m");
             $endDate->modify(" -{$numDays} months");
             $numDays = $endDate->format("d");
             $endDate->modify(" -{$numDays} days");
             $startDate = new DateTime($endDate->format('m/d/Y') . " - 2 years");
         }
     }
     $interface->assign('startDate', $startDate->format('m/d/Y'));
     //Set the end date to the end of the day
     $endDate->setTime(24, 0, 0);
     $startDate->setTime(0, 0, 0);
     //Create the periods that are being represented
     $periods = array();
     $periodEnd = clone $endDate;
     while ($periodEnd >= $startDate) {
         array_unshift($periods, clone $periodEnd);
         $periodEnd->sub($periodLength);
     }
     //print_r($periods);
     //Load data for each period
     //this will be a two dimensional array
     //         Period 1, Period 2, Period 3
     //Status 1
     //Status 2
     //Status 3
     $periodData = array();
     for ($i = 0; $i < count($periods) - 1; $i++) {
         /** @var DateTime $periodStart */
         $periodStart = clone $periods[$i];
         /** @var DateTime $periodEnd */
         $periodEnd = clone $periods[$i + 1];
         $periodData[$periodStart->getTimestamp()] = array();
         //Determine how many requests were created
         $materialsRequest = new MaterialsRequest();
         $materialsRequest->joinAdd(new User(), 'INNER', 'user');
         $materialsRequest->selectAdd();
         $materialsRequest->selectAdd('COUNT(id) as numRequests');
         $materialsRequest->whereAdd('dateCreated >= ' . $periodStart->getTimestamp() . ' AND dateCreated < ' . $periodEnd->getTimestamp());
         if ($user->hasRole('library_material_requests')) {
             //Need to limit to only requests submitted for the user's home location
             $userHomeLibrary = Library::getPatronHomeLibrary();
             $locations = new Location();
             $locations->libraryId = $userHomeLibrary->libraryId;
             $locations->find();
             $locationsForLibrary = array();
             while ($locations->fetch()) {
                 $locationsForLibrary[] = $locations->locationId;
             }
             $materialsRequest->whereAdd('user.homeLocationId IN (' . implode(', ', $locationsForLibrary) . ')');
         }
         $materialsRequest->find();
         while ($materialsRequest->fetch()) {
             $periodData[$periodStart->getTimestamp()]['Created'] = $materialsRequest->numRequests;
         }
         //Get a list of all requests by the status of the request
         $materialsRequest = new MaterialsRequest();
         $materialsRequest->joinAdd(new MaterialsRequestStatus());
         $materialsRequest->joinAdd(new User(), 'INNER', 'user');
         $materialsRequest->selectAdd();
         $materialsRequest->selectAdd('COUNT(materials_request.id) as numRequests,description');
         $materialsRequest->whereAdd('dateUpdated >= ' . $periodStart->getTimestamp() . ' AND dateUpdated < ' . $periodEnd->getTimestamp());
         if ($user->hasRole('library_material_requests')) {
             //Need to limit to only requests submitted for the user's home location
             $userHomeLibrary = Library::getPatronHomeLibrary();
             $locations = new Location();
             $locations->libraryId = $userHomeLibrary->libraryId;
             $locations->find();
             $locationsForLibrary = array();
             while ($locations->fetch()) {
                 $locationsForLibrary[] = $locations->locationId;
             }
             $materialsRequest->whereAdd('user.homeLocationId IN (' . implode(', ', $locationsForLibrary) . ')');
         }
         $materialsRequest->groupBy('status');
         $materialsRequest->orderBy('status');
         $materialsRequest->find();
         while ($materialsRequest->fetch()) {
             $periodData[$periodStart->getTimestamp()][$materialsRequest->description] = $materialsRequest->numRequests;
         }
     }
     $interface->assign('periodData', $periodData, $periods);
     //Get a list of all of the statuses that will be shown
     $statuses = array();
     foreach ($periodData as $periodInfo) {
         foreach ($periodInfo as $status => $numRequests) {
             $statuses[$status] = translate($status);
         }
     }
     $interface->assign('statuses', $statuses);
     //Check to see if we are exporting to Excel
     if (isset($_REQUEST['exportToExcel'])) {
         $this->exportToExcel($periodData, $statuses);
     } else {
         //Generate the graph
         $this->generateGraph($periodData, $statuses);
     }
     $interface->setTemplate('summaryReport.tpl');
     $interface->assign('sidebar', 'MyAccount/account-sidebar.tpl');
     $interface->setPageTitle('Materials Request Summary Report');
     $interface->display('layout.tpl');
 }
Example #7
0
 function launch()
 {
     global $configArray;
     global $interface;
     global $user;
     //Make sure that the user is valid
     $processForm = true;
     if (!$user) {
         $user = UserAccount::login();
         if ($user == null) {
             $interface->assign('error', 'Sorry, we could not log you in.  Please enter a valid barcode and pin number submit a materials request.');
             $processForm = false;
         }
     }
     if ($processForm) {
         //Check to see if the user type is ok to submit a request
         $enableMaterialsRequest = true;
         if (isset($configArray['MaterialsRequest']['allowablePatronTypes'])) {
             //Check to see if we need to do additonal restrictions by patron type
             $allowablePatronTypes = $configArray['MaterialsRequest']['allowablePatronTypes'];
             if (strlen($allowablePatronTypes) > 0 && $user) {
                 if (!preg_match("/^{$allowablePatronTypes}\$/i", $user->patronType)) {
                     $enableMaterialsRequest = false;
                 }
             }
         }
         if (!$enableMaterialsRequest) {
             $interface->assign('success', false);
             $interface->assign('error', 'Sorry, only residents may submit materials requests at this time.');
         } else {
             if ($_REQUEST['format'] == 'article' && $_REQUEST['acceptCopyright'] != 1) {
                 $interface->assign('success', false);
                 $interface->assign('error', 'Sorry, you must accept the copyright agreement before submitting a materials request.');
             } else {
                 //Check to see how many active materials request results the user has already.
                 $materialsRequest = new MaterialsRequest();
                 $materialsRequest->createdBy = $user->id;
                 $statusQuery = new MaterialsRequestStatus();
                 $homeLibrary = Library::getPatronHomeLibrary();
                 $statusQuery->libraryId = $homeLibrary->libraryId;
                 $statusQuery->isOpen = 1;
                 $materialsRequest->joinAdd($statusQuery);
                 $materialsRequest->selectAdd();
                 $materialsRequest->selectAdd('materials_request.*, description as statusLabel');
                 $materialsRequest->find();
                 if ($materialsRequest->N >= 5) {
                     $interface->assign('success', false);
                     $interface->assign('error', "You\\'ve already reached your maximum limit of five requests open at one time. Once we've processed your existing requests, you'll be able to submit again. To check the status of your current requests, visit your account page [link to account page].");
                 } else {
                     //Materials request can be submitted.
                     $materialsRequest = new MaterialsRequest();
                     $materialsRequest->phone = isset($_REQUEST['phone']) ? strip_tags($_REQUEST['phone']) : '';
                     $materialsRequest->email = strip_tags($_REQUEST['email']);
                     $materialsRequest->title = strip_tags($_REQUEST['title']);
                     $materialsRequest->season = isset($_REQUEST['season']) ? strip_tags($_REQUEST['season']) : '';
                     $materialsRequest->magazineTitle = isset($_REQUEST['magazineTitle']) ? strip_tags($_REQUEST['magazineTitle']) : '';
                     $materialsRequest->magazineDate = isset($_REQUEST['magazineDate']) ? strip_tags($_REQUEST['magazineDate']) : '';
                     $materialsRequest->magazineVolume = isset($_REQUEST['magazineVolume']) ? strip_tags($_REQUEST['magazineVolume']) : '';
                     $materialsRequest->magazineNumber = isset($_REQUEST['magazineNumber']) ? strip_tags($_REQUEST['magazineNumber']) : '';
                     $materialsRequest->magazinePageNumbers = isset($_REQUEST['magazinePageNumbers']) ? strip_tags($_REQUEST['magazinePageNumbers']) : '';
                     $materialsRequest->author = strip_tags($_REQUEST['author']);
                     $materialsRequest->format = strip_tags($_REQUEST['format']);
                     if ($materialsRequest->format == 'ebook' && isset($_REQUEST['ebookFormat'])) {
                         $materialsRequest->subFormat = strip_tags($_REQUEST['ebookFormat']);
                     } elseif ($materialsRequest->format == 'eaudio' && isset($_REQUEST['eaudioFormat'])) {
                         $materialsRequest->subFormat = strip_tags($_REQUEST['eaudioFormat']);
                     }
                     $materialsRequest->subFormat = isset($_REQUEST['subFormat']) ? strip_tags($_REQUEST['subFormat']) : '';
                     $materialsRequest->ageLevel = isset($_REQUEST['ageLevel']) ? strip_tags($_REQUEST['ageLevel']) : '';
                     $materialsRequest->bookType = isset($_REQUEST['bookType']) ? strip_tags($_REQUEST['bookType']) : '';
                     $materialsRequest->isbn = isset($_REQUEST['isbn']) ? strip_tags($_REQUEST['isbn']) : '';
                     $materialsRequest->upc = isset($_REQUEST['upc']) ? strip_tags($_REQUEST['upc']) : '';
                     $materialsRequest->issn = isset($_REQUEST['issn']) ? strip_tags($_REQUEST['issn']) : '';
                     $materialsRequest->oclcNumber = isset($_REQUEST['oclcNumber']) ? strip_tags($_REQUEST['oclcNumber']) : '';
                     $materialsRequest->publisher = strip_tags($_REQUEST['publisher']);
                     $materialsRequest->publicationYear = strip_tags($_REQUEST['publicationYear']);
                     if (isset($_REQUEST['abridged'])) {
                         if ($_REQUEST['abridged'] == 'abridged') {
                             $materialsRequest->abridged = 1;
                         } elseif ($_REQUEST['abridged'] == 'unabridged') {
                             $materialsRequest->abridged = 0;
                         } else {
                             $materialsRequest->abridged = 2;
                             //Not applicable
                         }
                     }
                     $materialsRequest->about = strip_tags($_REQUEST['about']);
                     $materialsRequest->comments = strip_tags($_REQUEST['comments']);
                     if (isset($_REQUEST['placeHoldWhenAvailable'])) {
                         $materialsRequest->placeHoldWhenAvailable = $_REQUEST['placeHoldWhenAvailable'];
                     } else {
                         $materialsRequest->placeHoldWhenAvailable = 0;
                     }
                     if (isset($_REQUEST['holdPickupLocation'])) {
                         $materialsRequest->holdPickupLocation = $_REQUEST['holdPickupLocation'];
                     }
                     if (isset($_REQUEST['bookmobileStop'])) {
                         $materialsRequest->bookmobileStop = $_REQUEST['bookmobileStop'];
                     }
                     if (isset($_REQUEST['illItem'])) {
                         $materialsRequest->illItem = $_REQUEST['illItem'];
                     } else {
                         $materialsRequest->illItem = 0;
                     }
                     $defaultStatus = new MaterialsRequestStatus();
                     $defaultStatus->isDefault = 1;
                     $userLibraryId = Library::getPatronHomeLibrary();
                     $defaultStatus->libraryId = $userLibraryId->libraryId;
                     if (!$defaultStatus->find(true)) {
                         $interface->assign('success', false);
                         $interface->assign('error', 'There was an error submitting your materials request, could not determine the default status.');
                     } else {
                         $materialsRequest->status = $defaultStatus->id;
                         $materialsRequest->dateCreated = time();
                         $materialsRequest->createdBy = $user->id;
                         $materialsRequest->dateUpdated = time();
                         if ($materialsRequest->insert()) {
                             $interface->assign('success', true);
                             $interface->assign('materialsRequest', $materialsRequest);
                         } else {
                             $interface->assign('success', false);
                             $interface->assign('error', 'There was an error submitting your materials request.');
                         }
                     }
                 }
             }
         }
     }
     $interface->setTemplate('submission-result.tpl');
     $interface->setPageTitle('Submission Result');
     $interface->display('layout.tpl');
 }
Example #8
0
 function launch()
 {
     global $interface;
     global $configArray;
     global $timer;
     global $analytics;
     /** @var string|LibrarySearchSource|LocationSearchSource $searchSource */
     $searchSource = isset($_REQUEST['searchSource']) ? $_REQUEST['searchSource'] : 'local';
     if (preg_match('/library\\d+/', $searchSource)) {
         $trimmedId = str_replace('library', '', $searchSource);
         $searchSourceObj = new LibrarySearchSource();
         $searchSourceObj->id = $trimmedId;
         if ($searchSourceObj->find(true)) {
             $searchSource = $searchSourceObj;
         }
     }
     if (isset($_REQUEST['replacementTerm'])) {
         $replacementTerm = $_REQUEST['replacementTerm'];
         $interface->assign('replacementTerm', $replacementTerm);
         $oldTerm = $_REQUEST['lookfor'];
         $interface->assign('oldTerm', $oldTerm);
         $_REQUEST['lookfor'] = $replacementTerm;
         $_GET['lookfor'] = $replacementTerm;
         $oldSearchUrl = $_SERVER['REQUEST_URI'];
         $oldSearchUrl = str_replace('replacementTerm=' . urlencode($replacementTerm), 'disallowReplacements', $oldSearchUrl);
         $interface->assign('oldSearchUrl', $oldSearchUrl);
     }
     // Include Search Engine Class
     require_once ROOT_DIR . '/sys/Solr.php';
     $timer->logTime('Include search engine');
     //Check to see if the year has been set and if so, convert to a filter and resend.
     $dateFilters = array('publishDate');
     foreach ($dateFilters as $dateFilter) {
         if (isset($_REQUEST[$dateFilter . 'yearfrom']) || isset($_REQUEST[$dateFilter . 'yearto'])) {
             $queryParams = $_GET;
             $yearFrom = preg_match('/^\\d{2,4}$/', $_REQUEST[$dateFilter . 'yearfrom']) ? $_REQUEST[$dateFilter . 'yearfrom'] : '*';
             $yearTo = preg_match('/^\\d{2,4}$/', $_REQUEST[$dateFilter . 'yearto']) ? $_REQUEST[$dateFilter . 'yearto'] : '*';
             if (strlen($yearFrom) == 2) {
                 $yearFrom = '19' . $yearFrom;
             } else {
                 if (strlen($yearFrom) == 3) {
                     $yearFrom = '0' . $yearFrom;
                 }
             }
             if (strlen($yearTo) == 2) {
                 $yearTo = '19' . $yearTo;
             } else {
                 if (strlen($yearFrom) == 3) {
                     $yearTo = '0' . $yearTo;
                 }
             }
             if ($yearTo != '*' && $yearFrom != '*' && $yearTo < $yearFrom) {
                 $tmpYear = $yearTo;
                 $yearTo = $yearFrom;
                 $yearFrom = $tmpYear;
             }
             unset($queryParams['module']);
             unset($queryParams['action']);
             unset($queryParams[$dateFilter . 'yearfrom']);
             unset($queryParams[$dateFilter . 'yearto']);
             if (!isset($queryParams['sort'])) {
                 $queryParams['sort'] = 'year';
             }
             $queryParamStrings = array();
             foreach ($queryParams as $paramName => $queryValue) {
                 if (is_array($queryValue)) {
                     foreach ($queryValue as $arrayValue) {
                         if (strlen($arrayValue) > 0) {
                             $queryParamStrings[] = $paramName . '[]=' . $arrayValue;
                         }
                     }
                 } else {
                     if (strlen($queryValue)) {
                         $queryParamStrings[] = $paramName . '=' . $queryValue;
                     }
                 }
             }
             if ($yearFrom != '*' || $yearTo != '*') {
                 $queryParamStrings[] = "&filter[]={$dateFilter}:[{$yearFrom}+TO+{$yearTo}]";
             }
             $queryParamString = join('&', $queryParamStrings);
             header("Location: {$configArray['Site']['path']}/Search/Results?{$queryParamString}");
             exit;
         }
     }
     $rangeFilters = array('lexile_score', 'accelerated_reader_reading_level', 'accelerated_reader_point_value');
     foreach ($rangeFilters as $filter) {
         if (isset($_REQUEST[$filter . 'from']) && strlen($_REQUEST[$filter . 'from']) > 0 || isset($_REQUEST[$filter . 'to']) && strlen($_REQUEST[$filter . 'to']) > 0) {
             $queryParams = $_GET;
             $from = isset($_REQUEST[$filter . 'from']) && preg_match('/^\\d*(\\.\\d*)?$/', $_REQUEST[$filter . 'from']) ? $_REQUEST[$filter . 'from'] : '*';
             $to = isset($_REQUEST[$filter . 'to']) && preg_match('/^\\d*(\\.\\d*)?$/', $_REQUEST[$filter . 'to']) ? $_REQUEST[$filter . 'to'] : '*';
             if ($to != '*' && $from != '*' && $to < $from) {
                 $tmpFilter = $to;
                 $to = $from;
                 $from = $tmpFilter;
             }
             unset($queryParams['module']);
             unset($queryParams['action']);
             unset($queryParams[$filter . 'from']);
             unset($queryParams[$filter . 'to']);
             $queryParamStrings = array();
             foreach ($queryParams as $paramName => $queryValue) {
                 if (is_array($queryValue)) {
                     foreach ($queryValue as $arrayValue) {
                         if (strlen($arrayValue) > 0) {
                             $queryParamStrings[] = $paramName . '[]=' . $arrayValue;
                         }
                     }
                 } else {
                     if (strlen($queryValue)) {
                         $queryParamStrings[] = $paramName . '=' . $queryValue;
                     }
                 }
             }
             if ($from != '*' || $to != '*') {
                 $queryParamStrings[] = "&filter[]={$filter}:[{$from}+TO+{$to}]";
             }
             $queryParamString = join('&', $queryParamStrings);
             header("Location: {$configArray['Site']['path']}/Search/Results?{$queryParamString}");
             exit;
         }
     }
     // Initialise from the current search globals
     /** @var SearchObject_Solr $searchObject */
     $searchObject = SearchObjectFactory::initSearchObject();
     $searchObject->init($searchSource);
     $timer->logTime("Init Search Object");
     // Build RSS Feed for Results (if requested)
     if ($searchObject->getView() == 'rss') {
         // Throw the XML to screen
         echo $searchObject->buildRSS();
         // And we're done
         exit;
     } else {
         if ($searchObject->getView() == 'excel') {
             // Throw the Excel spreadsheet to screen for download
             echo $searchObject->buildExcel();
             // And we're done
             exit;
         }
     }
     // TODO : Investigate this... do we still need
     // If user wants to print record show directly print-dialog box
     if (isset($_GET['print'])) {
         $interface->assign('print', true);
     }
     // Set Interface Variables
     //   Those we can construct BEFORE the search is executed
     $interface->setPageTitle('Search Results');
     $interface->assign('sortList', $searchObject->getSortList());
     $interface->assign('rssLink', $searchObject->getRSSUrl());
     $interface->assign('excelLink', $searchObject->getExcelUrl());
     $timer->logTime('Setup Search');
     // Process Search
     $result = $searchObject->processSearch(true, true);
     if (PEAR_Singleton::isError($result)) {
         PEAR_Singleton::raiseError($result->getMessage());
     }
     $timer->logTime('Process Search');
     // Some more variables
     //   Those we can construct AFTER the search is executed, but we need
     //   no matter whether there were any results
     $interface->assign('qtime', round($searchObject->getQuerySpeed(), 2));
     $interface->assign('spellingSuggestions', $searchObject->getSpellingSuggestions());
     $interface->assign('lookfor', $searchObject->displayQuery());
     $interface->assign('searchType', $searchObject->getSearchType());
     // Will assign null for an advanced search
     $interface->assign('searchIndex', $searchObject->getSearchIndex());
     // We'll need recommendations no matter how many results we found:
     $interface->assign('topRecommendations', $searchObject->getRecommendationsTemplates('top'));
     $interface->assign('sideRecommendations', $searchObject->getRecommendationsTemplates('side'));
     // 'Finish' the search... complete timers and log search history.
     $searchObject->close();
     $interface->assign('time', round($searchObject->getTotalSpeed(), 2));
     // Show the save/unsave code on screen
     // The ID won't exist until after the search has been put in the search history
     //    so this needs to occur after the close() on the searchObject
     $interface->assign('showSaved', true);
     $interface->assign('savedSearch', $searchObject->isSavedSearch());
     $interface->assign('searchId', $searchObject->getSearchId());
     $currentPage = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1;
     $interface->assign('page', $currentPage);
     //Enable and disable functionality based on library settings
     //This must be done before we process each result
     global $library;
     /** @var Location $locationSingleton */
     global $locationSingleton;
     $location = $locationSingleton->getActiveLocation();
     $showHoldButton = 1;
     $showHoldButtonInSearchResults = 1;
     $interface->assign('showNotInterested', false);
     if (isset($library) && $location != null) {
         $interface->assign('showFavorites', $library->showFavorites);
         $interface->assign('showComments', $library->showComments);
         $showHoldButton = $location->showHoldButton == 1 && $library->showHoldButton == 1 ? 1 : 0;
         $showHoldButtonInSearchResults = $location->showHoldButton == 1 && $library->showHoldButtonInSearchResults == 1 ? 1 : 0;
     } else {
         if ($location != null) {
             $interface->assign('showFavorites', 1);
             $showHoldButton = $location->showHoldButton;
         } else {
             if (isset($library)) {
                 $interface->assign('showFavorites', $library->showFavorites);
                 $showHoldButton = $library->showHoldButton;
                 $showHoldButtonInSearchResults = $library->showHoldButtonInSearchResults;
                 $interface->assign('showComments', $library->showComments);
             } else {
                 $interface->assign('showFavorites', 1);
                 $interface->assign('showComments', 1);
             }
         }
     }
     if ($showHoldButton == 0) {
         $showHoldButtonInSearchResults = 0;
     }
     $interface->assign('showHoldButton', $showHoldButtonInSearchResults);
     $interface->assign('page_body_style', 'sidebar_left');
     $interface->assign('overDriveVersion', isset($configArray['OverDrive']['interfaceVersion']) ? $configArray['OverDrive']['interfaceVersion'] : 1);
     //Check to see if we should show unscoped results
     $enableUnscopedSearch = false;
     $searchLibrary = Library::getSearchLibrary();
     if ($searchLibrary != null && $searchLibrary->showMarmotResultsAtEndOfSearch) {
         if (is_object($searchSource)) {
             $enableUnscopedSearch = $searchSource->catalogScoping != 'unscoped';
             $unscopedSearch = clone $searchObject;
         } else {
             $searchSources = new SearchSources();
             $searchOptions = $searchSources->getSearchSources();
             if (isset($searchOptions['marmot'])) {
                 $unscopedSearch = clone $searchObject;
                 $enableUnscopedSearch = true;
             }
         }
     }
     $enableProspectorIntegration = isset($configArray['Content']['Prospector']) ? $configArray['Content']['Prospector'] : false;
     $showRatings = 1;
     $showProspectorResultsAtEndOfSearch = true;
     if (isset($library)) {
         $enableProspectorIntegration = $library->enablePospectorIntegration == 1;
         $showRatings = $library->showRatings;
         $showProspectorResultsAtEndOfSearch = $library->showProspectorResultsAtEndOfSearch == 1;
     }
     $interface->assign('showRatings', $showRatings);
     $numProspectorTitlesToLoad = 0;
     $numUnscopedTitlesToLoad = 0;
     // Save the ID of this search to the session so we can return to it easily:
     $_SESSION['lastSearchId'] = $searchObject->getSearchId();
     // Save the URL of this search to the session so we can return to it easily:
     $_SESSION['lastSearchURL'] = $searchObject->renderSearchUrl();
     if (is_object($searchSource)) {
         $translatedSearch = $searchSource->label;
     } else {
         $allSearchSources = SearchSources::getSearchSources();
         if (!isset($allSearchSources[$searchSource]) && $searchSource == 'marmot') {
             $searchSource = 'local';
         }
         $translatedSearch = $allSearchSources[$searchSource]['name'];
     }
     $analytics->addSearch($translatedSearch, $searchObject->displayQuery(), $searchObject->isAdvanced(), $searchObject->getFullSearchType(), $searchObject->hasAppliedFacets(), $searchObject->getResultTotal());
     if ($searchObject->getResultTotal() < 1) {
         //We didn't find anything.  Look for search Suggestions
         //Don't try to find suggestions if facets were applied
         $autoSwitchSearch = false;
         $disallowReplacements = isset($_REQUEST['disallowReplacements']) || isset($_REQUEST['replacementTerm']);
         if (!$disallowReplacements && (!isset($facetSet) || count($facetSet) == 0)) {
             require_once ROOT_DIR . '/services/Search/lib/SearchSuggestions.php';
             $searchSuggestions = new SearchSuggestions();
             $commonSearches = $searchSuggestions->getCommonSearchesMySql($searchObject->displayQuery(), $searchObject->getSearchIndex());
             //If the first search in the list is used 10 times more than the next, just show results for that
             $numSuggestions = count($commonSearches);
             if ($numSuggestions == 1) {
                 $autoSwitchSearch = true;
             } elseif ($numSuggestions >= 2) {
                 $firstTimesSearched = $commonSearches[0]['numSearches'];
                 $secondTimesSearched = $commonSearches[1]['numSearches'];
                 if ($firstTimesSearched / $secondTimesSearched > 10) {
                     $autoSwitchSearch = true;
                 }
             }
             $interface->assign('autoSwitchSearch', $autoSwitchSearch);
             if ($autoSwitchSearch) {
                 //Get search results for the new search
                 $interface->assign('oldTerm', $searchObject->displayQuery());
                 $interface->assign('newTerm', $commonSearches[0]['phrase']);
                 $thisUrl = $_SERVER['REQUEST_URI'];
                 $thisUrl = $thisUrl . "&replacementTerm=" . urlencode($commonSearches[0]['phrase']);
                 header("Location: " . $thisUrl);
                 exit;
             }
             $interface->assign('searchSuggestions', $commonSearches);
         }
         //Var for the IDCLREADER TEMPLATE
         $interface->assign('ButtonBack', true);
         $interface->assign('ButtonHome', true);
         $interface->assign('MobileTitle', 'No Results Found');
         // No record found
         $interface->setTemplate('list-none.tpl');
         $interface->assign('recordCount', 0);
         // Was the empty result set due to an error?
         $error = $searchObject->getIndexError();
         if ($error !== false) {
             // If it's a parse error or the user specified an invalid field, we
             // should display an appropriate message:
             if (stristr($error, 'org.apache.lucene.queryParser.ParseException') || preg_match('/^undefined field/', $error)) {
                 $interface->assign('parseError', true);
                 // Unexpected error -- let's treat this as a fatal condition.
             } else {
                 PEAR_Singleton::raiseError(new PEAR_Error('Unable to process query<br />' . 'Solr Returned: ' . $error));
             }
         }
         $numProspectorTitlesToLoad = 10;
         $numUnscopedTitlesToLoad = 10;
         $timer->logTime('no hits processing');
     } else {
         if ($searchObject->getResultTotal() == 1 && (strpos($searchObject->displayQuery(), 'id') === 0 || $searchObject->getSearchType() == 'id')) {
             //Redirect to the home page for the record
             $recordSet = $searchObject->getResultRecordSet();
             $record = reset($recordSet);
             $_SESSION['searchId'] = $searchObject->getSearchId();
             if ($record['recordtype'] == 'list') {
                 $listId = substr($record['id'], 4);
                 header("Location: " . $configArray['Site']['path'] . "/MyResearch/MyList/{$listId}");
                 exit;
             } elseif ($record['recordtype'] == 'econtentRecord') {
                 $shortId = str_replace('econtentRecord', '', $record['id']);
                 header("Location: " . $configArray['Site']['path'] . "/EcontentRecord/{$shortId}/Home");
                 exit;
             } else {
                 header("Location: " . $configArray['Site']['path'] . "/Record/{$record['id']}/Home");
                 exit;
             }
         } else {
             $timer->logTime('save search');
             // Assign interface variables
             $summary = $searchObject->getResultSummary();
             $interface->assign('recordCount', $summary['resultTotal']);
             $interface->assign('recordStart', $summary['startRecord']);
             $interface->assign('recordEnd', $summary['endRecord']);
             $facetSet = $searchObject->getFacetList();
             $interface->assign('facetSet', $facetSet);
             //Check to see if a format category is already set
             $categorySelected = false;
             if (isset($facetSet['top'])) {
                 foreach ($facetSet['top'] as $cluster) {
                     if ($cluster['label'] == 'Category') {
                         foreach ($cluster['list'] as $thisFacet) {
                             if ($thisFacet['isApplied']) {
                                 $categorySelected = true;
                             }
                         }
                     }
                 }
             }
             $interface->assign('categorySelected', $categorySelected);
             $timer->logTime('load selected category');
             // Big one - our results
             $recordSet = $searchObject->getResultRecordHTML();
             $interface->assign('recordSet', $recordSet);
             $timer->logTime('load result records');
             // Setup Display
             $interface->assign('sitepath', $configArray['Site']['path']);
             $interface->assign('subpage', 'Search/list-list.tpl');
             $interface->setTemplate('list.tpl');
             //Var for the IDCLREADER TEMPLATE
             $interface->assign('ButtonBack', true);
             $interface->assign('ButtonHome', true);
             $interface->assign('MobileTitle', 'Search Results');
             // Process Paging
             $link = $searchObject->renderLinkPageTemplate();
             $options = array('totalItems' => $summary['resultTotal'], 'fileName' => $link, 'perPage' => $summary['perPage']);
             $pager = new VuFindPager($options);
             $interface->assign('pageLinks', $pager->getLinks());
             if ($pager->isLastPage()) {
                 $numProspectorTitlesToLoad = 5;
                 $numUnscopedTitlesToLoad = 5;
             }
             $timer->logTime('finish hits processing');
         }
     }
     if ($numProspectorTitlesToLoad > 0 && $enableProspectorIntegration && $showProspectorResultsAtEndOfSearch) {
         $interface->assign('prospectorNumTitlesToLoad', $numProspectorTitlesToLoad);
         $interface->assign('prospectorSavedSearchId', $searchObject->getSearchId());
     } else {
         $interface->assign('prospectorNumTitlesToLoad', 0);
     }
     if ($enableUnscopedSearch && isset($unscopedSearch)) {
         $unscopedSearch->setLimit($numUnscopedTitlesToLoad * 4);
         $unscopedSearch->disableScoping();
         $unscopedSearch->processSearch(false, false);
         $numUnscopedResults = $unscopedSearch->getResultTotal();
         $interface->assign('numUnscopedResults', $numUnscopedResults);
         $unscopedSearchUrl = $unscopedSearch->renderSearchUrl();
         if (preg_match('/searchSource=(.*?)(?:&|$)/', $unscopedSearchUrl)) {
             $unscopedSearchUrl = preg_replace('/(.*searchSource=)(.*?)(&|$)(.*)/', '$1marmot$3$4', $unscopedSearchUrl);
             $unscopedSearchUrl = preg_replace('/&/', '&amp;', $unscopedSearchUrl);
         } else {
             $unscopedSearchUrl .= "&amp;searchSource=marmot";
         }
         $unscopedSearchUrl .= "&amp;shard=";
         $interface->assign('unscopedSearchUrl', $unscopedSearchUrl);
         if ($numUnscopedTitlesToLoad > 0) {
             $unscopedResults = $unscopedSearch->getSupplementalResultRecordHTML($searchObject->getResultRecordSet(), $numUnscopedTitlesToLoad, $searchObject->getResultTotal());
             $interface->assign('unscopedResults', $unscopedResults);
         }
     }
     //Determine whether or not materials request functionality should be enabled
     $interface->assign('enableMaterialsRequest', MaterialsRequest::enableMaterialsRequest());
     if ($configArray['Statistics']['enabled'] && isset($_GET['lookfor'])) {
         require_once ROOT_DIR . '/Drivers/marmot_inc/SearchStat.php';
         $searchStat = new SearchStat();
         $searchStat->saveSearch(strip_tags($_GET['lookfor']), strip_tags(isset($_GET['type']) ? $_GET['type'] : (isset($_GET['basicType']) ? $_GET['basicType'] : 'Keyword')), $searchObject->getResultTotal());
     }
     // Done, display the page
     $interface->display('layout.tpl');
 }
Example #9
0
 public function getMyProfile($patron, $forceReload = false)
 {
     global $timer;
     global $configArray;
     if (is_object($patron)) {
         $patron = get_object_vars($patron);
     }
     if (array_key_exists($patron['username'], $this->patronProfiles) && !$forceReload) {
         $timer->logTime('Retrieved Cached Profile for Patron');
         return $this->patronProfiles[$patron['username']];
     }
     $mysip = new sip2();
     $mysip->hostname = $configArray['SIP2']['host'];
     $mysip->port = $configArray['SIP2']['port'];
     if ($mysip->connect()) {
         //send selfcheck status message
         $in = $mysip->msgSCStatus();
         $msg_result = $mysip->get_message($in);
         // Make sure the response is 98 as expected
         if (preg_match("/^98/", $msg_result)) {
             $result = $mysip->parseACSStatusResponse($msg_result);
             //  Use result to populate SIP2 setings
             $mysip->AO = $result['variable']['AO'][0];
             /* set AO to value returned */
             $mysip->AN = $result['variable']['AN'][0];
             /* set AN to value returned */
             $mysip->patron = $patron['username'];
             $mysip->patronpwd = $patron['cat_password'];
             $in = $mysip->msgPatronInformation('fine');
             $msg_result = $mysip->get_message($in);
             // Make sure the response is 24 as expected
             if (preg_match("/^64/", $msg_result)) {
                 $result = $mysip->parsePatronInfoResponse($msg_result);
                 $address = $result['variable']['BD'][0];
                 $addressParts = explode(',', $address);
                 $expirationDate = $result['variable']['PE'][0];
                 $formattedExpiration = substr($expirationDate, 4, 2) . '/' . substr($expirationDate, 6, 2) . '/' . substr($expirationDate, 0, 4);
                 //$fines = $this->parseSip2Fines($result['variable']['AV']);
                 $location = new Location();
                 $location->code = $result['variable']['AQ'][0];
                 $location->find();
                 if ($location->N > 0) {
                     $location->fetch();
                     $homeLocationId = $location->locationId;
                 }
                 global $user;
                 $profile = array('lastname' => $result['variable']['DJ'][0], 'firstname' => isset($result['variable']['DH'][0]) ? $result['variable']['DH'][0] : '', 'displayName' => $patron['displayName'], 'fullname' => $result['variable']['AE'][0], 'address1' => trim($addressParts[0]), 'city' => trim($addressParts[1]), 'state' => trim($addressParts[2]), 'zip' => isset($addressParts[3]) ? trim($addressParts[3]) : '', 'phone' => isset($result['variable']['BF'][0]) ? $result['variable']['BF'][0] : '', 'email' => isset($result['variable']['BE'][0]) ? $result['variable']['BE'][0] : '', 'homeLocationId' => isset($homeLocationId) ? $homeLocationId : -1, 'homeLocationName' => $this->translateLocation($result['variable']['AQ'][0]), 'expires' => $formattedExpiration, 'fines' => isset($result['variable']['BV']) ? sprintf('$%01.2f', $result['variable']['BV'][0]) : 0, 'finesval' => isset($result['variable']['BV']) ? $result['variable']['BV'][0] : '', 'numHolds' => $result['fixed']['HoldCount'] + $result['fixed']['UnavailableCount'], 'numHoldsAvailable' => $result['fixed']['HoldCount'], 'numHoldsRequested' => $result['fixed']['UnavailableCount'], 'numCheckedOut' => $result['fixed']['ChargedCount'], 'bypassAutoLogout' => $user ? $user->bypassAutoLogout : false);
                 //Get eContent info as well
                 require_once ROOT_DIR . '/Drivers/EContentDriver.php';
                 $eContentDriver = new EContentDriver();
                 $eContentAccountSummary = $eContentDriver->getAccountSummary();
                 $profile = array_merge($profile, $eContentAccountSummary);
                 //Get a count of the materials requests for the user
                 $materialsRequest = new MaterialsRequest();
                 $materialsRequest->createdBy = $user->id;
                 $statusQuery = new MaterialsRequestStatus();
                 $statusQuery->isOpen = 1;
                 $materialsRequest->joinAdd($statusQuery);
                 $materialsRequest->find();
                 $profile['numMaterialsRequests'] = $materialsRequest->N;
             } else {
                 $profile = new PEAR_Error('patron_info_error_technical');
             }
         } else {
             $profile = new PEAR_Error('patron_info_error_technical');
         }
         $mysip->disconnect();
     } else {
         $profile = new PEAR_Error('patron_info_error_technical');
     }
     $this->patronProfiles[$patron['username']] = $profile;
     $timer->logTime('Retrieved Profile for Patron from SIP 2');
     return $profile;
 }
Example #10
0
 function __construct()
 {
     global $interface;
     global $configArray;
     global $user;
     //If the user isn't logged in, take them to the login page
     if (!$user) {
         header("Location: {$configArray['Site']['path']}/MyResearch/Login");
         die;
     }
     //Make sure the user has permission to access the page
     $allowableRoles = $this->getAllowableRoles();
     $userCanAccess = false;
     foreach ($allowableRoles as $roleId => $roleName) {
         if ($user->hasRole($roleName)) {
             $userCanAccess = true;
             break;
         }
     }
     $interface->assign('ils', $configArray['Catalog']['ils']);
     //Determine whether or not materials request functionality should be enabled
     $interface->assign('enableMaterialsRequest', MaterialsRequest::enableMaterialsRequest());
     //Check to see if we have any acs or single use eContent in the catalog
     //to enable the holds and wishlist appropriately
     if (isset($configArray['EContent']['hasProtectedEContent'])) {
         $interface->assign('hasProtectedEContent', $configArray['EContent']['hasProtectedEContent']);
     } else {
         $interface->assign('hasProtectedEContent', false);
     }
     //This code is also in Search/History since that page displays in the My Account menu as well.
     //It is also in MyList.php
     if ($user !== false) {
         $this->catalog = new CatalogConnection($configArray['Catalog']['driver']);
         $interface->assign('user', $user);
         // Get My Profile
         if ($this->catalog->status) {
             if ($user->cat_username) {
                 $patron = $this->catalog->patronLogin($user->cat_username, $user->cat_password);
                 if (PEAR_Singleton::isError($patron)) {
                     PEAR_Singleton::raiseError($patron);
                 }
                 $profile = $this->catalog->getMyProfile($patron);
                 if (!PEAR_Singleton::isError($profile)) {
                     $interface->assign('profile', $profile);
                 }
             }
         }
         //Figure out if we should show a link to classic opac to pay holds.
         $ecommerceLink = $configArray['Site']['ecommerceLink'];
         $homeLibrary = Library::getLibraryForLocation($user->homeLocationId);
         if (strlen($ecommerceLink) > 0 && isset($homeLibrary) && $homeLibrary->showEcommerceLink == 1) {
             $interface->assign('showEcommerceLink', true);
             $interface->assign('minimumFineAmount', $homeLibrary->minimumFineAmount);
             $interface->assign('ecommerceLink', $ecommerceLink);
         } else {
             $interface->assign('showEcommerceLink', false);
             $interface->assign('minimumFineAmount', 0);
         }
     }
     if (!$userCanAccess) {
         $interface->setTemplate('../Admin/noPermission.tpl');
         $interface->display('layout.tpl');
         exit;
     }
 }
Example #11
0
 function MaterialsRequestDetails()
 {
     global $interface;
     if (!isset($_REQUEST['id'])) {
         $interface->assign('error', 'Please provide an id of the materials request to view.');
     } else {
         $id = $_REQUEST['id'];
         $materialsRequest = new MaterialsRequest();
         $materialsRequest->id = $id;
         $statusQuery = new MaterialsRequestStatus();
         $materialsRequest->joinAdd($statusQuery);
         $locationQuery = new Location();
         $materialsRequest->joinAdd($locationQuery, "LEFT");
         $materialsRequest->selectAdd();
         $materialsRequest->selectAdd('materials_request.*, description as statusLabel, location.displayName as location');
         if ($materialsRequest->find(true)) {
             $interface->assign('materialsRequest', $materialsRequest);
             global $user;
             if ($user && $user->hasRole('cataloging') || $user->hasRole('library_material_requests')) {
                 $interface->assign('showUserInformation', true);
                 //Load user information
                 $requestUser = new User();
                 $requestUser->id = $materialsRequest->createdBy;
                 if ($requestUser->find(true)) {
                     $interface->assign('requestUser', $requestUser);
                 }
             } else {
                 $interface->assign('showUserInformation', false);
             }
         } else {
             $interface->assign('error', 'Sorry, we couldn\'t find a materials request for that id.');
         }
     }
     $return = array('title' => 'Materials Request Details', 'modalBody' => $interface->fetch('MaterialsRequest/ajax-request-details.tpl'), 'modalButtons' => '');
     return $return;
 }
 static function enableMaterialsRequest($forceReload = false)
 {
     if (MaterialsRequest::$materialsRequestEnabled != null && $forceReload == false) {
         return MaterialsRequest::$materialsRequestEnabled;
     }
     global $configArray;
     global $user;
     global $library;
     //First make sure we are enabled in the config file
     if (isset($configArray['MaterialsRequest']) && isset($configArray['MaterialsRequest']['enabled'])) {
         $enableMaterialsRequest = $configArray['MaterialsRequest']['enabled'];
         //Now check if the library allows material requests
         if ($enableMaterialsRequest) {
             if (isset($library) && $library->enableMaterialsRequest == 0) {
                 $enableMaterialsRequest = false;
             } else {
                 if ($user) {
                     $homeLibrary = Library::getPatronHomeLibrary();
                     if (is_null($homeLibrary)) {
                         $enableMaterialsRequest = false;
                     } else {
                         if ($homeLibrary->enableMaterialsRequest == 0) {
                             $enableMaterialsRequest = false;
                         } else {
                             if ($homeLibrary->libraryId != $library->libraryId) {
                                 $enableMaterialsRequest = false;
                             } else {
                                 if (isset($configArray['MaterialsRequest']['allowablePatronTypes'])) {
                                     //Check to see if we need to do additional restrictions by patron type
                                     $allowablePatronTypes = $configArray['MaterialsRequest']['allowablePatronTypes'];
                                     if (strlen($allowablePatronTypes) > 0) {
                                         if (!preg_match("/^{$allowablePatronTypes}\$/i", $user->patronType)) {
                                             $enableMaterialsRequest = false;
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     } else {
         $enableMaterialsRequest = false;
     }
     MaterialsRequest::$materialsRequestEnabled = $enableMaterialsRequest;
     return $enableMaterialsRequest;
 }
Example #13
0
 /**
  * Get Patron Profile
  *
  * This is responsible for retrieving the profile for a specific patron.
  * Interface defined in CatalogConnection.php
  *
  * @param   array   $patron     The patron array
  * @param   boolean $forceReload Whether or not we should force a reload of the data
  * @return  array               Array of the patron's profile data
  *                              If an error occurs, return a PEAR_Error
  * @access  public
  */
 public function getMyProfile($patron, $forceReload = false)
 {
     global $timer;
     global $configArray;
     /** @var Memcache $memCache */
     global $memCache;
     global $serverName;
     $memCacheProfileKey = "patronProfile_{$serverName}_";
     if (is_object($patron)) {
         $patron = get_object_vars($patron);
         $memCacheProfileKey .= $patron['username'];
         $id2 = $this->_getBarcode($patron);
     } else {
         global $user;
         $memCacheProfileKey .= $user->username;
         $id2 = $patron['cat_password'];
     }
     if (!$forceReload && !isset($_REQUEST['reload'])) {
         $patronProfile = $memCache->get($memCacheProfileKey);
         if ($patronProfile) {
             $timer->logTime('Retrieved Cached Profile for Patron');
             return $patronProfile;
         }
     }
     global $user;
     if ($configArray['Catalog']['offline'] == true) {
         $fullName = $patron['cat_username'];
         $Address1 = "";
         $City = "";
         $State = "";
         $Zip = "";
         $finesVal = 0;
         $expireClose = false;
         $homeBranchCode = '';
         $numHoldsAvailable = '?';
         $numHoldsRequested = '?';
         if (!$user) {
             $user = new User();
             $user->cat_password = $id2;
             if ($user->find(true)) {
                 $location = new Location();
                 $location->locationId = $user->homeLocationId;
                 $location->find(1);
                 $homeBranchCode = $location->code;
             }
         }
     } else {
         //Load the raw information about the patron
         $patronDump = $this->_getPatronDump($id2);
         if (isset($patronDump['ADDRESS'])) {
             $fullAddress = $patronDump['ADDRESS'];
             $addressParts = explode('$', $fullAddress);
             $Address1 = $addressParts[0];
             $City = isset($addressParts[1]) ? $addressParts[1] : '';
             $State = isset($addressParts[2]) ? $addressParts[2] : '';
             $Zip = isset($addressParts[3]) ? $addressParts[3] : '';
             if (preg_match('/(.*?),\\s+(.*)\\s+(\\d*(?:-\\d*)?)/', $City, $matches)) {
                 $City = $matches[1];
                 $State = $matches[2];
                 $Zip = $matches[3];
             } else {
                 if (preg_match('/(.*?)\\s+(\\w{2})\\s+(\\d*(?:-\\d*)?)/', $City, $matches)) {
                     $City = $matches[1];
                     $State = $matches[2];
                     $Zip = $matches[3];
                 }
             }
         } else {
             $Address1 = "";
             $City = "";
             $State = "";
             $Zip = "";
         }
         $fullName = $patronDump['PATRN_NAME'];
         //Get additional information about the patron's home branch for display.
         $location = null;
         if (isset($patronDump['HOME_LIBR']) || isset($patronDump['HOLD_LIBR'])) {
             $homeBranchCode = isset($patronDump['HOME_LIBR']) ? $patronDump['HOME_LIBR'] : $patronDump['HOLD_LIBR'];
             $homeBranchCode = str_replace('+', '', $homeBranchCode);
             //Translate home branch to plain text
             $location = new Location();
             $location->whereAdd("code = '{$homeBranchCode}'");
             $location->find(1);
             if ($location->N == 0) {
                 unset($location);
             }
         }
         if ($user) {
             if (isset($location)) {
                 if ($user->homeLocationId == 0) {
                     $user->homeLocationId = $location->locationId;
                     if ($location->nearbyLocation1 > 0) {
                         $user->myLocation1Id = $location->nearbyLocation1;
                     } else {
                         $user->myLocation1Id = $location->locationId;
                     }
                     if ($location->nearbyLocation2 > 0) {
                         $user->myLocation2Id = $location->nearbyLocation2;
                     } else {
                         $user->myLocation2Id = $location->locationId;
                     }
                     if ($user instanceof User) {
                         //Update the database
                         $user->update();
                         //Update the serialized instance stored in the session
                         $_SESSION['userinfo'] = serialize($user);
                     }
                 } else {
                     if ($location->locationId != $user->homeLocationId) {
                         $user->homeLocationId = $location->locationId;
                         //Update the database
                         $user->update();
                         //Update the serialized instance stored in the session
                         $_SESSION['userinfo'] = serialize($user);
                     }
                 }
             }
         }
         //see if expiration date is close
         if (trim($patronDump['EXP_DATE']) != '-  -') {
             list($monthExp, $dayExp, $yearExp) = explode("-", $patronDump['EXP_DATE']);
             $timeExpire = strtotime($monthExp . "/" . $dayExp . "/" . $yearExp);
             $timeNow = time();
             $timeToExpire = $timeExpire - $timeNow;
             $expired = 0;
             if ($timeToExpire <= 30 * 24 * 60 * 60) {
                 if ($timeToExpire <= 0) {
                     $expired = 1;
                 }
                 $expireClose = 1;
             } else {
                 $expireClose = 0;
             }
         } else {
             $expired = 0;
             $expireClose = 0;
         }
         $finesVal = floatval(preg_replace('/[^\\d.]/', '', $patronDump['MONEY_OWED']));
         $numHoldsAvailable = 0;
         $numHoldsRequested = 0;
         $availableStatusRegex = isset($configArray['Catalog']['patronApiAvailableHoldsRegex']) ? $configArray['Catalog']['patronApiAvailableHoldsRegex'] : "/ST=(105|98),/";
         if (isset($patronDump) && isset($patronDump['HOLD']) && count($patronDump['HOLD']) > 0) {
             foreach ($patronDump['HOLD'] as $hold) {
                 if (preg_match("{$availableStatusRegex}", $hold)) {
                     $numHoldsAvailable++;
                 } else {
                     $numHoldsRequested++;
                 }
             }
         }
     }
     $nameParts = explode(', ', $fullName);
     $lastName = $nameParts[0];
     $secondName = isset($nameParts[1]) ? $nameParts[1] : '';
     if (strpos($secondName, ' ')) {
         $nameParts2 = explode(' ', $secondName);
         $firstName = $nameParts2[0];
     } else {
         $firstName = $secondName;
     }
     if ($user) {
         //Get display name for preferred location 1
         $myLocation1 = new Location();
         $myLocation1->whereAdd("locationId = '{$user->myLocation1Id}'");
         $myLocation1->find(1);
         //Get display name for preferred location 1
         $myLocation2 = new Location();
         $myLocation2->whereAdd("locationId = '{$user->myLocation2Id}'");
         $myLocation2->find(1);
     }
     $noticeLabels = array('-' => '', 'a' => 'Mail', 'p' => 'Telephone', 'z' => 'E-mail');
     $profile = array('lastname' => $lastName, 'firstname' => $firstName, 'fullname' => $fullName, 'address1' => $Address1, 'address2' => $City . ', ' . $State, 'city' => $City, 'state' => $State, 'zip' => $Zip, 'email' => $user && $user->email ? $user->email : (isset($patronDump) && isset($patronDump['EMAIL_ADDR']) ? $patronDump['EMAIL_ADDR'] : ''), 'overdriveEmail' => $user ? $user->overdriveEmail : (isset($patronDump) && isset($patronDump['EMAIL_ADDR']) ? $patronDump['EMAIL_ADDR'] : ''), 'promptForOverdriveEmail' => $user ? $user->promptForOverdriveEmail : 1, 'phone' => isset($patronDump) && isset($patronDump['TELEPHONE']) ? $patronDump['TELEPHONE'] : (isset($patronDump['HOME_PHONE']) ? $patronDump['HOME_PHONE'] : ''), 'workPhone' => isset($patronDump) && isset($patronDump['G/WK_PHONE']) ? $patronDump['G/WK_PHONE'] : '', 'mobileNumber' => isset($patronDump) && isset($patronDump['MOBILE_NO']) ? $patronDump['MOBILE_NO'] : '', 'fines' => isset($patronDump) ? $patronDump['MONEY_OWED'] : '0', 'finesval' => $finesVal, 'expires' => isset($patronDump) ? $patronDump['EXP_DATE'] : '', 'expireclose' => $expireClose, 'expired' => $expired, 'homeLocationCode' => isset($homeBranchCode) ? trim($homeBranchCode) : '', 'homeLocationId' => isset($location) ? $location->locationId : 0, 'homeLocation' => isset($location) ? $location->displayName : '', 'myLocation1Id' => $user ? $user->myLocation1Id : -1, 'myLocation1' => isset($myLocation1) ? $myLocation1->displayName : '', 'myLocation2Id' => $user ? $user->myLocation2Id : -1, 'myLocation2' => isset($myLocation2) ? $myLocation2->displayName : '', 'numCheckedOut' => isset($patronDump) ? $patronDump['CUR_CHKOUT'] : '?', 'numHolds' => isset($patronDump) ? isset($patronDump['HOLD']) ? count($patronDump['HOLD']) : 0 : '?', 'numHoldsAvailable' => $numHoldsAvailable, 'numHoldsRequested' => $numHoldsRequested, 'bypassAutoLogout' => $user ? $user->bypassAutoLogout : 0, 'ptype' => $user && $user->patronType ? $user->patronType : (isset($patronDump) ? $patronDump['P_TYPE'] : 0), 'notices' => isset($patronDump) ? $patronDump['NOTICE_PREF'] : '-', 'web_note' => isset($patronDump) ? isset($patronDump['WEB_NOTE']) ? $patronDump['WEB_NOTE'] : '' : '');
     if (array_key_exists($profile['notices'], $noticeLabels)) {
         $profile['noticePreferenceLabel'] = $noticeLabels[$profile['notices']];
     } else {
         $profile['noticePreferenceLabel'] = 'Unknown';
     }
     //Get eContent info as well
     require_once ROOT_DIR . '/Drivers/EContentDriver.php';
     $eContentDriver = new EContentDriver();
     $eContentAccountSummary = $eContentDriver->getAccountSummary();
     $profile = array_merge($profile, $eContentAccountSummary);
     require_once ROOT_DIR . '/Drivers/OverDriveDriverFactory.php';
     $overDriveDriver = OverDriveDriverFactory::getDriver();
     if ($overDriveDriver->isUserValidForOverDrive($user)) {
         $overDriveSummary = $overDriveDriver->getOverDriveSummary($user);
         $profile['numOverDriveCheckedOut'] = $overDriveSummary['numCheckedOut'];
         $profile['numOverDriveHoldsAvailable'] = $overDriveSummary['numAvailableHolds'];
         $profile['numOverDriveHoldsRequested'] = $overDriveSummary['numUnavailableHolds'];
         $profile['canUseOverDrive'] = true;
     } else {
         $profile['numOverDriveCheckedOut'] = 0;
         $profile['numOverDriveHoldsAvailable'] = 0;
         $profile['numOverDriveHoldsRequested'] = 0;
         $profile['canUseOverDrive'] = false;
     }
     $profile['numCheckedOutTotal'] = $profile['numCheckedOut'] + $profile['numOverDriveCheckedOut'] + $eContentAccountSummary['numEContentCheckedOut'];
     $profile['numHoldsAvailableTotal'] = $profile['numHoldsAvailable'] + $profile['numOverDriveHoldsAvailable'] + $eContentAccountSummary['numEContentAvailableHolds'];
     $profile['numHoldsRequestedTotal'] = $profile['numHoldsRequested'] + $profile['numOverDriveHoldsRequested'] + $eContentAccountSummary['numEContentUnavailableHolds'];
     $profile['numHoldsTotal'] = $profile['numHoldsAvailableTotal'] + $profile['numHoldsRequestedTotal'];
     //Get a count of the materials requests for the user
     if ($user) {
         $materialsRequest = new MaterialsRequest();
         $materialsRequest->createdBy = $user->id;
         $homeLibrary = Library::getPatronHomeLibrary();
         $statusQuery = new MaterialsRequestStatus();
         $statusQuery->isOpen = 1;
         $statusQuery->libraryId = $homeLibrary->libraryId;
         $materialsRequest->joinAdd($statusQuery);
         $materialsRequest->find();
         $profile['numMaterialsRequests'] = $materialsRequest->N;
     }
     $timer->logTime("Got Patron Profile");
     $memCache->set($memCacheProfileKey, $profile, 0, $configArray['Caching']['patron_profile']);
     return $profile;
 }
Example #14
0
 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&amp;inst_code={$library->goldRushCode}&amp;search_type=ISSN&amp;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}&amp;isn={$this->isbn}&amp;issn={$this->issn}&amp;size=large&amp;upc={$this->upc}&amp;category=" . urlencode($format_category) . "&amp;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());
 }
Example #15
0
 /**
  * Get Patron Profile
  *
  * This is responsible for retrieving the profile for a specific patron.
  * Interface defined in CatalogConnection.php
  *
  * @param   array   $patron     The patron array
  * @return  array               Array of the patron's profile data
  *                              If an error occures, return a PEAR_Error
  * @access  public
  */
 public function getMyProfile($patron)
 {
     global $timer;
     global $configArray;
     if (is_object($patron)) {
         $patron = get_object_vars($patron);
         $id2 = $this->_getBarcode();
     } else {
         $id2 = $patron['id'];
     }
     if (array_key_exists($patron['id'], $this->patronProfiles)) {
         $timer->logTime('Retrieved Cached Profile for Patron');
         return $this->patronProfiles[$patron['id']];
     }
     //Load the raw information about the patron
     $patronDump = $this->_getPatronDump($id2);
     if (isset($patronDump['ADDRESS'])) {
         $Fulladdress = $patronDump['ADDRESS'];
         $addressParts = explode('$', $Fulladdress);
         $Address1 = $addressParts[0];
         $City = isset($addressParts[1]) ? $addressParts[1] : '';
         $State = isset($addressParts[2]) ? $addressParts[2] : '';
         $Zip = isset($addressParts[3]) ? $addressParts[3] : '';
         if (preg_match('/(.*?),\\s+(.*)\\s+(\\d*(?:-\\d*)?)/', $City, $matches)) {
             $City = $matches[1];
             $State = $matches[2];
             $Zip = $matches[3];
         }
     } else {
         $Address1 = "";
         $City = "";
         $State = "";
         $Zip = "";
     }
     $fullName = $patronDump['PATRN_NAME'];
     $nameParts = explode(', ', $fullName);
     $lastName = $nameParts[0];
     $secondName = isset($nameParts[1]) ? $nameParts[1] : '';
     if (strpos($secondName, ' ')) {
         $nameParts2 = explode(' ', $secondName);
         $firstName = $nameParts2[0];
     } else {
         $firstName = $secondName;
     }
     //Get additional information about the patron's home branch for display.
     $homeBranchCode = $patronDump['HOME_LIBR'];
     //Translate home branch to plain text
     global $user;
     $location = new Location();
     $location->whereAdd("code = '{$homeBranchCode}'");
     $location->find(1);
     if ($user) {
         if ($user->homeLocationId == 0) {
             $user->homeLocationId = $location->locationId;
             if ($location->nearbyLocation1 > 0) {
                 $user->myLocation1Id = $location->nearbyLocation1;
             } else {
                 $user->myLocation1Id = $location->locationId;
             }
             if ($location->nearbyLocation2 > 0) {
                 $user->myLocation2Id = $location->nearbyLocation2;
             } else {
                 $user->myLocation2Id = $location->locationId;
             }
             if ($user instanceof User) {
                 //Update the database
                 $user->update();
                 //Update the serialized instance stored in the session
                 $_SESSION['userinfo'] = serialize($user);
             }
         }
         //Get display name for preferred location 1
         $myLocation1 = new Location();
         $myLocation1->whereAdd("locationId = '{$user->myLocation1Id}'");
         $myLocation1->find(1);
         //Get display name for preferred location 1
         $myLocation2 = new Location();
         $myLocation2->whereAdd("locationId = '{$user->myLocation2Id}'");
         $myLocation2->find(1);
     }
     //see if expiration date is close
     list($monthExp, $dayExp, $yearExp) = explode("-", $patronDump['EXP_DATE']);
     $timeExpire = strtotime($monthExp . "/" . $dayExp . "/" . $yearExp);
     $timeNow = time();
     $timeToExpire = $timeExpire - $timeNow;
     if ($timeToExpire <= 30 * 24 * 60 * 60) {
         $expireClose = 1;
     } else {
         $expireClose = 0;
     }
     $finesVal = floatval(preg_replace('/[^\\d.]/', '', $patronDump['MONEY_OWED']));
     $numHoldsAvailable = 0;
     $numHoldsRequested = 0;
     $availableStatusRegex = isset($configArray['Catalog']['patronApiAvailableHoldsRegex']) ? $configArray['Catalog']['patronApiAvailableHoldsRegex'] : "/ST=(105|98),/";
     if (isset($patronDump['HOLD']) && count($patronDump['HOLD']) > 0) {
         foreach ($patronDump['HOLD'] as $hold) {
             if (preg_match("{$availableStatusRegex}", $hold)) {
                 $numHoldsAvailable++;
             } else {
                 $numHoldsRequested++;
             }
         }
     }
     $profile = array('lastname' => $lastName, 'firstname' => $firstName, 'fullname' => $fullName, 'address1' => $Address1, 'address2' => $City . ', ' . $State, 'city' => $City, 'state' => $State, 'zip' => $Zip, 'email' => isset($patronDump['EMAIL_ADDR']) ? $patronDump['EMAIL_ADDR'] : '', 'overdriveEmail' => $user ? $user->overdriveEmail : (isset($patronDump['EMAIL_ADDR']) ? $patronDump['EMAIL_ADDR'] : ''), 'promptForOverdriveEmail' => $user ? $user->promptForOverdriveEmail : 1, 'phone' => isset($patronDump['TELEPHONE']) ? $patronDump['TELEPHONE'] : '', 'fines' => $patronDump['MONEY_OWED'], 'finesval' => $finesVal, 'expires' => $patronDump['EXP_DATE'], 'expireclose' => $expireClose, 'homeLocationCode' => trim($homeBranchCode), 'homeLocationId' => $location->locationId, 'homeLocation' => $location->displayName, 'myLocation1Id' => $user ? $user->myLocation1Id : -1, 'myLocation1' => isset($myLocation1) ? $myLocation1->displayName : '', 'myLocation2Id' => $user ? $user->myLocation2Id : -1, 'myLocation2' => isset($myLocation2) ? $myLocation2->displayName : '', 'numCheckedOut' => $patronDump['CUR_CHKOUT'], 'numHolds' => isset($patronDump['HOLD']) ? count($patronDump['HOLD']) : 0, 'numHoldsAvailable' => $numHoldsAvailable, 'numHoldsRequested' => $numHoldsRequested, 'bypassAutoLogout' => $user ? $user->bypassAutoLogout : 0, 'ptype' => $patronDump['P_TYPE'], 'notices' => $patronDump['NOTICE_PREF'], 'web_note' => isset($patronDump['WEB_NOTE']) ? $patronDump['WEB_NOTE'] : '');
     //Get eContent info as well
     require_once ROOT_DIR . '/Drivers/EContentDriver.php';
     $eContentDriver = new EContentDriver();
     $eContentAccountSummary = $eContentDriver->getAccountSummary();
     $profile = array_merge($profile, $eContentAccountSummary);
     //Get a count of the materials requests for the user
     if ($user) {
         $materialsRequest = new MaterialsRequest();
         $materialsRequest->createdBy = $user->id;
         $homeLibrary = Library::getPatronHomeLibrary();
         $statusQuery = new MaterialsRequestStatus();
         $statusQuery->isOpen = 1;
         $statusQuery->libraryId = $homeLibrary->libraryId;
         $materialsRequest->joinAdd($statusQuery);
         $materialsRequest->find();
         $profile['numMaterialsRequests'] = $materialsRequest->N;
     }
     $timer->logTime("Got Patron Profile");
     $this->patronProfiles[$patron['id']] = $profile;
     return $profile;
 }
Example #16
0
 function loginUser()
 {
     //Login the user.  Must be called via Post parameters.
     global $user;
     global $interface;
     $user = UserAccount::isLoggedIn();
     if (!$user || PEAR_Singleton::isError($user)) {
         $user = UserAccount::login();
         $interface->assign('user', $user);
         if (!$user || PEAR_Singleton::isError($user)) {
             return array('success' => false, 'message' => translate("Sorry that login information was not recognized, please try again."));
         }
     }
     $patronHomeBranch = Location::getUserHomeLocation();
     //Check to see if materials request should be activated
     require_once ROOT_DIR . '/sys/MaterialsRequest.php';
     return array('success' => true, 'name' => ucwords($user->firstname . ' ' . $user->lastname), 'phone' => $user->phone, 'email' => $user->email, 'homeLocation' => isset($patronHomeBranch) ? $patronHomeBranch->code : '', 'homeLocationId' => isset($patronHomeBranch) ? $patronHomeBranch->locationId : '', 'enableMaterialsRequest' => MaterialsRequest::enableMaterialsRequest(true));
 }
Example #17
0
    $analytics->setLanguage($interface->getLanguage());
    $analytics->setTheme($interface->getPrimaryTheme());
    $analytics->setMobile($interface->isMobile() ? 1 : 0);
    $analytics->setDevice(get_device_name());
    $analytics->setPhysicalLocation($physicalLocation);
    if ($user) {
        $analytics->setPatronType($user->patronType);
        $analytics->setHomeLocationId($user->homeLocationId);
    } else {
        $analytics->setPatronType('logged out');
        $analytics->setHomeLocationId(-1);
    }
}
//Determine whether or not materials request functionality should be enabled
require_once ROOT_DIR . '/sys/MaterialsRequest.php';
$interface->assign('enableMaterialsRequest', MaterialsRequest::enableMaterialsRequest());
// Process Authentication, must be done here so we can redirect based on user information
// immediately after logging in.
if ($user) {
    $interface->assign('user', $user);
    //Create a cookie for the user's home branch so we can sort holdings even if they logout.
    //Cookie expires in 1 week.
    setcookie('home_location', $user->homeLocationId, time() + 60 * 60 * 24 * 7, '/');
} else {
    if ($configArray['Authentication']['method'] == 'Shibboleth' && $module == 'MyResearch' || isset($_POST['username']) && isset($_POST['password']) && ($action != 'Account' && $module != 'AJAX')) {
        $user = UserAccount::login();
        if (PEAR_Singleton::isError($user)) {
            require_once ROOT_DIR . '/services/MyResearch/Login.php';
            Login::launch($user->getMessage());
            exit;
        }
Example #18
0
 public function getMyProfile($patron, $forceReload = false)
 {
     global $timer;
     global $configArray;
     /** @var Memcache $memCache */
     global $memCache;
     global $serverName;
     $memCacheProfileKey = "patronProfile_{$serverName}_";
     if (is_object($patron)) {
         $patron = get_object_vars($patron);
         $userId = $patron['id'];
         $patronUserName = $patron['username'];
         $memCacheProfileKey .= $patron['username'];
     } else {
         global $user;
         $userId = $user->id;
         $patronUserName = $user->username;
         $memCacheProfileKey .= $user->username;
     }
     if (!$forceReload && !isset($_REQUEST['reload'])) {
         $patronProfile = $memCache->get($memCacheProfileKey);
         if ($patronProfile) {
             $timer->logTime('Retrieved Cached Profile for Patron');
             return $patronProfile;
         }
     }
     global $user;
     if ($configArray['Catalog']['offline'] == true) {
         $fullName = $patron['cat_username'];
         $Address1 = "";
         $City = "";
         $State = "";
         $Zip = "";
         $Email = "";
         $finesVal = 0;
         $expireClose = false;
         $homeBranchCode = '';
         $numHoldsAvailable = '?';
         $numHoldsRequested = '?';
         if (!$user) {
             $user = new User();
             $user->username = $patronUserName;
             if ($user->find(true)) {
                 $location = new Location();
                 $location->locationId = $user->homeLocationId;
                 $location->find(1);
                 $homeBranchCode = $location->code;
             }
         }
     } else {
         //Load the raw information about the patron from web services
         if (isset(HorizonAPI::$sessionIdsForUsers[$userId])) {
             $sessionToken = HorizonAPI::$sessionIdsForUsers[$userId];
             // keys off username
         } else {
             //Log the user in
             $return = $this->loginViaWebService($patron['cat_username'], $patron['cat_password']);
             if (count($return) == 1) {
                 $userValid = $return[0];
             } else {
                 list($userValid, $sessionToken) = $return;
             }
             if (!$userValid) {
                 echo "No session id found for user";
                 return PEAR_Singleton::raiseError("Could not login to web service " . $return);
             }
         }
         $lookupMyAccountInfoResponse = $this->getWebServiceResponse($configArray['Catalog']['webServiceUrl'] . '/standard/lookupMyAccountInfo?clientID=' . $configArray['Catalog']['clientId'] . '&sessionToken=' . $sessionToken . '&includeAddressInfo=true&includeHoldInfo=true&includeBlockInfo=true&includeItemsOutInfo=true');
         if ($lookupMyAccountInfoResponse === false) {
             global $logger;
             $logger->log("Unable to login", PEAR_LOG_WARNING);
             return null;
         }
         if (isset($lookupMyAccountInfoResponse->AddressInfo)) {
             $Address1 = (string) $lookupMyAccountInfoResponse->AddressInfo->line1;
             if (isset($lookupMyAccountInfoResponse->AddressInfo->cityState)) {
                 $cityState = (string) $lookupMyAccountInfoResponse->AddressInfo->cityState;
                 list($City, $State) = explode(', ', $cityState);
             } else {
                 $City = "";
                 $State = "";
             }
             $Zip = (string) $lookupMyAccountInfoResponse->AddressInfo->postalCode;
             if (isset($lookupMyAccountInfoResponse->AddressInfo->email)) {
                 $Email = (string) $lookupMyAccountInfoResponse->AddressInfo->email;
             }
         } else {
             $Address1 = "";
             $City = "";
             $State = "";
             $Zip = "";
             $Email = '';
         }
         $fullName = $lookupMyAccountInfoResponse->name;
         //Get additional information about the patron's home branch for display.
         if (isset($lookupMyAccountInfoResponse->locationID)) {
             $homeBranchCode = trim((string) $lookupMyAccountInfoResponse->locationID);
             //Translate home branch to plain text
             $location = new Location();
             $location->code = $homeBranchCode;
             $location->find(1);
             if ($location->N == 0) {
                 unset($location);
             }
         }
         if ($user) {
             if ($user->homeLocationId == 0 && isset($location)) {
                 $user->homeLocationId = $location->locationId;
                 if ($location->nearbyLocation1 > 0) {
                     $user->myLocation1Id = $location->nearbyLocation1;
                 } else {
                     $user->myLocation1Id = $location->locationId;
                 }
                 if ($location->nearbyLocation2 > 0) {
                     $user->myLocation2Id = $location->nearbyLocation2;
                 } else {
                     $user->myLocation2Id = $location->locationId;
                 }
                 if ($user instanceof User) {
                     //Update the database
                     $user->update();
                     //Update the serialized instance stored in the session
                     $_SESSION['userinfo'] = serialize($user);
                 }
             } else {
                 if (isset($location) && $location->locationId != $user->homeLocationId) {
                     $user->homeLocationId = $location->locationId;
                     //Update the database
                     $user->update();
                     //Update the serialized instance stored in the session
                     $_SESSION['userinfo'] = serialize($user);
                 }
             }
         }
         //TODO: See if we can get information about card expiration date
         $expireClose = 0;
         $finesVal = 0;
         if (isset($lookupMyAccountInfoResponse->BlockInfo)) {
             foreach ($lookupMyAccountInfoResponse->BlockInfo as $block) {
                 // $block is a simplexml object with attribute info about currency, type casting as below seems to work for adding up. plb 3-27-2015
                 $fineAmount = (double) $block->balance;
                 $finesVal += $fineAmount;
             }
         }
         $numHoldsAvailable = 0;
         $numHoldsRequested = 0;
         if (isset($lookupMyAccountInfoResponse->HoldInfo)) {
             foreach ($lookupMyAccountInfoResponse->HoldInfo as $hold) {
                 if ($hold->status == 'FILLED') {
                     $numHoldsAvailable++;
                 } else {
                     $numHoldsRequested++;
                 }
             }
         }
     }
     if ($user) {
         //Get display name for preferred location 1
         $myLocation1 = new Location();
         $myLocation1->whereAdd("locationId = '{$user->myLocation1Id}'");
         $myLocation1->find(1);
         //Get display name for preferred location 1
         $myLocation2 = new Location();
         $myLocation2->whereAdd("locationId = '{$user->myLocation2Id}'");
         $myLocation2->find(1);
     }
     list($fullName, $lastName, $firstName) = $this->splitFullName($fullName);
     $profile = array('lastname' => $lastName, 'firstname' => $firstName, 'fullname' => $fullName, 'address1' => $Address1, 'address2' => $City . ', ' . $State, 'city' => $City, 'state' => $State, 'zip' => $Zip, 'email' => $user && $user->email ? $user->email : $Email, 'overdriveEmail' => $user ? $user->overdriveEmail : $Email, 'promptForOverdriveEmail' => $user ? $user->promptForOverdriveEmail : 1, 'phone' => isset($lookupMyAccountInfoResponse->phone) ? (string) $lookupMyAccountInfoResponse->phone : '', 'workPhone' => '', 'mobileNumber' => '', 'fines' => sprintf('$%01.2f', $finesVal), 'finesval' => $finesVal, 'expires' => '', 'expireclose' => $expireClose, 'homeLocationCode' => isset($homeBranchCode) ? trim($homeBranchCode) : '', 'homeLocationId' => isset($location) ? $location->locationId : 0, 'homeLocation' => isset($location) ? $location->displayName : '', 'myLocation1Id' => $user ? $user->myLocation1Id : -1, 'myLocation1' => isset($myLocation1) ? $myLocation1->displayName : '', 'myLocation2Id' => $user ? $user->myLocation2Id : -1, 'myLocation2' => isset($myLocation2) ? $myLocation2->displayName : '', 'numCheckedOut' => isset($lookupMyAccountInfoResponse->ItemsOutInfo) ? count($lookupMyAccountInfoResponse->ItemsOutInfo) : 0, 'numHolds' => $numHoldsAvailable + $numHoldsRequested, 'numHoldsAvailable' => $numHoldsAvailable, 'numHoldsRequested' => $numHoldsRequested, 'bypassAutoLogout' => $user ? $user->bypassAutoLogout : 0, 'ptype' => 0, 'notices' => '-', 'noticePreferenceLabel' => 'e-mail', 'web_note' => '');
     //Get eContent info as well
     require_once ROOT_DIR . '/Drivers/EContentDriver.php';
     $eContentDriver = new EContentDriver();
     $eContentAccountSummary = $eContentDriver->getAccountSummary();
     $profile = array_merge($profile, $eContentAccountSummary);
     require_once ROOT_DIR . '/Drivers/OverDriveDriverFactory.php';
     $overDriveDriver = OverDriveDriverFactory::getDriver();
     if ($overDriveDriver->isUserValidForOverDrive($user)) {
         $overDriveSummary = $overDriveDriver->getOverDriveSummary($user);
         $profile['numOverDriveCheckedOut'] = $overDriveSummary['numCheckedOut'];
         $profile['numOverDriveHoldsAvailable'] = $overDriveSummary['numAvailableHolds'];
         $profile['numOverDriveHoldsRequested'] = $overDriveSummary['numUnavailableHolds'];
         $profile['canUseOverDrive'] = true;
     } else {
         $profile['numOverDriveCheckedOut'] = 0;
         $profile['numOverDriveHoldsAvailable'] = 0;
         $profile['numOverDriveHoldsRequested'] = 0;
         $profile['canUseOverDrive'] = false;
     }
     $profile['numCheckedOutTotal'] = $profile['numCheckedOut'] + $profile['numOverDriveCheckedOut'] + $eContentAccountSummary['numEContentCheckedOut'];
     $profile['numHoldsAvailableTotal'] = $profile['numHoldsAvailable'] + $profile['numOverDriveHoldsAvailable'] + $eContentAccountSummary['numEContentAvailableHolds'];
     $profile['numHoldsRequestedTotal'] = $profile['numHoldsRequested'] + $profile['numOverDriveHoldsRequested'] + $eContentAccountSummary['numEContentUnavailableHolds'];
     $profile['numHoldsTotal'] = $profile['numHoldsAvailableTotal'] + $profile['numHoldsRequestedTotal'];
     //Get a count of the materials requests for the user
     if ($user) {
         $materialsRequest = new MaterialsRequest();
         $materialsRequest->createdBy = $user->id;
         $homeLibrary = Library::getPatronHomeLibrary();
         $statusQuery = new MaterialsRequestStatus();
         $statusQuery->isOpen = 1;
         $statusQuery->libraryId = $homeLibrary->libraryId;
         $materialsRequest->joinAdd($statusQuery);
         $materialsRequest->find();
         $profile['numMaterialsRequests'] = $materialsRequest->N;
     }
     $timer->logTime("Got Patron Profile");
     $memCache->set($memCacheProfileKey, $profile, 0, $configArray['Caching']['patron_profile']);
     return $profile;
 }
Example #19
0
 function loadDisplayOptions()
 {
     global $library;
     global $locationSingleton;
     global $configArray;
     $location = $locationSingleton->getActiveLocation();
     $showHoldButton = 1;
     $showHoldButtonInSearchResults = 1;
     $this->assign('logoLink', $configArray['Site']['path']);
     if (isset($library) && $library->useHomeLinkForLogo) {
         if (isset($location) && strlen($location->homeLink) > 0 && $location->homeLink != 'default') {
             $this->assign('logoLink', $location->homeLink);
         } elseif (isset($library) && strlen($library->homeLink) > 0 && $library->homeLink != 'default') {
             $this->assign('logoLink', $library->homeLink);
         }
     }
     if (isset($location) && strlen($location->homeLink) > 0 && $location->homeLink != 'default') {
         $this->assign('homeLink', $location->homeLink);
     } elseif (isset($library) && strlen($library->homeLink) > 0 && $library->homeLink != 'default') {
         $this->assign('homeLink', $library->homeLink);
     }
     if (isset($library)) {
         $this->assign('facebookLink', $library->facebookLink);
         $this->assign('twitterLink', $library->twitterLink);
         $this->assign('youtubeLink', $library->youtubeLink);
         $this->assign('instagramLink', $library->instagramLink);
         $this->assign('goodreadsLink', $library->goodreadsLink);
         $this->assign('generalContactLink', $library->generalContactLink);
         $this->assign('showLoginButton', $library->showLoginButton);
         $this->assign('showAdvancedSearchbox', $library->showAdvancedSearchbox);
         $this->assign('enablePurchaseLinks', count($library->getBookStores()) > 0);
         $this->assign('enablePospectorIntegration', $library->enablePospectorIntegration);
         $this->assign('showTagging', $library->showTagging);
         $this->assign('showRatings', $library->showRatings);
         $this->assign('show856LinksAsTab', $library->show856LinksAsTab);
         $this->assign('showSearchTools', $library->showSearchTools);
         $this->assign('showExpirationWarnings', $library->showExpirationWarnings);
         $this->assign('showSimilarTitles', $library->showSimilarTitles);
         $this->assign('showSimilarAuthors', $library->showSimilarAuthors);
         $this->assign('showItsHere', $library->showItsHere);
     } else {
         $this->assign('showLoginButton', 1);
         $this->assign('showAdvancedSearchbox', 1);
         $this->assign('enablePurchaseLinks', 1);
         $this->assign('enablePospectorIntegration', isset($configArray['Content']['Prospector']) && $configArray['Content']['Prospector'] == true ? 1 : 0);
         $this->assign('showTagging', 1);
         $this->assign('showRatings', 1);
         $this->assign('show856LinksAsTab', 1);
         $this->assign('showSearchTools', 1);
         $this->assign('showExpirationWarnings', 1);
         $this->assign('showSimilarTitles', 1);
         $this->assign('showSimilarAuthors', 1);
         $this->assign('showItsHere', 0);
     }
     if (isset($library) && $location != null) {
         $this->assign('showFavorites', $location->showFavorites && $library->showFavorites);
         $this->assign('showComments', $location->showComments && $library->showComments);
         $this->assign('showTextThis', $location->showTextThis && $library->showTextThis);
         $this->assign('showEmailThis', $location->showEmailThis && $library->showEmailThis);
         $this->assign('showStaffView', $location->showStaffView && $library->showStaffView);
         $this->assign('showShareOnExternalSites', $location->showShareOnExternalSites && $library->showShareOnExternalSites);
         $this->assign('showQRCode', $location->showQRCode && $library->showQRCode);
         $this->assign('showStaffView', $location->showStaffView && $library->showStaffView);
         $this->assign('showGoodReadsReviews', $location->showGoodReadsReviews && $library->showGoodReadsReviews);
         $showHoldButton = $location->showHoldButton == 1 && $library->showHoldButton == 1 ? 1 : 0;
         $showHoldButtonInSearchResults = $location->showHoldButton == 1 && $library->showHoldButtonInSearchResults == 1 ? 1 : 0;
         $this->assign('showSimilarTitles', $library->showSimilarTitles);
         $this->assign('showSimilarAuthors', $library->showSimilarAuthors);
     } else {
         if ($location != null) {
             $this->assign('showFavorites', $location->showFavorites);
             $this->assign('showComments', $location->showComments);
             $this->assign('showTextThis', $location->showTextThis);
             $this->assign('showEmailThis', $location->showEmailThis);
             $this->assign('showShareOnExternalSites', $location->showShareOnExternalSites);
             $this->assign('showStaffView', $location->showStaffView);
             $this->assign('showQRCode', $location->showQRCode);
             $this->assign('showStaffView', $location->showStaffView);
             $this->assign('showGoodReadsReviews', $location->showGoodReadsReviews);
             $showHoldButton = $location->showHoldButton;
         } else {
             if (isset($library)) {
                 $this->assign('showFavorites', $library->showFavorites);
                 $showHoldButton = $library->showHoldButton;
                 $showHoldButtonInSearchResults = $library->showHoldButtonInSearchResults;
                 $this->assign('showComments', $library->showComments);
                 $this->assign('showTextThis', $library->showTextThis);
                 $this->assign('showEmailThis', $library->showEmailThis);
                 $this->assign('showShareOnExternalSites', $library->showShareOnExternalSites);
                 $this->assign('showStaffView', $library->showStaffView);
                 $this->assign('showQRCode', $library->showQRCode);
                 $this->assign('showStaffView', $library->showStaffView);
                 $this->assign('showGoodReadsReviews', $library->showGoodReadsReviews);
             } else {
                 $this->assign('showFavorites', 1);
                 $this->assign('showComments', 1);
                 $this->assign('showTextThis', 1);
                 $this->assign('showEmailThis', 1);
                 $this->assign('showShareOnExternalSites', 1);
                 $this->assign('showQRCode', 1);
                 $this->assign('showStaffView', 1);
                 $this->assign('showGoodReadsReviews', 1);
             }
         }
     }
     if ($showHoldButton == 0) {
         $showHoldButtonInSearchResults = 0;
     }
     if ($library && $library->additionalCss) {
         $this->assign('additionalCss', $library->additionalCss);
     }
     if ($location != null && $location->additionalCss) {
         $this->assign('additionalCss', $location->additionalCss);
     }
     $this->assign('showHoldButton', $showHoldButton);
     $this->assign('showHoldButtonInSearchResults', $showHoldButtonInSearchResults);
     $this->assign('showNotInterested', true);
     $this->assign('librarySystemName', 'Marmot');
     if (isset($library)) {
         $this->assign('showRatings', $library->showRatings);
         $this->assign('allowPinReset', $library->allowPinReset);
         $this->assign('librarySystemName', $library->displayName);
         $this->assign('showLibraryHoursAndLocationsLink', $library->showLibraryHoursAndLocationsLink);
         //Check to see if we should just call it library location
         $numLocations = $library->getNumLocationsForLibrary();
         $this->assign('numLocations', $numLocations);
         if ($numLocations == 1) {
             $locationForLibrary = new Location();
             $locationForLibrary->libraryId = $library->libraryId;
             $locationForLibrary->find(true);
             $numHours = $locationForLibrary->getNumHours();
             $this->assign('numHours', $numHours);
         }
         $this->assign('showDisplayNameInHeader', $library->showDisplayNameInHeader);
         $this->assign('externalMaterialsRequestUrl', $library->externalMaterialsRequestUrl);
     } else {
         $this->assign('showLibraryHoursAndLocationsLink', 1);
         $this->assign('showRatings', 1);
         $this->assign('allowPinReset', 0);
         $this->assign('showDisplayNameInHeader', 0);
     }
     if ($location != null) {
         $this->assign('showDisplayNameInHeader', $location->showDisplayNameInHeader);
         $this->assign('librarySystemName', $location->displayName);
     }
     //Determine whether or not materials request functionality should be enabled
     require_once ROOT_DIR . '/sys/MaterialsRequest.php';
     $this->assign('enableMaterialsRequest', MaterialsRequest::enableMaterialsRequest());
     //Load library links
     if (isset($library)) {
         $links = $library->libraryLinks;
         $libraryLinks = array();
         foreach ($links as $libraryLink) {
             if (!array_key_exists($libraryLink->category, $libraryLinks)) {
                 $libraryLinks[$libraryLink->category] = array();
             }
             $libraryLinks[$libraryLink->category][$libraryLink->linkText] = $libraryLink->url;
         }
         $this->assign('libraryLinks', $libraryLinks);
         $topLinks = $library->libraryTopLinks;
         $this->assign('topLinks', $topLinks);
     }
 }
Example #20
0
 function launch()
 {
     global $configArray;
     global $interface;
     global $user;
     //Load status information
     $materialsRequestStatus = new MaterialsRequestStatus();
     $materialsRequestStatus->orderBy('isDefault DESC, isOpen DESC, description ASC');
     if ($user->hasRole('library_material_requests')) {
         $homeLibrary = Library::getPatronHomeLibrary();
         $materialsRequestStatus->libraryId = $homeLibrary->libraryId;
     }
     $materialsRequestStatus->find();
     $availableStatuses = array();
     $defaultStatusesToShow = array();
     while ($materialsRequestStatus->fetch()) {
         $availableStatuses[$materialsRequestStatus->id] = $materialsRequestStatus->description;
         if ($materialsRequestStatus->isOpen == 1 || $materialsRequestStatus->isDefault == 1) {
             $defaultStatusesToShow[] = $materialsRequestStatus->id;
         }
     }
     $interface->assign('availableStatuses', $availableStatuses);
     if (isset($_REQUEST['statusFilter'])) {
         $statusesToShow = $_REQUEST['statusFilter'];
     } else {
         $statusesToShow = $defaultStatusesToShow;
     }
     $interface->assign('statusFilter', $statusesToShow);
     //Get a list of users that have requests open
     $materialsRequest = new MaterialsRequest();
     $materialsRequest->joinAdd(new User());
     $materialsRequest->joinAdd(new MaterialsRequestStatus());
     $materialsRequest->selectAdd();
     $materialsRequest->selectAdd('COUNT(materials_request.id) as numRequests');
     $materialsRequest->selectAdd('user.id as userId, status, description, user.firstName, user.lastName, user.cat_username, user.cat_password');
     if ($user->hasRole('library_material_requests')) {
         //Need to limit to only requests submitted for the user's home location
         $userHomeLibrary = Library::getPatronHomeLibrary();
         $locations = new Location();
         $locations->libraryId = $userHomeLibrary->libraryId;
         $locations->find();
         $locationsForLibrary = array();
         while ($locations->fetch()) {
             $locationsForLibrary[] = $locations->locationId;
         }
         $materialsRequest->whereAdd('user.homeLocationId IN (' . implode(', ', $locationsForLibrary) . ')');
     }
     $statusSql = "";
     foreach ($statusesToShow as $status) {
         if (strlen($statusSql) > 0) {
             $statusSql .= ",";
         }
         $statusSql .= "'" . $materialsRequest->escape($status) . "'";
     }
     $materialsRequest->whereAdd("status in ({$statusSql})");
     $materialsRequest->groupBy('userId, status');
     $materialsRequest->find();
     $userData = array();
     while ($materialsRequest->fetch()) {
         if (!array_key_exists($materialsRequest->userId, $userData)) {
             $userData[$materialsRequest->userId] = array();
             $userData[$materialsRequest->userId]['firstName'] = $materialsRequest->firstName;
             $userData[$materialsRequest->userId]['lastName'] = $materialsRequest->lastName;
             $barcodeProperty = $configArray['Catalog']['barcodeProperty'];
             $userData[$materialsRequest->userId]['barcode'] = $materialsRequest->{$barcodeProperty};
             $userData[$materialsRequest->userId]['totalRequests'] = 0;
             $userData[$materialsRequest->userId]['requestsByStatus'] = array();
         }
         $userData[$materialsRequest->userId]['requestsByStatus'][$materialsRequest->description] = $materialsRequest->numRequests;
         $userData[$materialsRequest->userId]['totalRequests'] += $materialsRequest->numRequests;
     }
     $interface->assign('userData', $userData);
     //Get a list of all of the statuses that will be shown
     $statuses = array();
     foreach ($userData as $userInfo) {
         foreach ($userInfo['requestsByStatus'] as $status => $numRequests) {
             $statuses[$status] = translate($status);
         }
     }
     $interface->assign('statuses', $statuses);
     //Check to see if we are exporting to Excel
     if (isset($_REQUEST['exportToExcel'])) {
         $this->exportToExcel($userData, $statuses);
     }
     $interface->setTemplate('userReport.tpl');
     $interface->setPageTitle('Materials Request User Report');
     $interface->assign('sidebar', 'MyAccount/account-sidebar.tpl');
     $interface->display('layout.tpl');
 }
Example #21
0
 function __construct()
 {
     global $interface;
     global $configArray;
     global $user;
     $interface->assign('page_body_style', 'sidebar_left');
     $interface->assign('ils', $configArray['Catalog']['ils']);
     if ($this->requireLogin && !UserAccount::isLoggedIn()) {
         require_once 'Login.php';
         Login::launch();
         exit;
     }
     //$interface->assign('userNoticeFile', 'MyResearch/listNotice.tpl');
     // Setup Search Engine Connection
     $class = $configArray['Index']['engine'];
     $this->db = new $class($configArray['Index']['url']);
     if ($configArray['System']['debugSolr']) {
         $this->db->debug = true;
     }
     // Connect to Database
     $this->catalog = new CatalogConnection($configArray['Catalog']['driver']);
     // Register Library Catalog Account
     if (isset($_POST['submit']) && !empty($_POST['submit'])) {
         if ($this->catalog && isset($_POST['cat_username']) && isset($_POST['cat_password'])) {
             $result = $this->catalog->patronLogin($_POST['cat_username'], $_POST['cat_password']);
             if ($result && !PEAR_Singleton::isError($result)) {
                 $user->cat_username = $_POST['cat_username'];
                 $user->cat_password = $_POST['cat_password'];
                 $user->update();
                 UserAccount::updateSession($user);
                 $interface->assign('user', $user);
             } else {
                 $interface->assign('loginError', 'Invalid Patron Login');
             }
         }
     }
     //Determine whether or not materials request functionality should be enabled
     $interface->assign('enableMaterialsRequest', MaterialsRequest::enableMaterialsRequest());
     //Check to see if we have any acs or single use eContent in the catalog
     //to enable the holds and wishlist appropriately
     if (isset($configArray['EContent']['hasProtectedEContent'])) {
         $interface->assign('hasProtectedEContent', $configArray['EContent']['hasProtectedEContent']);
     } else {
         $interface->assign('hasProtectedEContent', false);
     }
     global $library;
     if (isset($library)) {
         $interface->assign('showFavorites', $library->showFavorites);
         $interface->assign('showRatings', $library->showRatings);
         $interface->assign('showComments', $library->showComments);
     } else {
         $interface->assign('showFavorites', 1);
         $interface->assign('showRatings', 1);
         $interface->assign('showComments', 1);
     }
     //This code is also in Search/History since that page displays in the My Account menu as well.
     //It is also in MyList.php and Admin.php
     if ($user !== false) {
         $interface->assign('user', $user);
         // Get My Profile
         if ($this->catalog->status) {
             if ($user->cat_username) {
                 $patron = $this->catalog->patronLogin($user->cat_username, $user->cat_password);
                 if (PEAR_Singleton::isError($patron)) {
                     PEAR_Singleton::raiseError($patron);
                 }
                 $profile = $this->catalog->getMyProfile($patron);
                 //global $logger;
                 //$logger->log("Patron profile phone number in MyResearch = " . $profile['phone'], PEAR_LOG_INFO);
                 if (!PEAR_Singleton::isError($profile)) {
                     $interface->assign('profile', $profile);
                 }
             }
         }
         //Figure out if we should show a link to classic opac to pay holds.
         $ecommerceLink = $configArray['Site']['ecommerceLink'];
         $homeLibrary = Library::getLibraryForLocation($user->homeLocationId);
         if (strlen($ecommerceLink) > 0 && isset($homeLibrary) && $homeLibrary->showEcommerceLink == 1) {
             $interface->assign('showEcommerceLink', true);
             $interface->assign('minimumFineAmount', $homeLibrary->minimumFineAmount);
             if ($homeLibrary->payFinesLink == 'default') {
                 $interface->assign('ecommerceLink', $ecommerceLink);
             } else {
                 $interface->assign('ecommerceLink', $homeLibrary->payFinesLink);
             }
             $interface->assign('payFinesLinkText', $homeLibrary->payFinesLinkText);
         } else {
             $interface->assign('showEcommerceLink', false);
             $interface->assign('minimumFineAmount', 0);
         }
         //Load a list of lists
         $lists = array();
         if ($user->disableRecommendations == 0) {
             $lists[] = array('name' => 'Recommended For You', 'url' => '/MyResearch/SuggestedTitles', 'id' => 'suggestions');
         }
         $tmpList = new User_list();
         $tmpList->user_id = $user->id;
         $tmpList->orderBy("title ASC");
         $tmpList->find();
         if ($tmpList->N > 0) {
             while ($tmpList->fetch()) {
                 $lists[$tmpList->id] = array('name' => $tmpList->title, 'url' => '/MyResearch/MyList/' . $tmpList->id, 'id' => $tmpList->id);
             }
         } else {
             $lists[-1] = array('name' => "My Favorites", 'url' => '/MyResearch/MyList/-1', 'id' => -1);
         }
         $interface->assign('lists', $lists);
         // Get My Tags
         $tagList = $user->getTags();
         $interface->assign('tagList', $tagList);
     }
 }