You are here

search_api_federated_solr.module in Search API Federated Solr 7

search_api_federated_solr.module Contains hook implementations for the Federated Solr Search API Module.

@copyright Copyright (c) 2018 Palantir.net

File

search_api_federated_solr.module
View source
<?php

/**
 * @file search_api_federated_solr.module
 * Contains hook implementations for the Federated Solr Search API Module.
 *
 * @copyright Copyright (c) 2018 Palantir.net
 */

/**
 * Implements hook_help().
 */
function search_api_federated_solr_help($path, $arg) {
  switch ($path) {

    // Main module help for the search_api_federated_solr module.
    case 'admin/help#search_api_federated_solr':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('Allows indexing into a single Solr search index.') . '</p>';
      return $output;
  }
}

/**
 * Implements hook_search_api_alter_callback_info().
 */
function search_api_federated_solr_search_api_alter_callback_info() {
  $callbacks['site_name'] = array(
    'name' => t('Site Name'),
    'description' => t('The name of the site from which this content originated. This can be useful if indexing multiple sites with a single search index.'),
    'class' => 'SearchApiFederatedSolrSiteName',
  );
  $callbacks['search_api_urls'] = array(
    'name' => t('URLs'),
    'description' => t('The links to the node on all available sites. This can be useful if indexing multiple sites with a single search index.'),
    'class' => 'SearchApiFederatedSolrUrls',
  );
  $callbacks['canonical_url'] = array(
    'name' => t('Canonical URL'),
    'description' => t('Preferred URL for this content.'),
    'class' => 'SearchApiFederatedSolrCanonicalUrl',
  );
  $callbacks['federated_field'] = array(
    'name' => t('Federated Field'),
    'description' => t('A token or free text field that can be customized per-bundle.'),
    'class' => 'SearchApiFederatedSolrField',
  );
  $callbacks['federated_terms'] = array(
    'name' => t('Federated Term'),
    'description' => t('By adding this field to your search index configuration, you have enabled the federated terms processor to run when new items are indexed.  Next, add a "Federated Terms" field to any taxonomy vocabulary whose terms should be mapped to a "federated" term (this helps map terms across vocabularies and sites to a single "federated" term).  Then, edit terms in those vocabularies to add the federated term destination value (i.e. "Conditions>Blood Disorders").  Once that tagged content gets indexed, it will have "federated_terms" populated with any matching federated term destination values.'),
    'class' => 'SearchApiFederatedSolrTerms',
  );
  $callbacks['remap'] = array(
    'name' => t('Re-map Field Names'),
    'description' => t(''),
    'class' => 'SearchApiFederatedSolrRemap',
  );
  return $callbacks;
}

/**
 * Implements hook_menu().
 */
function search_api_federated_solr_menu() {
  $search_path = variable_get('search_api_federated_solr_path', 'search-app');
  $items[$search_path] = array(
    'title' => 'Search',
    'page callback' => 'page_search_api_federated_solr',
    'access arguments' => array(
      'use federated search',
    ),
  );
  $items['admin/config/search/federated-search-settings'] = array(
    'title' => 'Search API Federated Solr: Search App Settings',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'search_api_federated_solr_admin',
    ),
    'access arguments' => array(
      'administer federated search',
    ),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

/**
* Constructs the search page.
*/
function page_search_api_federated_solr() {
  $data_federated_search_app_config = search_api_federated_solr_config_json();
  $element = [];
  $element['#markup'] = '<div id="root" data-federated-search-app-config="' . htmlspecialchars($data_federated_search_app_config) . '"><noscript>This search page requires Javascript in order to function.  <a href="https://www.whatismybrowser.com/guides/how-to-enable-javascript/auto">Learn how to enable Javascript in your browser.</a></noscript><p class="element-invisible" aria-hidden="true">Federated Solr Search App: If you see this message in your DevTools, it likely means there is an issue adding the app javascript library to this page.  Follow the steps in the search_api_federated_solr module README.</p></div>';
  $element['#attached']['library'][] = [
    'search_api_federated_solr',
    'search-app',
  ];
  return $element;
}

/**
 * Implements hook_block_info().
 */
function search_api_federated_solr_block_info() {
  $blocks['federated_search_page_form_block'] = array(
    'info' => t('Federated Search Page Form block'),
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function search_api_federated_solr_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'federated_search_page_form_block':
      $block['title'] = 'Federated Search Page Form block';
      $srchblk = drupal_get_form('search_api_federated_solr_search_block_form');
      $block['content'] = drupal_render($srchblk);
      break;
  }
  return $block;
}

/**
 * Create custom search form.
 */
function search_api_federated_solr_search_block_form($form, &$form_state) {
  $form['q'] = array(
    '#type' => 'textfield',
    '#title' => t('Search'),
    '#title_display' => 'invisible',
    '#size' => 15,
    '#default_value' => '',
    '#attributes' => array(
      'title' => t('Enter the terms you wish to search for.'),
      'placeholder' => '',
    ),
    '#prefix' => '<div class="container-inline">',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
    '#name' => '',
    '#suffix' => '</div>',
  );
  return $form;
}

/**
 * Create custom search form handler.
 */
function search_api_federated_solr_search_block_form_submit($form, &$form_state) {
  $search_path = variable_get('search_api_federated_solr_path', 'search-app');

  // Define default search app qs params (i.e. search term).
  $qs_params = [
    'search' => $form_state['values']['q'],
  ];

  // If there is a site name and it should be set by default, add it as qs param.
  $is_site_name_property = variable_get('search_api_federated_solr_has_site_name_property');
  $set_default_site = variable_get('search_api_federated_solr_set_search_site');
  if ($is_site_name_property == 'true' && $set_default_site) {
    $search_index = variable_get('search_api_federated_solr_search_index');

    // Get the index configuration object.
    $index = search_api_index_load($search_index);

    // Get the domain machine name from Domain Access.
    if (function_exists('domain_get_domain')) {
      $domain = domain_get_domain()['machine_name'];
    }

    // If the site is using Domain Access and there's an altered site name.
    if (isset($domain) && !empty($index->options['data_alter_callbacks']['site_name']['settings']['domain'][$domain])) {

      // Lookup the altered site name matching the domain and set it.
      $domain_site_name = $index->options['data_alter_callbacks']['site_name']['settings']['domain'][$domain];
      $qs_params['sm_site_name'] = $domain_site_name;
    }
    elseif (!empty($index->options['data_alter_callbacks']['site_name']['settings']['site_name'])) {
      $site_name = $index->options['data_alter_callbacks']['site_name']['settings']['site_name'];
      $qs_params['sm_site_name'] = $site_name;
    }
    else {
      $qs_params['sm_site_name'] = variable_get('site_name');
    }
  }

  // Redirect to the search app path with necessary qs params.
  drupal_goto($search_path, [
    'query' => $qs_params,
  ]);
}

/**
 * Create search_api_federated_solr config form.
 */
function search_api_federated_solr_admin($form, &$form_state) {

  // Get search indexes.
  $indexes = [];
  foreach (search_api_index_load_multiple(FALSE) as $index) {
    $indexes[$index->machine_name] = $index->name;
  }
  $form['#prefix'] = '<div id="search-api-federated-solr-config-form">';
  $form['#suffix'] = '</div>';
  $form['search_api_federated_solr_path'] = [
    '#type' => 'textfield',
    '#title' => t('Search app path'),
    '#default_value' => variable_get('search_api_federated_solr_path', 'search-app'),
    '#description' => t('The path for the search app (Default: "search-app").'),
  ];
  $form['search_api_federated_solr_search_index'] = [
    '#type' => 'select',
    '#title' => t('Search API index'),
    '#description' => t('Defines <a href="/admin/config/search/search-api">which search_api index and server</a> the search app should use.'),
    '#options' => $indexes,
    '#default_value' => variable_get('search_api_federated_solr_search_index'),
    '#required' => TRUE,
    '#ajax' => [
      'callback' => 'get_site_name',
      'wrapper' => 'search-api-federated-solr-config-form',
    ],
  ];
  $form['search_api_federated_solr_has_site_name_property'] = [
    '#type' => 'hidden',
    '#default_value' => variable_get('search_api_federated_solr_has_site_name_property') ? 'true' : NULL,
  ];
  $form['search_api_federated_solr_set_search_site'] = [
    '#type' => 'checkbox',
    '#title' => t('Set the "Site name" facet to this site'),
    '#default_value' => variable_get('search_api_federated_solr_set_search_site'),
    '#description' => t('When checked, only search results from this site will be shown, by default, until this site\'s checkbox is unchecked in the search app\'s "Site name" facet.'),
    '#states' => [
      'visible' => [
        ':input[name="search_api_federated_solr_has_site_name_property"]' => [
          'value' => "true",
        ],
      ],
    ],
  ];
  $form['search_api_federated_solr_search_index_basic_auth'] = [
    '#type' => 'fieldset',
    '#title' => t('Search Index Basic Authentication'),
    '#description' => t('If your Solr server is protected by basic HTTP authentication, enter the login data here. This will be accessible to the client in an obscured, but non-secure method. It should, therefore, only provide read access to the index AND be different from that provided when configuring the server in Search API. The Password field is intentionally not obscured to emphasize this distinction.'),
  ];
  $form['search_api_federated_solr_search_index_basic_auth']['search_api_federated_solr_search_index_basic_auth_username'] = [
    '#type' => 'textfield',
    '#title' => t('Username'),
    '#default_value' => variable_get('search_api_federated_solr_search_index_basic_auth_username'),
  ];
  $form['search_api_federated_solr_search_index_basic_auth']['search_api_federated_solr_search_index_basic_auth_password'] = [
    '#type' => 'textfield',
    '#title' => t('Password'),
    '#default_value' => variable_get('search_api_federated_solr_search_index_basic_auth_password'),
  ];
  $form['search_api_federated_solr_show_empty_search_results'] = [
    '#type' => 'checkbox',
    '#title' => t('Show results for empty search'),
    '#default_value' => variable_get('search_api_federated_solr_show_empty_search_results'),
    '#description' => t('When checked, this option allows users to see all results when no search term is entered. By default, empty searches are disabled and yield no results.'),
  ];
  $form['search_api_federated_solr_no_results_text'] = [
    '#type' => 'textfield',
    '#title' => t('No results text'),
    '#default_value' => variable_get('search_api_federated_solr_no_results_text'),
    '#description' => t('This text is shown when a query returns no results. (Default: "Your search yielded no results.")'),
  ];
  $form['search_api_federated_solr_search_prompt_text'] = [
    '#type' => 'textfield',
    '#title' => t('Search prompt text'),
    '#default_value' => variable_get('search_api_federated_solr_search_prompt_text'),
    '#description' => t('This text is shown when no query term has been entered. (Default: "Please enter a search term.")'),
  ];
  $form['search_api_federated_solr_rows'] = [
    '#type' => 'textfield',
    '#attributes' => array(
      ' type' => 'number',
    ),
    '#title' => t('Number of search results per page'),
    '#default_value' => variable_get('search_api_federated_solr_rows'),
    '#description' => t('The max number of results to render per search results page. (Default: 20)'),
  ];
  $form['search_api_federated_solr_page_buttons'] = [
    '#type' => 'textfield',
    '#attributes' => array(
      ' type' => 'number',
    ),
    '#title' => t('Number of pagination buttons'),
    '#default_value' => variable_get('search_api_federated_solr_page_buttons'),
    '#description' => t('The max number of numbered pagination buttons to show at a given time. (Default: 5)'),
  ];
  $form['#cache'] = [
    'max-age' => 0,
  ];
  return system_settings_form($form);
}

/**
 * Create search_api_federated_solr_form_alter to validate the search path format.
 */
function search_api_federated_solr_form_search_api_federated_solr_admin_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = '_path_form_validate';
}
function _path_form_validate($form, &$form_state) {
  $form_state['values']['search_api_federated_solr_path'] = trim($form_state['values']['search_api_federated_solr_path'], '/');
}

/**
 * Ajax callback for search_api_federated_solr_search_index.
 */
function get_site_name($form, $form_state) {
  if (!empty($form_state['values']['search_api_federated_solr_search_index'])) {
    $search_index = $form_state['values']['search_api_federated_solr_search_index'];
    $index = search_api_index_load($search_index);
    $is_site_name_property = isset($index->options['fields']['site_name']) ? 'true' : '';
    $form['search_api_federated_solr_has_site_name_property']['#value'] = $is_site_name_property;
    $form_state['values']['search_api_federated_solr_has_site_name_property'] = $is_site_name_property;
  }
  return $form;
}

/**
 * Create search_api_federated_solr config json endpoint.
 */
function search_api_federated_solr_config_json() {
  $response_data = [];
  $search_index = variable_get('search_api_federated_solr_search_index');

  // Get the index configuration object.
  $index = search_api_index_load($search_index);
  $server = search_api_server_load($index->server);
  $server_url = trim($server
    ->getSolrConnection()
    ->getBaseUrl(), '/');

  // Append the request handler.
  $server_url .= '/select';
  if ($server_url) {
    $response_data['url'] = $server_url;
  }
  $basic_auth_username = variable_get('search_api_federated_solr_search_index_basic_auth_username');
  $basic_auth_password = variable_get('search_api_federated_solr_search_index_basic_auth_password');
  if ($basic_auth_username || $basic_auth_password) {
    $response_data['userpass'] = base64_encode($basic_auth_username . ':' . $basic_auth_password);
  }
  $is_site_name_property = variable_get('search_api_federated_solr_has_site_name_property');
  $set_default_site = variable_get('search_api_federated_solr_set_search_site');
  if ($is_site_name_property == 'true' && !$set_default_site) {
    variable_set('search_api_federated_solr_set_search_site', 0);
  }
  $no_response = variable_get('search_api_federated_solr_no_results_text');
  if ($no_response) {
    $response_data['noResults'] = $no_response;
  }
  $show_empty_search_results = variable_get('search_api_federated_solr_show_empty_search_results');
  if ($show_empty_search_results) {
    $response_data['showEmptySearchResults'] = $show_empty_search_results;
  }
  $search_prompt = variable_get('search_api_federated_solr_search_prompt_text');
  if ($search_prompt) {
    $response_data['searchPrompt'] = $search_prompt;
  }
  $rows = variable_get('search_api_federated_solr_rows');
  if ($rows) {
    $response_data['rows'] = $rows;
  }
  $pagination_buttons = variable_get('search_api_federated_solr_page_buttons');
  if ($pagination_buttons) {
    $response_data['paginationButtons'] = $pagination_buttons;
  }
  if (function_exists('domain_get_domain')) {
    $domain = domain_get_domain();
    if (isset($domain['path'])) {
      $response_data['hostname'] = parse_url($domain['path'], PHP_URL_HOST);
    }
  }
  return json_encode($response_data, JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
}

/**
 * Implements hook_field_info().
 */
function search_api_federated_solr_field_info() {
  return array(
    // We name our field as the associative name of the array.
    'federated_terms' => array(
      'label' => t('Federated terms'),
      'description' => t('Stores the solr search api federated term destination value for taxonomy terms.'),
      'settings' => array(
        'max_length' => 255,
      ),
      'default_widget' => 'federated_terms_textfield',
      'default_formatter' => 'string',
      'cardinality' => -1,
    ),
  );
}

/**
 * Implements hook_field_validate().
 */
function search_api_federated_solr_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  foreach ($items as $delta => $item) {
    if (!empty($item['value'])) {
      if (!empty($field['settings']['max_length']) && drupal_strlen($item['value']) > $field['settings']['max_length']) {
        $errors[$field['field_name']][$langcode][$delta][] = array(
          'error' => 'federated_field_max_length',
          'message' => t('%name: may not be longer than @max characters.', array(
            '%name' => $instance['label'],
            '%max' => $field['settings']['max_length'],
          )),
        );
      }
    }
  }
}

/**
 * Implements hook_field_widget_error().
 */
function search_api_federated_solr_field_widget_error($element, $error, $form, &$form_state) {
  switch ($error['error']) {
    case 'federated_field_max_length':
      form_error($element, $error['message']);
      break;
  }
}

/**
 * Implements hook_field_is_empty().
 */
function search_api_federated_solr_field_is_empty($item, $field) {
  return $item['value'] === NULL || $item['value'] === '';
}

/**
 * Implements hook_field_widget_info().
 */
function search_api_federated_solr_field_widget_info() {
  return array(
    'federated_terms_textfield' => array(
      'label' => t('Federated Terms Textfield'),
      'field types' => array(
        'federated_terms',
      ),
    ),
  );
}

/**
 * Implements hook_field_widget_form().
 */
function search_api_federated_solr_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $value = isset($items[$delta]['value']) ? $items[$delta]['value'] : NULL;
  $widget = $element;
  $widget['#delta'] = $delta;
  if ($instance['widget']['type'] == 'federated_terms_textfield') {
    $widget += array(
      '#type' => 'textfield',
      '#default_value' => $value,
      '#description' => t('This federated term is used as a facet value in your search application.  It should consist of a hierarchy made up of a type (i.e. "Condition") and term (i.e. "Diabetes"), separated by ">".  For example: Condition>Diabetes.'),
      '#size' => 75,
      '#maxlength' => 255,
      '#attributes' => [
        'class' => [
          'js-text-full',
          'text-full',
        ],
      ],
    );
  }
  $element['value'] = $widget;
  return $element;
}

/**
 * Declare search app static assets as module library.
 */
function search_api_federated_solr_library() {

  // Search app.
  $libraries['search-app'] = array(
    'title' => 'Federated Search App',
    'version' => variable_get('css_js_query_string', '0'),
    'js' => array(
      'https://cdn.jsdelivr.net/gh/palantirnet/federated-search-react@v1.0.12/js/main.b76ad392.js' => array(
        'type' => 'external',
        'scope' => 'footer',
      ),
    ),
    'css' => array(
      'https://cdn.jsdelivr.net/gh/palantirnet/federated-search-react@v1.0.12/css/main.cf6a58ce.css' => array(
        'type' => 'external',
      ),
    ),
  );
  return $libraries;
}

/**
 * Implements hook_permission().
 */
function search_api_federated_solr_permission() {
  return array(
    'administer federated search' => array(
      'title' => t('Administer Federated Search'),
      'description' => t('Update Federated Search page configuration.'),
    ),
    'use federated search' => array(
      'title' => t('Use Federated Search'),
      'description' => t('Allows users to view and use the Federated Search page.'),
    ),
  );
}

/**
 * Implements hook_image_default_styles().
 */
function search_api_federated_solr_image_default_styles() {
  $styles = array();
  $styles['search_api_federated_solr_image'] = array(
    'label' => 'Federated Image',
    'effects' => array(
      array(
        'name' => 'image_scale_and_crop',
        'data' => array(
          'width' => 425,
          'height' => 239,
        ),
        'weight' => 0,
      ),
    ),
  );
  return $styles;
}

Functions

Namesort descending Description
get_site_name Ajax callback for search_api_federated_solr_search_index.
page_search_api_federated_solr Constructs the search page.
search_api_federated_solr_admin Create search_api_federated_solr config form.
search_api_federated_solr_block_info Implements hook_block_info().
search_api_federated_solr_block_view Implements hook_block_view().
search_api_federated_solr_config_json Create search_api_federated_solr config json endpoint.
search_api_federated_solr_field_info Implements hook_field_info().
search_api_federated_solr_field_is_empty Implements hook_field_is_empty().
search_api_federated_solr_field_validate Implements hook_field_validate().
search_api_federated_solr_field_widget_error Implements hook_field_widget_error().
search_api_federated_solr_field_widget_form Implements hook_field_widget_form().
search_api_federated_solr_field_widget_info Implements hook_field_widget_info().
search_api_federated_solr_form_search_api_federated_solr_admin_alter Create search_api_federated_solr_form_alter to validate the search path format.
search_api_federated_solr_help Implements hook_help().
search_api_federated_solr_image_default_styles Implements hook_image_default_styles().
search_api_federated_solr_library Declare search app static assets as module library.
search_api_federated_solr_menu Implements hook_menu().
search_api_federated_solr_permission Implements hook_permission().
search_api_federated_solr_search_api_alter_callback_info Implements hook_search_api_alter_callback_info().
search_api_federated_solr_search_block_form Create custom search form.
search_api_federated_solr_search_block_form_submit Create custom search form handler.
_path_form_validate