google_json_api-1.0.0-rc2/google_json_api.module
google_json_api.module
<?php
/**
* @file
* Integrates Google Custom Search JSON API with core Search functionality.
*/
use Drupal\Core\Entity\EntityInterface;
use Drupal\search\Entity\SearchPage;
use Drupal\Core\Url;
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Implements hook_help().
*
* @see hook_help()
*/
function google_json_api_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'google_json_api.settings':
return t('The Google Programmable Search JSON API endpoints are provided by default. They likely will not need to be changed.');
case 'help.page.google_json_api':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' .
t('The Google JSON API module allows for the creation of search pages that use
the <a href=":googlelink">Google Programmable Search Engine JSON API</a>.',
[
':googlelink' => 'https://developers.google.com/custom-search/v1/overview',
]) .
'</p>';
$output .= '<p>' .
t('Each custom search page can be configured to use either the
<a href=":normalapi">Custom Search JSON API</a> or the
<a href=":siterestrictedapi">Custom Search Site Restricted JSON API</a>',
[
':normalapi' => 'https://developers.google.com/custom-search/v1/using_rest',
':siterestrictedapi' => 'https://developers.google.com/custom-search/v1/site_restricted_api',
]) .
'</p>';
$output .= '<p>' .
t('Additionally, each search page has configuration options
controlling results count, search form features (search page switching
and sorting), and user messaging.') . '</p>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Creating Search Pages') . '</dt>';
$output .= '<dd>' .
t('Users with the <i>Administer Google JSON API</i> permission can create custom
<a href=":searchpages">search pages</a> to retrieve search results from a
<a href=":gpse">Google Programmable Search Engine</a>.
A local index does not need to be maintained.',
[
':searchpages' => Url::fromRoute('entity.search_page.collection')->toString(),
':gpse' => 'https://programmablesearchengine.google.com/cse/all',
]) .
'</dd>';
$output .= '<dt>' . t('Configuring Search Pages') . '</dt>';
$output .= '<dd>' .
t('Users with the <i>Administer Google JSON API</i> permission can configure
the presentation of search results pages. Sort options, search page selection,
results per page, and various end-user messages can be configured.') .
'</dd>';
$output .= '</dl>';
return $output;
}
}
/**
* Implements hook_theme().
*/
function google_json_api_theme($existing, $type, $theme, $path) {
return [
'google_json_api_result' => [
'variables' => [
'result' => NULL,
'term' => NULL,
],
'file' => 'google_json_api.theme.inc',
'template' => 'google_json_api_result',
],
'google_json_api_results_message' => [
'variables' => [
'message' => NULL,
'term' => NULL,
],
'file' => 'google_json_api.theme.inc',
'template' => 'google_json_api_results_message',
],
'google_json_api_results_limitation_message' => [
'variables' => [
'message' => NULL,
'term' => NULL,
],
'file' => 'google_json_api.theme.inc',
'template' => 'google_json_api_results_limitation_message',
],
'google_json_api_promoted_result' => [
'variables' => [
'promotion' => NULL,
'term' => NULL,
],
'file' => 'google_json_api.theme.inc',
'template' => 'google_json_api_promoted_result',
],
'google_json_api_spelling_correction' => [
'variables' => [
'spelling' => NULL,
'url' => NULL,
],
'file' => 'google_json_api.theme.inc',
'template' => 'google_json_api_spelling_correction',
],
'google_json_api_no_results_message' => [
'variables' => [
'message' => NULL,
'term' => NULL,
],
'file' => 'google_json_api.theme.inc',
'template' => 'google_json_api_no_results_message',
],
'google_json_api_no_keywords_message' => [
'variables' => [
'message' => NULL,
'term' => NULL,
],
'file' => 'google_json_api.theme.inc',
'template' => 'google_json_api_no_keywords_message',
],
'google_json_api_results_last_page_message' => [
'variables' => [
'message' => NULL,
'term' => NULL,
],
'file' => 'google_json_api.theme.inc',
'template' => 'google_json_api_results_last_page_message',
],
'google_json_api_search_page_form' => [
'render element' => 'form',
'file' => 'google_json_api.theme.inc',
'template' => 'google_json_api_search_page_form',
],
];
}
/**
* Implements hook_entity_insert().
*
* Clear appropriate caches when creating new google_json_api search page.
*/
function google_json_api_entity_insert(EntityInterface $entity) {
// Build the route so that the new page is available immediately.
if ($entity instanceof SearchPage) {
$plugin = $entity->getPlugin()->getPluginId();
if ($plugin == 'google_json_api_search') {
\Drupal::service('router.builder')->rebuild();
}
}
}
/**
* Implements hook_preprocess_item_list__search_results__google_json_api_search().
*
* Overwrite the message for when there are no search results.
*/
function google_json_api_preprocess_item_list__search_results__google_json_api_search(&$variables) {
$configuration = _google_json_api_get_configuration($variables);
$tokens = _google_json_api_get_empty_search_tokens($configuration);
$message = (!empty($configuration['no_results_message'])) ?
\Drupal::service('token')->replace($configuration['no_results_message'], $tokens) : t("Your search yielded no results.");
$variables['empty'] = [
'#theme' => 'google_json_api_no_results_message',
'#message' => $message,
'#plugin_id' => 'google_json_api_search',
'#attached' => [
'library' => [
'google_json_api/googlejsonapiresults',
],
],
];
// If there are no keywords specified, use the 'no keys' message.
if (empty(trim($tokens['google_json_api']['google_json_api_search_keywords']))) {
$message = (!empty($configuration['no_keywords_message'])) ?
\Drupal::service('token')->replace($configuration['no_keywords_message'], $tokens) : t("Please enter some keywords to perform a search.");
$variables['empty']['#theme'] = 'google_json_api_no_keywords_message';
$variables['empty']['#message'] = $message;
}
}
/**
* Implements hook_preprocess_pager() for customizing pager output for google results.
*/
function google_json_api_preprocess_pager(&$variables) {
$configuration = _google_json_api_get_configuration($variables);
if (empty($variables['items']) || empty($configuration)) {
return;
}
$current = (!empty($variables['current'])) ? $variables['current'] : 0;
if (!empty($variables['items']['last'])) {
unset($variables['items']['last']);
}
$variables['ellipses']['previous'] = FALSE;
$variables['ellipses']['next'] = FALSE;
$offset = ($current > 5) ? $current - 5 : 0;
$variables['items']['pages'] = array_slice($variables['items']['pages'], $offset, $current, TRUE);
}
/**
* Returns the google_json_api_search plugin configuration.
*
* @param array $variables
* Variables available to preprocess functions.
*
* @return array
* Returns google_json_api_search page configuration or empty.
*/
function _google_json_api_get_configuration(array &$variables) {
$entity = \Drupal::service('current_route_match')->getParameter('entity');
$configuration = [];
if ($entity instanceof SearchPage) {
$plugin = $entity->getPlugin()->getPluginId();
if ($plugin == 'google_json_api_search') {
$configuration = $entity->getPlugin()->getConfiguration();
}
}
return $configuration;
}
/**
* Returns the Google JSON API search token values.
*
* @param array $configuration
* Array of configuration values for the search page.
*
* @return array
* Returns google_json_api specific tokens for a search
* with no results.
*/
function _google_json_api_get_empty_search_tokens(array $configuration) {
$page = 0;
$sort = '';
$keys = '';
$items_per_page = $configuration['resultsperpage'];
// Retrieve sort value from query string if present.
if (\Drupal::service('request_stack')->getCurrentRequest()->query->has('sort')) {
$sort = \Drupal::service('request_stack')->getCurrentRequest()->query->get('sort');
}
// Determine the sort used in the request.
$sortvalues = [
'date:d' => 'Newest First',
'date:a' => 'Oldest First',
'' => 'Relevance',
];
$sort = (!empty($sortvalues[$sort])) ? $sortvalues[$sort] : 'Unknown';
// Retrieve page number value from query string if present.
if (\Drupal::service('request_stack')->getCurrentRequest()->query->has('page')) {
$page = \Drupal::service('request_stack')->getCurrentRequest()->query->get('page');
}
// Retrieve page number value from query string if present.
if (\Drupal::service('request_stack')->getCurrentRequest()->query->has('keys')) {
$keys = \Drupal::service('request_stack')->getCurrentRequest()->query->get('keys');
}
// Calculate the start index for the API request.
// 100 is the max due to constraint of Google Custom Search.
$start = min(100, ($page * $items_per_page) + 1);
$end = $start + $items_per_page - 1;
// Populate the data array used to populate Google JSON API custom tokens.
$tokens['google_json_api'] = [
'google_total_results' => 0,
'google_json_api_search_keywords' => $keys,
'google_json_api_result_start' => $start,
'google_json_api_result_end' => $end,
'google_json_api_sort_value' => $sort,
'google_json_api_search_page' => $configuration['label'],
];
return $tokens;
}
