View source
<?php
namespace Drupal\search_api\Plugin\search_api\datasource;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Database\Query\SelectInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityDisplayRepositoryInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\TypedData\EntityDataDefinitionInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Logger\RfcLogLevel;
use Drupal\Core\Plugin\PluginFormInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\State\StateInterface;
use Drupal\Core\TypedData\ComplexDataDefinitionInterface;
use Drupal\Core\TypedData\ComplexDataInterface;
use Drupal\Core\TypedData\TypedDataManagerInterface;
use Drupal\field\FieldConfigInterface;
use Drupal\field\FieldStorageConfigInterface;
use Drupal\search_api\Datasource\DatasourcePluginBase;
use Drupal\search_api\IndexInterface;
use Drupal\search_api\LoggerTrait;
use Drupal\search_api\Plugin\PluginFormTrait;
use Drupal\search_api\Utility\Dependencies;
use Drupal\search_api\Utility\FieldsHelperInterface;
use Drupal\search_api\Utility\Utility;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ContentEntity extends DatasourcePluginBase implements PluginFormInterface {
use LoggerTrait;
use PluginFormTrait;
const TRACKING_PAGE_STATE_KEY = 'search_api.datasource.entity.last_ids';
protected $database;
protected $memoryCache;
protected $state;
protected $entityTypeManager;
protected $entityFieldManager;
protected $entityDisplayRepository;
protected $entityTypeBundleInfo;
protected $typedDataManager;
protected $configFactory;
protected $languageManager;
protected $fieldsHelper;
public function __construct(array $configuration, $plugin_id, array $plugin_definition) {
if (($configuration['#index'] ?? NULL) instanceof IndexInterface) {
$this
->setIndex($configuration['#index']);
unset($configuration['#index']);
}
$this->pluginDefinition = $plugin_definition;
$this->pluginId = $plugin_id;
$this->configuration = $configuration + $this
->defaultConfiguration();
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$datasource = parent::create($container, $configuration, $plugin_id, $plugin_definition);
$datasource
->setDatabaseConnection($container
->get('database'));
$datasource
->setEntityTypeManager($container
->get('entity_type.manager'));
$datasource
->setEntityFieldManager($container
->get('entity_field.manager'));
$datasource
->setEntityDisplayRepository($container
->get('entity_display.repository'));
$datasource
->setEntityTypeBundleInfo($container
->get('entity_type.bundle.info'));
$datasource
->setTypedDataManager($container
->get('typed_data_manager'));
$datasource
->setConfigFactory($container
->get('config.factory'));
$datasource
->setLanguageManager($container
->get('language_manager'));
$datasource
->setFieldsHelper($container
->get('search_api.fields_helper'));
$datasource
->setState($container
->get('state'));
$datasource
->setEntityMemoryCache($container
->get('entity.memory_cache'));
$datasource
->setLogger($container
->get('logger.channel.search_api'));
return $datasource;
}
public function getDatabaseConnection() : Connection {
return $this->database ?: \Drupal::database();
}
public function setDatabaseConnection(Connection $connection) : self {
$this->database = $connection;
return $this;
}
public function getEntityTypeManager() {
return $this->entityTypeManager ?: \Drupal::entityTypeManager();
}
protected function getEntityStorage() {
return $this
->getEntityTypeManager()
->getStorage($this
->getEntityTypeId());
}
protected function getEntityType() {
return $this
->getEntityTypeManager()
->getDefinition($this
->getEntityTypeId());
}
public function setEntityTypeManager(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
return $this;
}
public function getEntityFieldManager() {
return $this->entityFieldManager ?: \Drupal::service('entity_field.manager');
}
public function setEntityFieldManager(EntityFieldManagerInterface $entity_field_manager) {
$this->entityFieldManager = $entity_field_manager;
return $this;
}
public function getEntityDisplayRepository() {
return $this->entityDisplayRepository ?: \Drupal::service('entity_display.repository');
}
public function setEntityDisplayRepository(EntityDisplayRepositoryInterface $entity_display_repository) {
$this->entityDisplayRepository = $entity_display_repository;
return $this;
}
public function getEntityTypeBundleInfo() {
return $this->entityTypeBundleInfo ?: \Drupal::service('entity_type.bundle.info');
}
public function setEntityTypeBundleInfo(EntityTypeBundleInfoInterface $entity_type_bundle_info) {
$this->entityTypeBundleInfo = $entity_type_bundle_info;
return $this;
}
public function getTypedDataManager() {
return $this->typedDataManager ?: \Drupal::typedDataManager();
}
public function setTypedDataManager(TypedDataManagerInterface $typed_data_manager) {
$this->typedDataManager = $typed_data_manager;
return $this;
}
public function getConfigFactory() {
return $this->configFactory ?: \Drupal::configFactory();
}
protected function getConfigValue($key) {
return $this
->getConfigFactory()
->get('search_api.settings')
->get($key);
}
public function setConfigFactory(ConfigFactoryInterface $config_factory) {
$this->configFactory = $config_factory;
return $this;
}
public function getLanguageManager() {
return $this->languageManager ?: \Drupal::languageManager();
}
public function setLanguageManager(LanguageManagerInterface $language_manager) {
$this->languageManager = $language_manager;
}
public function getFieldsHelper() {
return $this->fieldsHelper ?: \Drupal::service('search_api.fields_helper');
}
public function setFieldsHelper(FieldsHelperInterface $fields_helper) {
$this->fieldsHelper = $fields_helper;
return $this;
}
public function getState() {
return $this->state ?: \Drupal::state();
}
public function setState(StateInterface $state) {
$this->state = $state;
return $this;
}
public function getEntityMemoryCache() {
return $this->memoryCache;
}
public function setEntityMemoryCache(CacheBackendInterface $memory_cache) {
$this->memoryCache = $memory_cache;
return $this;
}
public function getPropertyDefinitions() {
$type = $this
->getEntityTypeId();
$properties = $this
->getEntityFieldManager()
->getBaseFieldDefinitions($type);
if ($bundles = array_keys($this
->getBundles())) {
foreach ($bundles as $bundle_id) {
$properties += $this
->getEntityFieldManager()
->getFieldDefinitions($type, $bundle_id);
}
}
foreach ($properties as $key => $property) {
if (!$property
->isComputed() || $key === 'path') {
if ($property
->getFieldStorageDefinition()
->hasCustomStorage()) {
unset($properties[$key]);
}
}
}
return $properties;
}
public function loadMultiple(array $ids) {
$allowed_languages = $this
->getLanguages();
$allowed_languages[LanguageInterface::LANGCODE_NOT_SPECIFIED] = TRUE;
$allowed_languages[LanguageInterface::LANGCODE_NOT_APPLICABLE] = TRUE;
$entity_ids = [];
foreach ($ids as $item_id) {
$pos = strrpos($item_id, ':');
if ($pos === FALSE) {
continue;
}
$entity_id = substr($item_id, 0, $pos);
$langcode = substr($item_id, $pos + 1);
if (isset($allowed_languages[$langcode])) {
$entity_ids[$entity_id][$item_id] = $langcode;
}
}
$entities = $this
->getEntityStorage()
->loadMultiple(array_keys($entity_ids));
$items = [];
$allowed_bundles = $this
->getBundles();
foreach ($entity_ids as $entity_id => $langcodes) {
if (empty($entities[$entity_id]) || !isset($allowed_bundles[$entities[$entity_id]
->bundle()])) {
continue;
}
foreach ($langcodes as $item_id => $langcode) {
if ($entities[$entity_id]
->hasTranslation($langcode)) {
$items[$item_id] = $entities[$entity_id]
->getTranslation($langcode)
->getTypedData();
}
}
}
return $items;
}
public function defaultConfiguration() {
$default_configuration = [];
if ($this
->hasBundles()) {
$default_configuration['bundles'] = [
'default' => TRUE,
'selected' => [],
];
}
if ($this
->isTranslatable()) {
$default_configuration['languages'] = [
'default' => TRUE,
'selected' => [],
];
}
return $default_configuration;
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
if ($this
->hasBundles() && ($bundles = $this
->getEntityBundleOptions())) {
$form['bundles'] = [
'#type' => 'details',
'#title' => $this
->t('Bundles'),
'#open' => TRUE,
];
$form['bundles']['default'] = [
'#type' => 'radios',
'#title' => $this
->t('Which bundles should be indexed?'),
'#options' => [
0 => $this
->t('Only those selected'),
1 => $this
->t('All except those selected'),
],
'#default_value' => (int) $this->configuration['bundles']['default'],
];
$form['bundles']['selected'] = [
'#type' => 'checkboxes',
'#title' => $this
->t('Bundles'),
'#options' => $bundles,
'#default_value' => $this->configuration['bundles']['selected'],
'#size' => min(4, count($bundles)),
'#multiple' => TRUE,
];
}
if ($this
->isTranslatable()) {
$form['languages'] = [
'#type' => 'details',
'#title' => $this
->t('Languages'),
'#open' => TRUE,
];
$form['languages']['default'] = [
'#type' => 'radios',
'#title' => $this
->t('Which languages should be indexed?'),
'#options' => [
0 => $this
->t('Only those selected'),
1 => $this
->t('All except those selected'),
],
'#default_value' => (int) $this->configuration['languages']['default'],
];
$form['languages']['selected'] = [
'#type' => 'checkboxes',
'#title' => $this
->t('Languages'),
'#options' => $this
->getTranslationOptions(),
'#default_value' => $this->configuration['languages']['selected'],
'#multiple' => TRUE,
];
}
return $form;
}
protected function getEntityBundleOptions() {
$options = [];
if ($bundles = $this
->getEntityBundles()) {
foreach ($bundles as $bundle => $bundle_info) {
$options[$bundle] = Utility::escapeHtml($bundle_info['label']);
}
}
return $options;
}
protected function getTranslationOptions() {
$options = [];
foreach ($this
->getLanguageManager()
->getLanguages() as $language) {
$options[$language
->getId()] = $language
->getName();
}
return $options;
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
foreach ([
'bundles',
'languages',
] as $key) {
if ($form_state
->hasValue($key)) {
$parents = [
$key,
'selected',
];
$value = $form_state
->getValue($parents, []);
$value = array_keys(array_filter($value));
$form_state
->setValue($parents, $value);
}
}
$this
->setConfiguration($form_state
->getValues());
}
protected function getEntity(ComplexDataInterface $item) {
$value = $item
->getValue();
return $value instanceof EntityInterface ? $value : NULL;
}
public function getItemId(ComplexDataInterface $item) {
if ($entity = $this
->getEntity($item)) {
$enabled_bundles = $this
->getBundles();
if (isset($enabled_bundles[$entity
->bundle()])) {
return $entity
->id() . ':' . $entity
->language()
->getId();
}
}
return NULL;
}
public function getItemLabel(ComplexDataInterface $item) {
if ($entity = $this
->getEntity($item)) {
return $entity
->label();
}
return NULL;
}
public function getItemBundle(ComplexDataInterface $item) {
if ($entity = $this
->getEntity($item)) {
return $entity
->bundle();
}
return NULL;
}
public function getItemUrl(ComplexDataInterface $item) {
if ($entity = $this
->getEntity($item)) {
if ($entity
->hasLinkTemplate('canonical')) {
return $entity
->toUrl('canonical');
}
}
return NULL;
}
public function getItemAccessResult(ComplexDataInterface $item, AccountInterface $account = NULL) {
$entity = $this
->getEntity($item);
if ($entity) {
return $this
->getEntityTypeManager()
->getAccessControlHandler($this
->getEntityTypeId())
->access($entity, 'view', $account, TRUE);
}
return AccessResult::neutral('Item is not an entity, so cannot check access');
}
public function getItemIds($page = NULL) {
return $this
->getPartialItemIds($page);
}
public function getEntityTypeId() {
$plugin_definition = $this
->getPluginDefinition();
return $plugin_definition['entity_type'];
}
protected function hasBundles() {
return $this
->getEntityType()
->hasKey('bundle');
}
protected function isTranslatable() {
return $this
->getEntityType()
->isTranslatable();
}
protected function getEntityBundles() {
return $this
->hasBundles() ? $this
->getEntityTypeBundleInfo()
->getBundleInfo($this
->getEntityTypeId()) : [];
}
public function getPartialItemIds($page = NULL, array $bundles = NULL, array $languages = NULL) {
if ($bundles === [] && !$languages || $languages === [] && !$bundles) {
return NULL;
}
$entity_type = $this
->getEntityType();
$entity_id = $entity_type
->getKey('id');
if ($entity_type
->getBaseTable()) {
$select = $this
->getDatabaseConnection()
->select($entity_type
->getBaseTable(), 'base_table')
->fields('base_table', [
$entity_id,
]);
}
else {
$select = $this
->getEntityTypeManager()
->getStorage($this
->getEntityTypeId())
->getQuery();
$select
->accessCheck(FALSE);
}
$batch_page_context = [
'index_id' => $this
->getIndex()
->id(),
'datasource_id' => $this
->getPluginId(),
'bundles' => $bundles,
'languages' => $languages,
];
$context_key = Crypt::hashBase64(serialize($batch_page_context));
$last_ids = $this
->getState()
->get(self::TRACKING_PAGE_STATE_KEY, []);
if ($this
->hasBundles()) {
$bundle_property = $entity_type
->getKey('bundle');
if ($bundles && !$languages) {
$select
->condition($bundle_property, $bundles, 'IN');
}
else {
$enabled_bundles = array_keys($this
->getBundles());
if ($bundles) {
$enabled_bundles = array_unique(array_merge($bundles, $enabled_bundles));
}
if (count($enabled_bundles) < count($this
->getEntityBundles())) {
$select
->condition($bundle_property, $enabled_bundles, 'IN');
}
}
}
if (isset($page)) {
$page_size = $this
->getConfigValue('tracking_page_size');
assert($page_size, 'Tracking page size is not set.');
$offset = $page * $page_size;
if ($page > 0) {
if (isset($last_ids[$context_key]) && $last_ids[$context_key]['page'] == $page - 1 && $this
->getEntityTypeId() !== 'search_api_task') {
$select
->condition($entity_id, $last_ids[$context_key]['last_id'], '>');
$offset = 0;
}
}
$select
->range($offset, $page_size);
if ($select instanceof SelectInterface) {
$select
->orderBy($entity_id);
}
else {
$select
->sort($entity_id);
}
}
if ($select instanceof SelectInterface) {
$entity_ids = $select
->execute()
->fetchCol();
}
else {
$entity_ids = $select
->execute();
}
if (!$entity_ids) {
if (isset($page)) {
unset($last_ids[$context_key]);
$this
->getState()
->set(self::TRACKING_PAGE_STATE_KEY, $last_ids);
}
return NULL;
}
if (isset($page)) {
$last_ids[$context_key] = [
'page' => (int) $page,
'last_id' => end($entity_ids),
];
$this
->getState()
->set(self::TRACKING_PAGE_STATE_KEY, $last_ids);
}
$item_ids = [];
$enabled_languages = array_keys($this
->getLanguages());
if ($languages) {
$enabled_languages = array_unique(array_merge($languages, $enabled_languages));
}
$enabled_languages[] = LanguageInterface::LANGCODE_NOT_SPECIFIED;
$enabled_languages[] = LanguageInterface::LANGCODE_NOT_APPLICABLE;
foreach ($this
->getEntityStorage()
->loadMultiple($entity_ids) as $entity_id => $entity) {
$translations = array_keys($entity
->getTranslationLanguages());
$translations = array_intersect($translations, $enabled_languages);
if ($languages !== NULL && (!$bundles || !in_array($entity
->bundle(), $bundles))) {
$translations = array_intersect($translations, $languages);
}
foreach ($translations as $langcode) {
$item_ids[] = "{$entity_id}:{$langcode}";
}
}
if (Utility::isRunningInCli()) {
$this
->getEntityMemoryCache()
->deleteAll();
}
return $item_ids;
}
public function getBundles() {
if (!$this
->hasBundles()) {
return [
$this
->getEntityTypeId() => $this
->label(),
];
}
$configuration = $this
->getConfiguration();
$bundles = [];
$entity_bundles = $this
->getEntityBundles();
$selected_bundles = array_flip($configuration['bundles']['selected']);
$function = $configuration['bundles']['default'] ? 'array_diff_key' : 'array_intersect_key';
$entity_bundles = $function($entity_bundles, $selected_bundles);
foreach ($entity_bundles as $bundle_id => $bundle_info) {
$bundles[$bundle_id] = $bundle_info['label'] ?? $bundle_id;
}
return $bundles ?: [
$this
->getEntityTypeId() => $this
->label(),
];
}
protected function getLanguages() {
$all_languages = $this
->getLanguageManager()
->getLanguages();
if ($this
->isTranslatable()) {
$selected_languages = array_flip($this->configuration['languages']['selected']);
if ($this->configuration['languages']['default']) {
return array_diff_key($all_languages, $selected_languages);
}
else {
return array_intersect_key($all_languages, $selected_languages);
}
}
return $all_languages;
}
public function getViewModes($bundle = NULL) {
return $this
->getEntityDisplayRepository()
->getViewModeOptions($this
->getEntityTypeId());
}
public function viewItem(ComplexDataInterface $item, $view_mode, $langcode = NULL) {
try {
if ($entity = $this
->getEntity($item)) {
$langcode = $langcode ?: $entity
->language()
->getId();
return $this
->getEntityTypeManager()
->getViewBuilder($this
->getEntityTypeId())
->view($entity, $view_mode, $langcode);
}
} catch (\Exception $e) {
}
return [];
}
public function viewMultipleItems(array $items, $view_mode, $langcode = NULL) {
try {
$view_builder = $this
->getEntityTypeManager()
->getViewBuilder($this
->getEntityTypeId());
if (isset($langcode)) {
$entities = [];
foreach ($items as $i => $item) {
if ($entity = $this
->getEntity($item)) {
$entities[$i] = $entity;
}
}
if ($entities) {
return $view_builder
->viewMultiple($entities, $view_mode, $langcode);
}
return [];
}
$items_by_language = [];
foreach ($items as $i => $item) {
if ($entity = $this
->getEntity($item)) {
$items_by_language[$entity
->language()
->getId()][$i] = $entity;
}
}
$build = array_fill_keys(array_keys($items), []);
foreach ($items_by_language as $langcode => $language_items) {
$build = array_replace($build, $view_builder
->viewMultiple($language_items, $view_mode, $langcode));
}
return $build;
} catch (\Exception $e) {
return [];
}
}
public function calculateDependencies() {
$this->dependencies = parent::calculateDependencies();
$this
->addDependency('module', $this
->getEntityType()
->getProvider());
return $this->dependencies;
}
public function getFieldDependencies(array $fields) {
$dependencies = [];
$properties = $this
->getPropertyDefinitions();
foreach ($fields as $field_id => $property_path) {
$dependencies[$field_id] = $this
->getPropertyPathDependencies($property_path, $properties);
}
return $dependencies;
}
public function canContainEntityReferences() : bool {
return TRUE;
}
public function getAffectedItemsForEntityChange(EntityInterface $entity, array $foreign_entity_relationship_map, EntityInterface $original_entity = NULL) : array {
if (!$entity instanceof ContentEntityInterface) {
return [];
}
$ids_to_reindex = [];
$path_separator = IndexInterface::PROPERTY_PATH_SEPARATOR;
foreach ($foreign_entity_relationship_map as $relation_info) {
if (!empty($relation_info['datasource']) && $relation_info['datasource'] !== $this
->getPluginId()) {
continue;
}
if ($relation_info['entity_type'] !== $entity
->getEntityTypeId()) {
continue;
}
if (!empty($relation_info['bundles']) && !in_array($entity
->bundle(), $relation_info['bundles'])) {
continue;
}
if (!$entity
->hasField($relation_info['field_name'])) {
continue;
}
$items = $entity
->get($relation_info['field_name']);
if (!$original_entity || !$items
->equals($original_entity
->get($relation_info['field_name']))) {
$query = $this->entityTypeManager
->getStorage($this
->getEntityTypeId())
->getQuery();
$query
->accessCheck(FALSE);
$property_path = $relation_info['property_path_to_foreign_entity'];
$property_path = str_replace($path_separator, '.', $property_path);
$query
->condition($property_path, $entity
->id());
try {
$entity_ids = array_values($query
->execute());
} catch (\Throwable $e) {
if (!$e instanceof \Exception && (get_class($e) !== \Error::class || $e
->getMessage() !== 'Call to a member function getColumns() on bool')) {
throw $e;
}
$vars = [
'%index' => $this->index
->label(),
'%entity_type' => $entity
->getEntityType()
->getLabel(),
'@entity_id' => $entity
->id(),
];
try {
$link = $entity
->toLink($this
->t('Go to changed %entity_type with ID "@entity_id"', $vars))
->toString()
->getGeneratedLink();
} catch (\Throwable $e) {
$link = NULL;
}
$this
->logException($e, '%type while attempting to find indexed entities referencing changed %entity_type with ID "@entity_id" for index %index: @message in %function (line %line of %file).', $vars, RfcLogLevel::ERROR, $link);
continue;
}
foreach ($entity_ids as $entity_id) {
foreach ($this
->getLanguages() as $language) {
$ids_to_reindex["{$entity_id}:{$language->getId()}"] = 1;
}
}
}
}
return array_keys($ids_to_reindex);
}
protected function getPropertyPathDependencies($property_path, array $properties) {
list($key, $nested_path) = Utility::splitPropertyPath($property_path, FALSE);
if (!isset($properties[$key])) {
return [];
}
$dependencies = new Dependencies();
$property = $properties[$key];
if ($property instanceof FieldConfigInterface) {
$storage = $property
->getFieldStorageDefinition();
if ($storage instanceof FieldStorageConfigInterface) {
$name = $storage
->getConfigDependencyName();
$dependencies
->addDependency($storage
->getConfigDependencyKey(), $name);
}
}
if ($property instanceof FieldStorageDefinitionInterface) {
$dependencies
->addDependency('module', $property
->getProvider());
}
$property = $this
->getFieldsHelper()
->getInnerProperty($property);
if ($property instanceof EntityDataDefinitionInterface) {
$entity_type_definition = $this
->getEntityTypeManager()
->getDefinition($property
->getEntityTypeId());
if ($entity_type_definition) {
$module = $entity_type_definition
->getProvider();
$dependencies
->addDependency('module', $module);
}
}
if ($nested_path !== NULL && $property instanceof ComplexDataDefinitionInterface) {
$nested = $this
->getFieldsHelper()
->getNestedProperties($property);
$nested_dependencies = $this
->getPropertyPathDependencies($nested_path, $nested);
$dependencies
->addDependencies($nested_dependencies);
}
return $dependencies
->toArray();
}
public static function getIndexesForEntity(ContentEntityInterface $entity) {
return \Drupal::getContainer()
->get('search_api.entity_datasource.tracking_manager')
->getIndexesForEntity($entity);
}
public function getListCacheContexts() {
$contexts = parent::getListCacheContexts();
$entity_list_contexts = $this
->getEntityType()
->getListCacheContexts();
return Cache::mergeContexts($entity_list_contexts, $contexts);
}
}