Esempio n. 1
0
 /**
  * Constructor. Initialise some details about the server
  *
  * @access  public
  */
 public function __construct()
 {
     // Standard logic from parent class:
     parent::__construct();
     // Set up appropriate results action:
     $this->resultsModule = 'WorldCat';
     $this->resultsAction = 'Search';
     // Set up basic and advanced WorldCat search types; default to basic.
     $this->searchType = $this->basicSearchType = 'WorldCat';
     $this->advancedSearchType = 'WorldCatAdvanced';
     // Set up sort options
     $config = getExtraConfigArray('WorldCat');
     $this->sortOptions = $config['Sorting'];
     if (isset($config['General']['default_sort'])) {
         $this->defaultSort = $config['General']['default_sort'];
     }
     // Set up search options
     $this->basicTypes = $config['Basic_Searches'];
     if (isset($config['Advanced_Searches'])) {
         $this->advancedTypes = $config['Advanced_Searches'];
     }
     $this->defaultIndex = 'srw.kw';
     // Set up recommendations options -- settings are found in WorldCat.ini:
     $this->recommendIni = 'WorldCat';
     // Connect to WorldCat
     $this->worldcat = new Worldcat();
 }
Esempio n. 2
0
 /**
  * Display the page.
  *
  * @return void
  * @access public
  */
 public function launch()
 {
     global $interface;
     global $configArray;
     global $user;
     // Load a saved search, if any:
     $savedSearch = $this->_loadSavedSearch();
     // Send search type settings to the template
     $interface->assign('advSearchTypes', $this->searchObject->getAdvancedTypes());
     // Get checkbox filters to present narrow options; this may also strip some
     // filters out of the $savedSearch object to prevent redundant information
     // being retrieved via the getFilterList() method.
     $interface->assign('checkboxFilters', $this->_getCheckboxFilters($savedSearch));
     // Process settings to control special-purpose facets not supported by the
     //     more generic configuration options.
     $config = getExtraConfigArray('PCI');
     $special = isset($config['Advanced_Facet_Settings']['special_facets']) ? $config['Advanced_Facet_Settings']['special_facets'] : '';
     if (stristr($special, 'daterange')) {
         $interface->assign('dateRangeLimit', $this->_getDateRangeSettings($savedSearch));
     }
     // If we found a saved search, let's assign some details to the interface:
     if ($savedSearch) {
         $interface->assign('searchDetails', $savedSearch->getSearchTerms());
         $interface->assign('searchFilters', $savedSearch->getFilterList());
     }
     $interface->setPageTitle('Advanced Search');
     $interface->setTemplate('advanced.tpl');
     $interface->display('layout.tpl');
 }
Esempio n. 3
0
 /**
  * Constructor. Initialise details about the server
  *
  * @access public
  */
 public function __construct()
 {
     parent::__construct();
     $this->resultsModule = 'PCI';
     $this->resultsAction = 'Search';
     $config = getExtraConfigArray("PCI");
     foreach ($config['Facets'] as $key => $value) {
         $parts = explode(',', $key);
         $facetName = trim($parts[0]);
         $this->facetConfig[$facetName] = $value;
     }
     $this->translatedFacets = isset($config['Facet_Settings']['translated_facets']) ? $config['Facet_Settings']['translated_facets'] : null;
     $this->facetTranslationPrefix = isset($config['Facet_Settings']['facet_translation_prefix']) ? $config['Facet_Settings']['facet_translation_prefix'] : null;
     // Set up basic and advanced PCI search types; default to basic.
     $this->searchType = $this->basicSearchType = 'PCI';
     $this->advancedSearchType = 'PCIAdvanced';
     // Set up search options
     $this->basicTypes = $config['Basic_Searches'];
     if (isset($config['Advanced_Searches'])) {
         $this->advancedTypes = $config['Advanced_Searches'];
     }
     $this->recommendIni = 'PCI';
     $this->params['institution'] = $config['General']['institution'];
     $this->params['highlight'] = $config['General']['highlight'];
     $this->params['db'] = isset($config['General']['db']) ? $config['General']['db'] : null;
     // Set up sort options
     $this->sortOptions = $config['Sorting'];
     // default sort for PCI is empty string
     $this->defaultSort = "";
     // Connect to PCI
     $this->PCI = new PCI();
 }
Esempio n. 4
0
 /**
  * Constructor
  *
  * @access public
  */
 public function __construct()
 {
     global $interface;
     global $configArray;
     // Call parent constructor
     parent::__construct();
     // Fetch Record
     $config = getExtraConfigArray('MetaLib');
     $metalib = new MetaLib();
     $this->record = $metalib->getRecord($_REQUEST['id']);
     if (PEAR::isError($this->record)) {
         PEAR::raiseError($this->record);
     }
     // Get record driver
     $this->recordDriver = RecordDriverFactory::initRecordDriver($this->record);
     // Set Proxy URL
     $interface->assign('proxy', isset($configArray['EZproxy']['host']) ? $configArray['EZproxy']['host'] : false);
     // Whether RSI is enabled
     if (isset($configArray['OpenURL']['use_rsi']) && $configArray['OpenURL']['use_rsi']) {
         $interface->assign('rsi', true);
     }
     // Whether embedded openurl autocheck is enabled
     if (isset($configArray['OpenURL']['autocheck']) && $configArray['OpenURL']['autocheck']) {
         $interface->assign('openUrlAutoCheck', true);
     }
     // Send record ID to template
     $interface->assign('id', $_REQUEST['id']);
     // Send down legal export formats (if any):
     $interface->assign('exportFormats', array('RefWorks', 'EndNote'));
     // Set AddThis User
     $interface->assign('addThis', isset($configArray['AddThis']['key']) ? $configArray['AddThis']['key'] : false);
     // Get core metadata
     $interface->assign('coreMetadata', $this->recordDriver->getCoreMetadata());
 }
Esempio n. 5
0
 /**
 * Constructor
 *
 * @param string $mainDir  The main VuFind directory.
                           Each web directory must reside
                           under this (default: ..)
 * @param string $errEmail Email address for error reporting.
 *
 * @return void
 */
 function __construct($mainDir, $errEmail)
 {
     $this->mainDir = $mainDir;
     $this->errEmail = $errEmail;
     $this->mainConfig = readConfig();
     $this->datasourceConfig = getExtraConfigArray('datasources');
 }
Esempio n. 6
0
 /**
  * Constructor
  *
  * Establishes base settings for making recommendations.
  *
  * @param object $searchObject The SearchObject requesting recommendations.
  * @param string $params       Additional settings from searches.ini.
  *
  * @access public
  */
 public function __construct($searchObject, $params)
 {
     $this->_searchObject = $searchObject;
     $params = explode(':', $params);
     $iniName = isset($params[0]) && $params[0] != "" ? $params[0] : 'facets';
     // Load the desired facet information...
     $config = getExtraConfigArray($iniName);
 }
Esempio n. 7
0
 /**
  * Constructor
  *
  * Establishes base settings for making recommendations.
  *
  * @param object $searchObject The SearchObject requesting recommendations.
  * @param string $params       Additional settings from searches.ini.
  *
  * @access public
  */
 public function __construct($searchObject, $params)
 {
     // Save the passed-in SearchObject:
     $this->_searchObject = $searchObject;
     // Parse the additional settings:
     $params = explode(':', $params);
     $mainSection = empty($params[0]) ? 'Results' : $params[0];
     $checkboxSection = isset($params[1]) ? $params[1] : false;
     $iniName = isset($params[2]) ? $params[2] : 'facets';
     // Load the desired facet information...
     $config = getExtraConfigArray($iniName);
     // All standard facets to display:
     $this->_mainFacets = isset($config[$mainSection]) ? $config[$mainSection] : array();
     // Get a list of fields that should be displayed as date ranges rather than
     // standard facet lists.
     if (isset($config['SpecialFacets']['dateRange'])) {
         $this->_dateFacets = is_array($config['SpecialFacets']['dateRange']) ? $config['SpecialFacets']['dateRange'] : array($config['SpecialFacets']['dateRange']);
     }
     // Get a list of fields that should be displayed as a hierarchy.
     if (isset($config['SpecialFacets']['hierarchical'])) {
         $this->_hierarchicalFacets = $config['SpecialFacets']['hierarchical'];
     }
     // Get a list of fields that should be open on default.
     if (isset($config['SpecialFacets']['default'])) {
         $this->_defaultFacets = $config['SpecialFacets']['default'];
     } else {
         $this->_defaultFacets = array();
     }
     // Get a list of facetfields that should not be displayed.
     if (isset($config['SpecialFacets']['hidden'])) {
         $this->_hiddenFacets = $config['SpecialFacets']['hidden'];
     } else {
         $this->_hiddenFacets = array();
     }
     // Checkbox facets:
     $checkboxFacets = $checkboxSection && isset($config[$checkboxSection]) ? $config[$checkboxSection] : array();
     $this->_checkboxFacets = array();
     foreach ($checkboxFacets as $key => $val) {
         $this->_checkboxFacets[$key] = array('desc' => $val, 'data' => array());
     }
     // Checkbox facets inside facet sections
     foreach ($this->_mainFacets as $key => $val) {
         $section = "{$checkboxSection}:{$key}";
         if (isset($config[$section])) {
             $data = $config[$section];
             $this->_checkboxFacetsSection[$val] = $data;
             foreach ($data as $filter => $translationKey) {
                 $sectionKey = is_array($filter) ? array_pop(array_keys($filter)) : $filter;
                 // Store facet section id as 'parent'
                 $this->_checkboxFacets[$filter] = array('desc' => $translationKey, 'data' => array('parent' => $key));
             }
         }
     }
     //collection keyword filter
     $this->_collectionKeywordFilter = isset($config['Collection_Keyword']['search']) ? $config['Collection_Keyword']['search'] : false;
 }
Esempio n. 8
0
 /**
  * Constructor.
  *
  * @access public
  */
 public function __construct()
 {
     parent::__construct();
     $this->_searchObject = SearchObjectFactory::initSearchObject();
     // Load the desired facet information...
     $config = getExtraConfigArray('facets');
     if (isset($config['MapFacets']['location'])) {
         $this->_locationFacet = is_array($config['MapFacets']['location']) ? $config['MapFacets']['location'] : array($config['MapFacets']['location']);
     }
 }
Esempio n. 9
0
 public function __construct($searchObject, $params)
 {
     global $library;
     global $configArray;
     // Save the basic parameters:
     $this->searchObject = $searchObject;
     // Parse the additional parameters:
     $params = explode(':', $params);
     $section = empty($params[0]) ? 'ResultsTop' : $params[0];
     $iniFile = isset($params[1]) ? $params[1] : 'facets';
     // Load the desired facet information:
     $searchLibrary = Library::getActiveLibrary();
     $searchLocation = Location::getActiveLocation();
     $config = getExtraConfigArray($iniFile);
     if ($searchObject->getSearchType() == 'genealogy') {
         $this->mainFacets = array();
     } else {
         $searchLibrary = Library::getActiveLibrary();
         $searchLocation = Location::getActiveLocation();
         $userLocation = Location::getUserHomeLocation();
         $hasSearchLibraryFacets = $searchLibrary != null && count($searchLibrary->facets) > 0;
         $hasSearchLocationFacets = $searchLocation != null && count($searchLocation->facets) > 0;
         if ($hasSearchLocationFacets) {
             $facets = $searchLocation->facets;
         } elseif ($hasSearchLibraryFacets) {
             $facets = $searchLibrary->facets;
         } else {
             $facets = Library::getDefaultFacets();
         }
         foreach ($facets as $facet) {
             if ($facet->showAboveResults == 1) {
                 $facetName = $facet->facetName;
                 if (isset($searchLibrary)) {
                     if ($facet->facetName == 'availability_toggle' && $configArray['Index']['enableDetailedAvailability']) {
                         $facetName = 'availability_toggle_' . $searchLibrary->subdomain;
                     }
                 }
                 if (isset($userLocation)) {
                     if ($facet->facetName == 'availability_toggle' && $configArray['Index']['enableDetailedAvailability']) {
                         $facetName = 'availability_toggle_' . $userLocation->code;
                     }
                 }
                 if (isset($searchLocation)) {
                     if ($facet->facetName == 'availability_toggle' && $configArray['Index']['enableDetailedAvailability']) {
                         $facetName = 'availability_toggle_' . $searchLocation->code;
                     }
                 }
                 $this->facets[$facetName] = $facet->displayName;
                 $this->facetSettings[$facetName] = $facet;
             }
         }
     }
     // Load other relevant settings:
     $this->baseSettings = array('rows' => $config['Results_Settings']['top_rows'], 'cols' => $config['Results_Settings']['top_cols']);
 }
Esempio n. 10
0
 public function __construct($searchObject, $params)
 {
     global $configArray;
     // Save the basic parameters:
     /** @var SearchObject_Solr|SearchObject_Base searchObject */
     $this->searchObject = $searchObject;
     // Parse the additional parameters:
     $params = explode(':', $params);
     $iniFile = isset($params[1]) ? $params[1] : 'facets';
     // Load the desired facet information:
     $config = getExtraConfigArray($iniFile);
     if ($this->searchObject->getSearchType() == 'genealogy') {
         $this->mainFacets = array();
     } else {
         $searchLibrary = Library::getActiveLibrary();
         global $locationSingleton;
         $searchLocation = $locationSingleton->getActiveLocation();
         $userLocation = Location::getUserHomeLocation();
         $hasSearchLibraryFacets = $searchLibrary != null && count($searchLibrary->facets) > 0;
         $hasSearchLocationFacets = $searchLocation != null && count($searchLocation->facets) > 0;
         if ($hasSearchLocationFacets) {
             $facets = $searchLocation->facets;
         } elseif ($hasSearchLibraryFacets) {
             $facets = $searchLibrary->facets;
         } else {
             $facets = Library::getDefaultFacets();
         }
         global $solrScope;
         foreach ($facets as $facet) {
             if ($facet->showAboveResults == 1) {
                 $facetName = $facet->facetName;
                 if ($solrScope) {
                     if ($facet->facetName == 'availability_toggle' && $configArray['Index']['enableDetailedAvailability']) {
                         $facetName = 'availability_toggle_' . $solrScope;
                     } else {
                         if ($facet->facetName == 'format_category' && $configArray['Index']['enableDetailedFormats']) {
                             $facetName = 'format_category_' . $solrScope;
                         }
                     }
                 }
                 $this->facets[$facetName] = $facet->displayName;
                 $this->facetSettings[$facetName] = $facet;
                 if (!$solrScope && $facet->facetName == 'availability_toggle') {
                     //Don't do availability toggles in the global scope.
                     //TODO: Base this off the default scope (i.e. mercury/responsive).
                     unset($this->facets[$facetName]);
                     unset($this->facetSettings[$facetName]);
                 }
             }
         }
     }
     // Load other relevant settings:
     $this->baseSettings = array('rows' => $config['Results_Settings']['top_rows'], 'cols' => $config['Results_Settings']['top_cols']);
 }
Esempio n. 11
0
 /**
  * Constructor
  *
  * Establishes base settings for making recommendations.
  *
  * @param object $searchObject The SearchObject requesting recommendations.
  * @param string $params       Additional settings from searches.ini.
  *
  * @access public
  */
 public function __construct($searchObject, $params)
 {
     // Save the basic parameters:
     $this->_searchObject = $searchObject;
     // Parse the additional parameters:
     $params = explode(':', $params);
     $section = empty($params[0]) ? 'ResultsTop' : $params[0];
     $iniFile = isset($params[1]) ? $params[1] : 'facets';
     // Load the desired facet information:
     $config = getExtraConfigArray($iniFile);
     $this->_facets = isset($config[$section]) ? $config[$section] : array();
 }
Esempio n. 12
0
 /**
  * Constructor
  *
  * Establishes base settings for making recommendations.
  *
  * @param object $searchObject The SearchObject requesting recommendations.
  * @param string $params       Additional settings from searches.ini.
  *
  * @access public
  */
 public function __construct($searchObject, $params)
 {
     // Save the basic parameters:
     $this->_searchObject = $searchObject;
     // Parse the additional parameters:
     $params = explode(':', $params);
     $section = empty($params[0]) ? 'ResultsTop' : $params[0];
     $iniFile = isset($params[1]) ? $params[1] : 'facets';
     // Load the desired facet information:
     $config = getExtraConfigArray($iniFile);
     $this->_facets = isset($config[$section]) ? $config[$section] : array();
     // Load other relevant settings:
     $this->_baseSettings = array('rows' => isset($config['Results_Settings']['top_rows']) ? $config['Results_Settings']['top_rows'] : 1, 'cols' => isset($config['Results_Settings']['top_cols']) ? $config['Results_Settings']['top_cols'] : 1);
 }
Esempio n. 13
0
 /**
  * Constructor.
  *
  * @access public
  */
 public function __construct()
 {
     global $action;
     parent::__construct();
     if (isset($_REQUEST['collection'])) {
         $this->_searchObject = SearchObjectFactory::initSearchObject('SolrCollection');
         $action = isset($_REQUEST['collectionAction']) ? $_REQUEST['collectionAction'] : 'Home';
     } else {
         $this->_searchObject = SearchObjectFactory::initSearchObject();
     }
     // Load the desired facet information...
     $config = getExtraConfigArray('facets');
     if (isset($config['SpecialFacets']['dateVis'])) {
         $this->_dateFacets = is_array($config['SpecialFacets']['dateVis']) ? $config['SpecialFacets']['dateVis'] : array($config['SpecialFacets']['dateVis']);
     }
 }
Esempio n. 14
0
 /**
  * Constructor
  *
  * @access public
  */
 public function __construct()
 {
     global $action;
     parent::__construct();
     if (isset($_REQUEST['collection'])) {
         $this->searchObject = SearchObjectFactory::initSearchObject('SolrCollection');
         $action = isset($_REQUEST['collectionAction']) ? $_REQUEST['collectionAction'] : 'Home';
     } else {
         $this->searchObject = SearchObjectFactory::initSearchObject();
     }
     // Load the desired facet information...
     $config = getExtraConfigArray('facets');
     if (isset($config['SpecialFacets']['dateRangeVis'])) {
         list($this->filterField, $this->dateFacet) = explode(':', $config['SpecialFacets']['dateRangeVis'], 2);
     }
 }
Esempio n. 15
0
 /**
  * Constructor. Initialise some details about the server
  *
  * @access public
  */
 public function __construct()
 {
     global $configArray;
     // Standard logic from parent class:
     parent::__construct();
     // Set up appropriate results action:
     $this->resultsModule = 'Summon';
     $this->resultsAction = 'Search';
     // Set up basic and advanced Summon search types; default to basic.
     $this->searchType = $this->basicSearchType = 'Summon';
     $this->advancedSearchType = 'SummonAdvanced';
     // Set up facet configuration -- note that we may need to strip extra
     // parameters from the facet names (hence the extra processing):
     $config = getExtraConfigArray('Summon');
     foreach ($config['Facets'] as $key => $value) {
         $parts = explode(',', $key);
         $facetName = trim($parts[0]);
         $this->facetConfig[$facetName] = $value;
     }
     // Set up spelling preference
     if (isset($config['Spelling']['enabled'])) {
         $this->spellcheck = $config['Spelling']['enabled'];
     }
     // Set up sort options
     $this->sortOptions = $config['Sorting'];
     if (isset($config['General']['default_sort'])) {
         $this->defaultSort = $config['General']['default_sort'];
     }
     // Set up search options
     $this->basicTypes = $config['Basic_Searches'];
     if (isset($config['Advanced_Searches'])) {
         $this->advancedTypes = $config['Advanced_Searches'];
     }
     // Account for "retain filters" setting:
     if (isset($config['General']['retain_filters_by_default'])) {
         $this->retainFiltersByDefault = $config['General']['retain_filters_by_default'];
     }
     // Set up recommendations options -- settings are found in Summon.ini:
     $this->recommendIni = 'Summon';
     // Connect to Summon
     $id = isset($configArray['Summon']['apiId']) ? $configArray['Summon']['apiId'] : null;
     $key = isset($configArray['Summon']['apiKey']) ? $configArray['Summon']['apiKey'] : null;
     $this->_summon = new Summon($id, $key);
 }
Esempio n. 16
0
 /**
  * Constructor. Initialise some details about the server
  *
  * @access public
  */
 public function __construct()
 {
     // Standard logic from parent class:
     parent::__construct();
     global $configArray;
     // Connect to the index
     $this->_indexEngine = ConnectionManager::connectToIndex('SolrReserves');
     // Set up appropriate results action:
     $this->resultsModule = 'Search';
     $this->resultsAction = 'Reserves';
     // Set up basic and advanced search types; default to basic.
     $this->searchType = $this->basicSearchType = 'Reserves';
     // Get default facet settings
     $this->facetConfig = array();
     $this->recommendIni = 'reserves';
     // Load search preferences:
     $searchSettings = getExtraConfigArray('reserves');
     if (isset($searchSettings['General']['facet_limit'])) {
         $this->_facetLimit = $searchSettings['General']['facet_limit'];
     }
     if (isset($searchSettings['General']['default_handler'])) {
         $this->defaultIndex = $searchSettings['General']['default_handler'];
     }
     if (isset($searchSettings['General']['default_sort'])) {
         $this->defaultSort = $searchSettings['General']['default_sort'];
     }
     if (isset($searchSettings['Basic_Searches'])) {
         $this->basicTypes = $searchSettings['Basic_Searches'];
     }
     if (isset($searchSettings['Advanced_Searches'])) {
         $this->advancedTypes = $searchSettings['Advanced_Searches'];
     }
     if (isset($searchSettings['Autocomplete']['enabled'])) {
         $this->autocompleteStatus = $searchSettings['Autocomplete']['enabled'];
     }
     // Load sort preferences (or defaults if none in .ini file):
     if (isset($searchSettings['Sorting'])) {
         $this->sortOptions = $searchSettings['Sorting'];
     } else {
         $this->sortOptions = array('instructor_str' => 'sort_instructor', 'course_str' => 'sort_course', 'department_str' => 'sort_department');
     }
 }
 /**
  * getSuggestions
  *
  * This returns an array of suggestions based on current $_REQUEST parameters.
  * This logic is present in the factory class so that it can be easily shared
  * by multiple AJAX handlers.
  *
  * @param string $typeParam  Name of $_REQUEST parameter containing search type
  * @param string $queryParam Name of $_REQUEST parameter containing query string
  *
  * @return array
  * @access public
  */
 public static function getSuggestions($typeParam = 'type', $queryParam = 'q')
 {
     // Process incoming parameters:
     $type = isset($_REQUEST[$typeParam]) ? $_REQUEST[$typeParam] : '';
     $query = isset($_REQUEST[$queryParam]) ? $_REQUEST[$queryParam] : '';
     // Figure out which handler to use:
     $searchSettings = getExtraConfigArray('searches');
     if (!empty($type) && isset($searchSettings['Autocomplete_Types'][$type])) {
         $module = $searchSettings['Autocomplete_Types'][$type];
     } else {
         if (isset($searchSettings['Autocomplete']['default_handler'])) {
             $module = $searchSettings['Autocomplete']['default_handler'];
         } else {
             $module = false;
         }
     }
     // Get suggestions:
     if ($module) {
         @(list($name, $params) = explode(':', $module, 2));
         $handler = self::initAutocomplete($name, $params);
     }
     return isset($handler) && is_object($handler) ? $handler->getSuggestions($query) : array();
 }
Esempio n. 18
0
 /**
  * Process search query and display suggestion as a JSON object.
  *
  * @return void
  * @access public
  */
 public function getSuggestions()
 {
     $autocomplete = true;
     $prefilters = getExtraConfigArray('prefilters');
     if (isset($_REQUEST['prefilter']) && $_REQUEST['prefilter'] && isset($prefilters[$_REQUEST['prefilter']])) {
         $prefilter = $prefilters[$_REQUEST['prefilter']];
         if ($prefilter && $_REQUEST['prefilter'] != '-') {
             $params = $_REQUEST;
             $params['prefiltered'] = $params['prefilter'];
             unset($params['prefilter']);
             foreach ($prefilter as $key => $value) {
                 if ($key == 'module' || $key == 'action') {
                     if ($key == 'module' && ($value != 'Search' && $value != 'Browse')) {
                         // only autocomplete on local index and browse
                         $autocomplete = false;
                         break;
                     }
                     continue;
                 }
                 if (is_array($value)) {
                     foreach ($value as $v) {
                         $params[$key][] = $v;
                     }
                 } else {
                     $params[$key] = $value;
                 }
             }
             $_REQUEST = $params;
         }
     }
     if ($autocomplete) {
         $this->output(array_values(AutocompleteFactory::getSuggestions()), JSON::STATUS_OK);
     } else {
         $this->output('', JSON::STATUS_ERROR);
     }
 }
Esempio n. 19
0
 /**
  * Constructor. Initialise some details about the server
  *
  * @access  public
  */
 public function __construct()
 {
     // Call base class constructor
     parent::__construct();
     global $configArray;
     global $timer;
     // Include our solr index
     $class = $configArray['Genealogy']['engine'];
     require_once "sys/{$class}.php";
     $this->searchType = 'genealogy';
     $this->basicSearchType = 'genealogy';
     // Initialise the index
     $this->indexEngine = new $class($configArray['Genealogy']['url'], $configArray['Genealogy']['default_core']);
     $timer->logTime('Created Index Engine for Genealogy');
     //Make sure to turn off sharding for genealogy
     $this->indexEngine->setShards(array());
     // Get default facet settings
     $this->allFacetSettings = getExtraConfigArray('genealogyFacets');
     $this->facetConfig = array();
     $facetLimit = $this->getFacetSetting('Results_Settings', 'facet_limit');
     if (is_numeric($facetLimit)) {
         $this->facetLimit = $facetLimit;
     }
     $translatedFacets = $this->getFacetSetting('Advanced_Settings', 'translated_facets');
     if (is_array($translatedFacets)) {
         $this->translatedFacets = $translatedFacets;
     }
     // Load search preferences:
     $searchSettings = getExtraConfigArray('genealogySearches');
     if (isset($searchSettings['General']['default_handler'])) {
         $this->defaultIndex = $searchSettings['General']['default_handler'];
     }
     if (isset($searchSettings['General']['default_sort'])) {
         $this->defaultSort = $searchSettings['General']['default_sort'];
     }
     if (isset($searchSettings['DefaultSortingByType']) && is_array($searchSettings['DefaultSortingByType'])) {
         $this->defaultSortByType = $searchSettings['DefaultSortingByType'];
     }
     if (isset($searchSettings['Basic_Searches'])) {
         $this->basicTypes = $searchSettings['Basic_Searches'];
     }
     if (isset($searchSettings['Advanced_Searches'])) {
         $this->advancedTypes = $searchSettings['Advanced_Searches'];
     }
     // Load sort preferences (or defaults if none in .ini file):
     if (isset($searchSettings['Sorting'])) {
         $this->sortOptions = $searchSettings['Sorting'];
     } else {
         $this->sortOptions = array('relevance' => 'sort_relevance', 'year' => 'sort_year', 'year asc' => 'sort_year asc', 'title' => 'sort_title');
     }
     // Load Spelling preferences
     $this->spellcheck = $configArray['Spelling']['enabled'];
     $this->spellingLimit = $configArray['Spelling']['limit'];
     $this->spellSimple = $configArray['Spelling']['simple'];
     $this->spellSkipNumeric = isset($configArray['Spelling']['skip_numeric']) ? $configArray['Spelling']['skip_numeric'] : true;
     // Debugging
     if ($configArray['System']['debugSolr']) {
         $this->indexEngine->debug = true;
     } else {
         $this->indexEngine->debug = false;
     }
     $this->recommendIni = 'genealogySearches';
     $timer->logTime('Setup Solr Search Object');
 }
Esempio n. 20
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');
 }
Esempio n. 21
0
 /**
  * Get New Items
  *
  * Retrieve the IDs of items recently added to the catalog.
  *
  * @param int $page    Page number of results to retrieve (counting starts at 1)
  * @param int $limit   The size of each page of results to retrieve
  * @param int $daysOld The maximum age of records to retrieve in days (max. 30)
  * @param int $fundId  optional fund ID to use for limiting results (use a value
  * returned by getFunds, or exclude for no limit); note that "fund" may be a
  * misnomer - if funds are not an appropriate way to limit your new item
  * results, you can return a different set of values from getFunds. The
  * important thing is that this parameter supports an ID returned by getFunds,
  * whatever that may mean.
  *
  * @return array       Associative array with 'count' and 'results' keys
  * @access public
  */
 public function getNewItems($page, $limit, $daysOld, $fundId = null)
 {
     $items = array();
     // Prevent unnecessary load on Voyager -- no point in exceeding the maximum
     // configured date range.
     $maxAge = 30;
     $searchSettings = getExtraConfigArray('searches');
     if (isset($searchSettings['NewItem']['ranges'])) {
         $tmp = explode(',', $searchSettings['NewItem']['ranges']);
         foreach ($tmp as $current) {
             if (intval($current) > $maxAge) {
                 $maxAge = intval($current);
             }
         }
     }
     if ($daysOld > $maxAge) {
         $daysOld = $maxAge;
     }
     $bindParams = array(':enddate' => date('d-m-Y', strtotime('now')), ':startdate' => date('d-m-Y', strtotime("-{$daysOld} day")));
     $sql = "select count(distinct LINE_ITEM.BIB_ID) as count " . "from {$this->dbName}.LINE_ITEM, " . "{$this->dbName}.LINE_ITEM_COPY_STATUS, " . "{$this->dbName}.LINE_ITEM_FUNDS, {$this->dbName}.FUND " . "where LINE_ITEM.LINE_ITEM_ID = LINE_ITEM_COPY_STATUS.LINE_ITEM_ID " . "and LINE_ITEM_COPY_STATUS.COPY_ID = LINE_ITEM_FUNDS.COPY_ID " . "and LINE_ITEM_FUNDS.FUND_ID = FUND.FUND_ID ";
     if ($fundId) {
         // Although we're getting an ID value from getFunds() passed in here,
         // it's not actually an ID -- we use names as IDs (see note in getFunds
         // itself for more details).
         $sql .= "and lower(FUND.FUND_NAME) = :fund ";
         $bindParams[':fund'] = strtolower($fundId);
     }
     $sql .= "and LINE_ITEM.CREATE_DATE >= to_date(:startdate, 'dd-mm-yyyy') " . "and LINE_ITEM.CREATE_DATE < to_date(:enddate, 'dd-mm-yyyy')";
     try {
         $sqlStmt = $this->db->prepare($sql);
         $this->debugLogSQL(__FUNCTION__, $sql, $bindParams);
         $sqlStmt->execute($bindParams);
         $row = $sqlStmt->fetch(PDO::FETCH_ASSOC);
         $items['count'] = $row['COUNT'];
     } catch (PDOException $e) {
         return new PEAR_Error($e->getMessage());
     }
     $page = $page ? $page : 1;
     $limit = $limit ? $limit : 20;
     $bindParams[':startRow'] = ($page - 1) * $limit + 1;
     $bindParams[':endRow'] = $page * $limit;
     /*
     $sql = "select * from " .
            "(select a.*, rownum rnum from " .
            "(select LINE_ITEM.BIB_ID, BIB_TEXT.TITLE, FUND.FUND_NAME, " .
            "LINE_ITEM.CREATE_DATE, LINE_ITEM_STATUS.LINE_ITEM_STATUS_DESC " .
            "from $this->dbName.BIB_TEXT, $this->dbName.LINE_ITEM, " .
            "$this->dbName.LINE_ITEM_COPY_STATUS, " .
            "$this->dbName.LINE_ITEM_STATUS, $this->dbName.LINE_ITEM_FUNDS, " .
            "$this->dbName.FUND " .
            "where BIB_TEXT.BIB_ID = LINE_ITEM.BIB_ID " .
            "and LINE_ITEM.LINE_ITEM_ID = LINE_ITEM_COPY_STATUS.LINE_ITEM_ID " .
            "and LINE_ITEM_COPY_STATUS.COPY_ID = LINE_ITEM_FUNDS.COPY_ID " .
            "and LINE_ITEM_STATUS.LINE_ITEM_STATUS = " .
            "LINE_ITEM_COPY_STATUS.LINE_ITEM_STATUS " .
            "and LINE_ITEM_FUNDS.FUND_ID = FUND.FUND_ID ";
     */
     $sql = "select * from " . "(select a.*, rownum rnum from " . "(select LINE_ITEM.BIB_ID, LINE_ITEM.CREATE_DATE " . "from {$this->dbName}.LINE_ITEM, " . "{$this->dbName}.LINE_ITEM_COPY_STATUS, " . "{$this->dbName}.LINE_ITEM_STATUS, {$this->dbName}.LINE_ITEM_FUNDS, " . "{$this->dbName}.FUND " . "where LINE_ITEM.LINE_ITEM_ID = LINE_ITEM_COPY_STATUS.LINE_ITEM_ID " . "and LINE_ITEM_COPY_STATUS.COPY_ID = LINE_ITEM_FUNDS.COPY_ID " . "and LINE_ITEM_STATUS.LINE_ITEM_STATUS = " . "LINE_ITEM_COPY_STATUS.LINE_ITEM_STATUS " . "and LINE_ITEM_FUNDS.FUND_ID = FUND.FUND_ID ";
     if ($fundId) {
         $sql .= "and lower(FUND.FUND_NAME) = :fund ";
     }
     $sql .= "and LINE_ITEM.CREATE_DATE >= to_date(:startdate, 'dd-mm-yyyy') " . "and LINE_ITEM.CREATE_DATE < to_date(:enddate, 'dd-mm-yyyy') " . "group by LINE_ITEM.BIB_ID, LINE_ITEM.CREATE_DATE " . "order by LINE_ITEM.CREATE_DATE desc) a " . "where rownum <= :endRow) " . "where rnum >= :startRow";
     try {
         $sqlStmt = $this->db->prepare($sql);
         $this->debugLogSQL(__FUNCTION__, $sql, $bindParams);
         $sqlStmt->execute($bindParams);
         while ($row = $sqlStmt->fetch(PDO::FETCH_ASSOC)) {
             $items['results'][]['id'] = $row['BIB_ID'];
         }
         return $items;
     } catch (PDOException $e) {
         return new PEAR_Error($e->getMessage());
     }
 }
Esempio n. 22
0
 /**
  * Process PCI search
  * 
  * @return void
  */
 function doPCI()
 {
     global $interface;
     global $configArray;
     if (!$interface->get_template_vars('pciEnabled')) {
         PEAR::raiseError(new PEAR_Error("PCI is not enabled."));
     }
     // If we're loading PCI results via AJAX, we can't take advantage
     // of the counter used in the main page for ensuring uniqueness of HTML
     // elements.  To minimize the chance of a clash, let's reset the counter
     // to a very large number:
     if (isset($configArray['OpenURL']['embed']) && !empty($configArray['OpenURL']['embed'])) {
         include_once 'sys/Counter.php';
         $interface->assign('openUrlCounter', new Counter(100000));
     }
     // Whether embedded openurl autocheck is enabled
     if (isset($configArray['OpenURL']['autocheck']) && $configArray['OpenURL']['autocheck']) {
         $interface->assign('openUrlAutoCheck', true);
     }
     // Set Proxy URL
     if (isset($configArray['EZproxy']['host'])) {
         $interface->assign('proxy', $configArray['EZproxy']['host']);
     }
     // Determine whether to display book previews
     if (isset($configArray['Content']['previews'])) {
         $interface->assignPreviews();
     }
     $interface->assign("showContext", isset($configArray['Content']['showHierarchyTree']) ? $configArray['Content']['showHierarchyTree'] : false);
     // Initialise SearchObject.
     $searchObject = SearchObjectFactory::initSearchObject('PCI');
     $searchObject->init();
     $searchObject->setLimit(10);
     // Search
     $result = $searchObject->processSearch(true, true);
     // We'll need recommendations no matter how many results we found:
     $interface->assign('qtime', round($searchObject->getQuerySpeed(), 2));
     $interface->assign('spellingSuggestions', $searchObject->getSpellingSuggestions());
     $interface->assign('lookfor', $searchObject->displayQuery());
     $interface->assign('more', $searchObject->renderSearchUrl());
     if ($showGlobalFiltersNote = $interface->getGlobalFiltersNotification('Primo Central')) {
         $interface->assign('showGlobalFiltersNote', $showGlobalFiltersNote);
     }
     $searchWithoutLocalFilters = $searchObject->renderSearchUrl(false);
     $searchWithoutLocalFilters = str_replace('/PCI/Search', '/Search/DualResults', $searchWithoutLocalFilters);
     $interface->assign('searchWithoutLocalFilters', $searchWithoutLocalFilters);
     // We want to guide the user to login for access to licensed material
     $interface->assign('methodsAvailable', Login::getActiveAuthorizationMethods());
     $interface->assign('userAuthorized', UserAccount::isAuthorized());
     if ($result['recordCount'] > 0) {
         // Display Listing of Results
         $summary = $searchObject->getResultSummary();
         $page = $summary['page'];
         $interface->assign('recordCount', $summary['resultTotal']);
         $interface->assign('recordStart', $summary['startRecord']);
         $interface->assign('recordEnd', $summary['endRecord']);
         $interface->assign('recordSet', $result['response']['docs']);
         // If our result set is larger than the number of records that
         // PCI will let us page through, we should cut off the number
         // before passing it to our paging mechanism:
         $config = getExtraConfigArray('PCI');
         $pageLimit = isset($config['General']['result_limit']) ? $config['General']['result_limit'] : 2000;
         $totalPagerItems = $summary['resultTotal'] < $pageLimit ? $summary['resultTotal'] : $pageLimit;
     } else {
         if ($searchObject->isEmptySearch()) {
             $interface->assign('noQuery', true);
         }
     }
     // 'Finish' the search... complete timers and log search history.
     $searchObject->close();
     $interface->assign('time', round($searchObject->getTotalSpeed(), 2));
     return $interface->fetch('Search/list-dual-pci.tpl');
 }
Esempio n. 23
0
 /**
  * Send feedback on record.
  *
  * @param string $from    Message sender address
  * @param string $message Message to send
  *
  * @return mixed          Boolean true on success, PEAR_Error on failure.
  * @access public
  */
 public function sendEmail($from, $message)
 {
     global $interface;
     global $configArray;
     $institutionDetails = $this->recordDriver->getInstitutionDetails();
     $datasources = getExtraConfigArray('datasources');
     $to = $institutionDetails['datasource'] == '' ? $configArray['Site']['email'] : $datasources[$institutionDetails['datasource']]['feedbackEmail'];
     $subject = translate('Feedback on Record') . ': ' . $this->recordDriver->getBreadcrumb();
     $interface->assign('from', $from);
     $interface->assign('emailDetails', $interface->fetch($this->recordDriver->getSearchResult('email')));
     $interface->assign('recordID', $this->recordDriver->getUniqueID());
     $interface->assign('message', $message);
     $body = $interface->fetch('Emails/catalog-record.tpl');
     $mail = new VuFindMailer();
     return $mail->send($to, $from, $subject, $body);
 }
Esempio n. 24
0
 public function __construct($searchObject, $params)
 {
     global $configArray;
     // Save the passed-in SearchObject:
     $this->searchObject = $searchObject;
     // Parse the additional settings:
     $params = explode(':', $params);
     $mainSection = empty($params[0]) ? 'Results' : $params[0];
     $checkboxSection = isset($params[1]) ? $params[1] : false;
     $iniName = isset($params[2]) ? $params[2] : 'facets';
     if ($searchObject->getSearchType() == 'genealogy') {
         $config = getExtraConfigArray($iniName);
         $this->mainFacets = isset($config[$mainSection]) ? $config[$mainSection] : array();
     } else {
         $searchLibrary = Library::getActiveLibrary();
         global $locationSingleton;
         $searchLocation = $locationSingleton->getActiveLocation();
         $userLocation = Location::getUserHomeLocation();
         $hasSearchLibraryFacets = $searchLibrary != null && count($searchLibrary->facets) > 0;
         $hasSearchLocationFacets = $searchLocation != null && count($searchLocation->facets) > 0;
         if ($hasSearchLocationFacets) {
             $facets = $searchLocation->facets;
         } elseif ($hasSearchLibraryFacets) {
             $facets = $searchLibrary->facets;
         } else {
             $facets = Library::getDefaultFacets();
         }
         $this->facetSettings = array();
         $this->mainFacets = array();
         foreach ($facets as $facet) {
             $facetName = $facet->facetName;
             //Adjust facet name for local scoping
             if (isset($searchLibrary)) {
                 if ($facet->facetName == 'time_since_added') {
                     $facetName = 'local_time_since_added_' . $searchLibrary->subdomain;
                 } elseif ($facet->facetName == 'itype') {
                     $facetName = 'itype_' . $searchLibrary->subdomain;
                 } elseif ($facet->facetName == 'detailed_location') {
                     $facetName = 'detailed_location_' . $searchLibrary->subdomain;
                 } elseif ($facet->facetName == 'availability_toggle' && $configArray['Index']['enableDetailedAvailability']) {
                     $facetName = 'availability_toggle_' . $searchLibrary->subdomain;
                 }
             }
             if (isset($userLocation)) {
                 if ($facet->facetName == 'availability_toggle' && $configArray['Index']['enableDetailedAvailability']) {
                     $facetName = 'availability_toggle_' . $userLocation->code;
                 }
             }
             if (isset($searchLocation)) {
                 if ($facet->facetName == 'time_since_added' && $searchLocation->restrictSearchByLocation) {
                     $facetName = 'local_time_since_added_' . $searchLocation->code;
                 } elseif ($facet->facetName == 'availability_toggle' && $configArray['Index']['enableDetailedAvailability']) {
                     $facetName = 'availability_toggle_' . $searchLocation->code;
                 }
             }
             //Figure out if the facet should be included
             if ($mainSection == 'Results') {
                 if ($facet->showInResults == 1 && $facet->showAboveResults == 0) {
                     $this->facetSettings[$facetName] = $facet;
                     $this->mainFacets[$facetName] = $facet->displayName;
                 } elseif ($facet->showInAdvancedSearch == 1 && $facet->showAboveResults == 0) {
                     $this->facetSettings[$facetName] = $facet->displayName;
                 }
             } elseif ($mainSection == 'Author') {
                 if ($facet->showInAuthorResults == 1 && $facet->showAboveResults == 0) {
                     $this->facetSettings[$facetName] = $facet;
                     $this->mainFacets[$facetName] = $facet->displayName;
                 }
             }
         }
     }
     $this->checkboxFacets = $checkboxSection && isset($config[$checkboxSection]) ? $config[$checkboxSection] : array();
 }
 /**
  * Process transactions. Try to register unregistered transactions
  * and inform on expired transactions.
  *
  * @return void
  * @access public
  */
 public function process()
 {
     global $configArray;
     global $interface;
     ini_set('display_errors', true);
     $configArray = $mainConfig = readConfig();
     $datasourceConfig = getExtraConfigArray('datasources');
     // 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("OnlinePayment monitor started");
     // Setup Local Database Connection
     ConnectionManager::connectToDatabase();
     // Initialize Mailer
     $mailer = new VuFindMailer();
     $now = new DateTime();
     $expiredCnt = 0;
     $failedCnt = 0;
     $registeredCnt = 0;
     $remindCnt = 0;
     $user = false;
     $report = array();
     // Attempt to re-register paid transactions whose registration has failed.
     $tr = new Transaction();
     foreach ($tr->getFailedTransactions() as $t) {
         $this->msg("  Registering transaction id {$t->id} / {$t->transaction_id}");
         // check if the transaction has not been registered for too long
         $paid_time = new DateTime($t->paid);
         $diff = $now->diff($paid_time);
         $diffHours = $diff->days * 24 + $diff->h;
         if ($diffHours > $this->expireHours) {
             if (!isset($report[$t->driver])) {
                 $report[$t->driver] = 0;
             }
             $report[$t->driver]++;
             $expiredCnt++;
             if (!$t->setTransactionReported($t->transaction_id)) {
                 $this->err('    Failed to update transaction ' . $t->transaction_id . 'as reported');
             }
             $transaction = clone $t;
             $transaction->complete = Transaction::STATUS_REGISTRATION_EXPIRED;
             if ($transaction->update($t) === false) {
                 $this->err('    Failed to update transaction ' . $t->transaction_id . 'as expired.');
             } else {
                 $this->msg('    Transaction ' . $t->transaction_id . ' expired.');
             }
         } else {
             if ($user === false || $t->user_id != $user->id) {
                 $user = User::staticGet($t->user_id);
             }
             $catalog = ConnectionManager::connectToCatalog();
             if ($catalog && $catalog->status) {
                 $account = new User_account();
                 $account->user_id = $t->user_id;
                 $account->cat_username = $t->cat_username;
                 if ($account->find(true)) {
                     if (!($patron = $catalog->patronLogin($t->cat_username, $account->cat_password))) {
                         $this->err('    Could not perform patron login for transaction ' . $t->transaction_id);
                         $failedCnt++;
                         continue;
                     }
                 }
                 $res = $catalog->markFeesAsPaid($patron, $t->amount);
                 if ($res === true) {
                     if (!$t->setTransactionRegistered($t->transaction_id)) {
                         $this->err('    Failed to update transaction ' . $t->transaction_id . 'as registered');
                     }
                     $registeredCnt++;
                 } else {
                     $t->setTransactionRegistrationFailed($t->transaction_id, $res);
                     $failedCnt++;
                     $this->msg('    Registration of transaction ' . $t->transaction_id . ' failed');
                     $this->msg("      {$res}");
                 }
             } else {
                 $this->err("Failed to connect to catalog ({$patronId})");
                 continue;
             }
         }
     }
     // Report paid and unregistered transactions whose registration
     // can not be re-tried:
     $tr = new Transaction();
     foreach ($tr->getUnresolvedTransactions($this->reportIntervalHours) as $t) {
         $this->msg("  Transaction id {$t->transaction_id} still unresolved.");
         if (!$t->setTransactionReported($t->transaction_id)) {
             $this->err('    Failed to update transaction ' . $t->transaction_id . ' as reported');
         }
         if (!isset($report[$t->driver])) {
             $report[$t->driver] = 0;
         }
         $report[$t->driver]++;
         $remindCnt++;
     }
     if ($registeredCnt) {
         $this->msg("  Total registered: {$registeredCnt}");
     }
     if ($expiredCnt) {
         $this->msg("  Total expired: {$expiredCnt}");
     }
     if ($failedCnt) {
         $this->msg("  Total failed: {$failedCnt}");
     }
     if ($remindCnt) {
         $this->msg("  Total to be reminded: {$remindCnt}");
     }
     $configArray = readConfig();
     $siteLocal = $configArray['Site']['local'];
     $interface = new UInterface($siteLocal);
     // Send report of transactions that need to be resolved manually:
     foreach ($report as $driver => $cnt) {
         if ($cnt) {
             $settings = getExtraConfigArray("VoyagerRestful_{$driver}");
             if (!$settings || !isset($settings['OnlinePayment']['errorEmail'])) {
                 $this->err("  Error email for expired transactions not defined for driver {$driver} ({$cnt} expired transactions)");
                 continue;
             }
             $email = $settings['OnlinePayment']['errorEmail'];
             $this->msg("  [{$driver}] Inform {$cnt} expired transactions for driver {$driver} to {$email}");
             $mailer = new VuFindMailer();
             $subject = "Finna: ilmoitus tietokannan {$driver} epäonnistuneista verkkomaksuista";
             $interface->assign('driver', $driver);
             $interface->assign('cnt', $cnt);
             $msg = $interface->fetch('Emails/online-payment-error.tpl');
             if (!($result = $mailer->send($email, $this->fromEmail, $subject, $msg))) {
                 $this->err("    Failed to send error email to customer: {$email}");
             }
         }
     }
     $this->msg("OnlinePayment monitor completed");
     $this->reportErrors();
 }
Esempio n. 26
0
 /**
  * Assign necessary Smarty variables and return a template name to
  * load in order to display holdings extracted from the base record
  * (i.e. URLs in MARC 856 fields) and, if necessary, the ILS driver.
  * Returns null if no data is available.
  *
  * @param array $patron An array of patron data
  *
  * @return string Name of Smarty template file to display.
  * @access public
  */
 public function getHoldings($patron = false)
 {
     global $interface;
     global $configArray;
     // Only display OpenURL link if the option is turned on and we have
     // an ISSN.  We may eventually want to make this rule more flexible,
     // but for now the ISSN restriction is designed to be consistent with
     // the way we display items on the search results list. Actually,
     // display OpenURL link for records with ISBNs too.
     $hasOpenURL = $this->openURLActive('holdings') && ($this->getCleanISSN() || $this->getCleanISBN());
     if ($hasOpenURL) {
         $interface->assign('holdingsOpenURL', $this->getOpenURL());
     }
     // Display regular URLs unless OpenURL is present and configured to
     // replace them:
     if (!isset($configArray['OpenURL']['replace_other_urls']) || !$configArray['OpenURL']['replace_other_urls'] || !$hasOpenURL) {
         $interface->assign('holdingURLs', $this->getURLs());
     }
     $interface->assign('holdingLCCN', $this->getLCCN());
     $interface->assign('holdingArrOCLC', $this->getOCLC());
     // Load real-time data if available:
     $holdings = $this->getRealTimeHoldings($patron);
     $interface->assign('holdings', $holdings);
     $itemCount = 0;
     $requestCount = 0;
     if (is_array($holdings)) {
         foreach ($holdings as $locationArray) {
             if (!is_array($locationArray)) {
                 continue;
             }
             foreach ($locationArray as $location) {
                 if (is_array($location) && isset($location['status']) && isset($location['status']['reservations'])) {
                     if ($location['status']['reservations'] > $requestCount) {
                         $requestCount = $location['status']['reservations'];
                     }
                 }
                 if (isset($location['holdings']) && is_array($location['holdings'])) {
                     foreach ($location['holdings'] as $holding) {
                         if (isset($holding['total'])) {
                             $itemCount += $holding['total'];
                         }
                     }
                 }
             }
         }
     }
     $interface->assign('itemCount', $itemCount);
     $interface->assign('requestCount', $requestCount);
     $interface->assign('history', $this->getRealTimeHistory());
     // Source ID
     $sourceId = $this->getSourceID();
     $interface->assign('source', $sourceId);
     // NDL Location Service enabled
     $config = getExtraConfigArray('LocationService');
     if (isset($config['General']) && isset($config[$sourceId])) {
         $baseUrl = $config['General']['url'];
         $lang = $interface->getLanguage();
         $params = array('lang' => substr($lang, 0, 2), 'owner' => $config[$sourceId]['owner']);
         $url = $baseUrl . '?' . http_build_query($params);
         $interface->assign('locationServiceUrl', $url);
         if (isset($config['General']['modal']) && $config['General']['modal']) {
             $interface->assign('locationServiceModal', true);
         }
     }
     return 'RecordDrivers/Index/holdings.tpl';
 }
Esempio n. 27
0
 /**
  * Constructor
  *
  * Sets up SMS carriers and other settings from sms.ini.
  *
  * @access  public
  */
 public function __construct()
 {
     global $configArray;
     // if using sms.ini, then load the carriers from it
     // otherwise, fall back to the default list of US carriers
     if (isset($configArray['Extra_Config']['sms'])) {
         $smsConfig = getExtraConfigArray('sms');
         if (isset($smsConfig['Carriers']) && !empty($smsConfig['Carriers'])) {
             $this->carriers = array();
             foreach ($smsConfig['Carriers'] as $id => $config) {
                 list($domain, $name) = explode(':', $config, 2);
                 $this->carriers[$id] = array('name' => $name, 'domain' => $domain);
             }
         }
     }
     parent::__construct();
 }
Esempio n. 28
0
 /**
  * Process MetaLib search
  * 
  * @return void
  */
 function doMetaLib()
 {
     global $interface;
     global $configArray;
     // Initialise SearchObject.
     $searchObject = SearchObjectFactory::initSearchObject('MetaLib');
     $searchObject->init();
     if (isset($_GET['page'])) {
         $searchObject->setPage($_GET['page']);
     }
     $displayQuery = $searchObject->displayQuery();
     $interface->assign('lookfor', $displayQuery);
     $interface->assign('searchType', $searchObject->getSearchType());
     // Search MetaLib
     $template = null;
     if (!empty($displayQuery)) {
         $result = $searchObject->processSearch(true, true);
         // Whether RSI is enabled
         if (isset($configArray['OpenURL']['use_rsi']) && $configArray['OpenURL']['use_rsi']) {
             $interface->assign('rsi', true);
         }
         // Whether embedded openurl autocheck is enabled
         if (isset($configArray['OpenURL']['autocheck']) && $configArray['OpenURL']['autocheck']) {
             $interface->assign('openUrlAutoCheck', true);
         }
         // We'll need recommendations no matter how many results we found:
         $interface->assign('qtime', round($searchObject->getQuerySpeed(), 2));
         $interface->assign('spellingSuggestions', $searchObject->getSpellingSuggestions());
         $interface->assign('topRecommendations', $searchObject->getRecommendationsTemplates('top'));
         $interface->assign('sideRecommendations', $searchObject->getRecommendationsTemplates('side'));
         $interface->assign('disallowedDatabases', $result['disallowedDatabases']);
         $interface->assign('failedDatabases', $result['failedDatabases']);
         $interface->assign('successDatabases', $result['successDatabases']);
         $methodsAvailable = Login::getActiveAuthorizationMethods();
         $userAuthorized = UserAccount::isAuthorized();
         $setNotification = array();
         // We want to guide the user to login for access to licensed material
         if (!$userAuthorized && $methodsAvailable) {
             $setNotification[] = '<p>' . translate('authorize_user_notification') . '</p>';
         }
         if ($result['recordCount'] > 0) {
             $summary = $searchObject->getResultSummary();
             $page = $summary['page'];
             $interface->assign('recordCount', $summary['resultTotal']);
             $interface->assign('recordStart', $summary['startRecord']);
             $interface->assign('recordEnd', $summary['endRecord']);
             $interface->assign('recordSet', $result['documents']);
             $interface->assign('sortList', $searchObject->getSortList());
             // If our result set is larger than the number of records that
             // MetaLib will let us page through (10000 records per database),
             // we should cut off the number before passing it to our paging
             // mechanism:
             $config = getExtraConfigArray('MetaLib');
             $pageLimit = isset($config['General']['result_limit']) ? $config['General']['result_limit'] : 2000;
             $totalPagerItems = $summary['resultTotal'] < $pageLimit ? $summary['resultTotal'] : $pageLimit;
             // Process Paging
             $link = $searchObject->renderLinkPageTemplate();
             $options = array('totalItems' => $totalPagerItems, 'fileName' => $link, 'perPage' => $summary['perPage']);
             $pager = new VuFindPager($options);
             $interface->assign('pageLinks', $pager->getLinks());
             $interface->assign('pagesTotal', $totalPagerItems);
             // Display Listing of Results
             $template = 'list-list.tpl';
         } else {
             $interface->assign('recordCount', 0);
             // Was the empty result set due to an error?
             $error = $searchObject->getIndexError();
             if ($error !== false) {
                 // If it's a parse error or the user specified an invalid field, we
                 // should display an appropriate message:
                 if (stristr($error, 'user.entered.query.is.malformed') || stristr($error, 'unknown.field')) {
                     $interface->assign('parseError', true);
                 } else {
                     // Unexpected error -- let's treat this as a fatal condition.
                     PEAR::raiseError(new PEAR_Error('Unable to process query<br />MetaLib Returned: ' . $error));
                 }
             }
             // Show notification if all databases were disallowed.
             if (count($result['successDatabases']) === 0 && count($result['failedDatabases']) === 0 && count($result['disallowedDatabases']) > 0) {
                 array_unshift($setNotification, '<p>' . translate('metalib_not_authorized_all') . '</p>');
                 $interface->assign('noSearch', true);
             }
             $template = 'list-none.tpl';
         }
         $interface->assign('setNotification', implode('', $setNotification));
     } else {
         $result = false;
         $interface->assign('noQuery', true);
         $template = 'list-none.tpl';
     }
     // 'Finish' the search... complete timers and log search history.
     $searchObject->close();
     $interface->assign('time', round($searchObject->getTotalSpeed(), 2));
     // Show the save/unsave code on screen
     // The ID won't exist until after the search has been put in the search
     //    history so this needs to occur after the close() on the searchObject
     $interface->assign('showSaved', true);
     $interface->assign('savedSearch', $searchObject->isSavedSearch());
     $interface->assign('searchId', $searchObject->getSearchId());
     // Save the URL of this search to the session so we can return to it easily:
     $_SESSION['lastSearchURL'] = $searchObject->renderSearchUrl();
     return $interface->fetch("MetaLib/{$template}");
 }
Esempio n. 29
0
 /**
  * Checks if browse functionality is enabled
  *
  * @return boolean True if browse is enabled
  */
 protected function isBrowseEnabled()
 {
     $searchSettings = getExtraConfigArray('searches');
     if (isset($searchSettings['BrowseExtended'])) {
         foreach ($searchSettings['BrowseExtended'] as $key => $val) {
             if (strcmp('Database', $key) === 0 && (bool) $val) {
                 return true;
             }
         }
     }
     return false;
 }
Esempio n. 30
0
 /**
  * Return initialized online payment handler.
  *
  * @param string $patronId Patron's Catalog username (barcode).
  *
  * @return mixed handler or false on error
  * @access public
  */
 public function getOnlinePaymentHandler($patronId)
 {
     $config = getExtraConfigArray('datasources');
     list($driver, $cat_username) = explode('.', $patronId, 2);
     if (!isset($config[$driver]['onlinePayment'])) {
         return false;
     }
     $params = $config[$driver]['onlinePayment'];
     try {
         return OnlinePaymentFactory::initOnlinePayment($params['handler'], $params);
     } catch (Exception $e) {
         error_log("Error initializing payment handler {$driver} for patron {$patronId}: " . $e->getMessage());
         return false;
     }
 }