Exemplo n.º 1
0
 /**
  * Load a saved search, if appropriate and legal; assign an error to the
  * interface if necessary.
  *
  * @return mixed Search Object on successful load, false otherwise
  * @access private
  */
 private function _loadSavedSearch()
 {
     global $interface;
     // Are we editing an existing search?
     if (isset($_REQUEST['edit'])) {
         // Go find it
         $search = new SearchEntry();
         $search->id = $_REQUEST['edit'];
         if ($search->find(true)) {
             // Check permissions
             if ($search->session_id == session_id() || $search->user_id == $user->id) {
                 // Retrieve the search details
                 $minSO = unserialize($search->search_object);
                 $savedSearch = SearchObjectFactory::deminify($minSO);
                 // Make sure it's an advanced search
                 if ($savedSearch->getSearchType() == 'MetaLibAdvanced') {
                     // Activate facets so we get appropriate descriptions
                     // in the filter list:
                     $savedSearch->activateAllFacets();
                     return $savedSearch;
                 } else {
                     $interface->assign('editErr', 'notAdvanced');
                 }
             } else {
                 // No permissions
                 $interface->assign('editErr', 'noRights');
             }
         } else {
             // Not found
             $interface->assign('editErr', 'notFound');
         }
     }
     return false;
 }
Exemplo n.º 2
0
 /**
  * Call the expiration code to clean up old saved searches in the database.
  *
  * @return void
  * @access public
  */
 public function deleteExpiredSearches()
 {
     global $interface;
     include_once 'services/MyResearch/lib/Search.php';
     // Use passed-in value as expiration age, or default to 2.
     $daysOld = isset($_REQUEST['daysOld']) ? intval($_REQUEST['daysOld']) : 2;
     // Fail if we have an invalid expiration age.
     if ($daysOld < 2) {
         $interface->assign('status', "Expiration age must be at least two days.");
     } else {
         // Delete the expired searches -- this cleans up any junk left in the
         // database from old search histories that were not caught by the
         // session garbage collector.
         $search = new SearchEntry();
         $expired = $search->getExpiredSearches($daysOld);
         if (empty($expired)) {
             $interface->assign('status', "No expired searches to delete.");
         } else {
             $count = 0;
             while (!empty($expired)) {
                 $count += count($expired);
                 foreach ($expired as $oldSearch) {
                     $oldSearch->delete();
                 }
                 $expired = $search->getExpiredSearches($daysOld);
             }
             $interface->assign('status', "{$count} expired searches deleted.");
         }
     }
     $interface->setTemplate('maintenance.tpl');
     $interface->setPageTitle('System Maintenance');
     $interface->display('layout-admin.tpl');
 }
Exemplo n.º 3
0
 /**
  * Delete a search from the database
  *
  * @param SearchEntry $search
  */
 private function deleteSearch($search)
 {
     if ($search->saved != 0) {
         $search->saved = 0;
         $search->update();
     }
 }
Exemplo n.º 4
0
 /**
  * Process parameters and display the page.
  *
  * @return void
  * @access public
  */
 public function launch()
 {
     global $interface;
     global $configArray;
     global $user;
     if (isset($_REQUEST['delete']) && $_REQUEST['delete']) {
         $todo = '_deleteSearch';
         $searchId = $_REQUEST['delete'];
     }
     // If for some strange reason the user tries
     //    to do both, just focus on the save.
     if (isset($_REQUEST['save']) && $_REQUEST['save']) {
         $todo = '_addSearch';
         $searchId = $_REQUEST['save'];
     }
     $search = new SearchEntry();
     $search->id = $searchId;
     if ($search->find(true)) {
         // Found, make sure this is a search from this user
         if ($search->session_id == session_id() || $search->user_id == $user->id) {
             // Call whichever function is required below
             $this->{$todo}($search);
         }
     }
     // If we are in "edit history" mode, stay in Search History:
     if (isset($_REQUEST['mode']) && $_REQUEST['mode'] == 'history') {
         header("Location: " . $configArray['Site']['url'] . "/Search/History");
     } else {
         // If the ID wasn't found, or some other error occurred, nothing will
         //   have processed by now, let the error handling on the display
         //   screen take care of it.
         header("Location: " . $configArray['Site']['url'] . "/Search/Results?saved={$searchId}");
     }
 }
Exemplo n.º 5
0
 /**
  * Process parameters and remove the subscription.
  *
  * @return void
  * @access public
  */
 public function launch()
 {
     global $interface;
     global $configArray;
     if (!isset($_REQUEST['id']) || !isset($_REQUEST['key']) || !isset($_REQUEST['type'])) {
         PEAR::raiseError('Can\'t unsubscribe');
         return;
     }
     $id = $_REQUEST['id'];
     $key = $_REQUEST['key'];
     $type = $_REQUEST['type'];
     // display confirm dialog
     if (!isset($_REQUEST['confirm']) || !$_REQUEST['confirm']) {
         $params = array('id' => $id, 'type' => $type, 'key' => $key, 'confirm' => true);
         $unsubscribeUrl = $configArray['Site']['url'] . '/MyResearch/Unsubscribe?' . http_build_query($params);
         $interface->assign('unsubscribeUrl', $unsubscribeUrl);
         $interface->setTemplate('unsubscribe.tpl');
         $interface->display('layout.tpl');
     } else {
         $success = false;
         // scheduled alert
         if ($type == 'alert') {
             $search = new SearchEntry();
             if ($search->get($id)) {
                 $user = new User();
                 if ($user->get($search->user_id)) {
                     $secret = $this->_getSecret($user, $id);
                     if ($key === $secret) {
                         $search->schedule = 0;
                         $search->update();
                         $success = true;
                     }
                 }
             }
         } else {
             if ($type == 'reminder') {
                 // due date reminder
                 $user = new User();
                 if ($user->get($id)) {
                     $secret = $this->_getSecret($user, $id);
                     if ($key === $secret) {
                         $user->due_date_reminder = 0;
                         $user->update();
                         $success = true;
                     }
                 }
             }
         }
         if ($success) {
             $interface->assign('success', true);
             $interface->setTemplate('unsubscribe.tpl');
             $interface->display('layout.tpl');
         } else {
             PEAR::raiseError('Can\'t unsubscribe');
         }
     }
 }
Exemplo n.º 6
0
 function launch()
 {
     global $configArray;
     global $interface;
     global $user;
     $source = $_REQUEST['source'];
     $sourceId = $_REQUEST['id'];
     $existingWidget = isset($_REQUEST['widgetId']) ? $_REQUEST['widgetId'] : -1;
     $widgetName = isset($_REQUEST['widgetName']) ? $_REQUEST['widgetName'] : '';
     if ($existingWidget == -1) {
         $widget = new ListWidget();
         $widget->name = $widgetName;
         if ($user->hasRole('libraryAdmin') || $user->hasRole('contentEditor')) {
             //Get all widgets for the library
             $userLibrary = Library::getPatronHomeLibrary();
             $widget->libraryId = $userLibrary->libraryId;
         } else {
             $widget->libraryId = -1;
         }
         $widget->customCss = '';
         $widget->autoRotate = 0;
         $widget->description = '';
         $widget->showTitleDescriptions = 1;
         $widget->onSelectCallback = '';
         $widget->fullListLink = '';
         $widget->listDisplayType = 'tabs';
         $widget->showMultipleTitles = 1;
         $widget->insert();
     } else {
         $widget = new ListWidget();
         $widget->id = $existingWidget;
         $widget->find(true);
     }
     //Make sure to save the search
     if ($source == 'search') {
         $searchObject = new SearchEntry();
         $searchObject->id = $sourceId;
         $searchObject->find(true);
         $searchObject->saved = 1;
         $searchObject->update();
     }
     //Add the list to the widget
     $widgetList = new ListWidgetList();
     $widgetList->listWidgetId = $widget->id;
     $widgetList->displayFor = 'all';
     $widgetList->source = "{$source}:{$sourceId}";
     $widgetList->name = $widgetName;
     $widgetList->weight = 0;
     $widgetList->insert();
     //Redirect to the widget
     header("Location: {$path}/Admin/ListWidgets?objectAction=view&id={$widget->id}");
 }
Exemplo n.º 7
0
 public static function destroy($sess_id)
 {
     // Delete the searches stored for this session
     $search = new SearchEntry();
     $searchList = $search->getSearches($sess_id);
     // Make sure there are some
     if (count($searchList) > 0) {
         foreach ($searchList as $oldSearch) {
             // And make sure they aren't saved
             if ($oldSearch->saved == 0) {
                 $oldSearch->delete();
             }
         }
     }
 }
Exemplo n.º 8
0
 /**
  * Get an array of SearchEntry objects representing expired, unsaved searches.
  *
  * @access	public
  * @param	 int				 $daysOld				Age in days of an "expired" search.
  * @return	array											 Matching SearchEntry objects.
  */
 function getExpiredSearches($daysOld = 2)
 {
     // Determine the expiration date:
     $expirationDate = date('Y-m-d', time() - $daysOld * 24 * 60 * 60);
     // Find expired, unsaved searches:
     $sql = 'SELECT * FROM search WHERE saved=0 AND created<"' . $expirationDate . '"';
     $s = new SearchEntry();
     $s->query($sql);
     $searches = array();
     if ($s->N) {
         while ($s->fetch()) {
             $searches[] = clone $s;
         }
     }
     return $searches;
 }
Exemplo n.º 9
0
 /**
  * Anonymize user account by updating username to a random string 
  * and setting other user object fields (besides id) to their default values.
  * User comments are preserved. Catalog accounts, due date reminders, 
  * saved searches and lists are deleted.
  * 
  * @return boolean True on success
  */
 public function anonymizeAccount()
 {
     $conn = $this->getDatabaseConnection();
     $res = $conn->query("START TRANSACTION");
     try {
         // Delete catalog accounts
         $account = new User_account();
         $account->user_id = $this->id;
         if ($account->find(false)) {
             while ($account->fetch()) {
                 $account->delete();
             }
         }
         // Delete due date reminders
         $reminder = new Due_date_reminder();
         $reminder->user_id = $this->id;
         if ($reminder->find(false)) {
             while ($reminder->fetch()) {
                 $reminder->delete();
             }
         }
         // Delete lists (linked user_resource objects cascade)
         $list = new User_list();
         $list->user_id = $this->id;
         if ($list->find(false)) {
             while ($list->fetch()) {
                 $list->delete();
             }
         }
         // Delete saved searches
         $search = new SearchEntry();
         $search->user_id = $this->id;
         if ($search->find(false)) {
             while ($search->fetch()) {
                 $search->delete();
             }
         }
         // Anonymize user object
         $this->username = '******' . uniqid();
         $this->password = '';
         $this->firstname = '';
         $this->lastname = '';
         $this->email = '';
         $this->cat_username = '******';
         $this->cat_password = '******';
         $this->college = '';
         $this->major = '';
         $this->home_library = '';
         $this->language = '';
         $this->due_date_notification = 0;
         $this->due_date_reminder = 0;
         $this->authMethod = 'null';
         $this->update();
     } catch (Exception $e) {
         $conn->query("ROLLBACK");
         throw $e;
         return false;
     }
     $conn->query("COMMIT");
     return true;
 }
Exemplo n.º 10
0
 /**
  * Get an array of SearchEntry objects representing expired, unsaved searches.
  *
  * @param int $daysOld Age in days of an "expired" search.
  *
  * @return array       Matching SearchEntry objects.
  * @access public
  */
 public function getExpiredSearches($daysOld = 2)
 {
     // Determine the expiration date:
     $expireDate = date('Y-m-d', time() - $daysOld * 24 * 60 * 60);
     // Find expired, unsaved searches:
     $sql = 'SELECT * FROM "search" WHERE "saved"=0 AND "created"<' . "'{$expireDate}' LIMIT 0,10000";
     $s = new SearchEntry();
     $s->query($sql);
     $searches = array();
     if ($s->N) {
         while ($s->fetch()) {
             $searches[] = clone $s;
         }
     }
     return $searches;
 }
Exemplo n.º 11
0
 /**
  * Send scheduled alerts
  *
  * @return void
  */
 public function send()
 {
     global $configArray;
     global $interface;
     global $translator;
     $iso8601 = 'Y-m-d\\TH:i:s\\Z';
     ini_set('display_errors', true);
     $configArray = $mainConfig = readConfig();
     $datasourceConfig = getExtraConfigArray('datasources');
     $siteLocal = $configArray['Site']['local'];
     // Set up time zone. N.B. Don't use msg() or other functions requiring date before this.
     date_default_timezone_set($configArray['Site']['timezone']);
     $this->msg('Sending scheduled alerts');
     // Setup Local Database Connection
     ConnectionManager::connectToDatabase();
     // Initialize Mailer
     $mailer = new VuFindMailer();
     // Find all scheduled alerts
     $sql = 'SELECT * FROM "search" WHERE "schedule" > 0 ORDER BY user_id';
     $s = new SearchEntry();
     $s->query($sql);
     $this->msg('Processing ' . $s->N . ' searches');
     $user = false;
     $interface = false;
     $institution = false;
     $todayTime = new DateTime();
     while ($s->fetch()) {
         $lastTime = new DateTime($s->last_executed);
         if ($s->schedule == 1) {
             // Daily
             if ($todayTime->format('Y-m-d') == $lastTime->format('Y-m-d')) {
                 $this->msg('Bypassing search ' . $s->id . ': previous execution too recent (daily, ' . $lastTime->format($iso8601) . ')');
                 continue;
             }
         } elseif ($s->schedule == 2) {
             // Weekly
             $diff = $todayTime->diff($lastTime);
             if ($diff->days < 6) {
                 $this->msg('Bypassing search ' . $s->id . ': previous execution too recent (weekly, ' . $lastTime->format($iso8601) . ')');
                 continue;
             }
         } else {
             $this->msg('Search ' . $s->id . ': unknown schedule: ' . $s->schedule);
             continue;
         }
         if ($user === false || $s->user_id != $user->id) {
             $user = User::staticGet($s->user_id);
         }
         if (!$user->email || trim($user->email) == '') {
             $this->msg('User ' . $user->username . ' does not have an email address, bypassing alert ' . $s->id);
             continue;
         }
         $userInstitution = reset(explode(':', $user->username, 2));
         if (!$institution || $institution != $userInstitution) {
             $institution = $userInstitution;
             if (!isset($datasourceConfig[$institution])) {
                 foreach ($datasourceConfig as $code => $values) {
                     if (isset($values['institution']) && strcasecmp($values['institution'], $institution) == 0) {
                         $institution = $code;
                         break;
                     }
                 }
             }
             if (!($configArray = $this->readInstitutionConfig($institution))) {
                 continue;
             }
             $configArray['Site']['url'] = $s->schedule_base_url;
             // Start Interface
             $interface = new UInterface($siteLocal);
             $validLanguages = array_keys($configArray['Languages']);
             $dateFormat = new VuFindDate();
         }
         $language = $user->language;
         if (!in_array($user->language, $validLanguages)) {
             $language = $configArray['Site']['language'];
         }
         $translator = new I18N_Translator(array($configArray['Site']['local'] . '/lang', $configArray['Site']['local'] . '/lang_local'), $language, $configArray['System']['debug']);
         $interface->setLanguage($language);
         $minSO = unserialize($s->search_object);
         // Check minified search object type
         $searchObject = SearchObjectFactory::deminify($minSO);
         if (!$searchObject instanceof SearchObject_Solr) {
             $this->msg('Search ' . $s->id . ': search object type not supported');
             continue;
         }
         // Create a new search object to avoid cached defaults for e.g.
         // hidden filters.
         $searchObject = SearchObjectFactory::initSearchObject();
         $searchObject->deminify($minSO);
         $searchObject->setSort('first_indexed desc');
         $searchTime = time();
         $searchDate = gmdate($iso8601, time());
         $searchObject->setLimit(50);
         $searchObject->disableLogging();
         $results = $searchObject->processSearch();
         if (PEAR::isError($results)) {
             $this->msg('Search ' . $s->id . ' failed: ' . $results->getMessage());
             continue;
         }
         if ($searchObject->getResultTotal() < 1) {
             $this->msg('No results found for search ' . $s->id);
             continue;
         }
         $newestRecordDate = date($iso8601, strtotime($results['response']['docs'][0]['first_indexed']));
         $lastExecutionDate = $lastTime->format($iso8601);
         if ($newestRecordDate < $lastExecutionDate) {
             $this->msg('No new results for search ' . $s->id . ": {$newestRecordDate} < {$lastExecutionDate}");
         } else {
             $this->msg('New results for search ' . $s->id . ": {$newestRecordDate} >= {$lastExecutionDate}");
             $interface->assign('summary', $searchObject->getResultSummary());
             $interface->assign('searchDate', $dateFormat->convertToDisplayDate("U", floor($searchTime)));
             $interface->assign('lastSearchDate', $dateFormat->convertToDisplayDate("U", floor($lastTime->getTimestamp())));
             $records = array();
             foreach ($results['response']['docs'] as &$doc) {
                 $docDate = date($iso8601, strtotime($doc['first_indexed']));
                 if ($docDate < $lastExecutionDate) {
                     break;
                 }
                 $record = RecordDriverFactory::initRecordDriver($doc);
                 $records[] = $interface->fetch($record->getSearchResult('email'));
             }
             $interface->assign('recordSet', $records);
             $key = $this->getSecret($user, $s->id);
             $params = array('id' => $s->id, 'type' => 'alert', 'key' => $key);
             $unsubscribeUrl = $configArray['Site']['url'] . '/MyResearch/Unsubscribe?' . http_build_query($params);
             $interface->assign('info', array('time' => $dateFormat->convertToDisplayDate("U", floor($searchObject->getStartTime())), 'url' => $searchObject->renderSearchUrl(), 'searchId' => $searchObject->getSearchId(), 'description' => $searchObject->displayQuery(), 'filters' => $searchObject->getFilterList(), 'hits' => $searchObject->getResultTotal(), 'speed' => round($searchObject->getQuerySpeed(), 2) . "s", 'schedule' => $s->schedule, 'last_executed' => $s->last_executed, 'recordCount' => count($records), 'unsubscribeUrl' => $unsubscribeUrl));
             $searchObject->close();
             // Load template
             $message = $interface->fetch('MyResearch/alert-email.tpl');
             if (strstr($message, 'Warning: Smarty error:')) {
                 $this->msg("Message template processing failed: {$message}");
                 continue;
             }
             $result = $mailer->send($user->email, $configArray['Site']['email'], translate('Scheduled Alert Results'), $message);
             if (PEAR::isError($result)) {
                 $this->msg("Failed to send message to {$user->email}: " . $result->getMessage());
                 continue;
             }
         }
         // Update search date
         $s->changeLastExecuted($searchDate);
     }
     $this->reportErrors();
     $this->msg('Scheduled alerts execution completed');
 }
Exemplo n.º 12
0
 function deleteSavedSearch()
 {
     global $user;
     $searchId = $_REQUEST['searchId'];
     $search = new SearchEntry();
     $search->id = $searchId;
     $saveOk = false;
     if ($search->find(true)) {
         // Found, make sure this is a search from this user
         if ($search->session_id == session_id() || $search->user_id == $user->id) {
             if ($search->saved != 0) {
                 $search->saved = 0;
                 $saveOk = $search->update() !== FALSE;
                 $message = $saveOk ? "Your saved search was deleted successfully." : "Sorry, we could not delete that search for you.  It may have already been deleted.";
             } else {
                 $saveOk = true;
                 $message = "That search is not saved.";
             }
         } else {
             $message = "Sorry, it looks like that search does not belong to you.";
         }
     } else {
         $message = "Sorry, it looks like that search has expired.";
     }
     $result = array('result' => $saveOk, 'message' => $message);
     return $result;
 }
Exemplo n.º 13
0
 /**
  * Adds an object to the instance pool.
  *
  * Propel keeps cached copies of objects in an instance pool when they are retrieved
  * from the database.  In some cases -- especially when you override doSelect*()
  * methods in your stub classes -- you may need to explicitly add objects
  * to the cache in order to ensure that the same objects are always returned by doSelect*()
  * and retrieveByPK*() calls.
  *
  * @param      SearchEntry $value A SearchEntry object.
  * @param      string $key (optional) key to use for instance map (for performance boost if key was already calculated externally).
  */
 public static function addInstanceToPool(SearchEntry $obj, $key = null)
 {
     if (Propel::isInstancePoolingEnabled()) {
         if ($key === null) {
             $key = (string) $obj->getEntryId();
         }
         // if key === null
         self::$instances[$key] = $obj;
     }
 }
Exemplo n.º 14
0
 /**
  * Process incoming parameters and display the page.
  *
  * @return void
  * @access public
  */
 public function launch()
 {
     global $interface;
     global $user;
     // Assign the ID of the last search so the user can return to it.
     $interface->assign('lastsearch', isset($_SESSION['lastSearchURL']) ? $_SESSION['lastSearchURL'] : 'perkele');
     $dateFormat = new VuFindDate();
     // In some contexts, we want to require a login before showing search
     // history:
     if (isset($_REQUEST['require_login']) && !UserAccount::isLoggedIn()) {
         include_once 'services/MyResearch/Login.php';
         Login::launch();
         exit;
     }
     $interface->setPageTitle('Search History');
     // Retrieve search history
     $s = new SearchEntry();
     $searchHistory = $s->getSearches(session_id(), is_object($user) ? $user->id : null);
     if (count($searchHistory) > 0) {
         // Build an array of history entries
         $links = array();
         $saved = array();
         // Loop through the history
         foreach ($searchHistory as $search) {
             $size = strlen($search->search_object);
             $minSO = unserialize($search->search_object);
             $searchObject = SearchObjectFactory::deminify($minSO);
             // Make sure all facets are active so we get appropriate
             // descriptions in the filter box.
             $searchObject->activateAllFacets();
             $newItem = array('time' => $dateFormat->convertToDisplayDate("U", floor($searchObject->getStartTime())), 'url' => $searchObject->renderSearchUrl(), 'searchId' => $searchObject->getSearchId(), 'description' => $searchObject->displayQuery(), 'filters' => $searchObject->getFilterList(), 'hits' => number_format($searchObject->getResultTotal(), 0, ',', ' '), 'speed' => round($searchObject->getQuerySpeed(), 2) . "s", 'size' => round($size / 1024, 3) . "kb", 'schedule' => $search->schedule, 'last_executed' => $search->last_executed);
             // Saved searches
             if ($search->saved == 1) {
                 $saved[] = $newItem;
             } else {
                 // All the others...
                 // If this was a purge request we don't need this
                 if (isset($_REQUEST['purge']) && $_REQUEST['purge'] == 'true') {
                     $search->delete();
                     // We don't want to remember the last search after a purge:
                     unset($_SESSION['lastSearchURL']);
                     unset($_SESSION['lastSearchDisplayQuery']);
                 } else {
                     // Otherwise add to the list
                     $links[] = $newItem;
                 }
             }
         }
         // One final check, after a purge make sure we still have a history
         if (count($links) > 0 || count($saved) > 0) {
             $interface->assign('links', array_reverse($links));
             $interface->assign('saved', array_reverse($saved));
             $interface->assign('noHistory', false);
         } else {
             // Nothing left in history
             $interface->assign('noHistory', true);
         }
     } else {
         // No history
         $interface->assign('noHistory', true);
     }
     $interface->setTemplate('history.tpl');
     $interface->display('layout.tpl');
 }
Exemplo n.º 15
0
 public function getNextPrevLinks()
 {
     global $interface;
     global $timer;
     //Setup next and previous links based on the search results.
     if (isset($_REQUEST['searchId']) && isset($_REQUEST['recordIndex'])) {
         //rerun the search
         $s = new SearchEntry();
         $s->id = $_REQUEST['searchId'];
         $interface->assign('searchId', $_REQUEST['searchId']);
         $currentPage = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1;
         $interface->assign('page', $currentPage);
         $s->find();
         if ($s->N > 0) {
             $s->fetch();
             $minSO = unserialize($s->search_object);
             $searchObject = SearchObjectFactory::deminify($minSO);
             $searchObject->setPage($currentPage);
             //Run the search
             $result = $searchObject->processSearch(true, false, false);
             //Check to see if we need to run a search for the next or previous page
             $currentResultIndex = $_REQUEST['recordIndex'] - 1;
             $recordsPerPage = $searchObject->getLimit();
             $adjustedResultIndex = $currentResultIndex - $recordsPerPage * ($currentPage - 1);
             if ($currentResultIndex % $recordsPerPage == 0 && $currentResultIndex > 0) {
                 //Need to run a search for the previous page
                 $interface->assign('previousPage', $currentPage - 1);
                 $previousSearchObject = clone $searchObject;
                 $previousSearchObject->setPage($currentPage - 1);
                 $previousSearchObject->processSearch(true, false, false);
                 $previousResults = $previousSearchObject->getResultRecordSet();
             } else {
                 if (($currentResultIndex + 1) % $recordsPerPage == 0 && $currentResultIndex + 1 < $searchObject->getResultTotal()) {
                     //Need to run a search for the next page
                     $nextSearchObject = clone $searchObject;
                     $interface->assign('nextPage', $currentPage + 1);
                     $nextSearchObject->setPage($currentPage + 1);
                     $nextSearchObject->processSearch(true, false, false);
                     $nextResults = $nextSearchObject->getResultRecordSet();
                 }
             }
             if (PEAR_Singleton::isError($result)) {
                 //If we get an error excuting the search, just eat it for now.
             } else {
                 if ($searchObject->getResultTotal() < 1) {
                     //No results found
                 } else {
                     $recordSet = $searchObject->getResultRecordSet();
                     //Record set is 0 based, but we are passed a 1 based index
                     if ($currentResultIndex > 0) {
                         if (isset($previousResults)) {
                             $previousRecord = $previousResults[count($previousResults) - 1];
                         } else {
                             $previousId = $adjustedResultIndex - 1;
                             if (isset($recordSet[$previousId])) {
                                 $previousRecord = $recordSet[$previousId];
                             }
                         }
                         //Convert back to 1 based index
                         if (isset($previousRecord)) {
                             $interface->assign('previousIndex', $currentResultIndex - 1 + 1);
                             $interface->assign('previousTitle', $previousRecord['title_display']);
                             if (strpos($previousRecord['id'], 'econtentRecord') === 0) {
                                 $interface->assign('previousType', 'EcontentRecord');
                                 $interface->assign('previousId', str_replace('econtentRecord', '', $previousRecord['id']));
                             } elseif (strpos($previousRecord['id'], 'list') === 0) {
                                 $interface->assign('previousType', 'MyAccount/MyList');
                                 $interface->assign('previousId', str_replace('list', '', $previousRecord['id']));
                             } else {
                                 if ($previousRecord['recordtype'] == 'grouped_work') {
                                     $interface->assign('previousType', 'GroupedWork');
                                     $interface->assign('previousId', $previousRecord['id']);
                                 } else {
                                     $interface->assign('previousType', 'Record');
                                     $interface->assign('previousId', $previousRecord['id']);
                                 }
                             }
                         }
                     }
                     if ($currentResultIndex + 1 < $searchObject->getResultTotal()) {
                         if (isset($nextResults)) {
                             $nextRecord = $nextResults[0];
                         } else {
                             $nextRecordIndex = $adjustedResultIndex + 1;
                             if (isset($recordSet[$nextRecordIndex])) {
                                 $nextRecord = $recordSet[$nextRecordIndex];
                             }
                         }
                         //Convert back to 1 based index
                         $interface->assign('nextIndex', $currentResultIndex + 1 + 1);
                         if (isset($nextRecord)) {
                             $interface->assign('nextTitle', $nextRecord['title_display']);
                             if (strpos($nextRecord['id'], 'econtentRecord') === 0) {
                                 $interface->assign('nextType', 'EcontentRecord');
                                 $interface->assign('nextId', str_replace('econtentRecord', '', $nextRecord['id']));
                             } elseif (strpos($nextRecord['id'], 'list') === 0) {
                                 $interface->assign('nextType', 'MyAccount/MyList');
                                 $interface->assign('nextId', str_replace('list', '', $nextRecord['id']));
                             } else {
                                 if ($nextRecord['recordtype'] == 'grouped_work') {
                                     $interface->assign('nextType', 'GroupedWork');
                                     $interface->assign('nextId', $nextRecord['id']);
                                 } else {
                                     $interface->assign('nextType', 'Record');
                                     $interface->assign('nextId', $nextRecord['id']);
                                 }
                             }
                         }
                     }
                 }
             }
         }
         $timer->logTime('Got next/previous links');
     }
 }
Exemplo n.º 16
0
 /**
  * If there is a saved search being loaded through $_REQUEST, redirect to the
  * URL for that search.  If no saved search was requested, return false.  If
  * unable to load a requested saved search, return a PEAR_Error object.
  *
  * @return mixed Does not return on successful load, returns false if no search
  * to restore, returns PEAR_Error object in case of trouble.
  * @access protected
  */
 protected function restoreSavedSearch()
 {
     global $user;
     // Is this is a saved search?
     if (isset($_REQUEST['saved'])) {
         // Yes, retrieve it
         $search = new SearchEntry();
         $search->id = $_REQUEST['saved'];
         if ($search->find(true)) {
             // Found, make sure the user has the
             //   rights to view this search
             if ($search->session_id == session_id() || $search->user_id == $user->id) {
                 // They do, deminify it to a new object.
                 $minSO = unserialize($search->search_object);
                 $savedSearch = SearchObjectFactory::deminify($minSO);
                 // Now redirect to the URL associated with the saved search;
                 // this simplifies problems caused by mixing different classes
                 // of search object, and it also prevents the user from ever
                 // landing on a "?saved=xxxx" URL, which may not persist beyond
                 // the current session.  (We want all searches to be
                 // persistent and bookmarkable).
                 header('Location: ' . $savedSearch->renderSearchUrl());
                 die;
             } else {
                 // They don't
                 // TODO : Error handling -
                 //    User is trying to view a saved search from
                 //    another session (deliberate or expired) or
                 //    associated with another user.
                 return new PEAR_Error("Attempt to access invalid search ID");
             }
         }
     }
     // Report no saved search to restore.
     return false;
 }
Exemplo n.º 17
0
 function __construct($subAction = false, $record_id = null)
 {
     global $interface;
     global $configArray;
     global $library;
     global $timer;
     global $user;
     //Check to see if a user is logged in with admin permissions
     if ($user && $user->hasRole('genealogyContributor')) {
         $interface->assign('userIsAdmin', true);
     } else {
         $interface->assign('userIsAdmin', false);
     }
     $searchSource = isset($_REQUEST['searchSource']) ? $_REQUEST['searchSource'] : 'local';
     //Load basic information needed in subclasses
     if ($record_id == null || !isset($record_id)) {
         $this->id = $_GET['id'];
     } else {
         $this->id = $record_id;
     }
     // Setup Search Engine Connection
     // Include Search Engine Class
     require_once ROOT_DIR . '/sys/' . $configArray['Genealogy']['engine'] . '.php';
     $timer->logTime('Include search engine');
     // Initialise from the current search globals
     $this->db = SearchObjectFactory::initSearchObject($configArray['Genealogy']['searchObject']);
     $this->db->init($searchSource);
     // Retrieve Full Marc Record
     if (!($record = $this->db->getRecord('person' . $this->id))) {
         PEAR_Singleton::raiseError(new PEAR_Error('Record Does Not Exist'));
     }
     $this->record = $record;
     //Load person from the database to get additional information
     $person = Person::staticGet('personId', $this->id);
     $record['picture'] = $person->picture;
     $interface->assign('record', $record);
     $interface->assign('person', $person);
     $this->recordDriver = RecordDriverFactory::initRecordDriver($record);
     $timer->logTime('Initialized the Record Driver');
     $marriages = array();
     $personMarriages = $person->marriages;
     if (isset($personMarriages)) {
         foreach ($personMarriages as $marriage) {
             $marriageArray = (array) $marriage;
             $marriageArray['formattedMarriageDate'] = $person->formatPartialDate($marriage->marriageDateDay, $marriage->marriageDateMonth, $marriage->marriageDateYear);
             $marriages[] = $marriageArray;
         }
     }
     $interface->assign('marriages', $marriages);
     $obituaries = array();
     $personObituaries = $person->obituaries;
     if (isset($personObituaries)) {
         foreach ($personObituaries as $obit) {
             $obitArray = (array) $obit;
             $obitArray['formattedObitDate'] = $person->formatPartialDate($obit->dateDay, $obit->dateMonth, $obit->dateYear);
             $obituaries[] = $obitArray;
         }
     }
     $interface->assign('obituaries', $obituaries);
     //Do actions needed if this is the main action.
     $interface->assign('id', $this->id);
     // Retrieve User Search History
     $interface->assign('lastsearch', isset($_SESSION['lastSearchURL']) ? $_SESSION['lastSearchURL'] : false);
     $this->cacheId = 'Person|' . $_GET['id'] . '|' . get_class($this);
     // Send down text for inclusion in breadcrumbs
     $interface->assign('breadcrumbText', $this->recordDriver->getBreadcrumb());
     $formattedBirthdate = $person->formatPartialDate($person->birthDateDay, $person->birthDateMonth, $person->birthDateYear);
     $interface->assign('birthDate', $formattedBirthdate);
     $formattedDeathdate = $person->formatPartialDate($person->deathDateDay, $person->deathDateMonth, $person->deathDateYear);
     $interface->assign('deathDate', $formattedDeathdate);
     //Setup next and previous links based on the search results.
     if (isset($_REQUEST['searchId'])) {
         //rerun the search
         $s = new SearchEntry();
         $s->id = $_REQUEST['searchId'];
         $interface->assign('searchId', $_REQUEST['searchId']);
         $currentPage = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1;
         $interface->assign('page', $currentPage);
         $s->find();
         if ($s->N > 0) {
             $s->fetch();
             $minSO = unserialize($s->search_object);
             $searchObject = SearchObjectFactory::deminify($minSO);
             $searchObject->setPage($currentPage);
             //Run the search
             $result = $searchObject->processSearch(true, false, false);
             //Check to see if we need to run a search for the next or previous page
             $currentResultIndex = $_REQUEST['recordIndex'] - 1;
             $recordsPerPage = $searchObject->getLimit();
             if ($currentResultIndex % $recordsPerPage == 0 && $currentResultIndex > 0) {
                 //Need to run a search for the previous page
                 $interface->assign('previousPage', $currentPage - 1);
                 $previousSearchObject = clone $searchObject;
                 $previousSearchObject->setPage($currentPage - 1);
                 $previousSearchObject->processSearch(true, false, false);
                 $previousResults = $previousSearchObject->getResultRecordSet();
             } else {
                 if (($currentResultIndex + 1) % $recordsPerPage == 0 && $currentResultIndex + 1 < $searchObject->getResultTotal()) {
                     //Need to run a search for the next page
                     $nextSearchObject = clone $searchObject;
                     $interface->assign('nextPage', $currentPage + 1);
                     $nextSearchObject->setPage($currentPage + 1);
                     $nextSearchObject->processSearch(true, false, false);
                     $nextResults = $nextSearchObject->getResultRecordSet();
                 }
             }
             if (PEAR_Singleton::isError($result)) {
                 //If we get an error excuting the search, just eat it for now.
             } else {
                 if ($searchObject->getResultTotal() < 1) {
                     //No results found
                 } else {
                     $recordSet = $searchObject->getResultRecordSet();
                     //Record set is 0 based, but we are passed a 1 based index
                     if ($currentResultIndex > 0) {
                         if (isset($previousResults)) {
                             $previousRecord = $previousResults[count($previousResults) - 1];
                         } else {
                             $previousRecord = $recordSet[$currentResultIndex - 1 - ($currentPage - 1) * $recordsPerPage];
                         }
                         $interface->assign('previousId', $previousRecord['id']);
                         //Convert back to 1 based index
                         $interface->assign('previousIndex', $currentResultIndex - 1 + 1);
                         $interface->assign('previousTitle', $previousRecord['title']);
                     }
                     if ($currentResultIndex + 1 < $searchObject->getResultTotal()) {
                         if (isset($nextResults)) {
                             $nextRecord = $nextResults[0];
                         } else {
                             $nextRecord = $recordSet[$currentResultIndex + 1 - ($currentPage - 1) * $recordsPerPage];
                         }
                         $interface->assign('nextId', $nextRecord['id']);
                         //Convert back to 1 based index
                         $interface->assign('nextIndex', $currentResultIndex + 1 + 1);
                         $interface->assign('nextTitle', $nextRecord['title']);
                     }
                 }
             }
         }
         $timer->logTime('Got next/previous links');
     }
 }
Exemplo n.º 18
0
 */
require_once 'util.inc.php';
require_once 'services/MyResearch/lib/Search.php';
require_once 'sys/ConnectionManager.php';
// Use command line value as expiration age, or default to 2.
$daysOld = isset($argv[1]) ? intval($argv[1]) : 2;
// Die if we have an invalid expiration age.
if ($daysOld < 2) {
    die("Expiration age must be at least two days.\n");
}
// Retrieve values from configuration file
$configArray = readConfig();
// Setup time zone
date_default_timezone_set($configArray['Site']['timezone']);
// Setup Local Database Connection
ConnectionManager::connectToDatabase();
// Delete the expired searches -- this cleans up any junk left in the database
// from old search histories that were not caught by the session garbage collector.
$search = new SearchEntry();
$expired = $search->getExpiredSearches($daysOld);
if (empty($expired)) {
    die(date('Y-m-d H:i:s') . " No expired searches to delete.\n");
}
while (!empty($expired)) {
    $count = count($expired);
    foreach ($expired as $oldSearch) {
        $oldSearch->delete();
    }
    echo date('Y-m-d H:i:s') . " {$count} expired searches deleted.\n";
    $expired = $search->getExpiredSearches($daysOld);
}
Exemplo n.º 19
0
 /**
  * Restore the last saved search.
  *
  * @return SearchObject
  * @access private
  */
 private function _restoreLastSearch()
 {
     if (isset($_SESSION['lastSearchId'])) {
         $search = new SearchEntry();
         $search->id = $_SESSION['lastSearchId'];
         if ($search->find(true)) {
             $minSO = unserialize($search->search_object);
             $savedSearch = SearchObjectFactory::deminify($minSO);
             return $savedSearch;
         }
     }
     return null;
 }
Exemplo n.º 20
0
 function launch()
 {
     global $interface;
     global $user;
     // In some contexts, we want to require a login before showing search
     // history:
     if (isset($_REQUEST['require_login']) && !UserAccount::isLoggedIn()) {
         require_once ROOT_DIR . '/services/MyAccount/Login.php';
         MyAccount_Login::launch();
         exit;
     }
     $interface->setPageTitle('Search History');
     // Retrieve search history
     $s = new SearchEntry();
     $searchHistory = $s->getSearches(session_id(), is_object($user) ? $user->id : null);
     if (count($searchHistory) > 0) {
         // Build an array of history entries
         $links = array();
         $saved = array();
         // Loop through the history
         foreach ($searchHistory as $search) {
             $size = strlen($search->search_object);
             $minSO = unserialize($search->search_object);
             $searchObject = SearchObjectFactory::deminify($minSO);
             // Make sure all facets are active so we get appropriate
             // descriptions in the filter box.
             $searchObject->activateAllFacets();
             $newItem = array('id' => $search->id, 'time' => date("g:ia, jS M y", $searchObject->getStartTime()), 'url' => $searchObject->renderSearchUrl(), 'searchId' => $searchObject->getSearchId(), 'description' => $searchObject->displayQuery(), 'filters' => $searchObject->getFilterList(), 'hits' => number_format($searchObject->getResultTotal()), 'speed' => round($searchObject->getQuerySpeed(), 2) . "s", 'size' => round($size / 1024, 3) . "kb");
             // Saved searches
             if ($search->saved == 1) {
                 $saved[] = $newItem;
                 // All the others
             } else {
                 // If this was a purge request we don't need this
                 if (isset($_REQUEST['purge']) && $_REQUEST['purge'] == 'true') {
                     $search->delete();
                     // We don't want to remember the last search after a purge:
                     unset($_SESSION['lastSearchURL']);
                     // Otherwise add to the list
                 } else {
                     $links[] = $newItem;
                 }
             }
         }
         // One final check, after a purge make sure we still have a history
         if (count($links) > 0 || count($saved) > 0) {
             $interface->assign('links', array_reverse($links));
             $interface->assign('saved', array_reverse($saved));
             $interface->assign('noHistory', false);
             // Nothing left in history
         } else {
             $interface->assign('noHistory', true);
         }
         // No history
     } else {
         $interface->assign('noHistory', true);
     }
     //Load profile information for display in My Account menu
     //This code is also in MyResearch.php
     if ($user !== false) {
         global $configArray;
         $this->catalog = CatalogFactory::getCatalogConnectionInstance();
         // 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);
                 }
                 $result = $this->catalog->getMyProfile($patron);
                 if (!PEAR_Singleton::isError($result)) {
                     $interface->assign('profile', $result);
                 }
             }
         }
         //Figure out if we should show a link to classic opac to pay holds.
         global $library;
         $homeLibrary = $library->getLibraryForLocation($user->homeLocationId);
         if ($homeLibrary->showEcommerceLink == 1) {
             $interface->assign('showEcommerceLink', true);
             $interface->assign('minimumFineAmount', $homeLibrary->minimumFineAmount);
         } else {
             $interface->assign('showEcommerceLink', false);
             $interface->assign('minimumFineAmount', 0);
         }
     }
     $interface->assign('sidebar', 'MyAccount/account-sidebar.tpl');
     $interface->setTemplate('history.tpl');
     $interface->display('layout.tpl');
 }