/** * 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 \Zend\Stdlib\Parameters $request The user request * @param string $typeParam Request parameter containing search * type * @param string $queryParam Request parameter containing query * string * * @return array */ public function getSuggestions($request, $typeParam = 'type', $queryParam = 'q') { // Process incoming parameters: $type = $request->get($typeParam, ''); $query = $request->get($queryParam, ''); // get Autocomplete_Type config $searcher = $request->get('searcher', 'Solr'); $options = $this->getServiceLocator()->get('SearchManager')->setSearchClassId($searcher)->getOptionsInstance(); $config = ConfigReader::getConfig($options->getSearchIni()); $types = isset($config->Autocomplete_Types) ? $config->Autocomplete_Types->toArray() : array(); // Figure out which handler to use: if (!empty($type) && isset($types[$type])) { $module = $types[$type]; } else { if (isset($config->Autocomplete->default_handler)) { $module = $config->Autocomplete->default_handler; } else { $module = false; } } // Get suggestions: if ($module) { if (strpos($module, ':') === false) { $module .= ':'; // force colon to avoid warning in explode below } list($name, $params) = explode(':', $module, 2); $handler = $this->get($name); $handler->setConfig($params); } return isset($handler) && is_object($handler) ? array_values($handler->getSuggestions($query)) : array(); }
/** * @param Parameters $params * * @return Parameters */ protected function initDefaults(Parameters $params) { if (is_null($params->get('quality')) || !strlen(trim($params->get('quality')))) { $params->set('quality', QualityInterface::QUALITY_THUMBNAIL); } if (is_null($params->get('source')) || !strlen(trim($params->get('source')))) { $params->set('source', SourceNameInterface::SOURCE_USER); } return $params; }
/** * @param UploaderModelInterface $model * @param null $values * @return string * @throws InvalidArgumentException */ public function render($model, $values = null) { if (!$model instanceof UploaderModelInterface) { throw new InvalidArgumentException("Unsupportable type of model, required type UploaderModelInterface"); } $resources = $model->getResourcePaths(); $url = array_pop($resources); $funcNum = $this->params->get('CKEditorFuncNum', 0); return "<script type='text/javascript'>\n window.parent.CKEDITOR.tools.callFunction({$funcNum}, '" . $url . "', '');\n </script>"; }
/** * @return Http\Client */ public function getHttpClient() { if (!$this->httpClient instanceof Http\Client) { $this->httpClient = $this->getHttpClientFactory()->createHttpClient($this->options->get(self::OPT_HTTP_CLIENT, array())); } return $this->httpClient; }
/** * Initialize the object's search settings from a request object. * * @param \Zend\StdLib\Parameters $request Parameter object representing user * request. * * @return void */ protected function initSearch($request) { // Convert special 'id' parameter into a standard hidden filter: $idParam = $request->get('id', []); if (!empty($idParam)) { $this->addHiddenFilter('ids:' . implode("\t", $idParam)); } }
/** * Add filters to the object based on values found in the request object. * * @param \Zend\StdLib\Parameters $request Parameter object representing user * request. * * @return void */ protected function initFilters($request) { // Special filter -- if the "id" parameter is set, limit to a specific list: $id = $request->get('id'); if (!empty($id)) { $this->addFilter("lists:{$id}"); } // Otherwise use standard parent behavior: return parent::initFilters($request); }
/** * 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 \Zend\Stdlib\Parameters $request The user request * @param string $typeParam Request parameter containing search * type * @param string $queryParam Request parameter containing query * string * * @return array */ public function getSuggestions($request, $typeParam = 'type', $queryParam = 'q') { // Process incoming parameters: $type = $request->get($typeParam, ''); $query = $request->get($queryParam, ''); $searcher = $request->get('searcher', 'Solr'); $hiddenFilters = $request->get('hiddenFilters', []); // If we're using a combined search box, we need to override the searcher // and type settings. if (substr($type, 0, 7) == 'VuFind:') { list(, $tmp) = explode(':', $type, 2); list($searcher, $type) = explode('|', $tmp, 2); } // get Autocomplete_Type config $options = $this->getServiceLocator()->get('VuFind\\SearchOptionsPluginManager')->get($searcher); $config = $this->getServiceLocator()->get('VuFind\\Config')->get($options->getSearchIni()); $types = isset($config->Autocomplete_Types) ? $config->Autocomplete_Types->toArray() : []; // Figure out which handler to use: if (!empty($type) && isset($types[$type])) { $module = $types[$type]; } else { if (isset($config->Autocomplete->default_handler)) { $module = $config->Autocomplete->default_handler; } else { $module = false; } } // Get suggestions: if ($module) { if (strpos($module, ':') === false) { $module .= ':'; // force colon to avoid warning in explode below } list($name, $params) = explode(':', $module, 2); $handler = $this->get($name); $handler->setConfig($params); } if (is_callable([$handler, 'addFilters'])) { $handler->addFilters($hiddenFilters); } return isset($handler) && is_object($handler) ? array_values($handler->getSuggestions($query)) : []; }
/** * Support method for _initSearch() -- handle basic settings. * * @param \Zend\StdLib\Parameters $request Parameter object representing user * request. * * @return boolean True if search settings were found, false if not. */ protected function initBasicSearch($request) { // If no lookfor parameter was found, we have no search terms to // add to our array! if (is_null($lookfor = $request->get('lookfor'))) { return false; } // Set the search (handler is always Author for this module): $this->setBasicSearch($lookfor, 'Author'); return true; }
/** * init * * Called at the end of the Search Params objects' initFromRequest() method. * This method is responsible for setting search parameters needed by the * recommendation module and for reading any existing search parameters that may * be needed. * * @param \VuFind\Search\Base\Params $params Search parameter object * @param \Zend\StdLib\Parameters $request Parameter object representing user * request. * * @return void */ public function init($params, $request) { // Build a search parameters object: $sm = $this->getSearchManager()->setSearchClassId($this->getSearchClassId()); $params = $sm->getParams(); $params->setLimit($this->limit); $params->setBasicSearch($request->get($this->requestParam)); // Perform the search: $this->results = $sm->setSearchClassId($this->getSearchClassId())->getResults($params); $this->results->performAndProcessSearch(); }
/** * Sends the HTTP request and returns the response. * * @param Http\Request $httpRequest * @throws HttpClientException * @return Http\Response */ public function sendHttpRequest(Http\Request $httpRequest) { $this->setLastHttpRequest($httpRequest); $this->httpClient->setOptions($this->options->get(self::OPT_HTTP_OPTIONS, array())); try { $httpResponse = $this->httpClient->send($httpRequest); } catch (\Exception $e) { throw new HttpClientException(sprintf("Exception during HTTP request: [%s] %s", get_class($e), $e->getMessage())); } $this->setLastHttpResponse($httpResponse); return $httpResponse; }
/** * Process renewal requests. * * @param \Zend\Stdlib\Parameters $request Request object * @param \VuFind\ILS\Connection $catalog ILS connection object * @param array $patron Current logged in patron * * @return array The result of the renewal, an * associative array keyed by item ID (empty if no renewals performed) */ public function processRenewals($request, $catalog, $patron) { // Pick IDs to renew based on which button was pressed: $all = $request->get('renewAll'); $selected = $request->get('renewSelected'); if (!empty($all)) { $ids = $request->get('renewAllIDS'); } else { if (!empty($selected)) { $ids = $request->get('renewSelectedIDS'); } else { $ids = []; } } // Retrieve the flashMessenger helper: $flashMsg = $this->getController()->flashMessenger(); // If there is actually something to renew, attempt the renewal action: if (is_array($ids) && !empty($ids)) { $renewResult = $catalog->renewMyItems(['details' => $ids, 'patron' => $patron]); if ($renewResult !== false) { // Assign Blocks to the Template if (isset($renewResult['blocks']) && is_array($renewResult['blocks'])) { foreach ($renewResult['blocks'] as $block) { $flashMsg->setNamespace('info')->addMessage($block); } } // Send back result details: return $renewResult['details']; } else { // System failure: $flashMsg->setNamespace('error')->addMessage('renew_error'); } } else { if (!empty($all) || !empty($selected)) { // Button was clicked but no items were selected: $flashMsg->setNamespace('error')->addMessage('renew_empty_selection'); } } return []; }
/** * Support method for _initSearch() -- handle basic settings. * * @param \Zend\StdLib\Parameters $request Parameter object representing user * request. * * @return boolean True if search settings were found, false if not. */ protected function initBasicSearch($request) { // If no lookfor parameter was found, we have no search terms to // add to our array! if (is_null($lookfor = $request->get('author'))) { return false; } // Force the search to be a phrase: $lookfor = '"' . str_replace('"', '\\"', $lookfor) . '"'; // Set the search (handler is always Author for this module): $this->setBasicSearch($lookfor, 'Author'); return true; }
public function handleSort(Manager $manager, Parameters $request, $defaultSort, $target) { $user = $manager->isLoggedIn(); $requestParams = $request->toArray(); if ($user) { //in case user changed the the sort settings on the result list with a specialized UI control //we want to serialize the new value in database if (array_key_exists('sortControlElement', $requestParams)) { if (array_key_exists('sort', $requestParams)) { $sort = $requestParams['sort']; $dbSort = unserialize($user->default_sort); $dbSort[$target] = $requestParams['sort']; $user->default_sort = serialize($dbSort); $user->save(); } else { $tSort = $request->get('sort'); $sort = !empty($tSort) ? $tSort : $defaultSort; } } else { $tSort = $request->get('sort'); $sort = !empty($tSort) ? $tSort : $defaultSort; //overwrite sort if value is set in database if ($user->default_sort) { $userDefaultSort = unserialize($user->default_sort); if (isset($userDefaultSort[$target])) { $sort = $userDefaultSort[$target]; } } } } else { $sort = $request->get('sort'); } // Check for special parameter only relevant in RSS mode: if ($request->get('skip_rss_sort', 'unset') != 'unset') { $this->skipRssSort = true; } return $sort; }
/** * @param ServerRequestInterface $request * @param ResponseInterface $response * * @return HtmlResponse|RedirectResponse */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response) { try { $album = (array) $this->albumService->getAlbum($request->getAttribute('id')); } catch (\Exception $e) { return new HtmlResponse($this->template->render('error::404'), 404); } if ($request->getMethod() === 'POST') { $body = new Parameters($request->getParsedBody()); $del = $body->get('del', 'No'); if (strtolower($del) === 'yes') { $this->albumService->deleteAlbum($album); } return new RedirectResponse($this->router->generateUri('album.index')); } return new HtmlResponse($this->template->render('album::delete', ['album' => $album])); }
/** * @param ServerRequestInterface $request * @param ResponseInterface $response * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response) { try { $album = $this->albumService->getAlbum($request->getAttribute('id')); if ($request->getMethod() === 'POST') { $body = new Parameters($request->getParsedBody()); $del = $body->get('del', 'No'); if (strtolower($del) === 'yes') { $this->albumService->deleteAlbum($album); /** * @var Session $session */ $session = $request->getAttribute('session'); $session->getSegment('App\\Album')->setFlash('flash', ['type' => 'success', 'message' => sprintf('Successfully deleted album %s (%s)', $album->getTitle(), $album->getArtist())]); } // Redirect to list of albums return new RedirectResponse($this->router->generateUri('album.index')); } } catch (\Exception $e) { // do something useful } return new HtmlResponse($this->template->render('album::delete', compact('album'))); }
/** * Initialize new items filter (first_indexed) * * @param \Zend\StdLib\Parameters $request Parameter object representing user * request. * * @return void */ protected function initNewItemsFilter($request) { // first_indexed filter automatically included, no query param required // (compatible with Finna 1 implementation) $from = $request->get('first_indexedfrom'); $from = call_user_func([$this, 'formatDateForFullDateRange'], $from); if ($from != '*') { $rangeFacet = call_user_func([$this, 'buildFullDateRangeFilter'], 'first_indexed', $from, '*'); $this->addFilter($rangeFacet); } }
/** * Update and save the list object using a request object -- useful for * sharing form processing between multiple actions. * * @param \VuFind\Db\Row\User|bool $user Logged-in user (false if none) * @param \Zend\Stdlib\Parameters $request Request to process * * @return int ID of newly created row * @throws ListPermissionException * @throws MissingFieldException */ public function updateFromRequest($user, $request) { $this->title = $request->get('title'); $this->description = $request->get('desc'); $this->public = $request->get('public'); $this->save($user); return $this->id; }
/** * init * * Called at the end of the Search Params objects' initFromRequest() method. * This method is responsible for setting search parameters needed by the * recommendation module and for reading any existing search parameters that may * be needed. * * @param \VuFind\Search\Base\Params $params Search parameter object * @param \Zend\StdLib\Parameters $request Parameter object representing user * request. * * @return void */ public function init($params, $request) { // Save search query in case we need it later: $this->lookfor = $request->get($this->requestParam); }
/** * Called at the end of the Search Params objects' initFromRequest() method. * This method is responsible for setting search parameters needed by the * recommendation module and for reading any existing search parameters that may * be needed. * * @param \VuFind\Search\Base\Params $params Search parameter object * @param \Zend\StdLib\Parameters $request Parameter object representing user * request. * * @return void */ public function init($params, $request) { // See if we can determine the label for the current search type; first // check for an override in the GET parameters, then look at the incoming // params object.... $typeLabel = $request->get('typeLabel'); $type = $request->get('type'); if (empty($typeLabel) && !empty($type)) { $typeLabel = $params->getOptions()->getLabelForBasicHandler($type); } // Extract a search query: $lookfor = $request->get($this->requestParam); if (empty($lookfor) && is_object($params)) { $lookfor = $params->getQuery()->getAllTerms(); } // Set up the callback to initialize the parameters: $limit = $this->limit; $callback = function ($runner, $params) use($lookfor, $limit, $typeLabel) { $params->setLimit($limit); $params->setBasicSearch($lookfor, $params->getOptions()->getHandlerForLabel($typeLabel)); }; // Perform the search: $this->results = $this->runner->run([], $this->getSearchClassId(), $callback); }
/** * Called at the end of the Search Params objects' initFromRequest() method. * This method is responsible for setting search parameters needed by the * recommendation module and for reading any existing search parameters that may * be needed. * * @param \VuFind\Search\Base\Params $params Search parameter object * @param \Zend\StdLib\Parameters $request Parameter object representing user * request. * * @return void * @throws \Exception */ public function init($params, $request) { // Validate module setting: if (null === $this->module) { throw new \Exception('Missing module property'); } // Parse out parameters: $settings = explode(':', $this->rawParams); // Make sure all elements of the params array are filled in, even if just // with a blank string, so we can rebuild the parameters to pass through // AJAX later on! for ($i = 0; $i < $this->paramCount; $i++) { $settings[$i] = isset($settings[$i]) ? $settings[$i] : ''; } // Collect the best possible search term(s): $lookforParam = empty($settings[0]) ? 'lookfor' : $settings[0]; $this->lookfor = $request->get($lookforParam, ''); if (empty($this->lookfor) && is_object($params)) { $this->lookfor = $params->getQuery()->getAllTerms(); } $this->lookfor = trim($this->lookfor); // In AJAX mode, the query will always be found in the 'lookfor' parameter, // so override the setting: $settings[0] = 'lookfor'; // Now rebuild the parameters to pass via AJAX: $this->processedParams = implode(':', $settings); }
/** * Called at the end of the Search Params objects' initFromRequest() method. * This method is responsible for setting search parameters needed by the * recommendation module and for reading any existing search parameters that may * be needed. * * @param \VuFind\Search\Base\Params $params Search parameter object * @param \Zend\StdLib\Parameters $request Parameter object representing user * request. * * @return void */ public function init($params, $request) { // Parse out parameters: $settings = explode(':', $this->rawParams); // Make sure all elements of the params array are filled in, even if just // with a blank string, so we can rebuild the parameters to pass through // AJAX later on! for ($i = 0; $i < 4; $i++) { $settings[$i] = isset($settings[$i]) ? $settings[$i] : ''; } // Collect the best possible search term(s): $this->lookfor = $request->get('lookfor', ''); if (empty($this->lookfor) && is_object($params)) { $this->lookfor = $params->getQuery()->getAllTerms(); } $this->lookfor = trim($this->lookfor); $this->processedParams = implode(':', $settings); }
/** * Returns the refresh token expire interval. * * @return string */ public function getRefreshTokenExpireInterval() { return $this->options->get(self::OPT_REFRESH_TOKEN_EXPIRE_INTERVAL, 'PT24H'); }
/** * Log an exception triggered by ZF2 for administrative purposes. * * @param \Exception $error Exception to log * @param \Zend\Stdlib\Parameters $server Server metadata * * @return void */ public function logException($error, $server) { // We need to build a variety of pieces so we can supply // information at five different verbosity levels: $baseError = $error->getMessage(); $referer = $server->get('HTTP_REFERER', 'none'); $basicServer = '(Server: IP = ' . $server->get('REMOTE_ADDR') . ', ' . 'Referer = ' . $referer . ', ' . 'User Agent = ' . $server->get('HTTP_USER_AGENT') . ', ' . 'Host = ' . $server->get('HTTP_HOST') . ', ' . 'Request URI = ' . $server->get('REQUEST_URI') . ')'; $detailedServer = "\nServer Context:\n" . print_r($server->toArray(), true); $basicBacktrace = $detailedBacktrace = "\nBacktrace:\n"; if (is_array($error->getTrace())) { foreach ($error->getTrace() as $line) { if (!isset($line['file'])) { $line['file'] = 'unlisted file'; } if (!isset($line['line'])) { $line['line'] = 'unlisted'; } $basicBacktraceLine = $detailedBacktraceLine = $line['file'] . ' line ' . $line['line'] . ' - ' . (isset($line['class']) ? 'class = ' . $line['class'] . ', ' : '') . 'function = ' . $line['function']; $basicBacktrace .= "{$basicBacktraceLine}\n"; if (!empty($line['args'])) { $args = []; foreach ($line['args'] as $i => $arg) { $args[] = $i . ' = ' . $this->argumentToString($arg); } $detailedBacktraceLine .= ', args: ' . implode(', ', $args); } else { $detailedBacktraceLine .= ', args: none.'; } $detailedBacktrace .= "{$detailedBacktraceLine}\n"; } } $errorDetails = [1 => $baseError, 2 => $baseError . $basicServer, 3 => $baseError . $basicServer . $basicBacktrace, 4 => $baseError . $detailedServer . $basicBacktrace, 5 => $baseError . $detailedServer . $detailedBacktrace]; $this->log(BaseLogger::CRIT, $errorDetails); }
public function testParametersGetReturnsDefaultValueIfNonExistent() { $parameters = new Parameters(); $this->assertEquals(5, $parameters->get('nonExistentProp', 5)); }
/** * Add hidden filters to the object based on values found in the request object. * * @param \Zend\StdLib\Parameters $request Parameter object representing user * request. * * @return void */ protected function initHiddenFilters($request) { $hiddenFilters = $request->get('hiddenFilters'); if (!empty($hiddenFilters) && is_array($hiddenFilters)) { foreach ($hiddenFilters as $current) { $this->addHiddenFilter($current); } } }
/** * Support function to get publication date range. Return string in the form * "YYYY-YYYY" * * @param string $field Name of filter field to check for * date limits * @param \VuFind\Search\Params\Base $params Search parameter object * @param \Zend\StdLib\Parameters $request Parameter object representing user * request. * * @return string */ protected function getPublishedDates($field, $params, $request) { // Try to extract range details from request parameters or SearchObject: $from = $request->get($field . 'from'); $to = $request->get($field . 'to'); if (!is_null($from) && !is_null($to)) { $range = ['from' => $from, 'to' => $to]; } else { if (is_object($params)) { $currentFilters = $params->getFilters(); if (isset($currentFilters[$field][0])) { $range = SolrUtils::parseRange($currentFilters[$field][0]); } } } // Normalize range if we found one: if (isset($range)) { if (empty($range['from']) || $range['from'] == '*') { $range['from'] = 0; } if (empty($range['to']) || $range['to'] == '*') { $range['to'] = date('Y') + 1; } return $range['from'] . '-' . $range['to']; } // No range found? Return empty string: return ''; }
/** * Convert user request parameters into a query (currently for advanced searches * only). * * @param Parameters $request User-submitted parameters * @param string $defaultHandler Default search handler * * @return Query|QueryGroup */ public static function fromRequest(Parameters $request, $defaultHandler) { $groupCount = 0; $groups = []; // Loop through each search group while (!is_null($lookfor = $request->get("lookfor{$groupCount}"))) { $group = []; $lastBool = null; // Loop through each term inside the group for ($i = 0; $i < count($lookfor); $i++) { // Ignore advanced search fields with no lookup if ($lookfor[$i] != '') { // Use default fields if not set $typeArr = $request->get('type' . $groupCount); $handler = isset($typeArr[$i]) && !empty($typeArr[$i]) ? $typeArr[$i] : $defaultHandler; $opArr = $request->get('op' . $groupCount); $operator = isset($opArr[$i]) && !empty($opArr[$i]) ? $opArr[$i] : null; // Add term to this group $boolArr = $request->get('bool' . $groupCount); $lastBool = isset($boolArr[0]) ? $boolArr[0] : null; $group[] = new Query($lookfor[$i], $handler, $operator); } } // Make sure we aren't adding groups that had no terms if (count($group) > 0) { // Add the completed group to the list $groups[] = new QueryGroup($lastBool, $group); } // Increment $groupCount++; } return count($groups) > 0 ? new QueryGroup($request->get('join'), $groups) : new Query(); }
/** * Initialize the object's search settings from a request object. * * @param \Zend\StdLib\Parameters $request Parameter object representing user * request. * * @return void */ protected function initSearch($request) { $this->recordsToRequest = $request->get('id', []); // We always want to display the entire list as one page: $this->setLimit(count($this->recordsToRequest)); }
/** * Initialize the object's search settings from a request object. * * @param \Zend\StdLib\Parameters $request Parameter object representing user * request. * * @return void */ protected function initSearch($request) { // Special case -- did we get a list of IDs instead of a standard query? $ids = $request->get('overrideIds', null); if (is_array($ids)) { $this->setQueryIDs($ids); } else { // Use standard initialization: parent::initSearch($request); } }
/** * Add filters to the object based on values found in the request object. * * @param \Zend\StdLib\Parameters $request Parameter object representing user * request. * * @return void */ protected function initFilters($request) { // Handle standard filters: $filter = $request->get('filter'); if (!empty($filter)) { if (is_array($filter)) { foreach ($filter as $current) { $this->addFilter($current); } } else { $this->addFilter($filter); } } // If we don't have the special flag indicating that defaults have // been applied, and if we do have defaults, apply them: if ($request->get('dfApplied')) { $this->defaultsApplied = true; } else { $defaults = $this->getOptions()->getDefaultFilters(); if (!empty($defaults)) { foreach ($defaults as $current) { $this->addFilter($current); } $this->defaultsApplied = true; } } // Handle range filters: $this->initRangeFilters($request); }