View source
<?php
namespace Drupal\search_api_solr\Plugin\SolrConnector;
use Drupal\Core\Form\FormStateInterface;
use Solarium\Core\Client\Endpoint;
use Solarium\Core\Client\Request;
use Solarium\QueryType\Select\Query\Query;
class BasicAuthSolrConnector extends StandardSolrConnector {
public function defaultConfiguration() {
return parent::defaultConfiguration() + [
'username' => '',
'password' => '',
];
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$form['auth'] = array(
'#type' => 'fieldset',
'#title' => $this
->t('HTTP Basic Authentication'),
'#description' => $this
->t('If your Solr server is protected by basic HTTP authentication, enter the login data here.'),
'#collapsible' => TRUE,
'#collapsed' => empty($this->configuration['username']),
);
$form['auth']['username'] = array(
'#type' => 'textfield',
'#title' => $this
->t('Username'),
'#default_value' => $this->configuration['username'],
'#required' => TRUE,
);
$form['auth']['password'] = array(
'#type' => 'password',
'#title' => $this
->t('Password'),
'#description' => $this
->t('If this field is left blank and the HTTP username is filled out, the current password will not be changed.'),
);
return $form;
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$values = $form_state
->getValues();
$values += $values['auth'];
if ($values['password'] === '' && isset($this->configuration['username']) && $values['username'] === $this->configuration['username']) {
$values['password'] = $this->configuration['password'];
}
foreach ($values['auth'] as $key => $value) {
$form_state
->setValue($key, $value);
}
$form_state
->unsetValue('auth');
parent::submitConfigurationForm($form, $form_state);
}
public function search(Query $query, Endpoint $endpoint = NULL) {
$this
->connect();
if (!$endpoint) {
$endpoint = $this->solr
->getEndpoint('core');
}
if ($this->configuration['http_method'] == 'AUTO') {
$this->solr
->getPlugin('postbigrequest');
}
$request = $this->solr
->createRequest($query);
if ($this->configuration['http_method'] == 'POST') {
$request
->setMethod(Request::METHOD_POST);
}
elseif ($this->configuration['http_method'] == 'GET') {
$request
->setMethod(Request::METHOD_GET);
}
if (strlen($this->configuration['username']) && strlen($this->configuration['password'])) {
$request
->setAuthentication($this->configuration['username'], $this->configuration['password']);
}
return $this->solr
->executeRequest($request, $endpoint);
}
public function viewSettings() {
$vars = array(
'%user' => $this->configuration['username'],
'%pass' => str_repeat('*', strlen($this->configuration['password'])),
);
$info[] = array(
'label' => $this
->t('Basic HTTP authentication'),
'info' => $this
->t('Username: %user | Password: %pass', $vars),
);
return $info;
}
}